@arcteninc/core 0.0.170 → 0.0.171
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.cjs +7 -10
- package/dist/index.mjs +1259 -1276
- package/dist/lib/useAgent.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
To fix: Run "arcten-extract-types ." and ensure "${c}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}const Ll={password:[/^password$/i,/^pwd$/i,/^pass$/i,/^newPassword$/i,/^oldPassword$/i,/^currentPassword$/i,/^confirmPassword$/i,/.*password.*/i],email:[/^email$/i,/^emailAddress$/i,/^mail$/i,/.*email.*/i],phone:[/^phone$/i,/^phoneNumber$/i,/^mobile$/i,/^cell$/i,/^cellPhone$/i,/^telephone$/i,/.*phone.*/i,/.*mobile.*/i],pin:[/^pin$/i,/^pinCode$/i,/^securityPin$/i,/^accessPin$/i,/.*pin$/i],ssn:[/^ssn$/i,/^socialSecurityNumber$/i,/^social$/i,/.*ssn.*/i,/.*social.*/i],creditCard:[/^creditCard$/i,/^cardNumber$/i,/^card$/i,/^ccNumber$/i,/^creditCardNumber$/i,/.*card.*/i,/^cvv$/i,/^cvc$/i,/^cvn$/i,/^securityCode$/i],text:[]};function jn(e){for(const[t,n]of Object.entries(Ll))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function Fl(e,t){return{password:{title:"Password Required",description:"Please enter your password to continue",placeholder:"Enter password..."},email:{title:"Email Required",description:"Please enter your email address",placeholder:"Enter email address..."},phone:{title:"Phone Number Required",description:"Please enter your phone number",placeholder:"Enter phone number..."},pin:{title:"PIN Required",description:"Please enter your PIN",placeholder:"Enter PIN..."},ssn:{title:"Social Security Number Required",description:"Please enter your Social Security Number",placeholder:"XXX-XX-XXXX"},creditCard:{title:"Credit Card Required",description:"Please enter your credit card information",placeholder:"XXXX XXXX XXXX XXXX"},text:{title:"Secure Input Required",description:`Please enter your ${t}`,placeholder:`Enter ${t}...`}}[e]}function Bl(e,t,n){return t.length>0}function Ul(e,t,n,s={}){const r=[];return Object.keys(s).forEach(i=>{const a=i in n,l=n[i];if(!a){const f=s[i];if(f!=null&&f!=="")return}const c=zl(s[i]),d={name:i,type:_l(l||jn(i)||"text"),label:Ao(i),placeholder:Xl(i,l),required:!0,value:c};d.type==="password"&&(d.validation=f=>f.length<8?"Password must be at least 8 characters":null),r.push(d)}),r.sort((i,a)=>{const l=i.name in n,c=a.name in n;return l===c?0:l?1:-1}),{shouldUseForm:Bl(e,t),fields:r,title:Wl(e),description:ql(e,r.length)}}function zl(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function _l(e){switch(e){case"password":return"password";case"email":return"email";case"phone":return"phone";case"pin":return"pin";case"ssn":return"ssn";case"creditCard":return"creditCard";default:return"text"}}function Ao(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Xl(e,t){return t?Fl(t,e).placeholder:`Enter ${Ao(e).toLowerCase()}...`}function Wl(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function ql(e,t){const n=e.toLowerCase();return t<=2?`Please provide the required information to ${n}.`:`Please fill out the form below to ${n}. Required fields are marked with *.`}function An(e){if(typeof e=="string")try{const t=JSON.parse(e);return An(t)}catch{return e}if(Array.isArray(e))return e.map(An);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=An(s);return t}return e}function Kl(e,t){if(!t||Object.keys(t).length===0)return e;const n={...e};return Object.keys(t).forEach(s=>{s in n&&delete n[s]}),n}function Gl(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return An(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?An(e):{}}const ss="__secureOutput",rs="[hidden for privacy]";function Hl(e,t){if(!e||e.length===0)return t;const n=new Map;t.forEach(o=>{const i=o[Le]||o.name;i&&n.set(i,o)});const s=new Map(e.map(o=>[o.name,o])),r=[];return e.forEach(o=>{const i=n.get(o.name);if(!i){console.log(`[useAgent] Skipping server-only tool: ${o.name}`);return}if(!o.isEnabled&&!o.isOverridable){console.log(`[useAgent] Blocking non-overridable disabled tool: ${o.name}`);return}if(!o.isEnabled&&o.isOverridable&&i){console.log(`[useAgent] Allowing overridable disabled tool with local implementation: ${o.name}`),r.push(i);return}o.isEnabled&&i&&r.push(i)}),t.forEach(o=>{const i=o[Le]||o.name;i&&!s.has(i)&&(console.log(`[useAgent] Allowing client-only tool (forward compatible): ${i}`),r.push(o))}),r}function Yl(e){if(typeof globalThis.structuredClone=="function")return globalThis.structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn("[useAgent] Failed to clone value for redaction:",t),e}}function Jl(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function Zl(e,t){if(t.length===0)return e;if(!e||typeof e!="object")return;let n=e;for(const s of t){if(!n||typeof n!="object")return;n=n[s]}return n}function Ql(e,t,n){if(!e||typeof e!="object"||t.length===0)return!1;let s=e;for(let o=0;o<t.length-1;o++){if(!s||typeof s!="object")return!1;const i=s,a=t[o];if(a===void 0)return!1;const l=i[a];if(l==null||typeof l!="object")return!1;s=l}if(!s)return!1;const r=t[t.length-1];return!r||!(r in s)?!1:(s[r]=n,!0)}function Xs(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Eo(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=Xs(r),r&&typeof r=="object"&&Object.assign(n,Eo(r,o))}):t&&(n[t]=Xs(e)),n}function ec(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:rs,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:rs,includeFieldStatus:!1,preserve:[]};const t=e.strategy??(e.fields&&e.fields.length>0?"fields":"full");return{strategy:t,fields:t==="fields"?e.fields??[]:[],placeholder:e.placeholder??rs,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function tc(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=ec(s);r&&(t[n]=r)}return t}function Mo(e,t,n){const s=n.placeholder,r={tool:e,redacted:!0,strategy:n.strategy,placeholder:s};if(n.strategy==="full"){n.includeFieldStatus&&typeof t=="object"&&t!==null&&(r.fieldStatus=Eo(t)),r.redactedFields=["*"];let l={};return n.preserve.length>0&&t&&typeof t=="object"&&n.preserve.forEach(c=>{c in t&&(l[c]=t[c])}),l[ss]=r,l}if(n.fields.includes("*"))return Mo(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[ss]:{...r,redactedFields:n.fields}};const o=Yl(t),i=[],a={};return n.fields.forEach(l=>{const c=Jl(l);if(c.length===0)return;const d=Zl(o,c),f=Xs(d);a[l]=f,Ql(o,c,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[ss]=r,o}function ko({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],safeToolNames:a,toolMetadata:l,sensitiveParams:c,sensitiveOutputs:d,autoDetectSensitive:f=!1,autoFormGeneration:m=!1,formMode:p="auto",systemPrompt:b="",agentId:v,agentName:T,projectId:w,enableRemoteConfig:M,remoteConfigUrl:E,initialMessages:$=[],conversationId:D,state:I,onStateChange:k,allowStateEdits:j=!0,onToolCall:V,onFinish:A,sources:N,ragConfig:L,ragFilters:O,secureInputHandler:F}={}){const X=e.replace(/\/+$/,""),[G,K]=h.useState(null),[oe,be]=h.useState(!1),[Ge,Ct]=h.useState(null),tt=h.useMemo(()=>{const g=N||[],y=G?.config?.sources||[];return[...new Set([...g,...y])]},[N,G]),H=h.useMemo(()=>L!==void 0?L:O?{enabled:!0,filters:O}:tt&&tt.length>0?{enabled:!0,organizationId:tt[0],autoExecute:!0,filters:void 0}:{enabled:!1},[tt,L,O]),Ot=h.useMemo(()=>M===!1?!1:!!w,[w,M]);h.useEffect(()=>{if(!Ot||!ae.current)return;(async()=>{be(!0),Ct(null);try{const x=`${E||X.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,S=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ae.current}`},body:JSON.stringify({path:"agents:getConfigForClient",args:{projectId:w,agentName:T,agentId:v},format:"json"})});if(!S.ok){if(S.status===404){console.warn("[useAgent] Remote config endpoint not found (404), using local tools only"),K(null);return}const R=await S.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch remote config: ${S.status} ${R}`)}const P=await S.json();K(P?.value||null),console.log("[useAgent] Remote config loaded successfully:",P?.value)}catch(y){console.error("[useAgent] Failed to fetch remote config:",y);const x=y instanceof Error?y:new Error(String(y));Ct(x),K(null)}finally{be(!1)}})()},[Ot,w,T,v,X,E]);const ke=h.useMemo(()=>{const g={};if(c)for(const[y,x]of Object.entries(c))if(g[y]={},Array.isArray(x))for(const S of x){const P=jn(S);g[y][S]=P||"text"}else for(const[S,P]of Object.entries(x))g[y][S]=P;if(l){for(const[y,x]of Object.entries(l))if(x&&typeof x=="object"&&"sensitiveParams"in x){g[y]||(g[y]={});const S=x.sensitiveParams;if(Array.isArray(S))for(const P of S){const R=jn(P);g[y][P]=R||"text"}else if(S&&typeof S=="object")for(const[P,R]of Object.entries(S))g[y][P]=R}}return g},[c,l,f]),jt=h.useMemo(()=>tc(d),[d]),Ae=h.useCallback((g,y)=>{const x=jt[g];if(!x)return y;try{return Mo(g,y,x)}catch(S){return console.error(`[useAgent] Failed to redact output for ${g}:`,S),{value:rs,[ss]:{tool:g,redacted:!0,error:String(S)}}}},[jt]),[Ue,$t]=h.useState(n||null),ae=h.useRef(n||null),[pn,ut]=h.useState(null),[dt,gn]=h.useState(null),ze=h.useRef(null),[Pt,At]=h.useState([]),[Ve,yn]=h.useState(D||(typeof window<"u"?crypto.randomUUID():null)),[vs,Lt]=h.useState(!1),Ft=h.useRef(new Set),ft=h.useRef(new Set),Ie=h.useRef(new Set),[Qr,_n]=h.useState(new Map),[He,Xn]=h.useState(new Map),[ws,Bt]=h.useState(new Map),[xn,Ut]=h.useState(new Map),ce=I!==void 0,[Ye,nt]=h.useState({}),me=h.useRef({}),_e=ce?I||{}:Ye;ce&&I?me.current=I:ce||(me.current=Ye);const[bn,ht]=h.useState(!1),[Wn,vn]=h.useState(null),Ne=h.useRef(!1),wn=h.useCallback(async(g,y=3)=>{if(!Ve||!ae.current)return;const x=async()=>{const P=`${X.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,R=await fetch(P,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ae.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Ve,updates:g},format:"json"})});if(!R.ok){if(R.status===404)return;const B=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${R.status} ${B}`)}};for(let S=0;S<y;S++)try{await x(),vn(null);return}catch(P){if(S===y-1){const B=P instanceof Error?P:new Error(String(P));throw vn(B),console.error("Failed to sync state to Convex after retries:",P),B}await new Promise(B=>setTimeout(B,Math.pow(2,S)*100))}},[Ve,X,ae]),we=h.useMemo(()=>function(){return me.current},[]),st=h.useMemo(()=>async function(y){const x={...me.current,...y};me.current=x,ce||nt(x),k&&k(x);try{await wn(y)}catch(S){throw S}},[wn,k,ce]);h.useEffect(()=>{ce&&I&&(me.current=I)},[ce,I]);const zt=h.useCallback(g=>F?F.showSecureModal(g):new Promise(y=>{_n(x=>new Map(x).set(g.id,g)),Xn(x=>new Map(x).set(g.id,y))}),[F]),rt=h.useCallback((g,y)=>{if(F)return;const x=He.get(g);x&&(x(y),_n(S=>{const P=new Map(S);return P.delete(g),P}),Xn(S=>{const P=new Map(S);return P.delete(g),P}))},[He,F]),ei=h.useCallback(g=>F?F.showSecureForm(g):new Promise(y=>{Bt(x=>new Map(x).set(g.id,g)),Ut(x=>new Map(x).set(g.id,y))}),[F]),Ss=h.useCallback((g,y)=>{if(F)return;const x=xn.get(g);x&&(x(y),Bt(S=>{const P=new Map(S);return P.delete(g),P}),Ut(S=>{const P=new Map(S);return P.delete(g),P}))},[xn,F]),_t=h.useCallback((g,y)=>{const x=ke[g]||{},S=Object.keys(x).length>0;if(f){const P=Object.keys(y).filter(R=>jn(R)!==null);return S||P.length>0}return S},[ke,f]),Sn=h.useCallback((g,y)=>{const S={...ke[g]||{}};if(f){for(const R of Object.keys(y))if(!(R in S)){const B=jn(R);B&&(S[R]=B)}}const P=Object.entries(S).filter(([R])=>Object.prototype.hasOwnProperty.call(y,R));return P.length>0?Object.fromEntries(P):S},[ke,f]),mt=h.useMemo(()=>H?.enabled?async function(y,x=20,S){const P={...H.filters,...S};if(N&&N.length>1){const B=N.map(ee=>fetch(`${X}/search`,{method:"POST",headers:{"Content-Type":"application/json",...ae.current?{Authorization:`Bearer ${ae.current}`}:{}},body:JSON.stringify({q:y,k:Math.min(x,100),organizationId:ee,...Object.keys(P).length>0?{filters:P}:{}})}).then(ne=>ne.ok?ne.json():null)),Q=await Promise.all(B),q=[];for(const ee of Q)ee?.candidates&&q.push(...ee.candidates);q.sort((ee,ne)=>{const de=ee.scores?.rerank||ee.scores?.dense||0;return(ne.scores?.rerank||ne.scores?.dense||0)-de});const ue=q.slice(0,x).map((ee,ne)=>{const de=ee.citation||ee.url;return{rank:ne+1,doc_id:ee.doc_id,block_id:ee.block_id,url:ee.url,citation:de,title:ee.title||"Untitled",snippet:ee.snippet,score:ee.scores?.rerank||ee.scores?.dense||0,metadata:{site:ee.metadata?.site,lang:ee.metadata?.lang,contentType:ee.metadata?.content_type}}});return{success:!0,query:y,total:q.length,results:ue,summary:`Found ${q.length} relevant results across ${N.length} source(s) for "${y}". Top result: ${ue[0]?.title||"N/A"}`}}const R=H.organizationId&&H.organizationId!=="default"?H.organizationId:N&&N.length>0?N[0]:void 0;try{const B={q:y,k:Math.min(x,100)};R&&(B.organizationId=R),Object.keys(P).length>0&&(B.filters=P);const Q={"Content-Type":"application/json"};ae.current&&(Q.Authorization=`Bearer ${ae.current}`);const q=await fetch(`${X}/search`,{method:"POST",headers:Q,body:JSON.stringify(B)});if(!q.ok){const ne=await q.text();return{success:!1,error:`Search failed: ${q.status} ${ne}`}}const ue=await q.json(),ee=ue.candidates.map((ne,de)=>{const qt=ne.citation||ne.url;return{rank:de+1,doc_id:ne.doc_id,block_id:ne.block_id,url:ne.url,citation:qt,title:ne.title||"Untitled",snippet:ne.snippet,score:ne.scores?.rerank||ne.scores?.dense||0,metadata:{site:ne.metadata?.site,lang:ne.metadata?.lang,contentType:ne.metadata?.content_type}}});return{success:!0,query:ue.query,total:ue.total,results:ee,summary:`Found ${ue.total} relevant results for "${y}". Top result: ${ee[0]?.title||"N/A"}`}}catch(B){return{success:!1,error:B instanceof Error?B.message:"Unknown error occurred"}}}:null,[H,X,ae]),it=h.useMemo(()=>H?.enabled?async function(y,x){const S=H.organizationId&&H.organizationId!=="default"?H.organizationId:N&&N.length>0?N[0]:void 0;try{const P={"Content-Type":"application/json"};ae.current&&(P.Authorization=`Bearer ${ae.current}`);const R=await fetch(`${X}/fetch`,{method:"POST",headers:P,body:JSON.stringify({doc_id:y,block_ids:x,...S?{organizationId:S}:{}})});if(!R.ok){const Q=await R.text();return{success:!1,error:`Fetch failed: ${R.status} ${Q}`}}const B=await R.json();return{success:!0,blocks:B.blocks||[],fullContent:B.fullContent||"",pageUrl:B.pageUrl||"",pageTitle:B.pageTitle||"",summary:`Fetched ${B.blocks?.length||0} blocks from ${B.pageTitle||y}`}}catch(P){return{success:!1,error:P instanceof Error?P.message:"Unknown error occurred"}}}:null,[H,X,ae]),Xt=h.useMemo(()=>{if(G&&G.config?.tools){const g=Hl(G.config.tools,o);return console.log("[useAgent] Merged remote config:",{remoteToolCount:G.config.tools.length,localToolCount:o.length,mergedToolCount:g.length}),g}return o},[G,o]),Xe=G?.enableStateTools??!0,Je=G?.enableRagTools??H?.enabled??!1,qn=h.useMemo(()=>{const g=[...Xt,...i];return Xe&&(g.push(we),(!ce||j)&&g.push(st)),Je&&(mt&&g.push(mt),it&&g.push(it)),g},[Xt,i,we,st,mt,it,Xe,Je,ce,j]),Kn=h.useMemo(()=>[...Xt,...i],[Xt,i]),ot=h.useMemo(()=>pr(Kn,l),[Kn,l]),pt=h.useMemo(()=>{const g=new Map,y=new Map(ot.map(x=>[x.name,x]));return g.set("getState",we),(!ce||j)&&g.set("setState",st),H?.enabled&&(mt&&g.set("searchDocs",mt),it&&g.set("fetchDocContent",it)),qn.forEach(x=>{if(x===we||x===st||x===mt||x===it)return;const S=x[Le];if(S){const R=y.get(S);if(R){g.set(R.name,x);return}}const P=ot.find(R=>R.name===x.name);P&&g.set(P.name,x)}),g},[qn,ot,we,st,mt,it,H,ce,j]),Gn=h.useMemo(()=>new Set(ot.map(g=>g.name)),[ot]),Hn=h.useMemo(()=>{const g=[];Xe&&(g.push({name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}),(!ce||j)&&g.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}}));const y=[];Je&&y.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}});const x=[];return G?.config?.workflows&&G.config.workflows.forEach(S=>{const P={},R=[];S.parameters&&S.parameters.forEach(B=>{P[B.name]={type:B.type||"string",description:B.description},B.required&&R.push(B.name)}),x.push({name:`workflow_${S.name.replace(/\s+/g,"_").toLowerCase()}`,description:S.description||`Execute the "${S.name}" workflow. ${S.contentPlaintext?.slice(0,200)||""}`,jsonSchema:{type:"object",properties:P,required:R},_workflow:S})}),[...ot,...g,...y,...x]},[ot,Xe,Je,ce,j,G]),gt=h.useMemo(()=>Hn.filter(g=>g.name==="getState"?Xe:g.name==="setState"?Xe&&(!ce||j):g.name==="searchDocs"||g.name==="fetchDocContent"?Je:g.name.startsWith("workflow_")?!0:Gn.has(g.name)),[Hn,Gn,Xe,Je,ce,j]),Wt=h.useMemo(()=>{const g=new Set;return Xe&&(g.add("getState"),g.add("setState")),Je&&H?.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent")),G?.config?.tools?G.config.tools.forEach(y=>{y.isEnabled&&!y.requiresApproval&&g.add(y.name)}):(i.forEach(y=>{for(const[x,S]of pt.entries())if(S===y){g.add(x);break}}),a&&Array.isArray(a)&&a.forEach(y=>{typeof y=="string"&&g.add(y)})),G?.config?.workflows&&G.config.workflows.forEach(y=>{const x=`workflow_${y.name.replace(/\s+/g,"_").toLowerCase()}`;y.requiresApproval||g.add(x)}),g},[G,i,a,pt,Xe,Je,H]);h.useEffect(()=>{if(s||n)return;let g=!1,y=null;const x=async(S=1,P=3)=>{if(!g)try{const R=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!R.ok)throw new Error("Failed to fetch token");const B=await R.json();g||($t(B.clientToken),ae.current=B.clientToken,gn(B.expiresAt),ut(null))}catch(R){if(console.error(`[useAgent] Token fetch failed (attempt ${S}/${P}):`,R),S<P&&!g){const B=Math.pow(2,S-1)*1e3;y=setTimeout(()=>x(S+1,P),B)}else g||ut(R instanceof Error?R.message:"Failed to fetch token")}};return x(),()=>{g=!0,y&&clearTimeout(y),ze.current&&clearTimeout(ze.current)}},[t,JSON.stringify(r),s,n]),h.useEffect(()=>{if(!dt||s||n)return;ze.current&&clearTimeout(ze.current);const g=async(R=1,B=3)=>{try{const Q=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!Q.ok)throw new Error("Failed to refresh token");const q=await Q.json();$t(q.clientToken),ae.current=q.clientToken,gn(q.expiresAt),ut(null)}catch(Q){if(console.error(`[useAgent] Token refresh failed (attempt ${R}/${B}):`,Q),R<B){const q=Math.pow(2,R-1)*1e3;setTimeout(()=>g(R+1,B),q)}else ut(Q instanceof Error?Q.message:"Failed to refresh token")}},y=Math.floor(Date.now()/1e3),x=dt-y,P=Math.max(0,x-5);return ze.current=setTimeout(()=>g(),P*1e3),()=>{ze.current&&clearTimeout(ze.current)}},[dt,t,JSON.stringify(r),s,n]),h.useEffect(()=>{if(s||n)return;const g=async()=>{if(document.visibilityState!=="visible")return;const y=Math.floor(Date.now()/1e3);if(!dt||dt<=y+5){console.log("[useAgent] Tab visible, token expired - refreshing");try{const S=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(S.ok){const P=await S.json();$t(P.clientToken),ae.current=P.clientToken,gn(P.expiresAt),ut(null)}}catch(S){console.error("[useAgent] Token refresh on visibility change failed:",S)}}};return document.addEventListener("visibilitychange",g),()=>document.removeEventListener("visibilitychange",g)},[t,JSON.stringify(r),dt,s,n]);const Yn=async(g,y={})=>{const x=y.headers?new Headers(y.headers):new Headers;return x.delete("user-agent"),x.delete("User-Agent"),fetch(g,{...y,headers:x})},Tn=h.useRef(null),C=`${X}/chat`,{messages:U,sendMessage:W,status:Z,error:Y,stop:te,addToolResult:Re,setMessages:re}=Ml.useChat({id:Ve||void 0,messages:$,transport:new ri.DefaultChatTransport({api:C,fetch:Yn,headers:()=>{const g={};return ae.current&&(g.Authorization=`Bearer ${ae.current}`),g},body:()=>({tools:gt.map(y=>({name:y.name,description:y.description,inputSchema:y.jsonSchema})),...v&&{agentId:v},...T&&{agentName:T},state:me.current,...O&&{ragFilters:O}})}),sendAutomaticallyWhen:g=>{const y=g.messages;if(y[y.length-1]?.role!=="assistant")return!1;const P=[...y].reverse().find(B=>B.role==="user")?.id;if(P&&Tn.current===P)return!1;const R=ri.lastAssistantMessageIsCompleteWithToolCalls(g);return R&&P&&(Tn.current=P),R}}),Te=g=>{if(!g||Object.keys(g).length===0)return"";try{return`
|
|
3
|
-
|
|
4
|
-
--- Current State ---
|
|
5
|
-
${JSON.stringify(g,null,2)}`}catch(y){return console.error("[useAgent] Failed to format state:",y),""}},_=W,pe=h.useCallback(g=>{Tn.current=null,Ie.current=new Set;const y=Te(I||Ye),x={text:g.text+y};return _(x)},[_,I,Ye]),J=h.useCallback((g,y,x)=>{const S=Ae(g,x);Re({toolCallId:y,tool:g,output:S})},[Re,Ae]);h.useEffect(()=>{U.forEach(g=>{g.role==="assistant"&&g.parts.forEach(y=>{if(!y.type?.startsWith("tool-")||y.state!=="input-available")return;const x=y.type.replace("tool-",""),S=y.toolCallId;if(Ft.current.has(S)||ft.current.has(S)){console.log(`[useAgent] Skipping ${x} (${S}) - already processing or completed`);return}console.log(`[useAgent] Starting ${x} (${S})`),Ft.current.add(S);const P=Q=>{console.log(`[useAgent] Completed ${x} (${Q})`),ft.current.add(Q),Ft.current.delete(Q)},R=Gl(y.input),B=`${x}:${JSON.stringify(R)}`;if(Ie.current.has(B)){console.log(`[useAgent] Skipping duplicate tool call: ${B}`),J(x,S,"This tool was already called successfully with the same arguments in this response. Using previous result."),P(S);return}if(_t(x,R)){const Q=Sn(x,R),q=Object.entries(Q).filter(([de])=>R[de]!==void 0),ue=q.length>0?Object.fromEntries(q):Q,ee=Object.keys(R),ne=Kl(R,ue);(async()=>{try{const de=Ul(x,ee,ue,R),qt={id:`${S}-form`,toolName:x,toolCallId:S,title:de.title,description:de.description,fields:de.fields},Jn=await ei(qt);if(Jn===null){J(x,S,"User cancelled secure input"),P(S);return}const ti={...ne,...Jn},Ts=pt.get(x);if(!Ts)throw new Error(`Tool ${x} not found`);let Cs;const js=gt.find(ni=>ni.name===x);if(js&&js.jsonSchema?.properties){const vl=Object.keys(js.jsonSchema.properties).map(wl=>ti[wl]);Cs=await Ts(...vl)}else Cs=await Ts(...Object.values(ti));P(S),J(x,S,Cs),Ie.current.add(B)}catch(de){console.error(`[useAgent] Error executing tool with secure input ${x}:`,de),P(S),J(x,S,`Error: ${de}`)}})();return}if(x.startsWith("workflow_")&&Wt.has(x)){(async()=>{try{const q=gt.find(ee=>ee.name===x)?._workflow;if(!q)throw new Error(`Workflow metadata not found for ${x}`);let ue;if(q.webhook?.url){let ee=R;if(q.webhook.bodyTemplate){let de=q.webhook.bodyTemplate;Object.entries(R).forEach(([qt,Jn])=>{de=de.replace(new RegExp(`\\{\\{${qt}\\}\\}`,"g"),String(Jn))}),ee=JSON.parse(de)}const ne=await fetch(q.webhook.url,{method:q.webhook.method||"POST",headers:{"Content-Type":"application/json",...q.webhook.headers||{}},body:JSON.stringify(ee)});if(ne.ok)ue={success:!0,data:await ne.json().catch(()=>({success:!0}))};else{const de=await ne.text();ue={success:!1,error:`Webhook failed: ${ne.status} ${de}`}}}else ue={success:!0,message:`Workflow "${q.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:q.contentPlaintext};P(S),J(x,S,ue),Ie.current.add(B)}catch(Q){console.error(`[useAgent] Error executing workflow ${x}:`,Q),P(S),J(x,S,`Error: ${Q}`)}})();return}if(Wt.has(x)&&!_t(x,R)){const Q=pt.get(x);Q?(async()=>{try{const q=gt.find(ee=>ee.name===x);let ue;if(q&&q.jsonSchema?.properties){const ne=Object.keys(q.jsonSchema.properties).map(de=>R[de]);ue=await Q(...ne)}else if(x==="getState")ue=Q();else if(x==="setState"){const ee=R.updates||R;ue=await Q(ee)}else ue=await Q(...Object.values(R));P(S),J(x,S,ue),Ie.current.add(B)}catch(q){console.error(`[useAgent] Error executing tool ${x}:`,q),P(S),J(x,S,`Error: ${q}`)}})():(console.warn(`[useAgent] Tool ${x} not found in toolsMap`),J(x,S,`Error: Tool "${x}" not found. The tool may not be registered or available.`),P(S))}else x.startsWith("workflow_")&&V?V({toolCall:{toolCallId:S,toolName:x,args:R}}):V?V({toolCall:{toolCallId:S,toolName:x,args:R}}):(console.warn(`[useAgent] No handler for tool ${x} - tool is not safe and no onToolCall callback provided`),J(x,S,`Error: Tool "${x}" cannot be executed. No handler is available for this tool.`),P(S))})})},[U,Wt,pt,V,J,st,gt,_t,Sn,zt]),h.useEffect(()=>{if(Z==="ready"&&U.length>0&&A){const g=U[U.length-1];g&&g.role==="assistant"&&A({message:g,messages:U,isAbort:!1,isDisconnect:!1,isError:!!Y})}},[Z,U,Y,A]);async function Ee(){if(!(!r?.id||!Ue)){Lt(!0);try{const y=await(await fetch(`${X}/conversations`,{headers:{Authorization:`Bearer ${Ue}`}})).json();At(y.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{Lt(!1)}}}h.useEffect(()=>{r?.id&&Ue&&Ee()},[JSON.stringify(r),Ue,X]),h.useEffect(()=>{if(!Ve||!ae.current)return;(async()=>{ht(!0),vn(null);try{const y=await fetch(`${X.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ae.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Ve},format:"json"})});if(!y.ok){const P=await y.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${y.status} ${P}`)}const S=(await y.json())?.value||{};me.current=S,ce||nt(S),k&&k(S),Ne.current=!0}catch(y){console.error("Failed to fetch state:",y);const x=y instanceof Error?y:new Error(String(y));vn(x),Ne.current||(me.current={},ce?k&&k({}):(nt({}),k&&k({})),Ne.current=!0)}finally{ht(!1)}})()},[Ve,X,ce,k]);async function ge(g){yn(g),Lt(!0);try{const y=await fetch(`${X}/conversations/${g}/messages`,{headers:{Authorization:`Bearer ${ae.current}`}});if(!y.ok)throw new Error(`Failed to fetch messages: ${y.statusText}`);const S=(await y.json()).messages||[];re(S)}catch(y){console.error("Failed to load conversation messages:",y)}finally{Lt(!1)}}async function Ze(g){if(Ue)try{await fetch(`${X}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${Ue}`}}),At(Pt.filter(y=>y._id!==g)),g===Ve&&ve()}catch(y){console.error("Failed to delete conversation:",y)}}function ve(){const g=crypto.randomUUID();yn(g),re([]),Ft.current=new Set,ft.current=new Set,me.current={},ce?k&&k({}):(nt({}),k&&k({})),Ne.current=!1}function Ce(g){const y=g.tool||"unknown-tool",x=Ae(y,g.output);Re({toolCallId:g.toolCallId,tool:y,output:x})}async function Qe(g,y,x){if(!y.startsWith("workflow_"))throw new Error(`${y} is not a workflow tool`);try{const P=gt.find(B=>B.name===y)?._workflow;if(!P)throw new Error(`Workflow metadata not found for ${y}`);let R;if(P.webhook?.url){let B=x;if(P.webhook.bodyTemplate){let q=P.webhook.bodyTemplate;Object.entries(x).forEach(([ue,ee])=>{q=q.replace(new RegExp(`\\{\\{${ue}\\}\\}`,"g"),String(ee))}),B=JSON.parse(q)}const Q=await fetch(P.webhook.url,{method:P.webhook.method||"POST",headers:{"Content-Type":"application/json",...P.webhook.headers||{}},body:JSON.stringify(B)});if(Q.ok)R={success:!0,data:await Q.json().catch(()=>({success:!0}))};else{const q=await Q.text();R={success:!1,error:`Webhook failed: ${Q.status} ${q}`}}}else R={success:!0,message:`Workflow "${P.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:P.contentPlaintext};return Ce({toolCallId:g,tool:y,output:R}),R}catch(S){const P={success:!1,error:String(S)};throw Ce({toolCallId:g,tool:y,output:P}),S}}async function bl(g){const y={...me.current,...g};me.current=y,ce||nt(y),k&&k(y);try{await wn(g)}catch(x){throw x}}return{id:Ve,messages:U,status:Z,error:Y,sendMessage:pe,stop:te,addToolOutput:Ce,executeWorkflowTool:Qe,setMessages:re,conversations:Pt,loadConversation:ge,deleteConversation:Ze,startNewConversation:ve,isLoadingConversations:vs,clientToken:Ue,tokenError:pn,state:_e,setState:bl,isStateLoading:bn,stateError:Wn,pendingSecureInputs:Array.from(Qr.values()),completeSecureInput:rt,pendingSecureForms:Array.from(ws.values()),completeSecureForm:Ss,safeToolNames:Wt}}function ie(...e){return Nl.twMerge(kl.clsx(e))}const Mt=Po.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),Pe=qe.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?jo.Slot:"button";return u.jsx(i,{ref:o,"data-slot":"button",className:ie(Mt({variant:t,size:n,className:e})),...r})});Pe.displayName="Button";const nc=Po.cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function Ps({className:e,variant:t,asChild:n=!1,...s}){const r=n?jo.Slot:"span";return u.jsx(r,{"data-slot":"badge",className:ie(nc({variant:t}),e),...s})}const sc=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=qe.useState(!0);qe.useEffect(()=>{const a=e.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const l=a.scrollHeight;l>n?a.style.height=`${n}px`:a.style.height=`${l+6}px`}},[e.current,t])},No=qe.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=qe.useRef(null),[l,c]=qe.useState("");return sc({textAreaRef:a,triggerAutoSize:l,maxHeight:e,minHeight:t}),h.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),qe.useEffect(()=>{c(r)},[o?.defaultValue,r]),u.jsx("textarea",{...o,value:r,ref:a,className:ie("flex 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 disabled:cursor-not-allowed disabled:opacity-50",n),onChange:d=>{c(d.target.value),s?.(d)}})});No.displayName="AutosizeTextarea";function rc({delayDuration:e=0,...t}){return u.jsx(Qt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function yt({...e}){return u.jsx(rc,{children:u.jsx(Qt.Root,{"data-slot":"tooltip",...e})})}function xt({...e}){return u.jsx(Qt.Trigger,{"data-slot":"tooltip-trigger",...e})}function bt({className:e,sideOffset:t=0,children:n,...s}){return u.jsx(Qt.Portal,{children:u.jsxs(Qt.Content,{"data-slot":"tooltip-content",sideOffset:t,className:ie("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...s,children:[n,u.jsx(Qt.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function oi({className:e,...t}){return u.jsx("kbd",{"data-slot":"kbd",className:ie("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}const gr=h.createContext({});function yr(e){const t=h.useRef(null);return t.current===null&&(t.current=e()),t.current}const xr=typeof window<"u",Ro=xr?h.useLayoutEffect:h.useEffect,gs=h.createContext(null);function br(e,t){e.indexOf(t)===-1&&e.push(t)}function vr(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const at=(e,t,n)=>n>t?t:n<e?e:n;function Ws(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let sn=()=>{},lt=()=>{};process.env.NODE_ENV!=="production"&&(sn=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Ws(t,n))},lt=(e,t,n)=>{if(!e)throw new Error(Ws(t,n))});const ct={},Do=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Vo(e){return typeof e=="object"&&e!==null}const Io=e=>/^0[^.\s]+$/u.test(e);function wr(e){let t;return()=>(t===void 0&&(t=e()),t)}const Be=e=>e,ic=(e,t)=>n=>t(e(n)),Fn=(...e)=>e.reduce(ic),Dn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class Sr{constructor(){this.subscriptions=[]}add(t){return br(this.subscriptions,t),()=>vr(this.subscriptions,t)}notify(t,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Ke=e=>e*1e3,Fe=e=>e/1e3;function Oo(e,t){return t?e*(1e3/t):0}const ai=new Set;function Tr(e,t,n){e||ai.has(t)||(console.warn(Ws(t,n)),ai.add(t))}const $o=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,oc=1e-7,ac=12;function lc(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=$o(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>oc&&++a<ac);return i}function Bn(e,t,n,s){if(e===t&&n===s)return Be;const r=o=>lc(o,0,1,e,n);return o=>o===0||o===1?o:$o(r(o),t,s)}const Lo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Fo=e=>t=>1-e(1-t),Bo=Bn(.33,1.53,.69,.99),Cr=Fo(Bo),Uo=Lo(Cr),zo=e=>(e*=2)<1?.5*Cr(e):.5*(2-Math.pow(2,-10*(e-1))),jr=e=>1-Math.sin(Math.acos(e)),_o=Fo(jr),Xo=Lo(jr),cc=Bn(.42,0,1,1),uc=Bn(0,0,.58,1),Wo=Bn(.42,0,.58,1),dc=e=>Array.isArray(e)&&typeof e[0]!="number",qo=e=>Array.isArray(e)&&typeof e[0]=="number",li={linear:Be,easeIn:cc,easeInOut:Wo,easeOut:uc,circIn:jr,circInOut:Xo,circOut:_o,backIn:Cr,backInOut:Uo,backOut:Bo,anticipate:zo},fc=e=>typeof e=="string",ci=e=>{if(qo(e)){lt(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return Bn(t,n,s,r)}else if(fc(e))return lt(li[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),li[e];return e},Zn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function hc(e,t){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function l(d){i.has(d)&&(c.schedule(d),e()),d(a)}const c={schedule:(d,f=!1,m=!1)=>{const b=m&&r?n:s;return f&&i.add(d),b.has(d)||b.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(l),n.clear(),r=!1,o&&(o=!1,c.process(d))}};return c}const mc=40;function Ko(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Zn.reduce((E,$)=>(E[$]=hc(o),E),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:f,preRender:m,render:p,postRender:b}=i,v=()=>{const E=ct.useManualTiming?r.timestamp:performance.now();n=!1,ct.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(E-r.timestamp,mc),1)),r.timestamp=E,r.isProcessing=!0,a.process(r),l.process(r),c.process(r),d.process(r),f.process(r),m.process(r),p.process(r),b.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(v))},T=()=>{n=!0,s=!0,r.isProcessing||e(v)};return{schedule:Zn.reduce((E,$)=>{const D=i[$];return E[$]=(I,k=!1,j=!1)=>(n||T(),D.schedule(I,k,j)),E},{}),cancel:E=>{for(let $=0;$<Zn.length;$++)i[Zn[$]].cancel(E)},state:r,steps:i}}const{schedule:le,cancel:wt,state:Se,steps:As}=Ko(typeof requestAnimationFrame<"u"?requestAnimationFrame:Be,!0);let is;function pc(){is=void 0}const De={now:()=>(is===void 0&&De.set(Se.isProcessing||ct.useManualTiming?Se.timestamp:performance.now()),is),set:e=>{is=e,queueMicrotask(pc)}},Go=e=>t=>typeof t=="string"&&t.startsWith(e),Pr=Go("--"),gc=Go("var(--"),Ar=e=>gc(e)?yc.test(e.split("/*")[0].trim()):!1,yc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,rn={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Vn={...rn,transform:e=>at(0,1,e)},Qn={...rn,default:1},En=e=>Math.round(e*1e5)/1e5,Er=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function xc(e){return e==null}const bc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Mr=(e,t)=>n=>!!(typeof n=="string"&&bc.test(n)&&n.startsWith(e)||t&&!xc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ho=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Er);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},vc=e=>at(0,255,e),Es={...rn,transform:e=>Math.round(vc(e))},Nt={test:Mr("rgb","red"),parse:Ho("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Es.transform(e)+", "+Es.transform(t)+", "+Es.transform(n)+", "+En(Vn.transform(s))+")"};function wc(e){let t="",n="",s="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,s+=s,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const qs={test:Mr("#"),parse:wc,transform:Nt.transform},Un=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),vt=Un("deg"),et=Un("%"),z=Un("px"),Sc=Un("vh"),Tc=Un("vw"),ui={...et,parse:e=>et.parse(e)/100,transform:e=>et.transform(e*100)},Kt={test:Mr("hsl","hue"),parse:Ho("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+et.transform(En(t))+", "+et.transform(En(n))+", "+En(Vn.transform(s))+")"},xe={test:e=>Nt.test(e)||qs.test(e)||Kt.test(e),parse:e=>Nt.test(e)?Nt.parse(e):Kt.test(e)?Kt.parse(e):qs.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Nt.transform(e):Kt.transform(e),getAnimatableNone:e=>{const t=xe.parse(e);return t.alpha=0,xe.transform(t)}},Cc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function jc(e){return isNaN(e)&&typeof e=="string"&&(e.match(Er)?.length||0)+(e.match(Cc)?.length||0)>0}const Yo="number",Jo="color",Pc="var",Ac="var(",di="${}",Ec=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function In(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(Ec,l=>(xe.test(l)?(s.color.push(o),r.push(Jo),n.push(xe.parse(l))):l.startsWith(Ac)?(s.var.push(o),r.push(Pc),n.push(l)):(s.number.push(o),r.push(Yo),n.push(parseFloat(l))),++o,di)).split(di);return{values:n,split:a,indexes:s,types:r}}function Zo(e){return In(e).values}function Qo(e){const{split:t,types:n}=In(e),s=t.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=t[i],r[i]!==void 0){const a=n[i];a===Yo?o+=En(r[i]):a===Jo?o+=xe.transform(r[i]):o+=r[i]}return o}}const Mc=e=>typeof e=="number"?0:xe.test(e)?xe.getAnimatableNone(e):e;function kc(e){const t=Zo(e);return Qo(e)(t.map(Mc))}const St={test:jc,parse:Zo,createTransformer:Qo,getAnimatableNone:kc};function Ms(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Nc({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let r=0,o=0,i=0;if(!t)r=o=i=n;else{const a=n<.5?n*(1+t):n+t-n*t,l=2*n-a;r=Ms(l,a,e+1/3),o=Ms(l,a,e),i=Ms(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function us(e,t){return n=>n>0?t:e}const he=(e,t,n)=>e+(t-e)*n,ks=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},Rc=[qs,Nt,Kt],Dc=e=>Rc.find(t=>t.test(e));function fi(e){const t=Dc(e);if(sn(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Kt&&(n=Nc(n)),n}const hi=(e,t)=>{const n=fi(e),s=fi(t);if(!n||!s)return us(e,t);const r={...n};return o=>(r.red=ks(n.red,s.red,o),r.green=ks(n.green,s.green,o),r.blue=ks(n.blue,s.blue,o),r.alpha=he(n.alpha,s.alpha,o),Nt.transform(r))},Ks=new Set(["none","hidden"]);function Vc(e,t){return Ks.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Ic(e,t){return n=>he(e,t,n)}function kr(e){return typeof e=="number"?Ic:typeof e=="string"?Ar(e)?us:xe.test(e)?hi:Lc:Array.isArray(e)?ea:typeof e=="object"?xe.test(e)?hi:Oc:us}function ea(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>kr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Oc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=kr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function $c(e,t){const n=[],s={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const o=t.types[r],i=e.indexes[o][s[o]],a=e.values[i]??0;n[r]=a,s[o]++}return n}const Lc=(e,t)=>{const n=St.createTransformer(t),s=In(e),r=In(t);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?Ks.has(e)&&!r.values.length||Ks.has(t)&&!s.values.length?Vc(e,t):Fn(ea($c(s,r),r.values),n):(sn(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),us(e,t))};function ta(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?he(e,t,n):kr(e)(e,t)}const Fc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>le.update(t,n),stop:()=>wt(t),now:()=>Se.isProcessing?Se.timestamp:De.now()}},na=(e,t,n=10)=>{let s="";const r=Math.max(Math.round(t/n),2);for(let o=0;o<r;o++)s+=Math.round(e(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},ds=2e4;function Nr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<ds;)t+=n,s=e.next(t);return t>=ds?1/0:t}function Bc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(Nr(s),ds);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Fe(r)}}const Uc=5;function sa(e,t,n){const s=Math.max(t-Uc,0);return Oo(n-e(s),t-s)}const fe={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Ns=.001;function zc({duration:e=fe.duration,bounce:t=fe.bounce,velocity:n=fe.velocity,mass:s=fe.mass}){let r,o;sn(e<=Ke(fe.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=at(fe.minDamping,fe.maxDamping,i),e=at(fe.minDuration,fe.maxDuration,Fe(e)),i<1?(r=c=>{const d=c*i,f=d*e,m=d-n,p=Gs(c,i),b=Math.exp(-f);return Ns-m/p*b},o=c=>{const f=c*i*e,m=f*n+n,p=Math.pow(i,2)*Math.pow(c,2)*e,b=Math.exp(-f),v=Gs(Math.pow(c,2),i);return(-r(c)+Ns>0?-1:1)*((m-p)*b)/v}):(r=c=>{const d=Math.exp(-c*e),f=(c-n)*e+1;return-Ns+d*f},o=c=>{const d=Math.exp(-c*e),f=(n-c)*(e*e);return d*f});const a=5/e,l=Xc(r,o,a);if(e=Ke(e),isNaN(l))return{stiffness:fe.stiffness,damping:fe.damping,duration:e};{const c=Math.pow(l,2)*s;return{stiffness:c,damping:i*2*Math.sqrt(s*c),duration:e}}}const _c=12;function Xc(e,t,n){let s=n;for(let r=1;r<_c;r++)s=s-e(s)/t(s);return s}function Gs(e,t){return e*Math.sqrt(1-t*t)}const Wc=["duration","bounce"],qc=["stiffness","damping","mass"];function mi(e,t){return t.some(n=>e[n]!==void 0)}function Kc(e){let t={velocity:fe.velocity,stiffness:fe.stiffness,damping:fe.damping,mass:fe.mass,isResolvedFromDuration:!1,...e};if(!mi(e,qc)&&mi(e,Wc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*at(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:fe.mass,stiffness:r,damping:o}}else{const n=zc(e);t={...t,...n,mass:fe.mass},t.isResolvedFromDuration=!0}return t}function fs(e=fe.visualDuration,t=fe.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:d,duration:f,velocity:m,isResolvedFromDuration:p}=Kc({...n,velocity:-Fe(n.velocity||0)}),b=m||0,v=c/(2*Math.sqrt(l*d)),T=i-o,w=Fe(Math.sqrt(l/d)),M=Math.abs(T)<5;s||(s=M?fe.restSpeed.granular:fe.restSpeed.default),r||(r=M?fe.restDelta.granular:fe.restDelta.default);let E;if(v<1){const D=Gs(w,v);E=I=>{const k=Math.exp(-v*w*I);return i-k*((b+v*w*T)/D*Math.sin(D*I)+T*Math.cos(D*I))}}else if(v===1)E=D=>i-Math.exp(-w*D)*(T+(b+w*T)*D);else{const D=w*Math.sqrt(v*v-1);E=I=>{const k=Math.exp(-v*w*I),j=Math.min(D*I,300);return i-k*((b+v*w*T)*Math.sinh(j)+D*T*Math.cosh(j))/D}}const $={calculatedDuration:p&&f||null,next:D=>{const I=E(D);if(p)a.done=D>=f;else{let k=D===0?b:0;v<1&&(k=D===0?Ke(b):sa(E,D,I));const j=Math.abs(k)<=s,V=Math.abs(i-I)<=r;a.done=j&&V}return a.value=a.done?i:I,a},toString:()=>{const D=Math.min(Nr($),ds),I=na(k=>$.next(D*k).value,D,30);return D+"ms "+I},toTransition:()=>{}};return $}fs.applyToOptions=e=>{const t=Bc(e,100,fs);return e.ease=t.ease,e.duration=Ke(t.duration),e.type="keyframes",e};function Hs({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:l,restDelta:c=.5,restSpeed:d}){const f=e[0],m={done:!1,value:f},p=j=>a!==void 0&&j<a||l!==void 0&&j>l,b=j=>a===void 0?l:l===void 0||Math.abs(a-j)<Math.abs(l-j)?a:l;let v=n*t;const T=f+v,w=i===void 0?T:i(T);w!==T&&(v=w-f);const M=j=>-v*Math.exp(-j/s),E=j=>w+M(j),$=j=>{const V=M(j),A=E(j);m.done=Math.abs(V)<=c,m.value=m.done?w:A};let D,I;const k=j=>{p(m.value)&&(D=j,I=fs({keyframes:[m.value,b(m.value)],velocity:sa(E,j,m.value),damping:r,stiffness:o,restDelta:c,restSpeed:d}))};return k(0),{calculatedDuration:null,next:j=>{let V=!1;return!I&&D===void 0&&(V=!0,$(j),k(j)),D!==void 0&&j>=D?I.next(j-D):(!V&&$(j),m)}}}function Gc(e,t,n){const s=[],r=n||ct.mix||ta,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const l=Array.isArray(t)?t[i]||Be:t;a=Fn(l,a)}s.push(a)}return s}function Hc(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(lt(o===t.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const i=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=Gc(t,s,r),l=a.length,c=d=>{if(i&&d<e[0])return t[0];let f=0;if(l>1)for(;f<e.length-2&&!(d<e[f+1]);f++);const m=Dn(e[f],e[f+1],d);return a[f](m)};return n?d=>c(at(e[0],e[o-1],d)):c}function Yc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=Dn(0,t,s);e.push(he(n,1,r))}}function Jc(e){const t=[0];return Yc(t,e.length-1),t}function Zc(e,t){return e.map(n=>n*t)}function Qc(e,t){return e.map(()=>t||Wo).splice(0,e.length-1)}function Gt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=dc(s)?s.map(ci):ci(s),o={done:!1,value:t[0]},i=Zc(n&&n.length===t.length?n:Jc(t),e),a=Hc(i,t,{ease:Array.isArray(r)?r:Qc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const eu=e=>e!==null;function Rr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(eu),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const tu={decay:Hs,inertia:Hs,tween:Gt,keyframes:Gt,spring:fs};function ra(e){typeof e.type=="string"&&(e.type=tu[e.type])}class Dr{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const nu=e=>e/100;class Vr extends Dr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==De.now()&&this.tick(De.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;ra(t);const{type:n=Gt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Gt;process.env.NODE_ENV!=="production"&&l!==Gt&<(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Gt&&typeof a[0]!="number"&&(this.mixKeyframes=Fn(nu,ta(a[0],a[1])),a=[0,100]);const c=l({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...t,keyframes:[...a].reverse(),velocity:-i})),c.calculatedDuration===null&&(c.calculatedDuration=Nr(c));const{calculatedDuration:d}=c;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=c}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return s.next(0);const{delay:c=0,keyframes:d,repeat:f,repeatType:m,repeatDelay:p,type:b,onUpdate:v,finalKeyframe:T}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const w=this.currentTime-c*(this.playbackSpeed>=0?1:-1),M=this.playbackSpeed>=0?w<0:w>r;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let E=this.currentTime,$=s;if(f){const j=Math.min(this.currentTime,r)/a;let V=Math.floor(j),A=j%1;!A&&j>=1&&(A=1),A===1&&V--,V=Math.min(V,f+1),!!(V%2)&&(m==="reverse"?(A=1-A,p&&(A-=p/a)):m==="mirror"&&($=i)),E=at(0,1,A)*a}const D=M?{done:!1,value:d[0]}:$.next(E);o&&(D.value=o(D.value));let{done:I}=D;!M&&l!==null&&(I=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&I);return k&&b!==Hs&&(D.value=Rr(d,this.options,T,this.speed)),v&&v(D.value),k&&this.finish(),D}then(t,n){return this.finished.then(t,n)}get duration(){return Fe(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Fe(t)}get time(){return Fe(this.currentTime)}set time(t){t=Ke(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(De.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Fe(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Fc,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(De.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function su(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Rt=e=>e*180/Math.PI,Ys=e=>{const t=Rt(Math.atan2(e[1],e[0]));return Js(t)},ru={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Ys,rotateZ:Ys,skewX:e=>Rt(Math.atan(e[1])),skewY:e=>Rt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Js=e=>(e=e%360,e<0&&(e+=360),e),pi=Ys,gi=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),yi=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),iu={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:gi,scaleY:yi,scale:e=>(gi(e)+yi(e))/2,rotateX:e=>Js(Rt(Math.atan2(e[6],e[5]))),rotateY:e=>Js(Rt(Math.atan2(-e[2],e[0]))),rotateZ:pi,rotate:pi,skewX:e=>Rt(Math.atan(e[4])),skewY:e=>Rt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Zs(e){return e.includes("scale")?1:0}function Qs(e,t){if(!e||e==="none")return Zs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=iu,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=ru,r=a}if(!r)return Zs(t);const o=s[t],i=r[1].split(",").map(au);return typeof o=="function"?o(i):i[o]}const ou=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Qs(n,t)};function au(e){return parseFloat(e.trim())}const on=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],an=new Set(on),xi=e=>e===rn||e===z,lu=new Set(["x","y","z"]),cu=on.filter(e=>!lu.has(e));function uu(e){const t=[];return cu.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Dt={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Qs(t,"x"),y:(e,{transform:t})=>Qs(t,"y")};Dt.translateX=Dt.x;Dt.translateY=Dt.y;const Vt=new Set;let er=!1,tr=!1,nr=!1;function ia(){if(tr){const e=Array.from(Vt).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=uu(s);r.length&&(n.set(s,r),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}tr=!1,er=!1,Vt.forEach(e=>e.complete(nr)),Vt.clear()}function oa(){Vt.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(tr=!0)})}function du(){nr=!0,oa(),ia(),nr=!1}class Ir{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(Vt.add(this),er||(er=!0,le.read(oa),le.resolveKeyframes(ia))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}su(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Vt.delete(this)}cancel(){this.state==="scheduled"&&(Vt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const fu=e=>e.startsWith("--");function hu(e,t,n){fu(t)?e.style.setProperty(t,n):e.style[t]=n}const mu=wr(()=>window.ScrollTimeline!==void 0),pu={};function gu(e,t){const n=wr(e);return()=>pu[t]??n()}const aa=gu(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Pn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,bi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Pn([0,.65,.55,1]),circOut:Pn([.55,0,1,.45]),backIn:Pn([.31,.01,.66,-.59]),backOut:Pn([.33,1.53,.69,.99])};function la(e,t){if(e)return typeof e=="function"?aa()?na(e,t):"ease-out":qo(e)?Pn(e):Array.isArray(e)?e.map(n=>la(n,t)||bi.easeOut):bi[e]}function yu(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:l}={},c=void 0){const d={[t]:n};l&&(d.offset=l);const f=la(a,r);Array.isArray(f)&&(d.easing=f);const m={delay:s,duration:r,easing:Array.isArray(f)?"linear":f,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return c&&(m.pseudoElement=c),e.animate(d,m)}function ca(e){return typeof e=="function"&&"applyToOptions"in e}function xu({type:e,...t}){return ca(e)&&aa()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class bu extends Dr{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:l}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,lt(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const c=xu(t);this.animation=yu(n,s,r,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Rr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):hu(n,s,d),this.animation.cancel()}l?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return Fe(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Fe(t)}get time(){return Fe(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=Ke(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&mu()?(this.animation.timeline=t,Be):n(this)}}const ua={anticipate:zo,backInOut:Uo,circInOut:Xo};function vu(e){return e in ua}function wu(e){typeof e.ease=="string"&&vu(e.ease)&&(e.ease=ua[e.ease])}const vi=10;class Su extends bu{constructor(t){wu(t),ra(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new Vr({...i,autoplay:!1}),l=Ke(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-vi).value,a.sample(l).value,vi),a.stop()}}const wi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(St.test(e)||e==="0")&&!e.startsWith("url("));function Tu(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function Cu(e,t,n,s){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],i=wi(r,t),a=wi(o,t);return sn(i===a,`You are trying to animate ${t} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:Tu(e)||(n==="spring"||ca(n))&&s}function sr(e){e.duration=0,e.type="keyframes"}const ju=new Set(["opacity","clipPath","filter","transform"]),Pu=wr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Au(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:c}=t.owner.getProps();return Pu()&&n&&ju.has(n)&&(n!=="transform"||!c)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Eu=40;class Mu extends Dr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:l,motionValue:c,element:d,...f}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=De.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:l,motionValue:c,element:d,...f},p=d?.KeyframeResolver||Ir;this.keyframeResolver=new p(a,(b,v,T)=>this.onKeyframesResolved(b,v,m,!T),l,c,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:l,isHandoff:c,onUpdate:d}=s;this.resolvedAt=De.now(),Cu(t,o,i,a)||((ct.instantAnimations||!l)&&d?.(Rr(t,s,n)),t[0]=t[t.length-1],sr(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Eu?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!c&&Au(m)?new Su({...m,element:m.motionValue.owner.current}):new Vr(m);p.finished.then(()=>this.notifyFinished()).catch(Be),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),du()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const ku=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Nu(e){const t=ku.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const Ru=4;function da(e,t,n=1){lt(n<=Ru,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=Nu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return Do(i)?parseFloat(i):i}return Ar(r)?da(r,t,n+1):r}function Or(e,t){return e?.[t]??e?.default??e}const fa=new Set(["width","height","top","left","right","bottom",...on]),Du={test:e=>e==="auto",parse:e=>e},ha=e=>t=>t.test(e),ma=[rn,z,et,vt,Tc,Sc,Du],Si=e=>ma.find(ha(e));function Vu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Io(e):!0}const Iu=new Set(["brightness","contrast","saturate","opacity"]);function Ou(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Er)||[];if(!s)return e;const r=n.replace(s,"");let o=Iu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const $u=/\b([a-z-]*)\(.*?\)/gu,rr={...St,getAnimatableNone:e=>{const t=e.match($u);return t?t.map(Ou).join(" "):e}},Ti={...rn,transform:Math.round},Lu={rotate:vt,rotateX:vt,rotateY:vt,rotateZ:vt,scale:Qn,scaleX:Qn,scaleY:Qn,scaleZ:Qn,skew:vt,skewX:vt,skewY:vt,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:Vn,originX:ui,originY:ui,originZ:z},$r={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...Lu,zIndex:Ti,fillOpacity:Vn,strokeOpacity:Vn,numOctaves:Ti},Fu={...$r,color:xe,backgroundColor:xe,outlineColor:xe,fill:xe,stroke:xe,borderColor:xe,borderTopColor:xe,borderRightColor:xe,borderBottomColor:xe,borderLeftColor:xe,filter:rr,WebkitFilter:rr},pa=e=>Fu[e];function ga(e,t){let n=pa(e);return n!==rr&&(n=St),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Bu=new Set(["auto","none","0"]);function Uu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Bu.has(o)&&In(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ga(n,r)}class zu extends Ir{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<t.length;l++){let c=t[l];if(typeof c=="string"&&(c=c.trim(),Ar(c))){const d=da(c,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!fa.has(s)||t.length!==2)return;const[r,o]=t,i=Si(r),a=Si(o);if(i!==a)if(xi(i)&&xi(a))for(let l=0;l<t.length;l++){const c=t[l];typeof c=="string"&&(t[l]=parseFloat(c))}else Dt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||Vu(t[r]))&&s.push(r);s.length&&Uu(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Dt[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=Dt[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,l])=>{t.getValue(a).set(l)}),this.resolveNoneKeyframes()}}function _u(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const r=n?.[e]??s.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const ya=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function xa(e){return Vo(e)&&"offsetHeight"in e}const Ci=30,Xu=e=>!isNaN(parseFloat(e));class Wu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=De.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=De.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Xu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&Tr(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new Sr);const s=this.events[t].add(n);return t==="change"?()=>{s(),le.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-s}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=De.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Ci)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Ci);return Oo(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function tn(e,t){return new Wu(e,t)}const{schedule:Lr}=Ko(queueMicrotask,!1),We={x:!1,y:!1};function ba(){return We.x||We.y}function qu(e){return e==="x"||e==="y"?We[e]?null:(We[e]=!0,()=>{We[e]=!1}):We.x||We.y?null:(We.x=We.y=!0,()=>{We.x=We.y=!1})}function va(e,t){const n=_u(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function ji(e){return!(e.pointerType==="touch"||ba())}function Ku(e,t,n={}){const[s,r,o]=va(e,n),i=a=>{if(!ji(a))return;const{target:l}=a,c=t(l,a);if(typeof c!="function"||!l)return;const d=f=>{ji(f)&&(c(f),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const wa=(e,t)=>t?e===t?!0:wa(e,t.parentElement):!1,Fr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Gu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Hu(e){return Gu.has(e.tagName)||e.tabIndex!==-1}const os=new WeakSet;function Pi(e){return t=>{t.key==="Enter"&&e(t)}}function Rs(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Yu=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Pi(()=>{if(os.has(n))return;Rs(n,"down");const r=Pi(()=>{Rs(n,"up")}),o=()=>Rs(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function Ai(e){return Fr(e)&&!ba()}function Ju(e,t,n={}){const[s,r,o]=va(e,n),i=a=>{const l=a.currentTarget;if(!Ai(a))return;os.add(l);const c=t(l,a),d=(p,b)=>{window.removeEventListener("pointerup",f),window.removeEventListener("pointercancel",m),os.has(l)&&os.delete(l),Ai(p)&&typeof c=="function"&&c(p,{success:b})},f=p=>{d(p,l===window||l===document||n.useGlobalTarget||wa(l,p.target))},m=p=>{d(p,!1)};window.addEventListener("pointerup",f,r),window.addEventListener("pointercancel",m,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),xa(a)&&(a.addEventListener("focus",c=>Yu(c,r)),!Hu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Sa(e){return Vo(e)&&"ownerSVGElement"in e}function Zu(e){return Sa(e)&&e.tagName==="svg"}const je=e=>!!(e&&e.getVelocity),Qu=[...ma,xe,St],ed=e=>Qu.find(ha(e)),Br=h.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Ei(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function td(...e){return t=>{let n=!1;const s=e.map(r=>{const o=Ei(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():Ei(e[r],null)}}}}function nd(...e){return qe.useCallback(td(...e),e)}class sd extends qe.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=xa(s)&&s.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function rd({children:e,isPresent:t,anchorX:n,root:s}){const r=h.useId(),o=h.useRef(null),i=h.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=h.useContext(Br),l=nd(o,e?.ref);return h.useInsertionEffect(()=>{const{width:c,height:d,top:f,left:m,right:p}=i.current;if(t||!o.current||!c||!d)return;const b=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const v=document.createElement("style");a&&(v.nonce=a);const T=s??document.head;return T.appendChild(v),v.sheet&&v.sheet.insertRule(`
|
|
1
|
+
"use strict";var wl=Object.create;var si=Object.defineProperty;var Sl=Object.getOwnPropertyDescriptor;var Tl=Object.getOwnPropertyNames;var jl=Object.getPrototypeOf,Cl=Object.prototype.hasOwnProperty;var Pl=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Tl(t))!Cl.call(e,r)&&r!==n&&si(e,r,{get:()=>t[r],enumerable:!(s=Sl(t,r))||s.enumerable});return e};var Al=(e,t,n)=>(n=e!=null?wl(jl(e)):{},Pl(t||!e||!e.__esModule?si(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),h=require("react"),se=require("lucide-react"),El=require("@ai-sdk/react"),ri=require("ai"),Co=require("@radix-ui/react-slot"),Po=require("class-variance-authority"),Ml=require("clsx"),kl=require("tailwind-merge"),Nl=require("@radix-ui/react-tooltip"),ii=require("@radix-ui/react-use-controllable-state"),Rl=require("@radix-ui/react-collapsible"),Dl=require("react-dom"),Vl=require("@radix-ui/react-dialog");function ps(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Ke=ps(h),Qt=ps(Nl),mr=ps(Rl),It=ps(Vl),Le=Symbol.for("@arcteninc/core:originalName");function Il(e,t){return e[Le]=t,e}function Ol(e,t,n,s){if(typeof e!="function")return null;const r=e[Le];if(r){const a=t[r];if(a&&!n.has(a.name))return{fn:e,meta:a}}const o=e.name;let i;if(o&&(i=t[o],i&&!n.has(i.name)))return e[Le]=i.name,{fn:e,meta:i};if(s&&s.length>0){for(const a of s)if(!n.has(a)&&(i=t[a],i))return e[Le]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[Le]=i.name,{fn:e,meta:i};return null}function pr(e,t){if(!t)return[];let n,s;if("functions"in t&&typeof t.functions=="object"){const o=t;n=o.functions,s=o.toolOrder}else n=t,s=void 0;const r=new Set;return e.map(o=>{const i=Ol(o,n,r,s);if(!i){const a=o.name,c=o[Le]||a||"unnamed";return typeof process<"u"&&(process.env.NODE_ENV==="development"||process.env.NODE_ENV!=="production")&&typeof console<"u"&&console.warn&&console.warn(`⚠️ [@arcteninc/core] No metadata found for tool "${c}". This tool will be excluded.
|
|
2
|
+
To fix: Run "arcten-extract-types ." and ensure "${c}" is used in ArctenAgent/useAgent.`),null}return r.add(i.meta.name),{name:i.meta.name,description:i.meta.description,jsonSchema:i.meta.parameters}}).filter(o=>o!==null)}const $l={password:[/^password$/i,/^pwd$/i,/^pass$/i,/^newPassword$/i,/^oldPassword$/i,/^currentPassword$/i,/^confirmPassword$/i,/.*password.*/i],email:[/^email$/i,/^emailAddress$/i,/^mail$/i,/.*email.*/i],phone:[/^phone$/i,/^phoneNumber$/i,/^mobile$/i,/^cell$/i,/^cellPhone$/i,/^telephone$/i,/.*phone.*/i,/.*mobile.*/i],pin:[/^pin$/i,/^pinCode$/i,/^securityPin$/i,/^accessPin$/i,/.*pin$/i],ssn:[/^ssn$/i,/^socialSecurityNumber$/i,/^social$/i,/.*ssn.*/i,/.*social.*/i],creditCard:[/^creditCard$/i,/^cardNumber$/i,/^card$/i,/^ccNumber$/i,/^creditCardNumber$/i,/.*card.*/i,/^cvv$/i,/^cvc$/i,/^cvn$/i,/^securityCode$/i],text:[]};function Cn(e){for(const[t,n]of Object.entries($l))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function Ll(e,t){return{password:{title:"Password Required",description:"Please enter your password to continue",placeholder:"Enter password..."},email:{title:"Email Required",description:"Please enter your email address",placeholder:"Enter email address..."},phone:{title:"Phone Number Required",description:"Please enter your phone number",placeholder:"Enter phone number..."},pin:{title:"PIN Required",description:"Please enter your PIN",placeholder:"Enter PIN..."},ssn:{title:"Social Security Number Required",description:"Please enter your Social Security Number",placeholder:"XXX-XX-XXXX"},creditCard:{title:"Credit Card Required",description:"Please enter your credit card information",placeholder:"XXXX XXXX XXXX XXXX"},text:{title:"Secure Input Required",description:`Please enter your ${t}`,placeholder:`Enter ${t}...`}}[e]}function Fl(e,t,n){return t.length>0}function Bl(e,t,n,s={}){const r=[];return Object.keys(s).forEach(i=>{const a=i in n,l=n[i];if(!a){const f=s[i];if(f!=null&&f!=="")return}const c=Ul(s[i]),d={name:i,type:zl(l||Cn(i)||"text"),label:Ao(i),placeholder:_l(i,l),required:!0,value:c};d.type==="password"&&(d.validation=f=>f.length<8?"Password must be at least 8 characters":null),r.push(d)}),r.sort((i,a)=>{const l=i.name in n,c=a.name in n;return l===c?0:l?1:-1}),{shouldUseForm:Fl(e,t),fields:r,title:Xl(e),description:Wl(e,r.length)}}function Ul(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function zl(e){switch(e){case"password":return"password";case"email":return"email";case"phone":return"phone";case"pin":return"pin";case"ssn":return"ssn";case"creditCard":return"creditCard";default:return"text"}}function Ao(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function _l(e,t){return t?Ll(t,e).placeholder:`Enter ${Ao(e).toLowerCase()}...`}function Xl(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Wl(e,t){const n=e.toLowerCase();return t<=2?`Please provide the required information to ${n}.`:`Please fill out the form below to ${n}. Required fields are marked with *.`}function An(e){if(typeof e=="string")try{const t=JSON.parse(e);return An(t)}catch{return e}if(Array.isArray(e))return e.map(An);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=An(s);return t}return e}function ql(e,t){if(!t||Object.keys(t).length===0)return e;const n={...e};return Object.keys(t).forEach(s=>{s in n&&delete n[s]}),n}function Kl(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return An(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?An(e):{}}const ss="__secureOutput",rs="[hidden for privacy]";function Gl(e,t){if(!e||e.length===0)return t;const n=new Map;t.forEach(o=>{const i=o[Le]||o.name;i&&n.set(i,o)});const s=new Map(e.map(o=>[o.name,o])),r=[];return e.forEach(o=>{const i=n.get(o.name);if(!i){console.log(`[useAgent] Skipping server-only tool: ${o.name}`);return}if(!o.isEnabled&&!o.isOverridable){console.log(`[useAgent] Blocking non-overridable disabled tool: ${o.name}`);return}if(!o.isEnabled&&o.isOverridable&&i){console.log(`[useAgent] Allowing overridable disabled tool with local implementation: ${o.name}`),r.push(i);return}o.isEnabled&&i&&r.push(i)}),t.forEach(o=>{const i=o[Le]||o.name;i&&!s.has(i)&&(console.log(`[useAgent] Allowing client-only tool (forward compatible): ${i}`),r.push(o))}),r}function Hl(e){if(typeof globalThis.structuredClone=="function")return globalThis.structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch(t){return console.warn("[useAgent] Failed to clone value for redaction:",t),e}}function Yl(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function Jl(e,t){if(t.length===0)return e;if(!e||typeof e!="object")return;let n=e;for(const s of t){if(!n||typeof n!="object")return;n=n[s]}return n}function Zl(e,t,n){if(!e||typeof e!="object"||t.length===0)return!1;let s=e;for(let o=0;o<t.length-1;o++){if(!s||typeof s!="object")return!1;const i=s,a=t[o];if(a===void 0)return!1;const l=i[a];if(l==null||typeof l!="object")return!1;s=l}if(!s)return!1;const r=t[t.length-1];return!r||!(r in s)?!1:(s[r]=n,!0)}function Xs(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Eo(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=Xs(r),r&&typeof r=="object"&&Object.assign(n,Eo(r,o))}):t&&(n[t]=Xs(e)),n}function Ql(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:rs,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:rs,includeFieldStatus:!1,preserve:[]};const t=e.strategy??(e.fields&&e.fields.length>0?"fields":"full");return{strategy:t,fields:t==="fields"?e.fields??[]:[],placeholder:e.placeholder??rs,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function ec(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=Ql(s);r&&(t[n]=r)}return t}function Mo(e,t,n){const s=n.placeholder,r={tool:e,redacted:!0,strategy:n.strategy,placeholder:s};if(n.strategy==="full"){n.includeFieldStatus&&typeof t=="object"&&t!==null&&(r.fieldStatus=Eo(t)),r.redactedFields=["*"];let l={};return n.preserve.length>0&&t&&typeof t=="object"&&n.preserve.forEach(c=>{c in t&&(l[c]=t[c])}),l[ss]=r,l}if(n.fields.includes("*"))return Mo(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[ss]:{...r,redactedFields:n.fields}};const o=Hl(t),i=[],a={};return n.fields.forEach(l=>{const c=Yl(l);if(c.length===0)return;const d=Jl(o,c),f=Xs(d);a[l]=f,Zl(o,c,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[ss]=r,o}function ko({apiBaseUrl:e="https://api.arcten.com",tokenEndpoint:t="/api/arcten/token",clientToken:n,skipTokenFetch:s=!1,user:r,tools:o=[],safeTools:i=[],safeToolNames:a,toolMetadata:l,sensitiveParams:c,sensitiveOutputs:d,autoDetectSensitive:f=!1,autoFormGeneration:m=!1,formMode:p="auto",systemPrompt:b="",agentId:v,agentName:T,projectId:w,enableRemoteConfig:M,remoteConfigUrl:E,initialMessages:$=[],conversationId:D,state:I,onStateChange:k,allowStateEdits:C=!0,onToolCall:V,onFinish:A,sources:N,ragConfig:L,ragFilters:O,secureInputHandler:F}={}){const _=e.replace(/\/+$/,""),[G,K]=h.useState(null),[ae,ve]=h.useState(!1),[He,jt]=h.useState(null),et=h.useMemo(()=>{const g=N||[],y=G?.config?.sources||[];return[...new Set([...g,...y])]},[N,G]),H=h.useMemo(()=>L!==void 0?L:O?{enabled:!0,filters:O}:et&&et.length>0?{enabled:!0,organizationId:et[0],autoExecute:!0,filters:void 0}:{enabled:!1},[et,L,O]),Ot=h.useMemo(()=>M===!1?!1:!!w,[w,M]);h.useEffect(()=>{if(!Ot||!le.current)return;(async()=>{ve(!0),jt(null);try{const x=`${E||_.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,S=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${le.current}`},body:JSON.stringify({path:"agents:getConfigForClient",args:{projectId:w,agentName:T,agentId:v},format:"json"})});if(!S.ok){if(S.status===404){console.warn("[useAgent] Remote config endpoint not found (404), using local tools only"),K(null);return}const R=await S.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch remote config: ${S.status} ${R}`)}const P=await S.json();K(P?.value||null),console.log("[useAgent] Remote config loaded successfully:",P?.value)}catch(y){console.error("[useAgent] Failed to fetch remote config:",y);const x=y instanceof Error?y:new Error(String(y));jt(x),K(null)}finally{ve(!1)}})()},[Ot,w,T,v,_,E]);const Me=h.useMemo(()=>{const g={};if(c)for(const[y,x]of Object.entries(c))if(g[y]={},Array.isArray(x))for(const S of x){const P=Cn(S);g[y][S]=P||"text"}else for(const[S,P]of Object.entries(x))g[y][S]=P;if(l){for(const[y,x]of Object.entries(l))if(x&&typeof x=="object"&&"sensitiveParams"in x){g[y]||(g[y]={});const S=x.sensitiveParams;if(Array.isArray(S))for(const P of S){const R=Cn(P);g[y][P]=R||"text"}else if(S&&typeof S=="object")for(const[P,R]of Object.entries(S))g[y][P]=R}}return g},[c,l,f]),Ct=h.useMemo(()=>ec(d),[d]),Pe=h.useCallback((g,y)=>{const x=Ct[g];if(!x)return y;try{return Mo(g,y,x)}catch(S){return console.error(`[useAgent] Failed to redact output for ${g}:`,S),{value:rs,[ss]:{tool:g,redacted:!0,error:String(S)}}}},[Ct]),[Ue,$t]=h.useState(n||null),le=h.useRef(n||null),[pn,ct]=h.useState(null),[ut,gn]=h.useState(null),ze=h.useRef(null),[Pt,At]=h.useState([]),[Ve,yn]=h.useState(D||(typeof window<"u"?crypto.randomUUID():null)),[vs,Lt]=h.useState(!1),Ft=h.useRef(new Set),dt=h.useRef(new Set),Ie=h.useRef(new Set),[Qr,_n]=h.useState(new Map),[Ye,Xn]=h.useState(new Map),[ws,Bt]=h.useState(new Map),[xn,Ut]=h.useState(new Map),ue=I!==void 0,[ft,tt]=h.useState({}),pe=h.useRef({}),_e=ue?I||{}:ft;ue&&I?pe.current=I:ue||(pe.current=ft);const[bn,ht]=h.useState(!1),[Wn,vn]=h.useState(null),ke=h.useRef(!1),wn=h.useCallback(async(g,y=3)=>{if(!Ve||!le.current)return;const x=async()=>{const P=`${_.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,R=await fetch(P,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${le.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:Ve,updates:g},format:"json"})});if(!R.ok){if(R.status===404)return;const B=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${R.status} ${B}`)}};for(let S=0;S<y;S++)try{await x(),vn(null);return}catch(P){if(S===y-1){const B=P instanceof Error?P:new Error(String(P));throw vn(B),console.error("Failed to sync state to Convex after retries:",P),B}await new Promise(B=>setTimeout(B,Math.pow(2,S)*100))}},[Ve,_,le]),we=h.useMemo(()=>function(){return pe.current},[]),nt=h.useMemo(()=>async function(y){const x={...pe.current,...y};pe.current=x,ue||tt(x),k&&k(x);try{await wn(y)}catch(S){throw S}},[wn,k,ue]);h.useEffect(()=>{ue&&I&&(pe.current=I)},[ue,I]);const zt=h.useCallback(g=>F?F.showSecureModal(g):new Promise(y=>{_n(x=>new Map(x).set(g.id,g)),Xn(x=>new Map(x).set(g.id,y))}),[F]),st=h.useCallback((g,y)=>{if(F)return;const x=Ye.get(g);x&&(x(y),_n(S=>{const P=new Map(S);return P.delete(g),P}),Xn(S=>{const P=new Map(S);return P.delete(g),P}))},[Ye,F]),ei=h.useCallback(g=>F?F.showSecureForm(g):new Promise(y=>{Bt(x=>new Map(x).set(g.id,g)),Ut(x=>new Map(x).set(g.id,y))}),[F]),Ss=h.useCallback((g,y)=>{if(F)return;const x=xn.get(g);x&&(x(y),Bt(S=>{const P=new Map(S);return P.delete(g),P}),Ut(S=>{const P=new Map(S);return P.delete(g),P}))},[xn,F]),_t=h.useCallback((g,y)=>{const x=Me[g]||{},S=Object.keys(x).length>0;if(f){const P=Object.keys(y).filter(R=>Cn(R)!==null);return S||P.length>0}return S},[Me,f]),Sn=h.useCallback((g,y)=>{const S={...Me[g]||{}};if(f){for(const R of Object.keys(y))if(!(R in S)){const B=Cn(R);B&&(S[R]=B)}}const P=Object.entries(S).filter(([R])=>Object.prototype.hasOwnProperty.call(y,R));return P.length>0?Object.fromEntries(P):S},[Me,f]),mt=h.useMemo(()=>H?.enabled?async function(y,x=20,S){const P={...H.filters,...S};if(N&&N.length>1){const B=N.map(Q=>fetch(`${_}/search`,{method:"POST",headers:{"Content-Type":"application/json",...le.current?{Authorization:`Bearer ${le.current}`}:{}},body:JSON.stringify({q:y,k:Math.min(x,100),organizationId:Q,...Object.keys(P).length>0?{filters:P}:{}})}).then(ne=>ne.ok?ne.json():null)),Z=await Promise.all(B),q=[];for(const Q of Z)Q?.candidates&&q.push(...Q.candidates);q.sort((Q,ne)=>{const fe=Q.scores?.rerank||Q.scores?.dense||0;return(ne.scores?.rerank||ne.scores?.dense||0)-fe});const de=q.slice(0,x).map((Q,ne)=>{const fe=Q.citation||Q.url;return{rank:ne+1,doc_id:Q.doc_id,block_id:Q.block_id,url:Q.url,citation:fe,title:Q.title||"Untitled",snippet:Q.snippet,score:Q.scores?.rerank||Q.scores?.dense||0,metadata:{site:Q.metadata?.site,lang:Q.metadata?.lang,contentType:Q.metadata?.content_type}}});return{success:!0,query:y,total:q.length,results:de,summary:`Found ${q.length} relevant results across ${N.length} source(s) for "${y}". Top result: ${de[0]?.title||"N/A"}`}}const R=H.organizationId&&H.organizationId!=="default"?H.organizationId:N&&N.length>0?N[0]:void 0;try{const B={q:y,k:Math.min(x,100)};R&&(B.organizationId=R),Object.keys(P).length>0&&(B.filters=P);const Z={"Content-Type":"application/json"};le.current&&(Z.Authorization=`Bearer ${le.current}`);const q=await fetch(`${_}/search`,{method:"POST",headers:Z,body:JSON.stringify(B)});if(!q.ok){const ne=await q.text();return{success:!1,error:`Search failed: ${q.status} ${ne}`}}const de=await q.json(),Q=de.candidates.map((ne,fe)=>{const qt=ne.citation||ne.url;return{rank:fe+1,doc_id:ne.doc_id,block_id:ne.block_id,url:ne.url,citation:qt,title:ne.title||"Untitled",snippet:ne.snippet,score:ne.scores?.rerank||ne.scores?.dense||0,metadata:{site:ne.metadata?.site,lang:ne.metadata?.lang,contentType:ne.metadata?.content_type}}});return{success:!0,query:de.query,total:de.total,results:Q,summary:`Found ${de.total} relevant results for "${y}". Top result: ${Q[0]?.title||"N/A"}`}}catch(B){return{success:!1,error:B instanceof Error?B.message:"Unknown error occurred"}}}:null,[H,_,le]),rt=h.useMemo(()=>H?.enabled?async function(y,x){const S=H.organizationId&&H.organizationId!=="default"?H.organizationId:N&&N.length>0?N[0]:void 0;try{const P={"Content-Type":"application/json"};le.current&&(P.Authorization=`Bearer ${le.current}`);const R=await fetch(`${_}/fetch`,{method:"POST",headers:P,body:JSON.stringify({doc_id:y,block_ids:x,...S?{organizationId:S}:{}})});if(!R.ok){const Z=await R.text();return{success:!1,error:`Fetch failed: ${R.status} ${Z}`}}const B=await R.json();return{success:!0,blocks:B.blocks||[],fullContent:B.fullContent||"",pageUrl:B.pageUrl||"",pageTitle:B.pageTitle||"",summary:`Fetched ${B.blocks?.length||0} blocks from ${B.pageTitle||y}`}}catch(P){return{success:!1,error:P instanceof Error?P.message:"Unknown error occurred"}}}:null,[H,_,le]),Xt=h.useMemo(()=>{if(G&&G.config?.tools){const g=Gl(G.config.tools,o);return console.log("[useAgent] Merged remote config:",{remoteToolCount:G.config.tools.length,localToolCount:o.length,mergedToolCount:g.length}),g}return o},[G,o]),Xe=G?.enableStateTools??!0,Je=G?.enableRagTools??H?.enabled??!1,qn=h.useMemo(()=>{const g=[...Xt,...i];return Xe&&(g.push(we),(!ue||C)&&g.push(nt)),Je&&(mt&&g.push(mt),rt&&g.push(rt)),g},[Xt,i,we,nt,mt,rt,Xe,Je,ue,C]),Kn=h.useMemo(()=>[...Xt,...i],[Xt,i]),it=h.useMemo(()=>pr(Kn,l),[Kn,l]),pt=h.useMemo(()=>{const g=new Map,y=new Map(it.map(x=>[x.name,x]));return g.set("getState",we),(!ue||C)&&g.set("setState",nt),H?.enabled&&(mt&&g.set("searchDocs",mt),rt&&g.set("fetchDocContent",rt)),qn.forEach(x=>{if(x===we||x===nt||x===mt||x===rt)return;const S=x[Le];if(S){const R=y.get(S);if(R){g.set(R.name,x);return}}const P=it.find(R=>R.name===x.name);P&&g.set(P.name,x)}),g},[qn,it,we,nt,mt,rt,H,ue,C]),Gn=h.useMemo(()=>new Set(it.map(g=>g.name)),[it]),Hn=h.useMemo(()=>{const g=[];Xe&&(g.push({name:"getState",description:"Get the current agent state. Returns IDs, workflow state, checklists, and other persistent data.",jsonSchema:{type:"object",properties:{},required:[]}}),(!ue||C)&&g.push({name:"setState",description:"Update the agent state. Store IDs, workflow state, checklists, context, and other data that must persist across conversations. Merges with existing state.",jsonSchema:{type:"object",properties:{updates:{type:"object",description:"Partial state updates to merge with existing state"}},required:["updates"]}}));const y=[];Je&&y.push({name:"searchDocs",description:"Search documentation using semantic search. Returns relevant results with snippets and scores. Use this first to find relevant documentation. Default returns 20 results - use higher k values (30-50) when you need to find many sources.",jsonSchema:{type:"object",properties:{query:{type:"string",description:"The search query (user's question or keywords)"},k:{type:"number",description:"Number of results to return (default: 20, max: 100). Use 20-30 for comprehensive searches, or higher (50-100) when you need to find all relevant sources.",default:20},filters:{type:"object",description:"Optional filters to scope the search",properties:{site:{type:"string"},lang:{type:"string"},tags:{type:"array",items:{type:"string"}},docIds:{type:"array",items:{type:"string"}},pageIds:{type:"array",items:{type:"string"}}}}},required:["query"]}},{name:"fetchDocContent",description:"Fetch full content of documentation blocks after searching. Use this AFTER searchDocs when you find relevant results (scores > 0.3) to get complete text. Automatically fetches nearby blocks (5 chunks before/after each requested block) for context. You can pass multiple block_ids to fetch comprehensive content from multiple blocks/pages.",jsonSchema:{type:"object",properties:{doc_id:{type:"string",description:"The doc_id from searchDocs results"},block_ids:{type:"array",items:{type:"string"},description:"Array of block_ids from searchDocs results. You can pass multiple block_ids to fetch comprehensive content."}},required:["doc_id","block_ids"]}});const x=[];return G?.config?.workflows&&G.config.workflows.forEach(S=>{const P={},R=[];S.parameters&&S.parameters.forEach(B=>{P[B.name]={type:B.type||"string",description:B.description},B.required&&R.push(B.name)}),x.push({name:`workflow_${S.name.replace(/\s+/g,"_").toLowerCase()}`,description:S.description||`Execute the "${S.name}" workflow. ${S.contentPlaintext?.slice(0,200)||""}`,jsonSchema:{type:"object",properties:P,required:R},_workflow:S})}),[...it,...g,...y,...x]},[it,Xe,Je,ue,C,G]),gt=h.useMemo(()=>Hn.filter(g=>g.name==="getState"?Xe:g.name==="setState"?Xe&&(!ue||C):g.name==="searchDocs"||g.name==="fetchDocContent"?Je:g.name.startsWith("workflow_")?!0:Gn.has(g.name)),[Hn,Gn,Xe,Je,ue,C]),Wt=h.useMemo(()=>{const g=new Set;return Xe&&(g.add("getState"),g.add("setState")),Je&&H?.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent")),G?.config?.tools?G.config.tools.forEach(y=>{y.isEnabled&&!y.requiresApproval&&g.add(y.name)}):(i.forEach(y=>{for(const[x,S]of pt.entries())if(S===y){g.add(x);break}}),a&&Array.isArray(a)&&a.forEach(y=>{typeof y=="string"&&g.add(y)})),G?.config?.workflows&&G.config.workflows.forEach(y=>{const x=`workflow_${y.name.replace(/\s+/g,"_").toLowerCase()}`;y.requiresApproval||g.add(x)}),g},[G,i,a,pt,Xe,Je,H]);h.useEffect(()=>{if(s||n)return;let g=!1,y=null;const x=async(S=1,P=3)=>{if(!g)try{const R=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!R.ok)throw new Error("Failed to fetch token");const B=await R.json();g||($t(B.clientToken),le.current=B.clientToken,gn(B.expiresAt),ct(null))}catch(R){if(console.error(`[useAgent] Token fetch failed (attempt ${S}/${P}):`,R),S<P&&!g){const B=Math.pow(2,S-1)*1e3;y=setTimeout(()=>x(S+1,P),B)}else g||ct(R instanceof Error?R.message:"Failed to fetch token")}};return x(),()=>{g=!0,y&&clearTimeout(y),ze.current&&clearTimeout(ze.current)}},[t,JSON.stringify(r),s,n]),h.useEffect(()=>{if(!ut||s||n)return;ze.current&&clearTimeout(ze.current);const g=async(R=1,B=3)=>{try{const Z=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!Z.ok)throw new Error("Failed to refresh token");const q=await Z.json();$t(q.clientToken),le.current=q.clientToken,gn(q.expiresAt),ct(null)}catch(Z){if(console.error(`[useAgent] Token refresh failed (attempt ${R}/${B}):`,Z),R<B){const q=Math.pow(2,R-1)*1e3;setTimeout(()=>g(R+1,B),q)}else ct(Z instanceof Error?Z.message:"Failed to refresh token")}},y=Math.floor(Date.now()/1e3),x=ut-y,P=Math.max(0,x-5);return ze.current=setTimeout(()=>g(),P*1e3),()=>{ze.current&&clearTimeout(ze.current)}},[ut,t,JSON.stringify(r),s,n]),h.useEffect(()=>{if(s||n)return;const g=async()=>{if(document.visibilityState!=="visible")return;const y=Math.floor(Date.now()/1e3);if(!ut||ut<=y+5){console.log("[useAgent] Tab visible, token expired - refreshing");try{const S=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(S.ok){const P=await S.json();$t(P.clientToken),le.current=P.clientToken,gn(P.expiresAt),ct(null)}}catch(S){console.error("[useAgent] Token refresh on visibility change failed:",S)}}};return document.addEventListener("visibilitychange",g),()=>document.removeEventListener("visibilitychange",g)},[t,JSON.stringify(r),ut,s,n]);const Yn=async(g,y={})=>{const x=y.headers?new Headers(y.headers):new Headers;return x.delete("user-agent"),x.delete("User-Agent"),fetch(g,{...y,headers:x})},Tn=h.useRef(null),j=`${_}/chat`,{messages:U,sendMessage:X,status:J,error:Y,stop:ee,addToolResult:Ne,setMessages:re}=El.useChat({id:Ve||void 0,messages:$,transport:new ri.DefaultChatTransport({api:j,fetch:Yn,headers:()=>{const g={};return le.current&&(g.Authorization=`Bearer ${le.current}`),g},body:()=>({tools:gt.map(y=>({name:y.name,description:y.description,inputSchema:y.jsonSchema})),...v&&{agentId:v},...T&&{agentName:T},state:pe.current,...O&&{ragFilters:O}})}),sendAutomaticallyWhen:g=>{const y=g.messages;if(y[y.length-1]?.role!=="assistant")return!1;const P=[...y].reverse().find(B=>B.role==="user")?.id;if(P&&Tn.current===P)return!1;const R=ri.lastAssistantMessageIsCompleteWithToolCalls(g);return R&&P&&(Tn.current=P),R}}),Se=X,W=h.useCallback(g=>(Tn.current=null,Ie.current=new Set,Se(g)),[Se]),te=h.useCallback((g,y,x)=>{const S=Pe(g,x);Ne({toolCallId:y,tool:g,output:S})},[Ne,Pe]);h.useEffect(()=>{U.forEach(g=>{g.role==="assistant"&&g.parts.forEach(y=>{if(!y.type?.startsWith("tool-")||y.state!=="input-available")return;const x=y.type.replace("tool-",""),S=y.toolCallId;if(Ft.current.has(S)||dt.current.has(S)){console.log(`[useAgent] Skipping ${x} (${S}) - already processing or completed`);return}console.log(`[useAgent] Starting ${x} (${S})`),Ft.current.add(S);const P=Z=>{console.log(`[useAgent] Completed ${x} (${Z})`),dt.current.add(Z),Ft.current.delete(Z)},R=Kl(y.input),B=`${x}:${JSON.stringify(R)}`;if(Ie.current.has(B)){console.log(`[useAgent] Skipping duplicate tool call: ${B}`),te(x,S,"This tool was already called successfully with the same arguments in this response. Using previous result."),P(S);return}if(_t(x,R)){const Z=Sn(x,R),q=Object.entries(Z).filter(([fe])=>R[fe]!==void 0),de=q.length>0?Object.fromEntries(q):Z,Q=Object.keys(R),ne=ql(R,de);(async()=>{try{const fe=Bl(x,Q,de,R),qt={id:`${S}-form`,toolName:x,toolCallId:S,title:fe.title,description:fe.description,fields:fe.fields},Jn=await ei(qt);if(Jn===null){te(x,S,"User cancelled secure input"),P(S);return}const ti={...ne,...Jn},Ts=pt.get(x);if(!Ts)throw new Error(`Tool ${x} not found`);let js;const Cs=gt.find(ni=>ni.name===x);if(Cs&&Cs.jsonSchema?.properties){const bl=Object.keys(Cs.jsonSchema.properties).map(vl=>ti[vl]);js=await Ts(...bl)}else js=await Ts(...Object.values(ti));P(S),te(x,S,js),Ie.current.add(B)}catch(fe){console.error(`[useAgent] Error executing tool with secure input ${x}:`,fe),P(S),te(x,S,`Error: ${fe}`)}})();return}if(x.startsWith("workflow_")&&Wt.has(x)){(async()=>{try{const q=gt.find(Q=>Q.name===x)?._workflow;if(!q)throw new Error(`Workflow metadata not found for ${x}`);let de;if(q.webhook?.url){let Q=R;if(q.webhook.bodyTemplate){let fe=q.webhook.bodyTemplate;Object.entries(R).forEach(([qt,Jn])=>{fe=fe.replace(new RegExp(`\\{\\{${qt}\\}\\}`,"g"),String(Jn))}),Q=JSON.parse(fe)}const ne=await fetch(q.webhook.url,{method:q.webhook.method||"POST",headers:{"Content-Type":"application/json",...q.webhook.headers||{}},body:JSON.stringify(Q)});if(ne.ok)de={success:!0,data:await ne.json().catch(()=>({success:!0}))};else{const fe=await ne.text();de={success:!1,error:`Webhook failed: ${ne.status} ${fe}`}}}else de={success:!0,message:`Workflow "${q.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:q.contentPlaintext};P(S),te(x,S,de),Ie.current.add(B)}catch(Z){console.error(`[useAgent] Error executing workflow ${x}:`,Z),P(S),te(x,S,`Error: ${Z}`)}})();return}if(Wt.has(x)&&!_t(x,R)){const Z=pt.get(x);Z?(async()=>{try{const q=gt.find(Q=>Q.name===x);let de;if(q&&q.jsonSchema?.properties){const ne=Object.keys(q.jsonSchema.properties).map(fe=>R[fe]);de=await Z(...ne)}else if(x==="getState")de=Z();else if(x==="setState"){const Q=R.updates||R;de=await Z(Q)}else de=await Z(...Object.values(R));P(S),te(x,S,de),Ie.current.add(B)}catch(q){console.error(`[useAgent] Error executing tool ${x}:`,q),P(S),te(x,S,`Error: ${q}`)}})():(console.warn(`[useAgent] Tool ${x} not found in toolsMap`),te(x,S,`Error: Tool "${x}" not found. The tool may not be registered or available.`),P(S))}else x.startsWith("workflow_")&&V?V({toolCall:{toolCallId:S,toolName:x,args:R}}):V?V({toolCall:{toolCallId:S,toolName:x,args:R}}):(console.warn(`[useAgent] No handler for tool ${x} - tool is not safe and no onToolCall callback provided`),te(x,S,`Error: Tool "${x}" cannot be executed. No handler is available for this tool.`),P(S))})})},[U,Wt,pt,V,te,nt,gt,_t,Sn,zt]),h.useEffect(()=>{if(J==="ready"&&U.length>0&&A){const g=U[U.length-1];g&&g.role==="assistant"&&A({message:g,messages:U,isAbort:!1,isDisconnect:!1,isError:!!Y})}},[J,U,Y,A]);async function ie(){if(!(!r?.id||!Ue)){Lt(!0);try{const y=await(await fetch(`${_}/conversations`,{headers:{Authorization:`Bearer ${Ue}`}})).json();At(y.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{Lt(!1)}}}h.useEffect(()=>{r?.id&&Ue&&ie()},[JSON.stringify(r),Ue,_]),h.useEffect(()=>{if(!Ve||!le.current)return;(async()=>{ht(!0),vn(null);try{const y=await fetch(`${_.replace("/chat","")}/convex/api/query`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${le.current}`},body:JSON.stringify({path:"conversations:getStateByChatId",args:{chatId:Ve},format:"json"})});if(!y.ok){const P=await y.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${y.status} ${P}`)}const S=(await y.json())?.value||{};pe.current=S,ue||tt(S),k&&k(S),ke.current=!0}catch(y){console.error("Failed to fetch state:",y);const x=y instanceof Error?y:new Error(String(y));vn(x),ke.current||(pe.current={},ue?k&&k({}):(tt({}),k&&k({})),ke.current=!0)}finally{ht(!1)}})()},[Ve,_,ue,k]);async function Ae(g){yn(g),Lt(!0);try{const y=await fetch(`${_}/conversations/${g}/messages`,{headers:{Authorization:`Bearer ${le.current}`}});if(!y.ok)throw new Error(`Failed to fetch messages: ${y.statusText}`);const S=(await y.json()).messages||[];re(S)}catch(y){console.error("Failed to load conversation messages:",y)}finally{Lt(!1)}}async function ge(g){if(Ue)try{await fetch(`${_}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${Ue}`}}),At(Pt.filter(y=>y._id!==g)),g===Ve&&We()}catch(y){console.error("Failed to delete conversation:",y)}}function We(){const g=crypto.randomUUID();yn(g),re([]),Ft.current=new Set,dt.current=new Set,pe.current={},ue?k&&k({}):(tt({}),k&&k({})),ke.current=!1}function be(g){const y=g.tool||"unknown-tool",x=Pe(y,g.output);Ne({toolCallId:g.toolCallId,tool:y,output:x})}async function Re(g,y,x){if(!y.startsWith("workflow_"))throw new Error(`${y} is not a workflow tool`);try{const P=gt.find(B=>B.name===y)?._workflow;if(!P)throw new Error(`Workflow metadata not found for ${y}`);let R;if(P.webhook?.url){let B=x;if(P.webhook.bodyTemplate){let q=P.webhook.bodyTemplate;Object.entries(x).forEach(([de,Q])=>{q=q.replace(new RegExp(`\\{\\{${de}\\}\\}`,"g"),String(Q))}),B=JSON.parse(q)}const Z=await fetch(P.webhook.url,{method:P.webhook.method||"POST",headers:{"Content-Type":"application/json",...P.webhook.headers||{}},body:JSON.stringify(B)});if(Z.ok)R={success:!0,data:await Z.json().catch(()=>({success:!0}))};else{const q=await Z.text();R={success:!1,error:`Webhook failed: ${Z.status} ${q}`}}}else R={success:!0,message:`Workflow "${P.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:P.contentPlaintext};return be({toolCallId:g,tool:y,output:R}),R}catch(S){const P={success:!1,error:String(S)};throw be({toolCallId:g,tool:y,output:P}),S}}async function Ze(g){const y={...pe.current,...g};pe.current=y,ue||tt(y),k&&k(y);try{await wn(g)}catch(x){throw x}}return{id:Ve,messages:U,status:J,error:Y,sendMessage:W,stop:ee,addToolOutput:be,executeWorkflowTool:Re,setMessages:re,conversations:Pt,loadConversation:Ae,deleteConversation:ge,startNewConversation:We,isLoadingConversations:vs,clientToken:Ue,tokenError:pn,state:_e,setState:Ze,isStateLoading:bn,stateError:Wn,pendingSecureInputs:Array.from(Qr.values()),completeSecureInput:st,pendingSecureForms:Array.from(ws.values()),completeSecureForm:Ss,safeToolNames:Wt}}function oe(...e){return kl.twMerge(Ml.clsx(e))}const Mt=Po.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive active:scale-95",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}}),Ce=Ke.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?Co.Slot:"button";return u.jsx(i,{ref:o,"data-slot":"button",className:oe(Mt({variant:t,size:n,className:e})),...r})});Ce.displayName="Button";const tc=Po.cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function Ps({className:e,variant:t,asChild:n=!1,...s}){const r=n?Co.Slot:"span";return u.jsx(r,{"data-slot":"badge",className:oe(tc({variant:t}),e),...s})}const nc=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=Ke.useState(!0);Ke.useEffect(()=>{const a=e.current;if(a){r&&(a.style.minHeight=`${s+6}px`,n>s&&(a.style.maxHeight=`${n}px`),o(!1)),a.style.height=`${s+6}px`;const l=a.scrollHeight;l>n?a.style.height=`${n}px`:a.style.height=`${l+6}px`}},[e.current,t])},No=Ke.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=Ke.useRef(null),[l,c]=Ke.useState("");return nc({textAreaRef:a,triggerAutoSize:l,maxHeight:e,minHeight:t}),h.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),Ke.useEffect(()=>{c(r)},[o?.defaultValue,r]),u.jsx("textarea",{...o,value:r,ref:a,className:oe("flex 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 disabled:cursor-not-allowed disabled:opacity-50",n),onChange:d=>{c(d.target.value),s?.(d)}})});No.displayName="AutosizeTextarea";function sc({delayDuration:e=0,...t}){return u.jsx(Qt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function yt({...e}){return u.jsx(sc,{children:u.jsx(Qt.Root,{"data-slot":"tooltip",...e})})}function xt({...e}){return u.jsx(Qt.Trigger,{"data-slot":"tooltip-trigger",...e})}function bt({className:e,sideOffset:t=0,children:n,...s}){return u.jsx(Qt.Portal,{children:u.jsxs(Qt.Content,{"data-slot":"tooltip-content",sideOffset:t,className:oe("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...s,children:[n,u.jsx(Qt.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function oi({className:e,...t}){return u.jsx("kbd",{"data-slot":"kbd",className:oe("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}const gr=h.createContext({});function yr(e){const t=h.useRef(null);return t.current===null&&(t.current=e()),t.current}const xr=typeof window<"u",Ro=xr?h.useLayoutEffect:h.useEffect,gs=h.createContext(null);function br(e,t){e.indexOf(t)===-1&&e.push(t)}function vr(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const ot=(e,t,n)=>n>t?t:n<e?e:n;function Ws(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let sn=()=>{},at=()=>{};process.env.NODE_ENV!=="production"&&(sn=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Ws(t,n))},at=(e,t,n)=>{if(!e)throw new Error(Ws(t,n))});const lt={},Do=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Vo(e){return typeof e=="object"&&e!==null}const Io=e=>/^0[^.\s]+$/u.test(e);function wr(e){let t;return()=>(t===void 0&&(t=e()),t)}const Be=e=>e,rc=(e,t)=>n=>t(e(n)),Fn=(...e)=>e.reduce(rc),Dn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class Sr{constructor(){this.subscriptions=[]}add(t){return br(this.subscriptions,t),()=>vr(this.subscriptions,t)}notify(t,n,s){const r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](t,n,s);else for(let o=0;o<r;o++){const i=this.subscriptions[o];i&&i(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Ge=e=>e*1e3,Fe=e=>e/1e3;function Oo(e,t){return t?e*(1e3/t):0}const ai=new Set;function Tr(e,t,n){e||ai.has(t)||(console.warn(Ws(t,n)),ai.add(t))}const $o=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,ic=1e-7,oc=12;function ac(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=$o(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>ic&&++a<oc);return i}function Bn(e,t,n,s){if(e===t&&n===s)return Be;const r=o=>ac(o,0,1,e,n);return o=>o===0||o===1?o:$o(r(o),t,s)}const Lo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Fo=e=>t=>1-e(1-t),Bo=Bn(.33,1.53,.69,.99),jr=Fo(Bo),Uo=Lo(jr),zo=e=>(e*=2)<1?.5*jr(e):.5*(2-Math.pow(2,-10*(e-1))),Cr=e=>1-Math.sin(Math.acos(e)),_o=Fo(Cr),Xo=Lo(Cr),lc=Bn(.42,0,1,1),cc=Bn(0,0,.58,1),Wo=Bn(.42,0,.58,1),uc=e=>Array.isArray(e)&&typeof e[0]!="number",qo=e=>Array.isArray(e)&&typeof e[0]=="number",li={linear:Be,easeIn:lc,easeInOut:Wo,easeOut:cc,circIn:Cr,circInOut:Xo,circOut:_o,backIn:jr,backInOut:Uo,backOut:Bo,anticipate:zo},dc=e=>typeof e=="string",ci=e=>{if(qo(e)){at(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return Bn(t,n,s,r)}else if(dc(e))return at(li[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),li[e];return e},Zn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function fc(e,t){let n=new Set,s=new Set,r=!1,o=!1;const i=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function l(d){i.has(d)&&(c.schedule(d),e()),d(a)}const c={schedule:(d,f=!1,m=!1)=>{const b=m&&r?n:s;return f&&i.add(d),b.has(d)||b.add(d),d},cancel:d=>{s.delete(d),i.delete(d)},process:d=>{if(a=d,r){o=!0;return}r=!0,[n,s]=[s,n],n.forEach(l),n.clear(),r=!1,o&&(o=!1,c.process(d))}};return c}const hc=40;function Ko(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Zn.reduce((E,$)=>(E[$]=fc(o),E),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:f,preRender:m,render:p,postRender:b}=i,v=()=>{const E=lt.useManualTiming?r.timestamp:performance.now();n=!1,lt.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(E-r.timestamp,hc),1)),r.timestamp=E,r.isProcessing=!0,a.process(r),l.process(r),c.process(r),d.process(r),f.process(r),m.process(r),p.process(r),b.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(v))},T=()=>{n=!0,s=!0,r.isProcessing||e(v)};return{schedule:Zn.reduce((E,$)=>{const D=i[$];return E[$]=(I,k=!1,C=!1)=>(n||T(),D.schedule(I,k,C)),E},{}),cancel:E=>{for(let $=0;$<Zn.length;$++)i[Zn[$]].cancel(E)},state:r,steps:i}}const{schedule:ce,cancel:wt,state:Te,steps:As}=Ko(typeof requestAnimationFrame<"u"?requestAnimationFrame:Be,!0);let is;function mc(){is=void 0}const De={now:()=>(is===void 0&&De.set(Te.isProcessing||lt.useManualTiming?Te.timestamp:performance.now()),is),set:e=>{is=e,queueMicrotask(mc)}},Go=e=>t=>typeof t=="string"&&t.startsWith(e),Pr=Go("--"),pc=Go("var(--"),Ar=e=>pc(e)?gc.test(e.split("/*")[0].trim()):!1,gc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,rn={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Vn={...rn,transform:e=>ot(0,1,e)},Qn={...rn,default:1},En=e=>Math.round(e*1e5)/1e5,Er=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function yc(e){return e==null}const xc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Mr=(e,t)=>n=>!!(typeof n=="string"&&xc.test(n)&&n.startsWith(e)||t&&!yc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ho=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Er);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},bc=e=>ot(0,255,e),Es={...rn,transform:e=>Math.round(bc(e))},Nt={test:Mr("rgb","red"),parse:Ho("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Es.transform(e)+", "+Es.transform(t)+", "+Es.transform(n)+", "+En(Vn.transform(s))+")"};function vc(e){let t="",n="",s="",r="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),r=e.substring(4,5),t+=t,n+=n,s+=s,r+=r),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:r?parseInt(r,16)/255:1}}const qs={test:Mr("#"),parse:vc,transform:Nt.transform},Un=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),vt=Un("deg"),Qe=Un("%"),z=Un("px"),wc=Un("vh"),Sc=Un("vw"),ui={...Qe,parse:e=>Qe.parse(e)/100,transform:e=>Qe.transform(e*100)},Kt={test:Mr("hsl","hue"),parse:Ho("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Qe.transform(En(t))+", "+Qe.transform(En(n))+", "+En(Vn.transform(s))+")"},xe={test:e=>Nt.test(e)||qs.test(e)||Kt.test(e),parse:e=>Nt.test(e)?Nt.parse(e):Kt.test(e)?Kt.parse(e):qs.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Nt.transform(e):Kt.transform(e),getAnimatableNone:e=>{const t=xe.parse(e);return t.alpha=0,xe.transform(t)}},Tc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function jc(e){return isNaN(e)&&typeof e=="string"&&(e.match(Er)?.length||0)+(e.match(Tc)?.length||0)>0}const Yo="number",Jo="color",Cc="var",Pc="var(",di="${}",Ac=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function In(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(Ac,l=>(xe.test(l)?(s.color.push(o),r.push(Jo),n.push(xe.parse(l))):l.startsWith(Pc)?(s.var.push(o),r.push(Cc),n.push(l)):(s.number.push(o),r.push(Yo),n.push(parseFloat(l))),++o,di)).split(di);return{values:n,split:a,indexes:s,types:r}}function Zo(e){return In(e).values}function Qo(e){const{split:t,types:n}=In(e),s=t.length;return r=>{let o="";for(let i=0;i<s;i++)if(o+=t[i],r[i]!==void 0){const a=n[i];a===Yo?o+=En(r[i]):a===Jo?o+=xe.transform(r[i]):o+=r[i]}return o}}const Ec=e=>typeof e=="number"?0:xe.test(e)?xe.getAnimatableNone(e):e;function Mc(e){const t=Zo(e);return Qo(e)(t.map(Ec))}const St={test:jc,parse:Zo,createTransformer:Qo,getAnimatableNone:Mc};function Ms(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function kc({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let r=0,o=0,i=0;if(!t)r=o=i=n;else{const a=n<.5?n*(1+t):n+t-n*t,l=2*n-a;r=Ms(l,a,e+1/3),o=Ms(l,a,e),i=Ms(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function us(e,t){return n=>n>0?t:e}const me=(e,t,n)=>e+(t-e)*n,ks=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},Nc=[qs,Nt,Kt],Rc=e=>Nc.find(t=>t.test(e));function fi(e){const t=Rc(e);if(sn(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(e);return t===Kt&&(n=kc(n)),n}const hi=(e,t)=>{const n=fi(e),s=fi(t);if(!n||!s)return us(e,t);const r={...n};return o=>(r.red=ks(n.red,s.red,o),r.green=ks(n.green,s.green,o),r.blue=ks(n.blue,s.blue,o),r.alpha=me(n.alpha,s.alpha,o),Nt.transform(r))},Ks=new Set(["none","hidden"]);function Dc(e,t){return Ks.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Vc(e,t){return n=>me(e,t,n)}function kr(e){return typeof e=="number"?Vc:typeof e=="string"?Ar(e)?us:xe.test(e)?hi:$c:Array.isArray(e)?ea:typeof e=="object"?xe.test(e)?hi:Ic:us}function ea(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>kr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Ic(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=kr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Oc(e,t){const n=[],s={color:0,var:0,number:0};for(let r=0;r<t.values.length;r++){const o=t.types[r],i=e.indexes[o][s[o]],a=e.values[i]??0;n[r]=a,s[o]++}return n}const $c=(e,t)=>{const n=St.createTransformer(t),s=In(e),r=In(t);return s.indexes.var.length===r.indexes.var.length&&s.indexes.color.length===r.indexes.color.length&&s.indexes.number.length>=r.indexes.number.length?Ks.has(e)&&!r.values.length||Ks.has(t)&&!s.values.length?Dc(e,t):Fn(ea(Oc(s,r),r.values),n):(sn(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),us(e,t))};function ta(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?me(e,t,n):kr(e)(e,t)}const Lc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>ce.update(t,n),stop:()=>wt(t),now:()=>Te.isProcessing?Te.timestamp:De.now()}},na=(e,t,n=10)=>{let s="";const r=Math.max(Math.round(t/n),2);for(let o=0;o<r;o++)s+=Math.round(e(o/(r-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},ds=2e4;function Nr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<ds;)t+=n,s=e.next(t);return t>=ds?1/0:t}function Fc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(Nr(s),ds);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Fe(r)}}const Bc=5;function sa(e,t,n){const s=Math.max(t-Bc,0);return Oo(n-e(s),t-s)}const he={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Ns=.001;function Uc({duration:e=he.duration,bounce:t=he.bounce,velocity:n=he.velocity,mass:s=he.mass}){let r,o;sn(e<=Ge(he.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=ot(he.minDamping,he.maxDamping,i),e=ot(he.minDuration,he.maxDuration,Fe(e)),i<1?(r=c=>{const d=c*i,f=d*e,m=d-n,p=Gs(c,i),b=Math.exp(-f);return Ns-m/p*b},o=c=>{const f=c*i*e,m=f*n+n,p=Math.pow(i,2)*Math.pow(c,2)*e,b=Math.exp(-f),v=Gs(Math.pow(c,2),i);return(-r(c)+Ns>0?-1:1)*((m-p)*b)/v}):(r=c=>{const d=Math.exp(-c*e),f=(c-n)*e+1;return-Ns+d*f},o=c=>{const d=Math.exp(-c*e),f=(n-c)*(e*e);return d*f});const a=5/e,l=_c(r,o,a);if(e=Ge(e),isNaN(l))return{stiffness:he.stiffness,damping:he.damping,duration:e};{const c=Math.pow(l,2)*s;return{stiffness:c,damping:i*2*Math.sqrt(s*c),duration:e}}}const zc=12;function _c(e,t,n){let s=n;for(let r=1;r<zc;r++)s=s-e(s)/t(s);return s}function Gs(e,t){return e*Math.sqrt(1-t*t)}const Xc=["duration","bounce"],Wc=["stiffness","damping","mass"];function mi(e,t){return t.some(n=>e[n]!==void 0)}function qc(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!mi(e,Wc)&&mi(e,Xc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*ot(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:he.mass,stiffness:r,damping:o}}else{const n=Uc(e);t={...t,...n,mass:he.mass},t.isResolvedFromDuration=!0}return t}function fs(e=he.visualDuration,t=he.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:r}=n;const o=n.keyframes[0],i=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:d,duration:f,velocity:m,isResolvedFromDuration:p}=qc({...n,velocity:-Fe(n.velocity||0)}),b=m||0,v=c/(2*Math.sqrt(l*d)),T=i-o,w=Fe(Math.sqrt(l/d)),M=Math.abs(T)<5;s||(s=M?he.restSpeed.granular:he.restSpeed.default),r||(r=M?he.restDelta.granular:he.restDelta.default);let E;if(v<1){const D=Gs(w,v);E=I=>{const k=Math.exp(-v*w*I);return i-k*((b+v*w*T)/D*Math.sin(D*I)+T*Math.cos(D*I))}}else if(v===1)E=D=>i-Math.exp(-w*D)*(T+(b+w*T)*D);else{const D=w*Math.sqrt(v*v-1);E=I=>{const k=Math.exp(-v*w*I),C=Math.min(D*I,300);return i-k*((b+v*w*T)*Math.sinh(C)+D*T*Math.cosh(C))/D}}const $={calculatedDuration:p&&f||null,next:D=>{const I=E(D);if(p)a.done=D>=f;else{let k=D===0?b:0;v<1&&(k=D===0?Ge(b):sa(E,D,I));const C=Math.abs(k)<=s,V=Math.abs(i-I)<=r;a.done=C&&V}return a.value=a.done?i:I,a},toString:()=>{const D=Math.min(Nr($),ds),I=na(k=>$.next(D*k).value,D,30);return D+"ms "+I},toTransition:()=>{}};return $}fs.applyToOptions=e=>{const t=Fc(e,100,fs);return e.ease=t.ease,e.duration=Ge(t.duration),e.type="keyframes",e};function Hs({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:r=10,bounceStiffness:o=500,modifyTarget:i,min:a,max:l,restDelta:c=.5,restSpeed:d}){const f=e[0],m={done:!1,value:f},p=C=>a!==void 0&&C<a||l!==void 0&&C>l,b=C=>a===void 0?l:l===void 0||Math.abs(a-C)<Math.abs(l-C)?a:l;let v=n*t;const T=f+v,w=i===void 0?T:i(T);w!==T&&(v=w-f);const M=C=>-v*Math.exp(-C/s),E=C=>w+M(C),$=C=>{const V=M(C),A=E(C);m.done=Math.abs(V)<=c,m.value=m.done?w:A};let D,I;const k=C=>{p(m.value)&&(D=C,I=fs({keyframes:[m.value,b(m.value)],velocity:sa(E,C,m.value),damping:r,stiffness:o,restDelta:c,restSpeed:d}))};return k(0),{calculatedDuration:null,next:C=>{let V=!1;return!I&&D===void 0&&(V=!0,$(C),k(C)),D!==void 0&&C>=D?I.next(C-D):(!V&&$(C),m)}}}function Kc(e,t,n){const s=[],r=n||lt.mix||ta,o=e.length-1;for(let i=0;i<o;i++){let a=r(e[i],e[i+1]);if(t){const l=Array.isArray(t)?t[i]||Be:t;a=Fn(l,a)}s.push(a)}return s}function Gc(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(at(o===t.length,"Both input and output ranges must be the same length","range-length"),o===1)return()=>t[0];if(o===2&&t[0]===t[1])return()=>t[1];const i=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const a=Kc(t,s,r),l=a.length,c=d=>{if(i&&d<e[0])return t[0];let f=0;if(l>1)for(;f<e.length-2&&!(d<e[f+1]);f++);const m=Dn(e[f],e[f+1],d);return a[f](m)};return n?d=>c(ot(e[0],e[o-1],d)):c}function Hc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=Dn(0,t,s);e.push(me(n,1,r))}}function Yc(e){const t=[0];return Hc(t,e.length-1),t}function Jc(e,t){return e.map(n=>n*t)}function Zc(e,t){return e.map(()=>t||Wo).splice(0,e.length-1)}function Gt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=uc(s)?s.map(ci):ci(s),o={done:!1,value:t[0]},i=Jc(n&&n.length===t.length?n:Yc(t),e),a=Gc(i,t,{ease:Array.isArray(r)?r:Zc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const Qc=e=>e!==null;function Rr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Qc),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const eu={decay:Hs,inertia:Hs,tween:Gt,keyframes:Gt,spring:fs};function ra(e){typeof e.type=="string"&&(e.type=eu[e.type])}class Dr{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const tu=e=>e/100;class Vr extends Dr{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==De.now()&&this.tick(De.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;ra(t);const{type:n=Gt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Gt;process.env.NODE_ENV!=="production"&&l!==Gt&&at(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Gt&&typeof a[0]!="number"&&(this.mixKeyframes=Fn(tu,ta(a[0],a[1])),a=[0,100]);const c=l({...t,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...t,keyframes:[...a].reverse(),velocity:-i})),c.calculatedDuration===null&&(c.calculatedDuration=Nr(c));const{calculatedDuration:d}=c;this.calculatedDuration=d,this.resolvedDuration=d+r,this.totalDuration=this.resolvedDuration*(s+1)-r,this.generator=c}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:r,mixKeyframes:o,mirroredGenerator:i,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return s.next(0);const{delay:c=0,keyframes:d,repeat:f,repeatType:m,repeatDelay:p,type:b,onUpdate:v,finalKeyframe:T}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-r/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const w=this.currentTime-c*(this.playbackSpeed>=0?1:-1),M=this.playbackSpeed>=0?w<0:w>r;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let E=this.currentTime,$=s;if(f){const C=Math.min(this.currentTime,r)/a;let V=Math.floor(C),A=C%1;!A&&C>=1&&(A=1),A===1&&V--,V=Math.min(V,f+1),!!(V%2)&&(m==="reverse"?(A=1-A,p&&(A-=p/a)):m==="mirror"&&($=i)),E=ot(0,1,A)*a}const D=M?{done:!1,value:d[0]}:$.next(E);o&&(D.value=o(D.value));let{done:I}=D;!M&&l!==null&&(I=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&I);return k&&b!==Hs&&(D.value=Rr(d,this.options,T,this.speed)),v&&v(D.value),k&&this.finish(),D}then(t,n){return this.finished.then(t,n)}get duration(){return Fe(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Fe(t)}get time(){return Fe(this.currentTime)}set time(t){t=Ge(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?.start(!1)}get speed(){return this.playbackSpeed}set speed(t){this.updateTime(De.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Fe(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Lc,startTime:n}=this.options;this.driver||(this.driver=t(r=>this.tick(r))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(De.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function nu(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Rt=e=>e*180/Math.PI,Ys=e=>{const t=Rt(Math.atan2(e[1],e[0]));return Js(t)},su={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Ys,rotateZ:Ys,skewX:e=>Rt(Math.atan(e[1])),skewY:e=>Rt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Js=e=>(e=e%360,e<0&&(e+=360),e),pi=Ys,gi=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),yi=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),ru={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:gi,scaleY:yi,scale:e=>(gi(e)+yi(e))/2,rotateX:e=>Js(Rt(Math.atan2(e[6],e[5]))),rotateY:e=>Js(Rt(Math.atan2(-e[2],e[0]))),rotateZ:pi,rotate:pi,skewX:e=>Rt(Math.atan(e[4])),skewY:e=>Rt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Zs(e){return e.includes("scale")?1:0}function Qs(e,t){if(!e||e==="none")return Zs(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=ru,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=su,r=a}if(!r)return Zs(t);const o=s[t],i=r[1].split(",").map(ou);return typeof o=="function"?o(i):i[o]}const iu=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Qs(n,t)};function ou(e){return parseFloat(e.trim())}const on=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],an=new Set(on),xi=e=>e===rn||e===z,au=new Set(["x","y","z"]),lu=on.filter(e=>!au.has(e));function cu(e){const t=[];return lu.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Dt={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Qs(t,"x"),y:(e,{transform:t})=>Qs(t,"y")};Dt.translateX=Dt.x;Dt.translateY=Dt.y;const Vt=new Set;let er=!1,tr=!1,nr=!1;function ia(){if(tr){const e=Array.from(Vt).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=cu(s);r.length&&(n.set(s,r),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const r=n.get(s);r&&r.forEach(([o,i])=>{s.getValue(o)?.set(i)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}tr=!1,er=!1,Vt.forEach(e=>e.complete(nr)),Vt.clear()}function oa(){Vt.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(tr=!0)})}function uu(){nr=!0,oa(),ia(),nr=!1}class Ir{constructor(t,n,s,r,o,i=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=r,this.element=o,this.isAsync=i}scheduleResolve(){this.state="scheduled",this.isAsync?(Vt.add(this),er||(er=!0,ce.read(oa),ce.resolveKeyframes(ia))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:r}=this;if(t[0]===null){const o=r?.get(),i=t[t.length-1];if(o!==void 0)t[0]=o;else if(s&&n){const a=s.readValue(n,i);a!=null&&(t[0]=a)}t[0]===void 0&&(t[0]=i),r&&o===void 0&&r.set(t[0])}nu(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Vt.delete(this)}cancel(){this.state==="scheduled"&&(Vt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const du=e=>e.startsWith("--");function fu(e,t,n){du(t)?e.style.setProperty(t,n):e.style[t]=n}const hu=wr(()=>window.ScrollTimeline!==void 0),mu={};function pu(e,t){const n=wr(e);return()=>mu[t]??n()}const aa=pu(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Pn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,bi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Pn([0,.65,.55,1]),circOut:Pn([.55,0,1,.45]),backIn:Pn([.31,.01,.66,-.59]),backOut:Pn([.33,1.53,.69,.99])};function la(e,t){if(e)return typeof e=="function"?aa()?na(e,t):"ease-out":qo(e)?Pn(e):Array.isArray(e)?e.map(n=>la(n,t)||bi.easeOut):bi[e]}function gu(e,t,n,{delay:s=0,duration:r=300,repeat:o=0,repeatType:i="loop",ease:a="easeOut",times:l}={},c=void 0){const d={[t]:n};l&&(d.offset=l);const f=la(a,r);Array.isArray(f)&&(d.easing=f);const m={delay:s,duration:r,easing:Array.isArray(f)?"linear":f,fill:"both",iterations:o+1,direction:i==="reverse"?"alternate":"normal"};return c&&(m.pseudoElement=c),e.animate(d,m)}function ca(e){return typeof e=="function"&&"applyToOptions"in e}function yu({type:e,...t}){return ca(e)&&aa()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class xu extends Dr{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,!t)return;const{element:n,name:s,keyframes:r,pseudoElement:o,allowFlatten:i=!1,finalKeyframe:a,onComplete:l}=t;this.isPseudoElement=!!o,this.allowFlatten=i,this.options=t,at(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const c=yu(t);this.animation=gu(n,s,r,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Rr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):fu(n,s,d),this.animation.cancel()}l?.(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){this.isPseudoElement||this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return Fe(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Fe(t)}get time(){return Fe(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=Ge(t)}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(t){this.animation.startTime=t}attachTimeline({timeline:t,observe:n}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&hu()?(this.animation.timeline=t,Be):n(this)}}const ua={anticipate:zo,backInOut:Uo,circInOut:Xo};function bu(e){return e in ua}function vu(e){typeof e.ease=="string"&&bu(e.ease)&&(e.ease=ua[e.ease])}const vi=10;class wu extends xu{constructor(t){vu(t),ra(t),super(t),t.startTime&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:r,element:o,...i}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const a=new Vr({...i,autoplay:!1}),l=Ge(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-vi).value,a.sample(l).value,vi),a.stop()}}const wi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(St.test(e)||e==="0")&&!e.startsWith("url("));function Su(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function Tu(e,t,n,s){const r=e[0];if(r===null)return!1;if(t==="display"||t==="visibility")return!0;const o=e[e.length-1],i=wi(r,t),a=wi(o,t);return sn(i===a,`You are trying to animate ${t} from "${r}" to "${o}". "${i?o:r}" is not an animatable value.`,"value-not-animatable"),!i||!a?!1:Su(e)||(n==="spring"||ca(n))&&s}function sr(e){e.duration=0,e.type="keyframes"}const ju=new Set(["opacity","clipPath","filter","transform"]),Cu=wr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Pu(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:r,damping:o,type:i}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;const{onUpdate:l,transformTemplate:c}=t.owner.getProps();return Cu()&&n&&ju.has(n)&&(n!=="transform"||!c)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Au=40;class Eu extends Dr{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:r=0,repeatDelay:o=0,repeatType:i="loop",keyframes:a,name:l,motionValue:c,element:d,...f}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=De.now();const m={autoplay:t,delay:n,type:s,repeat:r,repeatDelay:o,repeatType:i,name:l,motionValue:c,element:d,...f},p=d?.KeyframeResolver||Ir;this.keyframeResolver=new p(a,(b,v,T)=>this.onKeyframesResolved(b,v,m,!T),l,c,d),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,r){this.keyframeResolver=void 0;const{name:o,type:i,velocity:a,delay:l,isHandoff:c,onUpdate:d}=s;this.resolvedAt=De.now(),Tu(t,o,i,a)||((lt.instantAnimations||!l)&&d?.(Rr(t,s,n)),t[0]=t[t.length-1],sr(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Au?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!c&&Pu(m)?new wu({...m,element:m.motionValue.owner.current}):new Vr(m);p.finished.then(()=>this.notifyFinished()).catch(Be),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),uu()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}const Mu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function ku(e){const t=Mu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const Nu=4;function da(e,t,n=1){at(n<=Nu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=ku(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return Do(i)?parseFloat(i):i}return Ar(r)?da(r,t,n+1):r}function Or(e,t){return e?.[t]??e?.default??e}const fa=new Set(["width","height","top","left","right","bottom",...on]),Ru={test:e=>e==="auto",parse:e=>e},ha=e=>t=>t.test(e),ma=[rn,z,Qe,vt,Sc,wc,Ru],Si=e=>ma.find(ha(e));function Du(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Io(e):!0}const Vu=new Set(["brightness","contrast","saturate","opacity"]);function Iu(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Er)||[];if(!s)return e;const r=n.replace(s,"");let o=Vu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const Ou=/\b([a-z-]*)\(.*?\)/gu,rr={...St,getAnimatableNone:e=>{const t=e.match(Ou);return t?t.map(Iu).join(" "):e}},Ti={...rn,transform:Math.round},$u={rotate:vt,rotateX:vt,rotateY:vt,rotateZ:vt,scale:Qn,scaleX:Qn,scaleY:Qn,scaleZ:Qn,skew:vt,skewX:vt,skewY:vt,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:Vn,originX:ui,originY:ui,originZ:z},$r={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...$u,zIndex:Ti,fillOpacity:Vn,strokeOpacity:Vn,numOctaves:Ti},Lu={...$r,color:xe,backgroundColor:xe,outlineColor:xe,fill:xe,stroke:xe,borderColor:xe,borderTopColor:xe,borderRightColor:xe,borderBottomColor:xe,borderLeftColor:xe,filter:rr,WebkitFilter:rr},pa=e=>Lu[e];function ga(e,t){let n=pa(e);return n!==rr&&(n=St),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Fu=new Set(["auto","none","0"]);function Bu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Fu.has(o)&&In(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ga(n,r)}class Uu extends Ir{constructor(t,n,s,r,o){super(t,n,s,r,o,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<t.length;l++){let c=t[l];if(typeof c=="string"&&(c=c.trim(),Ar(c))){const d=da(c,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!fa.has(s)||t.length!==2)return;const[r,o]=t,i=Si(r),a=Si(o);if(i!==a)if(xi(i)&&xi(a))for(let l=0;l<t.length;l++){const c=t[l];typeof c=="string"&&(t[l]=parseFloat(c))}else Dt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||Du(t[r]))&&s.push(r);s.length&&Bu(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Dt[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const r=n[n.length-1];r!==void 0&&t.getValue(s,r).jump(r,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const r=t.getValue(n);r&&r.jump(this.measuredOrigin,!1);const o=s.length-1,i=s[o];s[o]=Dt[n](t.measureViewportBox(),window.getComputedStyle(t.current)),i!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=i),this.removedTransforms?.length&&this.removedTransforms.forEach(([a,l])=>{t.getValue(a).set(l)}),this.resolveNoneKeyframes()}}function zu(e,t,n){if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const r=n?.[e]??s.querySelectorAll(e);return r?Array.from(r):[]}return Array.from(e)}const ya=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function xa(e){return Vo(e)&&"offsetHeight"in e}const ji=30,_u=e=>!isNaN(parseFloat(e));class Xu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=De.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const o of this.dependents)o.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=De.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=_u(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&Tr(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new Sr);const s=this.events[t].add(n);return t==="change"?()=>{s(),ce.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-s}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=De.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>ji)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,ji);return Oo(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function tn(e,t){return new Xu(e,t)}const{schedule:Lr}=Ko(queueMicrotask,!1),qe={x:!1,y:!1};function ba(){return qe.x||qe.y}function Wu(e){return e==="x"||e==="y"?qe[e]?null:(qe[e]=!0,()=>{qe[e]=!1}):qe.x||qe.y?null:(qe.x=qe.y=!0,()=>{qe.x=qe.y=!1})}function va(e,t){const n=zu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function Ci(e){return!(e.pointerType==="touch"||ba())}function qu(e,t,n={}){const[s,r,o]=va(e,n),i=a=>{if(!Ci(a))return;const{target:l}=a,c=t(l,a);if(typeof c!="function"||!l)return;const d=f=>{Ci(f)&&(c(f),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const wa=(e,t)=>t?e===t?!0:wa(e,t.parentElement):!1,Fr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Ku=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Gu(e){return Ku.has(e.tagName)||e.tabIndex!==-1}const os=new WeakSet;function Pi(e){return t=>{t.key==="Enter"&&e(t)}}function Rs(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Hu=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Pi(()=>{if(os.has(n))return;Rs(n,"down");const r=Pi(()=>{Rs(n,"up")}),o=()=>Rs(n,"cancel");n.addEventListener("keyup",r,t),n.addEventListener("blur",o,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function Ai(e){return Fr(e)&&!ba()}function Yu(e,t,n={}){const[s,r,o]=va(e,n),i=a=>{const l=a.currentTarget;if(!Ai(a))return;os.add(l);const c=t(l,a),d=(p,b)=>{window.removeEventListener("pointerup",f),window.removeEventListener("pointercancel",m),os.has(l)&&os.delete(l),Ai(p)&&typeof c=="function"&&c(p,{success:b})},f=p=>{d(p,l===window||l===document||n.useGlobalTarget||wa(l,p.target))},m=p=>{d(p,!1)};window.addEventListener("pointerup",f,r),window.addEventListener("pointercancel",m,r)};return s.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",i,r),xa(a)&&(a.addEventListener("focus",c=>Hu(c,r)),!Gu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Sa(e){return Vo(e)&&"ownerSVGElement"in e}function Ju(e){return Sa(e)&&e.tagName==="svg"}const je=e=>!!(e&&e.getVelocity),Zu=[...ma,xe,St],Qu=e=>Zu.find(ha(e)),Br=h.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Ei(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ed(...e){return t=>{let n=!1;const s=e.map(r=>{const o=Ei(r,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let r=0;r<s.length;r++){const o=s[r];typeof o=="function"?o():Ei(e[r],null)}}}}function td(...e){return Ke.useCallback(ed(...e),e)}class nd extends Ke.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=xa(s)&&s.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function sd({children:e,isPresent:t,anchorX:n,root:s}){const r=h.useId(),o=h.useRef(null),i=h.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=h.useContext(Br),l=td(o,e?.ref);return h.useInsertionEffect(()=>{const{width:c,height:d,top:f,left:m,right:p}=i.current;if(t||!o.current||!c||!d)return;const b=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const v=document.createElement("style");a&&(v.nonce=a);const T=s??document.head;return T.appendChild(v),v.sheet&&v.sheet.insertRule(`
|
|
6
3
|
[data-motion-pop-id="${r}"] {
|
|
7
4
|
position: absolute !important;
|
|
8
5
|
width: ${c}px !important;
|
|
@@ -10,10 +7,10 @@ ${JSON.stringify(g,null,2)}`}catch(y){return console.error("[useAgent] Failed to
|
|
|
10
7
|
${b}px !important;
|
|
11
8
|
top: ${f}px !important;
|
|
12
9
|
}
|
|
13
|
-
`),()=>{T.contains(v)&&T.removeChild(v)}},[t]),u.jsx(sd,{isPresent:t,childRef:o,sizeRef:i,children:qe.cloneElement(e,{ref:l})})}const id=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const c=yr(od),d=h.useId();let f=!0,m=h.useMemo(()=>(f=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:p=>{c.set(p,!0);for(const b of c.values())if(!b)return;s&&s()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[n,c,s]);return o&&f&&(m={...m}),h.useMemo(()=>{c.forEach((p,b)=>c.set(b,!1))},[n]),qe.useEffect(()=>{!n&&!c.size&&s&&s()},[n]),i==="popLayout"&&(e=u.jsx(rd,{isPresent:n,anchorX:a,root:l,children:e})),u.jsx(gs.Provider,{value:m,children:e})};function od(){return new Map}function Ta(e=!0){const t=h.useContext(gs);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,o=h.useId();h.useEffect(()=>{if(e)return r(o)},[e]);const i=h.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,i]:[!0]}const es=e=>e.key||"";function Mi(e){const t=[];return h.Children.forEach(e,n=>{h.isValidElement(n)&&t.push(n)}),t}const ad=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:l})=>{const[c,d]=Ta(i),f=h.useMemo(()=>Mi(e),[e]),m=i&&!c?[]:f.map(es),p=h.useRef(!0),b=h.useRef(f),v=yr(()=>new Map),[T,w]=h.useState(f),[M,E]=h.useState(f);Ro(()=>{p.current=!1,b.current=f;for(let I=0;I<M.length;I++){const k=es(M[I]);m.includes(k)?v.delete(k):v.get(k)!==!0&&v.set(k,!1)}},[M,m.length,m.join("-")]);const $=[];if(f!==T){let I=[...f];for(let k=0;k<M.length;k++){const j=M[k],V=es(j);m.includes(V)||(I.splice(k,0,j),$.push(j))}return o==="wait"&&$.length&&(I=$),E(Mi(I)),w(f),null}process.env.NODE_ENV!=="production"&&o==="wait"&&M.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:D}=h.useContext(gr);return u.jsx(u.Fragment,{children:M.map(I=>{const k=es(I),j=i&&!c?!1:f===M||m.includes(k),V=()=>{if(v.has(k))v.set(k,!0);else return;let A=!0;v.forEach(N=>{N||(A=!1)}),A&&(D?.(),E(b.current),i&&d?.(),s&&s())};return u.jsx(id,{isPresent:j,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:j?void 0:V,anchorX:a,children:I},k)})})},Ur=h.createContext({strict:!1}),ki={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},nn={};for(const e in ki)nn[e]={isEnabled:t=>ki[e].some(n=>!!t[n])};function ir(e){for(const t in e)nn[t]={...nn[t],...e[t]}}function ld({children:e,features:t,strict:n=!1}){const[,s]=h.useState(!Ds(t)),r=h.useRef(void 0);if(!Ds(t)){const{renderer:o,...i}=t;r.current=o,ir(i)}return h.useEffect(()=>{Ds(t)&&t().then(({renderer:o,...i})=>{ir(i),r.current=o,s(!0)})},[]),u.jsx(Ur.Provider,{value:{renderer:r.current,strict:n},children:e})}function Ds(e){return typeof e=="function"}const cd=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function hs(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||cd.has(e)}let Ca=e=>!hs(e);function ud(e){typeof e=="function"&&(Ca=t=>t.startsWith("on")?!hs(t):e(t))}try{ud(require("@emotion/is-prop-valid").default)}catch{}function dd(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(Ca(r)||n===!0&&hs(r)||!t&&!hs(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const ys=h.createContext({});function xs(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function On(e){return typeof e=="string"||Array.isArray(e)}const zr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],_r=["initial",...zr];function bs(e){return xs(e.animate)||_r.some(t=>On(e[t]))}function ja(e){return!!(bs(e)||e.variants)}function fd(e,t){if(bs(e)){const{initial:n,animate:s}=e;return{initial:n===!1||On(n)?n:void 0,animate:On(s)?s:void 0}}return e.inherit!==!1?t:{}}function hd(e){const{initial:t,animate:n}=fd(e,h.useContext(ys));return h.useMemo(()=>({initial:t,animate:n}),[Ni(t),Ni(n)])}function Ni(e){return Array.isArray(e)?e.join(" "):e}const $n={};function md(e){for(const t in e)$n[t]=e[t],Pr(t)&&($n[t].isCSSVariable=!0)}function Pa(e,{layout:t,layoutId:n}){return an.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!$n[e]||e==="opacity")}const pd={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},gd=on.length;function yd(e,t,n){let s="",r=!0;for(let o=0;o<gd;o++){const i=on[o],a=e[i];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(i.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=ya(a,$r[i]);if(!l){r=!1;const d=pd[i]||i;s+=`${d}(${c}) `}n&&(t[i]=c)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function Xr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const l in t){const c=t[l];if(an.has(l)){i=!0;continue}else if(Pr(l)){r[l]=c;continue}else{const d=ya(c,$r[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=yd(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:d=0}=o;s.transformOrigin=`${l} ${c} ${d}`}}const Wr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Aa(e,t,n){for(const s in t)!je(t[s])&&!Pa(s,n)&&(e[s]=t[s])}function xd({transformTemplate:e},t){return h.useMemo(()=>{const n=Wr();return Xr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function bd(e,t){const n=e.style||{},s={};return Aa(s,n,e),Object.assign(s,xd(e,t)),s}function vd(e,t){const n={},s=bd(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const wd={offset:"stroke-dashoffset",array:"stroke-dasharray"},Sd={offset:"strokeDashoffset",array:"strokeDasharray"};function Td(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?wd:Sd;e[o.offset]=z.transform(-s);const i=z.transform(t),a=z.transform(n);e[o.array]=`${i} ${a}`}function Ea(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,c,d){if(Xr(e,a,c),l){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:f,style:m}=e;f.transform&&(m.transform=f.transform,delete f.transform),(m.transform||f.transformOrigin)&&(m.transformOrigin=f.transformOrigin??"50% 50%",delete f.transformOrigin),m.transform&&(m.transformBox=d?.transformBox??"fill-box",delete f.transformBox),t!==void 0&&(f.x=t),n!==void 0&&(f.y=n),s!==void 0&&(f.scale=s),r!==void 0&&Td(f,r,o,i,!1)}const Ma=()=>({...Wr(),attrs:{}}),ka=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Cd(e,t,n,s){const r=h.useMemo(()=>{const o=Ma();return Ea(o,t,ka(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Aa(o,e.style,e),r.style={...o,...r.style}}return r}const jd=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function qr(e){return typeof e!="string"||e.includes("-")?!1:!!(jd.indexOf(e)>-1||/[A-Z]/u.test(e))}function Pd(e,t,n,{latestValues:s},r,o=!1){const a=(qr(e)?Cd:vd)(t,s,r,e),l=dd(t,typeof e=="string",o),c=e!==h.Fragment?{...l,...a,ref:n}:{},{children:d}=t,f=h.useMemo(()=>je(d)?d.get():d,[d]);return h.createElement(e,{...c,children:f})}function Ri(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Kr(e,t,n,s){if(typeof t=="function"){const[r,o]=Ri(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=Ri(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function as(e){return je(e)?e.get():e}function Ad({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:Ed(n,s,r,e),renderState:t()}}function Ed(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=as(o[m]);let{initial:i,animate:a}=e;const l=bs(e),c=ja(e);t&&c&&!l&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||i===!1;const f=d?a:i;if(f&&typeof f!="boolean"&&!xs(f)){const m=Array.isArray(f)?f:[f];for(let p=0;p<m.length;p++){const b=Kr(e,m[p]);if(b){const{transitionEnd:v,transition:T,...w}=b;for(const M in w){let E=w[M];if(Array.isArray(E)){const $=d?E.length-1:0;E=E[$]}E!==null&&(r[M]=E)}for(const M in v)r[M]=v[M]}}}return r}const Na=e=>(t,n)=>{const s=h.useContext(ys),r=h.useContext(gs),o=()=>Ad(e,t,s,r);return n?o():yr(o)};function Gr(e,t,n){const{style:s}=e,r={};for(const o in s)(je(s[o])||t.style&&je(t.style[o])||Pa(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const Md=Na({scrapeMotionValuesFromProps:Gr,createRenderState:Wr});function Ra(e,t,n){const s=Gr(e,t,n);for(const r in e)if(je(e[r])||je(t[r])){const o=on.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const kd=Na({scrapeMotionValuesFromProps:Ra,createRenderState:Ma}),Nd=Symbol.for("motionComponentSymbol");function Ht(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function Rd(e,t,n){return h.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):Ht(n)&&(n.current=s))},[t])}const Hr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Dd="framerAppearId",Da="data-"+Hr(Dd),Va=h.createContext({});function Vd(e,t,n,s,r){const{visualElement:o}=h.useContext(ys),i=h.useContext(Ur),a=h.useContext(gs),l=h.useContext(Br).reducedMotion,c=h.useRef(null);s=s||i.renderer,!c.current&&s&&(c.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=c.current,f=h.useContext(Va);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&Id(c.current,n,r,f);const m=h.useRef(!1);h.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Da],b=h.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return Ro(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),b.current&&d.animationState&&d.animationState.animateChanges())}),h.useEffect(()=>{d&&(!b.current&&d.animationState&&d.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),b.current=!1),d.enteringChildren=void 0)}),d}function Id(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Ia(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Ht(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:c})}function Ia(e){if(e)return e.options.allowProjection!==!1?e.projection:Ia(e.parent)}function ls(e,{forwardMotionProps:t=!1}={},n,s){n&&ir(n);const r=qr(e)?kd:Md;function o(a,l){let c;const d={...h.useContext(Br),...a,layoutId:Od(a)},{isStatic:f}=d,m=hd(a),p=r(a,f);if(!f&&xr){$d(d,n);const b=Ld(d);c=b.MeasureLayout,m.visualElement=Vd(e,p,d,s,b.ProjectionNode)}return u.jsxs(ys.Provider,{value:m,children:[c&&m.visualElement?u.jsx(c,{visualElement:m.visualElement,...d}):null,Pd(e,a,Rd(p,m.visualElement,l),p,f,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=h.forwardRef(o);return i[Nd]=e,i}function Od({layoutId:e}){const t=h.useContext(gr).id;return t&&e!==void 0?t+"-"+e:e}function $d(e,t){const n=h.useContext(Ur).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?sn(!1,s,"lazy-strict-mode"):lt(!1,s,"lazy-strict-mode")}}function Ld(e){const{drag:t,layout:n}=nn;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Fd(e,t){if(typeof Proxy>"u")return ls;const n=new Map,s=(o,i)=>ls(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Tr(!1,"motion() is deprecated. Use motion.create() instead."),s(o,i));return new Proxy(r,{get:(o,i)=>i==="create"?s:(n.has(i)||n.set(i,ls(i,void 0,e,t)),n.get(i))})}function Oa({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Bd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Ud(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function Vs(e){return e===void 0||e===1}function or({scale:e,scaleX:t,scaleY:n}){return!Vs(e)||!Vs(t)||!Vs(n)}function kt(e){return or(e)||$a(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function $a(e){return Di(e.x)||Di(e.y)}function Di(e){return e&&e!=="0%"}function ms(e,t,n){const s=e-n,r=t*s;return n+r}function Vi(e,t,n,s,r){return r!==void 0&&(e=ms(e,r,s)),ms(e,n,s)+t}function ar(e,t=0,n=1,s,r){e.min=Vi(e.min,t,n,s,r),e.max=Vi(e.max,t,n,s,r)}function La(e,{x:t,y:n}){ar(e.x,t.translate,t.scale,t.originPoint),ar(e.y,n.translate,n.scale,n.originPoint)}const Ii=.999999999999,Oi=1.0000000000001;function zd(e,t,n,s=!1){const r=n.length;if(!r)return;t.x=t.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Jt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,La(e,i)),s&&kt(o.latestValues)&&Jt(e,o.latestValues))}t.x<Oi&&t.x>Ii&&(t.x=1),t.y<Oi&&t.y>Ii&&(t.y=1)}function Yt(e,t){e.min=e.min+t,e.max=e.max+t}function $i(e,t,n,s,r=.5){const o=he(e.min,e.max,r);ar(e,t,n,o,s)}function Jt(e,t){$i(e.x,t.x,t.scaleX,t.scale,t.originX),$i(e.y,t.y,t.scaleY,t.scale,t.originY)}function Fa(e,t){return Oa(Ud(e.getBoundingClientRect(),t))}function _d(e,t,n){const s=Fa(e,n),{scroll:r}=t;return r&&(Yt(s.x,r.offset.x),Yt(s.y,r.offset.y)),s}const Li=()=>({translate:0,scale:1,origin:0,originPoint:0}),Zt=()=>({x:Li(),y:Li()}),Fi=()=>({min:0,max:0}),ye=()=>({x:Fi(),y:Fi()}),lr={current:null},Ba={current:!1};function Xd(){if(Ba.current=!0,!!xr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>lr.current=e.matches;e.addEventListener("change",t),t()}else lr.current=!1}const Wd=new WeakMap;function qd(e,t,n){for(const s in t){const r=t[s],o=n[s];if(je(r))e.addValue(s,r);else if(je(o))e.addValue(s,tn(r,{owner:e}));else if(o!==r)if(e.hasValue(s)){const i=e.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=e.getStaticValue(s);e.addValue(s,tn(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Bi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Kd{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Ir,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const m=De.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,le.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=i;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=bs(n),this.isVariantNode=ja(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:d,...f}=this.scrapeMotionValuesFromProps(n,{},this);for(const m in f){const p=f[m];l[m]!==void 0&&je(p)&&p.set(l[m])}}mount(t){this.current=t,Wd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),Ba.current||Xd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:lr.current,process.env.NODE_ENV!=="production"&&Tr(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),wt(this.notifyUpdate),wt(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const s=an.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&le.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in nn){const n=nn[t];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[t]&&r&&s(this.props)&&(this.features[t]=new r(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ye()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<Bi.length;s++){const r=Bi[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=t[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=qd(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=tn(n===null?void 0:n,{owner:this}),this.addValue(t,s)),s}readValue(t,n){let s=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return s!=null&&(typeof s=="string"&&(Do(s)||Io(s))?s=parseFloat(s):!ed(s)&&St.test(n)&&(s=ga(t,n)),this.setBaseTarget(t,je(s)?s.get():s)),je(s)?s.get():s}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=Kr(this.props,n,this.presenceContext?.custom);o&&(s=o[t])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!je(r)?r:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new Sr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Lr.render(this.render)}}class Ua extends Kd{constructor(){super(...arguments),this.KeyframeResolver=zu}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;je(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function za(e,{style:t,vars:n},s,r){const o=e.style;let i;for(i in t)o[i]=t[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function Gd(e){return window.getComputedStyle(e)}class Hd extends Ua{constructor(){super(...arguments),this.type="html",this.renderInstance=za}readValueFromInstance(t,n){if(an.has(n))return this.projection?.isProjecting?Zs(n):ou(t,n);{const s=Gd(t),r=(Pr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Fa(t,n)}build(t,n,s){Xr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Gr(t,n,s)}}const _a=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function Yd(e,t,n,s){za(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(_a.has(r)?r:Hr(r),t.attrs[r])}class Jd extends Ua{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ye}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(an.has(n)){const s=pa(n);return s&&s.default||0}return n=_a.has(n)?n:Hr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Ra(t,n,s)}build(t,n,s){Ea(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Yd(t,n,s,r)}mount(t){this.isSVGTag=ka(t.tagName),super.mount(t)}}const Xa=(e,t)=>qr(e)?new Jd(t):new Hd(t,{allowProjection:e!==h.Fragment});function en(e,t,n){const s=e.getProps();return Kr(s,t,n!==void 0?n:s.custom,e)}const cr=e=>Array.isArray(e);function Zd(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,tn(n))}function Qd(e){return cr(e)?e[e.length-1]||0:e}function ef(e,t){const n=en(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Qd(o[i]);Zd(e,i,a)}}function tf(e){return!!(je(e)&&e.add)}function ur(e,t){const n=e.getValue("willChange");if(tf(n))return n.add(t);if(!n&&ct.WillChange){const s=new ct.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Wa(e){return e.props[Da]}const nf=e=>e!==null;function sf(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(nf),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const rf={type:"spring",stiffness:500,damping:25,restSpeed:10},of=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),af={type:"keyframes",duration:.8},lf={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},cf=(e,{keyframes:t})=>t.length>2?af:an.has(e)?e.startsWith("scale")?of(t[1]):rf:lf;function uf({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}const Yr=(e,t,n,s={},r,o)=>i=>{const a=Or(s,e)||{},l=a.delay||s.delay||0;let{elapsed:c=0}=s;c=c-Ke(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,onUpdate:m=>{t.set(m),a.onUpdate&&a.onUpdate(m)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};uf(a)||Object.assign(d,cf(e,d)),d.duration&&(d.duration=Ke(d.duration)),d.repeatDelay&&(d.repeatDelay=Ke(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let f=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(sr(d),d.delay===0&&(f=!0)),(ct.instantAnimations||ct.skipAnimations)&&(f=!0,sr(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,f&&!o&&t.get()!==void 0){const m=sf(d.keyframes,a);if(m!==void 0){le.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Vr(d):new Mu(d)};function df({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function qa(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const l=[],c=r&&e.animationState&&e.animationState.getState()[r];for(const d in a){const f=e.getValue(d,e.latestValues[d]??null),m=a[d];if(m===void 0||c&&df(c,d))continue;const p={delay:n,...Or(o||{},d)},b=f.get();if(b!==void 0&&!f.isAnimating&&!Array.isArray(m)&&m===b&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const w=Wa(e);if(w){const M=window.MotionHandoffAnimation(w,d,le);M!==null&&(p.startTime=M,v=!0)}}ur(e,d),f.start(Yr(d,f,m,e.shouldReduceMotion&&fa.has(d)?{type:!1}:p,e,v));const T=f.animation;T&&l.push(T)}return i&&Promise.all(l).then(()=>{le.update(()=>{i&&ef(e,i)})}),l}function Ka(e,t,n,s=0,r=1){const o=Array.from(e).sort((c,d)=>c.sortNodePosition(d)).indexOf(t),i=e.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function dr(e,t,n={}){const s=en(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(qa(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:c=0,staggerChildren:d,staggerDirection:f}=r;return ff(e,t,l,c,d,f,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,c]=a==="beforeChildren"?[o,i]:[i,o];return l().then(()=>c())}else return Promise.all([o(),i(n.delay)])}function ff(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const l of e.variantChildren)l.notify("AnimationStart",t),a.push(dr(l,t,{...i,delay:n+(typeof s=="function"?0:s)+Ka(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function hf(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>dr(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=dr(e,t,n);else{const r=typeof t=="function"?en(e,t,n.custom):t;s=Promise.all(qa(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function Ga(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const mf=_r.length;function Ha(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Ha(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<mf;n++){const s=_r[n],r=e.props[s];(On(r)||r===!1)&&(t[s]=r)}return t}const pf=[...zr].reverse(),gf=zr.length;function yf(e){return t=>Promise.all(t.map(({animation:n,options:s})=>hf(e,n,s)))}function xf(e){let t=yf(e),n=Ui(),s=!0;const r=l=>(c,d)=>{const f=en(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(f){const{transition:m,transitionEnd:p,...b}=f;c={...c,...b,...p}}return c};function o(l){t=l(e)}function i(l){const{props:c}=e,d=Ha(e.parent)||{},f=[],m=new Set;let p={},b=1/0;for(let T=0;T<gf;T++){const w=pf[T],M=n[w],E=c[w]!==void 0?c[w]:d[w],$=On(E),D=w===l?M.isActive:null;D===!1&&(b=T);let I=E===d[w]&&E!==c[w]&&$;if(I&&s&&e.manuallyAnimateOnMount&&(I=!1),M.protectedKeys={...p},!M.isActive&&D===null||!E&&!M.prevProp||xs(E)||typeof E=="boolean")continue;const k=bf(M.prevProp,E);let j=k||w===l&&M.isActive&&!I&&$||T>b&&$,V=!1;const A=Array.isArray(E)?E:[E];let N=A.reduce(r(w),{});D===!1&&(N={});const{prevResolvedValues:L={}}=M,O={...L,...N},F=K=>{j=!0,m.has(K)&&(V=!0,m.delete(K)),M.needsAnimating[K]=!0;const oe=e.getValue(K);oe&&(oe.liveStyle=!1)};for(const K in O){const oe=N[K],be=L[K];if(p.hasOwnProperty(K))continue;let Ge=!1;cr(oe)&&cr(be)?Ge=!Ga(oe,be):Ge=oe!==be,Ge?oe!=null?F(K):m.add(K):oe!==void 0&&m.has(K)?F(K):M.protectedKeys[K]=!0}M.prevProp=E,M.prevResolvedValues=N,M.isActive&&(p={...p,...N}),s&&e.blockInitialAnimation&&(j=!1);const X=I&&k;j&&(!X||V)&&f.push(...A.map(K=>{const oe={type:w};if(typeof K=="string"&&s&&!X&&e.manuallyAnimateOnMount&&e.parent){const{parent:be}=e,Ge=en(be,K);if(be.enteringChildren&&Ge){const{delayChildren:Ct}=Ge.transition||{};oe.delay=Ka(be.enteringChildren,e,Ct)}}return{animation:K,options:oe}}))}if(m.size){const T={};if(typeof c.initial!="boolean"){const w=en(e,Array.isArray(c.initial)?c.initial[0]:c.initial);w&&w.transition&&(T.transition=w.transition)}m.forEach(w=>{const M=e.getBaseTarget(w),E=e.getValue(w);E&&(E.liveStyle=!0),T[w]=M??null}),f.push({animation:T})}let v=!!f.length;return s&&(c.initial===!1||c.initial===c.animate)&&!e.manuallyAnimateOnMount&&(v=!1),s=!1,v?t(f):Promise.resolve()}function a(l,c){if(n[l].isActive===c)return Promise.resolve();e.variantChildren?.forEach(f=>f.animationState?.setActive(l,c)),n[l].isActive=c;const d=i(l);for(const f in n)n[f].protectedKeys={};return d}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Ui()}}}function bf(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Ga(t,e):!1}function Et(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ui(){return{animate:Et(!0),whileInView:Et(),whileHover:Et(),whileTap:Et(),whileDrag:Et(),whileFocus:Et(),exit:Et()}}class Tt{constructor(t){this.isMounted=!1,this.node=t}update(){}}class vf extends Tt{constructor(t){super(t),t.animationState||(t.animationState=xf(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();xs(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let wf=0;class Sf extends Tt{constructor(){super(...arguments),this.id=wf++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Ya={animation:{Feature:vf},exit:{Feature:Sf}};function Ln(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function zn(e){return{point:{x:e.pageX,y:e.pageY}}}const Tf=e=>t=>Fr(t)&&e(t,zn(t));function Mn(e,t,n,s){return Ln(e,t,Tf(n),s)}const Ja=1e-4,Cf=1-Ja,jf=1+Ja,Za=.01,Pf=0-Za,Af=0+Za;function Me(e){return e.max-e.min}function Ef(e,t,n){return Math.abs(e-t)<=n}function zi(e,t,n,s=.5){e.origin=s,e.originPoint=he(t.min,t.max,e.origin),e.scale=Me(n)/Me(t),e.translate=he(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Cf&&e.scale<=jf||isNaN(e.scale))&&(e.scale=1),(e.translate>=Pf&&e.translate<=Af||isNaN(e.translate))&&(e.translate=0)}function kn(e,t,n,s){zi(e.x,t.x,n.x,s?s.originX:void 0),zi(e.y,t.y,n.y,s?s.originY:void 0)}function _i(e,t,n){e.min=n.min+t.min,e.max=e.min+Me(t)}function Mf(e,t,n){_i(e.x,t.x,n.x),_i(e.y,t.y,n.y)}function Xi(e,t,n){e.min=t.min-n.min,e.max=e.min+Me(t)}function Nn(e,t,n){Xi(e.x,t.x,n.x),Xi(e.y,t.y,n.y)}function $e(e){return[e("x"),e("y")]}const Qa=({current:e})=>e?e.ownerDocument.defaultView:null,Wi=(e,t)=>Math.abs(e-t);function kf(e,t){const n=Wi(e.x,t.x),s=Wi(e.y,t.y);return Math.sqrt(n**2+s**2)}class el{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const m=Os(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,b=kf(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!b)return;const{point:v}=m,{timestamp:T}=Se;this.history.push({...v,timestamp:T});const{onStart:w,onMove:M}=this.handlers;p||(w&&w(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),M&&M(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=Is(p,this.transformPagePoint),le.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:b,onSessionEnd:v,resumeAnimation:T}=this.handlers;if(this.dragSnapToOrigin&&T&&T(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=Os(m.type==="pointercancel"?this.lastMoveEventInfo:Is(p,this.transformPagePoint),this.history);this.startEvent&&b&&b(m,w),v&&v(m,w)},!Fr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=zn(t),l=Is(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=Se;this.history=[{...c,timestamp:d}];const{onSessionStart:f}=n;f&&f(t,Os(l,this.history)),this.removeListeners=Fn(Mn(this.contextWindow,"pointermove",this.handlePointerMove),Mn(this.contextWindow,"pointerup",this.handlePointerUp),Mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),wt(this.updatePoint)}}function Is(e,t){return t?{point:t(e.point)}:e}function qi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Os({point:e},t){return{point:e,delta:qi(e,tl(t)),offset:qi(e,Nf(t)),velocity:Rf(t,.1)}}function Nf(e){return e[0]}function tl(e){return e[e.length-1]}function Rf(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=tl(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Ke(t)));)n--;if(!s)return{x:0,y:0};const o=Fe(r.timestamp-s.timestamp);if(o===0)return{x:0,y:0};const i={x:(r.x-s.x)/o,y:(r.y-s.y)/o};return i.x===1/0&&(i.x=0),i.y===1/0&&(i.y=0),i}function Df(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?he(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?he(n,e,s.max):Math.min(e,n)),e}function Ki(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function Vf(e,{top:t,left:n,bottom:s,right:r}){return{x:Ki(e.x,n,r),y:Ki(e.y,t,s)}}function Gi(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function If(e,t){return{x:Gi(e.x,t.x),y:Gi(e.y,t.y)}}function Of(e,t){let n=.5;const s=Me(e),r=Me(t);return r>s?n=Dn(t.min,t.max-s,e.min):s>r&&(n=Dn(e.min,e.max-r,t.min)),at(0,1,n)}function $f(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const fr=.35;function Lf(e=fr){return e===!1?e=0:e===!0&&(e=fr),{x:Hi(e,"left","right"),y:Hi(e,"top","bottom")}}function Hi(e,t,n){return{min:Yi(e,t),max:Yi(e,n)}}function Yi(e,t){return typeof e=="number"?e:e[t]||0}const Ff=new WeakMap;class Bf{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ye(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=f=>{const{dragSnapToOrigin:m}=this.getProps();m?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(zn(f).point)},i=(f,m)=>{const{drag:p,dragPropagation:b,onDragStart:v}=this.getProps();if(p&&!b&&(this.openDragLock&&this.openDragLock(),this.openDragLock=qu(p),!this.openDragLock))return;this.latestPointerEvent=f,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),$e(w=>{let M=this.getAxisMotionValue(w).get()||0;if(et.test(M)){const{projection:E}=this.visualElement;if(E&&E.layout){const $=E.layout.layoutBox[w];$&&(M=Me($)*(parseFloat(M)/100))}}this.originPoint[w]=M}),v&&le.postRender(()=>v(f,m)),ur(this.visualElement,"transform");const{animationState:T}=this.visualElement;T&&T.setActive("whileDrag",!0)},a=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:b,onDirectionLock:v,onDrag:T}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:w}=m;if(b&&this.currentDirection===null){this.currentDirection=Uf(w),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",m.point,w),this.updateAxis("y",m.point,w),this.visualElement.render(),T&&T(f,m)},l=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m,this.stop(f,m),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>$e(f=>this.getAnimationState(f)==="paused"&&this.getAxisMotionValue(f).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new el(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Qa(this.visualElement)})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&le.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!ts(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=Df(i,this.constraints[t],this.elastic[t])),o.set(i)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&Ht(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Vf(s.layoutBox,t):this.constraints=!1,this.elastic=Lf(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&$e(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=$f(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Ht(t))return!1;const s=t.current;lt(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=_d(s,r.root,this.visualElement.getTransformPagePoint());let i=If(r.layout.layoutBox,o);if(n){const a=n(Bd(i));this.hasMutatedConstraints=!!a,a&&(i=Oa(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=$e(d=>{if(!ts(d,n,this.currentDirection))return;let f=l&&l[d]||{};i&&(f={min:0,max:0});const m=r?200:1e6,p=r?40:1e7,b={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...f};return this.startAxisValueAnimation(d,b)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return ur(this.visualElement,t),s.start(Yr(t,s,0,n,this.visualElement,!1))}stopAnimation(){$e(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){$e(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){$e(n=>{const{drag:s}=this.getProps();if(!ts(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(t[n]-he(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Ht(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};$e(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const l=a.get();r[i]=Of({min:l,max:l},this.constraints[i])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),$e(i=>{if(!ts(i,t,null))return;const a=this.getAxisMotionValue(i),{min:l,max:c}=this.constraints[i];a.set(he(l,c,r[i]))})}addListeners(){if(!this.visualElement.current)return;Ff.set(this.visualElement,this);const t=this.visualElement.current,n=Mn(t,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Ht(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,o=r.addEventListener("measure",s);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),le.read(s);const i=Ln(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&($e(d=>{const f=this.getAxisMotionValue(d);f&&(this.originPoint[d]+=l[d].translate,f.set(f.get()+l[d].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=fr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function ts(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Uf(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class zf extends Tt{constructor(t){super(t),this.removeGroupControls=Be,this.removeListeners=Be,this.controls=new Bf(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Be}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ji=e=>(t,n)=>{e&&le.postRender(()=>e(t,n))};class _f extends Tt{constructor(){super(...arguments),this.removePointerDownListener=Be}onPointerDown(t){this.session=new el(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Qa(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ji(t),onStart:Ji(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&le.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Mn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const cs={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Zi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Cn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(z.test(e))e=parseFloat(e);else return e;const n=Zi(e,t.target.x),s=Zi(e,t.target.y);return`${n}% ${s}%`}},Xf={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=St.parse(e);if(r.length>5)return s;const o=St.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=l;const c=he(a,l,.5);return typeof r[2+i]=="number"&&(r[2+i]/=c),typeof r[3+i]=="number"&&(r[3+i]/=c),o(r)}};let $s=!1;class Wf extends h.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;md(qf),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),$s&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),cs.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,$s=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||le.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Lr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;$s=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function nl(e){const[t,n]=Ta(),s=h.useContext(gr);return u.jsx(Wf,{...e,layoutGroup:s,switchLayoutGroup:h.useContext(Va),isPresent:t,safeToRemove:n})}const qf={borderRadius:{...Cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Cn,borderTopRightRadius:Cn,borderBottomLeftRadius:Cn,borderBottomRightRadius:Cn,boxShadow:Xf};function Kf(e,t,n){const s=je(e)?e:tn(e);return s.start(Yr("",s,t,n)),s.animation}const Gf=(e,t)=>e.depth-t.depth;class Hf{constructor(){this.children=[],this.isDirty=!1}add(t){br(this.children,t),this.isDirty=!0}remove(t){vr(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Gf),this.isDirty=!1,this.children.forEach(t)}}function Yf(e,t){const n=De.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(wt(s),e(o-t))};return le.setup(s,!0),()=>wt(s)}const sl=["TopLeft","TopRight","BottomLeft","BottomRight"],Jf=sl.length,Qi=e=>typeof e=="string"?parseFloat(e):e,eo=e=>typeof e=="number"||z.test(e);function Zf(e,t,n,s,r,o){r?(e.opacity=he(0,n.opacity??1,Qf(s)),e.opacityExit=he(t.opacity??1,0,eh(s))):o&&(e.opacity=he(t.opacity??1,n.opacity??1,s));for(let i=0;i<Jf;i++){const a=`border${sl[i]}Radius`;let l=to(t,a),c=to(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||eo(l)===eo(c)?(e[a]=Math.max(he(Qi(l),Qi(c),s),0),(et.test(c)||et.test(l))&&(e[a]+="%")):e[a]=c}(t.rotate||n.rotate)&&(e.rotate=he(t.rotate||0,n.rotate||0,s))}function to(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Qf=rl(0,.5,_o),eh=rl(.5,.95,Be);function rl(e,t,n){return s=>s<e?0:s>t?1:n(Dn(e,t,s))}function no(e,t){e.min=t.min,e.max=t.max}function Oe(e,t){no(e.x,t.x),no(e.y,t.y)}function so(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function ro(e,t,n,s,r){return e-=t,e=ms(e,1/n,s),r!==void 0&&(e=ms(e,1/r,s)),e}function th(e,t=0,n=1,s=.5,r,o=e,i=e){if(et.test(t)&&(t=parseFloat(t),t=he(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=he(o.min,o.max,s);e===o&&(a-=t),e.min=ro(e.min,t,n,a,r),e.max=ro(e.max,t,n,a,r)}function io(e,t,[n,s,r],o,i){th(e,t[n],t[s],t[r],t.scale,o,i)}const nh=["x","scaleX","originX"],sh=["y","scaleY","originY"];function oo(e,t,n,s){io(e.x,t,nh,n?n.x:void 0,s?s.x:void 0),io(e.y,t,sh,n?n.y:void 0,s?s.y:void 0)}function ao(e){return e.translate===0&&e.scale===1}function il(e){return ao(e.x)&&ao(e.y)}function lo(e,t){return e.min===t.min&&e.max===t.max}function rh(e,t){return lo(e.x,t.x)&&lo(e.y,t.y)}function co(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function ol(e,t){return co(e.x,t.x)&&co(e.y,t.y)}function uo(e){return Me(e.x)/Me(e.y)}function fo(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class ih{constructor(){this.members=[]}add(t){br(this.members,t),t.scheduleRender()}remove(t){if(vr(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.instance&&s.scheduleRender(),t.scheduleRender(),t.resumeFrom=s,n&&(t.resumeFrom.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:s}=t;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function oh(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:c,rotate:d,rotateX:f,rotateY:m,skewX:p,skewY:b}=n;c&&(s=`perspective(${c}px) ${s}`),d&&(s+=`rotate(${d}deg) `),f&&(s+=`rotateX(${f}deg) `),m&&(s+=`rotateY(${m}deg) `),p&&(s+=`skewX(${p}deg) `),b&&(s+=`skewY(${b}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const Ls=["","X","Y","Z"],ah=1e3;let lh=0;function Fs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function al(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Wa(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",le,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&al(s)}function ll({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=lh++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(dh),this.nodes.forEach(ph),this.nodes.forEach(gh),this.nodes.forEach(fh)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=i,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Hf)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Sr),this.eventHandlers.get(i).add(a)}notifyListeners(i,...a){const l=this.eventHandlers.get(i);l&&l.notify(...a)}hasListeners(i){return this.eventHandlers.has(i)}mount(i){if(this.instance)return;this.isSVG=Sa(i)&&!Zu(i),this.instance=i;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),e){let d,f=0;const m=()=>this.root.updateBlockedByResize=!1;le.read(()=>{f=window.innerWidth}),e(i,()=>{const p=window.innerWidth;p!==f&&(f=p,this.root.updateBlockedByResize=!0,d&&d(),d=Yf(m,250),cs.hasAnimatedSinceResize&&(cs.hasAnimatedSinceResize=!1,this.nodes.forEach(po)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:f,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const b=this.options.transition||c.getDefaultTransition()||wh,{onLayoutAnimationStart:v,onLayoutAnimationComplete:T}=c.getProps(),w=!this.targetLayout||!ol(this.targetLayout,p),M=!f&&m;if(this.options.layoutRoot||this.resumeFrom||M||f&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const E={...Or(b,"layout"),onPlay:v,onComplete:T};(c.shouldReduceMotion||this.options.layoutRoot)&&(E.delay=0,E.type=!1),this.startAnimation(E),this.setAnimationOrigin(d,M)}else f||po(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const i=this.getStack();i&&i.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),wt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(yh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&al(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const f=this.path[d];f.shouldResetTransform=!0,f.updateScroll("snapshot"),f.options.layoutRoot&&f.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(ho);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(mo);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(mh),this.nodes.forEach(ch),this.nodes.forEach(uh)):this.nodes.forEach(mo),this.clearAllSnapshots();const a=De.now();Se.delta=at(0,1e3/60,a-Se.timestamp),Se.timestamp=a,Se.isProcessing=!0,As.update.process(Se),As.preRender.process(Se),As.render.process(Se),Se.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Lr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(hh),this.sharedNodes.forEach(xh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,le.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){le.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Me(this.snapshot.measuredBox.x)&&!Me(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const i=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ye(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,i?i.layoutBox:void 0)}updateScroll(i="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===i&&(a=!1),a&&this.instance){const l=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!il(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;i&&this.instance&&(a||kt(this.latestValues)||d)&&(r(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),Sh(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ye();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Th))){const{scroll:c}=this.root;c&&(Yt(a.x,c.offset.x),Yt(a.y,c.offset.y))}return a}removeElementScroll(i){const a=ye();if(Oe(a,i),this.scroll?.wasRoot)return a;for(let l=0;l<this.path.length;l++){const c=this.path[l],{scroll:d,options:f}=c;c!==this.root&&d&&f.layoutScroll&&(d.wasRoot&&Oe(a,i),Yt(a.x,d.offset.x),Yt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=ye();Oe(l,i);for(let c=0;c<this.path.length;c++){const d=this.path[c];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&Jt(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),kt(d.latestValues)&&Jt(l,d.latestValues)}return kt(this.latestValues)&&Jt(l,this.latestValues),l}removeTransform(i){const a=ye();Oe(a,i);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!kt(c.latestValues))continue;or(c.latestValues)&&c.updateSnapshot();const d=ye(),f=c.measurePageBox();Oe(d,f),oo(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return kt(this.latestValues)&&oo(a,this.latestValues),a}setTargetDelta(i){this.targetDelta=i,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(i){this.options={...this.options,...i,crossfade:i.crossfade!==void 0?i.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Se.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(i||l&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:f}=this.options;if(!(!this.layout||!(d||f))){if(this.resolvedRelativeTargetAt=Se.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ye(),this.relativeTargetOrigin=ye(),Nn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Oe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ye(),this.targetWithTransforms=ye()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Mf(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Oe(this.target,this.layout.layoutBox),La(this.target,this.targetDelta)):Oe(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ye(),this.relativeTargetOrigin=ye(),Nn(this.relativeTargetOrigin,this.target,m.target),Oe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||or(this.parent.latestValues)||$a(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){const i=this.getLead(),a=!!this.resumingFrom||this!==i;let l=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Se.timestamp&&(l=!1),l)return;const{layout:c,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||d))return;Oe(this.layoutCorrected,this.layout.layoutBox);const f=this.treeScale.x,m=this.treeScale.y;zd(this.layoutCorrected,this.treeScale,this.path,a),i.layout&&!i.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(i.target=i.layout.layoutBox,i.targetWithTransforms=ye());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(so(this.prevProjectionDelta.x,this.projectionDelta.x),so(this.prevProjectionDelta.y,this.projectionDelta.y)),kn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==f||this.treeScale.y!==m||!fo(this.projectionDelta.x,this.prevProjectionDelta.x)||!fo(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(i=!0){if(this.options.visualElement?.scheduleRender(),i){const a=this.getStack();a&&a.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Zt(),this.projectionDelta=Zt(),this.projectionDeltaWithTransform=Zt()}setAnimationOrigin(i,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},f=Zt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ye(),p=l?l.source:void 0,b=this.layout?this.layout.source:void 0,v=p!==b,T=this.getStack(),w=!T||T.members.length<=1,M=!!(v&&!w&&this.options.crossfade===!0&&!this.path.some(vh));this.animationProgress=0;let E;this.mixTargetDelta=$=>{const D=$/1e3;go(f.x,i.x,D),go(f.y,i.y,D),this.setTargetDelta(f),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Nn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),bh(this.relativeTarget,this.relativeTargetOrigin,m,D),E&&rh(this.relativeTarget,E)&&(this.isProjectionDirty=!1),E||(E=ye()),Oe(E,this.relativeTarget)),v&&(this.animationValues=d,Zf(d,c,this.latestValues,D,M,w)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=D},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(wt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=le.update(()=>{cs.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=tn(0)),this.currentAnimation=Kf(this.motionValue,[0,1e3],{...i,velocity:0,isSync:!0,onUpdate:a=>{this.mixTargetDelta(a),i.onUpdate&&i.onUpdate(a)},onStop:()=>{},onComplete:()=>{i.onComplete&&i.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const i=this.getStack();i&&i.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(ah),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=i;if(!(!a||!l||!c)){if(this!==i&&this.layout&&c&&cl(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ye();const f=Me(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+f;const m=Me(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}Oe(a,l),Jt(a,d),kn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new ih),this.sharedNodes.get(i).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const i=this.getStack();return i?i.lead===this:!0}getLead(){const{layoutId:i}=this.options;return i?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:i}=this.options;return i?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:i}=this.options;if(i)return this.root.sharedNodes.get(i)}promote({needsReset:i,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),i&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const i=this.getStack();return i?i.relegate(this):!1}resetSkewAndRotation(){const{visualElement:i}=this.options;if(!i)return;let a=!1;const{latestValues:l}=i;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Fs("z",i,c,this.animationValues);for(let d=0;d<Ls.length;d++)Fs(`rotate${Ls[d]}`,i,c,this.animationValues),Fs(`skew${Ls[d]}`,i,c,this.animationValues);i.render();for(const d in c)i.setStaticValue(d,c[d]),this.animationValues&&(this.animationValues[d]=c[d]);i.scheduleRender()}applyProjectionStyles(i,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){i.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=as(a?.pointerEvents)||"",i.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(i.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,i.pointerEvents=as(a?.pointerEvents)||""),this.hasProjected&&!kt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let f=oh(this.projectionDeltaWithTransform,this.treeScale,d);l&&(f=l(d,f)),i.transform=f;const{x:m,y:p}=this.projectionDelta;i.transformOrigin=`${m.origin*100}% ${p.origin*100}% 0`,c.animationValues?i.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:i.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const b in $n){if(d[b]===void 0)continue;const{correct:v,applyTo:T,isCSSVariable:w}=$n[b],M=f==="none"?d[b]:v(d[b],c);if(T){const E=T.length;for(let $=0;$<E;$++)i[T[$]]=M}else w?this.options.visualElement.renderState.vars[b]=M:i[b]=M}this.options.layoutId&&(i.pointerEvents=c===this?as(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(ho),this.root.sharedNodes.clear()}}}function ch(e){e.updateLayout()}function uh(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?$e(d=>{const f=o?t.measuredBox[d]:t.layoutBox[d],m=Me(f);f.min=n[d].min,f.max=f.min+m}):cl(r,t.layoutBox,n)&&$e(d=>{const f=o?t.measuredBox[d]:t.layoutBox[d],m=Me(n[d]);f.max=f.min+m,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+m)});const i=Zt();kn(i,n,t.layoutBox);const a=Zt();o?kn(a,e.applyTransform(s,!0),t.measuredBox):kn(a,n,t.layoutBox);const l=!il(i);let c=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:m}=d;if(f&&m){const p=ye();Nn(p,t.layoutBox,f.layoutBox);const b=ye();Nn(b,n,m.layoutBox),ol(p,b)||(c=!0),d.options.layoutRoot&&(e.relativeTarget=b,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:c})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function dh(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function fh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function hh(e){e.clearSnapshot()}function ho(e){e.clearMeasurements()}function mo(e){e.isLayoutDirty=!1}function mh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function po(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function ph(e){e.resolveTargetDelta()}function gh(e){e.calcProjection()}function yh(e){e.resetSkewAndRotation()}function xh(e){e.removeLeadSnapshot()}function go(e,t,n){e.translate=he(t.translate,0,n),e.scale=he(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function yo(e,t,n,s){e.min=he(t.min,n.min,s),e.max=he(t.max,n.max,s)}function bh(e,t,n,s){yo(e.x,t.x,n.x,s),yo(e.y,t.y,n.y,s)}function vh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const wh={duration:.45,ease:[.4,0,.1,1]},xo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),bo=xo("applewebkit/")&&!xo("chrome/")?Math.round:Be;function vo(e){e.min=bo(e.min),e.max=bo(e.max)}function Sh(e){vo(e.x),vo(e.y)}function cl(e,t,n){return e==="position"||e==="preserve-aspect"&&!Ef(uo(t),uo(n),.2)}function Th(e){return e!==e.root&&e.scroll?.wasRoot}const Ch=ll({attachResizeListener:(e,t)=>Ln(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Bs={current:void 0},ul=ll({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Bs.current){const e=new Ch({});e.mount(window),e.setOptions({layoutScroll:!0}),Bs.current=e}return Bs.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),jh={pan:{Feature:_f},drag:{Feature:zf,ProjectionNode:ul,MeasureLayout:nl}};function wo(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&le.postRender(()=>o(t,zn(t)))}class Ph extends Tt{mount(){const{current:t}=this.node;t&&(this.unmount=Ku(t,(n,s)=>(wo(this.node,s,"Start"),r=>wo(this.node,r,"End"))))}unmount(){}}class Ah extends Tt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Fn(Ln(this.node.current,"focus",()=>this.onFocus()),Ln(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function So(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&le.postRender(()=>o(t,zn(t)))}class Eh extends Tt{mount(){const{current:t}=this.node;t&&(this.unmount=Ju(t,(n,s)=>(So(this.node,s,"Start"),(r,{success:o})=>So(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const hr=new WeakMap,Us=new WeakMap,Mh=e=>{const t=hr.get(e.target);t&&t(e)},kh=e=>{e.forEach(Mh)};function Nh({root:e,...t}){const n=e||document;Us.has(n)||Us.set(n,{});const s=Us.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(kh,{root:e,...t})),s[r]}function Rh(e,t,n){const s=Nh(t);return hr.set(e,n),s.observe(e),()=>{hr.delete(e),s.unobserve(e)}}const Dh={some:0,all:1};class Vh extends Tt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=t,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:Dh[r]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:f}=this.node.getProps(),m=c?d:f;m&&m(l)};return Rh(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Ih(t,n))&&this.startObserver()}unmount(){}}function Ih({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const dl={inView:{Feature:Vh},tap:{Feature:Eh},focus:{Feature:Ah},hover:{Feature:Ph}},Oh={layout:{ProjectionNode:ul,MeasureLayout:nl}},$h={...Ya,...dl,...jh,...Oh},Lh=Fd($h,Xa),Fh={renderer:Xa,...Ya,...dl};function Jr(e,t){return ls(e,t)}const Bh=Jr("button"),ns=Jr("div"),Uh=Jr("p");function zh({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return u.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:u.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&u.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>u.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[u.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),u.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),u.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[u.jsxs(Pe,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[u.jsx(se.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),u.jsx(Pe,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:u.jsx(se.X,{className:"h-3 w-3"})})]})]})})}function _h({toolName:e,args:t,isDenied:n,isSafe:s}){const[r,o]=h.useState(!1);if(e==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];e==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(t).filter(([c])=>!i.includes(c))),l=Object.keys(a).length>0;return u.jsxs("div",{className:"my-1",children:[u.jsxs("button",{onClick:()=>l&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors bg-muted text-muted-foreground ${l?"cursor-pointer hover:bg-muted/80":""}`,children:[l&&u.jsx("span",{className:"transition-transform duration-200",children:r?u.jsx(se.ChevronDown,{className:"h-3 w-3"}):u.jsx(se.ChevronRight,{className:"h-3 w-3"})}),n?u.jsx(se.X,{className:"h-3 w-3"}):s?u.jsx(se.Zap,{className:"h-3 w-3"}):u.jsx(se.Check,{className:"h-3 w-3"}),u.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&l&&u.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:u.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([c,d])=>u.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[u.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[c,":"]}),u.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},c))})})]})}function Xh({...e}){return u.jsx(mr.Root,{"data-slot":"collapsible",...e})}function Wh({...e}){return u.jsx(mr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function qh({...e}){return u.jsx(mr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const Kh=h.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Zr=h.memo(({className:e,...t})=>typeof window>"u"?null:u.jsx(h.Suspense,{fallback:null,children:u.jsx(Kh,{className:ie("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Zr.displayName="Response";const Gh=Object.freeze(Object.defineProperty({__proto__:null,Response:Zr},Symbol.toStringTag,{value:"Module"})),Hh=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=Lh.create(t),i=h.useMemo(()=>(e?.length??0)*r,[e,r]);return u.jsx(o,{animate:{backgroundPosition:"0% center"},className:ie("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},Yh=h.memo(Hh),fl=h.createContext(null),Jh=()=>{const e=h.useContext(fl);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Zh=1e3,Qh=1e3,hl=h.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,c]=ii.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,f]=ii.useControllableState({prop:o,defaultProp:0}),[m,p]=h.useState(!1),[b,v]=h.useState(null);h.useEffect(()=>{t?b===null&&v(Date.now()):b!==null&&(f(Math.ceil((Date.now()-b)/Qh)),v(null))},[t,b,f]),h.useEffect(()=>{if(s&&!t&&l&&!m){const w=setTimeout(()=>{c(!1),p(!0)},Zh);return()=>clearTimeout(w)}},[t,l,s,c,m]);const T=w=>{c(w)};return u.jsx(fl.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:c,duration:d},children:u.jsx(Xh,{className:ie("not-prose mb-4",e),onOpenChange:T,open:l,...a,children:i})})}),em=(e,t)=>e||t===0?u.jsx(Yh,{duration:1,children:"Thinking..."}):t===void 0?u.jsx("p",{children:"Thought for a few seconds"}):u.jsxs("p",{children:["Thought for ",t," seconds"]}),ml=h.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Jh();return u.jsx(Wh,{className:ie("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??u.jsxs(u.Fragment,{children:[u.jsx(se.BrainIcon,{className:"size-4"}),em(s,o),u.jsx(se.ChevronDownIcon,{className:ie("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),pl=h.memo(({className:e,children:t,...n})=>u.jsx(qh,{className:ie("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...n,children:u.jsx(Zr,{className:"grid gap-2",children:t})}));hl.displayName="Reasoning";ml.displayName="ReasoningTrigger";pl.displayName="ReasoningContent";function To(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function tm({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=To(s.domain);return u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsxs("button",{className:ie("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[u.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),u.jsx("span",{className:"leading-none",children:s.domain})]})}),u.jsx(bt,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:u.jsxs("div",{className:"space-y-1.5",children:[u.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",e.length]}),e.map(o=>{const i=o.title||o.domain;return u.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:ie("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:a=>a.stopPropagation(),children:[u.jsx("img",{src:To(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const l=a.target;l.style.display="none"}}),u.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function nm({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:l=!0}){const c=h.useRef(null),[d,f]=h.useState([]);h.useEffect(()=>{if(!a||!c.current||t.length===0||n.size===0){(n.size===0||!a)&&f([]);return}const T=c.current;let w,M=!1;const E=new WeakSet,$=()=>{if(!c.current||M)return;M=!0;const I=c.current,k=/\[(\d+)\]/g,j=document.createTreeWalker(I,NodeFilter.SHOW_TEXT,null),V=[];let A;for(;A=j.nextNode();)if(A.nodeType===Node.TEXT_NODE&&!E.has(A)){const L=A,O=L.textContent||"";let F=L.parentElement,X=!1;for(;F&&F!==I;){if(F.tagName==="A"||F.tagName==="CODE"||F.tagName==="PRE"){X=!0;break}F=F.parentElement}if(!X){const K=Array.from(O.matchAll(k)).filter(oe=>{if(!oe[1])return!1;const be=parseInt(oe[1],10);return n.has(be)});K.length>0&&V.push({node:L,matches:K})}}if(V.length===0){M=!1;return}const N=[];V.forEach(({node:L,matches:O})=>{E.add(L);const F=L.textContent||"",X=document.createDocumentFragment();let G=0;O.forEach(K=>{if(!K[1])return;K.index!==void 0&&K.index>G&&X.appendChild(document.createTextNode(F.slice(G,K.index)));const oe=document.createElement("span");oe.className="inline-flex items-center citation-button-container";const be=parseInt(K[1],10);oe.setAttribute("data-citation",K[1]),X.appendChild(oe),N.push({element:oe,citationNum:be}),G=(K.index||0)+K[0].length}),G<F.length&&X.appendChild(document.createTextNode(F.slice(G))),L.parentNode&&L.parentNode.replaceChild(X,L)}),N.length>0&&f(L=>{const O=new Set(L.map(G=>G.element)),F=L.filter(G=>G.element.isConnected),X=N.filter(G=>!O.has(G.element));return[...F,...X]}),M=!1},D=new MutationObserver(()=>{clearTimeout(w),w=setTimeout($,100)});return D.observe(T,{childList:!0,subtree:!0,characterData:!0}),w=setTimeout($,200),()=>{D.disconnect(),clearTimeout(w)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(T){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(T)}&sz=16`}function b(T){try{return new URL(T).hostname.replace(/^www\./,"")}catch{return T}}const v=a&&l&&m?u.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[u.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),u.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((T,w)=>{const M=T.title||T.baseUrl,E=b(T.url),$=p(E);return u.jsxs("a",{href:T.url,target:"_blank",rel:"noopener noreferrer",className:ie("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[u.jsx("img",{src:$,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:D=>{const I=D.target;I.style.display="none"}}),u.jsx("span",{className:"leading-none",children:M})]},`group-${w}`)}):Array.from(n.entries()).sort(([T],[w])=>T-w).map(([T,w])=>{const M=b(w),E=p(M);return u.jsxs("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:ie("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[u.jsx("img",{src:E,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:$=>{const D=$.target;D.style.display="none"}}),u.jsx("span",{className:"leading-none",children:w})]},T)})})]}):null;return u.jsxs("div",{className:i,children:[u.jsx("div",{ref:c,children:u.jsx(o,{children:e})}),a&&d.filter(({element:T})=>T.isConnected).map(({element:T,citationNum:w},M)=>{if(!t.find(D=>D.number===w))return null;const $=Array.from(new Map(t.map(D=>{const I=D.url.replace(/\/+$/,""),k=s?.find(j=>j.url.replace(/\/+$/,"")===I);return[I,{number:D.number,url:D.url,domain:b(D.url),title:k?.title}]})).values());return Vl.createPortal(u.jsx(tm,{sources:$,citationNumber:w},`citation-${w}-${T}`),T,`citation-${w}-${M}`)}),v]})}function ln({...e}){return u.jsx(It.Root,{"data-slot":"dialog",...e})}function sm({...e}){return u.jsx(It.Portal,{"data-slot":"dialog-portal",...e})}function rm({className:e,...t}){return u.jsx(It.Overlay,{"data-slot":"dialog-overlay",className:ie("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function cn({className:e,children:t,showCloseButton:n=!0,...s}){return u.jsxs(sm,{"data-slot":"dialog-portal",children:[u.jsx(rm,{}),u.jsxs(It.Content,{"data-slot":"dialog-content",className:ie("bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...s,children:[t,n&&u.jsxs(It.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[u.jsx(se.XIcon,{}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function un({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-header",className:ie("flex flex-col gap-2 text-center sm:text-left",e),...t})}function dn({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-footer",className:ie("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function fn({className:e,...t}){return u.jsx(It.Title,{"data-slot":"dialog-title",className:ie("text-lg leading-none font-semibold",e),...t})}function hn({className:e,...t}){return u.jsx(It.Description,{"data-slot":"dialog-description",className:ie("text-muted-foreground text-sm",e),...t})}function mn({className:e,type:t,...n}){return u.jsx("input",{type:t,"data-slot":"input",className:ie("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-white px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...n})}function im({isOpen:e,title:t="Password Required",description:n="Please enter your password to continue",placeholder:s="Enter password...",onComplete:r}){const[o,i]=h.useState(""),[a,l]=h.useState(!1),[c,d]=h.useState(!1),f=async p=>{if(p.preventDefault(),!!o.trim()){d(!0);try{r(o)}finally{d(!1)}}},m=()=>{i(""),r(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:f,children:[u.jsxs(un,{children:[u.jsx(fn,{children:t}),u.jsx(hn,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsxs("div",{className:"relative",children:[u.jsx(mn,{type:a?"text":"password",value:o,onChange:p=>i(p.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:c}),u.jsx("button",{type:"button",onClick:()=>l(!a),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:c,children:a?u.jsx(se.EyeOff,{className:"h-4 w-4"}):u.jsx(se.Eye,{className:"h-4 w-4"})})]})}),u.jsxs(dn,{children:[u.jsx(Pe,{type:"button",variant:"ghost",onClick:m,disabled:c,children:"Cancel"}),u.jsx(Pe,{type:"submit",disabled:!o.trim()||c,children:c?"Submitting...":"Submit"})]})]})})})}function om({isOpen:e,title:t="Email Required",description:n="Please enter your email address",placeholder:s="Enter email address...",onComplete:r}){const[o,i]=h.useState(""),[a,l]=h.useState(!0),[c,d]=h.useState(!1),f=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),m=v=>{i(v),v.trim()?l(f(v)):l(!0)},p=async v=>{if(v.preventDefault(),!o.trim()||!f(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},b=()=>{i(""),l(!0),r(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:p,children:[u.jsxs(un,{children:[u.jsxs(fn,{className:"flex items-center gap-2",children:[u.jsx(se.Mail,{className:"h-5 w-5"}),t]}),u.jsx(hn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(mn,{type:"email",value:o,onChange:v=>m(v.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:c}),!a&&u.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),u.jsxs(dn,{children:[u.jsx(Pe,{type:"button",variant:"ghost",onClick:b,disabled:c,children:"Cancel"}),u.jsx(Pe,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function am({isOpen:e,title:t="Phone Number Required",description:n="Please enter your phone number",placeholder:s="Enter phone number...",onComplete:r}){const[o,i]=h.useState(""),[a,l]=h.useState(!0),[c,d]=h.useState(!1),f=T=>{const w=T.replace(/\D/g,"");return w.length<=3?w:w.length<=6?`(${w.slice(0,3)}) ${w.slice(3)}`:`(${w.slice(0,3)}) ${w.slice(3,6)}-${w.slice(6,10)}`},m=T=>T.replace(/\D/g,"").length===10,p=T=>{const w=f(T);i(w),w.trim()?l(m(w)):l(!0)},b=async T=>{if(T.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const w=o.replace(/\D/g,"");r(w)}finally{d(!1)}},v=()=>{i(""),l(!0),r(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:b,children:[u.jsxs(un,{children:[u.jsxs(fn,{className:"flex items-center gap-2",children:[u.jsx(se.Phone,{className:"h-5 w-5"}),t]}),u.jsx(hn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(mn,{type:"tel",value:o,onChange:T=>p(T.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:c}),!a&&u.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),u.jsxs(dn,{children:[u.jsx(Pe,{type:"button",variant:"ghost",onClick:v,disabled:c,children:"Cancel"}),u.jsx(Pe,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function lm({isOpen:e,title:t="PIN Required",description:n="Please enter your PIN",placeholder:s="Enter PIN...",length:r=4,onComplete:o}){const[i,a]=h.useState(""),[l,c]=h.useState(!1),d=p=>{const b=p.replace(/\D/g,"");a(b.slice(0,r))},f=async p=>{if(p.preventDefault(),i.length===r){c(!0);try{o(i)}finally{c(!1)}}},m=()=>{a(""),o(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:f,children:[u.jsxs(un,{children:[u.jsxs(fn,{className:"flex items-center gap-2",children:[u.jsx(se.Shield,{className:"h-5 w-5"}),t]}),u.jsx(hn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(mn,{type:"password",value:i,onChange:p=>d(p.target.value),placeholder:s,className:"text-center text-lg tracking-widest",maxLength:r,autoFocus:!0,disabled:l}),u.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),u.jsxs(dn,{children:[u.jsx(Pe,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),u.jsx(Pe,{type:"submit",disabled:i.length!==r||l,children:l?"Submitting...":"Submit"})]})]})})})}function zs({isOpen:e,title:t="Secure Input Required",description:n="Please enter the requested information",placeholder:s="Enter value...",type:r="password",onComplete:o}){const[i,a]=h.useState(""),[l,c]=h.useState(!1),d=async m=>{if(m.preventDefault(),!!i.trim()){c(!0);try{o(i)}finally{c(!1)}}},f=()=>{a(""),o(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:d,children:[u.jsxs(un,{children:[u.jsxs(fn,{className:"flex items-center gap-2",children:[u.jsx(se.Lock,{className:"h-5 w-5"}),t]}),u.jsx(hn,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsx(mn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),u.jsxs(dn,{children:[u.jsx(Pe,{type:"button",variant:"ghost",onClick:f,disabled:l,children:"Cancel"}),u.jsx(Pe,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function cm({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,l]=h.useState(()=>{const A={};return s.forEach(N=>{A[N.name]=N.value||""}),A}),[c,d]=h.useState({}),[f,m]=h.useState({}),[p,b]=h.useState(!1),v=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)?null:"Please enter a valid email address",T=A=>A.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",w=(A,N=4)=>A.length===N?null:`PIN must be ${N} digits`,M=A=>{const N=A.replace(/\D/g,"");return N.length<=3?N:N.length<=6?`(${N.slice(0,3)}) ${N.slice(3)}`:`(${N.slice(0,3)}) ${N.slice(3,6)}-${N.slice(6,10)}`},E=(A,N,L)=>{let O=N,F=null;switch(L.type){case"phone":O=M(N),O.trim()&&(F=T(O));break;case"email":N.trim()&&(F=v(N));break;case"pin":O=N.replace(/\D/g,"").slice(0,6),O.trim()&&(F=w(O));break}!F&&L.validation&&O.trim()&&(F=L.validation(O)),l(X=>({...X,[A]:O})),d(X=>({...X,[A]:F||""}))},$=()=>{const A={};let N=!0;return s.forEach(L=>{const O=a[L.name]||"";let F=null;if(L.required&&!O.trim())F=`${L.label} is required`;else if(O.trim()){switch(L.type){case"email":F=v(O);break;case"phone":F=T(O);break;case"pin":F=w(O);break}!F&&L.validation&&(F=L.validation(O))}F&&(A[L.name]=F,N=!1)}),d(A),N},D=async A=>{if(A.preventDefault(),!!$()){b(!0);try{const N={};s.forEach(L=>{const O=a[L.name]?.trim();O&&(L.type==="phone"?N[L.name]=O.replace(/\D/g,""):N[L.name]=O)}),r(N)}finally{b(!1)}}},I=()=>{l({}),d({}),m({}),r(null)},k=A=>{m(N=>({...N,[A]:!N[A]}))},j=A=>{switch(A.type){case"password":return f[A.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},V=A=>{if(A.placeholder)return A.placeholder;switch(A.type){case"email":return"Enter email address...";case"phone":return"Enter phone number...";case"password":return"Enter password...";case"pin":return"Enter PIN...";case"ssn":return"XXX-XX-XXXX";case"creditCard":return"XXXX XXXX XXXX XXXX";default:return`Enter ${A.label.toLowerCase()}...`}};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,className:"max-w-md",children:u.jsxs("form",{onSubmit:D,children:[u.jsxs(un,{children:[u.jsx(fn,{children:t}),n&&u.jsx(hn,{children:n})]}),u.jsx("div",{className:"py-4 space-y-4",children:s.map(A=>u.jsxs("div",{children:[u.jsxs("label",{className:"block text-sm font-medium mb-1",children:[A.label,A.required&&u.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),u.jsxs("div",{className:"relative",children:[u.jsx(mn,{type:j(A),value:a[A.name]||"",onChange:N=>E(A.name,N.target.value,A),placeholder:V(A),className:c[A.name]?"border-red-500":"",disabled:p,autoFocus:A===s[0],maxLength:A.type==="pin"?6:A.type==="phone"?14:void 0}),A.type==="password"&&u.jsx("button",{type:"button",onClick:()=>k(A.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:f[A.name]?u.jsx(se.EyeOff,{className:"h-4 w-4"}):u.jsx(se.Eye,{className:"h-4 w-4"})})]}),c[A.name]&&u.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[u.jsx(se.AlertCircle,{className:"h-3 w-3"}),c[A.name]]})]},A.name))}),u.jsxs(dn,{children:[u.jsx(Pe,{type:"button",variant:"ghost",onClick:I,disabled:p,children:i}),u.jsx(Pe,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const gl=h.createContext(void 0);function yl(){const e=h.useContext(gl);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function xl({children:e}){const[t,n]=h.useState(null),[s,r]=h.useState(null),o=h.useRef(null),i=h.useRef(null),a=h.useCallback(p=>new Promise(b=>{n(p),o.current=b}),[]),l=h.useCallback(p=>new Promise(b=>{r(p),i.current=b}),[]),c=h.useCallback(p=>{o.current&&(o.current(p),o.current=null),n(null)},[]),d=h.useCallback(p=>{i.current&&(i.current(p),i.current=null),r(null)},[]),f=()=>{if(s){const b=s.fields.map(v=>({name:v.name,type:v.type==="text"?"text":v.type==="password"?"password":v.type==="email"?"email":v.type==="phone"?"phone":v.type==="pin"?"pin":v.type==="ssn"?"ssn":v.type==="creditCard"?"creditCard":"text",label:v.label,placeholder:v.placeholder,required:v.required!==!1,value:v.value}));return u.jsx(cm,{isOpen:!0,title:s.title,description:s.description,fields:b,onComplete:d})}if(!t)return null;const p={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:c};switch(t.type){case"password":return u.jsx(im,{...p});case"email":return u.jsx(om,{...p});case"phone":return u.jsx(am,{...p});case"pin":return u.jsx(lm,{...p});case"ssn":return u.jsx(zs,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return u.jsx(zs,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return u.jsx(zs,{...p})}},m=h.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return u.jsxs(gl.Provider,{value:m,children:[e,f()]})}function um(e){try{const t=new URL(e),n=`${t.protocol}//${t.host}${t.pathname}`,s=t.hash?t.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const t=e.indexOf("#");return t!==-1?{baseUrl:e.substring(0,t),anchor:e.substring(t+1)}:{baseUrl:e}}}function dm(e){try{const t=new URL(e),s=t.pathname.split("/").filter(a=>a.length>0);if(s.length===0)return t.hostname;const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||t.hostname}catch{const t=e.indexOf("#"),n=t!==-1?e.substring(0,t):e,s=n.split("/").filter(r=>r.length>0);if(s.length>0){const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||n}return n}}function Co(e){let t=e.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=t.match(n),r=new Map,o=[],i=new Map,a=new Map,l=new Map,c=new Map;if(s&&s[1]){const j=s[1],V=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let A;for(;(A=V.exec(j))!==null;)if(A[1]&&A[2]){const N=parseInt(A[1],10),L=A[2].replace(/[.,;:!?]+$/,""),O=L.replace(/\/+$/,"");if(a.has(O)||a.set(O,L),i.has(O)||i.set(O,[]),i.get(O).push(N),!l.has(O))l.set(O,N);else{const F=l.get(O);N<F&&l.set(O,N)}}for(const[N,L]of i.entries()){const O=l.get(N);for(const F of L)F!==O&&c.set(F,O)}for(const[N,L]of l.entries()){const O=a.get(N)||N;r.set(L,O),o.push({number:L,url:O})}}let d,f=t;s&&s[0]&&(d=s[0],f=t.replace(n,""));const m=[];let p=0;const b=/```[\s\S]*?```|`[^`]+`/g;let v;for(;(v=b.exec(f))!==null;)v.index>p&&m.push({type:"text",content:f.slice(p,v.index),start:p,end:v.index}),m.push({type:"code",content:v[0],start:v.index,end:v.index+v[0].length}),p=v.index+v[0].length;p<f.length&&m.push({type:"text",content:f.slice(p),start:p,end:f.length});const T=m.map(j=>{if(j.type==="code")return j.content;let V=j.content;return V=V.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(N,L,O)=>{const F=parseInt(L,10),X=O.replace(/\/+$/,""),G=c.get(F)||F;return l.has(X)||(l.set(X,G),r.has(G)||(r.set(G,O),o.push({number:G,url:O}))),`[${G}]`}),V=V.replace(/\[(\d+)\]/g,(N,L)=>{const O=parseInt(L,10);return`[${c.get(O)||O}]`}),V}),w=[];for(const[j,V]of l.entries()){const A=a.get(j)||j,{baseUrl:N,anchor:L}=um(A),O=dm(A);w.push({url:A,baseUrl:N,numbers:[V],anchor:L,title:O})}w.sort((j,V)=>(j.numbers[0]||0)-(V.numbers[0]||0));const M=new Map;let E=1;for(const j of w){const V=j.numbers[0];M.set(V,E),j.numbers=[E],E++}const $=new Map;for(const[j,V]of r.entries()){const A=M.get(j);A&&$.set(A,V)}const D=o.map(j=>{const V=M.get(j.number);return V?{number:V,url:j.url}:j}).filter(j=>M.has(j.number)),I=Array.from(M.entries()).sort((j,V)=>V[0]-j[0]);let k=T.join("");for(const[j,V]of I){const A=new RegExp(`\\[${j}\\](?!\\d)`,"g");k=k.replace(A,`[${V}]`)}return{processedText:k,citations:D.sort((j,V)=>j.number-V.number),citationMap:$,groupedCitations:w,referencesText:d}}function Rn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Rn(t)}catch{return e}if(Array.isArray(e))return e.map(Rn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Rn(s);return t}return e}function _s(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Rn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Rn(e):{}}function fm({theme:e="auto",layout:t="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:l=800,initiallyExpanded:c=!1,tools:d=[],safeTools:f=[],safeToolNames:m,toolMetadata:p,systemPrompt:b="",agentId:v,agentName:T,tokenEndpoint:w="/api/arcten/token",apiBaseUrl:M="https://api.arcten.com",user:E,state:$,onStateChange:D,allowStateEdits:I=!0,sources:k,ragConfig:j,showCitations:V=!0,sensitiveParams:A,autoDetectSensitive:N=!1}){const L=M.replace(/\/+$/,""),{showSecureModal:O}=yl(),F=ko({apiBaseUrl:L,tokenEndpoint:w,user:E,tools:d,safeTools:f,toolMetadata:p,sensitiveParams:A,autoDetectSensitive:N,agentId:v,agentName:T,state:$,onStateChange:D,allowStateEdits:I,sources:k,ragConfig:j});h.useMemo(()=>j!==void 0?j:k&&k.length>0?{enabled:!0,organizationId:k[0],autoExecute:!0,filters:void 0}:{enabled:!1},[k,j]);const[X,G]=h.useState(c),[K,oe]=h.useState(i),[be,Ge]=h.useState(600),[Ct,tt]=h.useState(!1),[H,Ot]=h.useState(!1),[ke,jt]=h.useState(!1),[Ae,Ue]=h.useState({x:100,y:100}),[$t,ae]=h.useState(!1),[pn,ut]=h.useState({x:0,y:0}),[dt,gn]=h.useState(!1),ze=h.useRef(null),Pt=h.useRef(null),[At,Ve]=h.useState(""),[yn,vs]=h.useState(null),[Lt,Ft]=h.useState("Thinking..."),[ft,Ie]=h.useState(new Set),[Qr,_n]=h.useState(""),[He,Xn]=h.useState([]),ws=h.useRef(new Map),Bt=h.useRef(!1),xn=h.useRef(""),[Ut,ce]=h.useState(!1),[Ye,nt]=h.useState(!1),me=h.useMemo(()=>[...d,...f],[d,f]),_e=h.useMemo(()=>pr(me,p),[me,p]),bn=h.useMemo(()=>{const C=new Map,U=new Map(_e.map(W=>[W.name,W]));return me.forEach(W=>{const Z=W[Le];if(Z){const te=U.get(Z);if(te){C.set(te.name,W);return}}const Y=_e.find(te=>te.name===W.name);Y&&C.set(Y.name,W)}),C},[me,_e]),ht=h.useMemo(()=>{const C=new Set,U=new Map(_e.map(W=>[W.name,W]));return f.forEach(W=>{const Z=W[Le];if(Z&&U.has(Z))C.add(Z);else{const Y=_e.find(te=>te.name===W.name);Y&&C.add(Y.name)}}),m&&Array.isArray(m)&&m.forEach(W=>{typeof W=="string"&&C.add(W)}),C},[f,_e,m]),Wn=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];h.useEffect(()=>{if(typeof window<"u"){const C=localStorage.getItem("arcten-sidebar-expanded");C&&G(JSON.parse(C));const U=localStorage.getItem("arcten-sidebar-width");U&&oe(parseInt(U));const W=localStorage.getItem("arcten-sidebar-height");W&&Ge(parseInt(W));const Z=localStorage.getItem("arcten-sidebar-detached");Z&&Ot(JSON.parse(Z));const Y=localStorage.getItem("arcten-sidebar-position");if(Y){const Re=JSON.parse(Y),re=50,Te=Math.max(re-i,Math.min(Re.x,window.innerWidth-re)),_=Math.max(0,Math.min(Re.y,window.innerHeight-re));Ue({x:Te,y:_})}const te=localStorage.getItem("arcten-sidebar-minimized");te&&jt(JSON.parse(te)),gn(!0)}},[]),h.useMemo(()=>E,[E?.id]),h.useEffect(()=>{(async()=>{if(me.length===0)return;const U=me.map(W=>`${W.name}:${W.toString()}`).join("|");if(U!==xn.current&&!Bt.current){Bt.current=!0,xn.current=U;try{const W=me.map(Y=>({name:Y.name,code:Y.toString()})),Z=await fetch(`${L}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:W})});if(Z.ok){const Y=await Z.json();Y.tools&&Y.tools.forEach(te=>{ws.current.set(te.name,te)}),Xn(Y.tools)}}catch(W){console.error("Failed to fetch tool descriptions:",W)}finally{Bt.current=!1}}})()},[me,L]),h.useEffect(()=>{Promise.resolve().then(()=>Gh).then(C=>{vs(()=>C.Response)})},[]),h.useEffect(()=>{const C=()=>{_n(window.location.pathname)};C(),window.addEventListener("popstate",C);const U=setInterval(C,500);return()=>{window.removeEventListener("popstate",C),clearInterval(U)}},[]);const{id:vn,messages:Ne,sendMessage:wn,status:we,error:st,stop:zt,addToolOutput:rt,setMessages:ei,clientToken:Ss,tokenError:_t,conversations:Sn,isLoadingConversations:mt,loadConversation:it,deleteConversation:Xt,startNewConversation:Xe}=F;h.useEffect(()=>{X&&Pt.current&&Pt.current.focus()},[X,Ne]),h.useEffect(()=>{const C=Ne[Ne.length-1];if(!C||C.role!=="assistant")return;const U=C.parts?.filter(W=>W.type?.startsWith("tool-")&&W.state==="input-available"&&typeof W.toolCallId=="string"&&W.input!==void 0)||[];for(const W of U){const Z=W,Y=Z.type?.replace("tool-","")||"",te=Z.toolCallId;if(ht.has(Y)){if(ft.has(te))continue;Ie(re=>re.has(te)?re:new Set(re).add(te)),(async()=>{try{const re=bn.get(Y);if(!re){console.warn(`[ArctenAgent] Tool ${Y} not found in toolsMap`),rt({toolCallId:te,tool:Y,output:`Error: Tool ${Y} not found`}),Ie(J=>{const Ee=new Set(J);return Ee.delete(te),Ee});return}const Te=_s(Z.input),_=_e.find(J=>J.name===Y);let pe;if(_&&_.jsonSchema?.properties){const Ee=Object.keys(_.jsonSchema.properties).map(ge=>Te[ge]);pe=await re(...Ee)}else pe=await re(...Object.values(Te));rt({toolCallId:te,tool:Y,output:pe}),Ie(J=>{const Ee=new Set(J);return Ee.delete(te),Ee})}catch(re){console.error(`[ArctenAgent] Error executing safe tool ${Y}:`,re),rt({toolCallId:te,tool:Y,output:`Error: ${re instanceof Error?re.message:String(re)}`}),Ie(Te=>{const _=new Set(Te);return _.delete(te),_})}})()}}},[Ne,ht,bn,_e,rt,ft]);function Je(){G(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function qn(){G(!1),localStorage.setItem("arcten-sidebar-expanded","false")}h.useEffect(()=>{},[X]),h.useEffect(()=>{ze.current&&ze.current.scrollIntoView({behavior:"smooth"})},[Ne]),h.useEffect(()=>{function C(U){U.key==="Escape"&&(we==="streaming"||we==="submitted")&&(U.preventDefault(),zt())}return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[we,zt]);function Kn(C){const U=Math.floor((Date.now()-C)/1e3);return U<60?"now":U<3600?`${Math.floor(U/60)}m`:U<86400?`${Math.floor(U/3600)}h`:`${Math.floor(U/86400)}d`}function ot(){Xe(),nt(!1)}function pt(C){if(C.preventDefault(),!At.trim())return;(we==="streaming"||we==="submitted")&&zt();const U=Wn[Math.floor(Math.random()*Wn.length)]||"Thinking...";Ft(U),wn({text:At}),Ve("")}function Gn(C){const U=C.target.value;Ve(U)}h.useEffect(()=>{if(!Ct)return;function C(W){if(H){const Z=W.clientX-Ae.x,Y=W.clientY-Ae.y;Z>=a&&Z<=l&&oe(Z),Y>=400&&Y<=1e3&&Ge(Y)}else{const Z=window.innerWidth-W.clientX;Z>=a&&Z<=l&&oe(Z)}}function U(){tt(!1),localStorage.setItem("arcten-sidebar-width",K.toString()),localStorage.setItem("arcten-sidebar-height",be.toString())}return window.addEventListener("mousemove",C),window.addEventListener("mouseup",U),()=>{window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",U)}},[Ct,K,be,H,Ae,a,l]);function Hn(C){C.preventDefault(),tt(!0)}function gt(){Ot(!0),jt(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Wt(){Ot(!1),jt(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Yn(){jt(!ke),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!ke))}function Tn(C){H&&(ae(!0),ut({x:C.clientX-Ae.x,y:C.clientY-Ae.y}))}return h.useEffect(()=>{if(!H)return;function C(){Ue(U=>{const Z=window.innerWidth-50,Y=window.innerHeight-50,te=50-K,Re=0,re=Math.max(te,Math.min(U.x,Z)),Te=Math.max(Re,Math.min(U.y,Y));if(re!==U.x||Te!==U.y){const _={x:re,y:Te};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(_)),_}return U})}return window.addEventListener("resize",C),()=>window.removeEventListener("resize",C)},[H,K]),h.useEffect(()=>{if(!$t)return;function C(W){const Z=W.clientX-pn.x,Y=W.clientY-pn.y,te=50,Re=window.innerWidth-te,re=window.innerHeight-te,Te=te-K,_=0,pe=Math.max(Te,Math.min(Z,Re)),J=Math.max(_,Math.min(Y,re));Ue({x:pe,y:J})}function U(){ae(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(Ae))}return window.addEventListener("mousemove",C),window.addEventListener("mouseup",U),()=>{window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",U)}},[$t,pn,Ae,K]),dt?_t?u.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:u.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",_t]})}):Ss?u.jsx(ld,{features:Fh,children:u.jsx(ns,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:H?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:H?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
|
|
10
|
+
`),()=>{T.contains(v)&&T.removeChild(v)}},[t]),u.jsx(nd,{isPresent:t,childRef:o,sizeRef:i,children:Ke.cloneElement(e,{ref:l})})}const rd=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const c=yr(id),d=h.useId();let f=!0,m=h.useMemo(()=>(f=!1,{id:d,initial:t,isPresent:n,custom:r,onExitComplete:p=>{c.set(p,!0);for(const b of c.values())if(!b)return;s&&s()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[n,c,s]);return o&&f&&(m={...m}),h.useMemo(()=>{c.forEach((p,b)=>c.set(b,!1))},[n]),Ke.useEffect(()=>{!n&&!c.size&&s&&s()},[n]),i==="popLayout"&&(e=u.jsx(sd,{isPresent:n,anchorX:a,root:l,children:e})),u.jsx(gs.Provider,{value:m,children:e})};function id(){return new Map}function Ta(e=!0){const t=h.useContext(gs);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,o=h.useId();h.useEffect(()=>{if(e)return r(o)},[e]);const i=h.useCallback(()=>e&&s&&s(o),[o,s,e]);return!n&&s?[!1,i]:[!0]}const es=e=>e.key||"";function Mi(e){const t=[];return h.Children.forEach(e,n=>{h.isValidElement(n)&&t.push(n)}),t}const od=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:o="sync",propagate:i=!1,anchorX:a="left",root:l})=>{const[c,d]=Ta(i),f=h.useMemo(()=>Mi(e),[e]),m=i&&!c?[]:f.map(es),p=h.useRef(!0),b=h.useRef(f),v=yr(()=>new Map),[T,w]=h.useState(f),[M,E]=h.useState(f);Ro(()=>{p.current=!1,b.current=f;for(let I=0;I<M.length;I++){const k=es(M[I]);m.includes(k)?v.delete(k):v.get(k)!==!0&&v.set(k,!1)}},[M,m.length,m.join("-")]);const $=[];if(f!==T){let I=[...f];for(let k=0;k<M.length;k++){const C=M[k],V=es(C);m.includes(V)||(I.splice(k,0,C),$.push(C))}return o==="wait"&&$.length&&(I=$),E(Mi(I)),w(f),null}process.env.NODE_ENV!=="production"&&o==="wait"&&M.length>1&&console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);const{forceRender:D}=h.useContext(gr);return u.jsx(u.Fragment,{children:M.map(I=>{const k=es(I),C=i&&!c?!1:f===M||m.includes(k),V=()=>{if(v.has(k))v.set(k,!0);else return;let A=!0;v.forEach(N=>{N||(A=!1)}),A&&(D?.(),E(b.current),i&&d?.(),s&&s())};return u.jsx(rd,{isPresent:C,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:C?void 0:V,anchorX:a,children:I},k)})})},Ur=h.createContext({strict:!1}),ki={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},nn={};for(const e in ki)nn[e]={isEnabled:t=>ki[e].some(n=>!!t[n])};function ir(e){for(const t in e)nn[t]={...nn[t],...e[t]}}function ad({children:e,features:t,strict:n=!1}){const[,s]=h.useState(!Ds(t)),r=h.useRef(void 0);if(!Ds(t)){const{renderer:o,...i}=t;r.current=o,ir(i)}return h.useEffect(()=>{Ds(t)&&t().then(({renderer:o,...i})=>{ir(i),r.current=o,s(!0)})},[]),u.jsx(Ur.Provider,{value:{renderer:r.current,strict:n},children:e})}function Ds(e){return typeof e=="function"}const ld=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function hs(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||ld.has(e)}let ja=e=>!hs(e);function cd(e){typeof e=="function"&&(ja=t=>t.startsWith("on")?!hs(t):e(t))}try{cd(require("@emotion/is-prop-valid").default)}catch{}function ud(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(ja(r)||n===!0&&hs(r)||!t&&!hs(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const ys=h.createContext({});function xs(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function On(e){return typeof e=="string"||Array.isArray(e)}const zr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],_r=["initial",...zr];function bs(e){return xs(e.animate)||_r.some(t=>On(e[t]))}function Ca(e){return!!(bs(e)||e.variants)}function dd(e,t){if(bs(e)){const{initial:n,animate:s}=e;return{initial:n===!1||On(n)?n:void 0,animate:On(s)?s:void 0}}return e.inherit!==!1?t:{}}function fd(e){const{initial:t,animate:n}=dd(e,h.useContext(ys));return h.useMemo(()=>({initial:t,animate:n}),[Ni(t),Ni(n)])}function Ni(e){return Array.isArray(e)?e.join(" "):e}const $n={};function hd(e){for(const t in e)$n[t]=e[t],Pr(t)&&($n[t].isCSSVariable=!0)}function Pa(e,{layout:t,layoutId:n}){return an.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!$n[e]||e==="opacity")}const md={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},pd=on.length;function gd(e,t,n){let s="",r=!0;for(let o=0;o<pd;o++){const i=on[o],a=e[i];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(i.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=ya(a,$r[i]);if(!l){r=!1;const d=md[i]||i;s+=`${d}(${c}) `}n&&(t[i]=c)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function Xr(e,t,n){const{style:s,vars:r,transformOrigin:o}=e;let i=!1,a=!1;for(const l in t){const c=t[l];if(an.has(l)){i=!0;continue}else if(Pr(l)){r[l]=c;continue}else{const d=ya(c,$r[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=gd(t,e.transform,n):s.transform&&(s.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:d=0}=o;s.transformOrigin=`${l} ${c} ${d}`}}const Wr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Aa(e,t,n){for(const s in t)!je(t[s])&&!Pa(s,n)&&(e[s]=t[s])}function yd({transformTemplate:e},t){return h.useMemo(()=>{const n=Wr();return Xr(n,t,e),Object.assign({},n.vars,n.style)},[t])}function xd(e,t){const n=e.style||{},s={};return Aa(s,n,e),Object.assign(s,yd(e,t)),s}function bd(e,t){const n={},s=xd(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const vd={offset:"stroke-dashoffset",array:"stroke-dasharray"},wd={offset:"strokeDashoffset",array:"strokeDasharray"};function Sd(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?vd:wd;e[o.offset]=z.transform(-s);const i=z.transform(t),a=z.transform(n);e[o.array]=`${i} ${a}`}function Ea(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,c,d){if(Xr(e,a,c),l){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:f,style:m}=e;f.transform&&(m.transform=f.transform,delete f.transform),(m.transform||f.transformOrigin)&&(m.transformOrigin=f.transformOrigin??"50% 50%",delete f.transformOrigin),m.transform&&(m.transformBox=d?.transformBox??"fill-box",delete f.transformBox),t!==void 0&&(f.x=t),n!==void 0&&(f.y=n),s!==void 0&&(f.scale=s),r!==void 0&&Sd(f,r,o,i,!1)}const Ma=()=>({...Wr(),attrs:{}}),ka=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Td(e,t,n,s){const r=h.useMemo(()=>{const o=Ma();return Ea(o,t,ka(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Aa(o,e.style,e),r.style={...o,...r.style}}return r}const jd=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function qr(e){return typeof e!="string"||e.includes("-")?!1:!!(jd.indexOf(e)>-1||/[A-Z]/u.test(e))}function Cd(e,t,n,{latestValues:s},r,o=!1){const a=(qr(e)?Td:bd)(t,s,r,e),l=ud(t,typeof e=="string",o),c=e!==h.Fragment?{...l,...a,ref:n}:{},{children:d}=t,f=h.useMemo(()=>je(d)?d.get():d,[d]);return h.createElement(e,{...c,children:f})}function Ri(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Kr(e,t,n,s){if(typeof t=="function"){const[r,o]=Ri(s);t=t(n!==void 0?n:e.custom,r,o)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[r,o]=Ri(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function as(e){return je(e)?e.get():e}function Pd({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:Ad(n,s,r,e),renderState:t()}}function Ad(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=as(o[m]);let{initial:i,animate:a}=e;const l=bs(e),c=Ca(e);t&&c&&!l&&e.inherit!==!1&&(i===void 0&&(i=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||i===!1;const f=d?a:i;if(f&&typeof f!="boolean"&&!xs(f)){const m=Array.isArray(f)?f:[f];for(let p=0;p<m.length;p++){const b=Kr(e,m[p]);if(b){const{transitionEnd:v,transition:T,...w}=b;for(const M in w){let E=w[M];if(Array.isArray(E)){const $=d?E.length-1:0;E=E[$]}E!==null&&(r[M]=E)}for(const M in v)r[M]=v[M]}}}return r}const Na=e=>(t,n)=>{const s=h.useContext(ys),r=h.useContext(gs),o=()=>Pd(e,t,s,r);return n?o():yr(o)};function Gr(e,t,n){const{style:s}=e,r={};for(const o in s)(je(s[o])||t.style&&je(t.style[o])||Pa(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const Ed=Na({scrapeMotionValuesFromProps:Gr,createRenderState:Wr});function Ra(e,t,n){const s=Gr(e,t,n);for(const r in e)if(je(e[r])||je(t[r])){const o=on.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const Md=Na({scrapeMotionValuesFromProps:Ra,createRenderState:Ma}),kd=Symbol.for("motionComponentSymbol");function Ht(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function Nd(e,t,n){return h.useCallback(s=>{s&&e.onMount&&e.onMount(s),t&&(s?t.mount(s):t.unmount()),n&&(typeof n=="function"?n(s):Ht(n)&&(n.current=s))},[t])}const Hr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Rd="framerAppearId",Da="data-"+Hr(Rd),Va=h.createContext({});function Dd(e,t,n,s,r){const{visualElement:o}=h.useContext(ys),i=h.useContext(Ur),a=h.useContext(gs),l=h.useContext(Br).reducedMotion,c=h.useRef(null);s=s||i.renderer,!c.current&&s&&(c.current=s(e,{visualState:t,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=c.current,f=h.useContext(Va);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&Vd(c.current,n,r,f);const m=h.useRef(!1);h.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Da],b=h.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return Ro(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),b.current&&d.animationState&&d.animationState.animateChanges())}),h.useEffect(()=>{d&&(!b.current&&d.animationState&&d.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),b.current=!1),d.enteringChildren=void 0)}),d}function Vd(e,t,n,s){const{layoutId:r,layout:o,drag:i,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Ia(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Ht(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:c})}function Ia(e){if(e)return e.options.allowProjection!==!1?e.projection:Ia(e.parent)}function ls(e,{forwardMotionProps:t=!1}={},n,s){n&&ir(n);const r=qr(e)?Md:Ed;function o(a,l){let c;const d={...h.useContext(Br),...a,layoutId:Id(a)},{isStatic:f}=d,m=fd(a),p=r(a,f);if(!f&&xr){Od(d,n);const b=$d(d);c=b.MeasureLayout,m.visualElement=Dd(e,p,d,s,b.ProjectionNode)}return u.jsxs(ys.Provider,{value:m,children:[c&&m.visualElement?u.jsx(c,{visualElement:m.visualElement,...d}):null,Cd(e,a,Nd(p,m.visualElement,l),p,f,t)]})}o.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const i=h.forwardRef(o);return i[kd]=e,i}function Id({layoutId:e}){const t=h.useContext(gr).id;return t&&e!==void 0?t+"-"+e:e}function Od(e,t){const n=h.useContext(Ur).strict;if(process.env.NODE_ENV!=="production"&&t&&n){const s="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?sn(!1,s,"lazy-strict-mode"):at(!1,s,"lazy-strict-mode")}}function $d(e){const{drag:t,layout:n}=nn;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Ld(e,t){if(typeof Proxy>"u")return ls;const n=new Map,s=(o,i)=>ls(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Tr(!1,"motion() is deprecated. Use motion.create() instead."),s(o,i));return new Proxy(r,{get:(o,i)=>i==="create"?s:(n.has(i)||n.set(i,ls(i,void 0,e,t)),n.get(i))})}function Oa({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Fd({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Bd(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function Vs(e){return e===void 0||e===1}function or({scale:e,scaleX:t,scaleY:n}){return!Vs(e)||!Vs(t)||!Vs(n)}function kt(e){return or(e)||$a(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function $a(e){return Di(e.x)||Di(e.y)}function Di(e){return e&&e!=="0%"}function ms(e,t,n){const s=e-n,r=t*s;return n+r}function Vi(e,t,n,s,r){return r!==void 0&&(e=ms(e,r,s)),ms(e,n,s)+t}function ar(e,t=0,n=1,s,r){e.min=Vi(e.min,t,n,s,r),e.max=Vi(e.max,t,n,s,r)}function La(e,{x:t,y:n}){ar(e.x,t.translate,t.scale,t.originPoint),ar(e.y,n.translate,n.scale,n.originPoint)}const Ii=.999999999999,Oi=1.0000000000001;function Ud(e,t,n,s=!1){const r=n.length;if(!r)return;t.x=t.y=1;let o,i;for(let a=0;a<r;a++){o=n[a],i=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(s&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Jt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,La(e,i)),s&&kt(o.latestValues)&&Jt(e,o.latestValues))}t.x<Oi&&t.x>Ii&&(t.x=1),t.y<Oi&&t.y>Ii&&(t.y=1)}function Yt(e,t){e.min=e.min+t,e.max=e.max+t}function $i(e,t,n,s,r=.5){const o=me(e.min,e.max,r);ar(e,t,n,o,s)}function Jt(e,t){$i(e.x,t.x,t.scaleX,t.scale,t.originX),$i(e.y,t.y,t.scaleY,t.scale,t.originY)}function Fa(e,t){return Oa(Bd(e.getBoundingClientRect(),t))}function zd(e,t,n){const s=Fa(e,n),{scroll:r}=t;return r&&(Yt(s.x,r.offset.x),Yt(s.y,r.offset.y)),s}const Li=()=>({translate:0,scale:1,origin:0,originPoint:0}),Zt=()=>({x:Li(),y:Li()}),Fi=()=>({min:0,max:0}),ye=()=>({x:Fi(),y:Fi()}),lr={current:null},Ba={current:!1};function _d(){if(Ba.current=!0,!!xr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>lr.current=e.matches;e.addEventListener("change",t),t()}else lr.current=!1}const Xd=new WeakMap;function Wd(e,t,n){for(const s in t){const r=t[s],o=n[s];if(je(r))e.addValue(s,r);else if(je(o))e.addValue(s,tn(r,{owner:e}));else if(o!==r)if(e.hasValue(s)){const i=e.getValue(s);i.liveStyle===!0?i.jump(r):i.hasAnimated||i.set(r)}else{const i=e.getStaticValue(s);e.addValue(s,tn(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Bi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class qd{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:r,blockInitialAnimation:o,visualState:i},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Ir,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const m=De.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,ce.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=i;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=r,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=bs(n),this.isVariantNode=Ca(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:d,...f}=this.scrapeMotionValuesFromProps(n,{},this);for(const m in f){const p=f[m];l[m]!==void 0&&je(p)&&p.set(l[m])}}mount(t){this.current=t,Xd.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),Ba.current||_d(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:lr.current,process.env.NODE_ENV!=="production"&&Tr(this.shouldReduceMotion!==!0,"You have Reduced Motion enabled on your device. Animations may not appear as expected.","reduced-motion-disabled"),this.parent?.addChild(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),wt(this.notifyUpdate),wt(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const s=an.has(t);s&&this.onBindTransform&&this.onBindTransform();const r=n.on("change",i=>{this.latestValues[t]=i,this.props.onUpdate&&ce.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in nn){const n=nn[t];if(!n)continue;const{isEnabled:s,Feature:r}=n;if(!this.features[t]&&r&&s(this.props)&&(this.features[t]=new r(this)),this.features[t]){const o=this.features[t];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ye()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<Bi.length;s++){const r=Bi[s];this.propEventSubscriptions[r]&&(this.propEventSubscriptions[r](),delete this.propEventSubscriptions[r]);const o="on"+r,i=t[o];i&&(this.propEventSubscriptions[r]=this.on(r,i))}this.prevMotionValues=Wd(this,this.scrapeMotionValuesFromProps(t,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=tn(n===null?void 0:n,{owner:this}),this.addValue(t,s)),s}readValue(t,n){let s=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return s!=null&&(typeof s=="string"&&(Do(s)||Io(s))?s=parseFloat(s):!Qu(s)&&St.test(n)&&(s=ga(t,n)),this.setBaseTarget(t,je(s)?s.get():s)),je(s)?s.get():s}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const o=Kr(this.props,n,this.presenceContext?.custom);o&&(s=o[t])}if(n&&s!==void 0)return s;const r=this.getBaseTargetFromProps(this.props,t);return r!==void 0&&!je(r)?r:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new Sr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Lr.render(this.render)}}class Ua extends qd{constructor(){super(...arguments),this.KeyframeResolver=Uu}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;je(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function za(e,{style:t,vars:n},s,r){const o=e.style;let i;for(i in t)o[i]=t[i];r?.applyProjectionStyles(o,s);for(i in n)o.setProperty(i,n[i])}function Kd(e){return window.getComputedStyle(e)}class Gd extends Ua{constructor(){super(...arguments),this.type="html",this.renderInstance=za}readValueFromInstance(t,n){if(an.has(n))return this.projection?.isProjecting?Zs(n):iu(t,n);{const s=Kd(t),r=(Pr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Fa(t,n)}build(t,n,s){Xr(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Gr(t,n,s)}}const _a=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function Hd(e,t,n,s){za(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(_a.has(r)?r:Hr(r),t.attrs[r])}class Yd extends Ua{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ye}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(an.has(n)){const s=pa(n);return s&&s.default||0}return n=_a.has(n)?n:Hr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Ra(t,n,s)}build(t,n,s){Ea(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Hd(t,n,s,r)}mount(t){this.isSVGTag=ka(t.tagName),super.mount(t)}}const Xa=(e,t)=>qr(e)?new Yd(t):new Gd(t,{allowProjection:e!==h.Fragment});function en(e,t,n){const s=e.getProps();return Kr(s,t,n!==void 0?n:s.custom,e)}const cr=e=>Array.isArray(e);function Jd(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,tn(n))}function Zd(e){return cr(e)?e[e.length-1]||0:e}function Qd(e,t){const n=en(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Zd(o[i]);Jd(e,i,a)}}function ef(e){return!!(je(e)&&e.add)}function ur(e,t){const n=e.getValue("willChange");if(ef(n))return n.add(t);if(!n&<.WillChange){const s=new lt.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Wa(e){return e.props[Da]}const tf=e=>e!==null;function nf(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(tf),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const sf={type:"spring",stiffness:500,damping:25,restSpeed:10},rf=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),of={type:"keyframes",duration:.8},af={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},lf=(e,{keyframes:t})=>t.length>2?of:an.has(e)?e.startsWith("scale")?rf(t[1]):sf:af;function cf({when:e,delay:t,delayChildren:n,staggerChildren:s,staggerDirection:r,repeat:o,repeatType:i,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}const Yr=(e,t,n,s={},r,o)=>i=>{const a=Or(s,e)||{},l=a.delay||s.delay||0;let{elapsed:c=0}=s;c=c-Ge(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,onUpdate:m=>{t.set(m),a.onUpdate&&a.onUpdate(m)},onComplete:()=>{i(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:o?void 0:r};cf(a)||Object.assign(d,lf(e,d)),d.duration&&(d.duration=Ge(d.duration)),d.repeatDelay&&(d.repeatDelay=Ge(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let f=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(sr(d),d.delay===0&&(f=!0)),(lt.instantAnimations||lt.skipAnimations)&&(f=!0,sr(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,f&&!o&&t.get()!==void 0){const m=nf(d.keyframes,a);if(m!==void 0){ce.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Vr(d):new Eu(d)};function uf({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function qa(e,t,{delay:n=0,transitionOverride:s,type:r}={}){let{transition:o=e.getDefaultTransition(),transitionEnd:i,...a}=t;s&&(o=s);const l=[],c=r&&e.animationState&&e.animationState.getState()[r];for(const d in a){const f=e.getValue(d,e.latestValues[d]??null),m=a[d];if(m===void 0||c&&uf(c,d))continue;const p={delay:n,...Or(o||{},d)},b=f.get();if(b!==void 0&&!f.isAnimating&&!Array.isArray(m)&&m===b&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const w=Wa(e);if(w){const M=window.MotionHandoffAnimation(w,d,ce);M!==null&&(p.startTime=M,v=!0)}}ur(e,d),f.start(Yr(d,f,m,e.shouldReduceMotion&&fa.has(d)?{type:!1}:p,e,v));const T=f.animation;T&&l.push(T)}return i&&Promise.all(l).then(()=>{ce.update(()=>{i&&Qd(e,i)})}),l}function Ka(e,t,n,s=0,r=1){const o=Array.from(e).sort((c,d)=>c.sortNodePosition(d)).indexOf(t),i=e.size,a=(i-1)*s;return typeof n=="function"?n(o,i):r===1?o*s:a-o*s}function dr(e,t,n={}){const s=en(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:r=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(r=n.transitionOverride);const o=s?()=>Promise.all(qa(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:c=0,staggerChildren:d,staggerDirection:f}=r;return df(e,t,l,c,d,f,n)}:()=>Promise.resolve(),{when:a}=r;if(a){const[l,c]=a==="beforeChildren"?[o,i]:[i,o];return l().then(()=>c())}else return Promise.all([o(),i(n.delay)])}function df(e,t,n=0,s=0,r=0,o=1,i){const a=[];for(const l of e.variantChildren)l.notify("AnimationStart",t),a.push(dr(l,t,{...i,delay:n+(typeof s=="function"?0:s)+Ka(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function ff(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>dr(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=dr(e,t,n);else{const r=typeof t=="function"?en(e,t,n.custom):t;s=Promise.all(qa(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function Ga(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const hf=_r.length;function Ha(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Ha(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<hf;n++){const s=_r[n],r=e.props[s];(On(r)||r===!1)&&(t[s]=r)}return t}const mf=[...zr].reverse(),pf=zr.length;function gf(e){return t=>Promise.all(t.map(({animation:n,options:s})=>ff(e,n,s)))}function yf(e){let t=gf(e),n=Ui(),s=!0;const r=l=>(c,d)=>{const f=en(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(f){const{transition:m,transitionEnd:p,...b}=f;c={...c,...b,...p}}return c};function o(l){t=l(e)}function i(l){const{props:c}=e,d=Ha(e.parent)||{},f=[],m=new Set;let p={},b=1/0;for(let T=0;T<pf;T++){const w=mf[T],M=n[w],E=c[w]!==void 0?c[w]:d[w],$=On(E),D=w===l?M.isActive:null;D===!1&&(b=T);let I=E===d[w]&&E!==c[w]&&$;if(I&&s&&e.manuallyAnimateOnMount&&(I=!1),M.protectedKeys={...p},!M.isActive&&D===null||!E&&!M.prevProp||xs(E)||typeof E=="boolean")continue;const k=xf(M.prevProp,E);let C=k||w===l&&M.isActive&&!I&&$||T>b&&$,V=!1;const A=Array.isArray(E)?E:[E];let N=A.reduce(r(w),{});D===!1&&(N={});const{prevResolvedValues:L={}}=M,O={...L,...N},F=K=>{C=!0,m.has(K)&&(V=!0,m.delete(K)),M.needsAnimating[K]=!0;const ae=e.getValue(K);ae&&(ae.liveStyle=!1)};for(const K in O){const ae=N[K],ve=L[K];if(p.hasOwnProperty(K))continue;let He=!1;cr(ae)&&cr(ve)?He=!Ga(ae,ve):He=ae!==ve,He?ae!=null?F(K):m.add(K):ae!==void 0&&m.has(K)?F(K):M.protectedKeys[K]=!0}M.prevProp=E,M.prevResolvedValues=N,M.isActive&&(p={...p,...N}),s&&e.blockInitialAnimation&&(C=!1);const _=I&&k;C&&(!_||V)&&f.push(...A.map(K=>{const ae={type:w};if(typeof K=="string"&&s&&!_&&e.manuallyAnimateOnMount&&e.parent){const{parent:ve}=e,He=en(ve,K);if(ve.enteringChildren&&He){const{delayChildren:jt}=He.transition||{};ae.delay=Ka(ve.enteringChildren,e,jt)}}return{animation:K,options:ae}}))}if(m.size){const T={};if(typeof c.initial!="boolean"){const w=en(e,Array.isArray(c.initial)?c.initial[0]:c.initial);w&&w.transition&&(T.transition=w.transition)}m.forEach(w=>{const M=e.getBaseTarget(w),E=e.getValue(w);E&&(E.liveStyle=!0),T[w]=M??null}),f.push({animation:T})}let v=!!f.length;return s&&(c.initial===!1||c.initial===c.animate)&&!e.manuallyAnimateOnMount&&(v=!1),s=!1,v?t(f):Promise.resolve()}function a(l,c){if(n[l].isActive===c)return Promise.resolve();e.variantChildren?.forEach(f=>f.animationState?.setActive(l,c)),n[l].isActive=c;const d=i(l);for(const f in n)n[f].protectedKeys={};return d}return{animateChanges:i,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Ui()}}}function xf(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Ga(t,e):!1}function Et(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Ui(){return{animate:Et(!0),whileInView:Et(),whileHover:Et(),whileTap:Et(),whileDrag:Et(),whileFocus:Et(),exit:Et()}}class Tt{constructor(t){this.isMounted=!1,this.node=t}update(){}}class bf extends Tt{constructor(t){super(t),t.animationState||(t.animationState=yf(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();xs(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let vf=0;class wf extends Tt{constructor(){super(...arguments),this.id=vf++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Ya={animation:{Feature:bf},exit:{Feature:wf}};function Ln(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function zn(e){return{point:{x:e.pageX,y:e.pageY}}}const Sf=e=>t=>Fr(t)&&e(t,zn(t));function Mn(e,t,n,s){return Ln(e,t,Sf(n),s)}const Ja=1e-4,Tf=1-Ja,jf=1+Ja,Za=.01,Cf=0-Za,Pf=0+Za;function Ee(e){return e.max-e.min}function Af(e,t,n){return Math.abs(e-t)<=n}function zi(e,t,n,s=.5){e.origin=s,e.originPoint=me(t.min,t.max,e.origin),e.scale=Ee(n)/Ee(t),e.translate=me(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Tf&&e.scale<=jf||isNaN(e.scale))&&(e.scale=1),(e.translate>=Cf&&e.translate<=Pf||isNaN(e.translate))&&(e.translate=0)}function kn(e,t,n,s){zi(e.x,t.x,n.x,s?s.originX:void 0),zi(e.y,t.y,n.y,s?s.originY:void 0)}function _i(e,t,n){e.min=n.min+t.min,e.max=e.min+Ee(t)}function Ef(e,t,n){_i(e.x,t.x,n.x),_i(e.y,t.y,n.y)}function Xi(e,t,n){e.min=t.min-n.min,e.max=e.min+Ee(t)}function Nn(e,t,n){Xi(e.x,t.x,n.x),Xi(e.y,t.y,n.y)}function $e(e){return[e("x"),e("y")]}const Qa=({current:e})=>e?e.ownerDocument.defaultView:null,Wi=(e,t)=>Math.abs(e-t);function Mf(e,t){const n=Wi(e.x,t.x),s=Wi(e.y,t.y);return Math.sqrt(n**2+s**2)}class el{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:o=!1,distanceThreshold:i=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const m=Os(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,b=Mf(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!b)return;const{point:v}=m,{timestamp:T}=Te;this.history.push({...v,timestamp:T});const{onStart:w,onMove:M}=this.handlers;p||(w&&w(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),M&&M(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=Is(p,this.transformPagePoint),ce.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:b,onSessionEnd:v,resumeAnimation:T}=this.handlers;if(this.dragSnapToOrigin&&T&&T(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=Os(m.type==="pointercancel"?this.lastMoveEventInfo:Is(p,this.transformPagePoint),this.history);this.startEvent&&b&&b(m,w),v&&v(m,w)},!Fr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=zn(t),l=Is(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=Te;this.history=[{...c,timestamp:d}];const{onSessionStart:f}=n;f&&f(t,Os(l,this.history)),this.removeListeners=Fn(Mn(this.contextWindow,"pointermove",this.handlePointerMove),Mn(this.contextWindow,"pointerup",this.handlePointerUp),Mn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),wt(this.updatePoint)}}function Is(e,t){return t?{point:t(e.point)}:e}function qi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Os({point:e},t){return{point:e,delta:qi(e,tl(t)),offset:qi(e,kf(t)),velocity:Nf(t,.1)}}function kf(e){return e[0]}function tl(e){return e[e.length-1]}function Nf(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=tl(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Ge(t)));)n--;if(!s)return{x:0,y:0};const o=Fe(r.timestamp-s.timestamp);if(o===0)return{x:0,y:0};const i={x:(r.x-s.x)/o,y:(r.y-s.y)/o};return i.x===1/0&&(i.x=0),i.y===1/0&&(i.y=0),i}function Rf(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?me(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?me(n,e,s.max):Math.min(e,n)),e}function Ki(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function Df(e,{top:t,left:n,bottom:s,right:r}){return{x:Ki(e.x,n,r),y:Ki(e.y,t,s)}}function Gi(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function Vf(e,t){return{x:Gi(e.x,t.x),y:Gi(e.y,t.y)}}function If(e,t){let n=.5;const s=Ee(e),r=Ee(t);return r>s?n=Dn(t.min,t.max-s,e.min):s>r&&(n=Dn(e.min,e.max-r,t.min)),ot(0,1,n)}function Of(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const fr=.35;function $f(e=fr){return e===!1?e=0:e===!0&&(e=fr),{x:Hi(e,"left","right"),y:Hi(e,"top","bottom")}}function Hi(e,t,n){return{min:Yi(e,t),max:Yi(e,n)}}function Yi(e,t){return typeof e=="number"?e:e[t]||0}const Lf=new WeakMap;class Ff{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ye(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const o=f=>{const{dragSnapToOrigin:m}=this.getProps();m?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(zn(f).point)},i=(f,m)=>{const{drag:p,dragPropagation:b,onDragStart:v}=this.getProps();if(p&&!b&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Wu(p),!this.openDragLock))return;this.latestPointerEvent=f,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),$e(w=>{let M=this.getAxisMotionValue(w).get()||0;if(Qe.test(M)){const{projection:E}=this.visualElement;if(E&&E.layout){const $=E.layout.layoutBox[w];$&&(M=Ee($)*(parseFloat(M)/100))}}this.originPoint[w]=M}),v&&ce.postRender(()=>v(f,m)),ur(this.visualElement,"transform");const{animationState:T}=this.visualElement;T&&T.setActive("whileDrag",!0)},a=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:b,onDirectionLock:v,onDrag:T}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:w}=m;if(b&&this.currentDirection===null){this.currentDirection=Bf(w),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",m.point,w),this.updateAxis("y",m.point,w),this.visualElement.render(),T&&T(f,m)},l=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m,this.stop(f,m),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>$e(f=>this.getAnimationState(f)==="paused"&&this.getAxisMotionValue(f).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new el(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Qa(this.visualElement)})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!r||!s)return;const{velocity:i}=r;this.startAnimation(i);const{onDragEnd:a}=this.getProps();a&&ce.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!ts(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=Rf(i,this.constraints[t],this.elastic[t])),o.set(i)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&Ht(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Df(s.layoutBox,t):this.constraints=!1,this.elastic=$f(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&$e(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Of(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Ht(t))return!1;const s=t.current;at(s!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const o=zd(s,r.root,this.visualElement.getTransformPagePoint());let i=Vf(r.layout.layoutBox,o);if(n){const a=n(Fd(i));this.hasMutatedConstraints=!!a,a&&(i=Oa(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=$e(d=>{if(!ts(d,n,this.currentDirection))return;let f=l&&l[d]||{};i&&(f={min:0,max:0});const m=r?200:1e6,p=r?40:1e7,b={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...f};return this.startAxisValueAnimation(d,b)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return ur(this.visualElement,t),s.start(Yr(t,s,0,n,this.visualElement,!1))}stopAnimation(){$e(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){$e(t=>this.getAxisMotionValue(t).animation?.pause())}getAnimationState(t){return this.getAxisMotionValue(t).animation?.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,s=this.visualElement.getProps(),r=s[n];return r||this.visualElement.getValue(t,(s.initial?s.initial[t]:void 0)||0)}snapToCursor(t){$e(n=>{const{drag:s}=this.getProps();if(!ts(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,o=this.getAxisMotionValue(n);if(r&&r.layout){const{min:i,max:a}=r.layout.layoutBox[n];o.set(t[n]-me(i,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Ht(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};$e(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const l=a.get();r[i]=If({min:l,max:l},this.constraints[i])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.resolveConstraints(),$e(i=>{if(!ts(i,t,null))return;const a=this.getAxisMotionValue(i),{min:l,max:c}=this.constraints[i];a.set(me(l,c,r[i]))})}addListeners(){if(!this.visualElement.current)return;Lf.set(this.visualElement,this);const t=this.visualElement.current,n=Mn(t,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Ht(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:r}=this.visualElement,o=r.addEventListener("measure",s);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),ce.read(s);const i=Ln(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&($e(d=>{const f=this.getAxisMotionValue(d);f&&(this.originPoint[d]+=l[d].translate,f.set(f.get()+l[d].translate))}),this.visualElement.render())});return()=>{i(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:o=!1,dragElastic:i=fr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function ts(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Bf(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Uf extends Tt{constructor(t){super(t),this.removeGroupControls=Be,this.removeListeners=Be,this.controls=new Ff(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Be}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ji=e=>(t,n)=>{e&&ce.postRender(()=>e(t,n))};class zf extends Tt{constructor(){super(...arguments),this.removePointerDownListener=Be}onPointerDown(t){this.session=new el(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Qa(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ji(t),onStart:Ji(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&ce.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Mn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const cs={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Zi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const jn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(z.test(e))e=parseFloat(e);else return e;const n=Zi(e,t.target.x),s=Zi(e,t.target.y);return`${n}% ${s}%`}},_f={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=St.parse(e);if(r.length>5)return s;const o=St.createTransformer(e),i=typeof r[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;r[0+i]/=a,r[1+i]/=l;const c=me(a,l,.5);return typeof r[2+i]=="number"&&(r[2+i]/=c),typeof r[3+i]=="number"&&(r[3+i]/=c),o(r)}};let $s=!1;class Xf extends h.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;hd(Wf),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),$s&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),cs.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,$s=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==o?i.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?i.promote():i.relegate()||ce.postRender(()=>{const a=i.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),Lr.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;$s=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function nl(e){const[t,n]=Ta(),s=h.useContext(gr);return u.jsx(Xf,{...e,layoutGroup:s,switchLayoutGroup:h.useContext(Va),isPresent:t,safeToRemove:n})}const Wf={borderRadius:{...jn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:jn,borderTopRightRadius:jn,borderBottomLeftRadius:jn,borderBottomRightRadius:jn,boxShadow:_f};function qf(e,t,n){const s=je(e)?e:tn(e);return s.start(Yr("",s,t,n)),s.animation}const Kf=(e,t)=>e.depth-t.depth;class Gf{constructor(){this.children=[],this.isDirty=!1}add(t){br(this.children,t),this.isDirty=!0}remove(t){vr(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Kf),this.isDirty=!1,this.children.forEach(t)}}function Hf(e,t){const n=De.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(wt(s),e(o-t))};return ce.setup(s,!0),()=>wt(s)}const sl=["TopLeft","TopRight","BottomLeft","BottomRight"],Yf=sl.length,Qi=e=>typeof e=="string"?parseFloat(e):e,eo=e=>typeof e=="number"||z.test(e);function Jf(e,t,n,s,r,o){r?(e.opacity=me(0,n.opacity??1,Zf(s)),e.opacityExit=me(t.opacity??1,0,Qf(s))):o&&(e.opacity=me(t.opacity??1,n.opacity??1,s));for(let i=0;i<Yf;i++){const a=`border${sl[i]}Radius`;let l=to(t,a),c=to(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||eo(l)===eo(c)?(e[a]=Math.max(me(Qi(l),Qi(c),s),0),(Qe.test(c)||Qe.test(l))&&(e[a]+="%")):e[a]=c}(t.rotate||n.rotate)&&(e.rotate=me(t.rotate||0,n.rotate||0,s))}function to(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Zf=rl(0,.5,_o),Qf=rl(.5,.95,Be);function rl(e,t,n){return s=>s<e?0:s>t?1:n(Dn(e,t,s))}function no(e,t){e.min=t.min,e.max=t.max}function Oe(e,t){no(e.x,t.x),no(e.y,t.y)}function so(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function ro(e,t,n,s,r){return e-=t,e=ms(e,1/n,s),r!==void 0&&(e=ms(e,1/r,s)),e}function eh(e,t=0,n=1,s=.5,r,o=e,i=e){if(Qe.test(t)&&(t=parseFloat(t),t=me(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=me(o.min,o.max,s);e===o&&(a-=t),e.min=ro(e.min,t,n,a,r),e.max=ro(e.max,t,n,a,r)}function io(e,t,[n,s,r],o,i){eh(e,t[n],t[s],t[r],t.scale,o,i)}const th=["x","scaleX","originX"],nh=["y","scaleY","originY"];function oo(e,t,n,s){io(e.x,t,th,n?n.x:void 0,s?s.x:void 0),io(e.y,t,nh,n?n.y:void 0,s?s.y:void 0)}function ao(e){return e.translate===0&&e.scale===1}function il(e){return ao(e.x)&&ao(e.y)}function lo(e,t){return e.min===t.min&&e.max===t.max}function sh(e,t){return lo(e.x,t.x)&&lo(e.y,t.y)}function co(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function ol(e,t){return co(e.x,t.x)&&co(e.y,t.y)}function uo(e){return Ee(e.x)/Ee(e.y)}function fo(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class rh{constructor(){this.members=[]}add(t){br(this.members,t),t.scheduleRender()}remove(t){if(vr(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(r=>t===r);if(n===0)return!1;let s;for(let r=n;r>=0;r--){const o=this.members[r];if(o.isPresent!==!1){s=o;break}}return s?(this.promote(s),!0):!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.instance&&s.scheduleRender(),t.scheduleRender(),t.resumeFrom=s,n&&(t.resumeFrom.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:r}=t.options;r===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:s}=t;n.onExitComplete&&n.onExitComplete(),s&&s.options.onExitComplete&&s.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function ih(e,t,n){let s="";const r=e.x.translate/t.x,o=e.y.translate/t.y,i=n?.z||0;if((r||o||i)&&(s=`translate3d(${r}px, ${o}px, ${i}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:c,rotate:d,rotateX:f,rotateY:m,skewX:p,skewY:b}=n;c&&(s=`perspective(${c}px) ${s}`),d&&(s+=`rotate(${d}deg) `),f&&(s+=`rotateX(${f}deg) `),m&&(s+=`rotateY(${m}deg) `),p&&(s+=`skewX(${p}deg) `),b&&(s+=`skewY(${b}deg) `)}const a=e.x.scale*t.x,l=e.y.scale*t.y;return(a!==1||l!==1)&&(s+=`scale(${a}, ${l})`),s||"none"}const Ls=["","X","Y","Z"],oh=1e3;let ah=0;function Fs(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function al(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Wa(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:r,layoutId:o}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",ce,!(r||o))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&al(s)}function ll({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=ah++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(uh),this.nodes.forEach(mh),this.nodes.forEach(ph),this.nodes.forEach(dh)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=i,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new Gf)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new Sr),this.eventHandlers.get(i).add(a)}notifyListeners(i,...a){const l=this.eventHandlers.get(i);l&&l.notify(...a)}hasListeners(i){return this.eventHandlers.has(i)}mount(i){if(this.instance)return;this.isSVG=Sa(i)&&!Ju(i),this.instance=i;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(i),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),e){let d,f=0;const m=()=>this.root.updateBlockedByResize=!1;ce.read(()=>{f=window.innerWidth}),e(i,()=>{const p=window.innerWidth;p!==f&&(f=p,this.root.updateBlockedByResize=!0,d&&d(),d=Hf(m,250),cs.hasAnimatedSinceResize&&(cs.hasAnimatedSinceResize=!1,this.nodes.forEach(po)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:f,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const b=this.options.transition||c.getDefaultTransition()||vh,{onLayoutAnimationStart:v,onLayoutAnimationComplete:T}=c.getProps(),w=!this.targetLayout||!ol(this.targetLayout,p),M=!f&&m;if(this.options.layoutRoot||this.resumeFrom||M||f&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const E={...Or(b,"layout"),onPlay:v,onComplete:T};(c.shouldReduceMotion||this.options.layoutRoot)&&(E.delay=0,E.type=!1),this.startAnimation(E),this.setAnimationOrigin(d,M)}else f||po(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const i=this.getStack();i&&i.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),wt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(gh),this.animationId++)}getTransformTemplate(){const{visualElement:i}=this.options;return i&&i.getProps().transformTemplate}willUpdate(i=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&al(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const f=this.path[d];f.shouldResetTransform=!0,f.updateScroll("snapshot"),f.options.layoutRoot&&f.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),i&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(ho);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(mo);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(hh),this.nodes.forEach(lh),this.nodes.forEach(ch)):this.nodes.forEach(mo),this.clearAllSnapshots();const a=De.now();Te.delta=ot(0,1e3/60,a-Te.timestamp),Te.timestamp=a,Te.isProcessing=!0,As.update.process(Te),As.preRender.process(Te),As.render.process(Te),Te.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Lr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(fh),this.sharedNodes.forEach(yh)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ce.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ce.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ee(this.snapshot.measuredBox.x)&&!Ee(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const i=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ye(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,i?i.layoutBox:void 0)}updateScroll(i="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===i&&(a=!1),a&&this.instance){const l=s(this.instance);this.scroll={animationId:this.root.animationId,phase:i,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!r)return;const i=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!il(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;i&&this.instance&&(a||kt(this.latestValues)||d)&&(r(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(i=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return i&&(l=this.removeTransform(l)),wh(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return ye();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Sh))){const{scroll:c}=this.root;c&&(Yt(a.x,c.offset.x),Yt(a.y,c.offset.y))}return a}removeElementScroll(i){const a=ye();if(Oe(a,i),this.scroll?.wasRoot)return a;for(let l=0;l<this.path.length;l++){const c=this.path[l],{scroll:d,options:f}=c;c!==this.root&&d&&f.layoutScroll&&(d.wasRoot&&Oe(a,i),Yt(a.x,d.offset.x),Yt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=ye();Oe(l,i);for(let c=0;c<this.path.length;c++){const d=this.path[c];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&Jt(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),kt(d.latestValues)&&Jt(l,d.latestValues)}return kt(this.latestValues)&&Jt(l,this.latestValues),l}removeTransform(i){const a=ye();Oe(a,i);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!kt(c.latestValues))continue;or(c.latestValues)&&c.updateSnapshot();const d=ye(),f=c.measurePageBox();Oe(d,f),oo(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return kt(this.latestValues)&&oo(a,this.latestValues),a}setTargetDelta(i){this.targetDelta=i,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(i){this.options={...this.options,...i,crossfade:i.crossfade!==void 0?i.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Te.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(i=!1){const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(i||l&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:f}=this.options;if(!(!this.layout||!(d||f))){if(this.resolvedRelativeTargetAt=Te.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ye(),this.relativeTargetOrigin=ye(),Nn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Oe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ye(),this.targetWithTransforms=ye()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Ef(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Oe(this.target,this.layout.layoutBox),La(this.target,this.targetDelta)):Oe(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ye(),this.relativeTargetOrigin=ye(),Nn(this.relativeTargetOrigin,this.target,m.target),Oe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||or(this.parent.latestValues)||$a(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){const i=this.getLead(),a=!!this.resumingFrom||this!==i;let l=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Te.timestamp&&(l=!1),l)return;const{layout:c,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||d))return;Oe(this.layoutCorrected,this.layout.layoutBox);const f=this.treeScale.x,m=this.treeScale.y;Ud(this.layoutCorrected,this.treeScale,this.path,a),i.layout&&!i.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(i.target=i.layout.layoutBox,i.targetWithTransforms=ye());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(so(this.prevProjectionDelta.x,this.projectionDelta.x),so(this.prevProjectionDelta.y,this.projectionDelta.y)),kn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==f||this.treeScale.y!==m||!fo(this.projectionDelta.x,this.prevProjectionDelta.x)||!fo(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(i=!0){if(this.options.visualElement?.scheduleRender(),i){const a=this.getStack();a&&a.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Zt(),this.projectionDelta=Zt(),this.projectionDeltaWithTransform=Zt()}setAnimationOrigin(i,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},f=Zt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=ye(),p=l?l.source:void 0,b=this.layout?this.layout.source:void 0,v=p!==b,T=this.getStack(),w=!T||T.members.length<=1,M=!!(v&&!w&&this.options.crossfade===!0&&!this.path.some(bh));this.animationProgress=0;let E;this.mixTargetDelta=$=>{const D=$/1e3;go(f.x,i.x,D),go(f.y,i.y,D),this.setTargetDelta(f),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Nn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),xh(this.relativeTarget,this.relativeTargetOrigin,m,D),E&&sh(this.relativeTarget,E)&&(this.isProjectionDirty=!1),E||(E=ye()),Oe(E,this.relativeTarget)),v&&(this.animationValues=d,Jf(d,c,this.latestValues,D,M,w)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=D},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(i){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(wt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ce.update(()=>{cs.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=tn(0)),this.currentAnimation=qf(this.motionValue,[0,1e3],{...i,velocity:0,isSync:!0,onUpdate:a=>{this.mixTargetDelta(a),i.onUpdate&&i.onUpdate(a)},onStop:()=>{},onComplete:()=>{i.onComplete&&i.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const i=this.getStack();i&&i.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(oh),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const i=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=i;if(!(!a||!l||!c)){if(this!==i&&this.layout&&c&&cl(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ye();const f=Ee(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+f;const m=Ee(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}Oe(a,l),Jt(a,d),kn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new rh),this.sharedNodes.get(i).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const i=this.getStack();return i?i.lead===this:!0}getLead(){const{layoutId:i}=this.options;return i?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:i}=this.options;return i?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:i}=this.options;if(i)return this.root.sharedNodes.get(i)}promote({needsReset:i,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),i&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const i=this.getStack();return i?i.relegate(this):!1}resetSkewAndRotation(){const{visualElement:i}=this.options;if(!i)return;let a=!1;const{latestValues:l}=i;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Fs("z",i,c,this.animationValues);for(let d=0;d<Ls.length;d++)Fs(`rotate${Ls[d]}`,i,c,this.animationValues),Fs(`skew${Ls[d]}`,i,c,this.animationValues);i.render();for(const d in c)i.setStaticValue(d,c[d]),this.animationValues&&(this.animationValues[d]=c[d]);i.scheduleRender()}applyProjectionStyles(i,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){i.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,i.visibility="",i.opacity="",i.pointerEvents=as(a?.pointerEvents)||"",i.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(i.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,i.pointerEvents=as(a?.pointerEvents)||""),this.hasProjected&&!kt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let f=ih(this.projectionDeltaWithTransform,this.treeScale,d);l&&(f=l(d,f)),i.transform=f;const{x:m,y:p}=this.projectionDelta;i.transformOrigin=`${m.origin*100}% ${p.origin*100}% 0`,c.animationValues?i.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:i.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const b in $n){if(d[b]===void 0)continue;const{correct:v,applyTo:T,isCSSVariable:w}=$n[b],M=f==="none"?d[b]:v(d[b],c);if(T){const E=T.length;for(let $=0;$<E;$++)i[T[$]]=M}else w?this.options.visualElement.renderState.vars[b]=M:i[b]=M}this.options.layoutId&&(i.pointerEvents=c===this?as(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(ho),this.root.sharedNodes.clear()}}}function lh(e){e.updateLayout()}function ch(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:r}=e.options,o=t.source!==e.layout.source;r==="size"?$e(d=>{const f=o?t.measuredBox[d]:t.layoutBox[d],m=Ee(f);f.min=n[d].min,f.max=f.min+m}):cl(r,t.layoutBox,n)&&$e(d=>{const f=o?t.measuredBox[d]:t.layoutBox[d],m=Ee(n[d]);f.max=f.min+m,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+m)});const i=Zt();kn(i,n,t.layoutBox);const a=Zt();o?kn(a,e.applyTransform(s,!0),t.measuredBox):kn(a,n,t.layoutBox);const l=!il(i);let c=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:m}=d;if(f&&m){const p=ye();Nn(p,t.layoutBox,f.layoutBox);const b=ye();Nn(b,n,m.layoutBox),ol(p,b)||(c=!0),d.options.layoutRoot&&(e.relativeTarget=b,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:a,layoutDelta:i,hasLayoutChanged:l,hasRelativeLayoutChanged:c})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function uh(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function dh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function fh(e){e.clearSnapshot()}function ho(e){e.clearMeasurements()}function mo(e){e.isLayoutDirty=!1}function hh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function po(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function mh(e){e.resolveTargetDelta()}function ph(e){e.calcProjection()}function gh(e){e.resetSkewAndRotation()}function yh(e){e.removeLeadSnapshot()}function go(e,t,n){e.translate=me(t.translate,0,n),e.scale=me(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function yo(e,t,n,s){e.min=me(t.min,n.min,s),e.max=me(t.max,n.max,s)}function xh(e,t,n,s){yo(e.x,t.x,n.x,s),yo(e.y,t.y,n.y,s)}function bh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const vh={duration:.45,ease:[.4,0,.1,1]},xo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),bo=xo("applewebkit/")&&!xo("chrome/")?Math.round:Be;function vo(e){e.min=bo(e.min),e.max=bo(e.max)}function wh(e){vo(e.x),vo(e.y)}function cl(e,t,n){return e==="position"||e==="preserve-aspect"&&!Af(uo(t),uo(n),.2)}function Sh(e){return e!==e.root&&e.scroll?.wasRoot}const Th=ll({attachResizeListener:(e,t)=>Ln(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Bs={current:void 0},ul=ll({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Bs.current){const e=new Th({});e.mount(window),e.setOptions({layoutScroll:!0}),Bs.current=e}return Bs.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),jh={pan:{Feature:zf},drag:{Feature:Uf,ProjectionNode:ul,MeasureLayout:nl}};function wo(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,o=s[r];o&&ce.postRender(()=>o(t,zn(t)))}class Ch extends Tt{mount(){const{current:t}=this.node;t&&(this.unmount=qu(t,(n,s)=>(wo(this.node,s,"Start"),r=>wo(this.node,r,"End"))))}unmount(){}}class Ph extends Tt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Fn(Ln(this.node.current,"focus",()=>this.onFocus()),Ln(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function So(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),o=s[r];o&&ce.postRender(()=>o(t,zn(t)))}class Ah extends Tt{mount(){const{current:t}=this.node;t&&(this.unmount=Yu(t,(n,s)=>(So(this.node,s,"Start"),(r,{success:o})=>So(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const hr=new WeakMap,Us=new WeakMap,Eh=e=>{const t=hr.get(e.target);t&&t(e)},Mh=e=>{e.forEach(Eh)};function kh({root:e,...t}){const n=e||document;Us.has(n)||Us.set(n,{});const s=Us.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(Mh,{root:e,...t})),s[r]}function Nh(e,t,n){const s=kh(t);return hr.set(e,n),s.observe(e),()=>{hr.delete(e),s.unobserve(e)}}const Rh={some:0,all:1};class Dh extends Tt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:o}=t,i={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:Rh[r]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:f}=this.node.getProps(),m=c?d:f;m&&m(l)};return Nh(this.node.current,i,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Vh(t,n))&&this.startObserver()}unmount(){}}function Vh({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const dl={inView:{Feature:Dh},tap:{Feature:Ah},focus:{Feature:Ph},hover:{Feature:Ch}},Ih={layout:{ProjectionNode:ul,MeasureLayout:nl}},Oh={...Ya,...dl,...jh,...Ih},$h=Ld(Oh,Xa),Lh={renderer:Xa,...Ya,...dl};function Jr(e,t){return ls(e,t)}const Fh=Jr("button"),ns=Jr("div"),Bh=Jr("p");function Uh({toolName:e,description:t,args:n,onApprove:s,onDeny:r}){const o=Object.keys(n).length>0;return u.jsx("div",{className:"bg-stone-100 dark:bg-stone-800 border border-border rounded-lg px-3 py-2.5 my-1.5",children:u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"flex items-center gap-1.5 mb-1",children:u.jsx("span",{className:"text-sm font-medium text-foreground",children:e})}),o&&u.jsx("div",{className:"space-y-0.5 mb-1.5",children:Object.entries(n).map(([i,a])=>u.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[u.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[i,":"]}),u.jsx("span",{className:"font-mono text-foreground",children:typeof a=="string"?a:JSON.stringify(a)})]},i))})]}),u.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[u.jsxs(Ce,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[u.jsx(se.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),u.jsx(Ce,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:u.jsx(se.X,{className:"h-3 w-3"})})]})]})})}function zh({toolName:e,args:t,isDenied:n,isSafe:s}){const[r,o]=h.useState(!1);if(e==="fetchDocContent")return null;const i=["k","maxResults","_organizationId"];e==="searchDocs"&&i.push("filters");const a=Object.fromEntries(Object.entries(t).filter(([c])=>!i.includes(c))),l=Object.keys(a).length>0;return u.jsxs("div",{className:"my-1",children:[u.jsxs("button",{onClick:()=>l&&o(!r),className:`inline-flex items-center gap-1.5 text-xs rounded-md px-2 py-1 transition-colors bg-muted text-muted-foreground ${l?"cursor-pointer hover:bg-muted/80":""}`,children:[l&&u.jsx("span",{className:"transition-transform duration-200",children:r?u.jsx(se.ChevronDown,{className:"h-3 w-3"}):u.jsx(se.ChevronRight,{className:"h-3 w-3"})}),n?u.jsx(se.X,{className:"h-3 w-3"}):s?u.jsx(se.Zap,{className:"h-3 w-3"}):u.jsx(se.Check,{className:"h-3 w-3"}),u.jsxs("span",{className:"font-medium",children:[n?"Denied":s?"Auto-executed":"Executed"," ",e]})]}),r&&l&&u.jsx("div",{className:"mt-1 ml-6 p-2 bg-stone-50 dark:bg-stone-900 rounded-md border border-border",children:u.jsx("div",{className:"space-y-0.5",children:Object.entries(a).map(([c,d])=>u.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[u.jsxs("span",{className:"text-muted-foreground min-w-[60px]",children:[c,":"]}),u.jsx("span",{className:"font-mono text-foreground",children:typeof d=="string"?d:JSON.stringify(d)})]},c))})})]})}function _h({...e}){return u.jsx(mr.Root,{"data-slot":"collapsible",...e})}function Xh({...e}){return u.jsx(mr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function Wh({...e}){return u.jsx(mr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const qh=h.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Zr=h.memo(({className:e,...t})=>typeof window>"u"?null:u.jsx(h.Suspense,{fallback:null,children:u.jsx(qh,{className:oe("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Zr.displayName="Response";const Kh=Object.freeze(Object.defineProperty({__proto__:null,Response:Zr},Symbol.toStringTag,{value:"Module"})),Gh=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=$h.create(t),i=h.useMemo(()=>(e?.length??0)*r,[e,r]);return u.jsx(o,{animate:{backgroundPosition:"0% center"},className:oe("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",n),initial:{backgroundPosition:"100% center"},style:{"--spread":`${i}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:s,ease:"linear"},children:e})},Hh=h.memo(Gh),fl=h.createContext(null),Yh=()=>{const e=h.useContext(fl);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Jh=1e3,Zh=1e3,hl=h.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,c]=ii.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,f]=ii.useControllableState({prop:o,defaultProp:0}),[m,p]=h.useState(!1),[b,v]=h.useState(null);h.useEffect(()=>{t?b===null&&v(Date.now()):b!==null&&(f(Math.ceil((Date.now()-b)/Zh)),v(null))},[t,b,f]),h.useEffect(()=>{if(s&&!t&&l&&!m){const w=setTimeout(()=>{c(!1),p(!0)},Jh);return()=>clearTimeout(w)}},[t,l,s,c,m]);const T=w=>{c(w)};return u.jsx(fl.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:c,duration:d},children:u.jsx(_h,{className:oe("not-prose mb-4",e),onOpenChange:T,open:l,...a,children:i})})}),Qh=(e,t)=>e||t===0?u.jsx(Hh,{duration:1,children:"Thinking..."}):t===void 0?u.jsx("p",{children:"Thought for a few seconds"}):u.jsxs("p",{children:["Thought for ",t," seconds"]}),ml=h.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Yh();return u.jsx(Xh,{className:oe("flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",e),...n,children:t??u.jsxs(u.Fragment,{children:[u.jsx(se.BrainIcon,{className:"size-4"}),Qh(s,o),u.jsx(se.ChevronDownIcon,{className:oe("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),pl=h.memo(({className:e,children:t,...n})=>u.jsx(Wh,{className:oe("mt-4 text-sm","data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",e),...n,children:u.jsx(Zr,{className:"grid gap-2",children:t})}));hl.displayName="Reasoning";ml.displayName="ReasoningTrigger";pl.displayName="ReasoningContent";function To(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function em({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=To(s.domain);return u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsxs("button",{className:oe("inline-flex items-center gap-1 px-1 py-0.5 rounded text-[10px] font-medium","bg-stone-200/60 dark:bg-stone-700/60 text-stone-800 dark:text-stone-200","hover:bg-stone-300/80 dark:hover:bg-stone-600/80","transition-all duration-200","border border-stone-300/60 dark:border-stone-600/60","cursor-pointer hover:scale-105 active:scale-95","leading-tight",n),onClick:o=>{o.preventDefault(),o.stopPropagation(),window.open(s.url,"_blank","noopener,noreferrer")},children:[u.jsx("img",{src:r,alt:"",className:"w-3 h-3 leading-none",onError:o=>{const i=o.target;i.style.display="none"}}),u.jsx("span",{className:"leading-none",children:s.domain})]})}),u.jsx(bt,{side:"top",className:"bg-stone-800 dark:bg-stone-900 border border-stone-700 dark:border-stone-600 p-3 max-w-sm z-50 rounded-lg shadow-lg",children:u.jsxs("div",{className:"space-y-1.5",children:[u.jsxs("div",{className:"text-xs font-semibold text-stone-300 dark:text-stone-200 mb-2 pb-2 border-b border-stone-700 dark:border-stone-600",children:["Sources • ",e.length]}),e.map(o=>{const i=o.title||o.domain;return u.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:oe("flex items-center gap-2 p-2 rounded-md hover:bg-stone-700/50 dark:hover:bg-stone-700/50 transition-colors","text-stone-300 dark:text-stone-300 hover:text-white dark:hover:text-white"),onClick:a=>a.stopPropagation(),children:[u.jsx("img",{src:To(o.domain),alt:"",className:"w-4 h-4 flex-shrink-0",onError:a=>{const l=a.target;l.style.display="none"}}),u.jsx("span",{className:"text-xs flex-1 truncate",children:i})]},o.number)})]})})]})}function tm({text:e,citations:t,citationMap:n,groupedCitations:s,referencesText:r,ResponseComponent:o,className:i,showCitations:a=!0,showReferences:l=!0}){const c=h.useRef(null),[d,f]=h.useState([]);h.useEffect(()=>{if(!a||!c.current||t.length===0||n.size===0){(n.size===0||!a)&&f([]);return}const T=c.current;let w,M=!1;const E=new WeakSet,$=()=>{if(!c.current||M)return;M=!0;const I=c.current,k=/\[(\d+)\]/g,C=document.createTreeWalker(I,NodeFilter.SHOW_TEXT,null),V=[];let A;for(;A=C.nextNode();)if(A.nodeType===Node.TEXT_NODE&&!E.has(A)){const L=A,O=L.textContent||"";let F=L.parentElement,_=!1;for(;F&&F!==I;){if(F.tagName==="A"||F.tagName==="CODE"||F.tagName==="PRE"){_=!0;break}F=F.parentElement}if(!_){const K=Array.from(O.matchAll(k)).filter(ae=>{if(!ae[1])return!1;const ve=parseInt(ae[1],10);return n.has(ve)});K.length>0&&V.push({node:L,matches:K})}}if(V.length===0){M=!1;return}const N=[];V.forEach(({node:L,matches:O})=>{E.add(L);const F=L.textContent||"",_=document.createDocumentFragment();let G=0;O.forEach(K=>{if(!K[1])return;K.index!==void 0&&K.index>G&&_.appendChild(document.createTextNode(F.slice(G,K.index)));const ae=document.createElement("span");ae.className="inline-flex items-center citation-button-container";const ve=parseInt(K[1],10);ae.setAttribute("data-citation",K[1]),_.appendChild(ae),N.push({element:ae,citationNum:ve}),G=(K.index||0)+K[0].length}),G<F.length&&_.appendChild(document.createTextNode(F.slice(G))),L.parentNode&&L.parentNode.replaceChild(_,L)}),N.length>0&&f(L=>{const O=new Set(L.map(G=>G.element)),F=L.filter(G=>G.element.isConnected),_=N.filter(G=>!O.has(G.element));return[...F,..._]}),M=!1},D=new MutationObserver(()=>{clearTimeout(w),w=setTimeout($,100)});return D.observe(T,{childList:!0,subtree:!0,characterData:!0}),w=setTimeout($,200),()=>{D.disconnect(),clearTimeout(w)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(T){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(T)}&sz=16`}function b(T){try{return new URL(T).hostname.replace(/^www\./,"")}catch{return T}}const v=a&&l&&m?u.jsxs("div",{className:"mt-4 pt-4 border-t border-stone-200 dark:border-stone-700",children:[u.jsx("div",{className:"text-xs font-semibold text-stone-600 dark:text-stone-400 mb-3",children:"References"}),u.jsx("div",{className:"flex flex-wrap gap-2",children:s&&s.length>0?s.map((T,w)=>{const M=T.title||T.baseUrl,E=b(T.url),$=p(E);return u.jsxs("a",{href:T.url,target:"_blank",rel:"noopener noreferrer",className:oe("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[u.jsx("img",{src:$,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:D=>{const I=D.target;I.style.display="none"}}),u.jsx("span",{className:"leading-none",children:M})]},`group-${w}`)}):Array.from(n.entries()).sort(([T],[w])=>T-w).map(([T,w])=>{const M=b(w),E=p(M);return u.jsxs("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:oe("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium","bg-stone-100 dark:bg-stone-800 text-stone-700 dark:text-stone-300","hover:bg-stone-200 dark:hover:bg-stone-700","transition-all duration-200","border border-stone-200 dark:border-stone-700","cursor-pointer hover:scale-105 active:scale-95","no-underline"),children:[u.jsx("img",{src:E,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:$=>{const D=$.target;D.style.display="none"}}),u.jsx("span",{className:"leading-none",children:w})]},T)})})]}):null;return u.jsxs("div",{className:i,children:[u.jsx("div",{ref:c,children:u.jsx(o,{children:e})}),a&&d.filter(({element:T})=>T.isConnected).map(({element:T,citationNum:w},M)=>{if(!t.find(D=>D.number===w))return null;const $=Array.from(new Map(t.map(D=>{const I=D.url.replace(/\/+$/,""),k=s?.find(C=>C.url.replace(/\/+$/,"")===I);return[I,{number:D.number,url:D.url,domain:b(D.url),title:k?.title}]})).values());return Dl.createPortal(u.jsx(em,{sources:$,citationNumber:w},`citation-${w}-${T}`),T,`citation-${w}-${M}`)}),v]})}function ln({...e}){return u.jsx(It.Root,{"data-slot":"dialog",...e})}function nm({...e}){return u.jsx(It.Portal,{"data-slot":"dialog-portal",...e})}function sm({className:e,...t}){return u.jsx(It.Overlay,{"data-slot":"dialog-overlay",className:oe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function cn({className:e,children:t,showCloseButton:n=!0,...s}){return u.jsxs(nm,{"data-slot":"dialog-portal",children:[u.jsx(sm,{}),u.jsxs(It.Content,{"data-slot":"dialog-content",className:oe("bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...s,children:[t,n&&u.jsxs(It.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[u.jsx(se.XIcon,{}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function un({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-header",className:oe("flex flex-col gap-2 text-center sm:text-left",e),...t})}function dn({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-footer",className:oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function fn({className:e,...t}){return u.jsx(It.Title,{"data-slot":"dialog-title",className:oe("text-lg leading-none font-semibold",e),...t})}function hn({className:e,...t}){return u.jsx(It.Description,{"data-slot":"dialog-description",className:oe("text-muted-foreground text-sm",e),...t})}function mn({className:e,type:t,...n}){return u.jsx("input",{type:t,"data-slot":"input",className:oe("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-white px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...n})}function rm({isOpen:e,title:t="Password Required",description:n="Please enter your password to continue",placeholder:s="Enter password...",onComplete:r}){const[o,i]=h.useState(""),[a,l]=h.useState(!1),[c,d]=h.useState(!1),f=async p=>{if(p.preventDefault(),!!o.trim()){d(!0);try{r(o)}finally{d(!1)}}},m=()=>{i(""),r(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:f,children:[u.jsxs(un,{children:[u.jsx(fn,{children:t}),u.jsx(hn,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsxs("div",{className:"relative",children:[u.jsx(mn,{type:a?"text":"password",value:o,onChange:p=>i(p.target.value),placeholder:s,className:"pr-10",autoFocus:!0,disabled:c}),u.jsx("button",{type:"button",onClick:()=>l(!a),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:c,children:a?u.jsx(se.EyeOff,{className:"h-4 w-4"}):u.jsx(se.Eye,{className:"h-4 w-4"})})]})}),u.jsxs(dn,{children:[u.jsx(Ce,{type:"button",variant:"ghost",onClick:m,disabled:c,children:"Cancel"}),u.jsx(Ce,{type:"submit",disabled:!o.trim()||c,children:c?"Submitting...":"Submit"})]})]})})})}function im({isOpen:e,title:t="Email Required",description:n="Please enter your email address",placeholder:s="Enter email address...",onComplete:r}){const[o,i]=h.useState(""),[a,l]=h.useState(!0),[c,d]=h.useState(!1),f=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),m=v=>{i(v),v.trim()?l(f(v)):l(!0)},p=async v=>{if(v.preventDefault(),!o.trim()||!f(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},b=()=>{i(""),l(!0),r(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:p,children:[u.jsxs(un,{children:[u.jsxs(fn,{className:"flex items-center gap-2",children:[u.jsx(se.Mail,{className:"h-5 w-5"}),t]}),u.jsx(hn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(mn,{type:"email",value:o,onChange:v=>m(v.target.value),placeholder:s,className:a?"":"border-red-500",autoFocus:!0,disabled:c}),!a&&u.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid email address"})]}),u.jsxs(dn,{children:[u.jsx(Ce,{type:"button",variant:"ghost",onClick:b,disabled:c,children:"Cancel"}),u.jsx(Ce,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function om({isOpen:e,title:t="Phone Number Required",description:n="Please enter your phone number",placeholder:s="Enter phone number...",onComplete:r}){const[o,i]=h.useState(""),[a,l]=h.useState(!0),[c,d]=h.useState(!1),f=T=>{const w=T.replace(/\D/g,"");return w.length<=3?w:w.length<=6?`(${w.slice(0,3)}) ${w.slice(3)}`:`(${w.slice(0,3)}) ${w.slice(3,6)}-${w.slice(6,10)}`},m=T=>T.replace(/\D/g,"").length===10,p=T=>{const w=f(T);i(w),w.trim()?l(m(w)):l(!0)},b=async T=>{if(T.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const w=o.replace(/\D/g,"");r(w)}finally{d(!1)}},v=()=>{i(""),l(!0),r(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:b,children:[u.jsxs(un,{children:[u.jsxs(fn,{className:"flex items-center gap-2",children:[u.jsx(se.Phone,{className:"h-5 w-5"}),t]}),u.jsx(hn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(mn,{type:"tel",value:o,onChange:T=>p(T.target.value),placeholder:s,className:a?"":"border-red-500",maxLength:14,autoFocus:!0,disabled:c}),!a&&u.jsx("p",{className:"text-sm text-red-500 mt-1",children:"Please enter a valid 10-digit phone number"})]}),u.jsxs(dn,{children:[u.jsx(Ce,{type:"button",variant:"ghost",onClick:v,disabled:c,children:"Cancel"}),u.jsx(Ce,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function am({isOpen:e,title:t="PIN Required",description:n="Please enter your PIN",placeholder:s="Enter PIN...",length:r=4,onComplete:o}){const[i,a]=h.useState(""),[l,c]=h.useState(!1),d=p=>{const b=p.replace(/\D/g,"");a(b.slice(0,r))},f=async p=>{if(p.preventDefault(),i.length===r){c(!0);try{o(i)}finally{c(!1)}}},m=()=>{a(""),o(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:f,children:[u.jsxs(un,{children:[u.jsxs(fn,{className:"flex items-center gap-2",children:[u.jsx(se.Shield,{className:"h-5 w-5"}),t]}),u.jsx(hn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(mn,{type:"password",value:i,onChange:p=>d(p.target.value),placeholder:s,className:"text-center text-lg tracking-widest",maxLength:r,autoFocus:!0,disabled:l}),u.jsxs("p",{className:"text-sm text-gray-500 mt-1 text-center",children:["Enter ",r,"-digit PIN"]})]}),u.jsxs(dn,{children:[u.jsx(Ce,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),u.jsx(Ce,{type:"submit",disabled:i.length!==r||l,children:l?"Submitting...":"Submit"})]})]})})})}function zs({isOpen:e,title:t="Secure Input Required",description:n="Please enter the requested information",placeholder:s="Enter value...",type:r="password",onComplete:o}){const[i,a]=h.useState(""),[l,c]=h.useState(!1),d=async m=>{if(m.preventDefault(),!!i.trim()){c(!0);try{o(i)}finally{c(!1)}}},f=()=>{a(""),o(null)};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:d,children:[u.jsxs(un,{children:[u.jsxs(fn,{className:"flex items-center gap-2",children:[u.jsx(se.Lock,{className:"h-5 w-5"}),t]}),u.jsx(hn,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsx(mn,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),u.jsxs(dn,{children:[u.jsx(Ce,{type:"button",variant:"ghost",onClick:f,disabled:l,children:"Cancel"}),u.jsx(Ce,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function lm({isOpen:e,title:t,description:n,fields:s,onComplete:r,submitText:o="Submit",cancelText:i="Cancel"}){const[a,l]=h.useState(()=>{const A={};return s.forEach(N=>{A[N.name]=N.value||""}),A}),[c,d]=h.useState({}),[f,m]=h.useState({}),[p,b]=h.useState(!1),v=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)?null:"Please enter a valid email address",T=A=>A.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",w=(A,N=4)=>A.length===N?null:`PIN must be ${N} digits`,M=A=>{const N=A.replace(/\D/g,"");return N.length<=3?N:N.length<=6?`(${N.slice(0,3)}) ${N.slice(3)}`:`(${N.slice(0,3)}) ${N.slice(3,6)}-${N.slice(6,10)}`},E=(A,N,L)=>{let O=N,F=null;switch(L.type){case"phone":O=M(N),O.trim()&&(F=T(O));break;case"email":N.trim()&&(F=v(N));break;case"pin":O=N.replace(/\D/g,"").slice(0,6),O.trim()&&(F=w(O));break}!F&&L.validation&&O.trim()&&(F=L.validation(O)),l(_=>({..._,[A]:O})),d(_=>({..._,[A]:F||""}))},$=()=>{const A={};let N=!0;return s.forEach(L=>{const O=a[L.name]||"";let F=null;if(L.required&&!O.trim())F=`${L.label} is required`;else if(O.trim()){switch(L.type){case"email":F=v(O);break;case"phone":F=T(O);break;case"pin":F=w(O);break}!F&&L.validation&&(F=L.validation(O))}F&&(A[L.name]=F,N=!1)}),d(A),N},D=async A=>{if(A.preventDefault(),!!$()){b(!0);try{const N={};s.forEach(L=>{const O=a[L.name]?.trim();O&&(L.type==="phone"?N[L.name]=O.replace(/\D/g,""):N[L.name]=O)}),r(N)}finally{b(!1)}}},I=()=>{l({}),d({}),m({}),r(null)},k=A=>{m(N=>({...N,[A]:!N[A]}))},C=A=>{switch(A.type){case"password":return f[A.name]?"text":"password";case"email":return"email";case"phone":return"tel";case"pin":case"ssn":return"password";default:return"text"}},V=A=>{if(A.placeholder)return A.placeholder;switch(A.type){case"email":return"Enter email address...";case"phone":return"Enter phone number...";case"password":return"Enter password...";case"pin":return"Enter PIN...";case"ssn":return"XXX-XX-XXXX";case"creditCard":return"XXXX XXXX XXXX XXXX";default:return`Enter ${A.label.toLowerCase()}...`}};return u.jsx(ln,{open:e,children:u.jsx(cn,{showCloseButton:!1,className:"max-w-md",children:u.jsxs("form",{onSubmit:D,children:[u.jsxs(un,{children:[u.jsx(fn,{children:t}),n&&u.jsx(hn,{children:n})]}),u.jsx("div",{className:"py-4 space-y-4",children:s.map(A=>u.jsxs("div",{children:[u.jsxs("label",{className:"block text-sm font-medium mb-1",children:[A.label,A.required&&u.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),u.jsxs("div",{className:"relative",children:[u.jsx(mn,{type:C(A),value:a[A.name]||"",onChange:N=>E(A.name,N.target.value,A),placeholder:V(A),className:c[A.name]?"border-red-500":"",disabled:p,autoFocus:A===s[0],maxLength:A.type==="pin"?6:A.type==="phone"?14:void 0}),A.type==="password"&&u.jsx("button",{type:"button",onClick:()=>k(A.name),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",disabled:p,children:f[A.name]?u.jsx(se.EyeOff,{className:"h-4 w-4"}):u.jsx(se.Eye,{className:"h-4 w-4"})})]}),c[A.name]&&u.jsxs("div",{className:"flex items-center gap-1 mt-1 text-sm text-red-500",children:[u.jsx(se.AlertCircle,{className:"h-3 w-3"}),c[A.name]]})]},A.name))}),u.jsxs(dn,{children:[u.jsx(Ce,{type:"button",variant:"ghost",onClick:I,disabled:p,children:i}),u.jsx(Ce,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const gl=h.createContext(void 0);function yl(){const e=h.useContext(gl);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function xl({children:e}){const[t,n]=h.useState(null),[s,r]=h.useState(null),o=h.useRef(null),i=h.useRef(null),a=h.useCallback(p=>new Promise(b=>{n(p),o.current=b}),[]),l=h.useCallback(p=>new Promise(b=>{r(p),i.current=b}),[]),c=h.useCallback(p=>{o.current&&(o.current(p),o.current=null),n(null)},[]),d=h.useCallback(p=>{i.current&&(i.current(p),i.current=null),r(null)},[]),f=()=>{if(s){const b=s.fields.map(v=>({name:v.name,type:v.type==="text"?"text":v.type==="password"?"password":v.type==="email"?"email":v.type==="phone"?"phone":v.type==="pin"?"pin":v.type==="ssn"?"ssn":v.type==="creditCard"?"creditCard":"text",label:v.label,placeholder:v.placeholder,required:v.required!==!1,value:v.value}));return u.jsx(lm,{isOpen:!0,title:s.title,description:s.description,fields:b,onComplete:d})}if(!t)return null;const p={isOpen:!0,title:t.title,description:t.description,placeholder:t.placeholder,onComplete:c};switch(t.type){case"password":return u.jsx(rm,{...p});case"email":return u.jsx(im,{...p});case"phone":return u.jsx(om,{...p});case"pin":return u.jsx(am,{...p});case"ssn":return u.jsx(zs,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return u.jsx(zs,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return u.jsx(zs,{...p})}},m=h.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return u.jsxs(gl.Provider,{value:m,children:[e,f()]})}function cm(e){try{const t=new URL(e),n=`${t.protocol}//${t.host}${t.pathname}`,s=t.hash?t.hash.substring(1):void 0;return{baseUrl:n,anchor:s}}catch{const t=e.indexOf("#");return t!==-1?{baseUrl:e.substring(0,t),anchor:e.substring(t+1)}:{baseUrl:e}}}function um(e){try{const t=new URL(e),s=t.pathname.split("/").filter(a=>a.length>0);if(s.length===0)return t.hostname;const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||t.hostname}catch{const t=e.indexOf("#"),n=t!==-1?e.substring(0,t):e,s=n.split("/").filter(r=>r.length>0);if(s.length>0){const r=s[s.length-1];return r&&r.replace(/\.(md|mdx|html|htm)$/i,"").replace(/[-_]/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()).join(" ")||n}return n}}function jo(e){let t=e.replace(/_+$/gm,"");const n=/(?:^|\n)(?:#+\s*)?(?:References|References:)(?:\*\*)?\s*\n?([\s\S]*?)(?=\n\n|\n#|$)/i,s=t.match(n),r=new Map,o=[],i=new Map,a=new Map,l=new Map,c=new Map;if(s&&s[1]){const C=s[1],V=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let A;for(;(A=V.exec(C))!==null;)if(A[1]&&A[2]){const N=parseInt(A[1],10),L=A[2].replace(/[.,;:!?]+$/,""),O=L.replace(/\/+$/,"");if(a.has(O)||a.set(O,L),i.has(O)||i.set(O,[]),i.get(O).push(N),!l.has(O))l.set(O,N);else{const F=l.get(O);N<F&&l.set(O,N)}}for(const[N,L]of i.entries()){const O=l.get(N);for(const F of L)F!==O&&c.set(F,O)}for(const[N,L]of l.entries()){const O=a.get(N)||N;r.set(L,O),o.push({number:L,url:O})}}let d,f=t;s&&s[0]&&(d=s[0],f=t.replace(n,""));const m=[];let p=0;const b=/```[\s\S]*?```|`[^`]+`/g;let v;for(;(v=b.exec(f))!==null;)v.index>p&&m.push({type:"text",content:f.slice(p,v.index),start:p,end:v.index}),m.push({type:"code",content:v[0],start:v.index,end:v.index+v[0].length}),p=v.index+v[0].length;p<f.length&&m.push({type:"text",content:f.slice(p),start:p,end:f.length});const T=m.map(C=>{if(C.type==="code")return C.content;let V=C.content;return V=V.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(N,L,O)=>{const F=parseInt(L,10),_=O.replace(/\/+$/,""),G=c.get(F)||F;return l.has(_)||(l.set(_,G),r.has(G)||(r.set(G,O),o.push({number:G,url:O}))),`[${G}]`}),V=V.replace(/\[(\d+)\]/g,(N,L)=>{const O=parseInt(L,10);return`[${c.get(O)||O}]`}),V}),w=[];for(const[C,V]of l.entries()){const A=a.get(C)||C,{baseUrl:N,anchor:L}=cm(A),O=um(A);w.push({url:A,baseUrl:N,numbers:[V],anchor:L,title:O})}w.sort((C,V)=>(C.numbers[0]||0)-(V.numbers[0]||0));const M=new Map;let E=1;for(const C of w){const V=C.numbers[0];M.set(V,E),C.numbers=[E],E++}const $=new Map;for(const[C,V]of r.entries()){const A=M.get(C);A&&$.set(A,V)}const D=o.map(C=>{const V=M.get(C.number);return V?{number:V,url:C.url}:C}).filter(C=>M.has(C.number)),I=Array.from(M.entries()).sort((C,V)=>V[0]-C[0]);let k=T.join("");for(const[C,V]of I){const A=new RegExp(`\\[${C}\\](?!\\d)`,"g");k=k.replace(A,`[${V}]`)}return{processedText:k,citations:D.sort((C,V)=>C.number-V.number),citationMap:$,groupedCitations:w,referencesText:d}}function Rn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Rn(t)}catch{return e}if(Array.isArray(e))return e.map(Rn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Rn(s);return t}return e}function _s(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Rn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Rn(e):{}}function dm({theme:e="auto",layout:t="sidebar",model:n="auto",animated:s=!0,title:r="Chat",logo:o=void 0,defaultWidth:i=384,minWidth:a=300,maxWidth:l=800,initiallyExpanded:c=!1,tools:d=[],safeTools:f=[],safeToolNames:m,toolMetadata:p,systemPrompt:b="",agentId:v,agentName:T,tokenEndpoint:w="/api/arcten/token",apiBaseUrl:M="https://api.arcten.com",user:E,state:$,onStateChange:D,allowStateEdits:I=!0,sources:k,ragConfig:C,showCitations:V=!0,sensitiveParams:A,autoDetectSensitive:N=!1}){const L=M.replace(/\/+$/,""),{showSecureModal:O}=yl(),F=ko({apiBaseUrl:L,tokenEndpoint:w,user:E,tools:d,safeTools:f,toolMetadata:p,sensitiveParams:A,autoDetectSensitive:N,agentId:v,agentName:T,state:$,onStateChange:D,allowStateEdits:I,sources:k,ragConfig:C});h.useMemo(()=>C!==void 0?C:k&&k.length>0?{enabled:!0,organizationId:k[0],autoExecute:!0,filters:void 0}:{enabled:!1},[k,C]);const[_,G]=h.useState(c),[K,ae]=h.useState(i),[ve,He]=h.useState(600),[jt,et]=h.useState(!1),[H,Ot]=h.useState(!1),[Me,Ct]=h.useState(!1),[Pe,Ue]=h.useState({x:100,y:100}),[$t,le]=h.useState(!1),[pn,ct]=h.useState({x:0,y:0}),[ut,gn]=h.useState(!1),ze=h.useRef(null),Pt=h.useRef(null),[At,Ve]=h.useState(""),[yn,vs]=h.useState(null),[Lt,Ft]=h.useState("Thinking..."),[dt,Ie]=h.useState(new Set),[Qr,_n]=h.useState(""),[Ye,Xn]=h.useState([]),ws=h.useRef(new Map),Bt=h.useRef(!1),xn=h.useRef(""),[Ut,ue]=h.useState(!1),[ft,tt]=h.useState(!1),pe=h.useMemo(()=>[...d,...f],[d,f]),_e=h.useMemo(()=>pr(pe,p),[pe,p]),bn=h.useMemo(()=>{const j=new Map,U=new Map(_e.map(X=>[X.name,X]));return pe.forEach(X=>{const J=X[Le];if(J){const ee=U.get(J);if(ee){j.set(ee.name,X);return}}const Y=_e.find(ee=>ee.name===X.name);Y&&j.set(Y.name,X)}),j},[pe,_e]),ht=h.useMemo(()=>{const j=new Set,U=new Map(_e.map(X=>[X.name,X]));return f.forEach(X=>{const J=X[Le];if(J&&U.has(J))j.add(J);else{const Y=_e.find(ee=>ee.name===X.name);Y&&j.add(Y.name)}}),m&&Array.isArray(m)&&m.forEach(X=>{typeof X=="string"&&j.add(X)}),j},[f,_e,m]),Wn=["Thinking...","Pondering...","Contemplating...","Considering...","Analyzing...","Processing...","Reasoning...","Mulling it over...","Computing...","Cooking up a response...","Brewing ideas...","Connecting the dots...","Piecing it together...","Spinning up thoughts...","Loading brain cells...","Sharpening pencils...","Herding ideas...","Warming up neurons...","Stirring the think-pot...","Plotting a plan...","Wiggling the logic wires...","Rolling ideas around...","Charging the brainstorm...","Booting the brain...","Dusting off the cortex...","Running mental diagnostics...","Fetching cleverness...","Whisking up notions...","Tuning the idea radio...","Juggling possibilities...","Breathing in inspiration...","Squeezing the thought sponge...","Tickling the gray matter...","Bubbling up insights...","Spicing the soup of thought...","Lacing up hypotheses...","Winding the idea clock...","Casting the net for clues...","Polishing the crystal ball...","Mapping the maze...","Crunching the brain-biscuits...","Cueing the eureka moment...","Summoning the muse...","Knocking on insight’s door...","Combing the noodle...","Sailing the think-ship...","Scooping brain gelato...","Testing wild hunches...","Tick-tocking the neurons...","Planting idea seeds...","Shaking the thought snow globe...","Unlocking the mental toolbox...","Nudging the puzzle pieces...","Lighting the idea bulb...","Preheating the oven of insight...","Mixing the mental trail mix...","Spooling up reasoning reels...","Skimming the mind-palace index...","Surfing the thought waves...","Kicking the tires on ideas...","Rattling the idea can...","Waving the logic wand..."];h.useEffect(()=>{if(typeof window<"u"){const j=localStorage.getItem("arcten-sidebar-expanded");j&&G(JSON.parse(j));const U=localStorage.getItem("arcten-sidebar-width");U&&ae(parseInt(U));const X=localStorage.getItem("arcten-sidebar-height");X&&He(parseInt(X));const J=localStorage.getItem("arcten-sidebar-detached");J&&Ot(JSON.parse(J));const Y=localStorage.getItem("arcten-sidebar-position");if(Y){const Ne=JSON.parse(Y),re=50,Se=Math.max(re-i,Math.min(Ne.x,window.innerWidth-re)),W=Math.max(0,Math.min(Ne.y,window.innerHeight-re));Ue({x:Se,y:W})}const ee=localStorage.getItem("arcten-sidebar-minimized");ee&&Ct(JSON.parse(ee)),gn(!0)}},[]),h.useMemo(()=>E,[E?.id]),h.useEffect(()=>{(async()=>{if(pe.length===0)return;const U=pe.map(X=>`${X.name}:${X.toString()}`).join("|");if(U!==xn.current&&!Bt.current){Bt.current=!0,xn.current=U;try{const X=pe.map(Y=>({name:Y.name,code:Y.toString()})),J=await fetch(`${L}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:X})});if(J.ok){const Y=await J.json();Y.tools&&Y.tools.forEach(ee=>{ws.current.set(ee.name,ee)}),Xn(Y.tools)}}catch(X){console.error("Failed to fetch tool descriptions:",X)}finally{Bt.current=!1}}})()},[pe,L]),h.useEffect(()=>{Promise.resolve().then(()=>Kh).then(j=>{vs(()=>j.Response)})},[]),h.useEffect(()=>{const j=()=>{_n(window.location.pathname)};j(),window.addEventListener("popstate",j);const U=setInterval(j,500);return()=>{window.removeEventListener("popstate",j),clearInterval(U)}},[]);const{id:vn,messages:ke,sendMessage:wn,status:we,error:nt,stop:zt,addToolOutput:st,setMessages:ei,clientToken:Ss,tokenError:_t,conversations:Sn,isLoadingConversations:mt,loadConversation:rt,deleteConversation:Xt,startNewConversation:Xe}=F;h.useEffect(()=>{_&&Pt.current&&Pt.current.focus()},[_,ke]),h.useEffect(()=>{const j=ke[ke.length-1];if(!j||j.role!=="assistant")return;const U=j.parts?.filter(X=>X.type?.startsWith("tool-")&&X.state==="input-available"&&typeof X.toolCallId=="string"&&X.input!==void 0)||[];for(const X of U){const J=X,Y=J.type?.replace("tool-","")||"",ee=J.toolCallId;if(ht.has(Y)){if(dt.has(ee))continue;Ie(re=>re.has(ee)?re:new Set(re).add(ee)),(async()=>{try{const re=bn.get(Y);if(!re){console.warn(`[ArctenAgent] Tool ${Y} not found in toolsMap`),st({toolCallId:ee,tool:Y,output:`Error: Tool ${Y} not found`}),Ie(ie=>{const Ae=new Set(ie);return Ae.delete(ee),Ae});return}const Se=_s(J.input),W=_e.find(ie=>ie.name===Y);let te;if(W&&W.jsonSchema?.properties){const Ae=Object.keys(W.jsonSchema.properties).map(ge=>Se[ge]);te=await re(...Ae)}else te=await re(...Object.values(Se));st({toolCallId:ee,tool:Y,output:te}),Ie(ie=>{const Ae=new Set(ie);return Ae.delete(ee),Ae})}catch(re){console.error(`[ArctenAgent] Error executing safe tool ${Y}:`,re),st({toolCallId:ee,tool:Y,output:`Error: ${re instanceof Error?re.message:String(re)}`}),Ie(Se=>{const W=new Set(Se);return W.delete(ee),W})}})()}}},[ke,ht,bn,_e,st,dt]);function Je(){G(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function qn(){G(!1),localStorage.setItem("arcten-sidebar-expanded","false")}h.useEffect(()=>{},[_]),h.useEffect(()=>{ze.current&&ze.current.scrollIntoView({behavior:"smooth"})},[ke]),h.useEffect(()=>{function j(U){U.key==="Escape"&&(we==="streaming"||we==="submitted")&&(U.preventDefault(),zt())}return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[we,zt]);function Kn(j){const U=Math.floor((Date.now()-j)/1e3);return U<60?"now":U<3600?`${Math.floor(U/60)}m`:U<86400?`${Math.floor(U/3600)}h`:`${Math.floor(U/86400)}d`}function it(){Xe(),tt(!1)}function pt(j){if(j.preventDefault(),!At.trim())return;(we==="streaming"||we==="submitted")&&zt();const U=Wn[Math.floor(Math.random()*Wn.length)]||"Thinking...";Ft(U),wn({text:At}),Ve("")}function Gn(j){const U=j.target.value;Ve(U)}h.useEffect(()=>{if(!jt)return;function j(X){if(H){const J=X.clientX-Pe.x,Y=X.clientY-Pe.y;J>=a&&J<=l&&ae(J),Y>=400&&Y<=1e3&&He(Y)}else{const J=window.innerWidth-X.clientX;J>=a&&J<=l&&ae(J)}}function U(){et(!1),localStorage.setItem("arcten-sidebar-width",K.toString()),localStorage.setItem("arcten-sidebar-height",ve.toString())}return window.addEventListener("mousemove",j),window.addEventListener("mouseup",U),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",U)}},[jt,K,ve,H,Pe,a,l]);function Hn(j){j.preventDefault(),et(!0)}function gt(){Ot(!0),Ct(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function Wt(){Ot(!1),Ct(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Yn(){Ct(!Me),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Me))}function Tn(j){H&&(le(!0),ct({x:j.clientX-Pe.x,y:j.clientY-Pe.y}))}return h.useEffect(()=>{if(!H)return;function j(){Ue(U=>{const J=window.innerWidth-50,Y=window.innerHeight-50,ee=50-K,Ne=0,re=Math.max(ee,Math.min(U.x,J)),Se=Math.max(Ne,Math.min(U.y,Y));if(re!==U.x||Se!==U.y){const W={x:re,y:Se};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(W)),W}return U})}return window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[H,K]),h.useEffect(()=>{if(!$t)return;function j(X){const J=X.clientX-pn.x,Y=X.clientY-pn.y,ee=50,Ne=window.innerWidth-ee,re=window.innerHeight-ee,Se=ee-K,W=0,te=Math.max(Se,Math.min(J,Ne)),ie=Math.max(W,Math.min(Y,re));Ue({x:te,y:ie})}function U(){le(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(Pe))}return window.addEventListener("mousemove",j),window.addEventListener("mouseup",U),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",U)}},[$t,pn,Pe,K]),ut?_t?u.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:u.jsxs("div",{className:"p-4 bg-destructive/10 text-destructive text-sm rounded-lg",children:["Authentication error: ",_t]})}):Ss?u.jsx(ad,{features:Lh,children:u.jsx(ns,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:H?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:H?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
|
|
14
11
|
${H?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
|
|
15
|
-
${
|
|
12
|
+
${_?"bg-stone-50 dark:bg-stone-900":"bg-stone-100 dark:bg-stone-800 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors duration-200"}
|
|
16
13
|
${H?"border border-border":"border-l border-border"}
|
|
17
|
-
${
|
|
18
|
-
`,style:X?H?{width:`${K}px`,height:ke?"auto":`${be}px`,left:`${Ae.x}px`,top:`${Ae.y}px`}:{width:`${K}px`}:void 0,onClick:X?void 0:Je,children:X?u.jsxs(u.Fragment,{children:[!H&&u.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:Hn,children:u.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),H&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:C=>{C.preventDefault(),tt(!0)}}),u.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:C=>{C.preventDefault(),C.stopPropagation(),ae(!0),ut({x:C.clientX-Ae.x,y:C.clientY-Ae.y})},children:u.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),u.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:C=>{C.preventDefault(),tt(!0)}})]}),u.jsxs("div",{className:"flex flex-col h-full",children:[u.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${H?"cursor-move":""}`,onMouseDown:H?Tn:void 0,children:[u.jsx("h2",{className:`text-base font-semibold ${H&&ke?"cursor-pointer":""}`,onClick:H&&ke?C=>{C.stopPropagation(),Yn()}:void 0,children:r}),u.jsxs("div",{className:"flex items-center gap-1",onClick:C=>C.stopPropagation(),children:[u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"button",className:ie(Mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:ot,"aria-label":"New chat",children:u.jsx(se.Plus,{className:"h-4 w-4"})})}),u.jsx(bt,{children:"Start a new conversation"})]}),u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"button",className:ie(Mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:H?Wt:gt,"aria-label":H?"Dock sidebar":"Float sidebar",children:H?u.jsx(se.Dock,{className:"h-4 w-4"}):u.jsx(se.PictureInPicture2,{className:"h-4 w-4"})})}),u.jsx(bt,{children:H?"Dock to sidebar":"Undock to floating window"})]}),u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"button",className:ie(Mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:H?Yn:qn,"aria-label":H?ke?"Maximize":"Minimize":"Close sidebar",children:H?ke?u.jsx(se.Maximize2,{className:"h-4 w-4"}):u.jsx(se.Minimize2,{className:"h-4 w-4"}):u.jsx(se.X,{className:"h-4 w-4"})})}),u.jsx(bt,{children:H?ke?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!ke&&u.jsxs(u.Fragment,{children:[E&&Sn.length>0&&u.jsxs("div",{className:`border-b border-border ${Ye?"flex flex-col flex-1":""}`,children:[u.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[u.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),u.jsx(Pe,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{nt(!Ye)},children:Ye?"Show less":"View all"})]}),u.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${Ye?"flex-1 overflow-y-auto":""}`,children:Sn.slice(0,Ye?void 0:3).map(C=>u.jsxs("div",{className:"group relative",children:[u.jsxs(Bh,{type:"button",className:ie(Mt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>{it(C.chatId||C._id),nt(!1)},children:[u.jsx("span",{className:"text-xs truncate",children:C.title}),u.jsx("div",{className:"ml-2 flex items-center",children:u.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:Kn(C.updatedAt)})})]}),u.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:U=>{U.stopPropagation(),Xt(C._id)},"aria-label":"Delete conversation",children:u.jsx(se.X,{className:"h-3 w-3"})})]},C._id))})]}),u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[u.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:Ne.length===0?u.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&u.jsx("div",{className:"mb-6",children:o}),u.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),He.length>0&&u.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:u.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Ut?He:He.slice(0,10)).map(C=>u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx(Ps,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Ve(C.sampleUsage),Pt.current?.focus()},children:C.friendlyName})}),u.jsx(bt,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium",children:C.description}),u.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[u.jsx("span",{className:"font-medium",children:"Example:"}),' "',C.sampleUsage,'"']}),C.paramCount>0&&u.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[u.jsx("span",{className:"font-medium",children:"Parameters:"})," ",C.params.join(", ")]})]})})]},C.name)),He.length>10&&!Ut&&u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsxs(Ps,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>ce(!0),children:["+",He.length-10," more"]})}),u.jsx(bt,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),u.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:He.slice(10).map(C=>u.jsxs("div",{children:[u.jsxs("span",{className:"font-medium text-xs",children:[C.friendlyName,":"]}),u.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:C.description})]},C.name))}),u.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Ut&&He.length>10&&u.jsx(Ps,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>ce(!1),children:"Show less"})]})})]}):u.jsxs(u.Fragment,{children:[Ne.map(C=>{const W=C.parts.filter(_=>_.type==="text").map(_=>_.text).join("");let Z=C.parts;C.role==="assistant"&&C.parts.some(pe=>pe.timestamp)&&(Z=[...C.parts].sort((pe,J)=>{const Ee=pe.timestamp||0,ge=J.timestamp||0;return Ee-ge}));let Y=[],te=new Map,Re=[],re,Te=!0;if(C.role==="assistant"){const _=Z.filter(ge=>ge.type==="text"&&ge.text),pe=[],J=[];_.forEach(ge=>{const{citations:Ze,citationMap:ve,groupedCitations:Ce,referencesText:Qe}=Co(ge.text);Y.push(...Ze),pe.push(ve),Ce&&J.push(...Ce),Qe&&(re=Qe)}),pe.forEach(ge=>{ge.forEach((Ze,ve)=>{te.has(ve)||te.set(ve,Ze)})}),Re=Array.from(new Map(J.map(ge=>[ge.url,ge])).values()).sort((ge,Ze)=>(ge.numbers[0]||0)-(Ze.numbers[0]||0)),Te=!(we==="streaming"&&C.id===Ne.at(-1)?.id)}return u.jsx("div",{className:`${C.role==="user"?"flex justify-end":"w-full"}`,children:u.jsx("div",{className:`${C.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:C.role==="user"?u.jsx(Uh,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:W}):u.jsx("div",{className:"space-y-2",children:Z.map((_,pe)=>{if(_.type?.startsWith("tool-")){const J=_.type?.replace("tool-","")||"",Ee=_e.find(ve=>ve.name===J),ge=_.state==="input-available",Ze=_.state==="output-available";if(ge&&ht.has(J),ge){if(ht.has(J))return null;const ve=_s(_.input);return u.jsx(ns,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:u.jsx(zh,{toolName:J,description:Ee?.description||"",args:ve,onApprove:async()=>{if(ft.has(_.toolCallId))return;Ie(Qe=>new Set(Qe).add(_.toolCallId));const Ce=bn.get(J);if(Ce)try{const Qe=await Ce(...Object.values(ve));rt({toolCallId:_.toolCallId,tool:J,output:Qe})}catch(Qe){rt({toolCallId:_.toolCallId,tool:J,output:`Error: ${Qe}`})}},onDeny:async()=>{ft.has(_.toolCallId)||(Ie(Ce=>new Set(Ce).add(_.toolCallId)),rt({toolCallId:_.toolCallId,tool:J,output:"User denied tool execution"}))}})},`${_.toolCallId}-${pe}`)}else if(Ze){const ve=_.output==="User denied tool execution",Ce=_s(_.input);return u.jsx(_h,{toolName:J,args:Ce,isDenied:ve,isSafe:ht.has(J)},`${_.toolCallId}-${pe}`)}return null}if(_.type==="text"&&_.text&&yn){const{processedText:J}=Co(_.text),ve=!Z.slice(pe+1).some(Ce=>Ce.type==="text"&&Ce.text)&&Te&&te.size>0;return u.jsx(nm,{text:J,citations:Y,citationMap:te,groupedCitations:ve?Re:void 0,referencesText:ve?re:void 0,ResponseComponent:yn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:V,showReferences:ve},`${C.id}-${pe}`)}return _.type==="reasoning"&&_.text?u.jsxs(hl,{className:"w-full",isStreaming:we==="streaming"&&pe===C.parts.length-1&&C.id===Ne.at(-1)?.id,children:[u.jsx(ml,{}),u.jsx(pl,{children:_.text})]},`${C.id}-${pe}`):null})})})},C.id)}),u.jsx("div",{ref:ze})]})}),st&&u.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",st.message]}),u.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[u.jsx(ad,{mode:"wait",children:(we==="streaming"||we==="submitted")&&u.jsxs(ns,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[u.jsx(ns,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),u.jsx("p",{className:"text-xs text-muted-foreground",children:Lt})]})}),u.jsxs("form",{onSubmit:pt,className:"relative",children:[u.jsx(No,{ref:Pt,value:At,onChange:Gn,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),pt(C))}}),we==="streaming"||we==="submitted"?u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"button",className:ie(Mt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:zt,children:u.jsx(se.Square,{className:"h-4 w-4"})})}),u.jsxs(bt,{children:[u.jsx(oi,{children:"Escape"})," to stop"]})]}):u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"submit",className:ie(Mt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!At.trim(),children:u.jsx(se.ArrowRight,{className:"h-4 w-4"})})}),u.jsxs(bt,{children:[u.jsx(oi,{children:"Enter"})," to send"]})]})]})]})]}),u.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[u.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),u.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),u.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):u.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[u.jsx(se.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),u.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):u.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:u.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function hm(e){return u.jsx(xl,{children:u.jsx(fm,{...e})})}function mm(e={}){const{apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:n="/token",clientToken:s,skipTokenFetch:r=!1}=e,[o,i]=h.useState(!1),[a,l]=h.useState(null),c=h.useRef(s||null);h.useEffect(()=>{if(s){c.current=s;return}if(r)return;(async()=>{try{const p=await fetch(`${t}${n}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(p.ok){const b=await p.json();c.current=b.token}}catch(p){console.error("[useGenerate] Failed to fetch token:",p)}})()},[t,n,s,r]);const d=h.useCallback(async m=>{i(!0),l(null);try{const p={"Content-Type":"application/json"};c.current&&(p.Authorization=`Bearer ${c.current}`);const b=await fetch(`${t}/generate`,{method:"POST",headers:p,body:JSON.stringify(m)});if(!b.ok){const T=await b.json().catch(()=>({}));throw new Error(T.error||`HTTP ${b.status}`)}return await b.json()}catch(p){const b=p instanceof Error?p.message:String(p);throw l(b),p}finally{i(!1)}},[t]),f=h.useCallback(async(m,p)=>{i(!0),l(null);try{const b={"Content-Type":"application/json"};c.current&&(b.Authorization=`Bearer ${c.current}`);const v=await fetch(`${t}/generate/stream`,{method:"POST",headers:b,body:JSON.stringify(m)});if(!v.ok){const E=await v.json().catch(()=>({}));throw new Error(E.error||`HTTP ${v.status}`)}const T=v.body?.getReader();if(!T)throw new Error("No response body");const w=new TextDecoder;let M=null;for(;;){const{done:E,value:$}=await T.read();if(E)break;const I=w.decode($,{stream:!0}).split(`
|
|
19
|
-
`).filter(k=>k.startsWith("data: "));for(const k of I){const
|
|
14
|
+
${_?"":"w-[30px]"}
|
|
15
|
+
`,style:_?H?{width:`${K}px`,height:Me?"auto":`${ve}px`,left:`${Pe.x}px`,top:`${Pe.y}px`}:{width:`${K}px`}:void 0,onClick:_?void 0:Je,children:_?u.jsxs(u.Fragment,{children:[!H&&u.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500/40 hover:w-1 transition-all group",onMouseDown:Hn,children:u.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),H&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",onMouseDown:j=>{j.preventDefault(),et(!0)}}),u.jsx("div",{className:"absolute bottom-0 left-4 right-4 h-3 cursor-move hover:bg-blue-500/20 group",onMouseDown:j=>{j.preventDefault(),j.stopPropagation(),le(!0),ct({x:j.clientX-Pe.x,y:j.clientY-Pe.y})},children:u.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-1 rounded-full bg-stone-400/30 group-hover:bg-blue-500/40 transition-colors"})}),u.jsx("div",{className:"absolute top-0 right-0 bottom-0 w-1 cursor-ew-resize hover:bg-blue-500/40",onMouseDown:j=>{j.preventDefault(),et(!0)}})]}),u.jsxs("div",{className:"flex flex-col h-full",children:[u.jsxs("div",{className:`flex items-center justify-between p-3 border-b border-border ${H?"cursor-move":""}`,onMouseDown:H?Tn:void 0,children:[u.jsx("h2",{className:`text-base font-semibold ${H&&Me?"cursor-pointer":""}`,onClick:H&&Me?j=>{j.stopPropagation(),Yn()}:void 0,children:r}),u.jsxs("div",{className:"flex items-center gap-1",onClick:j=>j.stopPropagation(),children:[u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"button",className:oe(Mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:it,"aria-label":"New chat",children:u.jsx(se.Plus,{className:"h-4 w-4"})})}),u.jsx(bt,{children:"Start a new conversation"})]}),u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"button",className:oe(Mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:H?Wt:gt,"aria-label":H?"Dock sidebar":"Float sidebar",children:H?u.jsx(se.Dock,{className:"h-4 w-4"}):u.jsx(se.PictureInPicture2,{className:"h-4 w-4"})})}),u.jsx(bt,{children:H?"Dock to sidebar":"Undock to floating window"})]}),u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"button",className:oe(Mt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:H?Yn:qn,"aria-label":H?Me?"Maximize":"Minimize":"Close sidebar",children:H?Me?u.jsx(se.Maximize2,{className:"h-4 w-4"}):u.jsx(se.Minimize2,{className:"h-4 w-4"}):u.jsx(se.X,{className:"h-4 w-4"})})}),u.jsx(bt,{children:H?Me?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Me&&u.jsxs(u.Fragment,{children:[E&&Sn.length>0&&u.jsxs("div",{className:`border-b border-border ${ft?"flex flex-col flex-1":""}`,children:[u.jsxs("div",{className:"flex items-center justify-between px-3 py-1",children:[u.jsx("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Recent chats"}),u.jsx(Ce,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{tt(!ft)},children:ft?"Show less":"View all"})]}),u.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ft?"flex-1 overflow-y-auto":""}`,children:Sn.slice(0,ft?void 0:3).map(j=>u.jsxs("div",{className:"group relative",children:[u.jsxs(Fh,{type:"button",className:oe(Mt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>{rt(j.chatId||j._id),tt(!1)},children:[u.jsx("span",{className:"text-xs truncate",children:j.title}),u.jsx("div",{className:"ml-2 flex items-center",children:u.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:Kn(j.updatedAt)})})]}),u.jsx("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 h-6 w-6 p-0 hidden group-hover:flex items-center justify-center text-muted-foreground hover:text-foreground rounded-md hover:bg-accent transition-colors",onClick:U=>{U.stopPropagation(),Xt(j._id)},"aria-label":"Delete conversation",children:u.jsx(se.X,{className:"h-3 w-3"})})]},j._id))})]}),u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden relative",children:[u.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scroll-smooth",children:ke.length===0?u.jsxs("div",{className:"flex flex-col items-center justify-center h-full",children:[o&&u.jsx("div",{className:"mb-6",children:o}),u.jsx("h3",{className:"text-lg font-semibold text-center mb-2",children:"How can I help you?"}),Ye.length>0&&u.jsx("div",{className:"mt-4 px-4 max-w-md mx-auto",children:u.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[(Ut?Ye:Ye.slice(0,10)).map(j=>u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx(Ps,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Ve(j.sampleUsage),Pt.current?.focus()},children:j.friendlyName})}),u.jsx(bt,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium",children:j.description}),u.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[u.jsx("span",{className:"font-medium",children:"Example:"}),' "',j.sampleUsage,'"']}),j.paramCount>0&&u.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[u.jsx("span",{className:"font-medium",children:"Parameters:"})," ",j.params.join(", ")]})]})})]},j.name)),Ye.length>10&&!Ut&&u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsxs(Ps,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>ue(!0),children:["+",Ye.length-10," more"]})}),u.jsx(bt,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium mb-2",children:"Additional tools:"}),u.jsx("div",{className:"space-y-1 max-h-64 overflow-y-auto pr-2",children:Ye.slice(10).map(j=>u.jsxs("div",{children:[u.jsxs("span",{className:"font-medium text-xs",children:[j.friendlyName,":"]}),u.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:j.description})]},j.name))}),u.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Ut&&Ye.length>10&&u.jsx(Ps,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>ue(!1),children:"Show less"})]})})]}):u.jsxs(u.Fragment,{children:[ke.map(j=>{const X=j.parts.filter(W=>W.type==="text").map(W=>W.text).join("");let J=j.parts;j.role==="assistant"&&j.parts.some(te=>te.timestamp)&&(J=[...j.parts].sort((te,ie)=>{const Ae=te.timestamp||0,ge=ie.timestamp||0;return Ae-ge}));let Y=[],ee=new Map,Ne=[],re,Se=!0;if(j.role==="assistant"){const W=J.filter(ge=>ge.type==="text"&&ge.text),te=[],ie=[];W.forEach(ge=>{const{citations:We,citationMap:be,groupedCitations:Re,referencesText:Ze}=jo(ge.text);Y.push(...We),te.push(be),Re&&ie.push(...Re),Ze&&(re=Ze)}),te.forEach(ge=>{ge.forEach((We,be)=>{ee.has(be)||ee.set(be,We)})}),Ne=Array.from(new Map(ie.map(ge=>[ge.url,ge])).values()).sort((ge,We)=>(ge.numbers[0]||0)-(We.numbers[0]||0)),Se=!(we==="streaming"&&j.id===ke.at(-1)?.id)}return u.jsx("div",{className:`${j.role==="user"?"flex justify-end":"w-full"}`,children:u.jsx("div",{className:`${j.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:j.role==="user"?u.jsx(Bh,{initial:{opacity:0,filter:"blur(4px)"},animate:{opacity:1,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},className:"text-sm whitespace-pre-wrap inline-block bg-stone-100 dark:bg-stone-800 px-3 py-2 rounded-xl",children:X}):u.jsx("div",{className:"space-y-2",children:J.map((W,te)=>{if(W.type?.startsWith("tool-")){const ie=W.type?.replace("tool-","")||"",Ae=_e.find(be=>be.name===ie),ge=W.state==="input-available",We=W.state==="output-available";if(ge&&ht.has(ie),ge){if(ht.has(ie))return null;const be=_s(W.input);return u.jsx(ns,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:u.jsx(Uh,{toolName:ie,description:Ae?.description||"",args:be,onApprove:async()=>{if(dt.has(W.toolCallId))return;Ie(Ze=>new Set(Ze).add(W.toolCallId));const Re=bn.get(ie);if(Re)try{const Ze=await Re(...Object.values(be));st({toolCallId:W.toolCallId,tool:ie,output:Ze})}catch(Ze){st({toolCallId:W.toolCallId,tool:ie,output:`Error: ${Ze}`})}},onDeny:async()=>{dt.has(W.toolCallId)||(Ie(Re=>new Set(Re).add(W.toolCallId)),st({toolCallId:W.toolCallId,tool:ie,output:"User denied tool execution"}))}})},`${W.toolCallId}-${te}`)}else if(We){const be=W.output==="User denied tool execution",Re=_s(W.input);return u.jsx(zh,{toolName:ie,args:Re,isDenied:be,isSafe:ht.has(ie)},`${W.toolCallId}-${te}`)}return null}if(W.type==="text"&&W.text&&yn){const{processedText:ie}=jo(W.text),be=!J.slice(te+1).some(Re=>Re.type==="text"&&Re.text)&&Se&&ee.size>0;return u.jsx(tm,{text:ie,citations:Y,citationMap:ee,groupedCitations:be?Ne:void 0,referencesText:be?re:void 0,ResponseComponent:yn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:V,showReferences:be},`${j.id}-${te}`)}return W.type==="reasoning"&&W.text?u.jsxs(hl,{className:"w-full",isStreaming:we==="streaming"&&te===j.parts.length-1&&j.id===ke.at(-1)?.id,children:[u.jsx(ml,{}),u.jsx(pl,{children:W.text})]},`${j.id}-${te}`):null})})})},j.id)}),u.jsx("div",{ref:ze})]})}),nt&&u.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",nt.message]}),u.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[u.jsx(od,{mode:"wait",children:(we==="streaming"||we==="submitted")&&u.jsxs(ns,{initial:{opacity:0,filter:"blur(4px)",y:5},animate:{opacity:1,filter:"blur(0px)",y:0},exit:{opacity:0,filter:"blur(4px)",y:5},transition:{duration:.2,ease:"easeOut"},className:"absolute left-1/2 -translate-x-1/2 -top-6 flex items-center gap-1.5 bg-stone-100 dark:bg-stone-800 px-3 py-1.5 rounded-full shadow-lg border border-border z-50",children:[u.jsx(ns,{className:"w-2 h-2 bg-stone-400 dark:bg-stone-600",animate:{rotate:[0,0,90,90],borderRadius:["50%","30%","30%","50%"],scale:[.75,1,1,.75]},transition:{duration:2,repeat:1/0,ease:"easeInOut",times:[0,.4,.6,1]}}),u.jsx("p",{className:"text-xs text-muted-foreground",children:Lt})]})}),u.jsxs("form",{onSubmit:pt,className:"relative",children:[u.jsx(No,{ref:Pt,value:At,onChange:Gn,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),pt(j))}}),we==="streaming"||we==="submitted"?u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"button",className:oe(Mt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:zt,children:u.jsx(se.Square,{className:"h-4 w-4"})})}),u.jsxs(bt,{children:[u.jsx(oi,{children:"Escape"})," to stop"]})]}):u.jsxs(yt,{children:[u.jsx(xt,{asChild:!0,children:u.jsx("button",{type:"submit",className:oe(Mt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!At.trim(),children:u.jsx(se.ArrowRight,{className:"h-4 w-4"})})}),u.jsxs(bt,{children:[u.jsx(oi,{children:"Enter"})," to send"]})]})]})]})]}),u.jsxs("a",{href:"https://arcten.com",target:"_blank",rel:"noopener noreferrer",className:"group flex items-center justify-center gap-1.5 py-3 text-xs text-muted-foreground/40 hover:text-muted-foreground/60 transition-all",children:[u.jsx("span",{className:"whitespace-nowrap",children:"Powered by"}),u.jsx("div",{className:"w-4 h-2 bg-current rounded-t-full flex-shrink-0"}),u.jsx("span",{className:"whitespace-nowrap",children:"Arcten"})]})]})]})]}):u.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 h-full cursor-pointer",children:[u.jsx(se.BotMessageSquare,{className:"h-5 w-5 text-stone-600 dark:text-stone-400"}),u.jsx("span",{className:"text-xs font-medium text-stone-600 dark:text-stone-400 [writing-mode:vertical-lr]",children:"AI agent"})]})})}):u.jsx("div",{className:"fixed right-0 top-0 h-screen w-96 flex items-center justify-center p-4 bg-stone-50 dark:bg-stone-900 border-l border-border",children:u.jsx("div",{className:"p-4 text-muted-foreground text-sm",children:"Loading..."})}):null}function fm(e){return u.jsx(xl,{children:u.jsx(dm,{...e})})}function hm(e={}){const{apiBaseUrl:t="https://api.arcten.com",tokenEndpoint:n="/token",clientToken:s,skipTokenFetch:r=!1}=e,[o,i]=h.useState(!1),[a,l]=h.useState(null),c=h.useRef(s||null);h.useEffect(()=>{if(s){c.current=s;return}if(r)return;(async()=>{try{const p=await fetch(`${t}${n}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(p.ok){const b=await p.json();c.current=b.token}}catch(p){console.error("[useGenerate] Failed to fetch token:",p)}})()},[t,n,s,r]);const d=h.useCallback(async m=>{i(!0),l(null);try{const p={"Content-Type":"application/json"};c.current&&(p.Authorization=`Bearer ${c.current}`);const b=await fetch(`${t}/generate`,{method:"POST",headers:p,body:JSON.stringify(m)});if(!b.ok){const T=await b.json().catch(()=>({}));throw new Error(T.error||`HTTP ${b.status}`)}return await b.json()}catch(p){const b=p instanceof Error?p.message:String(p);throw l(b),p}finally{i(!1)}},[t]),f=h.useCallback(async(m,p)=>{i(!0),l(null);try{const b={"Content-Type":"application/json"};c.current&&(b.Authorization=`Bearer ${c.current}`);const v=await fetch(`${t}/generate/stream`,{method:"POST",headers:b,body:JSON.stringify(m)});if(!v.ok){const E=await v.json().catch(()=>({}));throw new Error(E.error||`HTTP ${v.status}`)}const T=v.body?.getReader();if(!T)throw new Error("No response body");const w=new TextDecoder;let M=null;for(;;){const{done:E,value:$}=await T.read();if(E)break;const I=w.decode($,{stream:!0}).split(`
|
|
16
|
+
`).filter(k=>k.startsWith("data: "));for(const k of I){const C=k.slice(6).trim();if(C)try{const V=JSON.parse(C);if(V.error)throw new Error(V.error);V.done&&V.object?M={object:V.object,usage:V.usage,finishReason:V.finishReason}:V.partial&&p&&p(V.partial)}catch{}}}if(!M)throw new Error("Stream ended without final result");return M}catch(b){const v=b instanceof Error?b.message:String(b);throw l(v),b}finally{i(!1)}},[t]);return{generate:d,streamGenerate:f,isLoading:o,error:a}}exports.ARCTEN_ORIGINAL_NAME=Le;exports.ArctenAgent=fm;exports.SecureModalProvider=xl;exports.extractToolsMetadata=pr;exports.preserveToolName=Il;exports.useAgent=ko;exports.useGenerate=hm;exports.useSecureModal=yl;
|