@arcteninc/core 0.0.167 → 0.0.169
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 +8 -8
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +2720 -2717
- package/dist/lib/useAgent.d.ts.map +1 -1
- package/dist/utils/extract-tool-metadata.d.ts +2 -2
- package/dist/utils/extract-tool-metadata.d.ts.map +1 -1
- package/package.json +1 -6
- package/dist/server.cjs +0 -1
- package/dist/server.d.ts +0 -9
- package/dist/server.d.ts.map +0 -1
- package/dist/server.mjs +0 -49
- package/dist/verifyToken.d.ts +0 -19
- package/dist/verifyToken.d.ts.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
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 Vl={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 Sn(e){for(const[t,n]of Object.entries(Vl))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function Il(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 Ol(e,t,n){return t.length>0}function $l(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=Ll(s[i]),d={name:i,type:Fl(l||Sn(i)||"text"),label:To(i),placeholder:Bl(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:Ol(e,t),fields:r,title:Ul(e),description:zl(e,r.length)}}function Ll(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function Fl(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 To(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Bl(e,t){return t?Il(t,e).placeholder:`Enter ${To(e).toLowerCase()}...`}function Ul(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function zl(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 jn(e){if(typeof e=="string")try{const t=JSON.parse(e);return jn(t)}catch{return e}if(Array.isArray(e))return e.map(jn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=jn(s);return t}return e}function _l(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 Xl(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return jn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?jn(e):{}}const ns="__secureOutput",ss="[hidden for privacy]";function Wl(e,t){if(!e||e.length===0)return t;const n=new Map;t.forEach(o=>{const i=o[Oe]||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[Oe]||o.name;i&&!s.has(i)&&(console.log(`[useAgent] Allowing client-only tool (forward compatible): ${i}`),r.push(o))}),r}function ql(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 Kl(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function Gl(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 Hl(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 _s(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 jo(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=_s(r),r&&typeof r=="object"&&Object.assign(n,jo(r,o))}):t&&(n[t]=_s(e)),n}function Yl(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:ss,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:ss,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??ss,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function Jl(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=Yl(s);r&&(t[n]=r)}return t}function Co(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=jo(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[ns]=r,l}if(n.fields.includes("*"))return Co(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[ns]:{...r,redactedFields:n.fields}};const o=ql(t),i=[],a={};return n.fields.forEach(l=>{const c=Kl(l);if(c.length===0)return;const d=Gl(o,c),f=_s(d);a[l]=f,Hl(o,c,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[ns]=r,o}function Po({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:x="",agentId:b,agentName:S,projectId:v,enableRemoteConfig:M,remoteConfigUrl:E,initialMessages:L=[],conversationId:D,state:O,onStateChange:k,allowStateEdits:P=!0,onToolCall:V,onFinish:A,sources:N,ragConfig:F,ragFilters:$,secureInputHandler:B}={}){const X=e.replace(/\/+$/,""),[G,K]=h.useState(null),[oe,ye]=h.useState(!1),[We,wt]=h.useState(null),tt=h.useMemo(()=>{const g=N||[],y=G?.config?.sources||[];return[...new Set([...g,...y])]},[N,G]),H=h.useMemo(()=>F!==void 0?F:$?{enabled:!0,filters:$}:tt&&tt.length>0?{enabled:!0,organizationId:tt[0],autoExecute:!0,filters:void 0}:{enabled:!1},[tt,F,$]),It=h.useMemo(()=>M===!1?!1:!!v,[v,M]);h.useEffect(()=>{if(!It||!ae.current)return;(async()=>{ye(!0),wt(null);try{const w=`${E||X.replace("/chat","").replace(/\/$/,"")}/convex/api/query`,j=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ae.current}`},body:JSON.stringify({path:"agents:getConfigForClient",args:{projectId:v,agentName:S,agentId:b},format:"json"})});if(!j.ok){if(j.status===404){console.warn("[useAgent] Remote config endpoint not found (404), using local tools only"),K(null);return}const R=await j.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch remote config: ${j.status} ${R}`)}const C=await j.json();K(C?.value||null),console.log("[useAgent] Remote config loaded successfully:",C?.value)}catch(y){console.error("[useAgent] Failed to fetch remote config:",y);const w=y instanceof Error?y:new Error(String(y));wt(w),K(null)}finally{ye(!1)}})()},[It,v,S,b,X,E]);const Ee=h.useMemo(()=>{const g={};if(c)for(const[y,w]of Object.entries(c))if(g[y]={},Array.isArray(w))for(const j of w){const C=Sn(j);g[y][j]=C||"text"}else for(const[j,C]of Object.entries(w))g[y][j]=C;if(l){for(const[y,w]of Object.entries(l))if(w&&typeof w=="object"&&"sensitiveParams"in w){g[y]||(g[y]={});const j=w.sensitiveParams;if(Array.isArray(j))for(const C of j){const R=Sn(C);g[y][C]=R||"text"}else if(j&&typeof j=="object")for(const[C,R]of Object.entries(j))g[y][C]=R}}return g},[c,l,f]),St=h.useMemo(()=>Jl(d),[d]),Ce=h.useCallback((g,y)=>{const w=St[g];if(!w)return y;try{return Co(g,y,w)}catch(j){return console.error(`[useAgent] Failed to redact output for ${g}:`,j),{value:ss,[ns]:{tool:g,redacted:!0,error:String(j)}}}},[St]),[Fe,Ot]=h.useState(n||null),ae=h.useRef(n||null),[dn,ct]=h.useState(null),[ut,fn]=h.useState(null),Be=h.useRef(null),[Tt,jt]=h.useState([]),[ke,hn]=h.useState(D||(typeof window<"u"?crypto.randomUUID():null)),[bs,$t]=h.useState(!1),mn=h.useRef(new Set),[Lt,nt]=h.useState(new Map),[vs,Bn]=h.useState(new Map),[st,Un]=h.useState(new Map),[zn,Ft]=h.useState(new Map),ce=O!==void 0,[Bt,dt]=h.useState({}),xe=h.useRef({}),pn=ce?O||{}:Bt;ce&&O?xe.current=O:ce||(xe.current=Bt);const[qe,Re]=h.useState(!1),[gn,Ke]=h.useState(null),Ct=h.useRef(!1),_n=h.useCallback(async(g,y=3)=>{if(!ke||!ae.current)return;const w=async()=>{const C=`${X.replace("/chat","").replace(/\/$/,"")}/convex/api/mutation`,R=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ae.current}`},body:JSON.stringify({path:"conversations:mergeStateByChatId",args:{chatId:ke,updates:g},format:"json"})});if(!R.ok){if(R.status===404)return;const I=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${R.status} ${I}`)}};for(let j=0;j<y;j++)try{await w(),Ke(null);return}catch(C){if(j===y-1){const I=C instanceof Error?C:new Error(String(C));throw Ke(I),console.error("Failed to sync state to Convex after retries:",C),I}await new Promise(I=>setTimeout(I,Math.pow(2,j)*100))}},[ke,X,ae]),Pe=h.useMemo(()=>function(){return xe.current},[]),ft=h.useMemo(()=>async function(y){const w={...xe.current,...y};xe.current=w,ce||dt(w),k&&k(w);try{await _n(y)}catch(j){throw j}},[_n,k,ce]);h.useEffect(()=>{ce&&O&&(xe.current=O)},[ce,O]);const Ne=h.useCallback(g=>B?B.showSecureModal(g):new Promise(y=>{nt(w=>new Map(w).set(g.id,g)),Bn(w=>new Map(w).set(g.id,y))}),[B]),Xn=h.useCallback((g,y)=>{if(B)return;const w=vs.get(g);w&&(w(y),nt(j=>{const C=new Map(j);return C.delete(g),C}),Bn(j=>{const C=new Map(j);return C.delete(g),C}))},[vs,B]),Ut=h.useCallback(g=>B?B.showSecureForm(g):new Promise(y=>{Un(w=>new Map(w).set(g.id,g)),Ft(w=>new Map(w).set(g.id,y))}),[B]),rt=h.useCallback((g,y)=>{if(B)return;const w=zn.get(g);w&&(w(y),Un(j=>{const C=new Map(j);return C.delete(g),C}),Ft(j=>{const C=new Map(j);return C.delete(g),C}))},[zn,B]),Wn=h.useCallback((g,y)=>{const w=Ee[g]||{},j=Object.keys(w).length>0;if(f){const C=Object.keys(y).filter(R=>Sn(R)!==null);return j||C.length>0}return j},[Ee,f]),qn=h.useCallback((g,y)=>{const j={...Ee[g]||{}};if(f){for(const R of Object.keys(y))if(!(R in j)){const I=Sn(R);I&&(j[R]=I)}}const C=Object.entries(j).filter(([R])=>Object.prototype.hasOwnProperty.call(y,R));return C.length>0?Object.fromEntries(C):j},[Ee,f]),Ge=h.useMemo(()=>H?.enabled?async function(y,w=20,j){const C={...H.filters,...j};if(N&&N.length>1){const I=N.map(q=>fetch(`${X}/search`,{method:"POST",headers:{"Content-Type":"application/json",...ae.current?{Authorization:`Bearer ${ae.current}`}:{}},body:JSON.stringify({q:y,k:Math.min(w,100),organizationId:q,...Object.keys(C).length>0?{filters:C}:{}})}).then(ie=>ie.ok?ie.json():null)),ee=await Promise.all(I),Q=[];for(const q of ee)q?.candidates&&Q.push(...q.candidates);Q.sort((q,ie)=>{const Qe=q.scores?.rerank||q.scores?.dense||0;return(ie.scores?.rerank||ie.scores?.dense||0)-Qe});const be=Q.slice(0,w).map((q,ie)=>{const Qe=q.citation||q.url;return{rank:ie+1,doc_id:q.doc_id,block_id:q.block_id,url:q.url,citation:Qe,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:be,summary:`Found ${Q.length} relevant results across ${N.length} source(s) for "${y}". Top result: ${be[0]?.title||"N/A"}`}}const R=H.organizationId&&H.organizationId!=="default"?H.organizationId:N&&N.length>0?N[0]:void 0;try{const I={q:y,k:Math.min(w,100)};R&&(I.organizationId=R),Object.keys(C).length>0&&(I.filters=C);const ee={"Content-Type":"application/json"};ae.current&&(ee.Authorization=`Bearer ${ae.current}`);const Q=await fetch(`${X}/search`,{method:"POST",headers:ee,body:JSON.stringify(I)});if(!Q.ok){const ie=await Q.text();return{success:!1,error:`Search failed: ${Q.status} ${ie}`}}const be=await Q.json(),q=be.candidates.map((ie,Qe)=>{const vn=ie.citation||ie.url;return{rank:Qe+1,doc_id:ie.doc_id,block_id:ie.block_id,url:ie.url,citation:vn,title:ie.title||"Untitled",snippet:ie.snippet,score:ie.scores?.rerank||ie.scores?.dense||0,metadata:{site:ie.metadata?.site,lang:ie.metadata?.lang,contentType:ie.metadata?.content_type}}});return{success:!0,query:be.query,total:be.total,results:q,summary:`Found ${be.total} relevant results for "${y}". Top result: ${q[0]?.title||"N/A"}`}}catch(I){return{success:!1,error:I instanceof Error?I.message:"Unknown error occurred"}}}:null,[H,X,ae]),He=h.useMemo(()=>H?.enabled?async function(y,w){const j=H.organizationId&&H.organizationId!=="default"?H.organizationId:N&&N.length>0?N[0]:void 0;try{const C={"Content-Type":"application/json"};ae.current&&(C.Authorization=`Bearer ${ae.current}`);const R=await fetch(`${X}/fetch`,{method:"POST",headers:C,body:JSON.stringify({doc_id:y,block_ids:w,...j?{organizationId:j}:{}})});if(!R.ok){const ee=await R.text();return{success:!1,error:`Fetch failed: ${R.status} ${ee}`}}const I=await R.json();return{success:!0,blocks:I.blocks||[],fullContent:I.fullContent||"",pageUrl:I.pageUrl||"",pageTitle:I.pageTitle||"",summary:`Fetched ${I.blocks?.length||0} blocks from ${I.pageTitle||y}`}}catch(C){return{success:!1,error:C instanceof Error?C.message:"Unknown error occurred"}}}:null,[H,X,ae]),yn=h.useMemo(()=>{if(G&&G.config?.tools){const g=Wl(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]),Ue=G?.enableStateTools??!0,Ye=G?.enableRagTools??H?.enabled??!1,Kn=h.useMemo(()=>{const g=[...yn,...i];return Ue&&(g.push(Pe),(!ce||P)&&g.push(ft)),Ye&&(Ge&&g.push(Ge),He&&g.push(He)),g},[yn,i,Pe,ft,Ge,He,Ue,Ye,ce,P]),Gn=h.useMemo(()=>[...yn,...i],[yn,i]),it=h.useMemo(()=>mr(Gn,l),[Gn,l]),Pt=h.useMemo(()=>{const g=new Map,y=new Map(it.map(w=>[w.name,w]));return g.set("getState",Pe),(!ce||P)&&g.set("setState",ft),H?.enabled&&(Ge&&g.set("searchDocs",Ge),He&&g.set("fetchDocContent",He)),Kn.forEach(w=>{if(w===Pe||w===ft||w===Ge||w===He)return;const j=w[Oe];if(j){const R=y.get(j);if(R){g.set(R.name,w);return}}const C=it.find(R=>R.name===w.name);C&&g.set(C.name,w)}),g},[Kn,it,Pe,ft,Ge,He,H,ce,P]),Hn=h.useMemo(()=>new Set(it.map(g=>g.name)),[it]),xn=h.useMemo(()=>{const g=[];Ue&&(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||P)&&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=[];Ye&&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 w=[];return G?.config?.workflows&&G.config.workflows.forEach(j=>{const C={},R=[];j.parameters&&j.parameters.forEach(I=>{C[I.name]={type:I.type||"string",description:I.description},I.required&&R.push(I.name)}),w.push({name:`workflow_${j.name.replace(/\s+/g,"_").toLowerCase()}`,description:j.description||`Execute the "${j.name}" workflow. ${j.contentPlaintext?.slice(0,200)||""}`,jsonSchema:{type:"object",properties:C,required:R},_workflow:j})}),[...it,...g,...y,...w]},[it,Ue,Ye,ce,P,G]),ht=h.useMemo(()=>xn.filter(g=>g.name==="getState"?Ue:g.name==="setState"?Ue&&(!ce||P):g.name==="searchDocs"||g.name==="fetchDocContent"?Ye:g.name.startsWith("workflow_")?!0:Hn.has(g.name)),[xn,Hn,Ue,Ye,ce,P]),zt=h.useMemo(()=>{const g=new Set;return Ue&&(g.add("getState"),g.add("setState")),Ye&&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[w,j]of Pt.entries())if(j===y){g.add(w);break}}),a&&Array.isArray(a)&&a.forEach(y=>{typeof y=="string"&&g.add(y)})),G?.config?.workflows&&G.config.workflows.forEach(y=>{const w=`workflow_${y.name.replace(/\s+/g,"_").toLowerCase()}`;y.requiresApproval||g.add(w)}),g},[G,i,a,Pt,Ue,Ye,H]);h.useEffect(()=>{if(s||n)return;let g=!1,y=null;const w=async(j=1,C=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 I=await R.json();g||(Ot(I.clientToken),ae.current=I.clientToken,fn(I.expiresAt),ct(null))}catch(R){if(console.error(`[useAgent] Token fetch failed (attempt ${j}/${C}):`,R),j<C&&!g){const I=Math.pow(2,j-1)*1e3;y=setTimeout(()=>w(j+1,C),I)}else g||ct(R instanceof Error?R.message:"Failed to fetch token")}};return w(),()=>{g=!0,y&&clearTimeout(y),Be.current&&clearTimeout(Be.current)}},[t,JSON.stringify(r),s,n]),h.useEffect(()=>{if(!ut||s||n)return;Be.current&&clearTimeout(Be.current);const g=async(R=1,I=3)=>{try{const ee=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!ee.ok)throw new Error("Failed to refresh token");const Q=await ee.json();Ot(Q.clientToken),ae.current=Q.clientToken,fn(Q.expiresAt),ct(null)}catch(ee){if(console.error(`[useAgent] Token refresh failed (attempt ${R}/${I}):`,ee),R<I){const Q=Math.pow(2,R-1)*1e3;setTimeout(()=>g(R+1,I),Q)}else ct(ee instanceof Error?ee.message:"Failed to refresh token")}},y=Math.floor(Date.now()/1e3),w=ut-y,C=Math.max(0,w-5);return Be.current=setTimeout(()=>g(),C*1e3),()=>{Be.current&&clearTimeout(Be.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 j=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(j.ok){const C=await j.json();Ot(C.clientToken),ae.current=C.clientToken,fn(C.expiresAt),ct(null)}}catch(j){console.error("[useAgent] Token refresh on visibility change failed:",j)}}};return document.addEventListener("visibilitychange",g),()=>document.removeEventListener("visibilitychange",g)},[t,JSON.stringify(r),ut,s,n]);const ws=async(g,y={})=>{const w=y.headers?new Headers(y.headers):new Headers;return w.delete("user-agent"),w.delete("User-Agent"),fetch(g,{...y,headers:w})},bn=h.useRef(null),Yn=`${X}/chat`,{messages:Je,sendMessage:T,status:_,error:z,stop:Z,addToolResult:Y,setMessages:J}=jl.useChat({id:ke||void 0,messages:L,transport:new ei.DefaultChatTransport({api:Yn,fetch:ws,headers:()=>{const g={};return ae.current&&(g.Authorization=`Bearer ${ae.current}`),g},body:()=>({tools:ht.map(y=>({name:y.name,description:y.description,inputSchema:y.jsonSchema})),...b&&{agentId:b},...S&&{agentName:S},state:xe.current,...$&&{ragFilters:$}})}),sendAutomaticallyWhen:g=>{const y=g.messages;if(y[y.length-1]?.role!=="assistant")return!1;const C=[...y].reverse().find(I=>I.role==="user")?.id;if(C&&bn.current===C)return!1;const R=ei.lastAssistantMessageIsCompleteWithToolCalls(g);return R&&C&&(bn.current=C),R}}),De=T,re=h.useCallback(g=>(bn.current=null,De(g)),[De]),ue=h.useCallback((g,y,w)=>{const j=Ce(g,w);Y({toolCallId:y,tool:g,output:j})},[Y,Ce]);h.useEffect(()=>{Je.forEach(g=>{g.role==="assistant"&&g.parts.forEach(y=>{if(!y.type?.startsWith("tool-")||y.state!=="input-available")return;const w=y.type.replace("tool-",""),j=y.toolCallId;if(mn.current.has(j))return;mn.current.add(j);const C=Xl(y.input);if(Wn(w,C)){const R=qn(w,C),I=Object.entries(R).filter(([q])=>C[q]!==void 0),ee=I.length>0?Object.fromEntries(I):R,Q=Object.keys(C),be=_l(C,ee);(async()=>{try{const q=$l(w,Q,ee,C),ie={id:`${j}-form`,toolName:w,toolCallId:j,title:q.title,description:q.description,fields:q.fields},Qe=await Ut(ie);if(Qe===null){ue(w,j,"User cancelled secure input");return}const vn={...be,...Qe},Ss=Pt.get(w);if(!Ss)throw new Error(`Tool ${w} not found`);let Ts;const js=ht.find(Zr=>Zr.name===w);if(js&&js.jsonSchema?.properties){const pl=Object.keys(js.jsonSchema.properties).map(gl=>vn[gl]);Ts=await Ss(...pl)}else Ts=await Ss(...Object.values(vn));ue(w,j,Ts)}catch(q){console.error(`[useAgent] Error executing tool with secure input ${w}:`,q),ue(w,j,`Error: ${q}`)}})();return}if(w.startsWith("workflow_")&&zt.has(w)){(async()=>{try{const I=ht.find(Q=>Q.name===w)?._workflow;if(!I)throw new Error(`Workflow metadata not found for ${w}`);let ee;if(I.webhook?.url){let Q=C;if(I.webhook.bodyTemplate){let q=I.webhook.bodyTemplate;Object.entries(C).forEach(([ie,Qe])=>{q=q.replace(new RegExp(`\\{\\{${ie}\\}\\}`,"g"),String(Qe))}),Q=JSON.parse(q)}const be=await fetch(I.webhook.url,{method:I.webhook.method||"POST",headers:{"Content-Type":"application/json",...I.webhook.headers||{}},body:JSON.stringify(Q)});if(be.ok)ee={success:!0,data:await be.json().catch(()=>({success:!0}))};else{const q=await be.text();ee={success:!1,error:`Webhook failed: ${be.status} ${q}`}}}else ee={success:!0,message:`Workflow "${I.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:I.contentPlaintext};ue(w,j,ee)}catch(R){console.error(`[useAgent] Error executing workflow ${w}:`,R),ue(w,j,`Error: ${R}`)}})();return}if(zt.has(w)&&!Wn(w,C)){const R=Pt.get(w);R?(async()=>{try{const I=ht.find(Q=>Q.name===w);let ee;if(I&&I.jsonSchema?.properties){const be=Object.keys(I.jsonSchema.properties).map(q=>C[q]);ee=await R(...be)}else if(w==="getState")ee=R();else if(w==="setState"){const Q=C.updates||C;ee=await R(Q)}else ee=await R(...Object.values(C));ue(w,j,ee)}catch(I){console.error(`[useAgent] Error executing tool ${w}:`,I),ue(w,j,`Error: ${I}`)}})():console.warn(`[useAgent] Tool ${w} not found in toolsMap`)}else w.startsWith("workflow_")&&V?V({toolCall:{toolCallId:j,toolName:w,args:C}}):V&&V({toolCall:{toolCallId:j,toolName:w,args:C}})})})},[Je,zt,Pt,V,ue,ft,ht,Wn,qn,Ne]),h.useEffect(()=>{if(_==="ready"&&Je.length>0&&A){const g=Je[Je.length-1];g&&g.role==="assistant"&&A({message:g,messages:Je,isAbort:!1,isDisconnect:!1,isError:!!z})}},[_,Je,z,A]);async function W(){if(!(!r?.id||!Fe)){$t(!0);try{const y=await(await fetch(`${X}/conversations`,{headers:{Authorization:`Bearer ${Fe}`}})).json();jt(y.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{$t(!1)}}}h.useEffect(()=>{r?.id&&Fe&&W()},[JSON.stringify(r),Fe,X]),h.useEffect(()=>{if(!ke||!ae.current)return;(async()=>{Re(!0),Ke(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:ke},format:"json"})});if(!y.ok){const C=await y.text().catch(()=>"Unknown error");throw new Error(`Failed to fetch conversation state: ${y.status} ${C}`)}const j=(await y.json())?.value||{};xe.current=j,ce||dt(j),k&&k(j),Ct.current=!0}catch(y){console.error("Failed to fetch state:",y);const w=y instanceof Error?y:new Error(String(y));Ke(w),Ct.current||(xe.current={},ce?k&&k({}):(dt({}),k&&k({})),Ct.current=!0)}finally{Re(!1)}})()},[ke,X,ce,k]);async function me(g){hn(g),$t(!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 j=(await y.json()).messages||[];J(j)}catch(y){console.error("Failed to load conversation messages:",y)}finally{$t(!1)}}async function ne(g){if(Fe)try{await fetch(`${X}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${Fe}`}}),jt(Tt.filter(y=>y._id!==g)),g===ke&&Se()}catch(y){console.error("Failed to delete conversation:",y)}}function Se(){const g=crypto.randomUUID();hn(g),J([]),mn.current=new Set,xe.current={},ce?k&&k({}):(dt({}),k&&k({})),Ct.current=!1}function de(g){const y=g.tool||"unknown-tool",w=Ce(y,g.output);Y({toolCallId:g.toolCallId,tool:y,output:w})}async function Ze(g,y,w){if(!y.startsWith("workflow_"))throw new Error(`${y} is not a workflow tool`);try{const C=ht.find(I=>I.name===y)?._workflow;if(!C)throw new Error(`Workflow metadata not found for ${y}`);let R;if(C.webhook?.url){let I=w;if(C.webhook.bodyTemplate){let Q=C.webhook.bodyTemplate;Object.entries(w).forEach(([be,q])=>{Q=Q.replace(new RegExp(`\\{\\{${be}\\}\\}`,"g"),String(q))}),I=JSON.parse(Q)}const ee=await fetch(C.webhook.url,{method:C.webhook.method||"POST",headers:{"Content-Type":"application/json",...C.webhook.headers||{}},body:JSON.stringify(I)});if(ee.ok)R={success:!0,data:await ee.json().catch(()=>({success:!0}))};else{const Q=await ee.text();R={success:!1,error:`Webhook failed: ${ee.status} ${Q}`}}}else R={success:!0,message:`Workflow "${C.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:C.contentPlaintext};return de({toolCallId:g,tool:y,output:R}),R}catch(j){const C={success:!1,error:String(j)};throw de({toolCallId:g,tool:y,output:C}),j}}async function ve(g){const y={...xe.current,...g};xe.current=y,ce||dt(y),k&&k(y);try{await _n(g)}catch(w){throw w}}return{id:ke,messages:Je,status:_,error:z,sendMessage:re,stop:Z,addToolOutput:de,executeWorkflowTool:Ze,setMessages:J,conversations:Tt,loadConversation:me,deleteConversation:ne,startNewConversation:Se,isLoadingConversations:bs,clientToken:Fe,tokenError:dn,state:pn,setState:ve,isStateLoading:qe,stateError:gn,pendingSecureInputs:Array.from(Lt.values()),completeSecureInput:Xn,pendingSecureForms:Array.from(st.values()),completeSecureForm:rt,safeToolNames:zt}}function se(...e){return Pl.twMerge(Cl.clsx(e))}const Et=So.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"}}),je=_e.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?wo.Slot:"button";return u.jsx(i,{ref:o,"data-slot":"button",className:se(Et({variant:t,size:n,className:e})),...r})});je.displayName="Button";const Zl=So.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 Cs({className:e,variant:t,asChild:n=!1,...s}){const r=n?wo.Slot:"span";return u.jsx(r,{"data-slot":"badge",className:se(Zl({variant:t}),e),...s})}const Ql=({textAreaRef:e,triggerAutoSize:t,maxHeight:n=Number.MAX_SAFE_INTEGER,minHeight:s=0})=>{const[r,o]=_e.useState(!0);_e.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])},Ao=_e.forwardRef(({maxHeight:e=Number.MAX_SAFE_INTEGER,minHeight:t=52,className:n,onChange:s,value:r,...o},i)=>{const a=_e.useRef(null),[l,c]=_e.useState("");return Ql({textAreaRef:a,triggerAutoSize:l,maxHeight:e,minHeight:t}),h.useImperativeHandle(i,()=>({textArea:a.current,focus:()=>a?.current?.focus(),maxHeight:e,minHeight:t})),_e.useEffect(()=>{c(r)},[o?.defaultValue,r]),u.jsx("textarea",{...o,value:r,ref:a,className:se("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)}})});Ao.displayName="AutosizeTextarea";function ec({delayDuration:e=0,...t}){return u.jsx(Ht.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function mt({...e}){return u.jsx(ec,{children:u.jsx(Ht.Root,{"data-slot":"tooltip",...e})})}function pt({...e}){return u.jsx(Ht.Trigger,{"data-slot":"tooltip-trigger",...e})}function gt({className:e,sideOffset:t=0,children:n,...s}){return u.jsx(Ht.Portal,{children:u.jsxs(Ht.Content,{"data-slot":"tooltip-content",sideOffset:t,className:se("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(Ht.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function ni({className:e,...t}){return u.jsx("kbd",{"data-slot":"kbd",className:se("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 pr=h.createContext({});function gr(e){const t=h.useRef(null);return t.current===null&&(t.current=e()),t.current}const yr=typeof window<"u",Eo=yr?h.useLayoutEffect:h.useEffect,ps=h.createContext(null);function xr(e,t){e.indexOf(t)===-1&&e.push(t)}function br(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 Xs(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let Qt=()=>{},at=()=>{};process.env.NODE_ENV!=="production"&&(Qt=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Xs(t,n))},at=(e,t,n)=>{if(!e)throw new Error(Xs(t,n))});const lt={},Mo=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function ko(e){return typeof e=="object"&&e!==null}const No=e=>/^0[^.\s]+$/u.test(e);function vr(e){let t;return()=>(t===void 0&&(t=e()),t)}const Le=e=>e,tc=(e,t)=>n=>t(e(n)),On=(...e)=>e.reduce(tc),kn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class wr{constructor(){this.subscriptions=[]}add(t){return xr(this.subscriptions,t),()=>br(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 Xe=e=>e*1e3,$e=e=>e/1e3;function Do(e,t){return t?e*(1e3/t):0}const si=new Set;function Sr(e,t,n){e||si.has(t)||(console.warn(Xs(t,n)),si.add(t))}const Ro=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,nc=1e-7,sc=12;function rc(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Ro(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>nc&&++a<sc);return i}function $n(e,t,n,s){if(e===t&&n===s)return Le;const r=o=>rc(o,0,1,e,n);return o=>o===0||o===1?o:Ro(r(o),t,s)}const Vo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Io=e=>t=>1-e(1-t),Oo=$n(.33,1.53,.69,.99),Tr=Io(Oo),$o=Vo(Tr),Lo=e=>(e*=2)<1?.5*Tr(e):.5*(2-Math.pow(2,-10*(e-1))),jr=e=>1-Math.sin(Math.acos(e)),Fo=Io(jr),Bo=Vo(jr),ic=$n(.42,0,1,1),oc=$n(0,0,.58,1),Uo=$n(.42,0,.58,1),ac=e=>Array.isArray(e)&&typeof e[0]!="number",zo=e=>Array.isArray(e)&&typeof e[0]=="number",ri={linear:Le,easeIn:ic,easeInOut:Uo,easeOut:oc,circIn:jr,circInOut:Bo,circOut:Fo,backIn:Tr,backInOut:$o,backOut:Oo,anticipate:Lo},lc=e=>typeof e=="string",ii=e=>{if(zo(e)){at(e.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,s,r]=e;return $n(t,n,s,r)}else if(lc(e))return at(ri[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),ri[e];return e},Jn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function cc(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 x=m&&r?n:s;return f&&i.add(d),x.has(d)||x.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 uc=40;function _o(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Jn.reduce((E,L)=>(E[L]=cc(o),E),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:f,preRender:m,render:p,postRender:x}=i,b=()=>{const E=lt.useManualTiming?r.timestamp:performance.now();n=!1,lt.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(E-r.timestamp,uc),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),x.process(r),r.isProcessing=!1,n&&t&&(s=!1,e(b))},S=()=>{n=!0,s=!0,r.isProcessing||e(b)};return{schedule:Jn.reduce((E,L)=>{const D=i[L];return E[L]=(O,k=!1,P=!1)=>(n||S(),D.schedule(O,k,P)),E},{}),cancel:E=>{for(let L=0;L<Jn.length;L++)i[Jn[L]].cancel(E)},state:r,steps:i}}const{schedule:le,cancel:xt,state:we,steps:Ps}=_o(typeof requestAnimationFrame<"u"?requestAnimationFrame:Le,!0);let rs;function dc(){rs=void 0}const Me={now:()=>(rs===void 0&&Me.set(we.isProcessing||lt.useManualTiming?we.timestamp:performance.now()),rs),set:e=>{rs=e,queueMicrotask(dc)}},Xo=e=>t=>typeof t=="string"&&t.startsWith(e),Cr=Xo("--"),fc=Xo("var(--"),Pr=e=>fc(e)?hc.test(e.split("/*")[0].trim()):!1,hc=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,en={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Nn={...en,transform:e=>ot(0,1,e)},Zn={...en,default:1},Cn=e=>Math.round(e*1e5)/1e5,Ar=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function mc(e){return e==null}const pc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Er=(e,t)=>n=>!!(typeof n=="string"&&pc.test(n)&&n.startsWith(e)||t&&!mc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Wo=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Ar);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},gc=e=>ot(0,255,e),As={...en,transform:e=>Math.round(gc(e))},kt={test:Er("rgb","red"),parse:Wo("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+As.transform(e)+", "+As.transform(t)+", "+As.transform(n)+", "+Cn(Nn.transform(s))+")"};function yc(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 Ws={test:Er("#"),parse:yc,transform:kt.transform},Ln=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),yt=Ln("deg"),et=Ln("%"),U=Ln("px"),xc=Ln("vh"),bc=Ln("vw"),oi={...et,parse:e=>et.parse(e)/100,transform:e=>et.transform(e*100)},_t={test:Er("hsl","hue"),parse:Wo("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+et.transform(Cn(t))+", "+et.transform(Cn(n))+", "+Cn(Nn.transform(s))+")"},ge={test:e=>kt.test(e)||Ws.test(e)||_t.test(e),parse:e=>kt.test(e)?kt.parse(e):_t.test(e)?_t.parse(e):Ws.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?kt.transform(e):_t.transform(e),getAnimatableNone:e=>{const t=ge.parse(e);return t.alpha=0,ge.transform(t)}},vc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function wc(e){return isNaN(e)&&typeof e=="string"&&(e.match(Ar)?.length||0)+(e.match(vc)?.length||0)>0}const qo="number",Ko="color",Sc="var",Tc="var(",ai="${}",jc=/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 Dn(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},r=[];let o=0;const a=t.replace(jc,l=>(ge.test(l)?(s.color.push(o),r.push(Ko),n.push(ge.parse(l))):l.startsWith(Tc)?(s.var.push(o),r.push(Sc),n.push(l)):(s.number.push(o),r.push(qo),n.push(parseFloat(l))),++o,ai)).split(ai);return{values:n,split:a,indexes:s,types:r}}function Go(e){return Dn(e).values}function Ho(e){const{split:t,types:n}=Dn(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===qo?o+=Cn(r[i]):a===Ko?o+=ge.transform(r[i]):o+=r[i]}return o}}const Cc=e=>typeof e=="number"?0:ge.test(e)?ge.getAnimatableNone(e):e;function Pc(e){const t=Go(e);return Ho(e)(t.map(Cc))}const bt={test:wc,parse:Go,createTransformer:Ho,getAnimatableNone:Pc};function Es(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 Ac({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=Es(l,a,e+1/3),o=Es(l,a,e),i=Es(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function cs(e,t){return n=>n>0?t:e}const he=(e,t,n)=>e+(t-e)*n,Ms=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},Ec=[Ws,kt,_t],Mc=e=>Ec.find(t=>t.test(e));function li(e){const t=Mc(e);if(Qt(!!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===_t&&(n=Ac(n)),n}const ci=(e,t)=>{const n=li(e),s=li(t);if(!n||!s)return cs(e,t);const r={...n};return o=>(r.red=Ms(n.red,s.red,o),r.green=Ms(n.green,s.green,o),r.blue=Ms(n.blue,s.blue,o),r.alpha=he(n.alpha,s.alpha,o),kt.transform(r))},qs=new Set(["none","hidden"]);function kc(e,t){return qs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Nc(e,t){return n=>he(e,t,n)}function Mr(e){return typeof e=="number"?Nc:typeof e=="string"?Pr(e)?cs:ge.test(e)?ci:Vc:Array.isArray(e)?Yo:typeof e=="object"?ge.test(e)?ci:Dc:cs}function Yo(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>Mr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Dc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=Mr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Rc(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 Vc=(e,t)=>{const n=bt.createTransformer(t),s=Dn(e),r=Dn(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?qs.has(e)&&!r.values.length||qs.has(t)&&!s.values.length?kc(e,t):On(Yo(Rc(s,r),r.values),n):(Qt(!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"),cs(e,t))};function Jo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?he(e,t,n):Mr(e)(e,t)}const Ic=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>le.update(t,n),stop:()=>xt(t),now:()=>we.isProcessing?we.timestamp:Me.now()}},Zo=(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)})`},us=2e4;function kr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<us;)t+=n,s=e.next(t);return t>=us?1/0:t}function Oc(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(kr(s),us);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:$e(r)}}const $c=5;function Qo(e,t,n){const s=Math.max(t-$c,0);return Do(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},ks=.001;function Lc({duration:e=fe.duration,bounce:t=fe.bounce,velocity:n=fe.velocity,mass:s=fe.mass}){let r,o;Qt(e<=Xe(fe.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=ot(fe.minDamping,fe.maxDamping,i),e=ot(fe.minDuration,fe.maxDuration,$e(e)),i<1?(r=c=>{const d=c*i,f=d*e,m=d-n,p=Ks(c,i),x=Math.exp(-f);return ks-m/p*x},o=c=>{const f=c*i*e,m=f*n+n,p=Math.pow(i,2)*Math.pow(c,2)*e,x=Math.exp(-f),b=Ks(Math.pow(c,2),i);return(-r(c)+ks>0?-1:1)*((m-p)*x)/b}):(r=c=>{const d=Math.exp(-c*e),f=(c-n)*e+1;return-ks+d*f},o=c=>{const d=Math.exp(-c*e),f=(n-c)*(e*e);return d*f});const a=5/e,l=Bc(r,o,a);if(e=Xe(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 Fc=12;function Bc(e,t,n){let s=n;for(let r=1;r<Fc;r++)s=s-e(s)/t(s);return s}function Ks(e,t){return e*Math.sqrt(1-t*t)}const Uc=["duration","bounce"],zc=["stiffness","damping","mass"];function ui(e,t){return t.some(n=>e[n]!==void 0)}function _c(e){let t={velocity:fe.velocity,stiffness:fe.stiffness,damping:fe.damping,mass:fe.mass,isResolvedFromDuration:!1,...e};if(!ui(e,zc)&&ui(e,Uc))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:fe.mass,stiffness:r,damping:o}}else{const n=Lc(e);t={...t,...n,mass:fe.mass},t.isResolvedFromDuration=!0}return t}function ds(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}=_c({...n,velocity:-$e(n.velocity||0)}),x=m||0,b=c/(2*Math.sqrt(l*d)),S=i-o,v=$e(Math.sqrt(l/d)),M=Math.abs(S)<5;s||(s=M?fe.restSpeed.granular:fe.restSpeed.default),r||(r=M?fe.restDelta.granular:fe.restDelta.default);let E;if(b<1){const D=Ks(v,b);E=O=>{const k=Math.exp(-b*v*O);return i-k*((x+b*v*S)/D*Math.sin(D*O)+S*Math.cos(D*O))}}else if(b===1)E=D=>i-Math.exp(-v*D)*(S+(x+v*S)*D);else{const D=v*Math.sqrt(b*b-1);E=O=>{const k=Math.exp(-b*v*O),P=Math.min(D*O,300);return i-k*((x+b*v*S)*Math.sinh(P)+D*S*Math.cosh(P))/D}}const L={calculatedDuration:p&&f||null,next:D=>{const O=E(D);if(p)a.done=D>=f;else{let k=D===0?x:0;b<1&&(k=D===0?Xe(x):Qo(E,D,O));const P=Math.abs(k)<=s,V=Math.abs(i-O)<=r;a.done=P&&V}return a.value=a.done?i:O,a},toString:()=>{const D=Math.min(kr(L),us),O=Zo(k=>L.next(D*k).value,D,30);return D+"ms "+O},toTransition:()=>{}};return L}ds.applyToOptions=e=>{const t=Oc(e,100,ds);return e.ease=t.ease,e.duration=Xe(t.duration),e.type="keyframes",e};function Gs({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=P=>a!==void 0&&P<a||l!==void 0&&P>l,x=P=>a===void 0?l:l===void 0||Math.abs(a-P)<Math.abs(l-P)?a:l;let b=n*t;const S=f+b,v=i===void 0?S:i(S);v!==S&&(b=v-f);const M=P=>-b*Math.exp(-P/s),E=P=>v+M(P),L=P=>{const V=M(P),A=E(P);m.done=Math.abs(V)<=c,m.value=m.done?v:A};let D,O;const k=P=>{p(m.value)&&(D=P,O=ds({keyframes:[m.value,x(m.value)],velocity:Qo(E,P,m.value),damping:r,stiffness:o,restDelta:c,restSpeed:d}))};return k(0),{calculatedDuration:null,next:P=>{let V=!1;return!O&&D===void 0&&(V=!0,L(P),k(P)),D!==void 0&&P>=D?O.next(P-D):(!V&&L(P),m)}}}function Xc(e,t,n){const s=[],r=n||lt.mix||Jo,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]||Le:t;a=On(l,a)}s.push(a)}return s}function Wc(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=Xc(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=kn(e[f],e[f+1],d);return a[f](m)};return n?d=>c(ot(e[0],e[o-1],d)):c}function qc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=kn(0,t,s);e.push(he(n,1,r))}}function Kc(e){const t=[0];return qc(t,e.length-1),t}function Gc(e,t){return e.map(n=>n*t)}function Hc(e,t){return e.map(()=>t||Uo).splice(0,e.length-1)}function Xt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=ac(s)?s.map(ii):ii(s),o={done:!1,value:t[0]},i=Gc(n&&n.length===t.length?n:Kc(t),e),a=Wc(i,t,{ease:Array.isArray(r)?r:Hc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const Yc=e=>e!==null;function Nr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Yc),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const Jc={decay:Gs,inertia:Gs,tween:Xt,keyframes:Xt,spring:ds};function ea(e){typeof e.type=="string"&&(e.type=Jc[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 Zc=e=>e/100;class Rr 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!==Me.now()&&this.tick(Me.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;ea(t);const{type:n=Xt,repeat:s=0,repeatDelay:r=0,repeatType:o,velocity:i=0}=t;let{keyframes:a}=t;const l=n||Xt;process.env.NODE_ENV!=="production"&&l!==Xt&&at(a.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${a}`,"spring-two-frames"),l!==Xt&&typeof a[0]!="number"&&(this.mixKeyframes=On(Zc,Jo(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=kr(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:x,onUpdate:b,finalKeyframe:S}=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 v=this.currentTime-c*(this.playbackSpeed>=0?1:-1),M=this.playbackSpeed>=0?v<0:v>r;this.currentTime=Math.max(v,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=r);let E=this.currentTime,L=s;if(f){const P=Math.min(this.currentTime,r)/a;let V=Math.floor(P),A=P%1;!A&&P>=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"&&(L=i)),E=ot(0,1,A)*a}const D=M?{done:!1,value:d[0]}:L.next(E);o&&(D.value=o(D.value));let{done:O}=D;!M&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return k&&x!==Gs&&(D.value=Nr(d,this.options,S,this.speed)),b&&b(D.value),k&&this.finish(),D}then(t,n){return this.finished.then(t,n)}get duration(){return $e(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+$e(t)}get time(){return $e(this.currentTime)}set time(t){t=Xe(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(Me.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=$e(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Ic,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(Me.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 Qc(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Nt=e=>e*180/Math.PI,Hs=e=>{const t=Nt(Math.atan2(e[1],e[0]));return Ys(t)},eu={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Hs,rotateZ:Hs,skewX:e=>Nt(Math.atan(e[1])),skewY:e=>Nt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ys=e=>(e=e%360,e<0&&(e+=360),e),di=Hs,fi=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),hi=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),tu={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:fi,scaleY:hi,scale:e=>(fi(e)+hi(e))/2,rotateX:e=>Ys(Nt(Math.atan2(e[6],e[5]))),rotateY:e=>Ys(Nt(Math.atan2(-e[2],e[0]))),rotateZ:di,rotate:di,skewX:e=>Nt(Math.atan(e[4])),skewY:e=>Nt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Js(e){return e.includes("scale")?1:0}function Zs(e,t){if(!e||e==="none")return Js(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=tu,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=eu,r=a}if(!r)return Js(t);const o=s[t],i=r[1].split(",").map(su);return typeof o=="function"?o(i):i[o]}const nu=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Zs(n,t)};function su(e){return parseFloat(e.trim())}const tn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],nn=new Set(tn),mi=e=>e===en||e===U,ru=new Set(["x","y","z"]),iu=tn.filter(e=>!ru.has(e));function ou(e){const t=[];return iu.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})=>Zs(t,"x"),y:(e,{transform:t})=>Zs(t,"y")};Dt.translateX=Dt.x;Dt.translateY=Dt.y;const Rt=new Set;let Qs=!1,er=!1,tr=!1;function ta(){if(er){const e=Array.from(Rt).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=ou(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)})}er=!1,Qs=!1,Rt.forEach(e=>e.complete(tr)),Rt.clear()}function na(){Rt.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(er=!0)})}function au(){tr=!0,na(),ta(),tr=!1}class Vr{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?(Rt.add(this),Qs||(Qs=!0,le.read(na),le.resolveKeyframes(ta))):(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])}Qc(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),Rt.delete(this)}cancel(){this.state==="scheduled"&&(Rt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const lu=e=>e.startsWith("--");function cu(e,t,n){lu(t)?e.style.setProperty(t,n):e.style[t]=n}const uu=vr(()=>window.ScrollTimeline!==void 0),du={};function fu(e,t){const n=vr(e);return()=>du[t]??n()}const sa=fu(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Tn=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,pi={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Tn([0,.65,.55,1]),circOut:Tn([.55,0,1,.45]),backIn:Tn([.31,.01,.66,-.59]),backOut:Tn([.33,1.53,.69,.99])};function ra(e,t){if(e)return typeof e=="function"?sa()?Zo(e,t):"ease-out":zo(e)?Tn(e):Array.isArray(e)?e.map(n=>ra(n,t)||pi.easeOut):pi[e]}function hu(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=ra(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 ia(e){return typeof e=="function"&&"applyToOptions"in e}function mu({type:e,...t}){return ia(e)&&sa()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class pu 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=mu(t);this.animation=hu(n,s,r,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Nr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):cu(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 $e(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+$e(t)}get time(){return $e(Number(this.animation.currentTime)||0)}set time(t){this.finishedTime=null,this.animation.currentTime=Xe(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&&uu()?(this.animation.timeline=t,Le):n(this)}}const oa={anticipate:Lo,backInOut:$o,circInOut:Bo};function gu(e){return e in oa}function yu(e){typeof e.ease=="string"&&gu(e.ease)&&(e.ease=oa[e.ease])}const gi=10;class xu extends pu{constructor(t){yu(t),ea(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 Rr({...i,autoplay:!1}),l=Xe(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-gi).value,a.sample(l).value,gi),a.stop()}}const yi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(bt.test(e)||e==="0")&&!e.startsWith("url("));function bu(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 vu(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=yi(r,t),a=yi(o,t);return Qt(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:bu(e)||(n==="spring"||ia(n))&&s}function nr(e){e.duration=0,e.type="keyframes"}const wu=new Set(["opacity","clipPath","filter","transform"]),Su=vr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Tu(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 Su()&&n&&wu.has(n)&&(n!=="transform"||!c)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const ju=40;class Cu 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=Me.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||Vr;this.keyframeResolver=new p(a,(x,b,S)=>this.onKeyframesResolved(x,b,m,!S),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=Me.now(),vu(t,o,i,a)||((lt.instantAnimations||!l)&&d?.(Nr(t,s,n)),t[0]=t[t.length-1],nr(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>ju?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!c&&Tu(m)?new xu({...m,element:m.motionValue.owner.current}):new Rr(m);p.finished.then(()=>this.notifyFinished()).catch(Le),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(),au()),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 Pu=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Au(e){const t=Pu.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const Eu=4;function aa(e,t,n=1){at(n<=Eu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=Au(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return Mo(i)?parseFloat(i):i}return Pr(r)?aa(r,t,n+1):r}function Ir(e,t){return e?.[t]??e?.default??e}const la=new Set(["width","height","top","left","right","bottom",...tn]),Mu={test:e=>e==="auto",parse:e=>e},ca=e=>t=>t.test(e),ua=[en,U,et,yt,bc,xc,Mu],xi=e=>ua.find(ca(e));function ku(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||No(e):!0}const Nu=new Set(["brightness","contrast","saturate","opacity"]);function Du(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Ar)||[];if(!s)return e;const r=n.replace(s,"");let o=Nu.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const Ru=/\b([a-z-]*)\(.*?\)/gu,sr={...bt,getAnimatableNone:e=>{const t=e.match(Ru);return t?t.map(Du).join(" "):e}},bi={...en,transform:Math.round},Vu={rotate:yt,rotateX:yt,rotateY:yt,rotateZ:yt,scale:Zn,scaleX:Zn,scaleY:Zn,scaleZ:Zn,skew:yt,skewX:yt,skewY:yt,distance:U,translateX:U,translateY:U,translateZ:U,x:U,y:U,z:U,perspective:U,transformPerspective:U,opacity:Nn,originX:oi,originY:oi,originZ:U},Or={borderWidth:U,borderTopWidth:U,borderRightWidth:U,borderBottomWidth:U,borderLeftWidth:U,borderRadius:U,radius:U,borderTopLeftRadius:U,borderTopRightRadius:U,borderBottomRightRadius:U,borderBottomLeftRadius:U,width:U,maxWidth:U,height:U,maxHeight:U,top:U,right:U,bottom:U,left:U,padding:U,paddingTop:U,paddingRight:U,paddingBottom:U,paddingLeft:U,margin:U,marginTop:U,marginRight:U,marginBottom:U,marginLeft:U,backgroundPositionX:U,backgroundPositionY:U,...Vu,zIndex:bi,fillOpacity:Nn,strokeOpacity:Nn,numOctaves:bi},Iu={...Or,color:ge,backgroundColor:ge,outlineColor:ge,fill:ge,stroke:ge,borderColor:ge,borderTopColor:ge,borderRightColor:ge,borderBottomColor:ge,borderLeftColor:ge,filter:sr,WebkitFilter:sr},da=e=>Iu[e];function fa(e,t){let n=da(e);return n!==sr&&(n=bt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Ou=new Set(["auto","none","0"]);function $u(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!Ou.has(o)&&Dn(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=fa(n,r)}class Lu extends Vr{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(),Pr(c))){const d=aa(c,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!la.has(s)||t.length!==2)return;const[r,o]=t,i=xi(r),a=xi(o);if(i!==a)if(mi(i)&&mi(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||ku(t[r]))&&s.push(r);s.length&&$u(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 Fu(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 ha=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function ma(e){return ko(e)&&"offsetHeight"in e}const vi=30,Bu=e=>!isNaN(parseFloat(e));class Uu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Me.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=Me.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Bu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&Sr(!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 wr);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=Me.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>vi)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,vi);return Do(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 Jt(e,t){return new Uu(e,t)}const{schedule:$r}=_o(queueMicrotask,!1),ze={x:!1,y:!1};function pa(){return ze.x||ze.y}function zu(e){return e==="x"||e==="y"?ze[e]?null:(ze[e]=!0,()=>{ze[e]=!1}):ze.x||ze.y?null:(ze.x=ze.y=!0,()=>{ze.x=ze.y=!1})}function ga(e,t){const n=Fu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function wi(e){return!(e.pointerType==="touch"||pa())}function _u(e,t,n={}){const[s,r,o]=ga(e,n),i=a=>{if(!wi(a))return;const{target:l}=a,c=t(l,a);if(typeof c!="function"||!l)return;const d=f=>{wi(f)&&(c(f),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ya=(e,t)=>t?e===t?!0:ya(e,t.parentElement):!1,Lr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Xu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Wu(e){return Xu.has(e.tagName)||e.tabIndex!==-1}const is=new WeakSet;function Si(e){return t=>{t.key==="Enter"&&e(t)}}function Ns(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const qu=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Si(()=>{if(is.has(n))return;Ns(n,"down");const r=Si(()=>{Ns(n,"up")}),o=()=>Ns(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 Ti(e){return Lr(e)&&!pa()}function Ku(e,t,n={}){const[s,r,o]=ga(e,n),i=a=>{const l=a.currentTarget;if(!Ti(a))return;is.add(l);const c=t(l,a),d=(p,x)=>{window.removeEventListener("pointerup",f),window.removeEventListener("pointercancel",m),is.has(l)&&is.delete(l),Ti(p)&&typeof c=="function"&&c(p,{success:x})},f=p=>{d(p,l===window||l===document||n.useGlobalTarget||ya(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),ma(a)&&(a.addEventListener("focus",c=>qu(c,r)),!Wu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function xa(e){return ko(e)&&"ownerSVGElement"in e}function Gu(e){return xa(e)&&e.tagName==="svg"}const Te=e=>!!(e&&e.getVelocity),Hu=[...ua,ge,bt],Yu=e=>Hu.find(ca(e)),Fr=h.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function ji(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ju(...e){return t=>{let n=!1;const s=e.map(r=>{const o=ji(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():ji(e[r],null)}}}}function Zu(...e){return _e.useCallback(Ju(...e),e)}class Qu extends _e.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=ma(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 ed({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(Fr),l=Zu(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 x=n==="left"?`left: ${m}`:`right: ${p}`;o.current.dataset.motionPopId=r;const b=document.createElement("style");a&&(b.nonce=a);const S=s??document.head;return S.appendChild(b),b.sheet&&b.sheet.insertRule(`
|
|
1
|
+
"use strict";var bl=Object.create;var ti=Object.defineProperty;var vl=Object.getOwnPropertyDescriptor;var wl=Object.getOwnPropertyNames;var Sl=Object.getPrototypeOf,Tl=Object.prototype.hasOwnProperty;var jl=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of wl(t))!Tl.call(e,r)&&r!==n&&ti(e,r,{get:()=>t[r],enumerable:!(s=vl(t,r))||s.enumerable});return e};var Cl=(e,t,n)=>(n=e!=null?bl(Sl(e)):{},jl(t||!e||!e.__esModule?ti(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react/jsx-runtime"),h=require("react"),ne=require("lucide-react"),Pl=require("@ai-sdk/react"),ni=require("ai"),To=require("@radix-ui/react-slot"),jo=require("class-variance-authority"),Al=require("clsx"),El=require("tailwind-merge"),Ml=require("@radix-ui/react-tooltip"),si=require("@radix-ui/react-use-controllable-state"),kl=require("@radix-ui/react-collapsible"),Nl=require("react-dom"),Rl=require("@radix-ui/react-dialog");function fs(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 qe=fs(h),Qt=fs(Ml),hr=fs(kl),Ot=fs(Rl),$e=Symbol.for("@arcteninc/core:originalName");function Dl(e,t){return e[$e]=t,e}function Vl(e,t,n,s){if(typeof e!="function")return null;const r=e[$e];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[$e]=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[$e]=i.name,{fn:e,meta:i}}else if(i=Object.values(t).find(l=>!n.has(l.name)),i)return e[$e]=i.name,{fn:e,meta:i};return null}function mr(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=Vl(o,n,r,s);if(!i){const a=o.name,c=o[$e]||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 Il={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(Il))if(t!=="text"){for(const s of n)if(s.test(e))return t}return null}function Ol(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 $l(e,t,n){return t.length>0}function Ll(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=Fl(s[i]),d={name:i,type:Bl(l||Cn(i)||"text"),label:Co(i),placeholder:Ul(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:$l(e,t),fields:r,title:zl(e),description:_l(e,r.length)}}function Fl(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}}function Bl(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 Co(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Ul(e,t){return t?Ol(t,e).placeholder:`Enter ${Co(e).toLowerCase()}...`}function zl(e){return e.replace(/([A-Z])/g," $1").trim().toLowerCase().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function _l(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 Xl(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 Wl(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 es="__secureOutput",ts="[hidden for privacy]";function ql(e,t){if(!e||e.length===0)return t;const n=new Map;t.forEach(o=>{const i=o[$e]||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[$e]||o.name;i&&!s.has(i)&&(console.log(`[useAgent] Allowing client-only tool (forward compatible): ${i}`),r.push(o))}),r}function Kl(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 Gl(e){return e.replace(/\[(\w+)\]/g,".$1").split(".").map(t=>t.trim()).filter(Boolean)}function Hl(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 Yl(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 _s(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 Po(e,t=""){const n={};return e&&typeof e=="object"?Object.entries(e).forEach(([s,r])=>{const o=t?`${t}.${s}`:s;n[o]=_s(r),r&&typeof r=="object"&&Object.assign(n,Po(r,o))}):t&&(n[t]=_s(e)),n}function Jl(e){if(e===void 0||e===!1)return;if(e===!0)return{strategy:"full",fields:[],placeholder:ts,includeFieldStatus:!1,preserve:[]};if(Array.isArray(e))return{strategy:"fields",fields:e,placeholder:ts,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??ts,includeFieldStatus:e.includeFieldStatus??!1,preserve:e.preserve??[]}}function Zl(e){if(!e)return{};const t={};for(const[n,s]of Object.entries(e)){const r=Jl(s);r&&(t[n]=r)}return t}function Ao(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=Po(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[es]=r,l}if(n.fields.includes("*"))return Ao(e,t,{...n,strategy:"full",fields:[]});if(typeof t!="object"||t===null)return{value:s,[es]:{...r,redactedFields:n.fields}};const o=Kl(t),i=[],a={};return n.fields.forEach(l=>{const c=Gl(l);if(c.length===0)return;const d=Hl(o,c),f=_s(d);a[l]=f,Yl(o,c,s)&&i.push(l)}),r.redactedFields=i,n.includeFieldStatus&&(r.fieldStatus=a),o[es]=r,o}function Eo({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:L=[],conversationId:D,state:O,onStateChange:k,allowStateEdits:C=!0,onToolCall:V,onFinish:A,sources:N,ragConfig:F,ragFilters:$,secureInputHandler:B}={}){const X=e.replace(/\/+$/,""),[K,q]=h.useState(null),[oe,ye]=h.useState(!1),[Ge,vt]=h.useState(null),et=h.useMemo(()=>{const g=N||[],y=K?.config?.sources||[];return[...new Set([...g,...y])]},[N,K]),G=h.useMemo(()=>F!==void 0?F:$?{enabled:!0,filters:$}:et&&et.length>0?{enabled:!0,organizationId:et[0],autoExecute:!0,filters:void 0}:{enabled:!1},[et,F,$]),$t=h.useMemo(()=>M===!1?!1:!!w,[w,M]);h.useEffect(()=>{if(!$t||!ae.current)return;(async()=>{ye(!0),vt(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"),q(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();q(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));vt(x),q(null)}finally{ye(!1)}})()},[$t,w,T,v,X,E]);const Ee=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]),wt=h.useMemo(()=>Zl(d),[d]),Ce=h.useCallback((g,y)=>{const x=wt[g];if(!x)return y;try{return Ao(g,y,x)}catch(S){return console.error(`[useAgent] Failed to redact output for ${g}:`,S),{value:ts,[es]:{tool:g,redacted:!0,error:String(S)}}}},[wt]),[Be,Lt]=h.useState(n||null),ae=h.useRef(n||null),[pn,at]=h.useState(null),[lt,gn]=h.useState(null),Ue=h.useRef(null),[St,Tt]=h.useState([]),[Re,yn]=h.useState(D||(typeof window<"u"?crypto.randomUUID():null)),[ys,Ft]=h.useState(!1),Bt=h.useRef(new Set),ct=h.useRef(new Set),[ut,xs]=h.useState(new Map),[_n,He]=h.useState(new Map),[bs,Xn]=h.useState(new Map),[Ut,xn]=h.useState(new Map),le=O!==void 0,[bn,ze]=h.useState({}),we=h.useRef({}),Ye=le?O||{}:bn;le&&O?we.current=O:le||(we.current=bn);const[_e,zt]=h.useState(!1),[jt,Ct]=h.useState(null),vn=h.useRef(!1),De=h.useCallback(async(g,y=3)=>{if(!Re||!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:Re,updates:g},format:"json"})});if(!R.ok){if(R.status===404)return;const I=await R.text().catch(()=>"Unknown error");throw new Error(`Failed to sync conversation state: ${R.status} ${I}`)}};for(let S=0;S<y;S++)try{await x(),Ct(null);return}catch(P){if(S===y-1){const I=P instanceof Error?P:new Error(String(P));throw Ct(I),console.error("Failed to sync state to Convex after retries:",P),I}await new Promise(I=>setTimeout(I,Math.pow(2,S)*100))}},[Re,X,ae]),Pt=h.useMemo(()=>function(){return we.current},[]),xe=h.useMemo(()=>async function(y){const x={...we.current,...y};we.current=x,le||ze(x),k&&k(x);try{await De(y)}catch(S){throw S}},[De,k,le]);h.useEffect(()=>{le&&O&&(we.current=O)},[le,O]);const Wn=h.useCallback(g=>B?B.showSecureModal(g):new Promise(y=>{xs(x=>new Map(x).set(g.id,g)),He(x=>new Map(x).set(g.id,y))}),[B]),_t=h.useCallback((g,y)=>{if(B)return;const x=_n.get(g);x&&(x(y),xs(S=>{const P=new Map(S);return P.delete(g),P}),He(S=>{const P=new Map(S);return P.delete(g),P}))},[_n,B]),tt=h.useCallback(g=>B?B.showSecureForm(g):new Promise(y=>{Xn(x=>new Map(x).set(g.id,g)),xn(x=>new Map(x).set(g.id,y))}),[B]),Zr=h.useCallback((g,y)=>{if(B)return;const x=Ut.get(g);x&&(x(y),Xn(S=>{const P=new Map(S);return P.delete(g),P}),xn(S=>{const P=new Map(S);return P.delete(g),P}))},[Ut,B]),wn=h.useCallback((g,y)=>{const x=Ee[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},[Ee,f]),Sn=h.useCallback((g,y)=>{const S={...Ee[g]||{}};if(f){for(const R of Object.keys(y))if(!(R in S)){const I=Cn(R);I&&(S[R]=I)}}const P=Object.entries(S).filter(([R])=>Object.prototype.hasOwnProperty.call(y,R));return P.length>0?Object.fromEntries(P):S},[Ee,f]),Je=h.useMemo(()=>G?.enabled?async function(y,x=20,S){const P={...G.filters,...S};if(N&&N.length>1){const I=N.map(te=>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:te,...Object.keys(P).length>0?{filters:P}:{}})}).then(H=>H.ok?H.json():null)),J=await Promise.all(I),ee=[];for(const te of J)te?.candidates&&ee.push(...te.candidates);ee.sort((te,H)=>{const st=te.scores?.rerank||te.scores?.dense||0;return(H.scores?.rerank||H.scores?.dense||0)-st});const me=ee.slice(0,x).map((te,H)=>{const st=te.citation||te.url;return{rank:H+1,doc_id:te.doc_id,block_id:te.block_id,url:te.url,citation:st,title:te.title||"Untitled",snippet:te.snippet,score:te.scores?.rerank||te.scores?.dense||0,metadata:{site:te.metadata?.site,lang:te.metadata?.lang,contentType:te.metadata?.content_type}}});return{success:!0,query:y,total:ee.length,results:me,summary:`Found ${ee.length} relevant results across ${N.length} source(s) for "${y}". Top result: ${me[0]?.title||"N/A"}`}}const R=G.organizationId&&G.organizationId!=="default"?G.organizationId:N&&N.length>0?N[0]:void 0;try{const I={q:y,k:Math.min(x,100)};R&&(I.organizationId=R),Object.keys(P).length>0&&(I.filters=P);const J={"Content-Type":"application/json"};ae.current&&(J.Authorization=`Bearer ${ae.current}`);const ee=await fetch(`${X}/search`,{method:"POST",headers:J,body:JSON.stringify(I)});if(!ee.ok){const H=await ee.text();return{success:!1,error:`Search failed: ${ee.status} ${H}`}}const me=await ee.json(),te=me.candidates.map((H,st)=>{const Et=H.citation||H.url;return{rank:st+1,doc_id:H.doc_id,block_id:H.block_id,url:H.url,citation:Et,title:H.title||"Untitled",snippet:H.snippet,score:H.scores?.rerank||H.scores?.dense||0,metadata:{site:H.metadata?.site,lang:H.metadata?.lang,contentType:H.metadata?.content_type}}});return{success:!0,query:me.query,total:me.total,results:te,summary:`Found ${me.total} relevant results for "${y}". Top result: ${te[0]?.title||"N/A"}`}}catch(I){return{success:!1,error:I instanceof Error?I.message:"Unknown error occurred"}}}:null,[G,X,ae]),dt=h.useMemo(()=>G?.enabled?async function(y,x){const S=G.organizationId&&G.organizationId!=="default"?G.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 J=await R.text();return{success:!1,error:`Fetch failed: ${R.status} ${J}`}}const I=await R.json();return{success:!0,blocks:I.blocks||[],fullContent:I.fullContent||"",pageUrl:I.pageUrl||"",pageTitle:I.pageTitle||"",summary:`Fetched ${I.blocks?.length||0} blocks from ${I.pageTitle||y}`}}catch(P){return{success:!1,error:P instanceof Error?P.message:"Unknown error occurred"}}}:null,[G,X,ae]),Xt=h.useMemo(()=>{if(K&&K.config?.tools){const g=ql(K.config.tools,o);return console.log("[useAgent] Merged remote config:",{remoteToolCount:K.config.tools.length,localToolCount:o.length,mergedToolCount:g.length}),g}return o},[K,o]),Xe=K?.enableStateTools??!0,Ze=K?.enableRagTools??G?.enabled??!1,qn=h.useMemo(()=>{const g=[...Xt,...i];return Xe&&(g.push(Pt),(!le||C)&&g.push(xe)),Ze&&(Je&&g.push(Je),dt&&g.push(dt)),g},[Xt,i,Pt,xe,Je,dt,Xe,Ze,le,C]),Kn=h.useMemo(()=>[...Xt,...i],[Xt,i]),nt=h.useMemo(()=>mr(Kn,l),[Kn,l]),At=h.useMemo(()=>{const g=new Map,y=new Map(nt.map(x=>[x.name,x]));return g.set("getState",Pt),(!le||C)&&g.set("setState",xe),G?.enabled&&(Je&&g.set("searchDocs",Je),dt&&g.set("fetchDocContent",dt)),qn.forEach(x=>{if(x===Pt||x===xe||x===Je||x===dt)return;const S=x[$e];if(S){const R=y.get(S);if(R){g.set(R.name,x);return}}const P=nt.find(R=>R.name===x.name);P&&g.set(P.name,x)}),g},[qn,nt,Pt,xe,Je,dt,G,le,C]),Tn=h.useMemo(()=>new Set(nt.map(g=>g.name)),[nt]),Gn=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:[]}}),(!le||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=[];Ze&&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 K?.config?.workflows&&K.config.workflows.forEach(S=>{const P={},R=[];S.parameters&&S.parameters.forEach(I=>{P[I.name]={type:I.type||"string",description:I.description},I.required&&R.push(I.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})}),[...nt,...g,...y,...x]},[nt,Xe,Ze,le,C,K]),ft=h.useMemo(()=>Gn.filter(g=>g.name==="getState"?Xe:g.name==="setState"?Xe&&(!le||C):g.name==="searchDocs"||g.name==="fetchDocContent"?Ze:g.name.startsWith("workflow_")?!0:Tn.has(g.name)),[Gn,Tn,Xe,Ze,le,C]),Wt=h.useMemo(()=>{const g=new Set;return Xe&&(g.add("getState"),g.add("setState")),Ze&&G?.autoExecute!==!1&&(g.add("searchDocs"),g.add("fetchDocContent")),K?.config?.tools?K.config.tools.forEach(y=>{y.isEnabled&&!y.requiresApproval&&g.add(y.name)}):(i.forEach(y=>{for(const[x,S]of At.entries())if(S===y){g.add(x);break}}),a&&Array.isArray(a)&&a.forEach(y=>{typeof y=="string"&&g.add(y)})),K?.config?.workflows&&K.config.workflows.forEach(y=>{const x=`workflow_${y.name.replace(/\s+/g,"_").toLowerCase()}`;y.requiresApproval||g.add(x)}),g},[K,i,a,At,Xe,Ze,G]);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 I=await R.json();g||(Lt(I.clientToken),ae.current=I.clientToken,gn(I.expiresAt),at(null))}catch(R){if(console.error(`[useAgent] Token fetch failed (attempt ${S}/${P}):`,R),S<P&&!g){const I=Math.pow(2,S-1)*1e3;y=setTimeout(()=>x(S+1,P),I)}else g||at(R instanceof Error?R.message:"Failed to fetch token")}};return x(),()=>{g=!0,y&&clearTimeout(y),Ue.current&&clearTimeout(Ue.current)}},[t,JSON.stringify(r),s,n]),h.useEffect(()=>{if(!lt||s||n)return;Ue.current&&clearTimeout(Ue.current);const g=async(R=1,I=3)=>{try{const J=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:r})});if(!J.ok)throw new Error("Failed to refresh token");const ee=await J.json();Lt(ee.clientToken),ae.current=ee.clientToken,gn(ee.expiresAt),at(null)}catch(J){if(console.error(`[useAgent] Token refresh failed (attempt ${R}/${I}):`,J),R<I){const ee=Math.pow(2,R-1)*1e3;setTimeout(()=>g(R+1,I),ee)}else at(J instanceof Error?J.message:"Failed to refresh token")}},y=Math.floor(Date.now()/1e3),x=lt-y,P=Math.max(0,x-5);return Ue.current=setTimeout(()=>g(),P*1e3),()=>{Ue.current&&clearTimeout(Ue.current)}},[lt,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(!lt||lt<=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();Lt(P.clientToken),ae.current=P.clientToken,gn(P.expiresAt),at(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),lt,s,n]);const vs=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})},qt=h.useRef(null),ws=`${X}/chat`,{messages:j,sendMessage:W,status:_,error:Z,stop:Y,addToolResult:Q,setMessages:Me}=Pl.useChat({id:Re||void 0,messages:L,transport:new ni.DefaultChatTransport({api:ws,fetch:vs,headers:()=>{const g={};return ae.current&&(g.Authorization=`Bearer ${ae.current}`),g},body:()=>({tools:ft.map(y=>({name:y.name,description:y.description,inputSchema:y.jsonSchema})),...v&&{agentId:v},...T&&{agentName:T},state:we.current,...$&&{ragFilters:$}})}),sendAutomaticallyWhen:g=>{const y=g.messages;if(y[y.length-1]?.role!=="assistant")return!1;const P=[...y].reverse().find(I=>I.role==="user")?.id;if(P&&qt.current===P)return!1;const R=ni.lastAssistantMessageIsCompleteWithToolCalls(g);return R&&P&&(qt.current=P),R}}),ie=W,Se=h.useCallback(g=>(qt.current=null,ie(g)),[ie]),U=h.useCallback((g,y,x)=>{const S=Ce(g,x);Q({toolCallId:y,tool:g,output:S})},[Q,Ce]);h.useEffect(()=>{j.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(Bt.current.has(S)||ct.current.has(S)){console.log(`[useAgent] Skipping ${x} (${S}) - already processing or completed`);return}console.log(`[useAgent] Starting ${x} (${S})`),Bt.current.add(S);const P=I=>{console.log(`[useAgent] Completed ${x} (${I})`),ct.current.add(I),Bt.current.delete(I)},R=Wl(y.input);if(wn(x,R)){const I=Sn(x,R),J=Object.entries(I).filter(([H])=>R[H]!==void 0),ee=J.length>0?Object.fromEntries(J):I,me=Object.keys(R),te=Xl(R,ee);(async()=>{try{const H=Ll(x,me,ee,R),st={id:`${S}-form`,toolName:x,toolCallId:S,title:H.title,description:H.description,fields:H.fields},Et=await tt(st);if(Et===null){U(x,S,"User cancelled secure input"),P(S);return}const Qr={...te,...Et},Ss=At.get(x);if(!Ss)throw new Error(`Tool ${x} not found`);let Ts;const js=ft.find(ei=>ei.name===x);if(js&&js.jsonSchema?.properties){const yl=Object.keys(js.jsonSchema.properties).map(xl=>Qr[xl]);Ts=await Ss(...yl)}else Ts=await Ss(...Object.values(Qr));P(S),U(x,S,Ts)}catch(H){console.error(`[useAgent] Error executing tool with secure input ${x}:`,H),P(S),U(x,S,`Error: ${H}`)}})();return}if(x.startsWith("workflow_")&&Wt.has(x)){(async()=>{try{const J=ft.find(me=>me.name===x)?._workflow;if(!J)throw new Error(`Workflow metadata not found for ${x}`);let ee;if(J.webhook?.url){let me=R;if(J.webhook.bodyTemplate){let H=J.webhook.bodyTemplate;Object.entries(R).forEach(([st,Et])=>{H=H.replace(new RegExp(`\\{\\{${st}\\}\\}`,"g"),String(Et))}),me=JSON.parse(H)}const te=await fetch(J.webhook.url,{method:J.webhook.method||"POST",headers:{"Content-Type":"application/json",...J.webhook.headers||{}},body:JSON.stringify(me)});if(te.ok)ee={success:!0,data:await te.json().catch(()=>({success:!0}))};else{const H=await te.text();ee={success:!1,error:`Webhook failed: ${te.status} ${H}`}}}else ee={success:!0,message:`Workflow "${J.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:J.contentPlaintext};P(S),U(x,S,ee)}catch(I){console.error(`[useAgent] Error executing workflow ${x}:`,I),P(S),U(x,S,`Error: ${I}`)}})();return}if(Wt.has(x)&&!wn(x,R)){const I=At.get(x);I?(async()=>{try{const J=ft.find(me=>me.name===x);let ee;if(J&&J.jsonSchema?.properties){const te=Object.keys(J.jsonSchema.properties).map(H=>R[H]);ee=await I(...te)}else if(x==="getState")ee=I();else if(x==="setState"){const me=R.updates||R;ee=await I(me)}else ee=await I(...Object.values(R));P(S),U(x,S,ee)}catch(J){console.error(`[useAgent] Error executing tool ${x}:`,J),P(S),U(x,S,`Error: ${J}`)}})():(console.warn(`[useAgent] Tool ${x} not found in toolsMap`),U(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`),U(x,S,`Error: Tool "${x}" cannot be executed. No handler is available for this tool.`),P(S))})})},[j,Wt,At,V,U,xe,ft,wn,Sn,Wn]),h.useEffect(()=>{if(_==="ready"&&j.length>0&&A){const g=j[j.length-1];g&&g.role==="assistant"&&A({message:g,messages:j,isAbort:!1,isDisconnect:!1,isError:!!Z})}},[_,j,Z,A]);async function he(){if(!(!r?.id||!Be)){Ft(!0);try{const y=await(await fetch(`${X}/conversations`,{headers:{Authorization:`Bearer ${Be}`}})).json();Tt(y.conversations||[])}catch(g){console.error("Failed to fetch conversations:",g)}finally{Ft(!1)}}}h.useEffect(()=>{r?.id&&Be&&he()},[JSON.stringify(r),Be,X]),h.useEffect(()=>{if(!Re||!ae.current)return;(async()=>{zt(!0),Ct(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:Re},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||{};we.current=S,le||ze(S),k&&k(S),vn.current=!0}catch(y){console.error("Failed to fetch state:",y);const x=y instanceof Error?y:new Error(String(y));Ct(x),vn.current||(we.current={},le?k&&k({}):(ze({}),k&&k({})),vn.current=!0)}finally{zt(!1)}})()},[Re,X,le,k]);async function se(g){yn(g),Ft(!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||[];Me(S)}catch(y){console.error("Failed to load conversation messages:",y)}finally{Ft(!1)}}async function Pe(g){if(Be)try{await fetch(`${X}/conversations/${g}`,{method:"DELETE",headers:{Authorization:`Bearer ${Be}`}}),Tt(St.filter(y=>y._id!==g)),g===Re&&fe()}catch(y){console.error("Failed to delete conversation:",y)}}function fe(){const g=crypto.randomUUID();yn(g),Me([]),Bt.current=new Set,ct.current=new Set,we.current={},le?k&&k({}):(ze({}),k&&k({})),vn.current=!1}function Ve(g){const y=g.tool||"unknown-tool",x=Ce(y,g.output);Q({toolCallId:g.toolCallId,tool:y,output:x})}async function be(g,y,x){if(!y.startsWith("workflow_"))throw new Error(`${y} is not a workflow tool`);try{const P=ft.find(I=>I.name===y)?._workflow;if(!P)throw new Error(`Workflow metadata not found for ${y}`);let R;if(P.webhook?.url){let I=x;if(P.webhook.bodyTemplate){let ee=P.webhook.bodyTemplate;Object.entries(x).forEach(([me,te])=>{ee=ee.replace(new RegExp(`\\{\\{${me}\\}\\}`,"g"),String(te))}),I=JSON.parse(ee)}const J=await fetch(P.webhook.url,{method:P.webhook.method||"POST",headers:{"Content-Type":"application/json",...P.webhook.headers||{}},body:JSON.stringify(I)});if(J.ok)R={success:!0,data:await J.json().catch(()=>({success:!0}))};else{const ee=await J.text();R={success:!1,error:`Webhook failed: ${J.status} ${ee}`}}}else R={success:!0,message:`Workflow "${P.name}" acknowledged. Follow the workflow instructions to proceed.`,instructions:P.contentPlaintext};return Ve({toolCallId:g,tool:y,output:R}),R}catch(S){const P={success:!1,error:String(S)};throw Ve({toolCallId:g,tool:y,output:P}),S}}async function ke(g){const y={...we.current,...g};we.current=y,le||ze(y),k&&k(y);try{await De(g)}catch(x){throw x}}return{id:Re,messages:j,status:_,error:Z,sendMessage:Se,stop:Y,addToolOutput:Ve,executeWorkflowTool:be,setMessages:Me,conversations:St,loadConversation:se,deleteConversation:Pe,startNewConversation:fe,isLoadingConversations:ys,clientToken:Be,tokenError:pn,state:Ye,setState:ke,isStateLoading:_e,stateError:jt,pendingSecureInputs:Array.from(ut.values()),completeSecureInput:_t,pendingSecureForms:Array.from(bs.values()),completeSecureForm:Zr,safeToolNames:Wt}}function re(...e){return El.twMerge(Al.clsx(e))}const kt=jo.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"}}),je=qe.forwardRef(({className:e,variant:t,size:n,asChild:s=!1,...r},o)=>{const i=s?To.Slot:"button";return u.jsx(i,{ref:o,"data-slot":"button",className:re(kt({variant:t,size:n,className:e})),...r})});je.displayName="Button";const Ql=jo.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 Cs({className:e,variant:t,asChild:n=!1,...s}){const r=n?To.Slot:"span";return u.jsx(r,{"data-slot":"badge",className:re(Ql({variant:t}),e),...s})}const ec=({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])},Mo=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 ec({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:re("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)}})});Mo.displayName="AutosizeTextarea";function tc({delayDuration:e=0,...t}){return u.jsx(Qt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function ht({...e}){return u.jsx(tc,{children:u.jsx(Qt.Root,{"data-slot":"tooltip",...e})})}function mt({...e}){return u.jsx(Qt.Trigger,{"data-slot":"tooltip-trigger",...e})}function pt({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:re("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 ri({className:e,...t}){return u.jsx("kbd",{"data-slot":"kbd",className:re("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 pr=h.createContext({});function gr(e){const t=h.useRef(null);return t.current===null&&(t.current=e()),t.current}const yr=typeof window<"u",ko=yr?h.useLayoutEffect:h.useEffect,hs=h.createContext(null);function xr(e,t){e.indexOf(t)===-1&&e.push(t)}function br(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const rt=(e,t,n)=>n>t?t:n<e?e:n;function Xs(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}let sn=()=>{},it=()=>{};process.env.NODE_ENV!=="production"&&(sn=(e,t,n)=>{!e&&typeof console<"u"&&console.warn(Xs(t,n))},it=(e,t,n)=>{if(!e)throw new Error(Xs(t,n))});const ot={},No=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Ro(e){return typeof e=="object"&&e!==null}const Do=e=>/^0[^.\s]+$/u.test(e);function vr(e){let t;return()=>(t===void 0&&(t=e()),t)}const Fe=e=>e,nc=(e,t)=>n=>t(e(n)),Fn=(...e)=>e.reduce(nc),Dn=(e,t,n)=>{const s=t-e;return s===0?1:(n-e)/s};class wr{constructor(){this.subscriptions=[]}add(t){return xr(this.subscriptions,t),()=>br(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,Le=e=>e/1e3;function Vo(e,t){return t?e*(1e3/t):0}const ii=new Set;function Sr(e,t,n){e||ii.has(t)||(console.warn(Xs(t,n)),ii.add(t))}const Io=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,sc=1e-7,rc=12;function ic(e,t,n,s,r){let o,i,a=0;do i=t+(n-t)/2,o=Io(i,s,r)-e,o>0?n=i:t=i;while(Math.abs(o)>sc&&++a<rc);return i}function Bn(e,t,n,s){if(e===t&&n===s)return Fe;const r=o=>ic(o,0,1,e,n);return o=>o===0||o===1?o:Io(r(o),t,s)}const Oo=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,$o=e=>t=>1-e(1-t),Lo=Bn(.33,1.53,.69,.99),Tr=$o(Lo),Fo=Oo(Tr),Bo=e=>(e*=2)<1?.5*Tr(e):.5*(2-Math.pow(2,-10*(e-1))),jr=e=>1-Math.sin(Math.acos(e)),Uo=$o(jr),zo=Oo(jr),oc=Bn(.42,0,1,1),ac=Bn(0,0,.58,1),_o=Bn(.42,0,.58,1),lc=e=>Array.isArray(e)&&typeof e[0]!="number",Xo=e=>Array.isArray(e)&&typeof e[0]=="number",oi={linear:Fe,easeIn:oc,easeInOut:_o,easeOut:ac,circIn:jr,circInOut:zo,circOut:Uo,backIn:Tr,backInOut:Fo,backOut:Lo,anticipate:Bo},cc=e=>typeof e=="string",ai=e=>{if(Xo(e)){it(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(cc(e))return it(oi[e]!==void 0,`Invalid easing type '${e}'`,"invalid-easing-type"),oi[e];return e},Hn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function uc(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 dc=40;function Wo(e,t){let n=!1,s=!0;const r={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,i=Hn.reduce((E,L)=>(E[L]=uc(o),E),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:f,preRender:m,render:p,postRender:b}=i,v=()=>{const E=ot.useManualTiming?r.timestamp:performance.now();n=!1,ot.useManualTiming||(r.delta=s?1e3/60:Math.max(Math.min(E-r.timestamp,dc),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:Hn.reduce((E,L)=>{const D=i[L];return E[L]=(O,k=!1,C=!1)=>(n||T(),D.schedule(O,k,C)),E},{}),cancel:E=>{for(let L=0;L<Hn.length;L++)i[Hn[L]].cancel(E)},state:r,steps:i}}const{schedule:ce,cancel:yt,state:ve,steps:Ps}=Wo(typeof requestAnimationFrame<"u"?requestAnimationFrame:Fe,!0);let ns;function fc(){ns=void 0}const Ne={now:()=>(ns===void 0&&Ne.set(ve.isProcessing||ot.useManualTiming?ve.timestamp:performance.now()),ns),set:e=>{ns=e,queueMicrotask(fc)}},qo=e=>t=>typeof t=="string"&&t.startsWith(e),Cr=qo("--"),hc=qo("var(--"),Pr=e=>hc(e)?mc.test(e.split("/*")[0].trim()):!1,mc=/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=>rt(0,1,e)},Yn={...rn,default:1},En=e=>Math.round(e*1e5)/1e5,Ar=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function pc(e){return e==null}const gc=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Er=(e,t)=>n=>!!(typeof n=="string"&&gc.test(n)&&n.startsWith(e)||t&&!pc(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ko=(e,t,n)=>s=>{if(typeof s!="string")return s;const[r,o,i,a]=s.match(Ar);return{[e]:parseFloat(r),[t]:parseFloat(o),[n]:parseFloat(i),alpha:a!==void 0?parseFloat(a):1}},yc=e=>rt(0,255,e),As={...rn,transform:e=>Math.round(yc(e))},Rt={test:Er("rgb","red"),parse:Ko("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+As.transform(e)+", "+As.transform(t)+", "+As.transform(n)+", "+En(Vn.transform(s))+")"};function xc(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 Ws={test:Er("#"),parse:xc,transform:Rt.transform},Un=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),gt=Un("deg"),Qe=Un("%"),z=Un("px"),bc=Un("vh"),vc=Un("vw"),li={...Qe,parse:e=>Qe.parse(e)/100,transform:e=>Qe.transform(e*100)},Kt={test:Er("hsl","hue"),parse:Ko("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))+")"},ge={test:e=>Rt.test(e)||Ws.test(e)||Kt.test(e),parse:e=>Rt.test(e)?Rt.parse(e):Kt.test(e)?Kt.parse(e):Ws.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?Rt.transform(e):Kt.transform(e),getAnimatableNone:e=>{const t=ge.parse(e);return t.alpha=0,ge.transform(t)}},wc=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Sc(e){return isNaN(e)&&typeof e=="string"&&(e.match(Ar)?.length||0)+(e.match(wc)?.length||0)>0}const Go="number",Ho="color",Tc="var",jc="var(",ci="${}",Cc=/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(Cc,l=>(ge.test(l)?(s.color.push(o),r.push(Ho),n.push(ge.parse(l))):l.startsWith(jc)?(s.var.push(o),r.push(Tc),n.push(l)):(s.number.push(o),r.push(Go),n.push(parseFloat(l))),++o,ci)).split(ci);return{values:n,split:a,indexes:s,types:r}}function Yo(e){return In(e).values}function Jo(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===Go?o+=En(r[i]):a===Ho?o+=ge.transform(r[i]):o+=r[i]}return o}}const Pc=e=>typeof e=="number"?0:ge.test(e)?ge.getAnimatableNone(e):e;function Ac(e){const t=Yo(e);return Jo(e)(t.map(Pc))}const xt={test:Sc,parse:Yo,createTransformer:Jo,getAnimatableNone:Ac};function Es(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 Ec({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=Es(l,a,e+1/3),o=Es(l,a,e),i=Es(l,a,e-1/3)}return{red:Math.round(r*255),green:Math.round(o*255),blue:Math.round(i*255),alpha:s}}function as(e,t){return n=>n>0?t:e}const de=(e,t,n)=>e+(t-e)*n,Ms=(e,t,n)=>{const s=e*e,r=n*(t*t-s)+s;return r<0?0:Math.sqrt(r)},Mc=[Ws,Rt,Kt],kc=e=>Mc.find(t=>t.test(e));function ui(e){const t=kc(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=Ec(n)),n}const di=(e,t)=>{const n=ui(e),s=ui(t);if(!n||!s)return as(e,t);const r={...n};return o=>(r.red=Ms(n.red,s.red,o),r.green=Ms(n.green,s.green,o),r.blue=Ms(n.blue,s.blue,o),r.alpha=de(n.alpha,s.alpha,o),Rt.transform(r))},qs=new Set(["none","hidden"]);function Nc(e,t){return qs.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Rc(e,t){return n=>de(e,t,n)}function Mr(e){return typeof e=="number"?Rc:typeof e=="string"?Pr(e)?as:ge.test(e)?di:Ic:Array.isArray(e)?Zo:typeof e=="object"?ge.test(e)?di:Dc:as}function Zo(e,t){const n=[...e],s=n.length,r=e.map((o,i)=>Mr(o)(o,t[i]));return o=>{for(let i=0;i<s;i++)n[i]=r[i](o);return n}}function Dc(e,t){const n={...e,...t},s={};for(const r in n)e[r]!==void 0&&t[r]!==void 0&&(s[r]=Mr(e[r])(e[r],t[r]));return r=>{for(const o in s)n[o]=s[o](r);return n}}function Vc(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 Ic=(e,t)=>{const n=xt.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?qs.has(e)&&!r.values.length||qs.has(t)&&!s.values.length?Nc(e,t):Fn(Zo(Vc(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"),as(e,t))};function Qo(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?de(e,t,n):Mr(e)(e,t)}const Oc=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>ce.update(t,n),stop:()=>yt(t),now:()=>ve.isProcessing?ve.timestamp:Ne.now()}},ea=(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)})`},ls=2e4;function kr(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<ls;)t+=n,s=e.next(t);return t>=ls?1/0:t}function $c(e,t=100,n){const s=n({...e,keyframes:[0,t]}),r=Math.min(kr(s),ls);return{type:"keyframes",ease:o=>s.next(r*o).value/t,duration:Le(r)}}const Lc=5;function ta(e,t,n){const s=Math.max(t-Lc,0);return Vo(n-e(s),t-s)}const ue={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},ks=.001;function Fc({duration:e=ue.duration,bounce:t=ue.bounce,velocity:n=ue.velocity,mass:s=ue.mass}){let r,o;sn(e<=Ke(ue.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let i=1-t;i=rt(ue.minDamping,ue.maxDamping,i),e=rt(ue.minDuration,ue.maxDuration,Le(e)),i<1?(r=c=>{const d=c*i,f=d*e,m=d-n,p=Ks(c,i),b=Math.exp(-f);return ks-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=Ks(Math.pow(c,2),i);return(-r(c)+ks>0?-1:1)*((m-p)*b)/v}):(r=c=>{const d=Math.exp(-c*e),f=(c-n)*e+1;return-ks+d*f},o=c=>{const d=Math.exp(-c*e),f=(n-c)*(e*e);return d*f});const a=5/e,l=Uc(r,o,a);if(e=Ke(e),isNaN(l))return{stiffness:ue.stiffness,damping:ue.damping,duration:e};{const c=Math.pow(l,2)*s;return{stiffness:c,damping:i*2*Math.sqrt(s*c),duration:e}}}const Bc=12;function Uc(e,t,n){let s=n;for(let r=1;r<Bc;r++)s=s-e(s)/t(s);return s}function Ks(e,t){return e*Math.sqrt(1-t*t)}const zc=["duration","bounce"],_c=["stiffness","damping","mass"];function fi(e,t){return t.some(n=>e[n]!==void 0)}function Xc(e){let t={velocity:ue.velocity,stiffness:ue.stiffness,damping:ue.damping,mass:ue.mass,isResolvedFromDuration:!1,...e};if(!fi(e,_c)&&fi(e,zc))if(e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),r=s*s,o=2*rt(.05,1,1-(e.bounce||0))*Math.sqrt(r);t={...t,mass:ue.mass,stiffness:r,damping:o}}else{const n=Fc(e);t={...t,...n,mass:ue.mass},t.isResolvedFromDuration=!0}return t}function cs(e=ue.visualDuration,t=ue.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}=Xc({...n,velocity:-Le(n.velocity||0)}),b=m||0,v=c/(2*Math.sqrt(l*d)),T=i-o,w=Le(Math.sqrt(l/d)),M=Math.abs(T)<5;s||(s=M?ue.restSpeed.granular:ue.restSpeed.default),r||(r=M?ue.restDelta.granular:ue.restDelta.default);let E;if(v<1){const D=Ks(w,v);E=O=>{const k=Math.exp(-v*w*O);return i-k*((b+v*w*T)/D*Math.sin(D*O)+T*Math.cos(D*O))}}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=O=>{const k=Math.exp(-v*w*O),C=Math.min(D*O,300);return i-k*((b+v*w*T)*Math.sinh(C)+D*T*Math.cosh(C))/D}}const L={calculatedDuration:p&&f||null,next:D=>{const O=E(D);if(p)a.done=D>=f;else{let k=D===0?b:0;v<1&&(k=D===0?Ke(b):ta(E,D,O));const C=Math.abs(k)<=s,V=Math.abs(i-O)<=r;a.done=C&&V}return a.value=a.done?i:O,a},toString:()=>{const D=Math.min(kr(L),ls),O=ea(k=>L.next(D*k).value,D,30);return D+"ms "+O},toTransition:()=>{}};return L}cs.applyToOptions=e=>{const t=$c(e,100,cs);return e.ease=t.ease,e.duration=Ke(t.duration),e.type="keyframes",e};function Gs({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),L=C=>{const V=M(C),A=E(C);m.done=Math.abs(V)<=c,m.value=m.done?w:A};let D,O;const k=C=>{p(m.value)&&(D=C,O=cs({keyframes:[m.value,b(m.value)],velocity:ta(E,C,m.value),damping:r,stiffness:o,restDelta:c,restSpeed:d}))};return k(0),{calculatedDuration:null,next:C=>{let V=!1;return!O&&D===void 0&&(V=!0,L(C),k(C)),D!==void 0&&C>=D?O.next(C-D):(!V&&L(C),m)}}}function Wc(e,t,n){const s=[],r=n||ot.mix||Qo,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]||Fe:t;a=Fn(l,a)}s.push(a)}return s}function qc(e,t,{clamp:n=!0,ease:s,mixer:r}={}){const o=e.length;if(it(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=Wc(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(rt(e[0],e[o-1],d)):c}function Kc(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const r=Dn(0,t,s);e.push(de(n,1,r))}}function Gc(e){const t=[0];return Kc(t,e.length-1),t}function Hc(e,t){return e.map(n=>n*t)}function Yc(e,t){return e.map(()=>t||_o).splice(0,e.length-1)}function Gt({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const r=lc(s)?s.map(ai):ai(s),o={done:!1,value:t[0]},i=Hc(n&&n.length===t.length?n:Gc(t),e),a=qc(i,t,{ease:Array.isArray(r)?r:Yc(t,r)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}const Jc=e=>e!==null;function Nr(e,{repeat:t,repeatType:n="loop"},s,r=1){const o=e.filter(Jc),a=r<0||t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||s===void 0?o[a]:s}const Zc={decay:Gs,inertia:Gs,tween:Gt,keyframes:Gt,spring:cs};function na(e){typeof e.type=="string"&&(e.type=Zc[e.type])}class Rr{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 Qc=e=>e/100;class Dr extends Rr{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!==Ne.now()&&this.tick(Ne.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;na(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&&it(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(Qc,Qo(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=kr(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,L=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"&&(L=i)),E=rt(0,1,A)*a}const D=M?{done:!1,value:d[0]}:L.next(E);o&&(D.value=o(D.value));let{done:O}=D;!M&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return k&&b!==Gs&&(D.value=Nr(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 Le(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Le(t)}get time(){return Le(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(Ne.now());const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=Le(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=Oc,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(Ne.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 eu(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const Dt=e=>e*180/Math.PI,Hs=e=>{const t=Dt(Math.atan2(e[1],e[0]));return Ys(t)},tu={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Hs,rotateZ:Hs,skewX:e=>Dt(Math.atan(e[1])),skewY:e=>Dt(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Ys=e=>(e=e%360,e<0&&(e+=360),e),hi=Hs,mi=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),pi=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),nu={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:mi,scaleY:pi,scale:e=>(mi(e)+pi(e))/2,rotateX:e=>Ys(Dt(Math.atan2(e[6],e[5]))),rotateY:e=>Ys(Dt(Math.atan2(-e[2],e[0]))),rotateZ:hi,rotate:hi,skewX:e=>Dt(Math.atan(e[4])),skewY:e=>Dt(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Js(e){return e.includes("scale")?1:0}function Zs(e,t){if(!e||e==="none")return Js(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,r;if(n)s=nu,r=n;else{const a=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=tu,r=a}if(!r)return Js(t);const o=s[t],i=r[1].split(",").map(ru);return typeof o=="function"?o(i):i[o]}const su=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Zs(n,t)};function ru(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),gi=e=>e===rn||e===z,iu=new Set(["x","y","z"]),ou=on.filter(e=>!iu.has(e));function au(e){const t=[];return ou.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Vt={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})=>Zs(t,"x"),y:(e,{transform:t})=>Zs(t,"y")};Vt.translateX=Vt.x;Vt.translateY=Vt.y;const It=new Set;let Qs=!1,er=!1,tr=!1;function sa(){if(er){const e=Array.from(It).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const r=au(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)})}er=!1,Qs=!1,It.forEach(e=>e.complete(tr)),It.clear()}function ra(){It.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(er=!0)})}function lu(){tr=!0,ra(),sa(),tr=!1}class Vr{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?(It.add(this),Qs||(Qs=!0,ce.read(ra),ce.resolveKeyframes(sa))):(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])}eu(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),It.delete(this)}cancel(){this.state==="scheduled"&&(It.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const cu=e=>e.startsWith("--");function uu(e,t,n){cu(t)?e.style.setProperty(t,n):e.style[t]=n}const du=vr(()=>window.ScrollTimeline!==void 0),fu={};function hu(e,t){const n=vr(e);return()=>fu[t]??n()}const ia=hu(()=>{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})`,yi={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 oa(e,t){if(e)return typeof e=="function"?ia()?ea(e,t):"ease-out":Xo(e)?Pn(e):Array.isArray(e)?e.map(n=>oa(n,t)||yi.easeOut):yi[e]}function mu(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=oa(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 aa(e){return typeof e=="function"&&"applyToOptions"in e}function pu({type:e,...t}){return aa(e)&&ia()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class gu extends Rr{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,it(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const c=pu(t);this.animation=mu(n,s,r,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Nr(r,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):uu(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 Le(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Le(t)}get time(){return Le(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&&du()?(this.animation.timeline=t,Fe):n(this)}}const la={anticipate:Bo,backInOut:Fo,circInOut:zo};function yu(e){return e in la}function xu(e){typeof e.ease=="string"&&yu(e.ease)&&(e.ease=la[e.ease])}const xi=10;class bu extends gu{constructor(t){xu(t),na(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 Dr({...i,autoplay:!1}),l=Ke(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-xi).value,a.sample(l).value,xi),a.stop()}}const bi=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(xt.test(e)||e==="0")&&!e.startsWith("url("));function vu(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 wu(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=bi(r,t),a=bi(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:vu(e)||(n==="spring"||aa(n))&&s}function nr(e){e.duration=0,e.type="keyframes"}const Su=new Set(["opacity","clipPath","filter","transform"]),Tu=vr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function ju(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 Tu()&&n&&Su.has(n)&&(n!=="transform"||!c)&&!l&&!s&&r!=="mirror"&&o!==0&&i!=="inertia"}const Cu=40;class Pu extends Rr{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=Ne.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||Vr;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=Ne.now(),wu(t,o,i,a)||((ot.instantAnimations||!l)&&d?.(Nr(t,s,n)),t[0]=t[t.length-1],nr(s),s.repeat=0);const m={startTime:r?this.resolvedAt?this.resolvedAt-this.createdAt>Cu?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},p=!c&&ju(m)?new bu({...m,element:m.motionValue.owner.current}):new Dr(m);p.finished.then(()=>this.notifyFinished()).catch(Fe),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(),lu()),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 Au=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Eu(e){const t=Au.exec(e);if(!t)return[,];const[,n,s,r]=t;return[`--${n??s}`,r]}const Mu=4;function ca(e,t,n=1){it(n<=Mu,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[s,r]=Eu(e);if(!s)return;const o=window.getComputedStyle(t).getPropertyValue(s);if(o){const i=o.trim();return No(i)?parseFloat(i):i}return Pr(r)?ca(r,t,n+1):r}function Ir(e,t){return e?.[t]??e?.default??e}const ua=new Set(["width","height","top","left","right","bottom",...on]),ku={test:e=>e==="auto",parse:e=>e},da=e=>t=>t.test(e),fa=[rn,z,Qe,gt,vc,bc,ku],vi=e=>fa.find(da(e));function Nu(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Do(e):!0}const Ru=new Set(["brightness","contrast","saturate","opacity"]);function Du(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(Ar)||[];if(!s)return e;const r=n.replace(s,"");let o=Ru.has(t)?1:0;return s!==n&&(o*=100),t+"("+o+r+")"}const Vu=/\b([a-z-]*)\(.*?\)/gu,sr={...xt,getAnimatableNone:e=>{const t=e.match(Vu);return t?t.map(Du).join(" "):e}},wi={...rn,transform:Math.round},Iu={rotate:gt,rotateX:gt,rotateY:gt,rotateZ:gt,scale:Yn,scaleX:Yn,scaleY:Yn,scaleZ:Yn,skew:gt,skewX:gt,skewY:gt,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:Vn,originX:li,originY:li,originZ:z},Or={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,...Iu,zIndex:wi,fillOpacity:Vn,strokeOpacity:Vn,numOctaves:wi},Ou={...Or,color:ge,backgroundColor:ge,outlineColor:ge,fill:ge,stroke:ge,borderColor:ge,borderTopColor:ge,borderRightColor:ge,borderBottomColor:ge,borderLeftColor:ge,filter:sr,WebkitFilter:sr},ha=e=>Ou[e];function ma(e,t){let n=ha(e);return n!==sr&&(n=xt),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const $u=new Set(["auto","none","0"]);function Lu(e,t,n){let s=0,r;for(;s<e.length&&!r;){const o=e[s];typeof o=="string"&&!$u.has(o)&&In(o).values.length&&(r=e[s]),s++}if(r&&n)for(const o of t)e[o]=ma(n,r)}class Fu extends Vr{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(),Pr(c))){const d=ca(c,n.current);d!==void 0&&(t[l]=d),l===t.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!ua.has(s)||t.length!==2)return;const[r,o]=t,i=vi(r),a=vi(o);if(i!==a)if(gi(i)&&gi(a))for(let l=0;l<t.length;l++){const c=t[l];typeof c=="string"&&(t[l]=parseFloat(c))}else Vt[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let r=0;r<t.length;r++)(t[r]===null||Nu(t[r]))&&s.push(r);s.length&&Lu(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=Vt[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]=Vt[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 Bu(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 pa=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function ga(e){return Ro(e)&&"offsetHeight"in e}const Si=30,Uu=e=>!isNaN(parseFloat(e));class zu{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const r=Ne.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=Ne.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Uu(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return process.env.NODE_ENV!=="production"&&Sr(!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 wr);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=Ne.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Si)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Si);return Vo(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 zu(e,t)}const{schedule:$r}=Wo(queueMicrotask,!1),We={x:!1,y:!1};function ya(){return We.x||We.y}function _u(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 xa(e,t){const n=Bu(e),s=new AbortController,r={passive:!0,...t,signal:s.signal};return[n,r,()=>s.abort()]}function Ti(e){return!(e.pointerType==="touch"||ya())}function Xu(e,t,n={}){const[s,r,o]=xa(e,n),i=a=>{if(!Ti(a))return;const{target:l}=a,c=t(l,a);if(typeof c!="function"||!l)return;const d=f=>{Ti(f)&&(c(f),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,r)};return s.forEach(a=>{a.addEventListener("pointerenter",i,r)}),o}const ba=(e,t)=>t?e===t?!0:ba(e,t.parentElement):!1,Lr=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,Wu=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function qu(e){return Wu.has(e.tagName)||e.tabIndex!==-1}const ss=new WeakSet;function ji(e){return t=>{t.key==="Enter"&&e(t)}}function Ns(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Ku=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=ji(()=>{if(ss.has(n))return;Ns(n,"down");const r=ji(()=>{Ns(n,"up")}),o=()=>Ns(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 Ci(e){return Lr(e)&&!ya()}function Gu(e,t,n={}){const[s,r,o]=xa(e,n),i=a=>{const l=a.currentTarget;if(!Ci(a))return;ss.add(l);const c=t(l,a),d=(p,b)=>{window.removeEventListener("pointerup",f),window.removeEventListener("pointercancel",m),ss.has(l)&&ss.delete(l),Ci(p)&&typeof c=="function"&&c(p,{success:b})},f=p=>{d(p,l===window||l===document||n.useGlobalTarget||ba(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),ga(a)&&(a.addEventListener("focus",c=>Ku(c,r)),!qu(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function va(e){return Ro(e)&&"ownerSVGElement"in e}function Hu(e){return va(e)&&e.tagName==="svg"}const Te=e=>!!(e&&e.getVelocity),Yu=[...fa,ge,xt],Ju=e=>Yu.find(da(e)),Fr=h.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Pi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Zu(...e){return t=>{let n=!1;const s=e.map(r=>{const o=Pi(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():Pi(e[r],null)}}}}function Qu(...e){return qe.useCallback(Zu(...e),e)}class ed extends qe.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const s=n.offsetParent,r=ga(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 td({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(Fr),l=Qu(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(`
|
|
3
3
|
[data-motion-pop-id="${r}"] {
|
|
4
4
|
position: absolute !important;
|
|
5
5
|
width: ${c}px !important;
|
|
6
6
|
height: ${d}px !important;
|
|
7
|
-
${
|
|
7
|
+
${b}px !important;
|
|
8
8
|
top: ${f}px !important;
|
|
9
9
|
}
|
|
10
|
-
`),()=>{S.contains(b)&&S.removeChild(b)}},[t]),u.jsx(Qu,{isPresent:t,childRef:o,sizeRef:i,children:_e.cloneElement(e,{ref:l})})}const td=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const c=gr(nd),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 x of c.values())if(!x)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,x)=>c.set(x,!1))},[n]),_e.useEffect(()=>{!n&&!c.size&&s&&s()},[n]),i==="popLayout"&&(e=u.jsx(ed,{isPresent:n,anchorX:a,root:l,children:e})),u.jsx(ps.Provider,{value:m,children:e})};function nd(){return new Map}function ba(e=!0){const t=h.useContext(ps);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 Qn=e=>e.key||"";function Ci(e){const t=[];return h.Children.forEach(e,n=>{h.isValidElement(n)&&t.push(n)}),t}const sd=({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]=ba(i),f=h.useMemo(()=>Ci(e),[e]),m=i&&!c?[]:f.map(Qn),p=h.useRef(!0),x=h.useRef(f),b=gr(()=>new Map),[S,v]=h.useState(f),[M,E]=h.useState(f);Eo(()=>{p.current=!1,x.current=f;for(let O=0;O<M.length;O++){const k=Qn(M[O]);m.includes(k)?b.delete(k):b.get(k)!==!0&&b.set(k,!1)}},[M,m.length,m.join("-")]);const L=[];if(f!==S){let O=[...f];for(let k=0;k<M.length;k++){const P=M[k],V=Qn(P);m.includes(V)||(O.splice(k,0,P),L.push(P))}return o==="wait"&&L.length&&(O=L),E(Ci(O)),v(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(pr);return u.jsx(u.Fragment,{children:M.map(O=>{const k=Qn(O),P=i&&!c?!1:f===M||m.includes(k),V=()=>{if(b.has(k))b.set(k,!0);else return;let A=!0;b.forEach(N=>{N||(A=!1)}),A&&(D?.(),E(x.current),i&&d?.(),s&&s())};return u.jsx(td,{isPresent:P,initial:!p.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:o,root:l,onExitComplete:P?void 0:V,anchorX:a,children:O},k)})})},Br=h.createContext({strict:!1}),Pi={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"]},Zt={};for(const e in Pi)Zt[e]={isEnabled:t=>Pi[e].some(n=>!!t[n])};function rr(e){for(const t in e)Zt[t]={...Zt[t],...e[t]}}function rd({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,rr(i)}return h.useEffect(()=>{Ds(t)&&t().then(({renderer:o,...i})=>{rr(i),r.current=o,s(!0)})},[]),u.jsx(Br.Provider,{value:{renderer:r.current,strict:n},children:e})}function Ds(e){return typeof e=="function"}const id=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 fs(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||id.has(e)}let va=e=>!fs(e);function od(e){typeof e=="function"&&(va=t=>t.startsWith("on")?!fs(t):e(t))}try{od(require("@emotion/is-prop-valid").default)}catch{}function ad(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(va(r)||n===!0&&fs(r)||!t&&!fs(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const gs=h.createContext({});function ys(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Rn(e){return typeof e=="string"||Array.isArray(e)}const Ur=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],zr=["initial",...Ur];function xs(e){return ys(e.animate)||zr.some(t=>Rn(e[t]))}function wa(e){return!!(xs(e)||e.variants)}function ld(e,t){if(xs(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Rn(n)?n:void 0,animate:Rn(s)?s:void 0}}return e.inherit!==!1?t:{}}function cd(e){const{initial:t,animate:n}=ld(e,h.useContext(gs));return h.useMemo(()=>({initial:t,animate:n}),[Ai(t),Ai(n)])}function Ai(e){return Array.isArray(e)?e.join(" "):e}const Vn={};function ud(e){for(const t in e)Vn[t]=e[t],Cr(t)&&(Vn[t].isCSSVariable=!0)}function Sa(e,{layout:t,layoutId:n}){return nn.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Vn[e]||e==="opacity")}const dd={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},fd=tn.length;function hd(e,t,n){let s="",r=!0;for(let o=0;o<fd;o++){const i=tn[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=ha(a,Or[i]);if(!l){r=!1;const d=dd[i]||i;s+=`${d}(${c}) `}n&&(t[i]=c)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function _r(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(nn.has(l)){i=!0;continue}else if(Cr(l)){r[l]=c;continue}else{const d=ha(c,Or[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=hd(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 Xr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ta(e,t,n){for(const s in t)!Te(t[s])&&!Sa(s,n)&&(e[s]=t[s])}function md({transformTemplate:e},t){return h.useMemo(()=>{const n=Xr();return _r(n,t,e),Object.assign({},n.vars,n.style)},[t])}function pd(e,t){const n=e.style||{},s={};return Ta(s,n,e),Object.assign(s,md(e,t)),s}function gd(e,t){const n={},s=pd(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 yd={offset:"stroke-dashoffset",array:"stroke-dasharray"},xd={offset:"strokeDashoffset",array:"strokeDasharray"};function bd(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?yd:xd;e[o.offset]=U.transform(-s);const i=U.transform(t),a=U.transform(n);e[o.array]=`${i} ${a}`}function ja(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,c,d){if(_r(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&&bd(f,r,o,i,!1)}const Ca=()=>({...Xr(),attrs:{}}),Pa=e=>typeof e=="string"&&e.toLowerCase()==="svg";function vd(e,t,n,s){const r=h.useMemo(()=>{const o=Ca();return ja(o,t,Pa(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Ta(o,e.style,e),r.style={...o,...r.style}}return r}const wd=["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 Wr(e){return typeof e!="string"||e.includes("-")?!1:!!(wd.indexOf(e)>-1||/[A-Z]/u.test(e))}function Sd(e,t,n,{latestValues:s},r,o=!1){const a=(Wr(e)?vd:gd)(t,s,r,e),l=ad(t,typeof e=="string",o),c=e!==h.Fragment?{...l,...a,ref:n}:{},{children:d}=t,f=h.useMemo(()=>Te(d)?d.get():d,[d]);return h.createElement(e,{...c,children:f})}function Ei(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function qr(e,t,n,s){if(typeof t=="function"){const[r,o]=Ei(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]=Ei(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function os(e){return Te(e)?e.get():e}function Td({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:jd(n,s,r,e),renderState:t()}}function jd(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=os(o[m]);let{initial:i,animate:a}=e;const l=xs(e),c=wa(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"&&!ys(f)){const m=Array.isArray(f)?f:[f];for(let p=0;p<m.length;p++){const x=qr(e,m[p]);if(x){const{transitionEnd:b,transition:S,...v}=x;for(const M in v){let E=v[M];if(Array.isArray(E)){const L=d?E.length-1:0;E=E[L]}E!==null&&(r[M]=E)}for(const M in b)r[M]=b[M]}}}return r}const Aa=e=>(t,n)=>{const s=h.useContext(gs),r=h.useContext(ps),o=()=>Td(e,t,s,r);return n?o():gr(o)};function Kr(e,t,n){const{style:s}=e,r={};for(const o in s)(Te(s[o])||t.style&&Te(t.style[o])||Sa(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const Cd=Aa({scrapeMotionValuesFromProps:Kr,createRenderState:Xr});function Ea(e,t,n){const s=Kr(e,t,n);for(const r in e)if(Te(e[r])||Te(t[r])){const o=tn.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const Pd=Aa({scrapeMotionValuesFromProps:Ea,createRenderState:Ca}),Ad=Symbol.for("motionComponentSymbol");function Wt(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function Ed(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):Wt(n)&&(n.current=s))},[t])}const Gr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Md="framerAppearId",Ma="data-"+Gr(Md),ka=h.createContext({});function kd(e,t,n,s,r){const{visualElement:o}=h.useContext(gs),i=h.useContext(Br),a=h.useContext(ps),l=h.useContext(Fr).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(ka);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&Nd(c.current,n,r,f);const m=h.useRef(!1);h.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Ma],x=h.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return Eo(()=>{d&&(m.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),d.scheduleRenderMicrotask(),x.current&&d.animationState&&d.animationState.animateChanges())}),h.useEffect(()=>{d&&(!x.current&&d.animationState&&d.animationState.animateChanges(),x.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(p)}),x.current=!1),d.enteringChildren=void 0)}),d}function Nd(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:Na(e.parent)),e.projection.setOptions({layoutId:r,layout:o,alwaysMeasureLayout:!!i||a&&Wt(a),visualElement:e,animationType:typeof o=="string"?o:"both",initialPromotionConfig:s,crossfade:d,layoutScroll:l,layoutRoot:c})}function Na(e){if(e)return e.options.allowProjection!==!1?e.projection:Na(e.parent)}function as(e,{forwardMotionProps:t=!1}={},n,s){n&&rr(n);const r=Wr(e)?Pd:Cd;function o(a,l){let c;const d={...h.useContext(Fr),...a,layoutId:Dd(a)},{isStatic:f}=d,m=cd(a),p=r(a,f);if(!f&&yr){Rd(d,n);const x=Vd(d);c=x.MeasureLayout,m.visualElement=kd(e,p,d,s,x.ProjectionNode)}return u.jsxs(gs.Provider,{value:m,children:[c&&m.visualElement?u.jsx(c,{visualElement:m.visualElement,...d}):null,Sd(e,a,Ed(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[Ad]=e,i}function Dd({layoutId:e}){const t=h.useContext(pr).id;return t&&e!==void 0?t+"-"+e:e}function Rd(e,t){const n=h.useContext(Br).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?Qt(!1,s,"lazy-strict-mode"):at(!1,s,"lazy-strict-mode")}}function Vd(e){const{drag:t,layout:n}=Zt;if(!t&&!n)return{};const s={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function Id(e,t){if(typeof Proxy>"u")return as;const n=new Map,s=(o,i)=>as(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Sr(!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,as(i,void 0,e,t)),n.get(i))})}function Da({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function Od({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function $d(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 Rs(e){return e===void 0||e===1}function ir({scale:e,scaleX:t,scaleY:n}){return!Rs(e)||!Rs(t)||!Rs(n)}function Mt(e){return ir(e)||Ra(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Ra(e){return Mi(e.x)||Mi(e.y)}function Mi(e){return e&&e!=="0%"}function hs(e,t,n){const s=e-n,r=t*s;return n+r}function ki(e,t,n,s,r){return r!==void 0&&(e=hs(e,r,s)),hs(e,n,s)+t}function or(e,t=0,n=1,s,r){e.min=ki(e.min,t,n,s,r),e.max=ki(e.max,t,n,s,r)}function Va(e,{x:t,y:n}){or(e.x,t.translate,t.scale,t.originPoint),or(e.y,n.translate,n.scale,n.originPoint)}const Ni=.999999999999,Di=1.0000000000001;function Ld(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&&Kt(e,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),i&&(t.x*=i.x.scale,t.y*=i.y.scale,Va(e,i)),s&&Mt(o.latestValues)&&Kt(e,o.latestValues))}t.x<Di&&t.x>Ni&&(t.x=1),t.y<Di&&t.y>Ni&&(t.y=1)}function qt(e,t){e.min=e.min+t,e.max=e.max+t}function Ri(e,t,n,s,r=.5){const o=he(e.min,e.max,r);or(e,t,n,o,s)}function Kt(e,t){Ri(e.x,t.x,t.scaleX,t.scale,t.originX),Ri(e.y,t.y,t.scaleY,t.scale,t.originY)}function Ia(e,t){return Da($d(e.getBoundingClientRect(),t))}function Fd(e,t,n){const s=Ia(e,n),{scroll:r}=t;return r&&(qt(s.x,r.offset.x),qt(s.y,r.offset.y)),s}const Vi=()=>({translate:0,scale:1,origin:0,originPoint:0}),Gt=()=>({x:Vi(),y:Vi()}),Ii=()=>({min:0,max:0}),pe=()=>({x:Ii(),y:Ii()}),ar={current:null},Oa={current:!1};function Bd(){if(Oa.current=!0,!!yr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>ar.current=e.matches;e.addEventListener("change",t),t()}else ar.current=!1}const Ud=new WeakMap;function zd(e,t,n){for(const s in t){const r=t[s],o=n[s];if(Te(r))e.addValue(s,r);else if(Te(o))e.addValue(s,Jt(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,Jt(i!==void 0?i:r,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Oi=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class _d{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=Vr,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=Me.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=xs(n),this.isVariantNode=wa(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&&Te(p)&&p.set(l[m])}}mount(t){this.current=t,Ud.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)),Oa.current||Bd(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ar.current,process.env.NODE_ENV!=="production"&&Sr(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(),xt(this.notifyUpdate),xt(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=nn.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 Zt){const n=Zt[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):pe()}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<Oi.length;s++){const r=Oi[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=zd(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=Jt(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"&&(Mo(s)||No(s))?s=parseFloat(s):!Yu(s)&&bt.test(n)&&(s=fa(t,n)),this.setBaseTarget(t,Te(s)?s.get():s)),Te(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=qr(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&&!Te(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 wr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){$r.render(this.render)}}class $a extends _d{constructor(){super(...arguments),this.KeyframeResolver=Lu}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;Te(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function La(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 Xd(e){return window.getComputedStyle(e)}class Wd extends $a{constructor(){super(...arguments),this.type="html",this.renderInstance=La}readValueFromInstance(t,n){if(nn.has(n))return this.projection?.isProjecting?Js(n):nu(t,n);{const s=Xd(t),r=(Cr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Ia(t,n)}build(t,n,s){_r(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Kr(t,n,s)}}const Fa=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 qd(e,t,n,s){La(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(Fa.has(r)?r:Gr(r),t.attrs[r])}class Kd extends $a{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=pe}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(nn.has(n)){const s=da(n);return s&&s.default||0}return n=Fa.has(n)?n:Gr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Ea(t,n,s)}build(t,n,s){ja(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){qd(t,n,s,r)}mount(t){this.isSVGTag=Pa(t.tagName),super.mount(t)}}const Ba=(e,t)=>Wr(e)?new Kd(t):new Wd(t,{allowProjection:e!==h.Fragment});function Yt(e,t,n){const s=e.getProps();return qr(s,t,n!==void 0?n:s.custom,e)}const lr=e=>Array.isArray(e);function Gd(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Jt(n))}function Hd(e){return lr(e)?e[e.length-1]||0:e}function Yd(e,t){const n=Yt(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Hd(o[i]);Gd(e,i,a)}}function Jd(e){return!!(Te(e)&&e.add)}function cr(e,t){const n=e.getValue("willChange");if(Jd(n))return n.add(t);if(!n&<.WillChange){const s=new lt.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Ua(e){return e.props[Ma]}const Zd=e=>e!==null;function Qd(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Zd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const ef={type:"spring",stiffness:500,damping:25,restSpeed:10},tf=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),nf={type:"keyframes",duration:.8},sf={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},rf=(e,{keyframes:t})=>t.length>2?nf:nn.has(e)?e.startsWith("scale")?tf(t[1]):ef:sf;function of({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 Hr=(e,t,n,s={},r,o)=>i=>{const a=Ir(s,e)||{},l=a.delay||s.delay||0;let{elapsed:c=0}=s;c=c-Xe(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};of(a)||Object.assign(d,rf(e,d)),d.duration&&(d.duration=Xe(d.duration)),d.repeatDelay&&(d.repeatDelay=Xe(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let f=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(nr(d),d.delay===0&&(f=!0)),(lt.instantAnimations||lt.skipAnimations)&&(f=!0,nr(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,f&&!o&&t.get()!==void 0){const m=Qd(d.keyframes,a);if(m!==void 0){le.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Rr(d):new Cu(d)};function af({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function za(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&&af(c,d))continue;const p={delay:n,...Ir(o||{},d)},x=f.get();if(x!==void 0&&!f.isAnimating&&!Array.isArray(m)&&m===x&&!p.velocity)continue;let b=!1;if(window.MotionHandoffAnimation){const v=Ua(e);if(v){const M=window.MotionHandoffAnimation(v,d,le);M!==null&&(p.startTime=M,b=!0)}}cr(e,d),f.start(Hr(d,f,m,e.shouldReduceMotion&&la.has(d)?{type:!1}:p,e,b));const S=f.animation;S&&l.push(S)}return i&&Promise.all(l).then(()=>{le.update(()=>{i&&Yd(e,i)})}),l}function _a(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 ur(e,t,n={}){const s=Yt(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(za(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:c=0,staggerChildren:d,staggerDirection:f}=r;return lf(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 lf(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(ur(l,t,{...i,delay:n+(typeof s=="function"?0:s)+_a(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function cf(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>ur(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=ur(e,t,n);else{const r=typeof t=="function"?Yt(e,t,n.custom):t;s=Promise.all(za(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function Xa(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 uf=zr.length;function Wa(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Wa(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<uf;n++){const s=zr[n],r=e.props[s];(Rn(r)||r===!1)&&(t[s]=r)}return t}const df=[...Ur].reverse(),ff=Ur.length;function hf(e){return t=>Promise.all(t.map(({animation:n,options:s})=>cf(e,n,s)))}function mf(e){let t=hf(e),n=$i(),s=!0;const r=l=>(c,d)=>{const f=Yt(e,d,l==="exit"?e.presenceContext?.custom:void 0);if(f){const{transition:m,transitionEnd:p,...x}=f;c={...c,...x,...p}}return c};function o(l){t=l(e)}function i(l){const{props:c}=e,d=Wa(e.parent)||{},f=[],m=new Set;let p={},x=1/0;for(let S=0;S<ff;S++){const v=df[S],M=n[v],E=c[v]!==void 0?c[v]:d[v],L=Rn(E),D=v===l?M.isActive:null;D===!1&&(x=S);let O=E===d[v]&&E!==c[v]&&L;if(O&&s&&e.manuallyAnimateOnMount&&(O=!1),M.protectedKeys={...p},!M.isActive&&D===null||!E&&!M.prevProp||ys(E)||typeof E=="boolean")continue;const k=pf(M.prevProp,E);let P=k||v===l&&M.isActive&&!O&&L||S>x&&L,V=!1;const A=Array.isArray(E)?E:[E];let N=A.reduce(r(v),{});D===!1&&(N={});const{prevResolvedValues:F={}}=M,$={...F,...N},B=K=>{P=!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 $){const oe=N[K],ye=F[K];if(p.hasOwnProperty(K))continue;let We=!1;lr(oe)&&lr(ye)?We=!Xa(oe,ye):We=oe!==ye,We?oe!=null?B(K):m.add(K):oe!==void 0&&m.has(K)?B(K):M.protectedKeys[K]=!0}M.prevProp=E,M.prevResolvedValues=N,M.isActive&&(p={...p,...N}),s&&e.blockInitialAnimation&&(P=!1);const X=O&&k;P&&(!X||V)&&f.push(...A.map(K=>{const oe={type:v};if(typeof K=="string"&&s&&!X&&e.manuallyAnimateOnMount&&e.parent){const{parent:ye}=e,We=Yt(ye,K);if(ye.enteringChildren&&We){const{delayChildren:wt}=We.transition||{};oe.delay=_a(ye.enteringChildren,e,wt)}}return{animation:K,options:oe}}))}if(m.size){const S={};if(typeof c.initial!="boolean"){const v=Yt(e,Array.isArray(c.initial)?c.initial[0]:c.initial);v&&v.transition&&(S.transition=v.transition)}m.forEach(v=>{const M=e.getBaseTarget(v),E=e.getValue(v);E&&(E.liveStyle=!0),S[v]=M??null}),f.push({animation:S})}let b=!!f.length;return s&&(c.initial===!1||c.initial===c.animate)&&!e.manuallyAnimateOnMount&&(b=!1),s=!1,b?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=$i()}}}function pf(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Xa(t,e):!1}function At(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function $i(){return{animate:At(!0),whileInView:At(),whileHover:At(),whileTap:At(),whileDrag:At(),whileFocus:At(),exit:At()}}class vt{constructor(t){this.isMounted=!1,this.node=t}update(){}}class gf extends vt{constructor(t){super(t),t.animationState||(t.animationState=mf(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();ys(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 yf=0;class xf extends vt{constructor(){super(...arguments),this.id=yf++}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 qa={animation:{Feature:gf},exit:{Feature:xf}};function In(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n)}function Fn(e){return{point:{x:e.pageX,y:e.pageY}}}const bf=e=>t=>Lr(t)&&e(t,Fn(t));function Pn(e,t,n,s){return In(e,t,bf(n),s)}const Ka=1e-4,vf=1-Ka,wf=1+Ka,Ga=.01,Sf=0-Ga,Tf=0+Ga;function Ae(e){return e.max-e.min}function jf(e,t,n){return Math.abs(e-t)<=n}function Li(e,t,n,s=.5){e.origin=s,e.originPoint=he(t.min,t.max,e.origin),e.scale=Ae(n)/Ae(t),e.translate=he(n.min,n.max,e.origin)-e.originPoint,(e.scale>=vf&&e.scale<=wf||isNaN(e.scale))&&(e.scale=1),(e.translate>=Sf&&e.translate<=Tf||isNaN(e.translate))&&(e.translate=0)}function An(e,t,n,s){Li(e.x,t.x,n.x,s?s.originX:void 0),Li(e.y,t.y,n.y,s?s.originY:void 0)}function Fi(e,t,n){e.min=n.min+t.min,e.max=e.min+Ae(t)}function Cf(e,t,n){Fi(e.x,t.x,n.x),Fi(e.y,t.y,n.y)}function Bi(e,t,n){e.min=t.min-n.min,e.max=e.min+Ae(t)}function En(e,t,n){Bi(e.x,t.x,n.x),Bi(e.y,t.y,n.y)}function Ie(e){return[e("x"),e("y")]}const Ha=({current:e})=>e?e.ownerDocument.defaultView:null,Ui=(e,t)=>Math.abs(e-t);function Pf(e,t){const n=Ui(e.x,t.x),s=Ui(e.y,t.y);return Math.sqrt(n**2+s**2)}class Ya{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=Is(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,x=Pf(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!x)return;const{point:b}=m,{timestamp:S}=we;this.history.push({...b,timestamp:S});const{onStart:v,onMove:M}=this.handlers;p||(v&&v(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),M&&M(this.lastMoveEvent,m)},this.handlePointerMove=(m,p)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=Vs(p,this.transformPagePoint),le.update(this.updatePoint,!0)},this.handlePointerUp=(m,p)=>{this.end();const{onEnd:x,onSessionEnd:b,resumeAnimation:S}=this.handlers;if(this.dragSnapToOrigin&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const v=Is(m.type==="pointercancel"?this.lastMoveEventInfo:Vs(p,this.transformPagePoint),this.history);this.startEvent&&x&&x(m,v),b&&b(m,v)},!Lr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=Fn(t),l=Vs(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=we;this.history=[{...c,timestamp:d}];const{onSessionStart:f}=n;f&&f(t,Is(l,this.history)),this.removeListeners=On(Pn(this.contextWindow,"pointermove",this.handlePointerMove),Pn(this.contextWindow,"pointerup",this.handlePointerUp),Pn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),xt(this.updatePoint)}}function Vs(e,t){return t?{point:t(e.point)}:e}function zi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Is({point:e},t){return{point:e,delta:zi(e,Ja(t)),offset:zi(e,Af(t)),velocity:Ef(t,.1)}}function Af(e){return e[0]}function Ja(e){return e[e.length-1]}function Ef(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Ja(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Xe(t)));)n--;if(!s)return{x:0,y:0};const o=$e(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 Mf(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 _i(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 kf(e,{top:t,left:n,bottom:s,right:r}){return{x:_i(e.x,n,r),y:_i(e.y,t,s)}}function Xi(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 Nf(e,t){return{x:Xi(e.x,t.x),y:Xi(e.y,t.y)}}function Df(e,t){let n=.5;const s=Ae(e),r=Ae(t);return r>s?n=kn(t.min,t.max-s,e.min):s>r&&(n=kn(e.min,e.max-r,t.min)),ot(0,1,n)}function Rf(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 dr=.35;function Vf(e=dr){return e===!1?e=0:e===!0&&(e=dr),{x:Wi(e,"left","right"),y:Wi(e,"top","bottom")}}function Wi(e,t,n){return{min:qi(e,t),max:qi(e,n)}}function qi(e,t){return typeof e=="number"?e:e[t]||0}const If=new WeakMap;class Of{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=pe(),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(Fn(f).point)},i=(f,m)=>{const{drag:p,dragPropagation:x,onDragStart:b}=this.getProps();if(p&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=zu(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),Ie(v=>{let M=this.getAxisMotionValue(v).get()||0;if(et.test(M)){const{projection:E}=this.visualElement;if(E&&E.layout){const L=E.layout.layoutBox[v];L&&(M=Ae(L)*(parseFloat(M)/100))}}this.originPoint[v]=M}),b&&le.postRender(()=>b(f,m)),cr(this.visualElement,"transform");const{animationState:S}=this.visualElement;S&&S.setActive("whileDrag",!0)},a=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:x,onDirectionLock:b,onDrag:S}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:v}=m;if(x&&this.currentDirection===null){this.currentDirection=$f(v),this.currentDirection!==null&&b&&b(this.currentDirection);return}this.updateAxis("x",m.point,v),this.updateAxis("y",m.point,v),this.visualElement.render(),S&&S(f,m)},l=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m,this.stop(f,m),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Ie(f=>this.getAnimationState(f)==="paused"&&this.getAxisMotionValue(f).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new Ya(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Ha(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||!es(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=Mf(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&&Wt(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=kf(s.layoutBox,t):this.constraints=!1,this.elastic=Vf(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Ie(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Rf(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Wt(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=Fd(s,r.root,this.visualElement.getTransformPagePoint());let i=Nf(r.layout.layoutBox,o);if(n){const a=n(Od(i));this.hasMutatedConstraints=!!a,a&&(i=Da(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Ie(d=>{if(!es(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,x={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...f};return this.startAxisValueAnimation(d,x)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return cr(this.visualElement,t),s.start(Hr(t,s,0,n,this.visualElement,!1))}stopAnimation(){Ie(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Ie(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){Ie(n=>{const{drag:s}=this.getProps();if(!es(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(!Wt(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Ie(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const l=a.get();r[i]=Df({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(),Ie(i=>{if(!es(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;If.set(this.visualElement,this);const t=this.visualElement.current,n=Pn(t,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),s=()=>{const{dragConstraints:l}=this.getProps();Wt(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=In(window,"resize",()=>this.scalePositionWithinConstraints()),a=r.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Ie(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=dr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function es(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function $f(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Lf extends vt{constructor(t){super(t),this.removeGroupControls=Le,this.removeListeners=Le,this.controls=new Of(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Le}unmount(){this.removeGroupControls(),this.removeListeners()}}const Ki=e=>(t,n)=>{e&&le.postRender(()=>e(t,n))};class Ff extends vt{constructor(){super(...arguments),this.removePointerDownListener=Le}onPointerDown(t){this.session=new Ya(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ha(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ki(t),onStart:Ki(n),onMove:s,onEnd:(o,i)=>{delete this.session,r&&le.postRender(()=>r(o,i))}}}mount(){this.removePointerDownListener=Pn(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 ls={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Gi(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const wn={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(U.test(e))e=parseFloat(e);else return e;const n=Gi(e,t.target.x),s=Gi(e,t.target.y);return`${n}% ${s}%`}},Bf={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=bt.parse(e);if(r.length>5)return s;const o=bt.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 Os=!1;class Uf extends h.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;ud(zf),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Os&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),ls.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Os=!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(),$r.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Os=!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 Za(e){const[t,n]=ba(),s=h.useContext(pr);return u.jsx(Uf,{...e,layoutGroup:s,switchLayoutGroup:h.useContext(ka),isPresent:t,safeToRemove:n})}const zf={borderRadius:{...wn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:wn,borderTopRightRadius:wn,borderBottomLeftRadius:wn,borderBottomRightRadius:wn,boxShadow:Bf};function _f(e,t,n){const s=Te(e)?e:Jt(e);return s.start(Hr("",s,t,n)),s.animation}const Xf=(e,t)=>e.depth-t.depth;class Wf{constructor(){this.children=[],this.isDirty=!1}add(t){xr(this.children,t),this.isDirty=!0}remove(t){br(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Xf),this.isDirty=!1,this.children.forEach(t)}}function qf(e,t){const n=Me.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(xt(s),e(o-t))};return le.setup(s,!0),()=>xt(s)}const Qa=["TopLeft","TopRight","BottomLeft","BottomRight"],Kf=Qa.length,Hi=e=>typeof e=="string"?parseFloat(e):e,Yi=e=>typeof e=="number"||U.test(e);function Gf(e,t,n,s,r,o){r?(e.opacity=he(0,n.opacity??1,Hf(s)),e.opacityExit=he(t.opacity??1,0,Yf(s))):o&&(e.opacity=he(t.opacity??1,n.opacity??1,s));for(let i=0;i<Kf;i++){const a=`border${Qa[i]}Radius`;let l=Ji(t,a),c=Ji(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Yi(l)===Yi(c)?(e[a]=Math.max(he(Hi(l),Hi(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 Ji(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Hf=el(0,.5,Fo),Yf=el(.5,.95,Le);function el(e,t,n){return s=>s<e?0:s>t?1:n(kn(e,t,s))}function Zi(e,t){e.min=t.min,e.max=t.max}function Ve(e,t){Zi(e.x,t.x),Zi(e.y,t.y)}function Qi(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function eo(e,t,n,s,r){return e-=t,e=hs(e,1/n,s),r!==void 0&&(e=hs(e,1/r,s)),e}function Jf(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=eo(e.min,t,n,a,r),e.max=eo(e.max,t,n,a,r)}function to(e,t,[n,s,r],o,i){Jf(e,t[n],t[s],t[r],t.scale,o,i)}const Zf=["x","scaleX","originX"],Qf=["y","scaleY","originY"];function no(e,t,n,s){to(e.x,t,Zf,n?n.x:void 0,s?s.x:void 0),to(e.y,t,Qf,n?n.y:void 0,s?s.y:void 0)}function so(e){return e.translate===0&&e.scale===1}function tl(e){return so(e.x)&&so(e.y)}function ro(e,t){return e.min===t.min&&e.max===t.max}function eh(e,t){return ro(e.x,t.x)&&ro(e.y,t.y)}function io(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function nl(e,t){return io(e.x,t.x)&&io(e.y,t.y)}function oo(e){return Ae(e.x)/Ae(e.y)}function ao(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class th{constructor(){this.members=[]}add(t){xr(this.members,t),t.scheduleRender()}remove(t){if(br(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 nh(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:x}=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) `),x&&(s+=`skewY(${x}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 $s=["","X","Y","Z"],sh=1e3;let rh=0;function Ls(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function sl(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=Ua(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&&sl(s)}function rl({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=rh++,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(ah),this.nodes.forEach(dh),this.nodes.forEach(fh),this.nodes.forEach(lh)},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 Wf)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new wr),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=xa(i)&&!Gu(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=qf(m,250),ls.hasAnimatedSinceResize&&(ls.hasAnimatedSinceResize=!1,this.nodes.forEach(uo)))})}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 x=this.options.transition||c.getDefaultTransition()||yh,{onLayoutAnimationStart:b,onLayoutAnimationComplete:S}=c.getProps(),v=!this.targetLayout||!nl(this.targetLayout,p),M=!f&&m;if(this.options.layoutRoot||this.resumeFrom||M||f&&(v||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const E={...Ir(x,"layout"),onPlay:b,onComplete:S};(c.shouldReduceMotion||this.options.layoutRoot)&&(E.delay=0,E.type=!1),this.startAnimation(E),this.setAnimationOrigin(d,M)}else f||uo(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(),xt(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(hh),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&&sl(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(lo);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(co);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(uh),this.nodes.forEach(ih),this.nodes.forEach(oh)):this.nodes.forEach(co),this.clearAllSnapshots();const a=Me.now();we.delta=ot(0,1e3/60,a-we.timestamp),we.timestamp=a,we.isProcessing=!0,Ps.update.process(we),Ps.preRender.process(we),Ps.render.process(we),we.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,$r.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(ch),this.sharedNodes.forEach(mh)}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&&!Ae(this.snapshot.measuredBox.x)&&!Ae(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=pe(),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&&!tl(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;i&&this.instance&&(a||Mt(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)),xh(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return pe();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(bh))){const{scroll:c}=this.root;c&&(qt(a.x,c.offset.x),qt(a.y,c.offset.y))}return a}removeElementScroll(i){const a=pe();if(Ve(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&&Ve(a,i),qt(a.x,d.offset.x),qt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=pe();Ve(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&&Kt(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Mt(d.latestValues)&&Kt(l,d.latestValues)}return Mt(this.latestValues)&&Kt(l,this.latestValues),l}removeTransform(i){const a=pe();Ve(a,i);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Mt(c.latestValues))continue;ir(c.latestValues)&&c.updateSnapshot();const d=pe(),f=c.measurePageBox();Ve(d,f),no(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return Mt(this.latestValues)&&no(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!==we.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=we.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pe(),this.relativeTargetOrigin=pe(),En(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Ve(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=pe(),this.targetWithTransforms=pe()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Cf(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ve(this.target,this.layout.layoutBox),Va(this.target,this.targetDelta)):Ve(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=pe(),this.relativeTargetOrigin=pe(),En(this.relativeTargetOrigin,this.target,m.target),Ve(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ir(this.parent.latestValues)||Ra(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===we.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;Ve(this.layoutCorrected,this.layout.layoutBox);const f=this.treeScale.x,m=this.treeScale.y;Ld(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=pe());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Qi(this.prevProjectionDelta.x,this.projectionDelta.x),Qi(this.prevProjectionDelta.y,this.projectionDelta.y)),An(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==f||this.treeScale.y!==m||!ao(this.projectionDelta.x,this.prevProjectionDelta.x)||!ao(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=Gt(),this.projectionDelta=Gt(),this.projectionDeltaWithTransform=Gt()}setAnimationOrigin(i,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},f=Gt();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=pe(),p=l?l.source:void 0,x=this.layout?this.layout.source:void 0,b=p!==x,S=this.getStack(),v=!S||S.members.length<=1,M=!!(b&&!v&&this.options.crossfade===!0&&!this.path.some(gh));this.animationProgress=0;let E;this.mixTargetDelta=L=>{const D=L/1e3;fo(f.x,i.x,D),fo(f.y,i.y,D),this.setTargetDelta(f),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(En(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),ph(this.relativeTarget,this.relativeTargetOrigin,m,D),E&&eh(this.relativeTarget,E)&&(this.isProjectionDirty=!1),E||(E=pe()),Ve(E,this.relativeTarget)),b&&(this.animationValues=d,Gf(d,c,this.latestValues,D,M,v)),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&&(xt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=le.update(()=>{ls.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Jt(0)),this.currentAnimation=_f(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(sh),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&&il(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||pe();const f=Ae(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+f;const m=Ae(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}Ve(a,l),Kt(a,d),An(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new th),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&&Ls("z",i,c,this.animationValues);for(let d=0;d<$s.length;d++)Ls(`rotate${$s[d]}`,i,c,this.animationValues),Ls(`skew${$s[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=os(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=os(a?.pointerEvents)||""),this.hasProjected&&!Mt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let f=nh(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 x in Vn){if(d[x]===void 0)continue;const{correct:b,applyTo:S,isCSSVariable:v}=Vn[x],M=f==="none"?d[x]:b(d[x],c);if(S){const E=S.length;for(let L=0;L<E;L++)i[S[L]]=M}else v?this.options.visualElement.renderState.vars[x]=M:i[x]=M}this.options.layoutId&&(i.pointerEvents=c===this?os(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(lo),this.root.sharedNodes.clear()}}}function ih(e){e.updateLayout()}function oh(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"?Ie(d=>{const f=o?t.measuredBox[d]:t.layoutBox[d],m=Ae(f);f.min=n[d].min,f.max=f.min+m}):il(r,t.layoutBox,n)&&Ie(d=>{const f=o?t.measuredBox[d]:t.layoutBox[d],m=Ae(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=Gt();An(i,n,t.layoutBox);const a=Gt();o?An(a,e.applyTransform(s,!0),t.measuredBox):An(a,n,t.layoutBox);const l=!tl(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=pe();En(p,t.layoutBox,f.layoutBox);const x=pe();En(x,n,m.layoutBox),nl(p,x)||(c=!0),d.options.layoutRoot&&(e.relativeTarget=x,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 ah(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 lh(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function ch(e){e.clearSnapshot()}function lo(e){e.clearMeasurements()}function co(e){e.isLayoutDirty=!1}function uh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function uo(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function dh(e){e.resolveTargetDelta()}function fh(e){e.calcProjection()}function hh(e){e.resetSkewAndRotation()}function mh(e){e.removeLeadSnapshot()}function fo(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 ho(e,t,n,s){e.min=he(t.min,n.min,s),e.max=he(t.max,n.max,s)}function ph(e,t,n,s){ho(e.x,t.x,n.x,s),ho(e.y,t.y,n.y,s)}function gh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const yh={duration:.45,ease:[.4,0,.1,1]},mo=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),po=mo("applewebkit/")&&!mo("chrome/")?Math.round:Le;function go(e){e.min=po(e.min),e.max=po(e.max)}function xh(e){go(e.x),go(e.y)}function il(e,t,n){return e==="position"||e==="preserve-aspect"&&!jf(oo(t),oo(n),.2)}function bh(e){return e!==e.root&&e.scroll?.wasRoot}const vh=rl({attachResizeListener:(e,t)=>In(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Fs={current:void 0},ol=rl({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Fs.current){const e=new vh({});e.mount(window),e.setOptions({layoutScroll:!0}),Fs.current=e}return Fs.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),wh={pan:{Feature:Ff},drag:{Feature:Lf,ProjectionNode:ol,MeasureLayout:Za}};function yo(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,Fn(t)))}class Sh extends vt{mount(){const{current:t}=this.node;t&&(this.unmount=_u(t,(n,s)=>(yo(this.node,s,"Start"),r=>yo(this.node,r,"End"))))}unmount(){}}class Th extends vt{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=On(In(this.node.current,"focus",()=>this.onFocus()),In(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function xo(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,Fn(t)))}class jh extends vt{mount(){const{current:t}=this.node;t&&(this.unmount=Ku(t,(n,s)=>(xo(this.node,s,"Start"),(r,{success:o})=>xo(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const fr=new WeakMap,Bs=new WeakMap,Ch=e=>{const t=fr.get(e.target);t&&t(e)},Ph=e=>{e.forEach(Ch)};function Ah({root:e,...t}){const n=e||document;Bs.has(n)||Bs.set(n,{});const s=Bs.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(Ph,{root:e,...t})),s[r]}function Eh(e,t,n){const s=Ah(t);return fr.set(e,n),s.observe(e),()=>{fr.delete(e),s.unobserve(e)}}const Mh={some:0,all:1};class kh extends vt{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:Mh[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 Eh(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(Nh(t,n))&&this.startObserver()}unmount(){}}function Nh({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const al={inView:{Feature:kh},tap:{Feature:jh},focus:{Feature:Th},hover:{Feature:Sh}},Dh={layout:{ProjectionNode:ol,MeasureLayout:Za}},Rh={...qa,...al,...wh,...Dh},Vh=Id(Rh,Ba),Ih={renderer:Ba,...qa,...al};function Yr(e,t){return as(e,t)}const Oh=Yr("button"),ts=Yr("div"),$h=Yr("p");function Lh({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(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[u.jsx(te.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),u.jsx(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:u.jsx(te.X,{className:"h-3 w-3"})})]})]})})}function Fh({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(te.ChevronDown,{className:"h-3 w-3"}):u.jsx(te.ChevronRight,{className:"h-3 w-3"})}),n?u.jsx(te.X,{className:"h-3 w-3"}):s?u.jsx(te.Zap,{className:"h-3 w-3"}):u.jsx(te.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 Bh({...e}){return u.jsx(hr.Root,{"data-slot":"collapsible",...e})}function Uh({...e}){return u.jsx(hr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function zh({...e}){return u.jsx(hr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const _h=h.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Jr=h.memo(({className:e,...t})=>typeof window>"u"?null:u.jsx(h.Suspense,{fallback:null,children:u.jsx(_h,{className:se("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Jr.displayName="Response";const Xh=Object.freeze(Object.defineProperty({__proto__:null,Response:Jr},Symbol.toStringTag,{value:"Module"})),Wh=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=Vh.create(t),i=h.useMemo(()=>(e?.length??0)*r,[e,r]);return u.jsx(o,{animate:{backgroundPosition:"0% center"},className:se("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})},qh=h.memo(Wh),ll=h.createContext(null),Kh=()=>{const e=h.useContext(ll);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Gh=1e3,Hh=1e3,cl=h.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,c]=ti.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,f]=ti.useControllableState({prop:o,defaultProp:0}),[m,p]=h.useState(!1),[x,b]=h.useState(null);h.useEffect(()=>{t?x===null&&b(Date.now()):x!==null&&(f(Math.ceil((Date.now()-x)/Hh)),b(null))},[t,x,f]),h.useEffect(()=>{if(s&&!t&&l&&!m){const v=setTimeout(()=>{c(!1),p(!0)},Gh);return()=>clearTimeout(v)}},[t,l,s,c,m]);const S=v=>{c(v)};return u.jsx(ll.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:c,duration:d},children:u.jsx(Bh,{className:se("not-prose mb-4",e),onOpenChange:S,open:l,...a,children:i})})}),Yh=(e,t)=>e||t===0?u.jsx(qh,{duration:1,children:"Thinking..."}):t===void 0?u.jsx("p",{children:"Thought for a few seconds"}):u.jsxs("p",{children:["Thought for ",t," seconds"]}),ul=h.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Kh();return u.jsx(Uh,{className:se("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(te.BrainIcon,{className:"size-4"}),Yh(s,o),u.jsx(te.ChevronDownIcon,{className:se("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),dl=h.memo(({className:e,children:t,...n})=>u.jsx(zh,{className:se("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(Jr,{className:"grid gap-2",children:t})}));cl.displayName="Reasoning";ul.displayName="ReasoningTrigger";dl.displayName="ReasoningContent";function bo(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function Jh({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=bo(s.domain);return u.jsxs(mt,{children:[u.jsx(pt,{asChild:!0,children:u.jsxs("button",{className:se("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(gt,{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:se("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:bo(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 Zh({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 S=c.current;let v,M=!1;const E=new WeakSet,L=()=>{if(!c.current||M)return;M=!0;const O=c.current,k=/\[(\d+)\]/g,P=document.createTreeWalker(O,NodeFilter.SHOW_TEXT,null),V=[];let A;for(;A=P.nextNode();)if(A.nodeType===Node.TEXT_NODE&&!E.has(A)){const F=A,$=F.textContent||"";let B=F.parentElement,X=!1;for(;B&&B!==O;){if(B.tagName==="A"||B.tagName==="CODE"||B.tagName==="PRE"){X=!0;break}B=B.parentElement}if(!X){const K=Array.from($.matchAll(k)).filter(oe=>{if(!oe[1])return!1;const ye=parseInt(oe[1],10);return n.has(ye)});K.length>0&&V.push({node:F,matches:K})}}if(V.length===0){M=!1;return}const N=[];V.forEach(({node:F,matches:$})=>{E.add(F);const B=F.textContent||"",X=document.createDocumentFragment();let G=0;$.forEach(K=>{if(!K[1])return;K.index!==void 0&&K.index>G&&X.appendChild(document.createTextNode(B.slice(G,K.index)));const oe=document.createElement("span");oe.className="inline-flex items-center citation-button-container";const ye=parseInt(K[1],10);oe.setAttribute("data-citation",K[1]),X.appendChild(oe),N.push({element:oe,citationNum:ye}),G=(K.index||0)+K[0].length}),G<B.length&&X.appendChild(document.createTextNode(B.slice(G))),F.parentNode&&F.parentNode.replaceChild(X,F)}),N.length>0&&f(F=>{const $=new Set(F.map(G=>G.element)),B=F.filter(G=>G.element.isConnected),X=N.filter(G=>!$.has(G.element));return[...B,...X]}),M=!1},D=new MutationObserver(()=>{clearTimeout(v),v=setTimeout(L,100)});return D.observe(S,{childList:!0,subtree:!0,characterData:!0}),v=setTimeout(L,200),()=>{D.disconnect(),clearTimeout(v)}},[e,t,n,a]);const m=s&&s.length>0||n&&n.size>0||r;function p(S){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(S)}&sz=16`}function x(S){try{return new URL(S).hostname.replace(/^www\./,"")}catch{return S}}const b=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((S,v)=>{const M=S.title||S.baseUrl,E=x(S.url),L=p(E);return u.jsxs("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",className:se("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:L,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:D=>{const O=D.target;O.style.display="none"}}),u.jsx("span",{className:"leading-none",children:M})]},`group-${v}`)}):Array.from(n.entries()).sort(([S],[v])=>S-v).map(([S,v])=>{const M=x(v),E=p(M);return u.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:se("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:L=>{const D=L.target;D.style.display="none"}}),u.jsx("span",{className:"leading-none",children:v})]},S)})})]}):null;return u.jsxs("div",{className:i,children:[u.jsx("div",{ref:c,children:u.jsx(o,{children:e})}),a&&d.filter(({element:S})=>S.isConnected).map(({element:S,citationNum:v},M)=>{if(!t.find(D=>D.number===v))return null;const L=Array.from(new Map(t.map(D=>{const O=D.url.replace(/\/+$/,""),k=s?.find(P=>P.url.replace(/\/+$/,"")===O);return[O,{number:D.number,url:D.url,domain:x(D.url),title:k?.title}]})).values());return Ml.createPortal(u.jsx(Jh,{sources:L,citationNumber:v},`citation-${v}-${S}`),S,`citation-${v}-${M}`)}),b]})}function sn({...e}){return u.jsx(Vt.Root,{"data-slot":"dialog",...e})}function Qh({...e}){return u.jsx(Vt.Portal,{"data-slot":"dialog-portal",...e})}function em({className:e,...t}){return u.jsx(Vt.Overlay,{"data-slot":"dialog-overlay",className:se("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 rn({className:e,children:t,showCloseButton:n=!0,...s}){return u.jsxs(Qh,{"data-slot":"dialog-portal",children:[u.jsx(em,{}),u.jsxs(Vt.Content,{"data-slot":"dialog-content",className:se("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(Vt.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(te.XIcon,{}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function on({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-header",className:se("flex flex-col gap-2 text-center sm:text-left",e),...t})}function an({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-footer",className:se("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function ln({className:e,...t}){return u.jsx(Vt.Title,{"data-slot":"dialog-title",className:se("text-lg leading-none font-semibold",e),...t})}function cn({className:e,...t}){return u.jsx(Vt.Description,{"data-slot":"dialog-description",className:se("text-muted-foreground text-sm",e),...t})}function un({className:e,type:t,...n}){return u.jsx("input",{type:t,"data-slot":"input",className:se("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 tm({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(sn,{open:e,children:u.jsx(rn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:f,children:[u.jsxs(on,{children:[u.jsx(ln,{children:t}),u.jsx(cn,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsxs("div",{className:"relative",children:[u.jsx(un,{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(te.EyeOff,{className:"h-4 w-4"}):u.jsx(te.Eye,{className:"h-4 w-4"})})]})}),u.jsxs(an,{children:[u.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:c,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:!o.trim()||c,children:c?"Submitting...":"Submit"})]})]})})})}function nm({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=b=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(b),m=b=>{i(b),b.trim()?l(f(b)):l(!0)},p=async b=>{if(b.preventDefault(),!o.trim()||!f(o)){l(!1);return}d(!0);try{r(o)}finally{d(!1)}},x=()=>{i(""),l(!0),r(null)};return u.jsx(sn,{open:e,children:u.jsx(rn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:p,children:[u.jsxs(on,{children:[u.jsxs(ln,{className:"flex items-center gap-2",children:[u.jsx(te.Mail,{className:"h-5 w-5"}),t]}),u.jsx(cn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(un,{type:"email",value:o,onChange:b=>m(b.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(an,{children:[u.jsx(je,{type:"button",variant:"ghost",onClick:x,disabled:c,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function sm({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=S=>{const v=S.replace(/\D/g,"");return v.length<=3?v:v.length<=6?`(${v.slice(0,3)}) ${v.slice(3)}`:`(${v.slice(0,3)}) ${v.slice(3,6)}-${v.slice(6,10)}`},m=S=>S.replace(/\D/g,"").length===10,p=S=>{const v=f(S);i(v),v.trim()?l(m(v)):l(!0)},x=async S=>{if(S.preventDefault(),!o.trim()||!m(o)){l(!1);return}d(!0);try{const v=o.replace(/\D/g,"");r(v)}finally{d(!1)}},b=()=>{i(""),l(!0),r(null)};return u.jsx(sn,{open:e,children:u.jsx(rn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:x,children:[u.jsxs(on,{children:[u.jsxs(ln,{className:"flex items-center gap-2",children:[u.jsx(te.Phone,{className:"h-5 w-5"}),t]}),u.jsx(cn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(un,{type:"tel",value:o,onChange:S=>p(S.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(an,{children:[u.jsx(je,{type:"button",variant:"ghost",onClick:b,disabled:c,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function rm({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 x=p.replace(/\D/g,"");a(x.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(sn,{open:e,children:u.jsx(rn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:f,children:[u.jsxs(on,{children:[u.jsxs(ln,{className:"flex items-center gap-2",children:[u.jsx(te.Shield,{className:"h-5 w-5"}),t]}),u.jsx(cn,{children:n})]}),u.jsxs("div",{className:"py-4",children:[u.jsx(un,{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(an,{children:[u.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:i.length!==r||l,children:l?"Submitting...":"Submit"})]})]})})})}function Us({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(sn,{open:e,children:u.jsx(rn,{showCloseButton:!1,children:u.jsxs("form",{onSubmit:d,children:[u.jsxs(on,{children:[u.jsxs(ln,{className:"flex items-center gap-2",children:[u.jsx(te.Lock,{className:"h-5 w-5"}),t]}),u.jsx(cn,{children:n})]}),u.jsx("div",{className:"py-4",children:u.jsx(un,{type:r,value:i,onChange:m=>a(m.target.value),placeholder:s,autoFocus:!0,disabled:l})}),u.jsxs(an,{children:[u.jsx(je,{type:"button",variant:"ghost",onClick:f,disabled:l,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function im({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,x]=h.useState(!1),b=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A)?null:"Please enter a valid email address",S=A=>A.replace(/\D/g,"").length===10?null:"Please enter a valid 10-digit phone number",v=(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,F)=>{let $=N,B=null;switch(F.type){case"phone":$=M(N),$.trim()&&(B=S($));break;case"email":N.trim()&&(B=b(N));break;case"pin":$=N.replace(/\D/g,"").slice(0,6),$.trim()&&(B=v($));break}!B&&F.validation&&$.trim()&&(B=F.validation($)),l(X=>({...X,[A]:$})),d(X=>({...X,[A]:B||""}))},L=()=>{const A={};let N=!0;return s.forEach(F=>{const $=a[F.name]||"";let B=null;if(F.required&&!$.trim())B=`${F.label} is required`;else if($.trim()){switch(F.type){case"email":B=b($);break;case"phone":B=S($);break;case"pin":B=v($);break}!B&&F.validation&&(B=F.validation($))}B&&(A[F.name]=B,N=!1)}),d(A),N},D=async A=>{if(A.preventDefault(),!!L()){x(!0);try{const N={};s.forEach(F=>{const $=a[F.name]?.trim();$&&(F.type==="phone"?N[F.name]=$.replace(/\D/g,""):N[F.name]=$)}),r(N)}finally{x(!1)}}},O=()=>{l({}),d({}),m({}),r(null)},k=A=>{m(N=>({...N,[A]:!N[A]}))},P=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(sn,{open:e,children:u.jsx(rn,{showCloseButton:!1,className:"max-w-md",children:u.jsxs("form",{onSubmit:D,children:[u.jsxs(on,{children:[u.jsx(ln,{children:t}),n&&u.jsx(cn,{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(un,{type:P(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(te.EyeOff,{className:"h-4 w-4"}):u.jsx(te.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(te.AlertCircle,{className:"h-3 w-3"}),c[A.name]]})]},A.name))}),u.jsxs(an,{children:[u.jsx(je,{type:"button",variant:"ghost",onClick:O,disabled:p,children:i}),u.jsx(je,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const fl=h.createContext(void 0);function hl(){const e=h.useContext(fl);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function ml({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(x=>{n(p),o.current=x}),[]),l=h.useCallback(p=>new Promise(x=>{r(p),i.current=x}),[]),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 x=s.fields.map(b=>({name:b.name,type:b.type==="text"?"text":b.type==="password"?"password":b.type==="email"?"email":b.type==="phone"?"phone":b.type==="pin"?"pin":b.type==="ssn"?"ssn":b.type==="creditCard"?"creditCard":"text",label:b.label,placeholder:b.placeholder,required:b.required!==!1,value:b.value}));return u.jsx(im,{isOpen:!0,title:s.title,description:s.description,fields:x,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(tm,{...p});case"email":return u.jsx(nm,{...p});case"phone":return u.jsx(sm,{...p});case"pin":return u.jsx(rm,{...p});case"ssn":return u.jsx(Us,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return u.jsx(Us,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return u.jsx(Us,{...p})}},m=h.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return u.jsxs(fl.Provider,{value:m,children:[e,f()]})}function om(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 am(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 vo(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 P=s[1],V=/\[(\d+)\]\s*(https?:\/\/[^\s\)]+)/g;let A;for(;(A=V.exec(P))!==null;)if(A[1]&&A[2]){const N=parseInt(A[1],10),F=A[2].replace(/[.,;:!?]+$/,""),$=F.replace(/\/+$/,"");if(a.has($)||a.set($,F),i.has($)||i.set($,[]),i.get($).push(N),!l.has($))l.set($,N);else{const B=l.get($);N<B&&l.set($,N)}}for(const[N,F]of i.entries()){const $=l.get(N);for(const B of F)B!==$&&c.set(B,$)}for(const[N,F]of l.entries()){const $=a.get(N)||N;r.set(F,$),o.push({number:F,url:$})}}let d,f=t;s&&s[0]&&(d=s[0],f=t.replace(n,""));const m=[];let p=0;const x=/```[\s\S]*?```|`[^`]+`/g;let b;for(;(b=x.exec(f))!==null;)b.index>p&&m.push({type:"text",content:f.slice(p,b.index),start:p,end:b.index}),m.push({type:"code",content:b[0],start:b.index,end:b.index+b[0].length}),p=b.index+b[0].length;p<f.length&&m.push({type:"text",content:f.slice(p),start:p,end:f.length});const S=m.map(P=>{if(P.type==="code")return P.content;let V=P.content;return V=V.replace(/\[(\d+)\]\((https?:\/\/[^\)]+)\)/g,(N,F,$)=>{const B=parseInt(F,10),X=$.replace(/\/+$/,""),G=c.get(B)||B;return l.has(X)||(l.set(X,G),r.has(G)||(r.set(G,$),o.push({number:G,url:$}))),`[${G}]`}),V=V.replace(/\[(\d+)\]/g,(N,F)=>{const $=parseInt(F,10);return`[${c.get($)||$}]`}),V}),v=[];for(const[P,V]of l.entries()){const A=a.get(P)||P,{baseUrl:N,anchor:F}=om(A),$=am(A);v.push({url:A,baseUrl:N,numbers:[V],anchor:F,title:$})}v.sort((P,V)=>(P.numbers[0]||0)-(V.numbers[0]||0));const M=new Map;let E=1;for(const P of v){const V=P.numbers[0];M.set(V,E),P.numbers=[E],E++}const L=new Map;for(const[P,V]of r.entries()){const A=M.get(P);A&&L.set(A,V)}const D=o.map(P=>{const V=M.get(P.number);return V?{number:V,url:P.url}:P}).filter(P=>M.has(P.number)),O=Array.from(M.entries()).sort((P,V)=>V[0]-P[0]);let k=S.join("");for(const[P,V]of O){const A=new RegExp(`\\[${P}\\](?!\\d)`,"g");k=k.replace(A,`[${V}]`)}return{processedText:k,citations:D.sort((P,V)=>P.number-V.number),citationMap:L,groupedCitations:v,referencesText:d}}function Mn(e){if(typeof e=="string")try{const t=JSON.parse(e);return Mn(t)}catch{return e}if(Array.isArray(e))return e.map(Mn);if(e&&typeof e=="object"){const t={};for(const[n,s]of Object.entries(e))t[n]=Mn(s);return t}return e}function zs(e){if(typeof e=="string"){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return Mn(t)}catch{}return{}}return e&&typeof e=="object"&&!Array.isArray(e)?Mn(e):{}}function lm({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:x="",agentId:b,agentName:S,tokenEndpoint:v="/api/arcten/token",apiBaseUrl:M="https://api.arcten.com",user:E,state:L,onStateChange:D,allowStateEdits:O=!0,sources:k,ragConfig:P,showCitations:V=!0,sensitiveParams:A,autoDetectSensitive:N=!1}){const F=M.replace(/\/+$/,""),{showSecureModal:$}=hl(),B=Po({apiBaseUrl:F,tokenEndpoint:v,user:E,tools:d,safeTools:f,toolMetadata:p,sensitiveParams:A,autoDetectSensitive:N,agentId:b,agentName:S,state:L,onStateChange:D,allowStateEdits:O,sources:k,ragConfig:P});h.useMemo(()=>P!==void 0?P:k&&k.length>0?{enabled:!0,organizationId:k[0],autoExecute:!0,filters:void 0}:{enabled:!1},[k,P]);const[X,G]=h.useState(c),[K,oe]=h.useState(i),[ye,We]=h.useState(600),[wt,tt]=h.useState(!1),[H,It]=h.useState(!1),[Ee,St]=h.useState(!1),[Ce,Fe]=h.useState({x:100,y:100}),[Ot,ae]=h.useState(!1),[dn,ct]=h.useState({x:0,y:0}),[ut,fn]=h.useState(!1),Be=h.useRef(null),Tt=h.useRef(null),[jt,ke]=h.useState(""),[hn,bs]=h.useState(null),[$t,mn]=h.useState("Thinking..."),[Lt,nt]=h.useState(new Set),[vs,Bn]=h.useState(""),[st,Un]=h.useState([]),zn=h.useRef(new Map),Ft=h.useRef(!1),ce=h.useRef(""),[Bt,dt]=h.useState(!1),[xe,pn]=h.useState(!1),qe=h.useMemo(()=>[...d,...f],[d,f]),Re=h.useMemo(()=>mr(qe,p),[qe,p]),gn=h.useMemo(()=>{const T=new Map,_=new Map(Re.map(z=>[z.name,z]));return qe.forEach(z=>{const Z=z[Oe];if(Z){const J=_.get(Z);if(J){T.set(J.name,z);return}}const Y=Re.find(J=>J.name===z.name);Y&&T.set(Y.name,z)}),T},[qe,Re]),Ke=h.useMemo(()=>{const T=new Set,_=new Map(Re.map(z=>[z.name,z]));return f.forEach(z=>{const Z=z[Oe];if(Z&&_.has(Z))T.add(Z);else{const Y=Re.find(J=>J.name===z.name);Y&&T.add(Y.name)}}),m&&Array.isArray(m)&&m.forEach(z=>{typeof z=="string"&&T.add(z)}),T},[f,Re,m]),Ct=["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 T=localStorage.getItem("arcten-sidebar-expanded");T&&G(JSON.parse(T));const _=localStorage.getItem("arcten-sidebar-width");_&&oe(parseInt(_));const z=localStorage.getItem("arcten-sidebar-height");z&&We(parseInt(z));const Z=localStorage.getItem("arcten-sidebar-detached");Z&&It(JSON.parse(Z));const Y=localStorage.getItem("arcten-sidebar-position");if(Y){const De=JSON.parse(Y),re=50,ue=Math.max(re-i,Math.min(De.x,window.innerWidth-re)),W=Math.max(0,Math.min(De.y,window.innerHeight-re));Fe({x:ue,y:W})}const J=localStorage.getItem("arcten-sidebar-minimized");J&&St(JSON.parse(J)),fn(!0)}},[]),h.useMemo(()=>E,[E?.id]),h.useEffect(()=>{(async()=>{if(qe.length===0)return;const _=qe.map(z=>`${z.name}:${z.toString()}`).join("|");if(_!==ce.current&&!Ft.current){Ft.current=!0,ce.current=_;try{const z=qe.map(Y=>({name:Y.name,code:Y.toString()})),Z=await fetch(`${F}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:z})});if(Z.ok){const Y=await Z.json();Y.tools&&Y.tools.forEach(J=>{zn.current.set(J.name,J)}),Un(Y.tools)}}catch(z){console.error("Failed to fetch tool descriptions:",z)}finally{Ft.current=!1}}})()},[qe,F]),h.useEffect(()=>{Promise.resolve().then(()=>Xh).then(T=>{bs(()=>T.Response)})},[]),h.useEffect(()=>{const T=()=>{Bn(window.location.pathname)};T(),window.addEventListener("popstate",T);const _=setInterval(T,500);return()=>{window.removeEventListener("popstate",T),clearInterval(_)}},[]);const{id:_n,messages:Pe,sendMessage:ft,status:Ne,error:Xn,stop:Ut,addToolOutput:rt,setMessages:Wn,clientToken:qn,tokenError:Ge,conversations:He,isLoadingConversations:yn,loadConversation:Ue,deleteConversation:Ye,startNewConversation:Kn}=B;h.useEffect(()=>{X&&Tt.current&&Tt.current.focus()},[X,Pe]),h.useEffect(()=>{const T=Pe[Pe.length-1];if(!T||T.role!=="assistant")return;const _=T.parts?.filter(z=>z.type?.startsWith("tool-")&&z.state==="input-available"&&typeof z.toolCallId=="string"&&z.input!==void 0)||[];for(const z of _){const Z=z,Y=Z.type?.replace("tool-","")||"",J=Z.toolCallId;if(Ke.has(Y)){if(Lt.has(J))continue;nt(re=>re.has(J)?re:new Set(re).add(J)),(async()=>{try{const re=gn.get(Y);if(!re){console.warn(`[ArctenAgent] Tool ${Y} not found in toolsMap`),rt({toolCallId:J,tool:Y,output:`Error: Tool ${Y} not found`}),nt(ne=>{const Se=new Set(ne);return Se.delete(J),Se});return}const ue=zs(Z.input),W=Re.find(ne=>ne.name===Y);let me;if(W&&W.jsonSchema?.properties){const Se=Object.keys(W.jsonSchema.properties).map(de=>ue[de]);me=await re(...Se)}else me=await re(...Object.values(ue));rt({toolCallId:J,tool:Y,output:me}),nt(ne=>{const Se=new Set(ne);return Se.delete(J),Se})}catch(re){console.error(`[ArctenAgent] Error executing safe tool ${Y}:`,re),rt({toolCallId:J,tool:Y,output:`Error: ${re instanceof Error?re.message:String(re)}`}),nt(ue=>{const W=new Set(ue);return W.delete(J),W})}})()}}},[Pe,Ke,gn,Re,rt,Lt]);function Gn(){G(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function it(){G(!1),localStorage.setItem("arcten-sidebar-expanded","false")}h.useEffect(()=>{},[X]),h.useEffect(()=>{Be.current&&Be.current.scrollIntoView({behavior:"smooth"})},[Pe]),h.useEffect(()=>{function T(_){_.key==="Escape"&&(Ne==="streaming"||Ne==="submitted")&&(_.preventDefault(),Ut())}return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[Ne,Ut]);function Pt(T){const _=Math.floor((Date.now()-T)/1e3);return _<60?"now":_<3600?`${Math.floor(_/60)}m`:_<86400?`${Math.floor(_/3600)}h`:`${Math.floor(_/86400)}d`}function Hn(){Kn(),pn(!1)}function xn(T){if(T.preventDefault(),!jt.trim())return;(Ne==="streaming"||Ne==="submitted")&&Ut();const _=Ct[Math.floor(Math.random()*Ct.length)]||"Thinking...";mn(_),ft({text:jt}),ke("")}function ht(T){const _=T.target.value;ke(_)}h.useEffect(()=>{if(!wt)return;function T(z){if(H){const Z=z.clientX-Ce.x,Y=z.clientY-Ce.y;Z>=a&&Z<=l&&oe(Z),Y>=400&&Y<=1e3&&We(Y)}else{const Z=window.innerWidth-z.clientX;Z>=a&&Z<=l&&oe(Z)}}function _(){tt(!1),localStorage.setItem("arcten-sidebar-width",K.toString()),localStorage.setItem("arcten-sidebar-height",ye.toString())}return window.addEventListener("mousemove",T),window.addEventListener("mouseup",_),()=>{window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",_)}},[wt,K,ye,H,Ce,a,l]);function zt(T){T.preventDefault(),tt(!0)}function ws(){It(!0),St(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function bn(){It(!1),St(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function Yn(){St(!Ee),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ee))}function Je(T){H&&(ae(!0),ct({x:T.clientX-Ce.x,y:T.clientY-Ce.y}))}return h.useEffect(()=>{if(!H)return;function T(){Fe(_=>{const Z=window.innerWidth-50,Y=window.innerHeight-50,J=50-K,De=0,re=Math.max(J,Math.min(_.x,Z)),ue=Math.max(De,Math.min(_.y,Y));if(re!==_.x||ue!==_.y){const W={x:re,y:ue};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(W)),W}return _})}return window.addEventListener("resize",T),()=>window.removeEventListener("resize",T)},[H,K]),h.useEffect(()=>{if(!Ot)return;function T(z){const Z=z.clientX-dn.x,Y=z.clientY-dn.y,J=50,De=window.innerWidth-J,re=window.innerHeight-J,ue=J-K,W=0,me=Math.max(ue,Math.min(Z,De)),ne=Math.max(W,Math.min(Y,re));Fe({x:me,y:ne})}function _(){ae(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(Ce))}return window.addEventListener("mousemove",T),window.addEventListener("mouseup",_),()=>{window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",_)}},[Ot,dn,Ce,K]),ut?Ge?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: ",Ge]})}):qn?u.jsx(rd,{features:Ih,children:u.jsx(ts,{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:`
|
|
11
|
-
${
|
|
10
|
+
`),()=>{T.contains(v)&&T.removeChild(v)}},[t]),u.jsx(ed,{isPresent:t,childRef:o,sizeRef:i,children:qe.cloneElement(e,{ref:l})})}const nd=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:o,mode:i,anchorX:a,root:l})=>{const c=gr(sd),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(td,{isPresent:n,anchorX:a,root:l,children:e})),u.jsx(hs.Provider,{value:m,children:e})};function sd(){return new Map}function wa(e=!0){const t=h.useContext(hs);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 Jn=e=>e.key||"";function Ai(e){const t=[];return h.Children.forEach(e,n=>{h.isValidElement(n)&&t.push(n)}),t}const rd=({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]=wa(i),f=h.useMemo(()=>Ai(e),[e]),m=i&&!c?[]:f.map(Jn),p=h.useRef(!0),b=h.useRef(f),v=gr(()=>new Map),[T,w]=h.useState(f),[M,E]=h.useState(f);ko(()=>{p.current=!1,b.current=f;for(let O=0;O<M.length;O++){const k=Jn(M[O]);m.includes(k)?v.delete(k):v.get(k)!==!0&&v.set(k,!1)}},[M,m.length,m.join("-")]);const L=[];if(f!==T){let O=[...f];for(let k=0;k<M.length;k++){const C=M[k],V=Jn(C);m.includes(V)||(O.splice(k,0,C),L.push(C))}return o==="wait"&&L.length&&(O=L),E(Ai(O)),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(pr);return u.jsx(u.Fragment,{children:M.map(O=>{const k=Jn(O),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(nd,{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:O},k)})})},Br=h.createContext({strict:!1}),Ei={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 Ei)nn[e]={isEnabled:t=>Ei[e].some(n=>!!t[n])};function rr(e){for(const t in e)nn[t]={...nn[t],...e[t]}}function id({children:e,features:t,strict:n=!1}){const[,s]=h.useState(!Rs(t)),r=h.useRef(void 0);if(!Rs(t)){const{renderer:o,...i}=t;r.current=o,rr(i)}return h.useEffect(()=>{Rs(t)&&t().then(({renderer:o,...i})=>{rr(i),r.current=o,s(!0)})},[]),u.jsx(Br.Provider,{value:{renderer:r.current,strict:n},children:e})}function Rs(e){return typeof e=="function"}const od=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 us(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||od.has(e)}let Sa=e=>!us(e);function ad(e){typeof e=="function"&&(Sa=t=>t.startsWith("on")?!us(t):e(t))}try{ad(require("@emotion/is-prop-valid").default)}catch{}function ld(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||(Sa(r)||n===!0&&us(r)||!t&&!us(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const ms=h.createContext({});function ps(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function On(e){return typeof e=="string"||Array.isArray(e)}const Ur=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],zr=["initial",...Ur];function gs(e){return ps(e.animate)||zr.some(t=>On(e[t]))}function Ta(e){return!!(gs(e)||e.variants)}function cd(e,t){if(gs(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 ud(e){const{initial:t,animate:n}=cd(e,h.useContext(ms));return h.useMemo(()=>({initial:t,animate:n}),[Mi(t),Mi(n)])}function Mi(e){return Array.isArray(e)?e.join(" "):e}const $n={};function dd(e){for(const t in e)$n[t]=e[t],Cr(t)&&($n[t].isCSSVariable=!0)}function ja(e,{layout:t,layoutId:n}){return an.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!$n[e]||e==="opacity")}const fd={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},hd=on.length;function md(e,t,n){let s="",r=!0;for(let o=0;o<hd;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=pa(a,Or[i]);if(!l){r=!1;const d=fd[i]||i;s+=`${d}(${c}) `}n&&(t[i]=c)}}return s=s.trim(),n?s=n(t,r?"":s):r&&(s="none"),s}function _r(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(Cr(l)){r[l]=c;continue}else{const d=pa(c,Or[l]);l.startsWith("origin")?(a=!0,o[l]=d):s[l]=d}}if(t.transform||(i||n?s.transform=md(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 Xr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ca(e,t,n){for(const s in t)!Te(t[s])&&!ja(s,n)&&(e[s]=t[s])}function pd({transformTemplate:e},t){return h.useMemo(()=>{const n=Xr();return _r(n,t,e),Object.assign({},n.vars,n.style)},[t])}function gd(e,t){const n=e.style||{},s={};return Ca(s,n,e),Object.assign(s,pd(e,t)),s}function yd(e,t){const n={},s=gd(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 xd={offset:"stroke-dashoffset",array:"stroke-dasharray"},bd={offset:"strokeDashoffset",array:"strokeDasharray"};function vd(e,t,n=1,s=0,r=!0){e.pathLength=1;const o=r?xd:bd;e[o.offset]=z.transform(-s);const i=z.transform(t),a=z.transform(n);e[o.array]=`${i} ${a}`}function Pa(e,{attrX:t,attrY:n,attrScale:s,pathLength:r,pathSpacing:o=1,pathOffset:i=0,...a},l,c,d){if(_r(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&&vd(f,r,o,i,!1)}const Aa=()=>({...Xr(),attrs:{}}),Ea=e=>typeof e=="string"&&e.toLowerCase()==="svg";function wd(e,t,n,s){const r=h.useMemo(()=>{const o=Aa();return Pa(o,t,Ea(s),e.transformTemplate,e.style),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};Ca(o,e.style,e),r.style={...o,...r.style}}return r}const Sd=["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 Wr(e){return typeof e!="string"||e.includes("-")?!1:!!(Sd.indexOf(e)>-1||/[A-Z]/u.test(e))}function Td(e,t,n,{latestValues:s},r,o=!1){const a=(Wr(e)?wd:yd)(t,s,r,e),l=ld(t,typeof e=="string",o),c=e!==h.Fragment?{...l,...a,ref:n}:{},{children:d}=t,f=h.useMemo(()=>Te(d)?d.get():d,[d]);return h.createElement(e,{...c,children:f})}function ki(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function qr(e,t,n,s){if(typeof t=="function"){const[r,o]=ki(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]=ki(s);t=t(n!==void 0?n:e.custom,r,o)}return t}function rs(e){return Te(e)?e.get():e}function jd({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:Cd(n,s,r,e),renderState:t()}}function Cd(e,t,n,s){const r={},o=s(e,{});for(const m in o)r[m]=rs(o[m]);let{initial:i,animate:a}=e;const l=gs(e),c=Ta(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"&&!ps(f)){const m=Array.isArray(f)?f:[f];for(let p=0;p<m.length;p++){const b=qr(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 L=d?E.length-1:0;E=E[L]}E!==null&&(r[M]=E)}for(const M in v)r[M]=v[M]}}}return r}const Ma=e=>(t,n)=>{const s=h.useContext(ms),r=h.useContext(hs),o=()=>jd(e,t,s,r);return n?o():gr(o)};function Kr(e,t,n){const{style:s}=e,r={};for(const o in s)(Te(s[o])||t.style&&Te(t.style[o])||ja(o,e)||n?.getValue(o)?.liveStyle!==void 0)&&(r[o]=s[o]);return r}const Pd=Ma({scrapeMotionValuesFromProps:Kr,createRenderState:Xr});function ka(e,t,n){const s=Kr(e,t,n);for(const r in e)if(Te(e[r])||Te(t[r])){const o=on.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;s[o]=e[r]}return s}const Ad=Ma({scrapeMotionValuesFromProps:ka,createRenderState:Aa}),Ed=Symbol.for("motionComponentSymbol");function Ht(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function Md(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 Gr=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),kd="framerAppearId",Na="data-"+Gr(kd),Ra=h.createContext({});function Nd(e,t,n,s,r){const{visualElement:o}=h.useContext(ms),i=h.useContext(Br),a=h.useContext(hs),l=h.useContext(Fr).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(Ra);d&&!d.projection&&r&&(d.type==="html"||d.type==="svg")&&Rd(c.current,n,r,f);const m=h.useRef(!1);h.useInsertionEffect(()=>{d&&m.current&&d.update(n,a)});const p=n[Na],b=h.useRef(!!p&&!window.MotionHandoffIsComplete?.(p)&&window.MotionHasOptimisedAnimation?.(p));return ko(()=>{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 Rd(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:Da(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 Da(e){if(e)return e.options.allowProjection!==!1?e.projection:Da(e.parent)}function is(e,{forwardMotionProps:t=!1}={},n,s){n&&rr(n);const r=Wr(e)?Ad:Pd;function o(a,l){let c;const d={...h.useContext(Fr),...a,layoutId:Dd(a)},{isStatic:f}=d,m=ud(a),p=r(a,f);if(!f&&yr){Vd(d,n);const b=Id(d);c=b.MeasureLayout,m.visualElement=Nd(e,p,d,s,b.ProjectionNode)}return u.jsxs(ms.Provider,{value:m,children:[c&&m.visualElement?u.jsx(c,{visualElement:m.visualElement,...d}):null,Td(e,a,Md(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[Ed]=e,i}function Dd({layoutId:e}){const t=h.useContext(pr).id;return t&&e!==void 0?t+"-"+e:e}function Vd(e,t){const n=h.useContext(Br).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"):it(!1,s,"lazy-strict-mode")}}function Id(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 Od(e,t){if(typeof Proxy>"u")return is;const n=new Map,s=(o,i)=>is(o,i,e,t),r=(o,i)=>(process.env.NODE_ENV!=="production"&&Sr(!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,is(i,void 0,e,t)),n.get(i))})}function Va({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function $d({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Ld(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 Ds(e){return e===void 0||e===1}function ir({scale:e,scaleX:t,scaleY:n}){return!Ds(e)||!Ds(t)||!Ds(n)}function Nt(e){return ir(e)||Ia(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Ia(e){return Ni(e.x)||Ni(e.y)}function Ni(e){return e&&e!=="0%"}function ds(e,t,n){const s=e-n,r=t*s;return n+r}function Ri(e,t,n,s,r){return r!==void 0&&(e=ds(e,r,s)),ds(e,n,s)+t}function or(e,t=0,n=1,s,r){e.min=Ri(e.min,t,n,s,r),e.max=Ri(e.max,t,n,s,r)}function Oa(e,{x:t,y:n}){or(e.x,t.translate,t.scale,t.originPoint),or(e.y,n.translate,n.scale,n.originPoint)}const Di=.999999999999,Vi=1.0000000000001;function Fd(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,Oa(e,i)),s&&Nt(o.latestValues)&&Jt(e,o.latestValues))}t.x<Vi&&t.x>Di&&(t.x=1),t.y<Vi&&t.y>Di&&(t.y=1)}function Yt(e,t){e.min=e.min+t,e.max=e.max+t}function Ii(e,t,n,s,r=.5){const o=de(e.min,e.max,r);or(e,t,n,o,s)}function Jt(e,t){Ii(e.x,t.x,t.scaleX,t.scale,t.originX),Ii(e.y,t.y,t.scaleY,t.scale,t.originY)}function $a(e,t){return Va(Ld(e.getBoundingClientRect(),t))}function Bd(e,t,n){const s=$a(e,n),{scroll:r}=t;return r&&(Yt(s.x,r.offset.x),Yt(s.y,r.offset.y)),s}const Oi=()=>({translate:0,scale:1,origin:0,originPoint:0}),Zt=()=>({x:Oi(),y:Oi()}),$i=()=>({min:0,max:0}),pe=()=>({x:$i(),y:$i()}),ar={current:null},La={current:!1};function Ud(){if(La.current=!0,!!yr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>ar.current=e.matches;e.addEventListener("change",t),t()}else ar.current=!1}const zd=new WeakMap;function _d(e,t,n){for(const s in t){const r=t[s],o=n[s];if(Te(r))e.addValue(s,r);else if(Te(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 Li=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Xd{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=Vr,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=Ne.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=gs(n),this.isVariantNode=Ta(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&&Te(p)&&p.set(l[m])}}mount(t){this.current=t,zd.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)),La.current||Ud(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ar.current,process.env.NODE_ENV!=="production"&&Sr(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(),yt(this.notifyUpdate),yt(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):pe()}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<Li.length;s++){const r=Li[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=_d(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"&&(No(s)||Do(s))?s=parseFloat(s):!Ju(s)&&xt.test(n)&&(s=ma(t,n)),this.setBaseTarget(t,Te(s)?s.get():s)),Te(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=qr(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&&!Te(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 wr),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){$r.render(this.render)}}class Fa extends Xd{constructor(){super(...arguments),this.KeyframeResolver=Fu}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;Te(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Ba(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 Wd(e){return window.getComputedStyle(e)}class qd extends Fa{constructor(){super(...arguments),this.type="html",this.renderInstance=Ba}readValueFromInstance(t,n){if(an.has(n))return this.projection?.isProjecting?Js(n):su(t,n);{const s=Wd(t),r=(Cr(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(t,{transformPagePoint:n}){return $a(t,n)}build(t,n,s){_r(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Kr(t,n,s)}}const Ua=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 Kd(e,t,n,s){Ba(e,t,void 0,s);for(const r in t.attrs)e.setAttribute(Ua.has(r)?r:Gr(r),t.attrs[r])}class Gd extends Fa{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=pe}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(an.has(n)){const s=ha(n);return s&&s.default||0}return n=Ua.has(n)?n:Gr(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return ka(t,n,s)}build(t,n,s){Pa(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,r){Kd(t,n,s,r)}mount(t){this.isSVGTag=Ea(t.tagName),super.mount(t)}}const za=(e,t)=>Wr(e)?new Gd(t):new qd(t,{allowProjection:e!==h.Fragment});function en(e,t,n){const s=e.getProps();return qr(s,t,n!==void 0?n:s.custom,e)}const lr=e=>Array.isArray(e);function Hd(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,tn(n))}function Yd(e){return lr(e)?e[e.length-1]||0:e}function Jd(e,t){const n=en(e,t);let{transitionEnd:s={},transition:r={},...o}=n||{};o={...o,...s};for(const i in o){const a=Yd(o[i]);Hd(e,i,a)}}function Zd(e){return!!(Te(e)&&e.add)}function cr(e,t){const n=e.getValue("willChange");if(Zd(n))return n.add(t);if(!n&&ot.WillChange){const s=new ot.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function _a(e){return e.props[Na]}const Qd=e=>e!==null;function ef(e,{repeat:t,repeatType:n="loop"},s){const r=e.filter(Qd),o=t&&n!=="loop"&&t%2===1?0:r.length-1;return r[o]}const tf={type:"spring",stiffness:500,damping:25,restSpeed:10},nf=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),sf={type:"keyframes",duration:.8},rf={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},of=(e,{keyframes:t})=>t.length>2?sf:an.has(e)?e.startsWith("scale")?nf(t[1]):tf:rf;function af({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 Hr=(e,t,n,s={},r,o)=>i=>{const a=Ir(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};af(a)||Object.assign(d,of(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)&&(nr(d),d.delay===0&&(f=!0)),(ot.instantAnimations||ot.skipAnimations)&&(f=!0,nr(d),d.delay=0),d.allowFlatten=!a.type&&!a.ease,f&&!o&&t.get()!==void 0){const m=ef(d.keyframes,a);if(m!==void 0){ce.update(()=>{d.onUpdate(m),d.onComplete()});return}}return a.isSync?new Dr(d):new Pu(d)};function lf({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Xa(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&&lf(c,d))continue;const p={delay:n,...Ir(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=_a(e);if(w){const M=window.MotionHandoffAnimation(w,d,ce);M!==null&&(p.startTime=M,v=!0)}}cr(e,d),f.start(Hr(d,f,m,e.shouldReduceMotion&&ua.has(d)?{type:!1}:p,e,v));const T=f.animation;T&&l.push(T)}return i&&Promise.all(l).then(()=>{ce.update(()=>{i&&Jd(e,i)})}),l}function Wa(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 ur(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(Xa(e,s,n)):()=>Promise.resolve(),i=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:c=0,staggerChildren:d,staggerDirection:f}=r;return cf(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 cf(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(ur(l,t,{...i,delay:n+(typeof s=="function"?0:s)+Wa(e.variantChildren,l,s,r,o)}).then(()=>l.notify("AnimationComplete",t)));return Promise.all(a)}function uf(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const r=t.map(o=>ur(e,o,n));s=Promise.all(r)}else if(typeof t=="string")s=ur(e,t,n);else{const r=typeof t=="function"?en(e,t,n.custom):t;s=Promise.all(Xa(e,r,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}function qa(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 df=zr.length;function Ka(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?Ka(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<df;n++){const s=zr[n],r=e.props[s];(On(r)||r===!1)&&(t[s]=r)}return t}const ff=[...Ur].reverse(),hf=Ur.length;function mf(e){return t=>Promise.all(t.map(({animation:n,options:s})=>uf(e,n,s)))}function pf(e){let t=mf(e),n=Fi(),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=Ka(e.parent)||{},f=[],m=new Set;let p={},b=1/0;for(let T=0;T<hf;T++){const w=ff[T],M=n[w],E=c[w]!==void 0?c[w]:d[w],L=On(E),D=w===l?M.isActive:null;D===!1&&(b=T);let O=E===d[w]&&E!==c[w]&&L;if(O&&s&&e.manuallyAnimateOnMount&&(O=!1),M.protectedKeys={...p},!M.isActive&&D===null||!E&&!M.prevProp||ps(E)||typeof E=="boolean")continue;const k=gf(M.prevProp,E);let C=k||w===l&&M.isActive&&!O&&L||T>b&&L,V=!1;const A=Array.isArray(E)?E:[E];let N=A.reduce(r(w),{});D===!1&&(N={});const{prevResolvedValues:F={}}=M,$={...F,...N},B=q=>{C=!0,m.has(q)&&(V=!0,m.delete(q)),M.needsAnimating[q]=!0;const oe=e.getValue(q);oe&&(oe.liveStyle=!1)};for(const q in $){const oe=N[q],ye=F[q];if(p.hasOwnProperty(q))continue;let Ge=!1;lr(oe)&&lr(ye)?Ge=!qa(oe,ye):Ge=oe!==ye,Ge?oe!=null?B(q):m.add(q):oe!==void 0&&m.has(q)?B(q):M.protectedKeys[q]=!0}M.prevProp=E,M.prevResolvedValues=N,M.isActive&&(p={...p,...N}),s&&e.blockInitialAnimation&&(C=!1);const X=O&&k;C&&(!X||V)&&f.push(...A.map(q=>{const oe={type:w};if(typeof q=="string"&&s&&!X&&e.manuallyAnimateOnMount&&e.parent){const{parent:ye}=e,Ge=en(ye,q);if(ye.enteringChildren&&Ge){const{delayChildren:vt}=Ge.transition||{};oe.delay=Wa(ye.enteringChildren,e,vt)}}return{animation:q,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=Fi()}}}function gf(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!qa(t,e):!1}function Mt(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Fi(){return{animate:Mt(!0),whileInView:Mt(),whileHover:Mt(),whileTap:Mt(),whileDrag:Mt(),whileFocus:Mt(),exit:Mt()}}class bt{constructor(t){this.isMounted=!1,this.node=t}update(){}}class yf extends bt{constructor(t){super(t),t.animationState||(t.animationState=pf(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();ps(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 xf=0;class bf extends bt{constructor(){super(...arguments),this.id=xf++}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 Ga={animation:{Feature:yf},exit:{Feature:bf}};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 vf=e=>t=>Lr(t)&&e(t,zn(t));function Mn(e,t,n,s){return Ln(e,t,vf(n),s)}const Ha=1e-4,wf=1-Ha,Sf=1+Ha,Ya=.01,Tf=0-Ya,jf=0+Ya;function Ae(e){return e.max-e.min}function Cf(e,t,n){return Math.abs(e-t)<=n}function Bi(e,t,n,s=.5){e.origin=s,e.originPoint=de(t.min,t.max,e.origin),e.scale=Ae(n)/Ae(t),e.translate=de(n.min,n.max,e.origin)-e.originPoint,(e.scale>=wf&&e.scale<=Sf||isNaN(e.scale))&&(e.scale=1),(e.translate>=Tf&&e.translate<=jf||isNaN(e.translate))&&(e.translate=0)}function kn(e,t,n,s){Bi(e.x,t.x,n.x,s?s.originX:void 0),Bi(e.y,t.y,n.y,s?s.originY:void 0)}function Ui(e,t,n){e.min=n.min+t.min,e.max=e.min+Ae(t)}function Pf(e,t,n){Ui(e.x,t.x,n.x),Ui(e.y,t.y,n.y)}function zi(e,t,n){e.min=t.min-n.min,e.max=e.min+Ae(t)}function Nn(e,t,n){zi(e.x,t.x,n.x),zi(e.y,t.y,n.y)}function Oe(e){return[e("x"),e("y")]}const Ja=({current:e})=>e?e.ownerDocument.defaultView:null,_i=(e,t)=>Math.abs(e-t);function Af(e,t){const n=_i(e.x,t.x),s=_i(e.y,t.y);return Math.sqrt(n**2+s**2)}class Za{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=Is(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,b=Af(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!b)return;const{point:v}=m,{timestamp:T}=ve;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=Vs(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=Is(m.type==="pointercancel"?this.lastMoveEventInfo:Vs(p,this.transformPagePoint),this.history);this.startEvent&&b&&b(m,w),v&&v(m,w)},!Lr(t))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=i,this.contextWindow=r||window;const a=zn(t),l=Vs(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=ve;this.history=[{...c,timestamp:d}];const{onSessionStart:f}=n;f&&f(t,Is(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(),yt(this.updatePoint)}}function Vs(e,t){return t?{point:t(e.point)}:e}function Xi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Is({point:e},t){return{point:e,delta:Xi(e,Qa(t)),offset:Xi(e,Ef(t)),velocity:Mf(t,.1)}}function Ef(e){return e[0]}function Qa(e){return e[e.length-1]}function Mf(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Qa(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>Ke(t)));)n--;if(!s)return{x:0,y:0};const o=Le(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 kf(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?de(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?de(n,e,s.max):Math.min(e,n)),e}function Wi(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 Nf(e,{top:t,left:n,bottom:s,right:r}){return{x:Wi(e.x,n,r),y:Wi(e.y,t,s)}}function qi(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 Rf(e,t){return{x:qi(e.x,t.x),y:qi(e.y,t.y)}}function Df(e,t){let n=.5;const s=Ae(e),r=Ae(t);return r>s?n=Dn(t.min,t.max-s,e.min):s>r&&(n=Dn(e.min,e.max-r,t.min)),rt(0,1,n)}function Vf(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 dr=.35;function If(e=dr){return e===!1?e=0:e===!0&&(e=dr),{x:Ki(e,"left","right"),y:Ki(e,"top","bottom")}}function Ki(e,t,n){return{min:Gi(e,t),max:Gi(e,n)}}function Gi(e,t){return typeof e=="number"?e:e[t]||0}const Of=new WeakMap;class $f{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=pe(),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=_u(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),Oe(w=>{let M=this.getAxisMotionValue(w).get()||0;if(Qe.test(M)){const{projection:E}=this.visualElement;if(E&&E.layout){const L=E.layout.layoutBox[w];L&&(M=Ae(L)*(parseFloat(M)/100))}}this.originPoint[w]=M}),v&&ce.postRender(()=>v(f,m)),cr(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=Lf(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=()=>Oe(f=>this.getAnimationState(f)==="paused"&&this.getAxisMotionValue(f).animation?.play()),{dragSnapToOrigin:d}=this.getProps();this.panSession=new Za(t,{onSessionStart:o,onStart:i,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Ja(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||!Zn(t,r,this.currentDirection))return;const o=this.getAxisMotionValue(t);let i=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(i=kf(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=Nf(s.layoutBox,t):this.constraints=!1,this.elastic=If(n),r!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&Oe(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Vf(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Ht(t))return!1;const s=t.current;it(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=Bd(s,r.root,this.visualElement.getTransformPagePoint());let i=Rf(r.layout.layoutBox,o);if(n){const a=n($d(i));this.hasMutatedConstraints=!!a,a&&(i=Va(a))}return i}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:o,dragSnapToOrigin:i,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Oe(d=>{if(!Zn(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 cr(this.visualElement,t),s.start(Hr(t,s,0,n,this.visualElement,!1))}stopAnimation(){Oe(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){Oe(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){Oe(n=>{const{drag:s}=this.getProps();if(!Zn(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]-de(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};Oe(i=>{const a=this.getAxisMotionValue(i);if(a&&this.constraints!==!1){const l=a.get();r[i]=Df({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(),Oe(i=>{if(!Zn(i,t,null))return;const a=this.getAxisMotionValue(i),{min:l,max:c}=this.constraints[i];a.set(de(l,c,r[i]))})}addListeners(){if(!this.visualElement.current)return;Of.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&&(Oe(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=dr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:o,dragElastic:i,dragMomentum:a}}}function Zn(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Lf(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Ff extends bt{constructor(t){super(t),this.removeGroupControls=Fe,this.removeListeners=Fe,this.controls=new $f(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Fe}unmount(){this.removeGroupControls(),this.removeListeners()}}const Hi=e=>(t,n)=>{e&&ce.postRender(()=>e(t,n))};class Bf extends bt{constructor(){super(...arguments),this.removePointerDownListener=Fe}onPointerDown(t){this.session=new Za(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ja(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Hi(t),onStart:Hi(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 os={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Yi(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=Yi(e,t.target.x),s=Yi(e,t.target.y);return`${n}% ${s}%`}},Uf={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,r=xt.parse(e);if(r.length>5)return s;const o=xt.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=de(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 Os=!1;class zf extends h.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:o}=t;dd(_f),o&&(n.group&&n.group.add(o),s&&s.register&&r&&s.register(o),Os&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),os.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:o}=this.props,{projection:i}=s;return i&&(i.isPresent=o,Os=!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(),$r.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;Os=!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 el(e){const[t,n]=wa(),s=h.useContext(pr);return u.jsx(zf,{...e,layoutGroup:s,switchLayoutGroup:h.useContext(Ra),isPresent:t,safeToRemove:n})}const _f={borderRadius:{...jn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:jn,borderTopRightRadius:jn,borderBottomLeftRadius:jn,borderBottomRightRadius:jn,boxShadow:Uf};function Xf(e,t,n){const s=Te(e)?e:tn(e);return s.start(Hr("",s,t,n)),s.animation}const Wf=(e,t)=>e.depth-t.depth;class qf{constructor(){this.children=[],this.isDirty=!1}add(t){xr(this.children,t),this.isDirty=!0}remove(t){br(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(Wf),this.isDirty=!1,this.children.forEach(t)}}function Kf(e,t){const n=Ne.now(),s=({timestamp:r})=>{const o=r-n;o>=t&&(yt(s),e(o-t))};return ce.setup(s,!0),()=>yt(s)}const tl=["TopLeft","TopRight","BottomLeft","BottomRight"],Gf=tl.length,Ji=e=>typeof e=="string"?parseFloat(e):e,Zi=e=>typeof e=="number"||z.test(e);function Hf(e,t,n,s,r,o){r?(e.opacity=de(0,n.opacity??1,Yf(s)),e.opacityExit=de(t.opacity??1,0,Jf(s))):o&&(e.opacity=de(t.opacity??1,n.opacity??1,s));for(let i=0;i<Gf;i++){const a=`border${tl[i]}Radius`;let l=Qi(t,a),c=Qi(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Zi(l)===Zi(c)?(e[a]=Math.max(de(Ji(l),Ji(c),s),0),(Qe.test(c)||Qe.test(l))&&(e[a]+="%")):e[a]=c}(t.rotate||n.rotate)&&(e.rotate=de(t.rotate||0,n.rotate||0,s))}function Qi(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const Yf=nl(0,.5,Uo),Jf=nl(.5,.95,Fe);function nl(e,t,n){return s=>s<e?0:s>t?1:n(Dn(e,t,s))}function eo(e,t){e.min=t.min,e.max=t.max}function Ie(e,t){eo(e.x,t.x),eo(e.y,t.y)}function to(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function no(e,t,n,s,r){return e-=t,e=ds(e,1/n,s),r!==void 0&&(e=ds(e,1/r,s)),e}function Zf(e,t=0,n=1,s=.5,r,o=e,i=e){if(Qe.test(t)&&(t=parseFloat(t),t=de(i.min,i.max,t/100)-i.min),typeof t!="number")return;let a=de(o.min,o.max,s);e===o&&(a-=t),e.min=no(e.min,t,n,a,r),e.max=no(e.max,t,n,a,r)}function so(e,t,[n,s,r],o,i){Zf(e,t[n],t[s],t[r],t.scale,o,i)}const Qf=["x","scaleX","originX"],eh=["y","scaleY","originY"];function ro(e,t,n,s){so(e.x,t,Qf,n?n.x:void 0,s?s.x:void 0),so(e.y,t,eh,n?n.y:void 0,s?s.y:void 0)}function io(e){return e.translate===0&&e.scale===1}function sl(e){return io(e.x)&&io(e.y)}function oo(e,t){return e.min===t.min&&e.max===t.max}function th(e,t){return oo(e.x,t.x)&&oo(e.y,t.y)}function ao(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function rl(e,t){return ao(e.x,t.x)&&ao(e.y,t.y)}function lo(e){return Ae(e.x)/Ae(e.y)}function co(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class nh{constructor(){this.members=[]}add(t){xr(this.members,t),t.scheduleRender()}remove(t){if(br(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 sh(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 $s=["","X","Y","Z"],rh=1e3;let ih=0;function Ls(e,t,n,s){const{latestValues:r}=t;r[e]&&(n[e]=r[e],t.setStaticValue(e,0),s&&(s[e]=0))}function il(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=_a(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&&il(s)}function ol({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:r}){return class{constructor(i={},a=t?.()){this.id=ih++,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(lh),this.nodes.forEach(fh),this.nodes.forEach(hh),this.nodes.forEach(ch)},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 qf)}addEventListener(i,a){return this.eventHandlers.has(i)||this.eventHandlers.set(i,new wr),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=va(i)&&!Hu(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=Kf(m,250),os.hasAnimatedSinceResize&&(os.hasAnimatedSinceResize=!1,this.nodes.forEach(ho)))})}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()||xh,{onLayoutAnimationStart:v,onLayoutAnimationComplete:T}=c.getProps(),w=!this.targetLayout||!rl(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={...Ir(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||ho(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(),yt(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(mh),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&&il(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(uo);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(fo);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(dh),this.nodes.forEach(oh),this.nodes.forEach(ah)):this.nodes.forEach(fo),this.clearAllSnapshots();const a=Ne.now();ve.delta=rt(0,1e3/60,a-ve.timestamp),ve.timestamp=a,ve.isProcessing=!0,Ps.update.process(ve),Ps.preRender.process(ve),Ps.render.process(ve),ve.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,$r.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(uh),this.sharedNodes.forEach(ph)}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&&!Ae(this.snapshot.measuredBox.x)&&!Ae(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=pe(),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&&!sl(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;i&&this.instance&&(a||Nt(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)),bh(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:i}=this.options;if(!i)return pe();const a=i.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(vh))){const{scroll:c}=this.root;c&&(Yt(a.x,c.offset.x),Yt(a.y,c.offset.y))}return a}removeElementScroll(i){const a=pe();if(Ie(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&&Ie(a,i),Yt(a.x,d.offset.x),Yt(a.y,d.offset.y))}return a}applyTransform(i,a=!1){const l=pe();Ie(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}),Nt(d.latestValues)&&Jt(l,d.latestValues)}return Nt(this.latestValues)&&Jt(l,this.latestValues),l}removeTransform(i){const a=pe();Ie(a,i);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Nt(c.latestValues))continue;ir(c.latestValues)&&c.updateSnapshot();const d=pe(),f=c.measurePageBox();Ie(d,f),ro(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return Nt(this.latestValues)&&ro(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!==ve.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=ve.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pe(),this.relativeTargetOrigin=pe(),Nn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Ie(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=pe(),this.targetWithTransforms=pe()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Pf(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ie(this.target,this.layout.layoutBox),Oa(this.target,this.targetDelta)):Ie(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=pe(),this.relativeTargetOrigin=pe(),Nn(this.relativeTargetOrigin,this.target,m.target),Ie(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||ir(this.parent.latestValues)||Ia(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===ve.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;Ie(this.layoutCorrected,this.layout.layoutBox);const f=this.treeScale.x,m=this.treeScale.y;Fd(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=pe());const{target:p}=i;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(to(this.prevProjectionDelta.x,this.projectionDelta.x),to(this.prevProjectionDelta.y,this.projectionDelta.y)),kn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==f||this.treeScale.y!==m||!co(this.projectionDelta.x,this.prevProjectionDelta.x)||!co(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=pe(),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(yh));this.animationProgress=0;let E;this.mixTargetDelta=L=>{const D=L/1e3;mo(f.x,i.x,D),mo(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),gh(this.relativeTarget,this.relativeTargetOrigin,m,D),E&&th(this.relativeTarget,E)&&(this.isProjectionDirty=!1),E||(E=pe()),Ie(E,this.relativeTarget)),v&&(this.animationValues=d,Hf(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&&(yt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ce.update(()=>{os.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=tn(0)),this.currentAnimation=Xf(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(rh),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&&al(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||pe();const f=Ae(this.layout.layoutBox.x);l.x.min=i.target.x.min,l.x.max=l.x.min+f;const m=Ae(this.layout.layoutBox.y);l.y.min=i.target.y.min,l.y.max=l.y.min+m}Ie(a,l),Jt(a,d),kn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(i,a){this.sharedNodes.has(i)||this.sharedNodes.set(i,new nh),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&&Ls("z",i,c,this.animationValues);for(let d=0;d<$s.length;d++)Ls(`rotate${$s[d]}`,i,c,this.animationValues),Ls(`skew${$s[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=rs(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=rs(a?.pointerEvents)||""),this.hasProjected&&!Nt(this.latestValues)&&(i.transform=l?l({},""):"none",this.hasProjected=!1);return}i.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let f=sh(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 L=0;L<E;L++)i[T[L]]=M}else w?this.options.visualElement.renderState.vars[b]=M:i[b]=M}this.options.layoutId&&(i.pointerEvents=c===this?rs(a?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(i=>i.currentAnimation?.stop()),this.root.nodes.forEach(uo),this.root.sharedNodes.clear()}}}function oh(e){e.updateLayout()}function ah(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"?Oe(d=>{const f=o?t.measuredBox[d]:t.layoutBox[d],m=Ae(f);f.min=n[d].min,f.max=f.min+m}):al(r,t.layoutBox,n)&&Oe(d=>{const f=o?t.measuredBox[d]:t.layoutBox[d],m=Ae(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=!sl(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=pe();Nn(p,t.layoutBox,f.layoutBox);const b=pe();Nn(b,n,m.layoutBox),rl(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 lh(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 ch(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function uh(e){e.clearSnapshot()}function uo(e){e.clearMeasurements()}function fo(e){e.isLayoutDirty=!1}function dh(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function ho(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function fh(e){e.resolveTargetDelta()}function hh(e){e.calcProjection()}function mh(e){e.resetSkewAndRotation()}function ph(e){e.removeLeadSnapshot()}function mo(e,t,n){e.translate=de(t.translate,0,n),e.scale=de(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function po(e,t,n,s){e.min=de(t.min,n.min,s),e.max=de(t.max,n.max,s)}function gh(e,t,n,s){po(e.x,t.x,n.x,s),po(e.y,t.y,n.y,s)}function yh(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const xh={duration:.45,ease:[.4,0,.1,1]},go=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),yo=go("applewebkit/")&&!go("chrome/")?Math.round:Fe;function xo(e){e.min=yo(e.min),e.max=yo(e.max)}function bh(e){xo(e.x),xo(e.y)}function al(e,t,n){return e==="position"||e==="preserve-aspect"&&!Cf(lo(t),lo(n),.2)}function vh(e){return e!==e.root&&e.scroll?.wasRoot}const wh=ol({attachResizeListener:(e,t)=>Ln(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Fs={current:void 0},ll=ol({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Fs.current){const e=new wh({});e.mount(window),e.setOptions({layoutScroll:!0}),Fs.current=e}return Fs.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),Sh={pan:{Feature:Bf},drag:{Feature:Ff,ProjectionNode:ll,MeasureLayout:el}};function bo(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 Th extends bt{mount(){const{current:t}=this.node;t&&(this.unmount=Xu(t,(n,s)=>(bo(this.node,s,"Start"),r=>bo(this.node,r,"End"))))}unmount(){}}class jh extends bt{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 vo(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 Ch extends bt{mount(){const{current:t}=this.node;t&&(this.unmount=Gu(t,(n,s)=>(vo(this.node,s,"Start"),(r,{success:o})=>vo(this.node,r,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const fr=new WeakMap,Bs=new WeakMap,Ph=e=>{const t=fr.get(e.target);t&&t(e)},Ah=e=>{e.forEach(Ph)};function Eh({root:e,...t}){const n=e||document;Bs.has(n)||Bs.set(n,{});const s=Bs.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(Ah,{root:e,...t})),s[r]}function Mh(e,t,n){const s=Eh(t);return fr.set(e,n),s.observe(e),()=>{fr.delete(e),s.unobserve(e)}}const kh={some:0,all:1};class Nh extends bt{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:kh[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 Mh(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(Rh(t,n))&&this.startObserver()}unmount(){}}function Rh({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const cl={inView:{Feature:Nh},tap:{Feature:Ch},focus:{Feature:jh},hover:{Feature:Th}},Dh={layout:{ProjectionNode:ll,MeasureLayout:el}},Vh={...Ga,...cl,...Sh,...Dh},Ih=Od(Vh,za),Oh={renderer:za,...Ga,...cl};function Yr(e,t){return is(e,t)}const $h=Yr("button"),Qn=Yr("div"),Lh=Yr("p");function Fh({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(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:s,children:[u.jsx(ne.Check,{className:"h-3 w-3 mr-1"}),"Approve"]}),u.jsx(je,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",onClick:r,children:u.jsx(ne.X,{className:"h-3 w-3"})})]})]})})}function Bh({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(ne.ChevronDown,{className:"h-3 w-3"}):u.jsx(ne.ChevronRight,{className:"h-3 w-3"})}),n?u.jsx(ne.X,{className:"h-3 w-3"}):s?u.jsx(ne.Zap,{className:"h-3 w-3"}):u.jsx(ne.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 Uh({...e}){return u.jsx(hr.Root,{"data-slot":"collapsible",...e})}function zh({...e}){return u.jsx(hr.CollapsibleTrigger,{"data-slot":"collapsible-trigger",...e})}function _h({...e}){return u.jsx(hr.CollapsibleContent,{"data-slot":"collapsible-content",...e})}const Xh=h.lazy(()=>import("streamdown").then(e=>({default:e.Streamdown}))),Jr=h.memo(({className:e,...t})=>typeof window>"u"?null:u.jsx(h.Suspense,{fallback:null,children:u.jsx(Xh,{className:re("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",e),...t})}),(e,t)=>e.children===t.children);Jr.displayName="Response";const Wh=Object.freeze(Object.defineProperty({__proto__:null,Response:Jr},Symbol.toStringTag,{value:"Module"})),qh=({children:e,as:t="p",className:n,duration:s=2,spread:r=2})=>{const o=Ih.create(t),i=h.useMemo(()=>(e?.length??0)*r,[e,r]);return u.jsx(o,{animate:{backgroundPosition:"0% center"},className:re("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})},Kh=h.memo(qh),ul=h.createContext(null),Gh=()=>{const e=h.useContext(ul);if(!e)throw new Error("Reasoning components must be used within Reasoning");return e},Hh=1e3,Yh=1e3,dl=h.memo(({className:e,isStreaming:t=!1,open:n,defaultOpen:s=!0,onOpenChange:r,duration:o,children:i,...a})=>{const[l,c]=si.useControllableState({prop:n,defaultProp:s,onChange:r}),[d,f]=si.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)/Yh)),v(null))},[t,b,f]),h.useEffect(()=>{if(s&&!t&&l&&!m){const w=setTimeout(()=>{c(!1),p(!0)},Hh);return()=>clearTimeout(w)}},[t,l,s,c,m]);const T=w=>{c(w)};return u.jsx(ul.Provider,{value:{isStreaming:t,isOpen:l,setIsOpen:c,duration:d},children:u.jsx(Uh,{className:re("not-prose mb-4",e),onOpenChange:T,open:l,...a,children:i})})}),Jh=(e,t)=>e||t===0?u.jsx(Kh,{duration:1,children:"Thinking..."}):t===void 0?u.jsx("p",{children:"Thought for a few seconds"}):u.jsxs("p",{children:["Thought for ",t," seconds"]}),fl=h.memo(({className:e,children:t,...n})=>{const{isStreaming:s,isOpen:r,duration:o}=Gh();return u.jsx(zh,{className:re("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(ne.BrainIcon,{className:"size-4"}),Jh(s,o),u.jsx(ne.ChevronDownIcon,{className:re("size-4 transition-transform",r?"rotate-180":"rotate-0")})]})})}),hl=h.memo(({className:e,children:t,...n})=>u.jsx(_h,{className:re("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(Jr,{className:"grid gap-2",children:t})}));dl.displayName="Reasoning";fl.displayName="ReasoningTrigger";hl.displayName="ReasoningContent";function wo(e){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(e)}&sz=16`}function Zh({sources:e,citationNumber:t,className:n}){const s=e.find(o=>o.number===t);if(!s)return null;const r=wo(s.domain);return u.jsxs(ht,{children:[u.jsx(mt,{asChild:!0,children:u.jsxs("button",{className:re("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(pt,{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:re("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:wo(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 Qh({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,L=()=>{if(!c.current||M)return;M=!0;const O=c.current,k=/\[(\d+)\]/g,C=document.createTreeWalker(O,NodeFilter.SHOW_TEXT,null),V=[];let A;for(;A=C.nextNode();)if(A.nodeType===Node.TEXT_NODE&&!E.has(A)){const F=A,$=F.textContent||"";let B=F.parentElement,X=!1;for(;B&&B!==O;){if(B.tagName==="A"||B.tagName==="CODE"||B.tagName==="PRE"){X=!0;break}B=B.parentElement}if(!X){const q=Array.from($.matchAll(k)).filter(oe=>{if(!oe[1])return!1;const ye=parseInt(oe[1],10);return n.has(ye)});q.length>0&&V.push({node:F,matches:q})}}if(V.length===0){M=!1;return}const N=[];V.forEach(({node:F,matches:$})=>{E.add(F);const B=F.textContent||"",X=document.createDocumentFragment();let K=0;$.forEach(q=>{if(!q[1])return;q.index!==void 0&&q.index>K&&X.appendChild(document.createTextNode(B.slice(K,q.index)));const oe=document.createElement("span");oe.className="inline-flex items-center citation-button-container";const ye=parseInt(q[1],10);oe.setAttribute("data-citation",q[1]),X.appendChild(oe),N.push({element:oe,citationNum:ye}),K=(q.index||0)+q[0].length}),K<B.length&&X.appendChild(document.createTextNode(B.slice(K))),F.parentNode&&F.parentNode.replaceChild(X,F)}),N.length>0&&f(F=>{const $=new Set(F.map(K=>K.element)),B=F.filter(K=>K.element.isConnected),X=N.filter(K=>!$.has(K.element));return[...B,...X]}),M=!1},D=new MutationObserver(()=>{clearTimeout(w),w=setTimeout(L,100)});return D.observe(T,{childList:!0,subtree:!0,characterData:!0}),w=setTimeout(L,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),L=p(E);return u.jsxs("a",{href:T.url,target:"_blank",rel:"noopener noreferrer",className:re("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:L,alt:"",className:"w-3.5 h-3.5 shrink-0",onError:D=>{const O=D.target;O.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:re("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:L=>{const D=L.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 L=Array.from(new Map(t.map(D=>{const O=D.url.replace(/\/+$/,""),k=s?.find(C=>C.url.replace(/\/+$/,"")===O);return[O,{number:D.number,url:D.url,domain:b(D.url),title:k?.title}]})).values());return Nl.createPortal(u.jsx(Zh,{sources:L,citationNumber:w},`citation-${w}-${T}`),T,`citation-${w}-${M}`)}),v]})}function ln({...e}){return u.jsx(Ot.Root,{"data-slot":"dialog",...e})}function em({...e}){return u.jsx(Ot.Portal,{"data-slot":"dialog-portal",...e})}function tm({className:e,...t}){return u.jsx(Ot.Overlay,{"data-slot":"dialog-overlay",className:re("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(em,{"data-slot":"dialog-portal",children:[u.jsx(tm,{}),u.jsxs(Ot.Content,{"data-slot":"dialog-content",className:re("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(Ot.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(ne.XIcon,{}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function un({className:e,...t}){return u.jsx("div",{"data-slot":"dialog-header",className:re("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:re("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function fn({className:e,...t}){return u.jsx(Ot.Title,{"data-slot":"dialog-title",className:re("text-lg leading-none font-semibold",e),...t})}function hn({className:e,...t}){return u.jsx(Ot.Description,{"data-slot":"dialog-description",className:re("text-muted-foreground text-sm",e),...t})}function mn({className:e,type:t,...n}){return u.jsx("input",{type:t,"data-slot":"input",className:re("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 nm({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(ne.EyeOff,{className:"h-4 w-4"}):u.jsx(ne.Eye,{className:"h-4 w-4"})})]})}),u.jsxs(dn,{children:[u.jsx(je,{type:"button",variant:"ghost",onClick:m,disabled:c,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:!o.trim()||c,children:c?"Submitting...":"Submit"})]})]})})})}function sm({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(ne.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(je,{type:"button",variant:"ghost",onClick:b,disabled:c,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function rm({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(ne.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(je,{type:"button",variant:"ghost",onClick:v,disabled:c,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:!o.trim()||!a||c,children:c?"Submitting...":"Submit"})]})]})})})}function im({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(ne.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(je,{type:"button",variant:"ghost",onClick:m,disabled:l,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:i.length!==r||l,children:l?"Submitting...":"Submit"})]})]})})})}function Us({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(ne.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(je,{type:"button",variant:"ghost",onClick:f,disabled:l,children:"Cancel"}),u.jsx(je,{type:"submit",disabled:!i.trim()||l,children:l?"Submitting...":"Submit"})]})]})})})}function om({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,F)=>{let $=N,B=null;switch(F.type){case"phone":$=M(N),$.trim()&&(B=T($));break;case"email":N.trim()&&(B=v(N));break;case"pin":$=N.replace(/\D/g,"").slice(0,6),$.trim()&&(B=w($));break}!B&&F.validation&&$.trim()&&(B=F.validation($)),l(X=>({...X,[A]:$})),d(X=>({...X,[A]:B||""}))},L=()=>{const A={};let N=!0;return s.forEach(F=>{const $=a[F.name]||"";let B=null;if(F.required&&!$.trim())B=`${F.label} is required`;else if($.trim()){switch(F.type){case"email":B=v($);break;case"phone":B=T($);break;case"pin":B=w($);break}!B&&F.validation&&(B=F.validation($))}B&&(A[F.name]=B,N=!1)}),d(A),N},D=async A=>{if(A.preventDefault(),!!L()){b(!0);try{const N={};s.forEach(F=>{const $=a[F.name]?.trim();$&&(F.type==="phone"?N[F.name]=$.replace(/\D/g,""):N[F.name]=$)}),r(N)}finally{b(!1)}}},O=()=>{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(ne.EyeOff,{className:"h-4 w-4"}):u.jsx(ne.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(ne.AlertCircle,{className:"h-3 w-3"}),c[A.name]]})]},A.name))}),u.jsxs(dn,{children:[u.jsx(je,{type:"button",variant:"ghost",onClick:O,disabled:p,children:i}),u.jsx(je,{type:"submit",disabled:p,children:p?"Submitting...":o})]})]})})})}const ml=h.createContext(void 0);function pl(){const e=h.useContext(ml);if(!e)throw new Error("useSecureModal must be used within a SecureModalProvider");return e}function gl({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(om,{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(nm,{...p});case"email":return u.jsx(sm,{...p});case"phone":return u.jsx(rm,{...p});case"pin":return u.jsx(im,{...p});case"ssn":return u.jsx(Us,{...p,title:t.title||"SSN Required",placeholder:t.placeholder||"XXX-XX-XXXX"});case"creditCard":return u.jsx(Us,{...p,title:t.title||"Credit Card Required",placeholder:t.placeholder||"XXXX XXXX XXXX XXXX",type:"text"});case"text":default:return u.jsx(Us,{...p})}},m=h.useMemo(()=>({showSecureModal:a,showSecureForm:l}),[a,l]);return u.jsxs(ml.Provider,{value:m,children:[e,f()]})}function am(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 lm(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 So(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),F=A[2].replace(/[.,;:!?]+$/,""),$=F.replace(/\/+$/,"");if(a.has($)||a.set($,F),i.has($)||i.set($,[]),i.get($).push(N),!l.has($))l.set($,N);else{const B=l.get($);N<B&&l.set($,N)}}for(const[N,F]of i.entries()){const $=l.get(N);for(const B of F)B!==$&&c.set(B,$)}for(const[N,F]of l.entries()){const $=a.get(N)||N;r.set(F,$),o.push({number:F,url:$})}}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,F,$)=>{const B=parseInt(F,10),X=$.replace(/\/+$/,""),K=c.get(B)||B;return l.has(X)||(l.set(X,K),r.has(K)||(r.set(K,$),o.push({number:K,url:$}))),`[${K}]`}),V=V.replace(/\[(\d+)\]/g,(N,F)=>{const $=parseInt(F,10);return`[${c.get($)||$}]`}),V}),w=[];for(const[C,V]of l.entries()){const A=a.get(C)||C,{baseUrl:N,anchor:F}=am(A),$=lm(A);w.push({url:A,baseUrl:N,numbers:[V],anchor:F,title:$})}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 L=new Map;for(const[C,V]of r.entries()){const A=M.get(C);A&&L.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)),O=Array.from(M.entries()).sort((C,V)=>V[0]-C[0]);let k=T.join("");for(const[C,V]of O){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:L,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 zs(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 cm({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:L,onStateChange:D,allowStateEdits:O=!0,sources:k,ragConfig:C,showCitations:V=!0,sensitiveParams:A,autoDetectSensitive:N=!1}){const F=M.replace(/\/+$/,""),{showSecureModal:$}=pl(),B=Eo({apiBaseUrl:F,tokenEndpoint:w,user:E,tools:d,safeTools:f,toolMetadata:p,sensitiveParams:A,autoDetectSensitive:N,agentId:v,agentName:T,state:L,onStateChange:D,allowStateEdits:O,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[X,K]=h.useState(c),[q,oe]=h.useState(i),[ye,Ge]=h.useState(600),[vt,et]=h.useState(!1),[G,$t]=h.useState(!1),[Ee,wt]=h.useState(!1),[Ce,Be]=h.useState({x:100,y:100}),[Lt,ae]=h.useState(!1),[pn,at]=h.useState({x:0,y:0}),[lt,gn]=h.useState(!1),Ue=h.useRef(null),St=h.useRef(null),[Tt,Re]=h.useState(""),[yn,ys]=h.useState(null),[Ft,Bt]=h.useState("Thinking..."),[ct,ut]=h.useState(new Set),[xs,_n]=h.useState(""),[He,bs]=h.useState([]),Xn=h.useRef(new Map),Ut=h.useRef(!1),xn=h.useRef(""),[le,bn]=h.useState(!1),[ze,we]=h.useState(!1),Ye=h.useMemo(()=>[...d,...f],[d,f]),_e=h.useMemo(()=>mr(Ye,p),[Ye,p]),zt=h.useMemo(()=>{const j=new Map,W=new Map(_e.map(_=>[_.name,_]));return Ye.forEach(_=>{const Z=_[$e];if(Z){const Q=W.get(Z);if(Q){j.set(Q.name,_);return}}const Y=_e.find(Q=>Q.name===_.name);Y&&j.set(Y.name,_)}),j},[Ye,_e]),jt=h.useMemo(()=>{const j=new Set,W=new Map(_e.map(_=>[_.name,_]));return f.forEach(_=>{const Z=_[$e];if(Z&&W.has(Z))j.add(Z);else{const Y=_e.find(Q=>Q.name===_.name);Y&&j.add(Y.name)}}),m&&Array.isArray(m)&&m.forEach(_=>{typeof _=="string"&&j.add(_)}),j},[f,_e,m]),Ct=["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&&K(JSON.parse(j));const W=localStorage.getItem("arcten-sidebar-width");W&&oe(parseInt(W));const _=localStorage.getItem("arcten-sidebar-height");_&&Ge(parseInt(_));const Z=localStorage.getItem("arcten-sidebar-detached");Z&&$t(JSON.parse(Z));const Y=localStorage.getItem("arcten-sidebar-position");if(Y){const Me=JSON.parse(Y),ie=50,Se=Math.max(ie-i,Math.min(Me.x,window.innerWidth-ie)),U=Math.max(0,Math.min(Me.y,window.innerHeight-ie));Be({x:Se,y:U})}const Q=localStorage.getItem("arcten-sidebar-minimized");Q&&wt(JSON.parse(Q)),gn(!0)}},[]),h.useMemo(()=>E,[E?.id]),h.useEffect(()=>{(async()=>{if(Ye.length===0)return;const W=Ye.map(_=>`${_.name}:${_.toString()}`).join("|");if(W!==xn.current&&!Ut.current){Ut.current=!0,xn.current=W;try{const _=Ye.map(Y=>({name:Y.name,code:Y.toString()})),Z=await fetch(`${F}/tools/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tools:_})});if(Z.ok){const Y=await Z.json();Y.tools&&Y.tools.forEach(Q=>{Xn.current.set(Q.name,Q)}),bs(Y.tools)}}catch(_){console.error("Failed to fetch tool descriptions:",_)}finally{Ut.current=!1}}})()},[Ye,F]),h.useEffect(()=>{Promise.resolve().then(()=>Wh).then(j=>{ys(()=>j.Response)})},[]),h.useEffect(()=>{const j=()=>{_n(window.location.pathname)};j(),window.addEventListener("popstate",j);const W=setInterval(j,500);return()=>{window.removeEventListener("popstate",j),clearInterval(W)}},[]);const{id:vn,messages:De,sendMessage:Pt,status:xe,error:Wn,stop:_t,addToolOutput:tt,setMessages:Zr,clientToken:wn,tokenError:Sn,conversations:Je,isLoadingConversations:dt,loadConversation:Xt,deleteConversation:Xe,startNewConversation:Ze}=B;h.useEffect(()=>{X&&St.current&&St.current.focus()},[X,De]),h.useEffect(()=>{const j=De[De.length-1];if(!j||j.role!=="assistant")return;const W=j.parts?.filter(_=>_.type?.startsWith("tool-")&&_.state==="input-available"&&typeof _.toolCallId=="string"&&_.input!==void 0)||[];for(const _ of W){const Z=_,Y=Z.type?.replace("tool-","")||"",Q=Z.toolCallId;if(jt.has(Y)){if(ct.has(Q))continue;ut(ie=>ie.has(Q)?ie:new Set(ie).add(Q)),(async()=>{try{const ie=zt.get(Y);if(!ie){console.warn(`[ArctenAgent] Tool ${Y} not found in toolsMap`),tt({toolCallId:Q,tool:Y,output:`Error: Tool ${Y} not found`}),ut(se=>{const Pe=new Set(se);return Pe.delete(Q),Pe});return}const Se=zs(Z.input),U=_e.find(se=>se.name===Y);let he;if(U&&U.jsonSchema?.properties){const Pe=Object.keys(U.jsonSchema.properties).map(fe=>Se[fe]);he=await ie(...Pe)}else he=await ie(...Object.values(Se));tt({toolCallId:Q,tool:Y,output:he}),ut(se=>{const Pe=new Set(se);return Pe.delete(Q),Pe})}catch(ie){console.error(`[ArctenAgent] Error executing safe tool ${Y}:`,ie),tt({toolCallId:Q,tool:Y,output:`Error: ${ie instanceof Error?ie.message:String(ie)}`}),ut(Se=>{const U=new Set(Se);return U.delete(Q),U})}})()}}},[De,jt,zt,_e,tt,ct]);function qn(){K(!0),localStorage.setItem("arcten-sidebar-expanded","true")}function Kn(){K(!1),localStorage.setItem("arcten-sidebar-expanded","false")}h.useEffect(()=>{},[X]),h.useEffect(()=>{Ue.current&&Ue.current.scrollIntoView({behavior:"smooth"})},[De]),h.useEffect(()=>{function j(W){W.key==="Escape"&&(xe==="streaming"||xe==="submitted")&&(W.preventDefault(),_t())}return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[xe,_t]);function nt(j){const W=Math.floor((Date.now()-j)/1e3);return W<60?"now":W<3600?`${Math.floor(W/60)}m`:W<86400?`${Math.floor(W/3600)}h`:`${Math.floor(W/86400)}d`}function At(){Ze(),we(!1)}function Tn(j){if(j.preventDefault(),!Tt.trim())return;(xe==="streaming"||xe==="submitted")&&_t();const W=Ct[Math.floor(Math.random()*Ct.length)]||"Thinking...";Bt(W),Pt({text:Tt}),Re("")}function Gn(j){const W=j.target.value;Re(W)}h.useEffect(()=>{if(!vt)return;function j(_){if(G){const Z=_.clientX-Ce.x,Y=_.clientY-Ce.y;Z>=a&&Z<=l&&oe(Z),Y>=400&&Y<=1e3&&Ge(Y)}else{const Z=window.innerWidth-_.clientX;Z>=a&&Z<=l&&oe(Z)}}function W(){et(!1),localStorage.setItem("arcten-sidebar-width",q.toString()),localStorage.setItem("arcten-sidebar-height",ye.toString())}return window.addEventListener("mousemove",j),window.addEventListener("mouseup",W),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",W)}},[vt,q,ye,G,Ce,a,l]);function ft(j){j.preventDefault(),et(!0)}function Wt(){$t(!0),wt(!1),localStorage.setItem("arcten-sidebar-detached","true"),localStorage.setItem("arcten-sidebar-minimized","false")}function vs(){$t(!1),wt(!1),localStorage.setItem("arcten-sidebar-detached","false"),localStorage.setItem("arcten-sidebar-minimized","false")}function qt(){wt(!Ee),localStorage.setItem("arcten-sidebar-minimized",JSON.stringify(!Ee))}function ws(j){G&&(ae(!0),at({x:j.clientX-Ce.x,y:j.clientY-Ce.y}))}return h.useEffect(()=>{if(!G)return;function j(){Be(W=>{const Z=window.innerWidth-50,Y=window.innerHeight-50,Q=50-q,Me=0,ie=Math.max(Q,Math.min(W.x,Z)),Se=Math.max(Me,Math.min(W.y,Y));if(ie!==W.x||Se!==W.y){const U={x:ie,y:Se};return localStorage.setItem("arcten-sidebar-position",JSON.stringify(U)),U}return W})}return window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[G,q]),h.useEffect(()=>{if(!Lt)return;function j(_){const Z=_.clientX-pn.x,Y=_.clientY-pn.y,Q=50,Me=window.innerWidth-Q,ie=window.innerHeight-Q,Se=Q-q,U=0,he=Math.max(Se,Math.min(Z,Me)),se=Math.max(U,Math.min(Y,ie));Be({x:he,y:se})}function W(){ae(!1),localStorage.setItem("arcten-sidebar-position",JSON.stringify(Ce))}return window.addEventListener("mousemove",j),window.addEventListener("mouseup",W),()=>{window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",W)}},[Lt,pn,Ce,q]),lt?Sn?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: ",Sn]})}):wn?u.jsx(id,{features:Oh,children:u.jsx(Qn,{id:"arcten-sidebar","data-theme":e,"data-layout":t,"data-model":n,initial:G?{opacity:0,scale:.95,filter:"blur(4px)"}:!1,animate:G?{opacity:1,scale:1,filter:"blur(0px)"}:{},transition:{duration:.2,ease:"easeOut"},className:`
|
|
11
|
+
${G?"fixed z-50 shadow-xl rounded-xl":"h-screen flex-shrink-0 relative rounded-l-2xl"}
|
|
12
12
|
${X?"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"}
|
|
13
|
-
${
|
|
13
|
+
${G?"border border-border":"border-l border-border"}
|
|
14
14
|
${X?"":"w-[30px]"}
|
|
15
|
-
`,style:X?H?{width:`${K}px`,height:Ee?"auto":`${ye}px`,left:`${Ce.x}px`,top:`${Ce.y}px`}:{width:`${K}px`}:void 0,onClick:X?void 0:Gn,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:zt,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:T=>{T.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:T=>{T.preventDefault(),T.stopPropagation(),ae(!0),ct({x:T.clientX-Ce.x,y:T.clientY-Ce.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:T=>{T.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?Je:void 0,children:[u.jsx("h2",{className:`text-base font-semibold ${H&&Ee?"cursor-pointer":""}`,onClick:H&&Ee?T=>{T.stopPropagation(),Yn()}:void 0,children:r}),u.jsxs("div",{className:"flex items-center gap-1",onClick:T=>T.stopPropagation(),children:[u.jsxs(mt,{children:[u.jsx(pt,{asChild:!0,children:u.jsx("button",{type:"button",className:se(Et({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:Hn,"aria-label":"New chat",children:u.jsx(te.Plus,{className:"h-4 w-4"})})}),u.jsx(gt,{children:"Start a new conversation"})]}),u.jsxs(mt,{children:[u.jsx(pt,{asChild:!0,children:u.jsx("button",{type:"button",className:se(Et({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:H?bn:ws,"aria-label":H?"Dock sidebar":"Float sidebar",children:H?u.jsx(te.Dock,{className:"h-4 w-4"}):u.jsx(te.PictureInPicture2,{className:"h-4 w-4"})})}),u.jsx(gt,{children:H?"Dock to sidebar":"Undock to floating window"})]}),u.jsxs(mt,{children:[u.jsx(pt,{asChild:!0,children:u.jsx("button",{type:"button",className:se(Et({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:H?Yn:it,"aria-label":H?Ee?"Maximize":"Minimize":"Close sidebar",children:H?Ee?u.jsx(te.Maximize2,{className:"h-4 w-4"}):u.jsx(te.Minimize2,{className:"h-4 w-4"}):u.jsx(te.X,{className:"h-4 w-4"})})}),u.jsx(gt,{children:H?Ee?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ee&&u.jsxs(u.Fragment,{children:[E&&He.length>0&&u.jsxs("div",{className:`border-b border-border ${xe?"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(je,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{pn(!xe)},children:xe?"Show less":"View all"})]}),u.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${xe?"flex-1 overflow-y-auto":""}`,children:He.slice(0,xe?void 0:3).map(T=>u.jsxs("div",{className:"group relative",children:[u.jsxs(Oh,{type:"button",className:se(Et({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>{Ue(T.chatId||T._id),pn(!1)},children:[u.jsx("span",{className:"text-xs truncate",children:T.title}),u.jsx("div",{className:"ml-2 flex items-center",children:u.jsx("span",{className:"text-xs text-muted-foreground group-hover:hidden",children:Pt(T.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:_=>{_.stopPropagation(),Ye(T._id)},"aria-label":"Delete conversation",children:u.jsx(te.X,{className:"h-3 w-3"})})]},T._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:Pe.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?"}),st.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:[(Bt?st:st.slice(0,10)).map(T=>u.jsxs(mt,{children:[u.jsx(pt,{asChild:!0,children:u.jsx(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{ke(T.sampleUsage),Tt.current?.focus()},children:T.friendlyName})}),u.jsx(gt,{children:u.jsxs("div",{className:"max-w-xs",children:[u.jsx("p",{className:"font-medium",children:T.description}),u.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[u.jsx("span",{className:"font-medium",children:"Example:"}),' "',T.sampleUsage,'"']}),T.paramCount>0&&u.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[u.jsx("span",{className:"font-medium",children:"Parameters:"})," ",T.params.join(", ")]})]})})]},T.name)),st.length>10&&!Bt&&u.jsxs(mt,{children:[u.jsx(pt,{asChild:!0,children:u.jsxs(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>dt(!0),children:["+",st.length-10," more"]})}),u.jsx(gt,{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:st.slice(10).map(T=>u.jsxs("div",{children:[u.jsxs("span",{className:"font-medium text-xs",children:[T.friendlyName,":"]}),u.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:T.description})]},T.name))}),u.jsx("p",{className:"text-xs text-muted-foreground mt-2 italic",children:"Click to show all tools"})]})})]}),Bt&&st.length>10&&u.jsx(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>dt(!1),children:"Show less"})]})})]}):u.jsxs(u.Fragment,{children:[Pe.map(T=>{const z=T.parts.filter(W=>W.type==="text").map(W=>W.text).join("");let Z=T.parts;T.role==="assistant"&&T.parts.some(me=>me.timestamp)&&(Z=[...T.parts].sort((me,ne)=>{const Se=me.timestamp||0,de=ne.timestamp||0;return Se-de}));let Y=[],J=new Map,De=[],re,ue=!0;if(T.role==="assistant"){const W=Z.filter(de=>de.type==="text"&&de.text),me=[],ne=[];W.forEach(de=>{const{citations:Ze,citationMap:ve,groupedCitations:g,referencesText:y}=vo(de.text);Y.push(...Ze),me.push(ve),g&&ne.push(...g),y&&(re=y)}),me.forEach(de=>{de.forEach((Ze,ve)=>{J.has(ve)||J.set(ve,Ze)})}),De=Array.from(new Map(ne.map(de=>[de.url,de])).values()).sort((de,Ze)=>(de.numbers[0]||0)-(Ze.numbers[0]||0)),ue=!(Ne==="streaming"&&T.id===Pe.at(-1)?.id)}return u.jsx("div",{className:`${T.role==="user"?"flex justify-end":"w-full"}`,children:u.jsx("div",{className:`${T.role==="user"?"max-w-[85%] text-right":"w-full"}`,children:T.role==="user"?u.jsx($h,{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:z}):u.jsx("div",{className:"space-y-2",children:Z.map((W,me)=>{if(W.type?.startsWith("tool-")){const ne=W.type?.replace("tool-","")||"",Se=Re.find(ve=>ve.name===ne),de=W.state==="input-available",Ze=W.state==="output-available";if(de&&Ke.has(ne),de){if(Ke.has(ne))return null;const ve=zs(W.input);return u.jsx(ts,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:u.jsx(Lh,{toolName:ne,description:Se?.description||"",args:ve,onApprove:async()=>{if(Lt.has(W.toolCallId))return;nt(y=>new Set(y).add(W.toolCallId));const g=gn.get(ne);if(g)try{const y=await g(...Object.values(ve));rt({toolCallId:W.toolCallId,tool:ne,output:y})}catch(y){rt({toolCallId:W.toolCallId,tool:ne,output:`Error: ${y}`})}},onDeny:async()=>{Lt.has(W.toolCallId)||(nt(g=>new Set(g).add(W.toolCallId)),rt({toolCallId:W.toolCallId,tool:ne,output:"User denied tool execution"}))}})},`${W.toolCallId}-${me}`)}else if(Ze){const ve=W.output==="User denied tool execution",g=zs(W.input);return u.jsx(Fh,{toolName:ne,args:g,isDenied:ve,isSafe:Ke.has(ne)},`${W.toolCallId}-${me}`)}return null}if(W.type==="text"&&W.text&&hn){const{processedText:ne}=vo(W.text),ve=!Z.slice(me+1).some(g=>g.type==="text"&&g.text)&&ue&&J.size>0;return u.jsx(Zh,{text:ne,citations:Y,citationMap:J,groupedCitations:ve?De:void 0,referencesText:ve?re:void 0,ResponseComponent:hn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:V,showReferences:ve},`${T.id}-${me}`)}return W.type==="reasoning"&&W.text?u.jsxs(cl,{className:"w-full",isStreaming:Ne==="streaming"&&me===T.parts.length-1&&T.id===Pe.at(-1)?.id,children:[u.jsx(ul,{}),u.jsx(dl,{children:W.text})]},`${T.id}-${me}`):null})})})},T.id)}),u.jsx("div",{ref:Be})]})}),Xn&&u.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Xn.message]}),u.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[u.jsx(sd,{mode:"wait",children:(Ne==="streaming"||Ne==="submitted")&&u.jsxs(ts,{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(ts,{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:$t})]})}),u.jsxs("form",{onSubmit:xn,className:"relative",children:[u.jsx(Ao,{ref:Tt,value:jt,onChange:ht,placeholder:"Ask anything..",className:"w-full pr-12 resize-none border border-border rounded-xl px-4 py-3",minHeight:24,maxHeight:200,onKeyDown:T=>{T.key==="Enter"&&!T.shiftKey&&(T.preventDefault(),xn(T))}}),Ne==="streaming"||Ne==="submitted"?u.jsxs(mt,{children:[u.jsx(pt,{asChild:!0,children:u.jsx("button",{type:"button",className:se(Et({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:Ut,children:u.jsx(te.Square,{className:"h-4 w-4"})})}),u.jsxs(gt,{children:[u.jsx(ni,{children:"Escape"})," to stop"]})]}):u.jsxs(mt,{children:[u.jsx(pt,{asChild:!0,children:u.jsx("button",{type:"submit",className:se(Et({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!jt.trim(),children:u.jsx(te.ArrowRight,{className:"h-4 w-4"})})}),u.jsxs(gt,{children:[u.jsx(ni,{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(te.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 cm(e){return u.jsx(ml,{children:u.jsx(lm,{...e})})}function um(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 x=await p.json();c.current=x.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 x=await fetch(`${t}/generate`,{method:"POST",headers:p,body:JSON.stringify(m)});if(!x.ok){const S=await x.json().catch(()=>({}));throw new Error(S.error||`HTTP ${x.status}`)}return await x.json()}catch(p){const x=p instanceof Error?p.message:String(p);throw l(x),p}finally{i(!1)}},[t]),f=h.useCallback(async(m,p)=>{i(!0),l(null);try{const x={"Content-Type":"application/json"};c.current&&(x.Authorization=`Bearer ${c.current}`);const b=await fetch(`${t}/generate/stream`,{method:"POST",headers:x,body:JSON.stringify(m)});if(!b.ok){const E=await b.json().catch(()=>({}));throw new Error(E.error||`HTTP ${b.status}`)}const S=b.body?.getReader();if(!S)throw new Error("No response body");const v=new TextDecoder;let M=null;for(;;){const{done:E,value:L}=await S.read();if(E)break;const O=v.decode(L,{stream:!0}).split(`
|
|
16
|
-
`).filter(k=>k.startsWith("data: "));for(const k of O){const
|
|
15
|
+
`,style:X?G?{width:`${q}px`,height:Ee?"auto":`${ye}px`,left:`${Ce.x}px`,top:`${Ce.y}px`}:{width:`${q}px`}:void 0,onClick:X?void 0:qn,children:X?u.jsxs(u.Fragment,{children:[!G&&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:ft,children:u.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-3 -translate-x-1"})}),G&&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(),ae(!0),at({x:j.clientX-Ce.x,y:j.clientY-Ce.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 ${G?"cursor-move":""}`,onMouseDown:G?ws:void 0,children:[u.jsx("h2",{className:`text-base font-semibold ${G&&Ee?"cursor-pointer":""}`,onClick:G&&Ee?j=>{j.stopPropagation(),qt()}:void 0,children:r}),u.jsxs("div",{className:"flex items-center gap-1",onClick:j=>j.stopPropagation(),children:[u.jsxs(ht,{children:[u.jsx(mt,{asChild:!0,children:u.jsx("button",{type:"button",className:re(kt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:At,"aria-label":"New chat",children:u.jsx(ne.Plus,{className:"h-4 w-4"})})}),u.jsx(pt,{children:"Start a new conversation"})]}),u.jsxs(ht,{children:[u.jsx(mt,{asChild:!0,children:u.jsx("button",{type:"button",className:re(kt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:G?vs:Wt,"aria-label":G?"Dock sidebar":"Float sidebar",children:G?u.jsx(ne.Dock,{className:"h-4 w-4"}):u.jsx(ne.PictureInPicture2,{className:"h-4 w-4"})})}),u.jsx(pt,{children:G?"Dock to sidebar":"Undock to floating window"})]}),u.jsxs(ht,{children:[u.jsx(mt,{asChild:!0,children:u.jsx("button",{type:"button",className:re(kt({variant:"ghost",size:"icon"}),"h-8 w-8"),onClick:G?qt:Kn,"aria-label":G?Ee?"Maximize":"Minimize":"Close sidebar",children:G?Ee?u.jsx(ne.Maximize2,{className:"h-4 w-4"}):u.jsx(ne.Minimize2,{className:"h-4 w-4"}):u.jsx(ne.X,{className:"h-4 w-4"})})}),u.jsx(pt,{children:G?Ee?"Maximize window":"Minimize to header":"Close the chat"})]})]})]}),!Ee&&u.jsxs(u.Fragment,{children:[E&&Je.length>0&&u.jsxs("div",{className:`border-b border-border ${ze?"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(je,{variant:"ghost",className:"h-auto px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{we(!ze)},children:ze?"Show less":"View all"})]}),u.jsx("div",{className:`px-2 pb-2 space-y-0.5 ${ze?"flex-1 overflow-y-auto":""}`,children:Je.slice(0,ze?void 0:3).map(j=>u.jsxs("div",{className:"group relative",children:[u.jsxs($h,{type:"button",className:re(kt({variant:"ghost"}),"w-full justify-between h-auto py-1 px-3 font-normal active:scale-[0.99]"),onClick:()=>{Xt(j.chatId||j._id),we(!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:nt(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:W=>{W.stopPropagation(),Xe(j._id)},"aria-label":"Delete conversation",children:u.jsx(ne.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:De.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:[(le?He:He.slice(0,10)).map(j=>u.jsxs(ht,{children:[u.jsx(mt,{asChild:!0,children:u.jsx(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>{Re(j.sampleUsage),St.current?.focus()},children:j.friendlyName})}),u.jsx(pt,{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)),He.length>10&&!le&&u.jsxs(ht,{children:[u.jsx(mt,{asChild:!0,children:u.jsxs(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>bn(!0),children:["+",He.length-10," more"]})}),u.jsx(pt,{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(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"})]})})]}),le&&He.length>10&&u.jsx(Cs,{variant:"secondary",className:"cursor-pointer text-xs px-2 py-1 hover:bg-stone-200 dark:hover:bg-stone-700 transition-colors",onClick:()=>bn(!1),children:"Show less"})]})})]}):u.jsxs(u.Fragment,{children:[De.map(j=>{const _=j.parts.filter(U=>U.type==="text").map(U=>U.text).join("");let Z=j.parts;j.role==="assistant"&&j.parts.some(he=>he.timestamp)&&(Z=[...j.parts].sort((he,se)=>{const Pe=he.timestamp||0,fe=se.timestamp||0;return Pe-fe}));let Y=[],Q=new Map,Me=[],ie,Se=!0;if(j.role==="assistant"){const U=Z.filter(fe=>fe.type==="text"&&fe.text),he=[],se=[];U.forEach(fe=>{const{citations:Ve,citationMap:be,groupedCitations:ke,referencesText:g}=So(fe.text);Y.push(...Ve),he.push(be),ke&&se.push(...ke),g&&(ie=g)}),he.forEach(fe=>{fe.forEach((Ve,be)=>{Q.has(be)||Q.set(be,Ve)})}),Me=Array.from(new Map(se.map(fe=>[fe.url,fe])).values()).sort((fe,Ve)=>(fe.numbers[0]||0)-(Ve.numbers[0]||0)),Se=!(xe==="streaming"&&j.id===De.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(Lh,{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:_}):u.jsx("div",{className:"space-y-2",children:Z.map((U,he)=>{if(U.type?.startsWith("tool-")){const se=U.type?.replace("tool-","")||"",Pe=_e.find(be=>be.name===se),fe=U.state==="input-available",Ve=U.state==="output-available";if(fe&&jt.has(se),fe){if(jt.has(se))return null;const be=zs(U.input);return u.jsx(Qn,{initial:{opacity:0,y:10,filter:"blur(4px)"},animate:{opacity:1,y:0,filter:"blur(0px)"},transition:{duration:.3,ease:"easeOut"},children:u.jsx(Fh,{toolName:se,description:Pe?.description||"",args:be,onApprove:async()=>{if(ct.has(U.toolCallId))return;ut(g=>new Set(g).add(U.toolCallId));const ke=zt.get(se);if(ke)try{const g=await ke(...Object.values(be));tt({toolCallId:U.toolCallId,tool:se,output:g})}catch(g){tt({toolCallId:U.toolCallId,tool:se,output:`Error: ${g}`})}},onDeny:async()=>{ct.has(U.toolCallId)||(ut(ke=>new Set(ke).add(U.toolCallId)),tt({toolCallId:U.toolCallId,tool:se,output:"User denied tool execution"}))}})},`${U.toolCallId}-${he}`)}else if(Ve){const be=U.output==="User denied tool execution",ke=zs(U.input);return u.jsx(Bh,{toolName:se,args:ke,isDenied:be,isSafe:jt.has(se)},`${U.toolCallId}-${he}`)}return null}if(U.type==="text"&&U.text&&yn){const{processedText:se}=So(U.text),be=!Z.slice(he+1).some(ke=>ke.type==="text"&&ke.text)&&Se&&Q.size>0;return u.jsx(Qh,{text:se,citations:Y,citationMap:Q,groupedCitations:be?Me:void 0,referencesText:be?ie:void 0,ResponseComponent:yn,className:"text-sm prose prose-sm dark:prose-invert max-w-none",showCitations:V,showReferences:be},`${j.id}-${he}`)}return U.type==="reasoning"&&U.text?u.jsxs(dl,{className:"w-full",isStreaming:xe==="streaming"&&he===j.parts.length-1&&j.id===De.at(-1)?.id,children:[u.jsx(fl,{}),u.jsx(hl,{children:U.text})]},`${j.id}-${he}`):null})})})},j.id)}),u.jsx("div",{ref:Ue})]})}),Wn&&u.jsxs("div",{className:"px-4 py-2 bg-destructive/10 text-destructive text-xs",children:["Error: ",Wn.message]}),u.jsxs("div",{className:"p-4 border-t border-border relative overflow-visible",children:[u.jsx(rd,{mode:"wait",children:(xe==="streaming"||xe==="submitted")&&u.jsxs(Qn,{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(Qn,{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:Ft})]})}),u.jsxs("form",{onSubmit:Tn,className:"relative",children:[u.jsx(Mo,{ref:St,value:Tt,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(),Tn(j))}}),xe==="streaming"||xe==="submitted"?u.jsxs(ht,{children:[u.jsx(mt,{asChild:!0,children:u.jsx("button",{type:"button",className:re(kt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),onClick:_t,children:u.jsx(ne.Square,{className:"h-4 w-4"})})}),u.jsxs(pt,{children:[u.jsx(ri,{children:"Escape"})," to stop"]})]}):u.jsxs(ht,{children:[u.jsx(mt,{asChild:!0,children:u.jsx("button",{type:"submit",className:re(kt({variant:"ghost",size:"icon"}),"absolute top-1/2 -translate-y-1/2 right-2 h-8 w-8"),disabled:!Tt.trim(),children:u.jsx(ne.ArrowRight,{className:"h-4 w-4"})})}),u.jsxs(pt,{children:[u.jsx(ri,{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(ne.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 um(e){return u.jsx(gl,{children:u.jsx(cm,{...e})})}function dm(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:L}=await T.read();if(E)break;const O=w.decode(L,{stream:!0}).split(`
|
|
16
|
+
`).filter(k=>k.startsWith("data: "));for(const k of O){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=$e;exports.ArctenAgent=um;exports.SecureModalProvider=gl;exports.extractToolsMetadata=mr;exports.preserveToolName=Dl;exports.useAgent=Eo;exports.useGenerate=dm;exports.useSecureModal=pl;
|