@mastra/deployer-cloud 1.60.1-alpha.0 → 1.61.0-alpha.1
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/CHANGELOG.md +8 -0
- package/dist/studio/assets/{core-AeuPbg-Y.js → core-CEXVmTJJ.js} +1 -1
- package/dist/studio/assets/{index-Ct0rH7x1.js → index-DroxhNw9.js} +2 -2
- package/dist/studio/assets/{main-BTdzbyJi.js → main-mGYykXm8.js} +4 -4
- package/dist/studio/index.html +1 -1
- package/package.json +4 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-CEXVmTJJ.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{_ as Da}from"./preload-helper-PPVm8Dsz.js";function XWt(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const a=Object.getOwnPropertyDescriptor(r,s);a&&Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var fj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var LK={exports:{}},GA={};var P$e;function JWt(){if(P$e)return GA;P$e=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,a){var i=null;if(a!==void 0&&(i=""+a),s.key!==void 0&&(i=""+s.key),"key"in s){a={};for(var l in s)l!=="key"&&(a[l]=s[l])}else a=s;return s=a.ref,{$$typeof:e,type:r,key:i,ref:s!==void 0?s:null,props:a}}return GA.Fragment=t,GA.jsx=n,GA.jsxs=n,GA}var $$e;function eZt(){return $$e||($$e=1,LK.exports=JWt()),LK.exports}var o=eZt(),FK={exports:{}},Vr={},M$e;function tZt(){if(M$e)return Vr;M$e=1;var e={env:{}};var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),h=Symbol.iterator;function m(q){return q===null||typeof q!="object"?null:(q=h&&q[h]||q["@@iterator"],typeof q=="function"?q:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(q,$,z){this.props=q,this.context=$,this.refs=b,this.updater=z||v}x.prototype.isReactComponent={},x.prototype.setState=function(q,$){if(typeof q!="object"&&typeof q!="function"&&q!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,q,$,"setState")},x.prototype.forceUpdate=function(q){this.updater.enqueueForceUpdate(this,q,"forceUpdate")};function S(){}S.prototype=x.prototype;function k(q,$,z){this.props=q,this.context=$,this.refs=b,this.updater=z||v}var _=k.prototype=new S;_.constructor=k,y(_,x.prototype),_.isPureReactComponent=!0;var C=Array.isArray;function E(){}var T={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(q,$,z){var Z=z.ref;return{$$typeof:t,type:q,key:$,ref:Z!==void 0?Z:null,props:z}}function A(q,$){return I(q.type,$,q.props)}function R(q){return typeof q=="object"&&q!==null&&q.$$typeof===t}function L(q){var $={"=":"=0",":":"=2"};return"$"+q.replace(/[=:]/g,function(z){return $[z]})}var D=/\/+/g;function F(q,$){return typeof q=="object"&&q!==null&&q.key!=null?L(""+q.key):$.toString(36)}function H(q){switch(q.status){case"fulfilled":return q.value;case"rejected":throw q.reason;default:switch(typeof q.status=="string"?q.then(E,E):(q.status="pending",q.then(function($){q.status==="pending"&&(q.status="fulfilled",q.value=$)},function($){q.status==="pending"&&(q.status="rejected",q.reason=$)})),q.status){case"fulfilled":return q.value;case"rejected":throw q.reason}}throw q}function B(q,$,z,Z,K){var ne=typeof q;(ne==="undefined"||ne==="boolean")&&(q=null);var ee=!1;if(q===null)ee=!0;else switch(ne){case"bigint":case"string":case"number":ee=!0;break;case"object":switch(q.$$typeof){case t:case n:ee=!0;break;case f:return ee=q._init,B(ee(q._payload),$,z,Z,K)}}if(ee)return K=K(q),ee=Z===""?"."+F(q,0):Z,C(K)?(z="",ee!=null&&(z=ee.replace(D,"$&/")+"/"),B(K,$,z,"",function(pe){return pe})):K!=null&&(R(K)&&(K=A(K,z+(K.key==null||q&&q.key===K.key?"":(""+K.key).replace(D,"$&/")+"/")+ee)),$.push(K)),1;ee=0;var J=Z===""?".":Z+":";if(C(q))for(var ae=0;ae<q.length;ae++)Z=q[ae],ne=J+F(Z,ae),ee+=B(Z,$,z,ne,K);else if(ae=m(q),typeof ae=="function")for(q=ae.call(q),ae=0;!(Z=q.next()).done;)Z=Z.value,ne=J+F(Z,ae++),ee+=B(Z,$,z,ne,K);else if(ne==="object"){if(typeof q.then=="function")return B(H(q),$,z,Z,K);throw $=String(q),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(q).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return ee}function U(q,$,z){if(q==null)return q;var Z=[],K=0;return B(q,Z,"","",function(ne){return $.call(z,ne,K++)}),Z}function V(q){if(q._status===-1){var $=q._result;$=$(),$.then(function(z){(q._status===0||q._status===-1)&&(q._status=1,q._result=z)},function(z){(q._status===0||q._status===-1)&&(q._status=2,q._result=z)}),q._status===-1&&(q._status=0,q._result=$)}if(q._status===1)return q._result.default;throw q._result}var M=typeof reportError=="function"?reportError:function(q){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof q=="object"&&q!==null&&typeof q.message=="string"?String(q.message):String(q),error:q});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",q);return}console.error(q)},G={map:U,forEach:function(q,$,z){U(q,function(){$.apply(this,arguments)},z)},count:function(q){var $=0;return U(q,function(){$++}),$},toArray:function(q){return U(q,function($){return $})||[]},only:function(q){if(!R(q))throw Error("React.Children.only expected to receive a single React element child.");return q}};return Vr.Activity=p,Vr.Children=G,Vr.Component=x,Vr.Fragment=r,Vr.Profiler=a,Vr.PureComponent=k,Vr.StrictMode=s,Vr.Suspense=u,Vr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,Vr.__COMPILER_RUNTIME={__proto__:null,c:function(q){return T.H.useMemoCache(q)}},Vr.cache=function(q){return function(){return q.apply(null,arguments)}},Vr.cacheSignal=function(){return null},Vr.cloneElement=function(q,$,z){if(q==null)throw Error("The argument must be a React element, but you passed "+q+".");var Z=y({},q.props),K=q.key;if($!=null)for(ne in $.key!==void 0&&(K=""+$.key),$)!N.call($,ne)||ne==="key"||ne==="__self"||ne==="__source"||ne==="ref"&&$.ref===void 0||(Z[ne]=$[ne]);var ne=arguments.length-2;if(ne===1)Z.children=z;else if(1<ne){for(var ee=Array(ne),J=0;J<ne;J++)ee[J]=arguments[J+2];Z.children=ee}return I(q.type,K,Z)},Vr.createContext=function(q){return q={$$typeof:l,_currentValue:q,_currentValue2:q,_threadCount:0,Provider:null,Consumer:null},q.Provider=q,q.Consumer={$$typeof:i,_context:q},q},Vr.createElement=function(q,$,z){var Z,K={},ne=null;if($!=null)for(Z in $.key!==void 0&&(ne=""+$.key),$)N.call($,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(K[Z]=$[Z]);var ee=arguments.length-2;if(ee===1)K.children=z;else if(1<ee){for(var J=Array(ee),ae=0;ae<ee;ae++)J[ae]=arguments[ae+2];K.children=J}if(q&&q.defaultProps)for(Z in ee=q.defaultProps,ee)K[Z]===void 0&&(K[Z]=ee[Z]);return I(q,ne,K)},Vr.createRef=function(){return{current:null}},Vr.forwardRef=function(q){return{$$typeof:c,render:q}},Vr.isValidElement=R,Vr.lazy=function(q){return{$$typeof:f,_payload:{_status:-1,_result:q},_init:V}},Vr.memo=function(q,$){return{$$typeof:d,type:q,compare:$===void 0?null:$}},Vr.startTransition=function(q){var $=T.T,z={};T.T=z;try{var Z=q(),K=T.S;K!==null&&K(z,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(E,M)}catch(ne){M(ne)}finally{$!==null&&z.types!==null&&($.types=z.types),T.T=$}},Vr.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},Vr.use=function(q){return T.H.use(q)},Vr.useActionState=function(q,$,z){return T.H.useActionState(q,$,z)},Vr.useCallback=function(q,$){return T.H.useCallback(q,$)},Vr.useContext=function(q){return T.H.useContext(q)},Vr.useDebugValue=function(){},Vr.useDeferredValue=function(q,$){return T.H.useDeferredValue(q,$)},Vr.useEffect=function(q,$){return T.H.useEffect(q,$)},Vr.useEffectEvent=function(q){return T.H.useEffectEvent(q)},Vr.useId=function(){return T.H.useId()},Vr.useImperativeHandle=function(q,$,z){return T.H.useImperativeHandle(q,$,z)},Vr.useInsertionEffect=function(q,$){return T.H.useInsertionEffect(q,$)},Vr.useLayoutEffect=function(q,$){return T.H.useLayoutEffect(q,$)},Vr.useMemo=function(q,$){return T.H.useMemo(q,$)},Vr.useOptimistic=function(q,$){return T.H.useOptimistic(q,$)},Vr.useReducer=function(q,$,z){return T.H.useReducer(q,$,z)},Vr.useRef=function(q){return T.H.useRef(q)},Vr.useState=function(q){return T.H.useState(q)},Vr.useSyncExternalStore=function(q,$,z){return T.H.useSyncExternalStore(q,$,z)},Vr.useTransition=function(){return T.H.useTransition()},Vr.version="19.2.7",Vr}var D$e;function LN(){return D$e||(D$e=1,FK.exports=tZt()),FK.exports}var g=LN();const ze=Bl(g),FN=XWt({__proto__:null,default:ze},[g]);var zK={exports:{}},QA={},BK={exports:{}},UK={};var L$e;function nZt(){return L$e||(L$e=1,(function(e){function t(H,B){var U=H.length;H.push(B);e:for(;0<U;){var V=U-1>>>1,M=H[V];if(0<s(M,B))H[V]=B,H[U]=M,U=V;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var B=H[0],U=H.pop();if(U!==B){H[0]=U;e:for(var V=0,M=H.length,G=M>>>1;V<G;){var q=2*(V+1)-1,$=H[q],z=q+1,Z=H[z];if(0>s($,U))z<M&&0>s(Z,$)?(H[V]=Z,H[z]=U,V=z):(H[V]=$,H[q]=U,V=q);else if(z<M&&0>s(Z,U))H[V]=Z,H[z]=U,V=z;else break e}}return B}function s(H,B){var U=H.sortIndex-B.sortIndex;return U!==0?U:H.id-B.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var i=Date,l=i.now();e.unstable_now=function(){return i.now()-l}}var c=[],u=[],d=1,f=null,p=3,h=!1,m=!1,v=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function k(H){for(var B=n(u);B!==null;){if(B.callback===null)r(u);else if(B.startTime<=H)r(u),B.sortIndex=B.expirationTime,t(c,B);else break;B=n(u)}}function _(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,C||(C=!0,R());else{var B=n(u);B!==null&&F(_,B.startTime-H)}}var C=!1,E=-1,T=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<T)}function A(){if(y=!1,C){var H=e.unstable_now();N=H;var B=!0;try{e:{m=!1,v&&(v=!1,x(E),E=-1),h=!0;var U=p;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var V=f.callback;if(typeof V=="function"){f.callback=null,p=f.priorityLevel;var M=V(f.expirationTime<=H);if(H=e.unstable_now(),typeof M=="function"){f.callback=M,k(H),B=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)B=!0;else{var G=n(u);G!==null&&F(_,G.startTime-H),B=!1}}break e}finally{f=null,p=U,h=!1}B=void 0}}finally{B?R():C=!1}}}var R;if(typeof S=="function")R=function(){S(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,D=L.port2;L.port1.onmessage=A,R=function(){D.postMessage(null)}}else R=function(){b(A,0)};function F(H,B){E=b(function(){H(e.unstable_now())},B)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):T=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(H){switch(p){case 1:case 2:case 3:var B=3;break;default:B=p}var U=p;p=B;try{return H()}finally{p=U}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,B){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var U=p;p=H;try{return B()}finally{p=U}},e.unstable_scheduleCallback=function(H,B,U){var V=e.unstable_now();switch(typeof U=="object"&&U!==null?(U=U.delay,U=typeof U=="number"&&0<U?V+U:V):U=V,H){case 1:var M=-1;break;case 2:M=250;break;case 5:M=1073741823;break;case 4:M=1e4;break;default:M=5e3}return M=U+M,H={id:d++,callback:B,priorityLevel:H,startTime:U,expirationTime:M,sortIndex:-1},U>V?(H.sortIndex=U,t(u,H),n(c)===null&&H===n(u)&&(v?(x(E),E=-1):v=!0,F(_,U-V))):(H.sortIndex=M,t(c,H),m||h||(m=!0,C||(C=!0,R()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var B=p;return function(){var U=p;p=B;try{return H.apply(this,arguments)}finally{p=U}}}})(UK)),UK}var F$e;function rZt(){return F$e||(F$e=1,BK.exports=nZt()),BK.exports}var VK={exports:{}},wu={};var z$e;function sZt(){if(z$e)return wu;z$e=1;var e=LN();function t(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function a(c,u,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:f==null?null:""+f,children:c,containerInfo:u,implementation:d}}var i=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return wu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,wu.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return a(c,u,null,d)},wu.flushSync=function(c){var u=i.T,d=r.p;try{if(i.T=null,r.p=2,c)return c()}finally{i.T=u,r.p=d,r.d.f()}},wu.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,r.d.C(c,u))},wu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},wu.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),p=typeof u.integrity=="string"?u.integrity:void 0,h=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:f,integrity:p,fetchPriority:h}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:p,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},wu.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var d=l(u.as,u.crossOrigin);r.d.M(c,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&r.d.M(c)},wu.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin);r.d.L(c,d,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},wu.preloadModule=function(c,u){if(typeof c=="string")if(u){var d=l(u.as,u.crossOrigin);r.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else r.d.m(c)},wu.requestFormReset=function(c){r.d.r(c)},wu.unstable_batchedUpdates=function(c,u){return c(u)},wu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},wu.useFormStatus=function(){return i.H.useHostTransitionStatus()},wu.version="19.2.7",wu}var B$e;function nlt(){if(B$e)return VK.exports;B$e=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),VK.exports=sZt(),VK.exports}var U$e;function aZt(){if(U$e)return QA;U$e=1;var e={env:{}};var t=rZt(),n=LN(),r=nlt();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)O+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+w+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(w){return!(!w||w.nodeType!==1&&w.nodeType!==9&&w.nodeType!==11)}function i(w){var O=w,j=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(j=O.return),w=O.return;while(w)}return O.tag===3?j:null}function l(w){if(w.tag===13){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function c(w){if(w.tag===31){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function u(w){if(i(w)!==w)throw Error(s(188))}function d(w){var O=w.alternate;if(!O){if(O=i(w),O===null)throw Error(s(188));return O!==w?null:w}for(var j=w,P=O;;){var W=j.return;if(W===null)break;var Q=W.alternate;if(Q===null){if(P=W.return,P!==null){j=P;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===j)return u(W),w;if(Q===P)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(j.return!==P.return)j=W,P=Q;else{for(var oe=!1,Se=W.child;Se;){if(Se===j){oe=!0,j=W,P=Q;break}if(Se===P){oe=!0,P=W,j=Q;break}Se=Se.sibling}if(!oe){for(Se=Q.child;Se;){if(Se===j){oe=!0,j=Q,P=W;break}if(Se===P){oe=!0,P=Q,j=W;break}Se=Se.sibling}if(!oe)throw Error(s(189))}}if(j.alternate!==P)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?w:O}function f(w){var O=w.tag;if(O===5||O===26||O===27||O===6)return w;for(w=w.child;w!==null;){if(O=f(w),O!==null)return O;w=w.sibling}return null}var p=Object.assign,h=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),k=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),R=Symbol.iterator;function L(w){return w===null||typeof w!="object"?null:(w=R&&w[R]||w["@@iterator"],typeof w=="function"?w:null)}var D=Symbol.for("react.client.reference");function F(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===D?null:w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){case y:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case C:return"Suspense";case E:return"SuspenseList";case I:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case v:return"Portal";case k:return w.displayName||"Context";case S:return(w._context.displayName||"Context")+".Consumer";case _:var O=w.render;return w=w.displayName,w||(w=O.displayName||O.name||"",w=w!==""?"ForwardRef("+w+")":"ForwardRef"),w;case T:return O=w.displayName||null,O!==null?O:F(w.type)||"Memo";case N:O=w._payload,w=w._init;try{return F(w(O))}catch{}}return null}var H=Array.isArray,B=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,U=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},M=[],G=-1;function q(w){return{current:w}}function $(w){0>G||(w.current=M[G],M[G]=null,G--)}function z(w,O){G++,M[G]=w.current,w.current=O}var Z=q(null),K=q(null),ne=q(null),ee=q(null);function J(w,O){switch(z(ne,O),z(K,w),z(Z,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?r$e(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=r$e(O),w=s$e(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(Z),z(Z,w)}function ae(){$(Z),$(K),$(ne)}function pe(w){w.memoizedState!==null&&z(ee,w);var O=Z.current,j=s$e(O,w.type);O!==j&&(z(K,w),z(Z,j))}function Y(w){K.current===w&&($(Z),$(K)),ee.current===w&&($(ee),qA._currentValue=V)}var te,ue;function fe(w){if(te===void 0)try{throw Error()}catch(j){var O=j.stack.trim().match(/\n( *(at )?)/);te=O&&O[1]||"",ue=-1<j.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+te+w+ue}var ce=!1;function me(w,O){if(!w||ce)return"";ce=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var P={DetermineComponentFrameRoot:function(){try{if(O){var jt=function(){throw Error()};if(Object.defineProperty(jt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(jt,[])}catch(ht){var ut=ht}Reflect.construct(w,[],jt)}else{try{jt.call()}catch(ht){ut=ht}w.call(jt.prototype)}}else{try{throw Error()}catch(ht){ut=ht}(jt=w())&&typeof jt.catch=="function"&&jt.catch(function(){})}}catch(ht){if(ht&&ut&&typeof ht.stack=="string")return[ht.stack,ut.stack]}return[null,null]}};P.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor(P.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty(P.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=P.DetermineComponentFrameRoot(),oe=Q[0],Se=Q[1];if(oe&&Se){var Ue=oe.split(`
|
|
@@ -194,7 +194,7 @@ Error message: ${lht(n)}`,cause:n}),this[vht]=!0,this.value=t}static isInstance(
|
|
|
194
194
|
`)}})}});Vs(ve(),CO.optional());function Swn(e){return e.type.startsWith("tool-")}function kwn(e){return e.type==="dynamic-tool"}function o7(e){return Swn(e)||kwn(e)}UD({prefix:"aitxt",size:24});Vs(ve(),CO.optional());UD({prefix:"aiobj",size:24});UD({prefix:"aiobj",size:24});function bLe(e){return e.some(t=>!(t.type==="text"&&t.text===""))?e.filter(t=>t.type==="text"?t.text!=="":!0):e}function hwe(e){const t=e.content.metadata?.signal;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=t.type;return typeof n=="string"?n:e.type}return e.type}function Own(e){const t=e.content.metadata?.signal;if(t&&typeof t=="object"&&!Array.isArray(t)){const r=t.tagName;if(typeof r=="string")return r}const n=hwe(e);return n==="user"?"user":n==="reactive"?e.type:n}function _wn(e){return e==="user"||e==="user-message"}function Cwn(e){return typeof e.content.content=="string"?e.content.content:e.content.parts.find(t=>t.type==="text")?.text??""}function Ewn(e){const t=e.content.metadata?.signal&&typeof e.content.metadata.signal=="object"?e.content.metadata.signal:{},n=t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?t.metadata:{},r=t.attributes&&typeof t.attributes=="object"&&!Array.isArray(t.attributes)?t.attributes:{},s=hwe(e)??"signal",a=Own(e)??s;return{type:s==="user"?"data-user-message":"data-signal",data:{id:typeof t.id=="string"?t.id:e.id,type:s,tagName:a,contents:"contents"in t?t.contents:Cwn(e),createdAt:typeof t.createdAt=="string"?t.createdAt:e.createdAt.toISOString(),...typeof t.acceptedAt=="string"?{acceptedAt:t.acceptedAt}:{},...Object.keys(r).length?{attributes:r}:{},...Object.keys(n).length?{metadata:n}:{}}}}function xLe(e){return typeof e=="object"&&e&&"type"in e&&(e=e.type),typeof e!="string"?nu(e):e==="dynamic-tool"?"dynamic-tool":e.startsWith("tool-")?nu(e.slice(5)):nu(e)}function hb(e,t){return t==null?e:{...e||{},mastra:{...(e||{}).mastra||{},createdAt:t}}}function op(e){const t=e?.mastra;if(!t||typeof t!="object")return;const n=t.createdAt;return typeof n=="number"?n:void 0}function US(e,t,n,r=!0){if(!r)return n;const s=lg(e,"display",t);return Cu(s)?s.transformed:n}function QX(e,t,n=!0){if(!n||!e||typeof e!="object")return e;const r=e,s=r.metadata??r.providerMetadata,a=lg(s,"display",t),i=lg(s,"display","input-available"),l=t==="approval"?Cu(a)?a.transformed:Cu(i)?i.transformed:void 0:Cu(i)?i.transformed:Cu(a)?a.transformed:void 0,c=t==="suspend"&&Cu(a)?a.transformed:void 0;return{...r,...l!==void 0?{args:l}:{},...c!==void 0?{suspendPayload:c}:{}}}var Fv=class{static toUIMessage(e,t){const n=_wn(e.role==="signal"?hwe(e):void 0),r=t?.transformToolPayloads??!0,s=[],a={...e.content.metadata||{}};if(e.role==="signal"&&!n&&s.push(Ewn(e)),e.createdAt&&(a.createdAt=e.createdAt),e.threadId&&(a.threadId=e.threadId),e.resourceId&&(a.resourceId=e.resourceId),e.content.providerMetadata&&(a.providerMetadata=e.content.providerMetadata),e.role==="signal"&&!n)return{id:e.id,role:"system",metadata:a,parts:s};const i=e.content.parts?.some(v=>v.type==="tool-invocation");if(e.content.toolInvocations&&!i)for(const v of e.content.toolInvocations)v.state==="result"?s.push({type:`tool-${v.toolName}`,toolCallId:v.toolCallId,state:"output-available",input:v.args,output:v.result}):s.push({type:`tool-${v.toolName}`,toolCallId:v.toolCallId,state:v.state==="call"?"input-available":"input-streaming",input:v.args});const l=e.content.parts?.some(v=>v.type==="reasoning"),c=e.content.parts?.some(v=>v.type==="file");e.content.reasoning&&!l&&s.push({type:"reasoning",text:e.content.reasoning});const u=new Set;if(e.content.experimental_attachments&&!c)for(const v of e.content.experimental_attachments)u.add(v.url),s.push({type:"file",url:v.url,mediaType:v.contentType||"unknown"});let d=!1;if(e.content.parts)for(const v of e.content.parts){if(v.type==="tool-invocation"&&v.toolInvocation){const y=v.toolInvocation;y.state==="result"?s.push({type:`tool-${y.toolName}`,toolCallId:y.toolCallId,input:US(v.providerMetadata,"input-available",y.args,r),output:US(v.providerMetadata,"output-available",US(v.providerMetadata,"error",y.result,r),r),state:"output-available",callProviderMetadata:hb(v.providerMetadata,v.createdAt),providerExecuted:v.providerExecuted}):y.state==="output-error"?s.push({type:`tool-${y.toolName}`,toolCallId:y.toolCallId,input:US(v.providerMetadata,"input-available",y.args,r),errorText:US(v.providerMetadata,"error",y.errorText||"",r),state:"output-error",callProviderMetadata:hb(v.providerMetadata,v.createdAt),providerExecuted:v.providerExecuted}):y.state==="output-denied"?s.push({type:`tool-${y.toolName}`,toolCallId:y.toolCallId,input:US(v.providerMetadata,"input-available",y.args,r),output:y.approval?.reason??"Tool call was not approved by the user",state:"output-available",callProviderMetadata:hb(v.providerMetadata,v.createdAt),providerExecuted:v.providerExecuted}):s.push({type:`tool-${y.toolName}`,toolCallId:y.toolCallId,input:US(v.providerMetadata,"input-available",y.args,r),state:"input-available",callProviderMetadata:hb(v.providerMetadata,v.createdAt),providerExecuted:v.providerExecuted});continue}if(v.type==="reasoning"){const y=v.reasoning||(v.details?.reduce((b,x)=>x.type==="text"&&x.text?b+x.text:b,"")??"");if(y||v.details?.length){const b={type:"reasoning",text:y||"",state:"done"};b.providerMetadata=hb(v.providerMetadata,v.createdAt),s.push(b)}continue}if(!(v.type==="tool-invocation"||v.type.startsWith("tool-")))if(v.type==="file"){const{mediaType:y,data:b}=Aq(v);if(typeof b=="string"&&u.has(b))continue;const x=typeof b=="string"?Oj(b,y):{type:"raw",mimeType:y};if((x.type==="url"||x.type==="providerFileId")&&typeof b=="string"){const S={type:"file",url:b,mediaType:x.mimeType||"image/png"};S.providerMetadata=hb(v.providerMetadata,v.createdAt),s.push(S)}else{let S,k=y;if(typeof b=="string"){const T=V9(b);T.isDataUri?(S=T.base64Content,T.mimeType&&(k=k||T.mimeType)):S=b}else S=uhe(b,k);const _=k||"image/png";let C;typeof S=="string"&&S.startsWith("data:")?C=S:C=M0e(S,_);const E={type:"file",url:C,mediaType:_};E.providerMetadata=hb(v.providerMetadata,v.createdAt),s.push(E)}}else if(v.type==="source"){const y={type:"source-url",url:v.source.url,sourceId:v.source.id,title:v.source.title};y.providerMetadata=hb(v.providerMetadata,v.createdAt),s.push(y)}else{if(v.type==="source-document")continue;if(v.type==="text"){const y={type:"text",text:v.text};y.providerMetadata=hb(v.providerMetadata,v.createdAt),s.push(y),d=!0}else v.type==="data-tool-call-suspended"||v.type==="data-tool-call-approval"?s.push({...v,data:QX(v.data,v.type==="data-tool-call-suspended"?"suspend":"approval",r)}):(s.push(v),d=!0)}}e.content.content&&!d&&s.push({type:"text",text:e.content.content});const f=new Set(s.filter(v=>v.type==="data-tool-call-suspended"||v.type==="data-tool-call-approval").map(v=>{const y=v.data;return typeof y?.toolCallId=="string"?y.toolCallId:void 0}).filter(v=>typeof v=="string")),p=(v,y)=>{const b=s.findIndex(x=>x.type.startsWith("tool-")&&x.toolCallId===v);if(b===-1){s.push(y);return}s.splice(b+1,0,y)},h=a.suspendedTools;if(h&&typeof h=="object")for(const v of Object.values(h)){if(!v||typeof v!="object")continue;const y="toolCallId"in v?v.toolCallId:void 0;typeof y!="string"||f.has(y)||(p(y,{type:"data-tool-call-suspended",data:QX(v,"suspend",r)}),f.add(y))}const m=a.pendingToolApprovals;if(m&&typeof m=="object")for(const v of Object.values(m)){if(!v||typeof v!="object")continue;const y="toolCallId"in v?v.toolCallId:void 0;typeof y!="string"||f.has(y)||(p(y,{type:"data-tool-call-approval",data:QX(v,"approval",r)}),f.add(y))}return{id:e.id,role:e.role==="signal"?n?"user":"system":e.role,metadata:a,parts:s}}static fromUIMessage(e){const{parts:t,metadata:n}=e,r=n||{},s=r.createdAt,a=s?typeof s=="string"?new Date(s):s instanceof Date?s:new Date:new Date,i=r.threadId,l=r.resourceId,c={...r};delete c.createdAt,delete c.threadId,delete c.resourceId;const u=t.filter(x=>Mp(x)),d=t.filter(x=>x.type==="reasoning"),f=t.filter(x=>x.type==="file"),p=t.filter(x=>x.type==="text");let h;u.length>0&&(h=u.map(x=>{const S=xLe(x);return x.state==="output-available"?{args:x.input,result:typeof x.output=="object"&&x.output&&"value"in x.output?x.output.value:x.output,toolCallId:x.toolCallId,toolName:S,state:"result"}:{args:x.input,toolCallId:x.toolCallId,toolName:S,state:"call"}}));let m;d.length>0&&(m=d.map(x=>x.text).join(`
|
|
195
195
|
`));let v;f.length>0&&(v=f.map(x=>({url:x.url||"",contentType:x.mediaType})));let y;p.length>0&&(y=p.map(x=>x.text).join(""));const b=bLe(t.map(x=>{if(Mp(x)){const S=xLe(x),k="callProviderMetadata"in x?x.callProviderMetadata:void 0;return x.state==="output-available"?{type:"tool-invocation",toolInvocation:{toolCallId:x.toolCallId,toolName:S,args:x.input,result:typeof x.output=="object"&&x.output&&"value"in x.output?x.output.value:x.output,state:"result"},providerMetadata:k,createdAt:op(k)}:{type:"tool-invocation",toolInvocation:{toolCallId:x.toolCallId,toolName:S,args:x.input,state:"call"},providerMetadata:k,createdAt:op(k)}}return x.type==="reasoning"?{type:"reasoning",reasoning:x.text,details:[{type:"text",text:x.text}],providerMetadata:x.providerMetadata,createdAt:op(x.providerMetadata)}:x.type==="file"?{type:"file",mimeType:x.mediaType,data:x.url||"",providerMetadata:x.providerMetadata,createdAt:op(x.providerMetadata),...x.filename?{filename:x.filename}:{}}:x.type==="source-url"?{type:"source",source:{url:x.url,sourceType:"url",id:x.url,providerMetadata:x.providerMetadata},providerMetadata:x.providerMetadata,createdAt:op(x.providerMetadata)}:x.type==="text"?{type:"text",text:x.text,providerMetadata:x.providerMetadata,createdAt:op(x.providerMetadata)}:x.type==="step-start"?x:typeof x.type=="string"&&x.type.startsWith("data-")?{type:x.type,data:"data"in x?x.data:void 0}:null}).filter(x=>x!==null));return{id:e.id,role:e.role,createdAt:a,threadId:i,resourceId:l,content:{format:2,parts:b,toolInvocations:h,reasoning:m,experimental_attachments:v,content:y,metadata:Object.keys(c).length>0?c:void 0}}}static getDataStringFromAIV5DataPart(e){let t,n;if("data"in e)t=e.mediaType||"application/octet-stream",n=e.data;else if("image"in e)t=e.mediaType||"image/jpeg",n=e.image;else{if("url"in e&&typeof e.url=="string")return e.url;throw new SO({id:"MASTRA_AIV5_DATA_PART_INVALID",domain:xO.AGENT,category:wO.USER,text:"Invalid AIV5 data part in getDataStringFromAIV5DataPart",details:{part:e}})}if(n instanceof URL)return n.toString();if(n instanceof Buffer){const r=n.toString("base64");return`data:${t};base64,${r}`}else{if(typeof n=="string")return n.startsWith("data:")||n.startsWith("http")||n.startsWith("file-")?n:`data:${t};base64,${n}`;if(n instanceof Uint8Array){const r=Buffer.from(n).toString("base64");return`data:${t};base64,${r}`}else if(n instanceof ArrayBuffer){const r=Buffer.from(n).toString("base64");return`data:${t};base64,${r}`}else return""}}static fromModelMessage(e,t,n={}){const r=Array.isArray(e.content)?e.content:[{type:"text",text:e.content}],s=[],a=[],i=[],l=[];for(const p of r)if(p.type==="text"){const h={type:"text",text:p.text};p.providerOptions&&(h.providerMetadata=p.providerOptions,h.createdAt=op(p.providerOptions)),s.push(h)}else if(p.type==="tool-call"){const h=p,m={type:"tool-invocation",toolInvocation:{toolCallId:h.toolCallId,toolName:nu(h.toolName),args:h.input,state:"call"}};p.providerOptions&&(m.providerMetadata=p.providerOptions,m.createdAt=op(p.providerOptions)),s.push(m),a.push({toolCallId:h.toolCallId,toolName:nu(h.toolName),args:h.input,state:"call"})}else if(p.type==="tool-result"){const h=p,m=a.find(S=>S.toolCallId===h.toolCallId),v=s.find(S=>S.type==="tool-invocation"&&"toolInvocation"in S&&S.toolInvocation.toolCallId===h.toolCallId),y=(S,k)=>{k.state="result",k.result=typeof S.output=="object"&&S.output&&"value"in S.output?S.output.value:S.output},b=n.dbMessages?Dq(n.dbMessages,h.toolCallId):void 0,x=b&&Object.keys(b).length>0?b:h.input??{};if(m)y(h,m);else{const S={state:"call",toolCallId:h.toolCallId,toolName:nu(h.toolName),args:x};y(h,S),a.push(S)}if(v&&v.type==="tool-invocation")y(h,v.toolInvocation),h.providerOptions&&(v.providerMetadata=h.providerOptions,v.createdAt=op(h.providerOptions)??v.createdAt);else{const S={type:"tool-invocation",toolInvocation:{toolCallId:h.toolCallId,toolName:nu(h.toolName),args:x,state:"call"}};y(h,S.toolInvocation),h.providerOptions&&(S.providerMetadata=h.providerOptions,S.createdAt=op(h.providerOptions)),s.push(S)}}else if(p.type==="reasoning"){const h={type:"reasoning",reasoning:p.text,details:[{type:"text",text:p.text}]};p.providerOptions&&(h.providerMetadata=p.providerOptions,h.createdAt=op(p.providerOptions)),s.push(h),i.push(p.text)}else if(p.type==="image"){const h=p,m=h.mediaType||"image/jpeg",v=this.getDataStringFromAIV5DataPart(h),y={type:"file",data:v,mimeType:m};p.providerOptions&&(y.providerMetadata=p.providerOptions,y.createdAt=op(p.providerOptions)),s.push(y),l.push({url:v,contentType:m})}else if(p.type==="file"){const h=p,m=h.mediaType||"application/octet-stream",v=this.getDataStringFromAIV5DataPart(h),y={type:"file",data:v,mimeType:m};p.providerOptions&&(y.providerMetadata=p.providerOptions,y.createdAt=op(p.providerOptions)),h.filename&&(y.filename=h.filename),s.push(y),l.push({url:v,contentType:m})}const c=bLe(s),u=c.filter(p=>p.type==="text").map(p=>p.text).join(`
|
|
196
196
|
`),d="metadata"in e&&e.metadata!==null&&e.metadata!==void 0?e.metadata:{},f={id:"id"in e&&typeof e.id=="string"?e.id:`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,role:e.role==="tool"?"assistant":e.role,createdAt:new Date,content:{format:2,parts:c,toolInvocations:a.length>0?a:void 0,reasoning:i.length>0?i.join(`
|
|
197
|
-
`):void 0,experimental_attachments:l.length>0?l:void 0,content:u||void 0,metadata:Object.keys(d).length>0?d:void 0}};return e.providerOptions&&(f.content.providerMetadata=e.providerOptions),f}};function vd(e,t){for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function cv(e,t,n){const r=lg(e,"display",t);return Cu(r)?r.transformed:n}function Twn(e){return e.startsWith("tool-")?nu(e.slice(5)):nu(e)}function dmt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function jwn(e){return typeof e=="object"&&e&&"value"in e?e.value:e}function Nwn(e){return e==="approval-requested"||e==="approval-responded"||e==="output-denied"}function Iwn(e){if(e)return{id:e.id,approved:"approved"in e?e.approved:void 0,reason:"reason"in e?e.reason:void 0}}function Awn(e){return e.type==="dynamic-tool"?nu(e.toolName):Twn(e.type)}function Rwn(e){const t={toolCallId:e.toolCallId,toolName:Awn(e),args:dmt(e.input),approval:"approval"in e?Iwn(e.approval):void 0,providerMetadata:"callProviderMetadata"in e?e.callProviderMetadata:void 0,providerExecuted:e.providerExecuted,title:e.title,preliminary:"preliminary"in e?e.preliminary:void 0};switch(e.state){case"input-streaming":return bw({...t,state:"partial-call"});case"input-available":return bw({...t,state:"call"});case"output-available":return bw({...t,state:"result",result:jwn(e.output)});case"output-error":return bw({...t,state:"output-error",errorText:e.errorText,rawInput:"rawInput"in e?e.rawInput:void 0});case"approval-requested":case"approval-responded":case"output-denied":return bw({...t,state:e.state})}}function Pwn(e){return e.type==="dynamic-tool"&&!Nwn(e.state)?{...e,type:`tool-${nu(e.toolName)}`}:e}function bw({toolCallId:e,toolName:t,args:n,state:r,approval:s,result:a,errorText:i,rawInput:l,providerMetadata:c,providerExecuted:u,title:d,preliminary:f}){return vd({type:"tool-invocation",toolInvocation:vd({toolCallId:e,toolName:t,args:n,state:r},{approval:s,result:a,errorText:i,rawInput:l})},{providerMetadata:c,providerExecuted:u,title:d,preliminary:f})}function fmt(e,t){for(const n of e)if(n.type==="tool-invocation"&&n.toolInvocation.toolCallId===t)return n}function $wn(e,t){if(e)for(const n of[...e].reverse()){for(const s of[...n.content.parts||[]].reverse())if(s.type==="tool-invocation"&&s.toolInvocation.approval?.id===t&&s.toolInvocation.state==="approval-requested")return s;const r=n.content.metadata?.pendingToolApprovals;if(!(!r||typeof r!="object"))for(const s of Object.values(r)){if(!s||typeof s!="object")continue;const a="toolCallId"in s?s.toolCallId:void 0;if(typeof a!="string")continue;const i="runId"in s?s.runId:void 0,l=typeof i=="string"?`${i}::${a}`:a;if(l!==t)continue;const c=fmt(n.content.parts||[],a);if(c)return bw({toolCallId:c.toolInvocation.toolCallId,toolName:c.toolInvocation.toolName,args:c.toolInvocation.args,state:"approval-requested",approval:{id:l},providerMetadata:c.providerMetadata,providerExecuted:c.providerExecuted,title:c.title,preliminary:c.preliminary})}}}function Mwn(e,t){const n=t.pendingToolApprovals;if(!(!n||typeof n!="object"))for(const r of Object.values(n)){if(!r||typeof r!="object")continue;const s="toolCallId"in r?r.toolCallId:void 0;if(typeof s!="string")continue;const a="runId"in r?r.runId:void 0,i=typeof a=="string"?`${a}::${s}`:s,l=e.findIndex(u=>o7(u)&&u.toolCallId===s&&u.state==="input-available");if(l===-1)continue;const c=e[l];!c||!o7(c)||c.state!=="input-available"||(e[l]={...c,state:"approval-requested",approval:{id:i}})}}function Dwn(e){const t=[];for(const n of e){if(n.type!=="tool-invocation")continue;const r=n.toolInvocation;if(r.state==="result"){t.push({args:r.args,result:r.result,toolCallId:r.toolCallId,toolName:r.toolName,state:"result"});continue}(r.state==="call"||r.state==="partial-call")&&t.push({args:r.args,toolCallId:r.toolCallId,toolName:r.toolName,state:r.state})}return t.length>0?t:void 0}var l7=class ow{static toUIMessage(t){const n=Fv.toUIMessage(t),r=n.metadata||{},s=[];if(t.role==="signal"&&n.role!=="user")return{id:t.id,role:"system",metadata:Object.keys(r).length>0?r:void 0,parts:n.parts.map(d=>ow.toUIPartFromV5(d))};const a=t.content.parts||[],i=a.some(d=>d.type==="tool-invocation"),l=a.some(d=>d.type==="reasoning"),c=a.some(d=>d.type==="file"),u=a.some(d=>d.type==="text");for(const d of a)s.push(ow.toUIPart(d));if(!i||!l||!c||!u)for(const d of n.parts){if(Mp(d)){i||s.push(ow.toUIPartFromV5(d));continue}if(d.type==="reasoning"){l||s.push(ow.toUIPartFromV5(d));continue}if(d.type==="file"){c||s.push(ow.toUIPartFromV5(d));continue}d.type==="text"&&!u&&s.push(ow.toUIPartFromV5(d))}return Mwn(s,r),{id:t.id,role:t.role==="signal"?n.role:t.role,metadata:Object.keys(r).length>0?r:void 0,parts:s}}static fromUIMessage(t){const n=t.parts.filter(l=>!(l.type==="source-document"||o7(l))),r=Fv.fromUIMessage({...t,parts:n.map(l=>Pwn(l))}),s=r.content.parts||[],a=[];let i=0;for(const l of t.parts){if(l.type==="source-document"){a.push(vd({type:"source-document",sourceId:l.sourceId,mediaType:l.mediaType,title:l.title},{filename:l.filename,providerMetadata:l.providerMetadata}));continue}if(!o7(l)){const c=s[i++];c&&a.push(c);continue}a.push(Rwn(l))}return{...r,content:{...r.content,parts:a,toolInvocations:Dwn(a)||r.content.toolInvocations}}}static fromModelMessage(t,n,r={}){const s=Array.isArray(t.content)?t.content:[{type:"text",text:t.content}],a=s.filter(c=>c.type!=="tool-approval-request"&&c.type!=="tool-approval-response"),i=Fv.fromModelMessage({...t,content:a},n,r),l=[...i.content.parts];if(t.role==="assistant"){const c=new Map;for(const u of s){if(u.type==="tool-call"){c.set(u.toolCallId,{toolName:nu(u.toolName),args:dmt(u.input)});continue}if(u.type!=="tool-approval-request")continue;const d=c.get(u.toolCallId),f=fmt(l,u.toolCallId);if(f){f.toolInvocation.state="approval-requested",f.toolInvocation.approval={id:u.approvalId};continue}l.push(bw({toolCallId:u.toolCallId,toolName:d?.toolName||"unknown",args:d?.args||{},state:"approval-requested",approval:{id:u.approvalId}}))}}else if(t.role==="tool")for(const c of s){if(c.type!=="tool-approval-response")continue;const u=$wn(r.dbMessages,c.approvalId);u&&l.push(bw({toolCallId:u.toolInvocation.toolCallId,toolName:u.toolInvocation.toolName,args:u.toolInvocation.args,state:"approval-responded",approval:{id:c.approvalId,approved:c.approved,reason:c.reason},providerMetadata:u.providerMetadata,providerExecuted:u.providerExecuted,title:u.title}))}return{...i,content:{...i.content,parts:l}}}static toUIPart(t){if(t.type==="tool-invocation"){const n=vd({type:`tool-${nu(t.toolInvocation.toolName)}`,toolCallId:t.toolInvocation.toolCallId,providerExecuted:t.providerExecuted},{callProviderMetadata:t.providerMetadata,title:t.title});switch(t.toolInvocation.state){case"partial-call":return{...n,state:"input-streaming",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args)};case"call":return{...n,state:"input-available",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args)};case"approval-requested":return{...n,state:"approval-requested",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId}};case"approval-responded":return{...n,state:"approval-responded",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId,approved:t.toolInvocation.approval?.approved??!1,reason:t.toolInvocation.approval?.reason}};case"output-error":return vd({...n,state:"output-error",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),errorText:cv(t.providerMetadata,"error",t.toolInvocation.errorText||"")},{rawInput:t.toolInvocation.rawInput,approval:t.toolInvocation.approval?.approved===!0?{id:t.toolInvocation.approval.id,approved:!0,reason:t.toolInvocation.approval.reason}:void 0});case"output-denied":return{...n,state:"output-denied",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId,approved:!1,reason:t.toolInvocation.approval?.reason}};case"result":return vd({...n,state:"output-available",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),output:cv(t.providerMetadata,"output-available",cv(t.providerMetadata,"error",t.toolInvocation.result))},{preliminary:t.preliminary,approval:t.toolInvocation.approval?.approved===!0?{id:t.toolInvocation.approval.id,approved:!0,reason:t.toolInvocation.approval.reason}:void 0});default:throw new Error(`Unhandled toolInvocation.state: ${String(t.toolInvocation.state)}`)}}return t.type==="source-document"?vd({type:"source-document",sourceId:t.sourceId,mediaType:t.mediaType,title:t.title},{filename:t.filename,providerMetadata:t.providerMetadata}):ow.toUIPartFromV5(Fv.toUIMessage({id:"tmp",role:"assistant",createdAt:new Date,content:{format:2,parts:[t]}}).parts[0])}static toUIPartFromV5(t){if(Mp(t)){const n={type:t.type,toolCallId:t.toolCallId,providerExecuted:t.providerExecuted};switch(t.state){case"input-streaming":return vd({...n,state:"input-streaming",input:t.input},{callProviderMetadata:"callProviderMetadata"in t?t.callProviderMetadata:void 0,title:"title"in t?t.title:void 0});case"input-available":return vd({...n,state:"input-available",input:t.input},{callProviderMetadata:"callProviderMetadata"in t?t.callProviderMetadata:void 0,title:"title"in t?t.title:void 0});case"output-available":return vd({...n,state:"output-available",input:t.input,output:t.output},{callProviderMetadata:"callProviderMetadata"in t?t.callProviderMetadata:void 0,preliminary:"preliminary"in t?t.preliminary:void 0,title:"title"in t?t.title:void 0});case"output-error":return vd({...n,state:"output-error",input:t.input,errorText:t.errorText},{rawInput:"rawInput"in t?t.rawInput:void 0,callProviderMetadata:"callProviderMetadata"in t?t.callProviderMetadata:void 0,title:"title"in t?t.title:void 0})}}switch(t.type){case"text":return vd({type:"text",text:t.text},{providerMetadata:t.providerMetadata});case"reasoning":return vd({type:"reasoning",text:t.text,state:t.state},{providerMetadata:t.providerMetadata});case"file":return vd({type:"file",url:t.url,mediaType:t.mediaType},{filename:"filename"in t?t.filename:void 0,providerMetadata:t.providerMetadata});case"source-url":return vd({type:"source-url",sourceId:t.sourceId,url:t.url},{title:t.title,providerMetadata:t.providerMetadata});case"step-start":return{type:"step-start"};default:return typeof t.type=="string"&&t.type.startsWith("data-")?{type:t.type,data:"data"in t?t.data:void 0}:t}}};function Lwn(e){return JSON.stringify(e,(t,n)=>{if(n&&typeof n=="object"&&!Array.isArray(n)){const r={};for(const s of Object.keys(n).sort())r[s]=n[s];return r}return n})}function W0(e,...t){const n=new Set(t.flatMap(r=>E0n(r)));for(const r of n)e+=`|${r}`;return e}var Xo=class Ehe{static fromAIV4Parts(t){let n="";for(const r of t)n+=r.type,n+=Ehe.fromAIV4Part(r);return n}static fromAIV4Part(t){let n="";if(t.type==="text"&&(n+=t.text,n=W0(n,t.providerMetadata)),t.type==="tool-invocation"){if(!t.toolInvocation)return n;n+=t.toolInvocation.toolCallId,n+=t.toolInvocation.state}if(t.type==="reasoning"){n+=t.reasoning,n+=(t.details??[]).reduce((s,a)=>a.type==="text"?s+(a.text?.length??0)+(a.signature?.length||0):s,0);const r=t;r&&Object.hasOwn(r,"providerMetadata")&&(n=W0(n,r.providerMetadata))}if(t.type==="file"){const{mediaType:r,data:s}=Aq(t);n+=s,n+=r}return n}static fromDBParts(t){let n="";for(const r of t)if(n+=r.type,r.type.startsWith("data-")){const s=r.data;n+=Lwn(s)}else n+=Ehe.fromAIV4Part(r);return n}static fromAIV4CoreMessageContent(t){if(typeof t=="string")return t;let n="";for(const r of t){if(n+=r.type,r.type==="text"){n+=r.text.length;const s=r;n=W0(n,s.providerMetadata,s.providerOptions)}if(r.type==="reasoning"){n+=r.text.length;const s=r;n=W0(n,s.providerMetadata,s.providerOptions)}r.type==="tool-call"&&(n+=r.toolCallId,n+=r.toolName),r.type==="tool-result"&&(n+=r.toolCallId,n+=r.toolName),r.type==="file"&&(n+=r.filename,n+=r.mimeType),r.type==="image"&&(n+=VDe(r.image),n+=r.mimeType),r.type==="redacted-reasoning"&&(n+=r.data.length)}return n}static fromAIV5Parts(t){let n="";for(const r of t)n+=r.type,r.type==="text"&&(n+=r.text,n=W0(n,r.providerMetadata)),(Mp(r)||r.type==="dynamic-tool")&&(n+=r.toolCallId,n+=r.state),r.type==="reasoning"&&(n+=r.text,n=W0(n,r.providerMetadata)),r.type==="file"&&(n+=r.url.length,n+=r.mediaType,n+=r.filename||"");return n}static fromAIV5ModelMessageContent(t){if(typeof t=="string")return t;let n="";for(const r of t)n+=r.type,r.type==="text"&&(n+=r.text.length,n=W0(n,r.providerOptions)),r.type==="reasoning"&&(n+=r.text.length,n=W0(n,r.providerOptions)),r.type==="tool-call"&&(n+=r.toolCallId,n+=r.toolName),r.type==="tool-result"&&(n+=r.toolCallId,n+=r.toolName),r.type==="file"&&(n+=r.filename,n+=r.mediaType),r.type==="image"&&(n+=VDe(r.image),n+=r.mediaType);return n}};function Fwn(e){return typeof e=="string"?e:e.reduce((t,n)=>(n.type==="text"&&(t+=n.text),t),"")}function YX(e,t){const n=Ga.isAIV4UIMessage(e)&&e,r=Ga.isAIV4UIMessage(t)&&t;if(n&&!r)return!1;if(n&&r)return Xo.fromAIV4Parts(e.parts)===Xo.fromAIV4Parts(t.parts);const s=Ga.isAIV4CoreMessage(e)&&e,a=Ga.isAIV4CoreMessage(t)&&t;if(s&&!a)return!1;if(s&&a)return Xo.fromAIV4CoreMessageContent(s.content)===Xo.fromAIV4CoreMessageContent(a.content);const i=Ga.isMastraMessageV1(e)&&e,l=Ga.isMastraMessageV1(t)&&t;if(i&&!l)return!1;if(i&&l)return i.id===l.id&&Xo.fromAIV4CoreMessageContent(i.content)===Xo.fromAIV4CoreMessageContent(l.content);const c=Ga.isMastraDBMessage(e)&&e,u=Ga.isMastraDBMessage(t)&&t;if(c&&!u)return!1;if(c&&u)return c.id===u.id&&Xo.fromDBParts(c.content.parts)===Xo.fromDBParts(u.content.parts);const d=Ga.isAIV5UIMessage(e)&&e,f=Ga.isAIV5UIMessage(t)&&t;if(d&&!f)return!1;if(d&&f)return Xo.fromAIV5Parts(e.parts)===Xo.fromAIV5Parts(t.parts);const p=Ga.isAIV5CoreMessage(e)&&e,h=Ga.isAIV5CoreMessage(t)&&t;return p&&!h?!1:p&&h?Xo.fromAIV5ModelMessageContent(p.content)===Xo.fromAIV5ModelMessageContent(h.content):!0}function mwe(e){return e.createdAt==null&&(e.createdAt=Date.now()),e}function rE(e,t){return t==="memory"||!Array.isArray(e.content.parts)||(e.content.parts=e.content.parts.map(n=>mwe(n))),e}function wLe(e,t,n){if(t!=="memory"&&"threadId"in e&&e.threadId&&n.memoryInfo&&e.threadId!==n.memoryInfo.threadId)throw new Error(`Received input message with wrong threadId. Input ${e.threadId}, expected ${n.memoryInfo.threadId}`);if(t!=="memory"&&"resourceId"in e&&e.resourceId&&n.memoryInfo?.resourceId&&e.resourceId!==n.memoryInfo.resourceId)throw new Error(`Received input message with wrong resourceId. Input ${e.resourceId}, expected ${n.memoryInfo.resourceId}`);if(Ga.isMastraMessageV1(e))return rE(zwn(e,t,n),t);if(Ga.isMastraDBMessage(e))return rE(Bwn(e,n,t),t);if(Ga.isAIV4CoreMessage(e))return rE(Bw.fromCoreMessage(e,n,t),t);if(Ga.isAIV4UIMessage(e))return rE(Bw.fromUIMessage(e,n,t),t);const r="id"in e&&typeof e.id=="string"?e.id:n.newMessageId();if(Ga.isAIV6CoreMessage(e)){const s=l7.fromModelMessage(e,t,n),a="metadata"in e&&e.metadata&&typeof e.metadata=="object"&&"createdAt"in e.metadata?e.metadata.createdAt:void 0;return{...s,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId}}if(Ga.isAIV6UIMessage(e)){const s=l7.fromUIMessage(e),a="createdAt"in e?e.createdAt:void 0;return{...s,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId}}if(Ga.isAIV5CoreMessage(e)){const s=Fv.fromModelMessage(e,t,n),a="metadata"in e&&e.metadata&&typeof e.metadata=="object"&&"createdAt"in e.metadata?e.metadata.createdAt:void 0;return rE({...s,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId},t)}if(Ga.isAIV5UIMessage(e)){const s=Fv.fromUIMessage(e),a="createdAt"in e?e.createdAt:void 0;return rE({...s,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId},t)}throw new Error(`Found unhandled message ${JSON.stringify(e)}`)}function zwn(e,t,n){const r=Bw.fromCoreMessage({content:e.content,role:e.role},n,t);return{id:e.id,role:r.role,createdAt:n.generateCreatedAt(t,e.createdAt),threadId:e.threadId,resourceId:e.resourceId,content:r.content}}function Bwn(e,t,n){return e.id||(e.id=t.newMessageId()),e.createdAt===void 0||e.createdAt===null?e.createdAt=t.generateCreatedAt(n):e.createdAt instanceof Date||(e.createdAt=new Date(e.createdAt)),e.content.toolInvocations&&e.content.parts&&(e.content.toolInvocations=e.content.toolInvocations.map(r=>{if(!r.args||Object.keys(r.args).length===0){const s=e.content.parts.find(a=>a.type==="tool-invocation"&&a.toolInvocation&&a.toolInvocation.toolCallId===r.toolCallId&&a.toolInvocation.args&&Object.keys(a.toolInvocation.args).length>0);if(s&&s.type==="tool-invocation")return{...r,args:s.toolInvocation.args}}return r})),!e.threadId&&t.memoryInfo?.threadId&&(e.threadId=t.memoryInfo.threadId),!e.resourceId&&t.memoryInfo?.resourceId&&(e.resourceId=t.memoryInfo.resourceId),e}function Uwn(e){return e.type.startsWith("source-")}function Vwn(e){const t=[];for(const n of e){if(n.type!=="text"){t.push(n);continue}const r=n,s=hLe(r.providerMetadata);if(!s){t.push(n);continue}let a=!1;for(let i=t.length-1;i>=0;i--){const l=t[i];if(l.type==="text"){const c=l;hLe(c.providerMetadata)===s&&(t[i]={...c,text:c.text+r.text},a=!0);break}if(!Uwn(l))break}a||t.push(n)}return t}function qwn(e){return e.map(t=>{if(t.parts.length===0)return!1;const n=t.parts.filter(s=>s.type!=="tool-invocation"||s.toolInvocation.state!=="call"&&s.toolInvocation.state!=="partial-call");if(!n.length)return!1;const r={...t,parts:n};return"toolInvocations"in t&&t.toolInvocations&&(r.toolInvocations=t.toolInvocations.filter(s=>s.state==="result")),r}).filter(t=>!!t)}function pmt(e,t="response"){let n=-1;for(let a=e.length-1;a>=0;a--)if(e[a].role==="user"){n=a;break}const r=(a,i)=>a.parts.filter(l=>typeof l.type=="string"&&l.type.startsWith("data-")||l.type==="text"&&(!("text"in l)||l.text===""||l.text?.trim()==="")&&(a.role==="user"||a.parts.some(c=>!(c.type==="text"&&(!("text"in c)||c.text===""||c.text?.trim()===""))))?!1:Mp(l)?t!=="response"?l.state==="output-available"||l.state==="output-error"?!0:l.state==="input-available"?l.providerExecuted?i:t==="prompt-with-suspended":!1:l.state!=="input-streaming":!0);let s=-1;if(n!==e.length-1)for(let a=e.length-1;a>n;a--){const i=e[a];if(!(i.role!=="assistant"||i.parts.length===0)&&r(i,!0).length>0){s=a;break}}return e.map((a,i)=>{if(a.parts.length===0)return!1;const l=a.role==="assistant"&&i===s,c=r(a,l);if(!c.length)return!1;const u=Vwn(c);return{...a,parts:u.map(d=>Mp(d)&&d.state==="output-available"?{...d,output:(()=>{const f=d.output;if(f==null||typeof f!="object")return f;const p=f;return p.type==="content"&&Array.isArray(p.value)?f:"value"in p?p.value:f})()}:d)}}).filter(a=>!!a)}function Hwn(e){for(const t of e)if(t.role==="assistant")for(const[n,r]of t.parts.entries()){if(!Mp(r))continue;const s=t.parts.at(n+1);s&&s.type!=="step-start"&&!Mp(s)&&t.parts.splice(n+1,0,{type:"step-start"}),s&&Mp(s)&&!r.providerExecuted&&s.providerExecuted&&(s.state==="output-available"||s.state==="output-error")&&t.parts.splice(n+1,0,{type:"step-start"})}return e}function bh(e){const t=qwn(e),n=new Map;let r=0;const s=Mxn(t.map(i=>{if(i.role!=="user")return i;const l=r++;if(!i.experimental_attachments?.length)return i;const c=i.experimental_attachments.filter(d=>Oj(d.url,d.contentType).type==="providerFileId");if(!c.length)return i;n.set(l,c);const u=i.experimental_attachments.filter(d=>!c.includes(d));return{...i,experimental_attachments:u.length?u:void 0}}));if(!n.size)return s;let a=0;return s.map(i=>{if(i.role!=="user")return i;const l=n.get(a++);if(!l)return i;const c=l.map(d=>({type:"file",data:d.url,mimeType:d.contentType||"application/octet-stream"})),u=typeof i.content=="string"?[{type:"text",text:i.content}]:i.content;return{...i,content:[...u,...c]}})}function Wwn(e){if(!e||typeof e!="object")return;const t=e.content;if(!Array.isArray(t)||!t.some(r=>{if(!r||typeof r!="object")return!1;const s=r;return(s.type==="image"||s.type==="audio")&&typeof s.data=="string"}))return;const n=t.map(r=>{if(!r||typeof r!="object")return null;const s=r;switch(s.type){case"text":return{type:"text",text:String(s.text??"")};case"image":return typeof s.data=="string"?{type:"image-data",data:s.data,mediaType:String(s.mimeType??"image/png")}:{type:"text",text:JSON.stringify(s)};case"audio":return typeof s.data=="string"?{type:"file-data",data:s.data,mediaType:String(s.mimeType??"audio/wav")}:{type:"text",text:JSON.stringify(s)};default:return{type:"text",text:JSON.stringify(s)}}}).filter(Boolean);return n.length>0?{type:"content",value:n}:void 0}function Zwn(e){const t=new Map;for(const n of e)if(!(n.content?.format!==2||!n.content.parts))for(const r of n.content.parts){if(r.type!=="tool-invocation"||r.toolInvocation?.state!=="result")continue;const s=r.providerMetadata?.mastra;s&&typeof s=="object"&&"modelOutput"in s||t.set(r.toolInvocation.toolCallId,r.toolInvocation.result)}return t}function Gwn(e,t){if(!e||typeof e!="object")return!1;const n=e;return n.type!=="json"?!1:n.value===t||ohe(n.value,t)}function Qwn(e,t){const n=Zwn(t);return n.size===0?e:e.map(r=>{if(r.role!=="tool"||!Array.isArray(r.content))return r;let s=!1;const a=r.content.map(i=>{if(i.type!=="tool-result"||!n.has(i.toolCallId)||i.output?.type!=="json")return i;const l=n.get(i.toolCallId);let c;try{if(c=Wwn(l),!c||!Gwn(i.output,l))return i}catch{return i}return s=!0,{...i,output:c}});return s?{...r,content:a}:r})}function Ywn(e,t){const n=[];for(const s of t)if(s.role==="assistant")for(const a of s.parts)a.type==="file"&&n.push(a.providerMetadata??void 0);if(n.length===0||n.every(s=>s==null))return e;let r=0;return e.map(s=>{if(s.role!=="assistant"||typeof s.content=="string")return s;let a=!1;const i=s.content.map(l=>{if(l.type!=="file"||r>=n.length)return l;const c=n[r++];return l.providerOptions||!c?l:(a=!0,{...l,providerOptions:c})});return a?{...s,content:i}:s})}function bv(e,t,n="response"){const r=Hwn(pmt(e,n)),s=[];for(const i of r){const l=xpt([i]);if(l.length===0)continue;const c=i.metadata&&typeof i.metadata=="object"&&"providerMetadata"in i.metadata?i.metadata.providerMetadata:void 0;if(c){let u=-1;for(let d=l.length-1;d>=0;d--)if(l[d]?.role===i.role){u=d;break}u!==-1&&(l[u]={...l[u],providerOptions:c})}s.push(...l)}const a=T0n(Qwn(Ywn(s,r),t),t);switch(n){case"prompt":return Yht(a);case"prompt-with-suspended":return j0n(a);default:return a}}function SLe(e,t,n,r){return bv(e.map(s=>Bw.fromCoreMessage(s,n,t)).map(s=>Fv.toUIMessage(s)),r)}function Kwn(e){if(typeof e=="string")return{role:"system",content:e};if(Ga.isAIV6CoreMessage(e)){const t=l7.fromModelMessage(e,"system");return Bw.systemToV4Core(t)}if(Ga.isAIV5CoreMessage(e)){const t=Fv.fromModelMessage(e,"system");return Bw.systemToV4Core(t)}return Ga.isMastraDBMessage(e)?Bw.systemToV4Core(e):e}var kLe=class Tb{static extractStepContent(t,n,r){const s=t.flatMap(i=>i.parts),a=[];return s.forEach((i,l)=>{i.type==="step-start"&&a.push(l)}),n===-1?Tb.extractLastStep(s,a,r):n===1?Tb.extractFirstStep(s,a,r):Tb.extractMiddleStep(s,a,n,r)}static extractLastStep(t,n,r){const s=t.filter(c=>c.type?.startsWith("tool-")),a=n.length>0;if(!a&&s.length>0){const c=s[s.length-1];if(!c)return[];const u=t.indexOf(c),d=s[s.length-2],f=(d?t.indexOf(d):-1)+1,p=t.slice(f,u+1);return Tb.convertPartsToContent(p,"last-step",r)}if(n.length+1===1&&!a)return Tb.convertPartsToContent(t,"last-step",r);const i=n[n.length-1];if(i===void 0)return[];const l=t.slice(i+1);return l.length===0?[]:Tb.convertPartsToContent(l,"last-step",r)}static extractFirstStep(t,n,r){const s=n[0]??t.length;if(s===0)return[];const a=t.slice(0,s);return Tb.convertPartsToContent(a,"step-1",r)}static extractMiddleStep(t,n,r,s){const a=r-2;if(a<0||a>=n.length)return[];const i=(n[a]??0)+1,l=n[a+1]??t.length;if(i>=l)return[];const c=t.slice(i,l);return Tb.convertPartsToContent(c,`step-${r}`,s)}static convertPartsToContent(t,n,r){return xpt(pmt([{id:n,role:"assistant",parts:t}])).flatMap(r)}static convertToStepContent(t,n,r){const s=t||r();return s?typeof s.content=="string"?[{type:"text",text:s.content}]:s.content.map(a=>a.type==="tool-result"?{type:"tool-result",input:Dq(n,a.toolCallId),output:a.output,toolCallId:a.toolCallId,toolName:a.toolName}:a.type==="file"?{type:"file",file:new pLe({data:typeof a.data=="string"?V9(a.data).base64Content:a.data instanceof URL?a.data.toString():kO(a.data),mediaType:a.mediaType})}:a.type==="image"?{type:"file",file:new pLe({data:typeof a.image=="string"?V9(a.image).base64Content:a.image instanceof URL?a.image.toString():kO(a.image),mediaType:a.mediaType||"unknown"})}:{...a}):[]}},mb=class _P{static isSealed(t){return t.content?.metadata?.mastra?.sealed===!0}static shouldMerge(t,n,r,s,a=!1){if(!t||_P.isSealed(t)||t.content?.metadata?.mastra?.responseBoundary||n.content.metadata?.completionResult||t.content.metadata?.completionResult||n.content.metadata?.isTaskCompleteResult||t.content.metadata?.isTaskCompleteResult)return!1;const i=t.content?.parts??[];return i.length>0&&i.every(l=>l.type.startsWith("data-"))&&t.id!==n.id?!1:t.role==="assistant"&&n.role==="assistant"&&t.threadId===n.threadId&&r!=="memory"&&(a?!s:!0)}static merge(t,n){n.content.metadata&&(t.content.metadata={...t.content.metadata??{},...n.content.metadata});const r=new Map,s=new Map;for(const[a,i]of n.content.parts.entries())if(i.type==="tool-invocation"){if(!i.toolInvocation)continue;const l=[...t.content.parts].reverse().find(c=>c.type==="tool-invocation"&&c.toolInvocation?.toolCallId===i.toolInvocation.toolCallId);if(l&&l.type==="tool-invocation"){if(i.toolInvocation.state==="result"){l.toolInvocation={...l.toolInvocation,step:i.toolInvocation.step,state:"result",result:i.toolInvocation.result,args:{...l.toolInvocation.args,...i.toolInvocation.args}},i.providerMetadata&&(l.providerMetadata={...l.providerMetadata,...i.providerMetadata}),t.content.toolInvocations||(t.content.toolInvocations=[]);const u=t.content.toolInvocations.findIndex(d=>d.toolCallId===l.toolInvocation.toolCallId);u===-1?t.content.toolInvocations.push(l.toolInvocation):t.content.toolInvocations[u]=l.toolInvocation}else(i.toolInvocation.state==="approval-requested"||i.toolInvocation.state==="approval-responded"||i.toolInvocation.state==="output-denied"||i.toolInvocation.state==="output-error")&&(l.toolInvocation={...l.toolInvocation,state:i.toolInvocation.state,approval:i.toolInvocation.approval,errorText:i.toolInvocation.errorText,rawInput:i.toolInvocation.rawInput,args:{...l.toolInvocation.args,...i.toolInvocation.args}},i.providerMetadata&&(l.providerMetadata={...l.providerMetadata,...i.providerMetadata}),"providerExecuted"in i&&i.providerExecuted!==void 0&&(l.providerExecuted=i.providerExecuted),"title"in i&&i.title!==void 0&&(l.title=i.title),"preliminary"in i&&i.preliminary!==void 0&&(l.preliminary=i.preliminary));const c=t.content.parts.findIndex(u=>u===l);r.set(a,c)}else s.set(a,i)}else s.set(a,i);_P.addPartsToMessage({latestMessage:t,incomingMessage:n,anchorMap:r,partsToAdd:s}),!t.content.content&&n.content.content&&(t.content.content=n.content.content),t.content.content&&n.content.content&&t.content.content!==n.content.content&&(t.content.content=n.content.content)}static addPartsToMessage({latestMessage:t,incomingMessage:n,anchorMap:r,partsToAdd:s}){for(let a=0;a<n.content.parts.length;++a){const i=n.content.parts[a];if(!i)continue;const l=Xo.fromDBParts([i]),c=s.get(a);if(!(!l||!c))if(r.size>0){if(r.has(a))continue;const u=[...r.keys()].filter(h=>h<a).pop()??-1,d=[...r.keys()].find(h=>h>a)??-1,f=(u!==-1?r.get(u):0)+(u===-1?a:a-u),p=d!==-1?r.get(d):t.content.parts.length;if(f>=0&&f<=p&&!t.content.parts.slice(f,p).some(h=>Xo.fromDBParts([h])===Xo.fromDBParts([i]))){_P.pushNewPart({latestMessage:t,newMessage:n,part:i,insertAt:f});for(const[h,m]of r.entries())m>=f&&r.set(h,m+1)}}else _P.pushNewPart({latestMessage:t,newMessage:n,part:i})}}static pushNewPart({latestMessage:t,newMessage:n,part:r,insertAt:s}){const a=Xo.fromDBParts([r]);if(t.content.parts.filter(i=>Xo.fromDBParts([i])===a).length<n.content.parts.filter(i=>Xo.fromDBParts([i])===a).length){const i=n.content.parts.indexOf(r),l=i>0&&n.content.parts[i-1]?.type==="step-start",c=t.role==="assistant"&&r.type==="text"&&!l&&t.content.parts.length>0&&t.content.parts.at(-1)?.type==="tool-invocation",u=[...t.content.parts].reverse().find(f=>f.type==="step-start"),d=u?.model?mwe({type:"step-start",model:u.model}):{type:"step-start"};typeof s=="number"?c?(t.content.parts.splice(s,0,d),t.content.parts.splice(s+1,0,r)):t.content.parts.splice(s,0,r):(c&&t.content.parts.push(d),t.content.parts.push(r))}}};const Xwn=[{mediaType:"image/gif",bytesPrefix:[71,73,70],base64Prefix:"R0lG"},{mediaType:"image/png",bytesPrefix:[137,80,78,71],base64Prefix:"iVBORw"},{mediaType:"image/jpeg",bytesPrefix:[255,216],base64Prefix:"/9j/"},{mediaType:"image/webp",bytesPrefix:[82,73,70,70],base64Prefix:"UklGRg"},{mediaType:"image/bmp",bytesPrefix:[66,77],base64Prefix:"Qk"},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0],base64Prefix:"SUkqAA"},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42],base64Prefix:"TU0AKg"},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102],base64Prefix:"AAAAIGZ0eXBhdmlm"},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99],base64Prefix:"AAAAIGZ0eXBoZWlj"}],Jwn=e=>{const t=typeof e=="string"?gft(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function e1n(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Jwn(e):e}function t1n({data:e,signatures:t}){const n=e1n(e);for(const r of t)if(typeof n=="string"?n.startsWith(r.base64Prefix):n.length>=r.bytesPrefix.length&&r.bytesPrefix.every((s,a)=>n[a]===s))return r.mediaType}function OLe(e,t){let n;const r=e.type;switch(r){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${r}`)}const{data:s,mediaType:a}=k0n(n);let i=a??e.mediaType,l=s;if(l instanceof URL&&t){const c=t[l.toString()];c&&(l=c.data,i??=c.mediaType)}switch(r){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=t1n({data:l,signatures:Xwn})??i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}function _Le(e){const t=[];for(const n of e){const r=Oj(n.url,n.contentType);if(r.type==="providerFileId"){t.push({type:"file",data:n.url,mimeType:n.contentType||"application/octet-stream"});continue}let s=n.url;r.type==="raw"&&(s=M0e(n.url,n.contentType||"application/octet-stream"));let a;try{a=new URL(s)}catch{throw new Error(`Invalid URL: ${n.url}`)}switch(a.protocol){case"http:":case"https:":case"gs:":case"s3:":if(n.contentType?.startsWith("image/"))t.push({type:"image",image:a.toString(),mimeType:n.contentType});else{if(!n.contentType)throw new Error("If the attachment is not an image, it must specify a content type");t.push({type:"file",data:a.toString(),mimeType:n.contentType})}break;case"data:":if(n.contentType?.startsWith("image/"))t.push({type:"image",image:s,mimeType:n.contentType});else if(n.contentType?.startsWith("text/"))t.push({type:"file",data:s,mimeType:n.contentType});else{if(!n.contentType)throw new Error("If the attachment is not an image or text, it must specify a content type");t.push({type:"file",data:s,mimeType:n.contentType})}break;default:throw new Error(`Unsupported URL protocol: ${a.protocol}`)}}return t}const n1n=e=>{const t=new Map,n=/__split-\d+$/;return r=>{const s=e.at(-1);if(r.role===s?.role&&Array.isArray(s.content)&&Array.isArray(r.content)&&(r.role!=="assistant"||r.role==="assistant"&&r.content.at(-1)?.type!=="tool-call"))for(const a of r.content)s.content.push(a);else{let a=r.id;if(n.test(a)){e.push(r);return}const i=t.get(a)||0;i>0&&(r.id=`${a}__split-${i}`),t.set(a,i+1),e.push(r)}}};function sE(e){const t=[],n=n1n(t);for(let r=0;r<e.length;r++){const s=e[r],a=r===e.length-1;if(!s?.content)continue;const{content:i,experimental_attachments:l=[],parts:c}=s.content,{role:u}=s,d={id:s.id,createdAt:s.createdAt,resourceId:s.resourceId,threadId:s.threadId},f=[...l],p=[];for(const h of c)if(h.type==="file"){const{mediaType:m,data:v}=Aq(h);f.push({url:v,contentType:m??"application/octet-stream"})}else p.push(h);switch(u){case"user":if(p==null){const h=f?[{type:"text",text:i||""},..._Le(f)]:{type:"text",text:i||""};n({role:"user",...d,type:"text",content:h})}else{const h=s.content.parts.filter(v=>v.type==="text").map(v=>({type:"text",text:v.text})),m=f?[...h,..._Le(f)]:h;n({role:"user",...d,type:"text",content:Array.isArray(m)&&m.length===1&&m[0]?.type==="text"&&typeof i<"u"?i:m})}break;case"assistant":{if(s.content.parts!=null){let v=function(){const k=[];for(const C of x)switch(C.type){case"file":case"text":k.push(C);break;case"reasoning":for(const E of C.details)switch(E.type){case"text":k.push({type:"reasoning",text:E.text,signature:E.signature});break;case"redacted":k.push({type:"redacted-reasoning",data:E.data});break}break;case"tool-invocation":C.toolInvocation.toolName!=="updateWorkingMemory"&&k.push({type:"tool-call",toolCallId:C.toolInvocation.toolCallId,toolName:C.toolInvocation.toolName,args:C.toolInvocation.args});break}n({role:"assistant",...d,type:k.some(C=>C.type==="tool-call")?"tool-call":"text",content:typeof k!="string"&&Array.isArray(k)&&k.length===1&&k[0]?.type==="text"?k[0].text:k});const _=x.filter(C=>"type"in C&&C.type==="tool-invocation").map(C=>C.toolInvocation).filter(C=>C.toolName!=="updateWorkingMemory").filter(C=>C.state==="result"&&"result"in C);_.length>0&&n({role:"tool",...d,type:"tool-result",content:_.map(C=>{const{toolCallId:E,toolName:T,result:N}=C;return{type:"tool-result",toolCallId:E,toolName:T,result:N}})}),x=[],b=!1,y++},y=0,b=!1,x=[];for(const k of s.content.parts)switch(k.type){case"text":b&&v(),x.push(k);break;case"file":case"reasoning":x.push(k);break;case"tool-invocation":(x.some(_=>_.type==="text"||_.type==="file"||_.type==="reasoning")||(k.toolInvocation.step??0)!==y)&&v(),x.push(k),b=!0;break}v();const S=s.content.toolInvocations;if(S&&S.length>0){const k=new Set;for(const C of s.content.parts)C.type==="tool-invocation"&&C.toolInvocation.toolCallId&&k.add(C.toolInvocation.toolCallId);const _=S.filter(C=>!k.has(C.toolCallId)&&C.toolName!=="updateWorkingMemory");if(_.length>0){const C=new Map;for(const T of _){const N=T.step??0;C.has(N)||C.set(N,[]),C.get(N).push(T)}const E=Array.from(C.keys()).sort((T,N)=>T-N);for(const T of E){const N=C.get(T);n({role:"assistant",...d,type:"tool-call",content:[...N.map(({toolCallId:A,toolName:R,args:L})=>({type:"tool-call",toolCallId:A,toolName:R,args:L}))]});const I=N.filter(A=>A.state==="result"&&"result"in A);I.length>0&&n({role:"tool",...d,type:"tool-result",content:I.map(A=>{const{toolCallId:R,toolName:L,result:D}=A;return{type:"tool-result",toolCallId:R,toolName:L,result:D}})})}}}break}const h=s.content.toolInvocations;if(h==null||h.length===0){n({role:"assistant",...d,content:i||"",type:"text"});break}const m=h.reduce((v,y)=>Math.max(v,y.step??0),0);for(let v=0;v<=m;v++){const y=h.filter(x=>(x.step??0)===v&&x.toolName!=="updateWorkingMemory");if(y.length===0)continue;n({role:"assistant",...d,type:"tool-call",content:[...a&&i&&v===0?[{type:"text",text:i}]:[],...y.map(({toolCallId:x,toolName:S,args:k})=>({type:"tool-call",toolCallId:x,toolName:S,args:k}))]});const b=y.filter(x=>x.state==="result"&&"result"in x);b.length>0&&n({role:"tool",...d,type:"tool-result",content:b.map(x=>{const{toolCallId:S,toolName:k,result:_}=x;return{type:"tool-result",toolCallId:S,toolName:k,result:_}})})}i&&!a&&n({role:"assistant",...d,type:"text",content:i||""});break}}}return t}function r1n(e){return`${e.origin}${e.pathname}`}const s1n=async({url:e,downloadRetries:t})=>{const n=e.toString(),r=r1n(e);try{const s=await dfn(n,{method:"GET"},t,{shouldRetryResponse:a=>a.status>=500});if(!s.ok)throw new SO({id:"DOWNLOAD_ASSETS_FAILED",text:`Failed to download asset: ${r}`,domain:xO.LLM,category:wO.USER,details:{url:n}});return{data:new Uint8Array(await s.arrayBuffer()),mediaType:s.headers.get("content-type")??void 0}}catch(s){throw new SO({id:"DOWNLOAD_ASSETS_FAILED",text:`Failed to download asset: ${r}`,domain:xO.LLM,category:wO.USER,details:{url:n}},s)}};async function a1n({messages:e,downloadConcurrency:t=10,downloadRetries:n=3,supportedUrls:r}){const s=(await Da(async()=>{const{default:i}=await import("./index-yUiD89B4.js");return{default:i}},[],import.meta.url)).default,a=(await s(e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{const l=i.mediaType??(i.type==="image"?"image/*":void 0);let c=i.type==="image"?i.image:i.data;if(typeof c=="string")try{c=new URL(c)}catch{}return{mediaType:l,data:c}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&gfn({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:r??{}})})),async i=>i.isUrlSupportedByModel?null:{url:i.url.toString(),...await s1n({url:i.url,downloadRetries:n})},{concurrency:t})).filter(i=>i?.data!=null).map(({url:i,data:l,mediaType:c})=>[i,{data:l,mediaType:c}]);return Object.fromEntries(a)}function i1n(e){return{...e,createdAt:e.createdAt.toISOString()}}function o1n(e){return{...e,createdAt:new Date(e.createdAt)}}function l1n(e){return e.map(i1n)}function c1n(e){return e.map(o1n)}var u1n=class{memoryMessages=new Set;newUserMessages=new Set;newResponseMessages=new Set;userContextMessages=new Set;memoryMessagesPersisted=new Set;newUserMessagesPersisted=new Set;newResponseMessagesPersisted=new Set;userContextMessagesPersisted=new Set;addToSource(e,t){switch(t){case"memory":this.memoryMessages.add(e),this.memoryMessagesPersisted.add(e);break;case"response":this.memoryMessages.has(e)&&this.memoryMessages.delete(e),this.newResponseMessages.add(e),this.newResponseMessagesPersisted.add(e),this.newUserMessages.has(e)&&this.newUserMessages.delete(e);break;case"input":case"user":this.newUserMessages.add(e),this.newUserMessagesPersisted.add(e);break;case"context":this.userContextMessages.add(e),this.userContextMessagesPersisted.add(e);break;default:throw new Error(`Missing message source for message ${e}`)}}isMemoryMessage(e){return this.memoryMessages.has(e)}isUserMessage(e){return this.newUserMessages.has(e)}isResponseMessage(e){return this.newResponseMessages.has(e)}isContextMessage(e){return this.userContextMessages.has(e)}getMemoryMessages(){return this.memoryMessages}getUserMessages(){return this.newUserMessages}getResponseMessages(){return this.newResponseMessages}getContextMessages(){return this.userContextMessages}getMemoryMessagesPersisted(){return this.memoryMessagesPersisted}getUserMessagesPersisted(){return this.newUserMessagesPersisted}getResponseMessagesPersisted(){return this.newResponseMessagesPersisted}getContextMessagesPersisted(){return this.userContextMessagesPersisted}removeMessage(e){this.memoryMessages.delete(e),this.newUserMessages.delete(e),this.newResponseMessages.delete(e),this.userContextMessages.delete(e)}clearUserMessages(){this.newUserMessages.clear()}clearResponseMessages(){this.newResponseMessages.clear()}clearContextMessages(){this.userContextMessages.clear()}clearAll(){this.newUserMessages.clear(),this.newResponseMessages.clear(),this.userContextMessages.clear()}createSourceChecker(){const e={memory:new Set(Array.from(this.memoryMessages.values()).map(t=>t.id)),output:new Set(Array.from(this.newResponseMessages.values()).map(t=>t.id)),input:new Set(Array.from(this.newUserMessages.values()).map(t=>t.id)),context:new Set(Array.from(this.userContextMessages.values()).map(t=>t.id))};return{...e,getSource:t=>e.memory.has(t.id)?"memory":e.input.has(t.id)?"input":e.output.has(t.id)?"response":e.context.has(t.id)?"context":null}}isNewMessage(e){const t=typeof e=="string"?e:e.id;return typeof e!="string"&&(this.newUserMessages.has(e)||this.newResponseMessages.has(e))?!0:Array.from(this.newUserMessages).some(n=>n.id===t)||Array.from(this.newResponseMessages).some(n=>n.id===t)}serializeSourceTracking(){const e=t=>Array.from(t).map(n=>n.id);return{memoryMessages:e(this.memoryMessages),newUserMessages:e(this.newUserMessages),newResponseMessages:e(this.newResponseMessages),userContextMessages:e(this.userContextMessages),memoryMessagesPersisted:e(this.memoryMessagesPersisted),newUserMessagesPersisted:e(this.newUserMessagesPersisted),newResponseMessagesPersisted:e(this.newResponseMessagesPersisted),userContextMessagesPersisted:e(this.userContextMessagesPersisted)}}deserializeSourceTracking(e,t){const n=r=>new Set(r.map(s=>t.find(a=>a.id===s)).filter(Boolean));this.memoryMessages=n(e.memoryMessages),this.newUserMessages=n(e.newUserMessages),this.newResponseMessages=n(e.newResponseMessages),this.userContextMessages=n(e.userContextMessages),this.memoryMessagesPersisted=n(e.memoryMessagesPersisted),this.newUserMessagesPersisted=n(e.newUserMessagesPersisted),this.newResponseMessagesPersisted=n(e.newResponseMessagesPersisted),this.userContextMessagesPersisted=n(e.userContextMessagesPersisted)}serializeAll(e){return{messages:l1n(e.messages),systemMessages:e.systemMessages,taggedSystemMessages:e.taggedSystemMessages,memoryInfo:e.memoryInfo,_agentNetworkAppend:e.agentNetworkAppend,...this.serializeSourceTracking()}}deserializeAll(e){const t=c1n(e.messages);return this.deserializeSourceTracking({memoryMessages:e.memoryMessages,newUserMessages:e.newUserMessages,newResponseMessages:e.newResponseMessages,userContextMessages:e.userContextMessages,memoryMessagesPersisted:e.memoryMessagesPersisted,newUserMessagesPersisted:e.newUserMessagesPersisted,newResponseMessagesPersisted:e.newResponseMessagesPersisted,userContextMessagesPersisted:e.userContextMessagesPersisted},t),{messages:t,systemMessages:e.systemMessages,taggedSystemMessages:e.taggedSystemMessages,memoryInfo:e.memoryInfo,agentNetworkAppend:e._agentNetworkAppend}}};function d1n(e){return e.role==="system"&&e.parts.length>0&&e.parts.every(t=>t.type.startsWith("data-"))}function KX(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n];if(!d1n(r)){t.push(r);continue}const s=t[t.length-1],a=e[n+1];s&&s.role==="assistant"?t[t.length-1]={...s,parts:[...s.parts,...r.parts]}:a&&a.role==="assistant"?e[n+1]={...a,parts:[...r.parts,...a.parts]}:t.push({...r,role:"assistant"})}return t}function CLe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ELe(e,t){if(!e&&!t)return;const n={...e??{}};for(const[r,s]of Object.entries(t??{})){const a=n[r];n[r]=CLe(a)&&CLe(s)?{...a,...s}:s}return n}var f1n=class{messages=[];systemMessages=[];taggedSystemMessages={};memoryInfo=null;stateManager=new u1n;get memoryMessages(){return this.stateManager.getMemoryMessages()}get newUserMessages(){return this.stateManager.getUserMessages()}get newResponseMessages(){return this.stateManager.getResponseMessages()}get userContextMessages(){return this.stateManager.getContextMessages()}get memoryMessagesPersisted(){return this.stateManager.getMemoryMessagesPersisted()}get newUserMessagesPersisted(){return this.stateManager.getUserMessagesPersisted()}get newResponseMessagesPersisted(){return this.stateManager.getResponseMessagesPersisted()}get userContextMessagesPersisted(){return this.stateManager.getContextMessagesPersisted()}generateMessageId;_agentNetworkAppend=!1;filterIncompleteToolCalls;logger;toAIV5UIMessages(t,n){return KX(t.map(r=>Fv.toUIMessage(r,n)))}toAIV4UIMessages(t,n){return KX(t.map(r=>Bw.toUIMessage(r,n)))}toAIV6UIMessages(t){return KX(t.map(l7.toUIMessage))}isRecording=!1;recordedEvents=[];constructor({threadId:t,resourceId:n,generateMessageId:r,logger:s,filterIncompleteToolCalls:a,_agentNetworkAppend:i}={}){t&&(this.memoryInfo={threadId:t,resourceId:n}),this.generateMessageId=r,this.logger=s,this.filterIncompleteToolCalls=a??!0,this._agentNetworkAppend=i||!1}startRecording(){this.isRecording=!0,this.recordedEvents=[]}hasRecordedEvents(){return this.recordedEvents.length>0}getRecordedEvents(){return[...this.recordedEvents]}stopRecording(){this.isRecording=!1;const t=this.getRecordedEvents();return this.recordedEvents=[],t}addSignal(t,n){const r=n?.source??"input",s=this.generateCreatedAt(r,new Date),a=t.acceptedAt??t.createdAt,i={id:t.id,tagName:t.tagName,contents:t.contents,attributes:t.attributes,metadata:t.metadata,providerOptions:t.providerOptions,createdAt:s,acceptedAt:a},l=t.type==="state"?U9({...i,type:t.type}):U9({...i,type:t.type,transient:t.transient});return this.addOne(l.toDBMessage(this.memoryInfo??void 0),r),l}add(t,n,r={}){if(n==="user"&&(n="input"),!t)return this;const s=Array.isArray(t)?t:[t];this.isRecording&&this.recordedEvents.push({type:"add",source:n,count:s.length});for(const a of s){if(UDe(a)&&n==="input"){this.addSignal(a,{source:n});continue}const i=UDe(a)?a.toDBMessage(this.memoryInfo??void 0):typeof a=="string"?{role:"user",content:a}:a;if(Array.isArray(i)){for(const l of i)this.addOne(typeof l=="string"?{role:"user",content:l}:l,n,r);continue}this.addOne(typeof i=="string"?{role:"user",content:i}:i,n,r)}return this}serialize(){return this.stateManager.serializeAll({messages:this.messages,systemMessages:this.systemMessages,taggedSystemMessages:this.taggedSystemMessages,memoryInfo:this.memoryInfo,agentNetworkAppend:this._agentNetworkAppend})}serializeForSpan(){return{messages:this.all.aiV4.core().map(t=>({role:t.role,content:t.content})),systemMessages:[...this.systemMessages.map(t=>({role:t.role,content:t.content})),...Object.entries(this.taggedSystemMessages).flatMap(([t,n])=>n.map(r=>({role:r.role,content:r.content,tag:t})))]}}deserialize(t){const n=this.stateManager.deserializeAll(t);this.messages=n.messages,this.systemMessages=n.systemMessages,this.taggedSystemMessages=n.taggedSystemMessages,this.memoryInfo=n.memoryInfo,this._agentNetworkAppend=n.agentNetworkAppend;for(const r of this.messages)this.updateLastCreatedAt(r);return this}get promptConversionMode(){return this.filterIncompleteToolCalls?"prompt":"prompt-with-suspended"}getMessagesForModelPrompt(){return this.messages.flatMap(t=>t.role!=="signal"?[t]:this.convertSignalForModelPrompt(t))}convertSignalForModelPrompt(t){const n=Ifn(t).toLLMMessage(),r=t.createdAt;return[wLe({...n,id:t.id,metadata:{createdAt:r}},"input",{memoryInfo:this.memoryInfo,newMessageId:()=>t.id,generateCreatedAt:(s,a)=>a instanceof Date?a:typeof a=="string"||typeof a=="number"?new Date(a):r,dbMessages:this.messages})]}makeMessageSourceChecker(){return this.stateManager.createSourceChecker()}getLatestUserContent(){const t=this.all.core().filter(n=>n.role==="user").at(-1)?.content;return t?Fwn(t):null}get get(){return{all:this.all,remembered:this.remembered,input:this.input,response:this.response}}get getPersisted(){return{remembered:this.rememberedPersisted,input:this.inputPersisted,taggedSystemMessages:this.taggedSystemMessages,response:this.responsePersisted}}get clear(){return{all:{db:()=>{const t=[...this.messages];return this.messages=[],this.stateManager.clearAll(),this.isRecording&&t.length>0&&this.recordedEvents.push({type:"clear",count:t.length}),t}},input:{db:()=>{const t=Array.from(this.stateManager.getUserMessages());return this.messages=this.messages.filter(n=>!this.stateManager.isUserMessage(n)),this.stateManager.clearUserMessages(),this.isRecording&&t.length>0&&this.recordedEvents.push({type:"clear",source:"input",count:t.length}),t}},response:{db:()=>{const t=Array.from(this.stateManager.getResponseMessages());return this.messages=this.messages.filter(n=>!this.stateManager.isResponseMessage(n)),this.stateManager.clearResponseMessages(),this.isRecording&&t.length>0&&this.recordedEvents.push({type:"clear",source:"response",count:t.length}),t}}}}removeByIds(t){const n=new Set(t),r=[];return this.messages=this.messages.filter(s=>n.has(s.id)?(r.push(s),this.stateManager.removeMessage(s),!1):!0),this.isRecording&&r.length>0&&this.recordedEvents.push({type:"removeByIds",ids:t,count:r.length}),r}all={db:()=>this.messages,v1:()=>sE(this.all.db()),aiV5:{model:()=>{const t=this.getMessagesForModelPrompt();return bv(this.toAIV5UIMessages(t,{transformToolPayloads:!1}),t)},ui:()=>this.toAIV5UIMessages(this.all.db()),prompt:()=>{const t=SLe([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()],"system",this.createAdapterContext(),this.messages),n=this.getMessagesForModelPrompt(),r=bv(this.toAIV5UIMessages(n,{transformToolPayloads:!1}),n,this.promptConversionMode);return Z5([...t,...r],this.logger)},llmPrompt:async(t={downloadConcurrency:10,downloadRetries:3})=>{const n=this.getMessagesForModelPrompt(),r=bv(this.toAIV5UIMessages(n,{transformToolPayloads:!1}),n,this.promptConversionMode),s=new Map;for(const c of this.messages)if(!(c.content?.format!==2||!c.content.parts))for(const u of c.content.parts)u.type==="tool-invocation"&&u.toolInvocation?.state==="result"&&u.providerMetadata?.mastra&&typeof u.providerMetadata.mastra=="object"&&u.providerMetadata.mastra.modelOutput!=null&&s.set(u.toolInvocation.toolCallId,u.providerMetadata.mastra.modelOutput);if(s.size>0){for(const c of r)if(!(c.role!=="tool"||!Array.isArray(c.content)))for(let u=0;u<c.content.length;u++){const d=c.content[u];d.type==="tool-result"&&s.has(d.toolCallId)&&(c.content[u]={...d,output:s.get(d.toolCallId)})}}const a=SLe([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()],"system",this.createAdapterContext(),this.messages),i=await a1n({messages:r,downloadConcurrency:t?.downloadConcurrency,downloadRetries:t?.downloadRetries,supportedUrls:t?.supportedUrls});let l=[...a,...r];return r.some(c=>(c.role==="user"||c.role==="assistant")&&typeof c.content!="string"&&c.content.some(u=>u.type==="image"||u.type==="file"))&&(l=l.map(c=>{if(c.role==="user")return typeof c.content=="string"?{role:"user",content:[{type:"text",text:c.content}],providerOptions:c.providerOptions}:{role:"user",content:c.content.map(u=>u.type==="image"||u.type==="file"?OLe(u,i):u).filter(u=>u.type!=="text"||u.text!==""),providerOptions:c.providerOptions};if(c.role==="assistant"&&typeof c.content!="string"){const u=c.content.map(d=>d.type==="file"?OLe(d,i):d);return{...c,content:u}}return c})),l=Z5(l,this.logger),l.filter(c=>c!=null).map($fn).filter(c=>c.role==="system"||typeof c.content=="string"||c.content.length>0)}},aiV6:{ui:()=>this.toAIV6UIMessages(this.all.db()),llmPrompt:async t=>Mfn(await this.all.aiV5.llmPrompt(t))},aiV7:{ui:()=>this.toAIV6UIMessages(this.all.db()),llmPrompt:async t=>Dfn(await this.all.aiV5.llmPrompt(t))},prompt:()=>this.all.aiV4.prompt(),ui:()=>this.toAIV4UIMessages(this.all.db()),core:()=>bh(this.toAIV4UIMessages(this.all.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.all.db()),core:()=>bh(this.toAIV4UIMessages(this.getMessagesForModelPrompt(),{transformToolPayloads:!1})),prompt:()=>{const t=this.all.aiV4.core();return Z5([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat(),...t],this.logger)},llmPrompt:()=>{const t=this.all.aiV4.core();let n=[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat(),...t];return n=Z5(n,this.logger),n.map(Pfn)}}};remembered={db:()=>this.messages.filter(t=>this.memoryMessages.has(t)),v1:()=>sE(this.remembered.db()),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.remembered.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.remembered.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.remembered.db())},ui:()=>this.toAIV4UIMessages(this.remembered.db()),core:()=>bh(this.toAIV4UIMessages(this.remembered.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.remembered.db()),core:()=>bh(this.toAIV4UIMessages(this.remembered.db(),{transformToolPayloads:!1}))}};rememberedPersisted={db:()=>this.all.db().filter(t=>this.memoryMessagesPersisted.has(t)),v1:()=>sE(this.rememberedPersisted.db()),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.rememberedPersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.rememberedPersisted.db())},ui:()=>this.toAIV4UIMessages(this.rememberedPersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.rememberedPersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1}))}};input={db:()=>this.messages.filter(t=>this.newUserMessages.has(t)),v1:()=>sE(this.input.db()),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.input.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.input.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.input.db())},ui:()=>this.toAIV4UIMessages(this.input.db()),core:()=>bh(this.toAIV4UIMessages(this.input.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.input.db()),core:()=>bh(this.toAIV4UIMessages(this.input.db(),{transformToolPayloads:!1}))}};inputPersisted={db:()=>this.messages.filter(t=>this.newUserMessagesPersisted.has(t)),v1:()=>sE(this.inputPersisted.db()),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.inputPersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.inputPersisted.db())},ui:()=>this.toAIV4UIMessages(this.inputPersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.inputPersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1}))}};response={db:()=>this.messages.filter(t=>this.newResponseMessages.has(t)),v1:()=>sE(this.response.db()),aiV5:{ui:()=>this.toAIV5UIMessages(this.response.db()),model:()=>bv(this.toAIV5UIMessages(this.response.db(),{transformToolPayloads:!1}),this.messages).filter(t=>t.role==="tool"||t.role==="assistant"),modelContent:t=>typeof t=="number"?kLe.extractStepContent(this.response.aiV5.ui(),t,this.response.aiV5.stepContent):this.response.aiV5.model().map(this.response.aiV5.stepContent).flat(),stepContent:t=>kLe.convertToStepContent(t,this.messages,()=>this.response.aiV5.model().at(-1))},aiV6:{ui:()=>this.toAIV6UIMessages(this.response.db())},aiV4:{ui:()=>this.toAIV4UIMessages(this.response.db()),core:()=>bh(this.toAIV4UIMessages(this.response.db(),{transformToolPayloads:!1}))}};responsePersisted={db:()=>this.messages.filter(t=>this.newResponseMessagesPersisted.has(t)),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.responsePersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.responsePersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.responsePersisted.db())},ui:()=>this.toAIV4UIMessages(this.responsePersisted.db()),aiV4:{ui:()=>this.toAIV4UIMessages(this.responsePersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.responsePersisted.db(),{transformToolPayloads:!1}))}};drainUnsavedMessages(){const t=this.messages.filter(n=>this.newUserMessages.has(n)||this.newResponseMessages.has(n));return this.newUserMessages.clear(),this.newResponseMessages.clear(),t.map(n=>this.transformMessageForTranscript(n))}transformToolStateDataForTranscript(t,n){if(!t||typeof t!="object")return t;const r=t,s=r.metadata??r.providerMetadata,a=lg(s,"transcript",n),i=lg(s,"transcript","input-available"),l=n==="approval"?Cu(a)?a.transformed:Cu(i)?i.transformed:void 0:Cu(i)?i.transformed:Cu(a)?a.transformed:void 0,c=n==="suspend"&&Cu(a)?a.transformed:void 0;return{...r,...l!==void 0?{args:l}:{},...c!==void 0?{suspendPayload:c}:{}}}transformMessageForTranscript(t){if(t.content?.format!==2||!t.content.parts)return t;let n=!1;const r=new Map,s=t.content.parts.map(l=>{if(l.type==="tool-invocation"&&l.toolInvocation){const c=lg(l.providerMetadata,"transcript","input-available"),u=l.toolInvocation.state==="result"?lg(l.providerMetadata,"transcript","output-available")??lg(l.providerMetadata,"transcript","error"):l.toolInvocation.state==="output-error"?lg(l.providerMetadata,"transcript","error"):void 0;if(!c&&!u)return l;n=!0;const d=Cu(c)?c.transformed:l.toolInvocation.args,f=l.toolInvocation.state==="result"?Cu(u)?u.transformed:l.toolInvocation.result:void 0,p=l.toolInvocation.state==="output-error"?Cu(u)?u.transformed:l.toolInvocation.errorText:void 0;return r.set(l.toolInvocation.toolCallId,{args:d,...l.toolInvocation.state==="result"?{result:f}:{},...l.toolInvocation.state==="output-error"?{errorText:p}:{}}),{...l,toolInvocation:{...l.toolInvocation,args:d,...l.toolInvocation.state==="result"?{result:f}:{},...l.toolInvocation.state==="output-error"?{errorText:p}:{}}}}return l.type==="data-tool-call-suspended"||l.type==="data-tool-call-approval"?(n=!0,{...l,data:this.transformToolStateDataForTranscript(l.data,l.type==="data-tool-call-suspended"?"suspend":"approval")}):l}),a=t.content.toolInvocations?.map(l=>{const c=r.get(l.toolCallId);if(!c)return l;const u=l.state;return n=!0,{...l,...c.args!==void 0?{args:c.args}:{},...l.state==="result"&&c.result!==void 0?{result:c.result}:{},...u==="output-error"&&c.errorText!==void 0?{errorText:c.errorText}:{}}}),i=t.content.metadata&&typeof t.content.metadata=="object"?{...t.content.metadata}:t.content.metadata;if(i&&typeof i=="object")for(const[l,c]of[["suspendedTools","suspend"],["pendingToolApprovals","approval"]]){const u=i[l];!u||typeof u!="object"||(n=!0,i[l]=Object.fromEntries(Object.entries(u).map(([d,f])=>[d,this.transformToolStateDataForTranscript(f,c)])))}return n?{...t,content:{...t.content,parts:s,...a?{toolInvocations:a}:{},...i?{metadata:i}:{}}}:t}getEarliestUnsavedMessageTimestamp(){const t=this.messages.filter(n=>this.newUserMessages.has(n)||this.newResponseMessages.has(n));if(t.length!==0)return Math.min(...t.map(n=>new Date(n.createdAt).getTime()))}isNewMessage(t){return this.stateManager.isNewMessage(t)}updateToolInvocation(t,n){if(!t.toolInvocation?.toolCallId)return!1;const r=t.toolInvocation.toolCallId;for(let a=this.messages.length-1;a>=0;a--){const i=this.messages[a];if(!(i.role!=="assistant"||!i.content?.parts))for(let l=0;l<i.content.parts.length;l++){const c=i.content.parts[l];if(c?.type==="tool-invocation"&&c.toolInvocation?.toolCallId===r)return this.mergeToolResultIntoPart(i,l,t,n),!0}}const s=t.toolInvocation.toolName;for(let a=this.messages.length-1;a>=0;a--){const i=this.messages[a];if(!(i.role!=="assistant"||!i.content?.parts))for(let l=0;l<i.content.parts.length;l++){const c=i.content.parts[l];if(c?.type!=="tool-invocation")continue;const u=c;if(u.providerExecuted===!0&&u.toolInvocation?.state==="call"&&u.toolInvocation.toolName===s){const d=u.toolInvocation.toolCallId;return u.toolInvocation.toolCallId=r,this.mergeToolResultIntoPart(i,l,t,n,d),!0}}}return this.logger?.warn(`updateToolInvocation: no matching tool call found for toolCallId=${r}`),!1}updateMessageMetadataByToolCallId(t,n){if(!t)return!1;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(s.role!=="assistant"||!s.content?.parts||!s.content.parts.some(d=>d?.type==="tool-invocation"&&d.toolInvocation?.toolCallId===t))continue;const a=s.content.metadata??{},i=n??{},l=a.backgroundTasks,c=i.backgroundTasks,u=ELe(l,c);return s.content.metadata={...a,...i,...u?{backgroundTasks:u}:{}},this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(s),this.stateManager.isResponseMessage(s)||(this.stateManager.removeMessage(s),this.stateManager.addToSource(s,"response")),!0}return this.logger?.warn(`updateMessageMetadataByToolCallId: no matching tool call found for toolCallId=${t}`),!1}mergeToolResultIntoPart(t,n,r,s,a){const i=t.content.parts[n],l=a??i.toolInvocation.toolCallId,c=i,u=r,d=c.providerMetadata!==void 0||u.providerMetadata!==void 0?(()=>{const y=c.providerMetadata??{},b=u.providerMetadata??{},x={...y};for(const[S,k]of Object.entries(b)){const _=x[S];x[S]=_&&typeof _=="object"&&!Array.isArray(_)&&k&&typeof k=="object"&&!Array.isArray(k)?{..._,...k}:k}return x})():void 0;t.content.parts[n]={...r,toolInvocation:{...r.toolInvocation,args:i.toolInvocation.args},...c.providerExecuted!==void 0&&u.providerExecuted===void 0?{providerExecuted:c.providerExecuted}:{},...d!==void 0?{providerMetadata:d}:{}},this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(t);const f=t.content.metadata??{},p=s??{},h=f.backgroundTasks,m=p.backgroundTasks,v=ELe(h,m);if(t.content.metadata={...f,...p,...v?{backgroundTasks:v}:{}},Array.isArray(t.content.toolInvocations)&&r.toolInvocation.state==="result"){const y=r.toolInvocation;t.content.toolInvocations=t.content.toolInvocations.map(b=>b.toolCallId===l?{...b,toolCallId:y.toolCallId,state:"result",args:i.toolInvocation.args,result:y.result}:b)}this.stateManager.isResponseMessage(t)||(this.stateManager.removeMessage(t),this.stateManager.addToSource(t,"response"))}stepStart(){const t=this.messages[this.messages.length-1];return!t||t.role!=="assistant"||!t.content?.parts||mb.isSealed(t)||t.content.parts[t.content.parts.length-1]?.type==="step-start"?!1:(t.content.parts.push(mwe({type:"step-start"})),this.stateManager.isResponseMessage(t)||(this.stateManager.removeMessage(t),this.stateManager.addToSource(t,"response")),!0)}markResponseMessageBoundary(t){const n=t?this.messages.find(r=>r.id===t):[...this.messages].reverse().find(r=>r.role==="assistant");return!n||n.role!=="assistant"?!1:(n.content.metadata={...n.content.metadata??{},mastra:{...n.content.metadata?.mastra??{},responseBoundary:!0}},this.stateManager.isResponseMessage(n)||(this.stateManager.removeMessage(n),this.stateManager.addToSource(n,"response")),!0)}enrichLastStepStart(t){const n=this.messages[this.messages.length-1];if(!n||n.role!=="assistant"||!n.content?.parts||mb.isSealed(n))return!1;for(let r=n.content.parts.length-1;r>=0;r--){const s=n.content.parts[r];if(s?.type==="step-start")return s.model?!1:(s.model=t,this.stateManager.isResponseMessage(n)||(this.stateManager.removeMessage(n),this.stateManager.addToSource(n,"response")),!0)}return!1}getSystemMessages(t){return t?this.taggedSystemMessages[t]||[]:this.systemMessages}getAllSystemMessages(){return[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()]}clearSystemMessages(t){return t?delete this.taggedSystemMessages[t]:this.systemMessages=[],this}replaceAllSystemMessages(t){this.systemMessages=[];for(const n of t)n.role==="system"&&this.systemMessages.push(n);return this}addSystem(t,n){if(!t)return this;for(const r of Array.isArray(t)?t:[t])this.addOneSystem(r,n);return this}addOneSystem(t,n){const r=Kwn(t);if(r.role!=="system")throw new Error(`Expected role "system" but saw ${r.role} for message ${JSON.stringify(r,null,2)}`);n&&!this.isDuplicateSystem(r,n)?(this.taggedSystemMessages[n]||=[],this.taggedSystemMessages[n].push(r),this.isRecording&&this.recordedEvents.push({type:"addSystem",tag:n,message:r})):!n&&!this.isDuplicateSystem(r)&&(this.systemMessages.push(r),this.isRecording&&this.recordedEvents.push({type:"addSystem",message:r}))}isDuplicateSystem(t,n){return n?this.taggedSystemMessages[n]?this.taggedSystemMessages[n].some(r=>Xo.fromAIV4CoreMessageContent(r.content)===Xo.fromAIV4CoreMessageContent(t.content)):!1:this.systemMessages.some(r=>Xo.fromAIV4CoreMessageContent(r.content)===Xo.fromAIV4CoreMessageContent(t.content))}getMessageById(t){return this.messages.find(n=>n.id===t)}shouldReplaceMessage(t){if(!this.messages.length)return{exists:!1};if(!("id"in t)||!t?.id)return{exists:!1};const n=this.getMessageById(t.id);return n?{exists:!0,shouldReplace:!YX(n,t),id:n.id}:{exists:!1}}addOne(t,n,r={}){if((!("content"in t)||!t.content&&typeof t.content!="string")&&(!("parts"in t)||!t.parts))throw new SO({id:"INVALID_MESSAGE_CONTENT",domain:xO.AGENT,category:wO.USER,text:`Message with role "${t.role}" must have either a 'content' property (string or array) or a 'parts' property (array) that is not empty, null, or undefined. Received message: ${JSON.stringify(t,null,2)}`,details:{role:t.role,messageSource:n,hasContent:"content"in t,hasParts:"parts"in t}});if(t.role==="system"){if(n==="memory")return null;if(Ga.isAIV4CoreMessage(t)||Ga.isAIV6CoreMessage(t)||Ga.isAIV5CoreMessage(t)||Ga.isMastraDBMessage(t))return this.addSystem(t);throw new SO({id:"INVALID_SYSTEM_MESSAGE_FORMAT",domain:xO.AGENT,category:wO.USER,text:"Invalid system message format. System messages must be CoreMessage format with 'role' and 'content' properties. The content should be a string or valid content array.",details:{messageSource:n,receivedMessage:JSON.stringify(t,null,2)}})}const s=wLe(t,n,this.createAdapterContext()),a=s.role==="signal"?s.content.metadata?.signal:void 0;if(n==="input"&&s.role==="signal"&&!a?.acceptedAt){const y=a?.createdAt??s.createdAt.toISOString();s.createdAt=this.generateCreatedAt(n,s.createdAt),s.content.metadata={...s.content.metadata,signal:{...a,createdAt:s.createdAt.toISOString(),acceptedAt:y}}}const{exists:i,shouldReplace:l,id:c}=this.shouldReplaceMessage(s),u=this.messages.findLastIndex(y=>mb.isSealed(y)),d=this.messages.at(-1),f=this.messages.length-1,p=u===-1||f>u;if(n==="memory"){for(const y of this.messages)if(YX(y,s))return}const h=i&&c?this.messages.find(y=>y.id===c):void 0,m=!!h&&mb.isSealed(h),v=d?this.memoryMessages.has(d):!1;if(r.merge!==!1&&p&&!m&&mb.shouldMerge(d,s,n,v,this._agentNetworkAppend)&&d)mb.merge(d,s),this.updateLastCreatedAt(d),this.pushMessageToSource(d,n);else{let y=-1;l&&(y=this.messages.findIndex(x=>x.id===c));const b=y!==-1&&this.messages[y];if(l&&b){const x=u!==-1&&y<=u;if(mb.isSealed(b)){const S=b.content?.parts||[];let k=0;for(let E=S.length-1;E>=0;E--)if(S[E]?.metadata?.mastra?.sealedAt){k=E+1;break}k===0&&(k=S.length);const _=s.content.parts;let C;if(_.length<=k){if(YX(b,s))return this;C=_}else C=_.slice(k);C.length>0&&(s.id=this.generateMessageId?.({idType:"message",source:"memory"})??wo(),s.content.parts=C,s.createdAt<=b.createdAt&&(s.createdAt=new Date(b.createdAt.getTime()+1)),this.messages.push(s))}else if(x)s.id=this.generateMessageId?.({idType:"message",source:"memory"})??wo(),s.createdAt<=b.createdAt&&(s.createdAt=new Date(b.createdAt.getTime()+1)),this.messages.push(s);else{const S=this.memoryMessages.has(b);if(r.merge!==!1&&mb.shouldMerge(b,s,n,S,this._agentNetworkAppend))return mb.merge(b,s),this.updateLastCreatedAt(b),this.pushMessageToSource(b,n),this.messages.sort((k,_)=>k.createdAt.getTime()-_.createdAt.getTime()),this;this.messages[y]=s}}else i||this.messages.push(s);this.pushMessageToSource(s,n)}for(const y of this.messages)this.updateLastCreatedAt(y);return this.messages.sort((y,b)=>y.createdAt.getTime()-b.createdAt.getTime()),this}pushMessageToSource(t,n){this.stateManager.addToSource(t,n)}lastCreatedAt;updateLastCreatedAt(t){this.lastCreatedAt=Math.max(this.lastCreatedAt||0,t.createdAt.getTime())}generateCreatedAt(t,n){const r=n instanceof Date?n:typeof n=="string"||typeof n=="number"?new Date(n):void 0;if(r&&!this.lastCreatedAt)return this.lastCreatedAt=r.getTime(),r;if(r&&t==="memory")return r;const s=new Date,a=r?.getTime()||s.getTime(),i=this.lastCreatedAt||0;if(a<=i){const l=new Date(i+1);return this.lastCreatedAt=l.getTime(),l}return this.lastCreatedAt=a,r??s}newMessageId(t){return this.generateMessageId?this.generateMessageId({idType:"message",source:"agent",threadId:this.memoryInfo?.threadId,resourceId:this.memoryInfo?.resourceId,role:t}):wo()}createAdapterContext(){return{memoryInfo:this.memoryInfo,newMessageId:()=>this.newMessageId(),generateCreatedAt:(t,n)=>this.generateCreatedAt(t,n),dbMessages:this.messages}}};const hmt=g.createContext({}),p1n=({children:e,baseUrl:t,headers:n,apiPrefix:r,credentials:s="include",customFetch:a})=>{const i=g.useMemo(()=>v1n(t,n,r,s,a),[t,n,r,s,a]);return o.jsx(hmt.Provider,{value:i,children:e})},Ze=()=>g.useContext(hmt),h1n=/^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,m1n=e=>{const t=h1n.exec(e);return t?+t[1]<=255&&+t[2]<=255&&+t[3]<=255:!1},g1n=e=>{if(!e)return!0;try{const{hostname:t}=new URL(e);return t==="localhost"||t.endsWith(".localhost")||m1n(t)||t==="::1"||t==="[::1]"}catch{return!1}},v1n=(e,t={},n,r="include",s)=>new SP({baseUrl:e||"",headers:g1n(e)?{...t,"x-mastra-dev-playground":"true"}:t,apiPrefix:n,credentials:r,fetch:s}),y1n=({children:e,baseUrl:t,headers:n,apiPrefix:r,credentials:s,customFetch:a})=>o.jsx(p1n,{baseUrl:t,headers:n,apiPrefix:r,credentials:s,customFetch:a,children:e}),gwe=e=>{let n="";for(let r=0;r<e.length;r+=32768)n+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(n)};function b1n(e){if(typeof e=="string")return e;const t=e instanceof ArrayBuffer?new Uint8Array(e):e;return gwe(t)}function c7(e,t){if(typeof e=="string")return e;if(e instanceof URL)return e.toString();const n=e instanceof ArrayBuffer?new Uint8Array(e):e,r=gwe(n);return r.startsWith("data:")?r:`data:${t};base64,${r}`}const mmt=(e,t,n,r)=>{const s=[];s.push("#### Completion Check Results"),s.push(""),s.push(`Overall: ${e.complete?"✅ COMPLETE":"❌ NOT COMPLETE"}`),s.push(`Duration: ${e.totalDuration}ms`),e.timedOut&&s.push("⚠️ Scoring timed out"),s.push("");for(const a of e.scorers)s.push(n(a)),s.push(`Score: ${a.score} ${a.passed?"✅":"❌"}`),a.reason&&s.push(`Reason: ${a.reason}`),s.push("");return e.complete?s.push("✅ The task is complete."):t?s.push("⚠️ Max iterations reached."):s.push(r),s.join(`
|
|
197
|
+
`):void 0,experimental_attachments:l.length>0?l:void 0,content:u||void 0,metadata:Object.keys(d).length>0?d:void 0}};return e.providerOptions&&(f.content.providerMetadata=e.providerOptions),f}};function vd(e,t){for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function cv(e,t,n){const r=lg(e,"display",t);return Cu(r)?r.transformed:n}function Twn(e){return e.startsWith("tool-")?nu(e.slice(5)):nu(e)}function dmt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function jwn(e){return typeof e=="object"&&e&&"value"in e?e.value:e}function Nwn(e){return e==="approval-requested"||e==="approval-responded"||e==="output-denied"}function Iwn(e){if(e)return{id:e.id,approved:"approved"in e?e.approved:void 0,reason:"reason"in e?e.reason:void 0}}function Awn(e){return e.type==="dynamic-tool"?nu(e.toolName):Twn(e.type)}function Rwn(e){const t={toolCallId:e.toolCallId,toolName:Awn(e),args:dmt(e.input),approval:"approval"in e?Iwn(e.approval):void 0,providerMetadata:"callProviderMetadata"in e?e.callProviderMetadata:void 0,providerExecuted:e.providerExecuted,title:e.title,preliminary:"preliminary"in e?e.preliminary:void 0};switch(e.state){case"input-streaming":return bw({...t,state:"partial-call"});case"input-available":return bw({...t,state:"call"});case"output-available":return bw({...t,state:"result",result:jwn(e.output)});case"output-error":return bw({...t,state:"output-error",errorText:e.errorText,rawInput:"rawInput"in e?e.rawInput:void 0});case"approval-requested":case"approval-responded":case"output-denied":return bw({...t,state:e.state})}}function Pwn(e){return e.type==="dynamic-tool"&&!Nwn(e.state)?{...e,type:`tool-${nu(e.toolName)}`}:e}function bw({toolCallId:e,toolName:t,args:n,state:r,approval:s,result:a,errorText:i,rawInput:l,providerMetadata:c,providerExecuted:u,title:d,preliminary:f}){return vd({type:"tool-invocation",toolInvocation:vd({toolCallId:e,toolName:t,args:n,state:r},{approval:s,result:a,errorText:i,rawInput:l})},{providerMetadata:c,providerExecuted:u,title:d,preliminary:f})}function fmt(e,t){for(const n of e)if(n.type==="tool-invocation"&&n.toolInvocation.toolCallId===t)return n}function $wn(e,t){if(e)for(const n of[...e].reverse()){for(const s of[...n.content.parts||[]].reverse())if(s.type==="tool-invocation"&&s.toolInvocation.approval?.id===t&&s.toolInvocation.state==="approval-requested")return s;const r=n.content.metadata?.pendingToolApprovals;if(!(!r||typeof r!="object"))for(const s of Object.values(r)){if(!s||typeof s!="object")continue;const a="toolCallId"in s?s.toolCallId:void 0;if(typeof a!="string")continue;const i="runId"in s?s.runId:void 0,l=typeof i=="string"?`${i}::${a}`:a;if(l!==t)continue;const c=fmt(n.content.parts||[],a);if(c)return bw({toolCallId:c.toolInvocation.toolCallId,toolName:c.toolInvocation.toolName,args:c.toolInvocation.args,state:"approval-requested",approval:{id:l},providerMetadata:c.providerMetadata,providerExecuted:c.providerExecuted,title:c.title,preliminary:c.preliminary})}}}function Mwn(e,t){const n=t.pendingToolApprovals;if(!(!n||typeof n!="object"))for(const r of Object.values(n)){if(!r||typeof r!="object")continue;const s="toolCallId"in r?r.toolCallId:void 0;if(typeof s!="string")continue;const a="runId"in r?r.runId:void 0,i=typeof a=="string"?`${a}::${s}`:s,l=e.findIndex(u=>o7(u)&&u.toolCallId===s&&u.state==="input-available");if(l===-1)continue;const c=e[l];!c||!o7(c)||c.state!=="input-available"||(e[l]={...c,state:"approval-requested",approval:{id:i}})}}function Dwn(e){const t=[];for(const n of e){if(n.type!=="tool-invocation")continue;const r=n.toolInvocation;if(r.state==="result"){t.push({args:r.args,result:r.result,toolCallId:r.toolCallId,toolName:r.toolName,state:"result"});continue}(r.state==="call"||r.state==="partial-call")&&t.push({args:r.args,toolCallId:r.toolCallId,toolName:r.toolName,state:r.state})}return t.length>0?t:void 0}var l7=class ow{static toUIMessage(t){const n=Fv.toUIMessage(t),r=n.metadata||{},s=[];if(t.role==="signal"&&n.role!=="user")return{id:t.id,role:"system",metadata:Object.keys(r).length>0?r:void 0,parts:n.parts.map(d=>ow.toUIPartFromV5(d))};const a=t.content.parts||[],i=a.some(d=>d.type==="tool-invocation"),l=a.some(d=>d.type==="reasoning"),c=a.some(d=>d.type==="file"),u=a.some(d=>d.type==="text");for(const d of a)s.push(ow.toUIPart(d));if(!i||!l||!c||!u)for(const d of n.parts){if(Mp(d)){i||s.push(ow.toUIPartFromV5(d));continue}if(d.type==="reasoning"){l||s.push(ow.toUIPartFromV5(d));continue}if(d.type==="file"){c||s.push(ow.toUIPartFromV5(d));continue}d.type==="text"&&!u&&s.push(ow.toUIPartFromV5(d))}return Mwn(s,r),{id:t.id,role:t.role==="signal"?n.role:t.role,metadata:Object.keys(r).length>0?r:void 0,parts:s}}static fromUIMessage(t){const n=t.parts.filter(l=>!(l.type==="source-document"||o7(l))),r=Fv.fromUIMessage({...t,parts:n.map(l=>Pwn(l))}),s=r.content.parts||[],a=[];let i=0;for(const l of t.parts){if(l.type==="source-document"){a.push(vd({type:"source-document",sourceId:l.sourceId,mediaType:l.mediaType,title:l.title},{filename:l.filename,providerMetadata:l.providerMetadata}));continue}if(!o7(l)){const c=s[i++];c&&a.push(c);continue}a.push(Rwn(l))}return{...r,content:{...r.content,parts:a,toolInvocations:Dwn(a)||r.content.toolInvocations}}}static fromModelMessage(t,n,r={}){const s=Array.isArray(t.content)?t.content:[{type:"text",text:t.content}],a=s.filter(c=>c.type!=="tool-approval-request"&&c.type!=="tool-approval-response"),i=Fv.fromModelMessage({...t,content:a},n,r),l=[...i.content.parts];if(t.role==="assistant"){const c=new Map;for(const u of s){if(u.type==="tool-call"){c.set(u.toolCallId,{toolName:nu(u.toolName),args:dmt(u.input)});continue}if(u.type!=="tool-approval-request")continue;const d=c.get(u.toolCallId),f=fmt(l,u.toolCallId);if(f){f.toolInvocation.state="approval-requested",f.toolInvocation.approval={id:u.approvalId};continue}l.push(bw({toolCallId:u.toolCallId,toolName:d?.toolName||"unknown",args:d?.args||{},state:"approval-requested",approval:{id:u.approvalId}}))}}else if(t.role==="tool")for(const c of s){if(c.type!=="tool-approval-response")continue;const u=$wn(r.dbMessages,c.approvalId);u&&l.push(bw({toolCallId:u.toolInvocation.toolCallId,toolName:u.toolInvocation.toolName,args:u.toolInvocation.args,state:"approval-responded",approval:{id:c.approvalId,approved:c.approved,reason:c.reason},providerMetadata:u.providerMetadata,providerExecuted:u.providerExecuted,title:u.title}))}return{...i,content:{...i.content,parts:l}}}static toUIPart(t){if(t.type==="tool-invocation"){const n=vd({type:`tool-${nu(t.toolInvocation.toolName)}`,toolCallId:t.toolInvocation.toolCallId,providerExecuted:t.providerExecuted},{callProviderMetadata:t.providerMetadata,title:t.title});switch(t.toolInvocation.state){case"partial-call":return{...n,state:"input-streaming",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args)};case"call":return{...n,state:"input-available",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args)};case"approval-requested":return{...n,state:"approval-requested",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId}};case"approval-responded":return{...n,state:"approval-responded",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId,approved:t.toolInvocation.approval?.approved??!1,reason:t.toolInvocation.approval?.reason}};case"output-error":return vd({...n,state:"output-error",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),errorText:cv(t.providerMetadata,"error",t.toolInvocation.errorText||"")},{rawInput:t.toolInvocation.rawInput,approval:t.toolInvocation.approval?.approved===!0?{id:t.toolInvocation.approval.id,approved:!0,reason:t.toolInvocation.approval.reason}:void 0});case"output-denied":return{...n,state:"output-denied",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),approval:{id:t.toolInvocation.approval?.id||t.toolInvocation.toolCallId,approved:!1,reason:t.toolInvocation.approval?.reason}};case"result":return vd({...n,state:"output-available",input:cv(t.providerMetadata,"input-available",t.toolInvocation.args),output:cv(t.providerMetadata,"output-available",cv(t.providerMetadata,"error",t.toolInvocation.result))},{preliminary:t.preliminary,approval:t.toolInvocation.approval?.approved===!0?{id:t.toolInvocation.approval.id,approved:!0,reason:t.toolInvocation.approval.reason}:void 0});default:throw new Error(`Unhandled toolInvocation.state: ${String(t.toolInvocation.state)}`)}}return t.type==="source-document"?vd({type:"source-document",sourceId:t.sourceId,mediaType:t.mediaType,title:t.title},{filename:t.filename,providerMetadata:t.providerMetadata}):ow.toUIPartFromV5(Fv.toUIMessage({id:"tmp",role:"assistant",createdAt:new Date,content:{format:2,parts:[t]}}).parts[0])}static toUIPartFromV5(t){if(Mp(t)){const n={type:t.type,toolCallId:t.toolCallId,providerExecuted:t.providerExecuted};switch(t.state){case"input-streaming":return vd({...n,state:"input-streaming",input:t.input},{callProviderMetadata:"callProviderMetadata"in t?t.callProviderMetadata:void 0,title:"title"in t?t.title:void 0});case"input-available":return vd({...n,state:"input-available",input:t.input},{callProviderMetadata:"callProviderMetadata"in t?t.callProviderMetadata:void 0,title:"title"in t?t.title:void 0});case"output-available":return vd({...n,state:"output-available",input:t.input,output:t.output},{callProviderMetadata:"callProviderMetadata"in t?t.callProviderMetadata:void 0,preliminary:"preliminary"in t?t.preliminary:void 0,title:"title"in t?t.title:void 0});case"output-error":return vd({...n,state:"output-error",input:t.input,errorText:t.errorText},{rawInput:"rawInput"in t?t.rawInput:void 0,callProviderMetadata:"callProviderMetadata"in t?t.callProviderMetadata:void 0,title:"title"in t?t.title:void 0})}}switch(t.type){case"text":return vd({type:"text",text:t.text},{providerMetadata:t.providerMetadata});case"reasoning":return vd({type:"reasoning",text:t.text,state:t.state},{providerMetadata:t.providerMetadata});case"file":return vd({type:"file",url:t.url,mediaType:t.mediaType},{filename:"filename"in t?t.filename:void 0,providerMetadata:t.providerMetadata});case"source-url":return vd({type:"source-url",sourceId:t.sourceId,url:t.url},{title:t.title,providerMetadata:t.providerMetadata});case"step-start":return{type:"step-start"};default:return typeof t.type=="string"&&t.type.startsWith("data-")?{type:t.type,data:"data"in t?t.data:void 0}:t}}};function Lwn(e){return JSON.stringify(e,(t,n)=>{if(n&&typeof n=="object"&&!Array.isArray(n)){const r={};for(const s of Object.keys(n).sort())r[s]=n[s];return r}return n})}function W0(e,...t){const n=new Set(t.flatMap(r=>E0n(r)));for(const r of n)e+=`|${r}`;return e}var Xo=class Ehe{static fromAIV4Parts(t){let n="";for(const r of t)n+=r.type,n+=Ehe.fromAIV4Part(r);return n}static fromAIV4Part(t){let n="";if(t.type==="text"&&(n+=t.text,n=W0(n,t.providerMetadata)),t.type==="tool-invocation"){if(!t.toolInvocation)return n;n+=t.toolInvocation.toolCallId,n+=t.toolInvocation.state}if(t.type==="reasoning"){n+=t.reasoning,n+=(t.details??[]).reduce((s,a)=>a.type==="text"?s+(a.text?.length??0)+(a.signature?.length||0):s,0);const r=t;r&&Object.hasOwn(r,"providerMetadata")&&(n=W0(n,r.providerMetadata))}if(t.type==="file"){const{mediaType:r,data:s}=Aq(t);n+=s,n+=r}return n}static fromDBParts(t){let n="";for(const r of t)if(n+=r.type,r.type.startsWith("data-")){const s=r.data;n+=Lwn(s)}else n+=Ehe.fromAIV4Part(r);return n}static fromAIV4CoreMessageContent(t){if(typeof t=="string")return t;let n="";for(const r of t){if(n+=r.type,r.type==="text"){n+=r.text.length;const s=r;n=W0(n,s.providerMetadata,s.providerOptions)}if(r.type==="reasoning"){n+=r.text.length;const s=r;n=W0(n,s.providerMetadata,s.providerOptions)}r.type==="tool-call"&&(n+=r.toolCallId,n+=r.toolName),r.type==="tool-result"&&(n+=r.toolCallId,n+=r.toolName),r.type==="file"&&(n+=r.filename,n+=r.mimeType),r.type==="image"&&(n+=VDe(r.image),n+=r.mimeType),r.type==="redacted-reasoning"&&(n+=r.data.length)}return n}static fromAIV5Parts(t){let n="";for(const r of t)n+=r.type,r.type==="text"&&(n+=r.text,n=W0(n,r.providerMetadata)),(Mp(r)||r.type==="dynamic-tool")&&(n+=r.toolCallId,n+=r.state),r.type==="reasoning"&&(n+=r.text,n=W0(n,r.providerMetadata)),r.type==="file"&&(n+=r.url.length,n+=r.mediaType,n+=r.filename||"");return n}static fromAIV5ModelMessageContent(t){if(typeof t=="string")return t;let n="";for(const r of t)n+=r.type,r.type==="text"&&(n+=r.text.length,n=W0(n,r.providerOptions)),r.type==="reasoning"&&(n+=r.text.length,n=W0(n,r.providerOptions)),r.type==="tool-call"&&(n+=r.toolCallId,n+=r.toolName),r.type==="tool-result"&&(n+=r.toolCallId,n+=r.toolName),r.type==="file"&&(n+=r.filename,n+=r.mediaType),r.type==="image"&&(n+=VDe(r.image),n+=r.mediaType);return n}};function Fwn(e){return typeof e=="string"?e:e.reduce((t,n)=>(n.type==="text"&&(t+=n.text),t),"")}function YX(e,t){const n=Ga.isAIV4UIMessage(e)&&e,r=Ga.isAIV4UIMessage(t)&&t;if(n&&!r)return!1;if(n&&r)return Xo.fromAIV4Parts(e.parts)===Xo.fromAIV4Parts(t.parts);const s=Ga.isAIV4CoreMessage(e)&&e,a=Ga.isAIV4CoreMessage(t)&&t;if(s&&!a)return!1;if(s&&a)return Xo.fromAIV4CoreMessageContent(s.content)===Xo.fromAIV4CoreMessageContent(a.content);const i=Ga.isMastraMessageV1(e)&&e,l=Ga.isMastraMessageV1(t)&&t;if(i&&!l)return!1;if(i&&l)return i.id===l.id&&Xo.fromAIV4CoreMessageContent(i.content)===Xo.fromAIV4CoreMessageContent(l.content);const c=Ga.isMastraDBMessage(e)&&e,u=Ga.isMastraDBMessage(t)&&t;if(c&&!u)return!1;if(c&&u)return c.id===u.id&&Xo.fromDBParts(c.content.parts)===Xo.fromDBParts(u.content.parts);const d=Ga.isAIV5UIMessage(e)&&e,f=Ga.isAIV5UIMessage(t)&&t;if(d&&!f)return!1;if(d&&f)return Xo.fromAIV5Parts(e.parts)===Xo.fromAIV5Parts(t.parts);const p=Ga.isAIV5CoreMessage(e)&&e,h=Ga.isAIV5CoreMessage(t)&&t;return p&&!h?!1:p&&h?Xo.fromAIV5ModelMessageContent(p.content)===Xo.fromAIV5ModelMessageContent(h.content):!0}function mwe(e){return e.createdAt==null&&(e.createdAt=Date.now()),e}function rE(e,t){return t==="memory"||!Array.isArray(e.content.parts)||(e.content.parts=e.content.parts.map(n=>mwe(n))),e}function wLe(e,t,n){if(t!=="memory"&&"threadId"in e&&e.threadId&&n.memoryInfo&&e.threadId!==n.memoryInfo.threadId)throw new Error(`Received input message with wrong threadId. Input ${e.threadId}, expected ${n.memoryInfo.threadId}`);if(t!=="memory"&&"resourceId"in e&&e.resourceId&&n.memoryInfo?.resourceId&&e.resourceId!==n.memoryInfo.resourceId)throw new Error(`Received input message with wrong resourceId. Input ${e.resourceId}, expected ${n.memoryInfo.resourceId}`);if(Ga.isMastraMessageV1(e))return rE(zwn(e,t,n),t);if(Ga.isMastraDBMessage(e))return rE(Bwn(e,n,t),t);if(Ga.isAIV4CoreMessage(e))return rE(Bw.fromCoreMessage(e,n,t),t);if(Ga.isAIV4UIMessage(e))return rE(Bw.fromUIMessage(e,n,t),t);const r="id"in e&&typeof e.id=="string"?e.id:n.newMessageId();if(Ga.isAIV6CoreMessage(e)){const s=l7.fromModelMessage(e,t,n),a="metadata"in e&&e.metadata&&typeof e.metadata=="object"&&"createdAt"in e.metadata?e.metadata.createdAt:void 0;return{...s,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId}}if(Ga.isAIV6UIMessage(e)){const s=l7.fromUIMessage(e),a="createdAt"in e?e.createdAt:void 0;return{...s,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId}}if(Ga.isAIV5CoreMessage(e)){const s=Fv.fromModelMessage(e,t,n),a="metadata"in e&&e.metadata&&typeof e.metadata=="object"&&"createdAt"in e.metadata?e.metadata.createdAt:void 0;return rE({...s,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId},t)}if(Ga.isAIV5UIMessage(e)){const s=Fv.fromUIMessage(e),a="createdAt"in e?e.createdAt:void 0;return rE({...s,id:r,createdAt:n.generateCreatedAt(t,a),threadId:n.memoryInfo?.threadId,resourceId:n.memoryInfo?.resourceId},t)}throw new Error(`Found unhandled message ${JSON.stringify(e)}`)}function zwn(e,t,n){const r=Bw.fromCoreMessage({content:e.content,role:e.role},n,t);return{id:e.id,role:r.role,createdAt:n.generateCreatedAt(t,e.createdAt),threadId:e.threadId,resourceId:e.resourceId,content:r.content}}function Bwn(e,t,n){return e.id||(e.id=t.newMessageId()),e.createdAt===void 0||e.createdAt===null?e.createdAt=t.generateCreatedAt(n):e.createdAt instanceof Date||(e.createdAt=new Date(e.createdAt)),e.content.toolInvocations&&e.content.parts&&(e.content.toolInvocations=e.content.toolInvocations.map(r=>{if(!r.args||Object.keys(r.args).length===0){const s=e.content.parts.find(a=>a.type==="tool-invocation"&&a.toolInvocation&&a.toolInvocation.toolCallId===r.toolCallId&&a.toolInvocation.args&&Object.keys(a.toolInvocation.args).length>0);if(s&&s.type==="tool-invocation")return{...r,args:s.toolInvocation.args}}return r})),!e.threadId&&t.memoryInfo?.threadId&&(e.threadId=t.memoryInfo.threadId),!e.resourceId&&t.memoryInfo?.resourceId&&(e.resourceId=t.memoryInfo.resourceId),e}function Uwn(e){return e.type.startsWith("source-")}function Vwn(e){const t=[];for(const n of e){if(n.type!=="text"){t.push(n);continue}const r=n,s=hLe(r.providerMetadata);if(!s){t.push(n);continue}let a=!1;for(let i=t.length-1;i>=0;i--){const l=t[i];if(l.type==="text"){const c=l;hLe(c.providerMetadata)===s&&(t[i]={...c,text:c.text+r.text},a=!0);break}if(!Uwn(l))break}a||t.push(n)}return t}function qwn(e){return e.map(t=>{if(t.parts.length===0)return!1;const n=t.parts.filter(s=>s.type!=="tool-invocation"||s.toolInvocation.state!=="call"&&s.toolInvocation.state!=="partial-call");if(!n.length)return!1;const r={...t,parts:n};return"toolInvocations"in t&&t.toolInvocations&&(r.toolInvocations=t.toolInvocations.filter(s=>s.state==="result")),r}).filter(t=>!!t)}function pmt(e,t="response"){let n=-1;for(let a=e.length-1;a>=0;a--)if(e[a].role==="user"){n=a;break}const r=(a,i)=>a.parts.filter(l=>typeof l.type=="string"&&l.type.startsWith("data-")||l.type==="text"&&(!("text"in l)||l.text===""||l.text?.trim()==="")&&(a.role==="user"||a.parts.some(c=>!(c.type==="text"&&(!("text"in c)||c.text===""||c.text?.trim()===""))))?!1:Mp(l)?t!=="response"?l.state==="output-available"||l.state==="output-error"?!0:l.state==="input-available"?l.providerExecuted?i:t==="prompt-with-suspended":!1:l.state!=="input-streaming":!0);let s=-1;if(n!==e.length-1)for(let a=e.length-1;a>n;a--){const i=e[a];if(!(i.role!=="assistant"||i.parts.length===0)&&r(i,!0).length>0){s=a;break}}return e.map((a,i)=>{if(a.parts.length===0)return!1;const l=a.role==="assistant"&&i===s,c=r(a,l);if(!c.length)return!1;const u=Vwn(c);return{...a,parts:u.map(d=>Mp(d)&&d.state==="output-available"?{...d,output:(()=>{const f=d.output;if(f==null||typeof f!="object")return f;const p=f;return p.type==="content"&&Array.isArray(p.value)?f:"value"in p?p.value:f})()}:d)}}).filter(a=>!!a)}function Hwn(e){for(const t of e)if(t.role==="assistant")for(const[n,r]of t.parts.entries()){if(!Mp(r))continue;const s=t.parts.at(n+1);s&&s.type!=="step-start"&&!Mp(s)&&t.parts.splice(n+1,0,{type:"step-start"}),s&&Mp(s)&&!r.providerExecuted&&s.providerExecuted&&(s.state==="output-available"||s.state==="output-error")&&t.parts.splice(n+1,0,{type:"step-start"})}return e}function bh(e){const t=qwn(e),n=new Map;let r=0;const s=Mxn(t.map(i=>{if(i.role!=="user")return i;const l=r++;if(!i.experimental_attachments?.length)return i;const c=i.experimental_attachments.filter(d=>Oj(d.url,d.contentType).type==="providerFileId");if(!c.length)return i;n.set(l,c);const u=i.experimental_attachments.filter(d=>!c.includes(d));return{...i,experimental_attachments:u.length?u:void 0}}));if(!n.size)return s;let a=0;return s.map(i=>{if(i.role!=="user")return i;const l=n.get(a++);if(!l)return i;const c=l.map(d=>({type:"file",data:d.url,mimeType:d.contentType||"application/octet-stream"})),u=typeof i.content=="string"?[{type:"text",text:i.content}]:i.content;return{...i,content:[...u,...c]}})}function Wwn(e){if(!e||typeof e!="object")return;const t=e.content;if(!Array.isArray(t)||!t.some(r=>{if(!r||typeof r!="object")return!1;const s=r;return(s.type==="image"||s.type==="audio")&&typeof s.data=="string"}))return;const n=t.map(r=>{if(!r||typeof r!="object")return null;const s=r;switch(s.type){case"text":return{type:"text",text:String(s.text??"")};case"image":return typeof s.data=="string"?{type:"image-data",data:s.data,mediaType:String(s.mimeType??"image/png")}:{type:"text",text:JSON.stringify(s)};case"audio":return typeof s.data=="string"?{type:"file-data",data:s.data,mediaType:String(s.mimeType??"audio/wav")}:{type:"text",text:JSON.stringify(s)};default:return{type:"text",text:JSON.stringify(s)}}}).filter(Boolean);return n.length>0?{type:"content",value:n}:void 0}function Zwn(e){const t=new Map;for(const n of e)if(!(n.content?.format!==2||!n.content.parts))for(const r of n.content.parts){if(r.type!=="tool-invocation"||r.toolInvocation?.state!=="result")continue;const s=r.providerMetadata?.mastra;s&&typeof s=="object"&&"modelOutput"in s||t.set(r.toolInvocation.toolCallId,r.toolInvocation.result)}return t}function Gwn(e,t){if(!e||typeof e!="object")return!1;const n=e;return n.type!=="json"?!1:n.value===t||ohe(n.value,t)}function Qwn(e,t){const n=Zwn(t);return n.size===0?e:e.map(r=>{if(r.role!=="tool"||!Array.isArray(r.content))return r;let s=!1;const a=r.content.map(i=>{if(i.type!=="tool-result"||!n.has(i.toolCallId)||i.output?.type!=="json")return i;const l=n.get(i.toolCallId);let c;try{if(c=Wwn(l),!c||!Gwn(i.output,l))return i}catch{return i}return s=!0,{...i,output:c}});return s?{...r,content:a}:r})}function Ywn(e,t){const n=[];for(const s of t)if(s.role==="assistant")for(const a of s.parts)a.type==="file"&&n.push(a.providerMetadata??void 0);if(n.length===0||n.every(s=>s==null))return e;let r=0;return e.map(s=>{if(s.role!=="assistant"||typeof s.content=="string")return s;let a=!1;const i=s.content.map(l=>{if(l.type!=="file"||r>=n.length)return l;const c=n[r++];return l.providerOptions||!c?l:(a=!0,{...l,providerOptions:c})});return a?{...s,content:i}:s})}function bv(e,t,n="response"){const r=Hwn(pmt(e,n)),s=[];for(const i of r){const l=xpt([i]);if(l.length===0)continue;const c=i.metadata&&typeof i.metadata=="object"&&"providerMetadata"in i.metadata?i.metadata.providerMetadata:void 0;if(c){let u=-1;for(let d=l.length-1;d>=0;d--)if(l[d]?.role===i.role){u=d;break}u!==-1&&(l[u]={...l[u],providerOptions:c})}s.push(...l)}const a=T0n(Qwn(Ywn(s,r),t),t);switch(n){case"prompt":return Yht(a);case"prompt-with-suspended":return j0n(a);default:return a}}function SLe(e,t,n,r){return bv(e.map(s=>Bw.fromCoreMessage(s,n,t)).map(s=>Fv.toUIMessage(s)),r)}function Kwn(e){if(typeof e=="string")return{role:"system",content:e};if(Ga.isAIV6CoreMessage(e)){const t=l7.fromModelMessage(e,"system");return Bw.systemToV4Core(t)}if(Ga.isAIV5CoreMessage(e)){const t=Fv.fromModelMessage(e,"system");return Bw.systemToV4Core(t)}return Ga.isMastraDBMessage(e)?Bw.systemToV4Core(e):e}var kLe=class Tb{static extractStepContent(t,n,r){const s=t.flatMap(i=>i.parts),a=[];return s.forEach((i,l)=>{i.type==="step-start"&&a.push(l)}),n===-1?Tb.extractLastStep(s,a,r):n===1?Tb.extractFirstStep(s,a,r):Tb.extractMiddleStep(s,a,n,r)}static extractLastStep(t,n,r){const s=t.filter(c=>c.type?.startsWith("tool-")),a=n.length>0;if(!a&&s.length>0){const c=s[s.length-1];if(!c)return[];const u=t.indexOf(c),d=s[s.length-2],f=(d?t.indexOf(d):-1)+1,p=t.slice(f,u+1);return Tb.convertPartsToContent(p,"last-step",r)}if(n.length+1===1&&!a)return Tb.convertPartsToContent(t,"last-step",r);const i=n[n.length-1];if(i===void 0)return[];const l=t.slice(i+1);return l.length===0?[]:Tb.convertPartsToContent(l,"last-step",r)}static extractFirstStep(t,n,r){const s=n[0]??t.length;if(s===0)return[];const a=t.slice(0,s);return Tb.convertPartsToContent(a,"step-1",r)}static extractMiddleStep(t,n,r,s){const a=r-2;if(a<0||a>=n.length)return[];const i=(n[a]??0)+1,l=n[a+1]??t.length;if(i>=l)return[];const c=t.slice(i,l);return Tb.convertPartsToContent(c,`step-${r}`,s)}static convertPartsToContent(t,n,r){return xpt(pmt([{id:n,role:"assistant",parts:t}])).flatMap(r)}static convertToStepContent(t,n,r){const s=t||r();return s?typeof s.content=="string"?[{type:"text",text:s.content}]:s.content.map(a=>a.type==="tool-result"?{type:"tool-result",input:Dq(n,a.toolCallId),output:a.output,toolCallId:a.toolCallId,toolName:a.toolName}:a.type==="file"?{type:"file",file:new pLe({data:typeof a.data=="string"?V9(a.data).base64Content:a.data instanceof URL?a.data.toString():kO(a.data),mediaType:a.mediaType})}:a.type==="image"?{type:"file",file:new pLe({data:typeof a.image=="string"?V9(a.image).base64Content:a.image instanceof URL?a.image.toString():kO(a.image),mediaType:a.mediaType||"unknown"})}:{...a}):[]}},mb=class _P{static isSealed(t){return t.content?.metadata?.mastra?.sealed===!0}static shouldMerge(t,n,r,s,a=!1){if(!t||_P.isSealed(t)||t.content?.metadata?.mastra?.responseBoundary||n.content.metadata?.completionResult||t.content.metadata?.completionResult||n.content.metadata?.isTaskCompleteResult||t.content.metadata?.isTaskCompleteResult)return!1;const i=t.content?.parts??[];return i.length>0&&i.every(l=>l.type.startsWith("data-"))&&t.id!==n.id?!1:t.role==="assistant"&&n.role==="assistant"&&t.threadId===n.threadId&&r!=="memory"&&(a?!s:!0)}static merge(t,n){n.content.metadata&&(t.content.metadata={...t.content.metadata??{},...n.content.metadata});const r=new Map,s=new Map;for(const[a,i]of n.content.parts.entries())if(i.type==="tool-invocation"){if(!i.toolInvocation)continue;const l=[...t.content.parts].reverse().find(c=>c.type==="tool-invocation"&&c.toolInvocation?.toolCallId===i.toolInvocation.toolCallId);if(l&&l.type==="tool-invocation"){if(i.toolInvocation.state==="result"){l.toolInvocation={...l.toolInvocation,step:i.toolInvocation.step,state:"result",result:i.toolInvocation.result,args:{...l.toolInvocation.args,...i.toolInvocation.args}},i.providerMetadata&&(l.providerMetadata={...l.providerMetadata,...i.providerMetadata}),t.content.toolInvocations||(t.content.toolInvocations=[]);const u=t.content.toolInvocations.findIndex(d=>d.toolCallId===l.toolInvocation.toolCallId);u===-1?t.content.toolInvocations.push(l.toolInvocation):t.content.toolInvocations[u]=l.toolInvocation}else(i.toolInvocation.state==="approval-requested"||i.toolInvocation.state==="approval-responded"||i.toolInvocation.state==="output-denied"||i.toolInvocation.state==="output-error")&&(l.toolInvocation={...l.toolInvocation,state:i.toolInvocation.state,approval:i.toolInvocation.approval,errorText:i.toolInvocation.errorText,rawInput:i.toolInvocation.rawInput,args:{...l.toolInvocation.args,...i.toolInvocation.args}},i.providerMetadata&&(l.providerMetadata={...l.providerMetadata,...i.providerMetadata}),"providerExecuted"in i&&i.providerExecuted!==void 0&&(l.providerExecuted=i.providerExecuted),"title"in i&&i.title!==void 0&&(l.title=i.title),"preliminary"in i&&i.preliminary!==void 0&&(l.preliminary=i.preliminary));const c=t.content.parts.findIndex(u=>u===l);r.set(a,c)}else s.set(a,i)}else s.set(a,i);_P.addPartsToMessage({latestMessage:t,incomingMessage:n,anchorMap:r,partsToAdd:s}),!t.content.content&&n.content.content&&(t.content.content=n.content.content),t.content.content&&n.content.content&&t.content.content!==n.content.content&&(t.content.content=n.content.content)}static addPartsToMessage({latestMessage:t,incomingMessage:n,anchorMap:r,partsToAdd:s}){for(let a=0;a<n.content.parts.length;++a){const i=n.content.parts[a];if(!i)continue;const l=Xo.fromDBParts([i]),c=s.get(a);if(!(!l||!c))if(r.size>0){if(r.has(a))continue;const u=[...r.keys()].filter(h=>h<a).pop()??-1,d=[...r.keys()].find(h=>h>a)??-1,f=(u!==-1?r.get(u):0)+(u===-1?a:a-u),p=d!==-1?r.get(d):t.content.parts.length;if(f>=0&&f<=p&&!t.content.parts.slice(f,p).some(h=>Xo.fromDBParts([h])===Xo.fromDBParts([i]))){_P.pushNewPart({latestMessage:t,newMessage:n,part:i,insertAt:f});for(const[h,m]of r.entries())m>=f&&r.set(h,m+1)}}else _P.pushNewPart({latestMessage:t,newMessage:n,part:i})}}static pushNewPart({latestMessage:t,newMessage:n,part:r,insertAt:s}){const a=Xo.fromDBParts([r]);if(t.content.parts.filter(i=>Xo.fromDBParts([i])===a).length<n.content.parts.filter(i=>Xo.fromDBParts([i])===a).length){const i=n.content.parts.indexOf(r),l=i>0&&n.content.parts[i-1]?.type==="step-start",c=t.role==="assistant"&&r.type==="text"&&!l&&t.content.parts.length>0&&t.content.parts.at(-1)?.type==="tool-invocation",u=[...t.content.parts].reverse().find(f=>f.type==="step-start"),d=u?.model?mwe({type:"step-start",model:u.model}):{type:"step-start"};typeof s=="number"?c?(t.content.parts.splice(s,0,d),t.content.parts.splice(s+1,0,r)):t.content.parts.splice(s,0,r):(c&&t.content.parts.push(d),t.content.parts.push(r))}}};const Xwn=[{mediaType:"image/gif",bytesPrefix:[71,73,70],base64Prefix:"R0lG"},{mediaType:"image/png",bytesPrefix:[137,80,78,71],base64Prefix:"iVBORw"},{mediaType:"image/jpeg",bytesPrefix:[255,216],base64Prefix:"/9j/"},{mediaType:"image/webp",bytesPrefix:[82,73,70,70],base64Prefix:"UklGRg"},{mediaType:"image/bmp",bytesPrefix:[66,77],base64Prefix:"Qk"},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0],base64Prefix:"SUkqAA"},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42],base64Prefix:"TU0AKg"},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102],base64Prefix:"AAAAIGZ0eXBhdmlm"},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99],base64Prefix:"AAAAIGZ0eXBoZWlj"}],Jwn=e=>{const t=typeof e=="string"?gft(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function e1n(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Jwn(e):e}function t1n({data:e,signatures:t}){const n=e1n(e);for(const r of t)if(typeof n=="string"?n.startsWith(r.base64Prefix):n.length>=r.bytesPrefix.length&&r.bytesPrefix.every((s,a)=>n[a]===s))return r.mediaType}function OLe(e,t){let n;const r=e.type;switch(r){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${r}`)}const{data:s,mediaType:a}=k0n(n);let i=a??e.mediaType,l=s;if(l instanceof URL&&t){const c=t[l.toString()];c&&(l=c.data,i??=c.mediaType)}switch(r){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=t1n({data:l,signatures:Xwn})??i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}function _Le(e){const t=[];for(const n of e){const r=Oj(n.url,n.contentType);if(r.type==="providerFileId"){t.push({type:"file",data:n.url,mimeType:n.contentType||"application/octet-stream"});continue}let s=n.url;r.type==="raw"&&(s=M0e(n.url,n.contentType||"application/octet-stream"));let a;try{a=new URL(s)}catch{throw new Error(`Invalid URL: ${n.url}`)}switch(a.protocol){case"http:":case"https:":case"gs:":case"s3:":if(n.contentType?.startsWith("image/"))t.push({type:"image",image:a.toString(),mimeType:n.contentType});else{if(!n.contentType)throw new Error("If the attachment is not an image, it must specify a content type");t.push({type:"file",data:a.toString(),mimeType:n.contentType})}break;case"data:":if(n.contentType?.startsWith("image/"))t.push({type:"image",image:s,mimeType:n.contentType});else if(n.contentType?.startsWith("text/"))t.push({type:"file",data:s,mimeType:n.contentType});else{if(!n.contentType)throw new Error("If the attachment is not an image or text, it must specify a content type");t.push({type:"file",data:s,mimeType:n.contentType})}break;default:throw new Error(`Unsupported URL protocol: ${a.protocol}`)}}return t}const n1n=e=>{const t=new Map,n=/__split-\d+$/;return r=>{const s=e.at(-1);if(r.role===s?.role&&Array.isArray(s.content)&&Array.isArray(r.content)&&(r.role!=="assistant"||r.role==="assistant"&&r.content.at(-1)?.type!=="tool-call"))for(const a of r.content)s.content.push(a);else{let a=r.id;if(n.test(a)){e.push(r);return}const i=t.get(a)||0;i>0&&(r.id=`${a}__split-${i}`),t.set(a,i+1),e.push(r)}}};function sE(e){const t=[],n=n1n(t);for(let r=0;r<e.length;r++){const s=e[r],a=r===e.length-1;if(!s?.content)continue;const{content:i,experimental_attachments:l=[],parts:c}=s.content,{role:u}=s,d={id:s.id,createdAt:s.createdAt,resourceId:s.resourceId,threadId:s.threadId},f=[...l],p=[];for(const h of c)if(h.type==="file"){const{mediaType:m,data:v}=Aq(h);f.push({url:v,contentType:m??"application/octet-stream"})}else p.push(h);switch(u){case"user":if(p==null){const h=f?[{type:"text",text:i||""},..._Le(f)]:{type:"text",text:i||""};n({role:"user",...d,type:"text",content:h})}else{const h=s.content.parts.filter(v=>v.type==="text").map(v=>({type:"text",text:v.text})),m=f?[...h,..._Le(f)]:h;n({role:"user",...d,type:"text",content:Array.isArray(m)&&m.length===1&&m[0]?.type==="text"&&typeof i<"u"?i:m})}break;case"assistant":{if(s.content.parts!=null){let v=function(){const k=[];for(const C of x)switch(C.type){case"file":case"text":k.push(C);break;case"reasoning":for(const E of C.details)switch(E.type){case"text":k.push({type:"reasoning",text:E.text,signature:E.signature});break;case"redacted":k.push({type:"redacted-reasoning",data:E.data});break}break;case"tool-invocation":C.toolInvocation.toolName!=="updateWorkingMemory"&&k.push({type:"tool-call",toolCallId:C.toolInvocation.toolCallId,toolName:C.toolInvocation.toolName,args:C.toolInvocation.args});break}n({role:"assistant",...d,type:k.some(C=>C.type==="tool-call")?"tool-call":"text",content:typeof k!="string"&&Array.isArray(k)&&k.length===1&&k[0]?.type==="text"?k[0].text:k});const _=x.filter(C=>"type"in C&&C.type==="tool-invocation").map(C=>C.toolInvocation).filter(C=>C.toolName!=="updateWorkingMemory").filter(C=>C.state==="result"&&"result"in C);_.length>0&&n({role:"tool",...d,type:"tool-result",content:_.map(C=>{const{toolCallId:E,toolName:T,result:N}=C;return{type:"tool-result",toolCallId:E,toolName:T,result:N}})}),x=[],b=!1,y++},y=0,b=!1,x=[];for(const k of s.content.parts)switch(k.type){case"text":b&&v(),x.push(k);break;case"file":case"reasoning":x.push(k);break;case"tool-invocation":(x.some(_=>_.type==="text"||_.type==="file"||_.type==="reasoning")||(k.toolInvocation.step??0)!==y)&&v(),x.push(k),b=!0;break}v();const S=s.content.toolInvocations;if(S&&S.length>0){const k=new Set;for(const C of s.content.parts)C.type==="tool-invocation"&&C.toolInvocation.toolCallId&&k.add(C.toolInvocation.toolCallId);const _=S.filter(C=>!k.has(C.toolCallId)&&C.toolName!=="updateWorkingMemory");if(_.length>0){const C=new Map;for(const T of _){const N=T.step??0;C.has(N)||C.set(N,[]),C.get(N).push(T)}const E=Array.from(C.keys()).sort((T,N)=>T-N);for(const T of E){const N=C.get(T);n({role:"assistant",...d,type:"tool-call",content:[...N.map(({toolCallId:A,toolName:R,args:L})=>({type:"tool-call",toolCallId:A,toolName:R,args:L}))]});const I=N.filter(A=>A.state==="result"&&"result"in A);I.length>0&&n({role:"tool",...d,type:"tool-result",content:I.map(A=>{const{toolCallId:R,toolName:L,result:D}=A;return{type:"tool-result",toolCallId:R,toolName:L,result:D}})})}}}break}const h=s.content.toolInvocations;if(h==null||h.length===0){n({role:"assistant",...d,content:i||"",type:"text"});break}const m=h.reduce((v,y)=>Math.max(v,y.step??0),0);for(let v=0;v<=m;v++){const y=h.filter(x=>(x.step??0)===v&&x.toolName!=="updateWorkingMemory");if(y.length===0)continue;n({role:"assistant",...d,type:"tool-call",content:[...a&&i&&v===0?[{type:"text",text:i}]:[],...y.map(({toolCallId:x,toolName:S,args:k})=>({type:"tool-call",toolCallId:x,toolName:S,args:k}))]});const b=y.filter(x=>x.state==="result"&&"result"in x);b.length>0&&n({role:"tool",...d,type:"tool-result",content:b.map(x=>{const{toolCallId:S,toolName:k,result:_}=x;return{type:"tool-result",toolCallId:S,toolName:k,result:_}})})}i&&!a&&n({role:"assistant",...d,type:"text",content:i||""});break}}}return t}function r1n(e){return`${e.origin}${e.pathname}`}const s1n=async({url:e,downloadRetries:t})=>{const n=e.toString(),r=r1n(e);try{const s=await dfn(n,{method:"GET"},t,{shouldRetryResponse:a=>a.status>=500});if(!s.ok)throw new SO({id:"DOWNLOAD_ASSETS_FAILED",text:`Failed to download asset: ${r}`,domain:xO.LLM,category:wO.USER,details:{url:n}});return{data:new Uint8Array(await s.arrayBuffer()),mediaType:s.headers.get("content-type")??void 0}}catch(s){throw new SO({id:"DOWNLOAD_ASSETS_FAILED",text:`Failed to download asset: ${r}`,domain:xO.LLM,category:wO.USER,details:{url:n}},s)}};async function a1n({messages:e,downloadConcurrency:t=10,downloadRetries:n=3,supportedUrls:r}){const s=(await Da(async()=>{const{default:i}=await import("./index-yUiD89B4.js");return{default:i}},[],import.meta.url)).default,a=(await s(e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{const l=i.mediaType??(i.type==="image"?"image/*":void 0);let c=i.type==="image"?i.image:i.data;if(typeof c=="string")try{c=new URL(c)}catch{}return{mediaType:l,data:c}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&gfn({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:r??{}})})),async i=>i.isUrlSupportedByModel?null:{url:i.url.toString(),...await s1n({url:i.url,downloadRetries:n})},{concurrency:t})).filter(i=>i?.data!=null).map(({url:i,data:l,mediaType:c})=>[i,{data:l,mediaType:c}]);return Object.fromEntries(a)}function i1n(e){return{...e,createdAt:e.createdAt.toISOString()}}function o1n(e){return{...e,createdAt:new Date(e.createdAt)}}function l1n(e){return e.map(i1n)}function c1n(e){return e.map(o1n)}var u1n=class{memoryMessages=new Set;newUserMessages=new Set;newResponseMessages=new Set;userContextMessages=new Set;memoryMessagesPersisted=new Set;newUserMessagesPersisted=new Set;newResponseMessagesPersisted=new Set;userContextMessagesPersisted=new Set;addToSource(e,t){switch(t){case"memory":this.memoryMessages.add(e),this.memoryMessagesPersisted.add(e);break;case"response":this.memoryMessages.has(e)&&this.memoryMessages.delete(e),this.newResponseMessages.add(e),this.newResponseMessagesPersisted.add(e),this.newUserMessages.has(e)&&this.newUserMessages.delete(e);break;case"input":case"user":this.newUserMessages.add(e),this.newUserMessagesPersisted.add(e);break;case"context":this.userContextMessages.add(e),this.userContextMessagesPersisted.add(e);break;default:throw new Error(`Missing message source for message ${e}`)}}isMemoryMessage(e){return this.memoryMessages.has(e)}isUserMessage(e){return this.newUserMessages.has(e)}isResponseMessage(e){return this.newResponseMessages.has(e)}isContextMessage(e){return this.userContextMessages.has(e)}getMemoryMessages(){return this.memoryMessages}getUserMessages(){return this.newUserMessages}getResponseMessages(){return this.newResponseMessages}getContextMessages(){return this.userContextMessages}getMemoryMessagesPersisted(){return this.memoryMessagesPersisted}getUserMessagesPersisted(){return this.newUserMessagesPersisted}getResponseMessagesPersisted(){return this.newResponseMessagesPersisted}getContextMessagesPersisted(){return this.userContextMessagesPersisted}removeMessage(e){this.memoryMessages.delete(e),this.newUserMessages.delete(e),this.newResponseMessages.delete(e),this.userContextMessages.delete(e)}clearUserMessages(){this.newUserMessages.clear()}clearResponseMessages(){this.newResponseMessages.clear()}clearContextMessages(){this.userContextMessages.clear()}clearAll(){this.newUserMessages.clear(),this.newResponseMessages.clear(),this.userContextMessages.clear()}createSourceChecker(){const e={memory:new Set(Array.from(this.memoryMessages.values()).map(t=>t.id)),output:new Set(Array.from(this.newResponseMessages.values()).map(t=>t.id)),input:new Set(Array.from(this.newUserMessages.values()).map(t=>t.id)),context:new Set(Array.from(this.userContextMessages.values()).map(t=>t.id))};return{...e,getSource:t=>e.memory.has(t.id)?"memory":e.input.has(t.id)?"input":e.output.has(t.id)?"response":e.context.has(t.id)?"context":null}}isNewMessage(e){const t=typeof e=="string"?e:e.id;return typeof e!="string"&&(this.newUserMessages.has(e)||this.newResponseMessages.has(e))?!0:Array.from(this.newUserMessages).some(n=>n.id===t)||Array.from(this.newResponseMessages).some(n=>n.id===t)}serializeSourceTracking(){const e=t=>Array.from(t).map(n=>n.id);return{memoryMessages:e(this.memoryMessages),newUserMessages:e(this.newUserMessages),newResponseMessages:e(this.newResponseMessages),userContextMessages:e(this.userContextMessages),memoryMessagesPersisted:e(this.memoryMessagesPersisted),newUserMessagesPersisted:e(this.newUserMessagesPersisted),newResponseMessagesPersisted:e(this.newResponseMessagesPersisted),userContextMessagesPersisted:e(this.userContextMessagesPersisted)}}deserializeSourceTracking(e,t){const n=r=>new Set(r.map(s=>t.find(a=>a.id===s)).filter(Boolean));this.memoryMessages=n(e.memoryMessages),this.newUserMessages=n(e.newUserMessages),this.newResponseMessages=n(e.newResponseMessages),this.userContextMessages=n(e.userContextMessages),this.memoryMessagesPersisted=n(e.memoryMessagesPersisted),this.newUserMessagesPersisted=n(e.newUserMessagesPersisted),this.newResponseMessagesPersisted=n(e.newResponseMessagesPersisted),this.userContextMessagesPersisted=n(e.userContextMessagesPersisted)}serializeAll(e){return{messages:l1n(e.messages),systemMessages:e.systemMessages,taggedSystemMessages:e.taggedSystemMessages,memoryInfo:e.memoryInfo,_agentNetworkAppend:e.agentNetworkAppend,...this.serializeSourceTracking()}}deserializeAll(e){const t=c1n(e.messages);return this.deserializeSourceTracking({memoryMessages:e.memoryMessages,newUserMessages:e.newUserMessages,newResponseMessages:e.newResponseMessages,userContextMessages:e.userContextMessages,memoryMessagesPersisted:e.memoryMessagesPersisted,newUserMessagesPersisted:e.newUserMessagesPersisted,newResponseMessagesPersisted:e.newResponseMessagesPersisted,userContextMessagesPersisted:e.userContextMessagesPersisted},t),{messages:t,systemMessages:e.systemMessages,taggedSystemMessages:e.taggedSystemMessages,memoryInfo:e.memoryInfo,agentNetworkAppend:e._agentNetworkAppend}}};function d1n(e){return e.role==="system"&&e.parts.length>0&&e.parts.every(t=>t.type.startsWith("data-"))}function KX(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n];if(!d1n(r)){t.push(r);continue}const s=t[t.length-1],a=e[n+1];s&&s.role==="assistant"?t[t.length-1]={...s,parts:[...s.parts,...r.parts]}:a&&a.role==="assistant"?e[n+1]={...a,parts:[...r.parts,...a.parts]}:t.push({...r,role:"assistant"})}return t}function CLe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ELe(e,t){if(!e&&!t)return;const n={...e??{}};for(const[r,s]of Object.entries(t??{})){const a=n[r];n[r]=CLe(a)&&CLe(s)?{...a,...s}:s}return n}var f1n=class{messages=[];systemMessages=[];taggedSystemMessages={};memoryInfo=null;stateManager=new u1n;get memoryMessages(){return this.stateManager.getMemoryMessages()}get newUserMessages(){return this.stateManager.getUserMessages()}get newResponseMessages(){return this.stateManager.getResponseMessages()}get userContextMessages(){return this.stateManager.getContextMessages()}get memoryMessagesPersisted(){return this.stateManager.getMemoryMessagesPersisted()}get newUserMessagesPersisted(){return this.stateManager.getUserMessagesPersisted()}get newResponseMessagesPersisted(){return this.stateManager.getResponseMessagesPersisted()}get userContextMessagesPersisted(){return this.stateManager.getContextMessagesPersisted()}generateMessageId;_agentNetworkAppend=!1;filterIncompleteToolCalls;logger;toAIV5UIMessages(t,n){return KX(t.map(r=>Fv.toUIMessage(r,n)))}toAIV4UIMessages(t,n){return KX(t.map(r=>Bw.toUIMessage(r,n)))}toAIV6UIMessages(t){return KX(t.map(l7.toUIMessage))}isRecording=!1;recordedEvents=[];constructor({threadId:t,resourceId:n,generateMessageId:r,logger:s,filterIncompleteToolCalls:a,_agentNetworkAppend:i}={}){t&&(this.memoryInfo={threadId:t,resourceId:n}),this.generateMessageId=r,this.logger=s,this.filterIncompleteToolCalls=a??!0,this._agentNetworkAppend=i||!1}startRecording(){this.isRecording=!0,this.recordedEvents=[]}hasRecordedEvents(){return this.recordedEvents.length>0}getRecordedEvents(){return[...this.recordedEvents]}stopRecording(){this.isRecording=!1;const t=this.getRecordedEvents();return this.recordedEvents=[],t}addSignal(t,n){const r=n?.source??"input",s=this.generateCreatedAt(r,new Date),a=t.acceptedAt??t.createdAt,i={id:t.id,tagName:t.tagName,contents:t.contents,attributes:t.attributes,metadata:t.metadata,providerOptions:t.providerOptions,createdAt:s,acceptedAt:a},l=t.type==="state"?U9({...i,type:t.type}):U9({...i,type:t.type,transient:t.transient});return this.addOne(l.toDBMessage(this.memoryInfo??void 0),r),l}add(t,n,r={}){if(n==="user"&&(n="input"),!t)return this;const s=Array.isArray(t)?t:[t];this.isRecording&&this.recordedEvents.push({type:"add",source:n,count:s.length});for(const a of s){if(UDe(a)&&n==="input"){this.addSignal(a,{source:n});continue}const i=UDe(a)?a.toDBMessage(this.memoryInfo??void 0):typeof a=="string"?{role:"user",content:a}:a;if(Array.isArray(i)){for(const l of i)this.addOne(typeof l=="string"?{role:"user",content:l}:l,n,r);continue}this.addOne(typeof i=="string"?{role:"user",content:i}:i,n,r)}return this}serialize(){return this.stateManager.serializeAll({messages:this.messages,systemMessages:this.systemMessages,taggedSystemMessages:this.taggedSystemMessages,memoryInfo:this.memoryInfo,agentNetworkAppend:this._agentNetworkAppend})}serializeForSpan(){return{messages:this.all.aiV4.core().map(t=>({role:t.role,content:t.content})),systemMessages:[...this.systemMessages.map(t=>({role:t.role,content:t.content})),...Object.entries(this.taggedSystemMessages).flatMap(([t,n])=>n.map(r=>({role:r.role,content:r.content,tag:t})))]}}deserialize(t){const n=this.stateManager.deserializeAll(t);this.messages=n.messages,this.systemMessages=n.systemMessages,this.taggedSystemMessages=n.taggedSystemMessages,this.memoryInfo=n.memoryInfo,this._agentNetworkAppend=n.agentNetworkAppend;for(const r of this.messages)this.updateLastCreatedAt(r);return this}get promptConversionMode(){return this.filterIncompleteToolCalls?"prompt":"prompt-with-suspended"}getMessagesForModelPrompt(){return this.messages.flatMap(t=>t.role!=="signal"?[t]:this.convertSignalForModelPrompt(t))}convertSignalForModelPrompt(t){const n=Ifn(t).toLLMMessage(),r=t.createdAt;return[wLe({...n,id:t.id,metadata:{createdAt:r}},"input",{memoryInfo:this.memoryInfo,newMessageId:()=>t.id,generateCreatedAt:(s,a)=>a instanceof Date?a:typeof a=="string"||typeof a=="number"?new Date(a):r,dbMessages:this.messages})]}makeMessageSourceChecker(){return this.stateManager.createSourceChecker()}getLatestUserContent(){const t=this.all.core().filter(n=>n.role==="user").at(-1)?.content;return t?Fwn(t):null}get get(){return{all:this.all,remembered:this.remembered,input:this.input,response:this.response}}get getPersisted(){return{remembered:this.rememberedPersisted,input:this.inputPersisted,taggedSystemMessages:this.taggedSystemMessages,response:this.responsePersisted}}get clear(){return{all:{db:()=>{const t=[...this.messages];return this.messages=[],this.stateManager.clearAll(),this.isRecording&&t.length>0&&this.recordedEvents.push({type:"clear",count:t.length}),t}},input:{db:()=>{const t=Array.from(this.stateManager.getUserMessages());return this.messages=this.messages.filter(n=>!this.stateManager.isUserMessage(n)),this.stateManager.clearUserMessages(),this.isRecording&&t.length>0&&this.recordedEvents.push({type:"clear",source:"input",count:t.length}),t}},response:{db:()=>{const t=Array.from(this.stateManager.getResponseMessages());return this.messages=this.messages.filter(n=>!this.stateManager.isResponseMessage(n)),this.stateManager.clearResponseMessages(),this.isRecording&&t.length>0&&this.recordedEvents.push({type:"clear",source:"response",count:t.length}),t}}}}removeByIds(t){const n=new Set(t),r=[];return this.messages=this.messages.filter(s=>n.has(s.id)?(r.push(s),this.stateManager.removeMessage(s),!1):!0),this.isRecording&&r.length>0&&this.recordedEvents.push({type:"removeByIds",ids:t,count:r.length}),r}all={db:()=>this.messages,v1:()=>sE(this.all.db()),aiV5:{model:()=>{const t=this.getMessagesForModelPrompt();return bv(this.toAIV5UIMessages(t,{transformToolPayloads:!1}),t)},ui:()=>this.toAIV5UIMessages(this.all.db()),prompt:()=>{const t=SLe([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()],"system",this.createAdapterContext(),this.messages),n=this.getMessagesForModelPrompt(),r=bv(this.toAIV5UIMessages(n,{transformToolPayloads:!1}),n,this.promptConversionMode);return Z5([...t,...r],this.logger)},llmPrompt:async(t={downloadConcurrency:10,downloadRetries:3})=>{const n=this.getMessagesForModelPrompt(),r=bv(this.toAIV5UIMessages(n,{transformToolPayloads:!1}),n,this.promptConversionMode),s=new Map;for(const c of this.messages)if(!(c.content?.format!==2||!c.content.parts))for(const u of c.content.parts)u.type==="tool-invocation"&&u.toolInvocation?.state==="result"&&u.providerMetadata?.mastra&&typeof u.providerMetadata.mastra=="object"&&u.providerMetadata.mastra.modelOutput!=null&&s.set(u.toolInvocation.toolCallId,u.providerMetadata.mastra.modelOutput);if(s.size>0){for(const c of r)if(!(c.role!=="tool"||!Array.isArray(c.content)))for(let u=0;u<c.content.length;u++){const d=c.content[u];d.type==="tool-result"&&s.has(d.toolCallId)&&(c.content[u]={...d,output:s.get(d.toolCallId)})}}const a=SLe([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()],"system",this.createAdapterContext(),this.messages),i=await a1n({messages:r,downloadConcurrency:t?.downloadConcurrency,downloadRetries:t?.downloadRetries,supportedUrls:t?.supportedUrls});let l=[...a,...r];return r.some(c=>(c.role==="user"||c.role==="assistant")&&typeof c.content!="string"&&c.content.some(u=>u.type==="image"||u.type==="file"))&&(l=l.map(c=>{if(c.role==="user")return typeof c.content=="string"?{role:"user",content:[{type:"text",text:c.content}],providerOptions:c.providerOptions}:{role:"user",content:c.content.map(u=>u.type==="image"||u.type==="file"?OLe(u,i):u).filter(u=>u.type!=="text"||u.text!==""),providerOptions:c.providerOptions};if(c.role==="assistant"&&typeof c.content!="string"){const u=c.content.map(d=>d.type==="file"?OLe(d,i):d);return{...c,content:u}}return c})),l=Z5(l,this.logger),l.filter(c=>c!=null).map($fn).filter(c=>c.role==="system"||typeof c.content=="string"||c.content.length>0)}},aiV6:{ui:()=>this.toAIV6UIMessages(this.all.db()),llmPrompt:async t=>Mfn(await this.all.aiV5.llmPrompt(t))},aiV7:{ui:()=>this.toAIV6UIMessages(this.all.db()),llmPrompt:async t=>Dfn(await this.all.aiV5.llmPrompt(t))},prompt:()=>this.all.aiV4.prompt(),ui:()=>this.toAIV4UIMessages(this.all.db()),core:()=>bh(this.toAIV4UIMessages(this.all.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.all.db()),core:()=>bh(this.toAIV4UIMessages(this.getMessagesForModelPrompt(),{transformToolPayloads:!1})),prompt:()=>{const t=this.all.aiV4.core();return Z5([...this.systemMessages,...Object.values(this.taggedSystemMessages).flat(),...t],this.logger)},llmPrompt:()=>{const t=this.all.aiV4.core();let n=[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat(),...t];return n=Z5(n,this.logger),n.map(Pfn)}}};remembered={db:()=>this.messages.filter(t=>this.memoryMessages.has(t)),v1:()=>sE(this.remembered.db()),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.remembered.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.remembered.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.remembered.db())},ui:()=>this.toAIV4UIMessages(this.remembered.db()),core:()=>bh(this.toAIV4UIMessages(this.remembered.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.remembered.db()),core:()=>bh(this.toAIV4UIMessages(this.remembered.db(),{transformToolPayloads:!1}))}};rememberedPersisted={db:()=>this.all.db().filter(t=>this.memoryMessagesPersisted.has(t)),v1:()=>sE(this.rememberedPersisted.db()),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.rememberedPersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.rememberedPersisted.db())},ui:()=>this.toAIV4UIMessages(this.rememberedPersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.rememberedPersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.rememberedPersisted.db(),{transformToolPayloads:!1}))}};input={db:()=>this.messages.filter(t=>this.newUserMessages.has(t)),v1:()=>sE(this.input.db()),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.input.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.input.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.input.db())},ui:()=>this.toAIV4UIMessages(this.input.db()),core:()=>bh(this.toAIV4UIMessages(this.input.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.input.db()),core:()=>bh(this.toAIV4UIMessages(this.input.db(),{transformToolPayloads:!1}))}};inputPersisted={db:()=>this.messages.filter(t=>this.newUserMessagesPersisted.has(t)),v1:()=>sE(this.inputPersisted.db()),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.inputPersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.inputPersisted.db())},ui:()=>this.toAIV4UIMessages(this.inputPersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1})),aiV4:{ui:()=>this.toAIV4UIMessages(this.inputPersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.inputPersisted.db(),{transformToolPayloads:!1}))}};response={db:()=>this.messages.filter(t=>this.newResponseMessages.has(t)),v1:()=>sE(this.response.db()),aiV5:{ui:()=>this.toAIV5UIMessages(this.response.db()),model:()=>bv(this.toAIV5UIMessages(this.response.db(),{transformToolPayloads:!1}),this.messages).filter(t=>t.role==="tool"||t.role==="assistant"),modelContent:t=>typeof t=="number"?kLe.extractStepContent(this.response.aiV5.ui(),t,this.response.aiV5.stepContent):this.response.aiV5.model().map(this.response.aiV5.stepContent).flat(),stepContent:t=>kLe.convertToStepContent(t,this.messages,()=>this.response.aiV5.model().at(-1))},aiV6:{ui:()=>this.toAIV6UIMessages(this.response.db())},aiV4:{ui:()=>this.toAIV4UIMessages(this.response.db()),core:()=>bh(this.toAIV4UIMessages(this.response.db(),{transformToolPayloads:!1}))}};responsePersisted={db:()=>this.messages.filter(t=>this.newResponseMessagesPersisted.has(t)),aiV5:{model:()=>bv(this.toAIV5UIMessages(this.responsePersisted.db(),{transformToolPayloads:!1}),this.messages),ui:()=>this.toAIV5UIMessages(this.responsePersisted.db())},aiV6:{ui:()=>this.toAIV6UIMessages(this.responsePersisted.db())},ui:()=>this.toAIV4UIMessages(this.responsePersisted.db()),aiV4:{ui:()=>this.toAIV4UIMessages(this.responsePersisted.db()),core:()=>bh(this.toAIV4UIMessages(this.responsePersisted.db(),{transformToolPayloads:!1}))}};drainUnsavedMessages(){const t=this.messages.filter(n=>this.newUserMessages.has(n)||this.newResponseMessages.has(n));return this.newUserMessages.clear(),this.newResponseMessages.clear(),t.map(n=>this.transformMessageForTranscript(n))}transformToolStateDataForTranscript(t,n){if(!t||typeof t!="object")return t;const r=t,s=r.metadata??r.providerMetadata,a=lg(s,"transcript",n),i=lg(s,"transcript","input-available"),l=n==="approval"?Cu(a)?a.transformed:Cu(i)?i.transformed:void 0:Cu(i)?i.transformed:Cu(a)?a.transformed:void 0,c=n==="suspend"&&Cu(a)?a.transformed:void 0;return{...r,...l!==void 0?{args:l}:{},...c!==void 0?{suspendPayload:c}:{}}}transformMessageForTranscript(t){if(t.content?.format!==2||!t.content.parts)return t;let n=!1;const r=new Map,s=t.content.parts.map(l=>{if(l.type==="tool-invocation"&&l.toolInvocation){const c=lg(l.providerMetadata,"transcript","input-available"),u=l.toolInvocation.state==="result"?lg(l.providerMetadata,"transcript","output-available")??lg(l.providerMetadata,"transcript","error"):l.toolInvocation.state==="output-error"?lg(l.providerMetadata,"transcript","error"):void 0;if(!c&&!u)return l;n=!0;const d=Cu(c)?c.transformed:l.toolInvocation.args,f=l.toolInvocation.state==="result"?Cu(u)?u.transformed:l.toolInvocation.result:void 0,p=l.toolInvocation.state==="output-error"?Cu(u)?u.transformed:l.toolInvocation.errorText:void 0;return r.set(l.toolInvocation.toolCallId,{args:d,...l.toolInvocation.state==="result"?{result:f}:{},...l.toolInvocation.state==="output-error"?{errorText:p}:{}}),{...l,toolInvocation:{...l.toolInvocation,args:d,...l.toolInvocation.state==="result"?{result:f}:{},...l.toolInvocation.state==="output-error"?{errorText:p}:{}}}}return l.type==="data-tool-call-suspended"||l.type==="data-tool-call-approval"?(n=!0,{...l,data:this.transformToolStateDataForTranscript(l.data,l.type==="data-tool-call-suspended"?"suspend":"approval")}):l}),a=t.content.toolInvocations?.map(l=>{const c=r.get(l.toolCallId);if(!c)return l;const u=l.state;return n=!0,{...l,...c.args!==void 0?{args:c.args}:{},...l.state==="result"&&c.result!==void 0?{result:c.result}:{},...u==="output-error"&&c.errorText!==void 0?{errorText:c.errorText}:{}}}),i=t.content.metadata&&typeof t.content.metadata=="object"?{...t.content.metadata}:t.content.metadata;if(i&&typeof i=="object")for(const[l,c]of[["suspendedTools","suspend"],["pendingToolApprovals","approval"]]){const u=i[l];!u||typeof u!="object"||(n=!0,i[l]=Object.fromEntries(Object.entries(u).map(([d,f])=>[d,this.transformToolStateDataForTranscript(f,c)])))}return n?{...t,content:{...t.content,parts:s,...a?{toolInvocations:a}:{},...i?{metadata:i}:{}}}:t}getEarliestUnsavedMessageTimestamp(){const t=this.messages.filter(n=>this.newUserMessages.has(n)||this.newResponseMessages.has(n));if(t.length!==0)return Math.min(...t.map(n=>new Date(n.createdAt).getTime()))}isNewMessage(t){return this.stateManager.isNewMessage(t)}updateToolInvocation(t,n){if(!t.toolInvocation?.toolCallId)return!1;const r=t.toolInvocation.toolCallId;for(let a=this.messages.length-1;a>=0;a--){const i=this.messages[a];if(!(i.role!=="assistant"||!i.content?.parts))for(let l=0;l<i.content.parts.length;l++){const c=i.content.parts[l];if(c?.type==="tool-invocation"&&c.toolInvocation?.toolCallId===r)return this.mergeToolResultIntoPart(i,l,t,n),!0}}const s=t.toolInvocation.toolName;for(let a=this.messages.length-1;a>=0;a--){const i=this.messages[a];if(!(i.role!=="assistant"||!i.content?.parts))for(let l=0;l<i.content.parts.length;l++){const c=i.content.parts[l];if(c?.type!=="tool-invocation")continue;const u=c;if(u.providerExecuted===!0&&u.toolInvocation?.state==="call"&&u.toolInvocation.toolName===s){const d=u.toolInvocation.toolCallId;return u.toolInvocation.toolCallId=r,this.mergeToolResultIntoPart(i,l,t,n,d),!0}}}return this.logger?.warn(`updateToolInvocation: no matching tool call found for toolCallId=${r}`),!1}updateMessageMetadataByToolCallId(t,n){if(!t)return!1;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(s.role!=="assistant"||!s.content?.parts||!s.content.parts.some(d=>d?.type==="tool-invocation"&&d.toolInvocation?.toolCallId===t))continue;const a=s.content.metadata??{},i=n??{},l=a.backgroundTasks,c=i.backgroundTasks,u=ELe(l,c);return s.content.metadata={...a,...i,...u?{backgroundTasks:u}:{}},this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(s),this.stateManager.isResponseMessage(s)||(this.stateManager.removeMessage(s),this.stateManager.addToSource(s,"response")),!0}return this.logger?.warn(`updateMessageMetadataByToolCallId: no matching tool call found for toolCallId=${t}`),!1}mergeToolResultIntoPart(t,n,r,s,a){const i=t.content.parts[n],l=a??i.toolInvocation.toolCallId,c=i,u=r,d=c.providerMetadata!==void 0||u.providerMetadata!==void 0?(()=>{const y=c.providerMetadata??{},b=u.providerMetadata??{},x={...y};for(const[S,k]of Object.entries(b)){const _=x[S];x[S]=_&&typeof _=="object"&&!Array.isArray(_)&&k&&typeof k=="object"&&!Array.isArray(k)?{..._,...k}:k}return x})():void 0;t.content.parts[n]={...r,toolInvocation:{...r.toolInvocation,args:i.toolInvocation.args},...c.providerExecuted!==void 0&&u.providerExecuted===void 0?{providerExecuted:c.providerExecuted}:{},...d!==void 0?{providerMetadata:d}:{}},this.lastCreatedAt=Math.max(this.lastCreatedAt||0,Date.now()),this.updateLastCreatedAt(t);const f=t.content.metadata??{},p=s??{},h=f.backgroundTasks,m=p.backgroundTasks,v=ELe(h,m);if(t.content.metadata={...f,...p,...v?{backgroundTasks:v}:{}},Array.isArray(t.content.toolInvocations)&&r.toolInvocation.state==="result"){const y=r.toolInvocation;t.content.toolInvocations=t.content.toolInvocations.map(b=>b.toolCallId===l?{...b,toolCallId:y.toolCallId,state:"result",args:i.toolInvocation.args,result:y.result}:b)}this.stateManager.isResponseMessage(t)||(this.stateManager.removeMessage(t),this.stateManager.addToSource(t,"response"))}stepStart(){const t=this.messages[this.messages.length-1];return!t||t.role!=="assistant"||!t.content?.parts||mb.isSealed(t)||t.content.parts[t.content.parts.length-1]?.type==="step-start"?!1:(t.content.parts.push(mwe({type:"step-start"})),this.stateManager.isResponseMessage(t)||(this.stateManager.removeMessage(t),this.stateManager.addToSource(t,"response")),!0)}rotateResponseMessageId(t){return this.markResponseMessageBoundary(t)||this.markResponseMessageBoundary(),this.newMessageId("assistant")}markResponseMessageBoundary(t){const n=t?this.messages.find(r=>r.id===t):[...this.messages].reverse().find(r=>r.role==="assistant");return!n||n.role!=="assistant"?!1:(n.content.metadata={...n.content.metadata??{},mastra:{...n.content.metadata?.mastra??{},responseBoundary:!0}},this.stateManager.isResponseMessage(n)||(this.stateManager.removeMessage(n),this.stateManager.addToSource(n,"response")),!0)}enrichLastStepStart(t){const n=this.messages[this.messages.length-1];if(!n||n.role!=="assistant"||!n.content?.parts||mb.isSealed(n))return!1;for(let r=n.content.parts.length-1;r>=0;r--){const s=n.content.parts[r];if(s?.type==="step-start")return s.model?!1:(s.model=t,this.stateManager.isResponseMessage(n)||(this.stateManager.removeMessage(n),this.stateManager.addToSource(n,"response")),!0)}return!1}getSystemMessages(t){return t?this.taggedSystemMessages[t]||[]:this.systemMessages}getAllSystemMessages(){return[...this.systemMessages,...Object.values(this.taggedSystemMessages).flat()]}clearSystemMessages(t){return t?delete this.taggedSystemMessages[t]:this.systemMessages=[],this}replaceAllSystemMessages(t){this.systemMessages=[];for(const n of t)n.role==="system"&&this.systemMessages.push(n);return this}addSystem(t,n){if(!t)return this;for(const r of Array.isArray(t)?t:[t])this.addOneSystem(r,n);return this}addOneSystem(t,n){const r=Kwn(t);if(r.role!=="system")throw new Error(`Expected role "system" but saw ${r.role} for message ${JSON.stringify(r,null,2)}`);n&&!this.isDuplicateSystem(r,n)?(this.taggedSystemMessages[n]||=[],this.taggedSystemMessages[n].push(r),this.isRecording&&this.recordedEvents.push({type:"addSystem",tag:n,message:r})):!n&&!this.isDuplicateSystem(r)&&(this.systemMessages.push(r),this.isRecording&&this.recordedEvents.push({type:"addSystem",message:r}))}isDuplicateSystem(t,n){return n?this.taggedSystemMessages[n]?this.taggedSystemMessages[n].some(r=>Xo.fromAIV4CoreMessageContent(r.content)===Xo.fromAIV4CoreMessageContent(t.content)):!1:this.systemMessages.some(r=>Xo.fromAIV4CoreMessageContent(r.content)===Xo.fromAIV4CoreMessageContent(t.content))}getMessageById(t){return this.messages.find(n=>n.id===t)}shouldReplaceMessage(t){if(!this.messages.length)return{exists:!1};if(!("id"in t)||!t?.id)return{exists:!1};const n=this.getMessageById(t.id);return n?{exists:!0,shouldReplace:!YX(n,t),id:n.id}:{exists:!1}}addOne(t,n,r={}){if((!("content"in t)||!t.content&&typeof t.content!="string")&&(!("parts"in t)||!t.parts))throw new SO({id:"INVALID_MESSAGE_CONTENT",domain:xO.AGENT,category:wO.USER,text:`Message with role "${t.role}" must have either a 'content' property (string or array) or a 'parts' property (array) that is not empty, null, or undefined. Received message: ${JSON.stringify(t,null,2)}`,details:{role:t.role,messageSource:n,hasContent:"content"in t,hasParts:"parts"in t}});if(t.role==="system"){if(n==="memory")return null;if(Ga.isAIV4CoreMessage(t)||Ga.isAIV6CoreMessage(t)||Ga.isAIV5CoreMessage(t)||Ga.isMastraDBMessage(t))return this.addSystem(t);throw new SO({id:"INVALID_SYSTEM_MESSAGE_FORMAT",domain:xO.AGENT,category:wO.USER,text:"Invalid system message format. System messages must be CoreMessage format with 'role' and 'content' properties. The content should be a string or valid content array.",details:{messageSource:n,receivedMessage:JSON.stringify(t,null,2)}})}const s=wLe(t,n,this.createAdapterContext()),a=s.role==="signal"?s.content.metadata?.signal:void 0;if(n==="input"&&s.role==="signal"&&!a?.acceptedAt){const y=a?.createdAt??s.createdAt.toISOString();s.createdAt=this.generateCreatedAt(n,s.createdAt),s.content.metadata={...s.content.metadata,signal:{...a,createdAt:s.createdAt.toISOString(),acceptedAt:y}}}const{exists:i,shouldReplace:l,id:c}=this.shouldReplaceMessage(s),u=this.messages.findLastIndex(y=>mb.isSealed(y)),d=this.messages.at(-1),f=this.messages.length-1,p=u===-1||f>u;if(n==="memory"){for(const y of this.messages)if(YX(y,s))return}const h=i&&c?this.messages.find(y=>y.id===c):void 0,m=!!h&&mb.isSealed(h),v=d?this.memoryMessages.has(d):!1;if(r.merge!==!1&&p&&!m&&mb.shouldMerge(d,s,n,v,this._agentNetworkAppend)&&d)mb.merge(d,s),this.updateLastCreatedAt(d),this.pushMessageToSource(d,n);else{let y=-1;l&&(y=this.messages.findIndex(x=>x.id===c));const b=y!==-1&&this.messages[y];if(l&&b){const x=u!==-1&&y<=u;if(mb.isSealed(b)){const S=b.content?.parts||[];let k=0;for(let E=S.length-1;E>=0;E--)if(S[E]?.metadata?.mastra?.sealedAt){k=E+1;break}k===0&&(k=S.length);const _=s.content.parts;let C;if(_.length<=k){if(YX(b,s))return this;C=_}else C=_.slice(k);C.length>0&&(s.id=this.generateMessageId?.({idType:"message",source:"memory"})??wo(),s.content.parts=C,s.createdAt<=b.createdAt&&(s.createdAt=new Date(b.createdAt.getTime()+1)),this.messages.push(s))}else if(x)s.id=this.generateMessageId?.({idType:"message",source:"memory"})??wo(),s.createdAt<=b.createdAt&&(s.createdAt=new Date(b.createdAt.getTime()+1)),this.messages.push(s);else{const S=this.memoryMessages.has(b);if(r.merge!==!1&&mb.shouldMerge(b,s,n,S,this._agentNetworkAppend))return mb.merge(b,s),this.updateLastCreatedAt(b),this.pushMessageToSource(b,n),this.messages.sort((k,_)=>k.createdAt.getTime()-_.createdAt.getTime()),this;this.messages[y]=s}}else i||this.messages.push(s);this.pushMessageToSource(s,n)}for(const y of this.messages)this.updateLastCreatedAt(y);return this.messages.sort((y,b)=>y.createdAt.getTime()-b.createdAt.getTime()),this}pushMessageToSource(t,n){this.stateManager.addToSource(t,n)}lastCreatedAt;updateLastCreatedAt(t){this.lastCreatedAt=Math.max(this.lastCreatedAt||0,t.createdAt.getTime())}generateCreatedAt(t,n){const r=n instanceof Date?n:typeof n=="string"||typeof n=="number"?new Date(n):void 0;if(r&&!this.lastCreatedAt)return this.lastCreatedAt=r.getTime(),r;if(r&&t==="memory")return r;const s=new Date,a=r?.getTime()||s.getTime(),i=this.lastCreatedAt||0;if(a<=i){const l=new Date(i+1);return this.lastCreatedAt=l.getTime(),l}return this.lastCreatedAt=a,r??s}newMessageId(t){return this.generateMessageId?this.generateMessageId({idType:"message",source:"agent",threadId:this.memoryInfo?.threadId,resourceId:this.memoryInfo?.resourceId,role:t}):wo()}createAdapterContext(){return{memoryInfo:this.memoryInfo,newMessageId:()=>this.newMessageId(),generateCreatedAt:(t,n)=>this.generateCreatedAt(t,n),dbMessages:this.messages}}};const hmt=g.createContext({}),p1n=({children:e,baseUrl:t,headers:n,apiPrefix:r,credentials:s="include",customFetch:a})=>{const i=g.useMemo(()=>v1n(t,n,r,s,a),[t,n,r,s,a]);return o.jsx(hmt.Provider,{value:i,children:e})},Ze=()=>g.useContext(hmt),h1n=/^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,m1n=e=>{const t=h1n.exec(e);return t?+t[1]<=255&&+t[2]<=255&&+t[3]<=255:!1},g1n=e=>{if(!e)return!0;try{const{hostname:t}=new URL(e);return t==="localhost"||t.endsWith(".localhost")||m1n(t)||t==="::1"||t==="[::1]"}catch{return!1}},v1n=(e,t={},n,r="include",s)=>new SP({baseUrl:e||"",headers:g1n(e)?{...t,"x-mastra-dev-playground":"true"}:t,apiPrefix:n,credentials:r,fetch:s}),y1n=({children:e,baseUrl:t,headers:n,apiPrefix:r,credentials:s,customFetch:a})=>o.jsx(p1n,{baseUrl:t,headers:n,apiPrefix:r,credentials:s,customFetch:a,children:e}),gwe=e=>{let n="";for(let r=0;r<e.length;r+=32768)n+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(n)};function b1n(e){if(typeof e=="string")return e;const t=e instanceof ArrayBuffer?new Uint8Array(e):e;return gwe(t)}function c7(e,t){if(typeof e=="string")return e;if(e instanceof URL)return e.toString();const n=e instanceof ArrayBuffer?new Uint8Array(e):e,r=gwe(n);return r.startsWith("data:")?r:`data:${t};base64,${r}`}const mmt=(e,t,n,r)=>{const s=[];s.push("#### Completion Check Results"),s.push(""),s.push(`Overall: ${e.complete?"✅ COMPLETE":"❌ NOT COMPLETE"}`),s.push(`Duration: ${e.totalDuration}ms`),e.timedOut&&s.push("⚠️ Scoring timed out"),s.push("");for(const a of e.scorers)s.push(n(a)),s.push(`Score: ${a.score} ${a.passed?"✅":"❌"}`),a.reason&&s.push(`Reason: ${a.reason}`),s.push("");return e.complete?s.push("✅ The task is complete."):t?s.push("⚠️ Max iterations reached."):s.push(r),s.join(`
|
|
198
198
|
`)},x1n=(e,t)=>mmt(e,t,n=>`###### ${n.scorerName} (${n.scorerId})`,"🔄 Will continue working on the task."),w1n=(e,t)=>mmt(e,t,n=>`**${n.scorerName}** (${n.scorerId})`,"🔄 The task is not yet complete. Please continue working based on the feedback above."),E$="clientMessageId",EO=e=>e?{...e}:{},Di=(e,t)=>({...e,content:{...e.content,parts:t}}),lx=(e,t)=>({...e,content:{...e.content,metadata:t}}),S1n=e=>{const{status:t,[E$]:n,...r}=e.content.metadata??{};return lx(e,r)},k1n=e=>{const{status:t,...n}=e.content.metadata??{};return lx(e,n)},pi=(e,t)=>[...e.slice(0,-1),t],Z0=(e,t,n)=>[...e.slice(0,t),n,...e.slice(t+1)],CP=(e,t,n)=>({id:e,role:"assistant",createdAt:new Date,content:{format:2,parts:t,metadata:EO(n)}}),yd=(e,t,n,r)=>[...e,CP(t,n,r)],uw=e=>e.type==="tool-invocation",TLe=e=>e.type==="text"?e.textId:void 0,The=e=>e.state,Wb=e=>{const t=e[e.length-1];if(!t||t.role!=="assistant")return e;if(t.content.parts.length===0)return e.slice(0,-1);const n=t.content.parts.map(r=>(r.type==="text"||r.type==="reasoning")&&The(r)==="streaming"?{...r,state:"done"}:r);return pi(e,Di(t,n))},G0=(e,t,n)=>{const r=l=>l.findIndex(c=>uw(c)&&c.toolInvocation.toolCallId===t),s=e[e.length-1];if(s&&s.role==="assistant"){const l=r(s.content.parts);if(l!==-1)return{messageIndex:e.length-1,toolPartIndex:l}}let a=0;const i=10;for(let l=e.length-1;l>=0&&!(a>i);l--){const c=e[l];if(c.role!=="assistant")continue;const u=r(c.content.parts);if(u!==-1)return{messageIndex:l,toolPartIndex:u};a++}if(!n)return null;for(let l=e.length-1;l>=0;l--)if(e[l].role==="assistant")return{messageIndex:l,toolPartIndex:-1};return null},XX=(e,t,n,r)=>{const s=EO(e),a=s.backgroundTasks??{},i={...a};if(n.perTaskEntry){const{toolCallId:c,startedAt:u,completedAt:d,taskId:f,suspendedAt:p}=n.perTaskEntry;i[c]={...a[c]??{taskId:f},taskId:f,...u!==void 0?{startedAt:u}:{},...d!==void 0?{completedAt:d}:{},...p!==void 0?{suspendedAt:p}:{}}}const l={...s,...r??{},mode:t,backgroundTasks:i};return n.resetRunningCount&&(l.runningBackgroundTasksCount=void 0),l},Cw=(e,t)=>{if(t.type==="workflow-start")return{input:e?.input,status:"running",steps:e?.steps||{}};if(t.type==="workflow-canceled")return{...e,status:"canceled"};if(t.type==="workflow-finish"){const i=t.payload.workflowStatus,l=e?.steps??{},c=Object.values(l).pop();return{...e,status:t.payload.workflowStatus,...i==="success"&&c?.status==="success"?{result:c?.output}:i==="failed"&&c?.status==="failed"?{error:c?.error}:i==="tripwire"&&t.payload.tripwire?{tripwire:t.payload.tripwire}:{}}}const{stepCallId:n,stepName:r,...s}=t.payload??{},a={...e?.steps,[t.payload.id]:{...e?.steps?.[t.payload.id],...s}};if(t.type==="workflow-step-start")return{...e,steps:a};if(t.type==="workflow-step-suspended"){const i=Object.entries(a).flatMap(([l,c])=>{if(c?.status==="suspended"){const u=c?.suspendPayload?.__workflow_meta?.path;return u?[[l,...u]]:[[l]]}return[]});return{...e,status:"suspended",steps:a,suspendPayload:t.payload.suspendPayload,suspended:i}}return t.type==="workflow-step-waiting"?{...e,status:"waiting",steps:a}:t.type==="workflow-step-progress"?{...e,steps:{...e?.steps,[t.payload.id]:{...e?.steps?.[t.payload.id],foreachProgress:{completedCount:t.payload.completedCount,totalCount:t.payload.totalCount,currentIndex:t.payload.currentIndex,iterationStatus:t.payload.iterationStatus,iterationOutput:t.payload.iterationOutput}}}}:t.type==="workflow-step-result"?{...e,steps:a}:e},vwe=(e,t)=>{const n=l=>({id:`signal-${Date.now()}`,role:"user",createdAt:new Date,content:{format:2,parts:l,metadata:EO(t)}}),r=l=>{if(!l||typeof l!="object")return[];const c=l;if(c.type==="text"&&typeof c.text=="string")return[{type:"text",text:c.text}];if(c.type==="image"){const u=c.image,d=typeof c.mediaType=="string"?c.mediaType:typeof c.mimeType=="string"?c.mimeType:"image/*";return typeof u=="string"||u instanceof URL||u instanceof ArrayBuffer||u instanceof Uint8Array?[{type:"file",mimeType:d,data:c7(u,d)}]:[{type:"file",mimeType:d,data:""}]}if(c.type==="file"){const u=c.data,d=typeof c.mediaType=="string"?c.mediaType:typeof c.mimeType=="string"?c.mimeType:"application/octet-stream";return typeof u=="string"||u instanceof URL||u instanceof ArrayBuffer||u instanceof Uint8Array?[{type:"file",mimeType:d,data:c7(u,d),...typeof c.filename=="string"?{filename:c.filename}:{}}]:[{type:"file",mimeType:d,data:typeof c.url=="string"?c.url:"",...typeof c.filename=="string"?{filename:c.filename}:{}}]}return[]};if(typeof e=="string")return[n([{type:"text",text:e}])];if(Array.isArray(e)){const l=e.flatMap(r);return l.length?[n(l)]:e.flatMap(c=>vwe(c,t))}if(!e||typeof e!="object")return[];const s=e;if(s.role&&s.role!=="user")return[];const a=s.content;if(typeof a=="string")return[n([{type:"text",text:a}])];if(!Array.isArray(a))return[];const i=a.flatMap(r);return i.length?[n(i)]:[]},jLe=(e,t,n,r)=>{const s=vwe(t,n)[0]?.content.parts;let a=typeof r.signalId=="string"?{...e,id:r.signalId}:e;return s?.length&&(a={...a,content:{...a.content,parts:s}}),r.keepClientMessageId?k1n(a):S1n(a)},NLe=e=>({type:"tool-invocation",toolInvocation:e}),O1n=e=>e.type.startsWith("agent-execution-event-")||e.type.startsWith("workflow-execution-event-"),_1n=e=>e.type.startsWith("data-"),C1n=({chunk:e,conversation:t,metadata:n})=>{const r=[...t];if(O1n(e))return r;if(_1n(e)){if(e.type==="data-user-message"&&"data"in e&&(e.data?.type==="user-message"||e.data?.type==="user")){const i=e.data.id,l=e.data?.metadata?.[E$];if(typeof l=="string"&&r.some(f=>f.content.metadata?.status==="pending"&&f.content.metadata.clientMessageId===l))return Wb(r.map(f=>f.content.metadata?.status==="pending"&&f.content.metadata.clientMessageId===l?jLe(f,e.data.contents,n,{signalId:typeof i=="string"?i:void 0,keepClientMessageId:!0}):f));if(typeof i=="string"&&r.some(f=>f.id===i))return Wb(r.map(f=>f.id===i&&f.content.metadata?.status==="pending"?jLe(f,e.data.contents,n,{keepClientMessageId:!1}):f));const c=vwe(e.data.contents,n);if(!c.length)return r;const u=Wb(r),d=typeof i=="string"?i:`signal-${e.runId}-${Date.now()}`;return[...u,...c.map((f,p)=>({...f,id:p===0?d:`${d}-${p}`}))]}const s={type:e.type,data:"data"in e?e.data:void 0,..."id"in e&&typeof e.id=="string"?{id:e.id}:{}},a=r[r.length-1];return!a||a.role!=="assistant"?yd(r,`data-${e.runId}-${Date.now()}`,[s],n):pi(r,Di(a,[...a.content.parts,s]))}switch(e.type){case"tripwire":{const s=CP(`tripwire-${e.runId+Date.now()}`,[{type:"text",text:e.payload.reason}],{...n,status:"tripwire",tripwire:{reason:e.payload.reason,retry:e.payload.retry,metadata:e.payload.metadata,processorId:e.payload.processorId}});return[...r,s]}case"start":{const s=typeof e.payload.messageId=="string"?e.payload.messageId:void 0;return s&&r.some(a=>a.id===s)?r:[...r,CP(s??`start-${e.runId+Date.now()}`,[],n)]}case"text-start":{const s=r[r.length-1],a=e.payload.id||`text-${Date.now()}`,i=s?.content.parts[s.content.parts.length-1];if(e.payload.id&&s?.role==="assistant"&&i?.type==="text"&&TLe(i)===a)return r;const l={type:"text",text:"",state:"streaming",textId:a,providerMetadata:e.payload.providerMetadata};return!s||s.role!=="assistant"?yd(r,`start-${e.runId}-${Date.now()}`,[l],n):s.content.metadata?.completionResult?yd(r,`start-${e.runId}-${Date.now()}`,[l],n):pi(r,Di(s,[...s.content.parts,l]))}case"background-task-progress":{const s=r[r.length-1];return!s||s.role!=="assistant"?r:pi(r,lx(s,{mode:n.mode,...s.content.metadata,runningBackgroundTasksCount:e.payload.runningCount}))}case"text-delta":{const s=r[r.length-1],a=e.payload.id;if(!s||s.role!=="assistant"){const c={type:"text",text:e.payload.text,state:"streaming",textId:a,providerMetadata:e.payload.providerMetadata};return yd(r,`text-${e.runId}-${Date.now()}`,[c],n)}const i=[...s.content.parts];let l=a?i.findLastIndex(c=>c.type==="text"&&TLe(c)===a):-1;if(l===-1&&(l=i.findLastIndex(c=>c.type==="text"&&The(c)==="streaming")),l!==-1&&i.some((c,u)=>u>l&&c.type!=="text")&&(l=-1),l===-1){const c={type:"text",text:e.payload.text,state:"streaming",textId:a,providerMetadata:e.payload.providerMetadata};i.push(c)}else{const c=i[l];i[l]={...c,text:c.text+e.payload.text,state:"streaming"}}return pi(r,Di(s,i))}case"text-end":return r;case"reasoning-start":{const s=r[r.length-1],a={type:"reasoning",reasoning:"",state:"streaming",providerMetadata:e.payload.providerMetadata};return!s||s.role!=="assistant"?yd(r,`reasoning-${e.runId+Date.now()}`,[a],n):pi(r,Di(s,[...s.content.parts,a]))}case"reasoning-delta":{const s=r[r.length-1];if(!s||s.role!=="assistant"){const c={type:"reasoning",reasoning:e.payload.text,state:"streaming",providerMetadata:e.payload.providerMetadata};return yd(r,`reasoning-${e.runId+Date.now()}`,[c],n)}const a=[...s.content.parts],i=a.length-1,l=a[i];if(l?.type==="reasoning"){const c=l;a[i]={...c,reasoning:c.reasoning+e.payload.text,state:"streaming"}}else{const c={type:"reasoning",reasoning:e.payload.text,state:"streaming",providerMetadata:e.payload.providerMetadata};a.push(c)}return pi(r,Di(s,a))}case"reasoning-end":{const s=r[r.length-1];if(!s||s.role!=="assistant")return r;const a=[...s.content.parts],i=a.findLastIndex(d=>d.type==="reasoning"&&The(d)==="streaming");if(i===-1)return r;const l=a[i],c=l.providerMetadata,u=e.payload.providerMetadata;return a[i]={...l,state:"done",...c||u?{providerMetadata:{...c??{},...u??{}}}:{}},pi(r,Di(s,a))}case"reasoning-signature":{const s=r[r.length-1];if(!s||s.role!=="assistant")return r;const a=[...s.content.parts],i=a.findLastIndex(d=>d.type==="reasoning");if(i===-1)return r;const l=a[i],c=l.providerMetadata,u=e.payload.providerMetadata;return a[i]={...l,...c||u?{providerMetadata:{...c??{},...u??{}}}:{}},pi(r,Di(s,a))}case"redacted-reasoning":{const s=r[r.length-1],a=e.payload.data,i={type:"reasoning",reasoning:typeof a=="string"?a:"",state:"done",redacted:!0,providerMetadata:e.payload.providerMetadata};return!s||s.role!=="assistant"?yd(r,`redacted-reasoning-${e.runId+Date.now()}`,[i],n):pi(r,Di(s,[...s.content.parts,i]))}case"tool-call":{const s={state:"call",toolCallId:e.payload.toolCallId,toolName:e.payload.toolName,args:e.payload.args},a={...NLe(s),providerMetadata:e.payload.providerMetadata},i=G0(r,e.payload.toolCallId,!1);if(i&&i.toolPartIndex>=0){const{messageIndex:c,toolPartIndex:u}=i,d=r[c];if(d&&d.role==="assistant"){const f=[...d.content.parts],p=f[u];if(uw(p)){const{argsText:h,...m}=p;return f[u]={...m,toolInvocation:{...p.toolInvocation,state:"call",toolName:e.payload.toolName,toolCallId:e.payload.toolCallId,args:e.payload.args},providerMetadata:e.payload.providerMetadata??p.providerMetadata},Z0(r,c,Di(d,f))}}}const l=r[r.length-1];return!l||l.role!=="assistant"?yd(r,`tool-call-${e.runId+Date.now()}`,[a],n):pi(r,Di(l,[...l.content.parts,a]))}case"tool-call-input-streaming-start":{const s=r[r.length-1],a={state:"partial-call",toolCallId:e.payload.toolCallId,toolName:e.payload.toolName,args:{}},i={...NLe(a),argsText:""};return!s||s.role!=="assistant"?yd(r,`tool-call-streaming-${e.runId+Date.now()}`,[i],n):pi(r,Di(s,[...s.content.parts,i]))}case"tool-call-delta":{const s=G0(r,e.payload.toolCallId,!1);if(!s||s.toolPartIndex<0)return r;const{messageIndex:a,toolPartIndex:i}=s,l=r[a];if(!l||l.role!=="assistant")return r;const c=[...l.content.parts],u=c[i];if(!uw(u))return r;const d=(u.argsText??"")+(e.payload.argsTextDelta??"");return c[i]={...u,argsText:d,toolInvocation:{...u.toolInvocation,state:"partial-call"}},Z0(r,a,Di(l,c))}case"tool-call-input-streaming-end":{const s=G0(r,e.payload.toolCallId,!1);if(!s||s.toolPartIndex<0)return r;const{messageIndex:a,toolPartIndex:i}=s,l=r[a];if(!l||l.role!=="assistant")return r;const c=[...l.content.parts],u=c[i];if(!uw(u))return r;let d={};const f=u.argsText;if(typeof f=="string"&&f.length>0)try{const p=JSON.parse(f);p&&typeof p=="object"&&!Array.isArray(p)&&(d=p)}catch{d={}}return c[i]={...u,toolInvocation:{...u.toolInvocation,state:"call",args:d}},Z0(r,a,Di(l,c))}case"tool-output-denied":{const s=G0(r,e.payload.toolCallId,!1);if(!s||s.toolPartIndex<0)return r;const{messageIndex:a,toolPartIndex:i}=s,l=r[a];if(!l||l.role!=="assistant")return r;const c=[...l.content.parts],u=c[i];return uw(u)?(c[i]={...u,toolInvocation:{...u.toolInvocation,state:"output-denied",toolName:e.payload.toolName,args:e.payload.args??u.toolInvocation.args,approval:e.payload.approval}},Z0(r,a,Di(l,c))):r}case"tool-error":case"tool-result":case"background-task-completed":case"background-task-failed":{const s=e.type==="background-task-completed"||e.type==="background-task-failed",a=G0(r,e.payload.toolCallId,s);if(!a)return r;const{messageIndex:i,toolPartIndex:l}=a,c=r[i];if(!c||c.role!=="assistant")return r;const u=[...c.content.parts],d=l>=0?u[l]:void 0;let f,p,h=!1,m,v,y;switch(e.type){case"tool-result":f=e.payload.result,h=!!e.payload.isError,m=e.payload.providerMetadata;break;case"tool-error":p=e.payload.error,m=e.payload.providerMetadata;break;case"background-task-completed":f=e.payload.result,v=e.payload.completedAt,y=e.payload.taskId;break;case"background-task-failed":p=e.payload.error,v=e.payload.completedAt,y=e.payload.taskId;break}if(d&&uw(d)){const{toolName:S,toolCallId:k,args:_}=d.toolInvocation,C=m??d.providerMetadata;if(e.type==="tool-error"||e.type==="background-task-failed"||h){const E=e.type==="tool-error"||e.type==="background-task-failed"?p:f,T=typeof E=="string"?E:E instanceof Error?E.message:E?.message??String(E);u[l]={...d,providerMetadata:C,toolInvocation:{state:"output-error",toolCallId:k,toolName:S,args:_,errorText:T}}}else{const E=f,T=d.toolInvocation.state==="partial-call"||d.toolInvocation.state==="result"?d.toolInvocation.result:void 0,N=!!(T&&typeof T=="object"&&"steps"in T),I=!!E?.result?.steps||S?.startsWith("workflow-")||N,A=e.from==="AGENT";let R;if(I){const L=N&&T&&typeof T=="object"?T:void 0,D=E?.result&&typeof E.result=="object"?E.result:void 0;L||D?R={...L??{},...D??{},steps:D?.steps??L?.steps??[],status:D?.status??L?.status??"success",output:f}:R=f}else if(A){const L=d.toolInvocation.state==="result"?d.toolInvocation.result:void 0,D=L?.childMessages;R=L?{...f,childMessages:D?.length?D:E?.childMessages}:f}else R=f;u[l]={...d,providerMetadata:C,toolInvocation:{state:"result",toolCallId:k,toolName:S,args:_,result:R}}}}const b=XX(c.content.metadata,n.mode,{resetRunningCount:s,perTaskEntry:s&&y?{toolCallId:e.payload.toolCallId,completedAt:v,taskId:y}:void 0}),x={...c,content:{...c.content,parts:u,metadata:b}};return Z0(r,i,x)}case"background-task-running":{const s=G0(r,e.payload.toolCallId,!0);if(!s)return r;const{messageIndex:a}=s,i=r[a];if(!i||i.role!=="assistant")return r;const l=XX(i.content.metadata,n.mode,{perTaskEntry:{toolCallId:e.payload.toolCallId,startedAt:e.payload.startedAt,taskId:e.payload.taskId}});return Z0(r,a,lx(i,l))}case"tool-output":case"background-task-output":{const s=e.type==="background-task-output",a=G0(r,e.payload.toolCallId,s);if(!a||a.toolPartIndex<0)return r;const{messageIndex:i,toolPartIndex:l}=a,c=r[i];if(!c||c.role!=="assistant")return r;const u=[...c.content.parts],d=u[l];if(!uw(d))return r;const{toolName:f,toolCallId:p,args:h}=d.toolInvocation,m=e.type==="background-task-output"?e.payload.payload.payload.output:e.payload.output;if(m?.type?.startsWith("workflow-")){const v=d.toolInvocation.result||{},y=Cw(v,m);u[l]={...d,toolInvocation:{state:"partial-call",toolCallId:p,toolName:f,args:h,result:y}}}else{if(m?.from==="AGENT"||m?.from==="USER"&&m?.payload?.output?.type?.startsWith("workflow-"))return T1n(m,r,n,p,f);{const v=d.toolInvocation.result,y=Array.isArray(v)?v:[];u[l]={...d,toolInvocation:{state:"partial-call",toolCallId:p,toolName:f,args:h,result:[...y,m]}}}}return Z0(r,i,Di(c,u))}case"is-task-complete":{if(e.payload.suppressFeedback)return r;const s=w1n({complete:e.payload.passed,scorers:e.payload.results,totalDuration:e.payload.duration,timedOut:e.payload.timedOut,completionReason:e.payload.reason},e.payload.maxIterationReached),a=CP(`is-task-complete-${e.runId+Date.now()}`,[{type:"text",text:s}],{...n,completionResult:{passed:e.payload.passed}});return[...r,a]}case"source":{const s=r[r.length-1];if(!s||s.role!=="assistant")return r;const a=[...s.content.parts];if(e.payload.sourceType==="url"){const i={type:"source-url",sourceId:e.payload.id,url:e.payload.url||"",title:e.payload.title,providerMetadata:e.payload.providerMetadata};a.push(i)}else e.payload.sourceType==="document"&&a.push({type:"source-document",sourceId:e.payload.id,mediaType:e.payload.mimeType||"application/octet-stream",title:e.payload.title,filename:e.payload.filename,providerMetadata:e.payload.providerMetadata});return pi(r,Di(s,a))}case"file":{const s=r[r.length-1];if(!s||s.role!=="assistant")return r;const a=[...s.content.parts];let i;if(typeof e.payload.data=="string")i=e.payload.base64?`data:${e.payload.mimeType};base64,${e.payload.data}`:`data:${e.payload.mimeType},${encodeURIComponent(e.payload.data)}`;else{const l=gwe(e.payload.data);i=`data:${e.payload.mimeType};base64,${l}`}return a.push({type:"file",mimeType:e.payload.mimeType,data:i,providerMetadata:e.payload.providerMetadata}),pi(r,Di(s,a))}case"tool-call-approval":{const s=r[r.length-1];if(!s||s.role!=="assistant")return r;const a=s.content.metadata??{},i=a.mode==="stream"?a.requireApprovalMetadata??{}:{};return pi(r,{...s,content:{...s.content,metadata:{...a,mode:"stream",requireApprovalMetadata:{...i,[e.payload.toolName]:{toolCallId:e.payload.toolCallId,toolName:e.payload.toolName,args:e.payload.args}}}}})}case"tool-call-suspended":case"background-task-suspended":{const s=e.type==="background-task-suspended";let a,i,l,c,u,d;e.type==="background-task-suspended"?(a=e.payload.toolCallId,i=e.payload.toolName,l=e.payload.args,c=e.payload.suspendPayload,u=e.payload.suspendedAt,d=e.payload.taskId):(a=e.payload.toolCallId,i=e.payload.toolName,l=e.payload.args,c=e.payload.suspendPayload);const f=s?G0(r,a,!0):{messageIndex:r.length-1};if(!f)return r;const{messageIndex:p}=f,h=r[p];if(!h||h.role!=="assistant")return r;const m=h.content.metadata??{},v=m.mode==="stream"?m.suspendedTools??{}:{},y=XX(m,"stream",{resetRunningCount:s,perTaskEntry:s&&d?{toolCallId:a,suspendedAt:u,taskId:d}:void 0},{suspendedTools:{...v,[i]:{toolCallId:a,toolName:i,args:l,suspendPayload:c,runId:e.runId}}});return Z0(r,p,lx(h,y))}case"finish":case"abort":return Wb(r);case"error":{const s=CP(`error-${e.runId+Date.now()}`,[{type:"text",text:typeof e.payload.error=="string"?e.payload.error:JSON.stringify(e.payload.error)}],{...n,status:"error"});return[...r,s]}case"step-start":{const s=typeof e.payload?.messageId=="string"?e.payload.messageId:void 0;if(!s)return r;const a=r[r.length-1];return!a||a.role!=="assistant"||r.some(i=>i.id===s)?r:a.content.parts.some(i=>!String(i.type).startsWith("data-"))?yd(Wb(r),s,[],n):pi(r,{...a,id:s})}case"step-finish":case"step-output":case"raw":case"watch":case"response-metadata":return r;case"goal":return r;case"object":case"object-result":return r;case"background-task-started":case"background-task-cancelled":case"background-task-resumed":return r;case"workflow-start":case"workflow-finish":case"workflow-canceled":case"workflow-paused":case"workflow-step-start":case"workflow-step-finish":case"workflow-step-suspended":case"workflow-step-waiting":case"workflow-step-output":case"workflow-step-progress":case"workflow-step-result":return r;case"agent-execution-start":case"agent-execution-approval":case"agent-execution-suspended":case"agent-execution-end":case"agent-execution-abort":case"tool-execution-start":case"tool-execution-end":case"tool-execution-approval":case"tool-execution-suspended":case"tool-execution-abort":case"routing-agent-start":case"routing-agent-text-delta":case"routing-agent-text-start":case"routing-agent-end":case"routing-agent-abort":case"workflow-execution-start":case"workflow-execution-end":case"workflow-execution-suspended":case"workflow-execution-abort":case"network-execution-event-step-finish":case"network-execution-event-finish":case"network-validation-start":case"network-validation-end":case"network-object":case"network-object-result":case"tool-output-denied":return r;default:return E1n(e,r)}},E1n=(e,t)=>t,T1n=(e,t,n,r,s)=>{const a=t[t.length-1];if(!a||a.role!=="assistant")return t;const i=[...a.content.parts],l=()=>i.findIndex(c=>uw(c)&&(r&&c.toolInvocation.toolCallId===r||s&&c.toolInvocation.toolName===s));if(e.type==="text-delta"){const c=e.payload,u=l();if(u===-1)return t;const d=i[u],f=d.toolInvocation.result||{},p=f.childMessages||[],h=p[p.length-1],m={type:"text",content:(h?.content||"")+c.text},v=h?.type==="text"?[...p.slice(0,-1),m]:[...p,m];i[u]={...d,toolInvocation:{...d.toolInvocation,result:{...f,childMessages:v}}}}else if(e.type==="tool-call"){const c=e.payload,u=l();if(u===-1)return t;const d=i[u],f=d.toolInvocation.result||{},p=f.childMessages||[];i[u]={...d,toolInvocation:{...d.toolInvocation,result:{...f,childMessages:[...p,{type:"tool",toolCallId:c.toolCallId,toolName:c.toolName,args:c.args}]}}}}else if(e.type==="tool-output"){const c=e.payload,u=l();if(u===-1)return t;const d=i[u];if(c?.output?.type?.startsWith("workflow-")){const f=d.toolInvocation.result||{},p=f.childMessages||[],h=p.length-1,m=p[h],v=m?.toolOutput||{},y=Cw(v,c.output);h>=0&&p[h]?.type==="tool"&&(i[u]={...d,toolInvocation:{...d.toolInvocation,result:{...f,childMessages:[...p.slice(0,-1),{...m,toolOutput:{...y,runId:c.output.runId}}]}}})}}else if(e.type==="tool-result"){const c=e.payload,u=l();if(u===-1)return t;const d=i[u],f=d.toolInvocation.result||{},p=f.childMessages||[],h=p.length-1,m=c?.toolName?.startsWith("workflow-");h>=0&&p[h]?.type==="tool"&&(i[u]={...d,toolInvocation:{...d.toolInvocation,result:{...f,childMessages:[...p.slice(0,-1),{...p[h],toolOutput:m?{...c.result?.result,runId:c.result?.runId}:c.result}]}}})}return pi(t,Di(a,i))},VD=e=>({...e,mode:"network"}),T$=(e,t)=>e.findIndex(t),u7=e=>e.type==="dynamic-tool",zv=e=>{const t=e[e.length-1];return t&&t.role==="assistant"?t:void 0},j1n=e=>{const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;try{const n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}},N1n=(e,t,n)=>{const r=e.payload?.text??"";if(!r)return t;const s=zv(t),a=i=>{const l=(i.routingDecisionBuffer??"")+r,c={...EO(i),mode:"network"},u=j1n(l);return u?(c.routingDecision=u,delete c.routingDecisionBuffer,delete c.routingDecisionText):(c.routingDecisionBuffer=l,c.routingDecisionText=l),c};if(!s){const i=a({});return yd(t,`routing-agent-${e.payload?.runId??"unknown"}-${Date.now()}`,[],{...VD(n),...i})}return pi(t,lx(s,a(s.content.metadata??{})))},I1n=(e,t,n)=>{if(e.type==="agent-execution-start"){const r=e.payload?.args?.primitiveId,s=e.payload.runId;if(!r||!s)return t;const a={type:"dynamic-tool",toolName:r,toolCallId:s,state:"input-available",input:e.payload.args};return yd(t,`agent-execution-start-${s}-${Date.now()}`,[a],{...VD(n),selectionReason:e.payload?.args?.selectionReason||"",agentInput:e.payload?.args?.task,from:"AGENT"})}if(e.type==="agent-execution-end"){const r=zv(t);if(!r)return t;const s=[...r.content.parts],a=T$(s,i=>u7(i));if(a!==-1){const i=s[a],l=i.output;s[a]={type:"dynamic-tool",toolName:i.toolName,toolCallId:i.toolCallId,state:"output-available",input:i.input,output:{...l,result:l?.result||e.payload?.result||""}}}return pi(t,Di(r,s))}if(e.type.startsWith("agent-execution-event-")){const r=zv(t);if(!r)return t;const s=e.payload,a=[...r.content.parts],i=T$(a,c=>u7(c));if(i===-1)return t;const l=a[i];if(s.type==="text-delta"){const c=l?.output?.childMessages||[],u=c[c.length-1],d={type:"text",content:(u?.content||"")+s.payload.text},f=u?.type==="text"?[...c.slice(0,-1),d]:[...c,d];a[i]={...l,output:{childMessages:f}}}else if(s.type==="tool-call"){const c=l?.output?.childMessages||[];a[i]={...l,output:{...l?.output,childMessages:[...c,{type:"tool",toolCallId:s.payload.toolCallId,toolName:s.payload.toolName,args:s.payload.args}]}}}else if(s.type==="tool-output"){if(s.payload?.output?.type?.startsWith("workflow-")){const c=l?.output?.childMessages||[],u=c.length-1,d=c[u],f=d?.toolOutput||{},p=Cw(f,s.payload.output);u>=0&&c[u]?.type==="tool"&&(a[i]={...l,output:{...l?.output,childMessages:[...c.slice(0,-1),{...d,toolOutput:p}]}})}}else if(s.type==="tool-result"){const c=l?.output?.childMessages||[],u=c.length-1,d=!!s.payload?.result?.result?.steps;u>=0&&c[u]?.type==="tool"&&(a[i]={...l,output:{...l?.output,childMessages:[...c.slice(0,-1),{...c[u],toolOutput:d?s.payload.result.result:s.payload.result}]}})}return pi(t,Di(r,a))}return t},A1n=(e,t,n)=>{if(e.type==="workflow-execution-start"){const r=e.payload?.args?.primitiveId,s=e.payload.runId;if(!r||!s)return t;let a;try{a=JSON.parse(e.payload?.args?.prompt)}catch{a=e.payload?.args?.prompt}const i={type:"dynamic-tool",toolName:r,toolCallId:s,state:"input-available",input:e.payload.args};return yd(t,`workflow-start-${s}-${Date.now()}`,[i],{...VD(n),selectionReason:e.payload?.args?.selectionReason||"",from:"WORKFLOW",agentInput:a})}if(e.type==="workflow-execution-suspended"){const r=zv(t);if(!r)return t;const s=r.content.metadata?.suspendedTools??{};return pi(t,lx(r,{...EO(r.content.metadata),mode:"network",suspendedTools:{...s,[e.payload.toolName]:{toolCallId:e.payload.toolCallId,toolName:e.payload.toolName,args:e.payload.args,suspendPayload:e.payload.suspendPayload,runId:e.payload.runId}}}))}if(e.type.startsWith("workflow-execution-event-")){const r=zv(t);if(!r)return t;const s=[...r.content.parts],a=T$(s,u=>u7(u));if(a===-1)return t;const i=s[a],l=i.output||{},c=Cw(l,e.payload);return s[a]={...i,output:c},pi(t,Di(r,s))}return t},R1n=(e,t,n)=>{if(e.type==="tool-execution-start"){const r=e.payload.args,s=r.args||{},a=zv(t),i={type:"dynamic-tool",toolName:r.toolName||"unknown",toolCallId:r.toolCallId||"unknown",state:"input-available",input:s};if(!a)return yd(t,`tool-start-${e.payload.runId}-${Date.now()}`,[i],{...VD(n),selectionReason:n.mode==="network"?n.selectionReason||r.selectionReason:"",agentInput:s});const l=[...a.content.parts,i];return pi(t,Di(a,l))}if(e.type==="tool-execution-approval"){const r=zv(t);if(!r)return t;const s=r.content.metadata?.requireApprovalMetadata??{};return pi(t,lx(r,{...EO(r.content.metadata),mode:"network",requireApprovalMetadata:{...s,[e.payload.toolName]:{toolCallId:e.payload.toolCallId,toolName:e.payload.toolName,args:e.payload.args,runId:e.payload.runId}}}))}if(e.type==="tool-execution-suspended"){const r=zv(t);if(!r)return t;const s=r.content.metadata?.suspendedTools??{};return pi(t,lx(r,{...EO(r.content.metadata),mode:"network",suspendedTools:{...s,[e.payload.toolName]:{toolCallId:e.payload.toolCallId,toolName:e.payload.toolName,args:e.payload.args,suspendPayload:e.payload.suspendPayload,runId:e.payload.runId}}}))}if(e.type==="tool-execution-end"){const r=zv(t);if(!r)return t;const s=[...r.content.parts],a=T$(s,i=>u7(i)&&i.toolCallId===e.payload.toolCallId);if(a!==-1){const i=s[a],l=i.output;s[a]={type:"dynamic-tool",toolName:i.toolName,toolCallId:i.toolCallId,state:"output-available",input:i.input,output:l?.result||e.payload?.result||""}}return pi(t,Di(r,s))}return t},JX=({chunk:e,conversation:t,metadata:n})=>{const r=[...t];if(e.type==="routing-agent-text-delta")return N1n(e,r,n);if(e.type.startsWith("agent-execution-"))return I1n(e,r,n);if(e.type.startsWith("workflow-execution-"))return A1n(e,r,n);if(e.type.startsWith("tool-execution-"))return R1n(e,r,n);if(e.type==="network-validation-end"){if(e.payload.suppressFeedback)return r;const s={type:"text",text:x1n({complete:e.payload.passed,scorers:e.payload.results,totalDuration:e.payload.duration,timedOut:e.payload.timedOut,completionReason:e.payload.reason},e.payload.maxIterationReached)};return yd(r,`network-validation-end-${e.payload.runId}-${Date.now()}`,[s],{...VD(n),completionResult:{passed:e.payload.passed}})}if(e.type==="network-execution-event-step-finish"){const s=zv(r);if(!s)return r;const a=e.payload,i=[...s.content.parts],l=T$(i,u=>u.type==="text");if(l===-1)return i.push({type:"text",text:a.result,state:"done"}),pi(r,Di(s,i));const c=i[l];return c.type==="text"?(i[l]={...c,state:"done"},pi(r,Di(s,i))):r}return r},P1n=e=>typeof e.content=="string"?[{type:"text",text:e.content}]:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":{const n=t.mimeType??"image/*";return{type:"file",mimeType:n,data:c7(t.image,n)}}case"file":return{type:"file",mimeType:t.mimeType,data:c7(t.data,t.mimeType),...t.filename!==void 0?{filename:t.filename}:{}};default:throw new Error(`Unhandled content part type: ${t.type}`)}}),$1n=e=>({id:`user-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,role:"user",createdAt:new Date,content:{format:2,parts:e}}),ILe=e=>$1n(e.flatMap(P1n)),gmt=new Set(["task_write","task_update","task_complete","task_check"]),M1n="tasks",D1n=new Set(["current-task-list","task-list-update"]),L1n=new Set(["pending","in_progress","completed"]),F1n=e=>typeof e.type=="string"&&e.type.startsWith("data-"),Xh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),z1n=e=>typeof e=="string"&&L1n.has(e),jhe=e=>Array.isArray(e)&&e.every(t=>Xh(t)&&typeof t.id=="string"&&typeof t.content=="string"&&z1n(t.status)&&typeof t.activeForm=="string"),B1n=e=>Xh(e)?e.id===M1n||typeof e.tagName=="string"&&D1n.has(e.tagName):!1,ywe=e=>{if(!B1n(e)||!Xh(e))return;const t=e.metadata;if(!Xh(t))return;const n=t.value;if(Xh(n))return jhe(n.tasks)?n.tasks:void 0},vmt=e=>{if(Xh(e)&&jhe(e.tasks))return e.tasks;if(typeof e=="string")try{const t=JSON.parse(e);return Xh(t)&&jhe(t.tasks)?t.tasks:void 0}catch{return}},U1n=e=>{if(F1n(e))return ywe(e.data)},V1n=e=>{if(e.type!=="tool-result")return;const t=e.payload;if(!(!Xh(t)||typeof t.toolName!="string"||!gmt.has(t.toolName)))return vmt(t.result)},q1n=e=>{if(!Xh(e)||e.type!=="tool-invocation"||!Xh(e.toolInvocation))return;const t=e.toolInvocation;if(!(typeof t.toolName!="string"||!gmt.has(t.toolName)))return vmt(t.result)},H1n=e=>{if(!(!Xh(e)||typeof e.type!="string"||!e.type.startsWith("data-")))return ywe(e.data)},W1n=e=>{if(e.role!=="signal")return;const t=e.content?.metadata;if(Xh(t))return ywe(t.signal)},Z1n=e=>{let t;for(const n of e){for(const s of n.content?.parts??[]){const a=q1n(s);a!==void 0&&(t=a)}const r=W1n(n);r!==void 0&&(t=r);for(const s of n.content?.parts??[]){const a=H1n(s);a!==void 0&&(t=a)}}return t??[]},d7=e=>e!==null&&typeof e=="object",G1n=["pendingToolApprovals","requireApprovalMetadata","suspendedTools"],Q1n=e=>d7(e)&&Object.values(e).every(t=>d7(t)),Y1n=e=>{if(!d7(e))return[];const t=[];for(const n of G1n){const r=e[n];Q1n(r)&&t.push(r)}return t},K1n=e=>{for(const t of e)for(const n of Y1n(t.content?.metadata))for(const r of Object.values(n))if(d7(r)&&typeof r.runId=="string"&&r.runId.length>0)return r.runId},X1n=e=>{const t=new Set;for(const n of e){const r=n.content?.metadata;if(!r)continue;const s=[r.pendingToolApprovals,r.requireApprovalMetadata,r.suspendedTools];for(const a of s)if(!(!a||typeof a!="object"))for(const i of Object.values(a)){const l=i?.toolCallId;typeof l=="string"&&l.length>0&&t.add(l)}}return t},J1n=(e,t)=>e.some(n=>{if(n.type!=="tool-invocation")return!1;const r=n.toolInvocation;return r.toolCallId!==t?!1:r.state==="result"||r.result!=null}),eSn=e=>e.filter(t=>{const n=t.content?.metadata;return!(n?.completionResult?.suppressFeedback||n?.isTaskCompleteResult?.suppressFeedback)}).map(t=>{const n=t.content?.metadata,r=n&&(n.status==="pending"||"clientMessageId"in n)?(()=>{const{[E$]:d,...f}=n,{status:p,...h}=f;return{...t,content:{...t.content,metadata:n.status==="pending"?h:f}}})():t,s=r.content?.metadata,a=s?.pendingToolApprovals;if(!a||typeof a!="object")return r;const i=Object.fromEntries(Object.entries(a).filter(([,d])=>d&&typeof d=="object"&&typeof d.toolCallId=="string"&&!J1n(r.content.parts,d.toolCallId))),{pendingToolApprovals:l,...c}=s,u=Object.keys(i).length>0;return{...r,content:{...r.content,metadata:{...c,mode:"stream",...u?{pendingToolApprovals:i,requireApprovalMetadata:i}:{}}}}}),ymt=e=>typeof e=="object"&&e!==null,tSn=e=>ymt(e)&&typeof e.name=="string"?e.name:void 0,eJ=e=>tSn(e)==="AbortError",tJ=e=>{if(!ymt(e))return!1;const t=e.status;return t===404||t===405||t===501?!0:t===400&&typeof e.message=="string"&&e.message.includes("No active agent run found for signal target")},nSn=e=>typeof e.type=="string"&&e.type.startsWith("data-"),Q5=(e,t)=>e.map(n=>{const r=Fv.fromUIMessage(n);return{...r,content:{...r.content,metadata:{...r.content.metadata??{},...t}}}}),bwe=({agentId:e,resourceId:t,threadId:n,initialMessages:r,requestContext:s,clientTools:a,onSignalSent:i,onSignalEcho:l,onThreadSignalsUnsupported:c,enableThreadSignals:u=!1})=>{const d=u===!1,f=g.useRef(void 0),p=g.useRef(void 0),h=g.useRef(void 0),m=g.useRef(void 0),v=g.useRef({requestContext:s}),y=g.useRef(null),b=g.useRef(null),x=g.useRef(null),S=g.useRef(void 0),k=g.useRef(null),_=g.useRef(!1),[C,E]=g.useState([]),[T,N]=g.useState([]),[I,A]=g.useState({}),[R,L]=g.useState({}),D=g.useRef(new Set),[F,H]=g.useState(!1),B=Ze(),[U,V]=g.useState(!1);g.useEffect(()=>{const be=eSn(r??[]);E(be),N(Z1n(be)),D.current=X1n(be),H(D.current.size>0),f.current=K1n(be)},[r]),g.useEffect(()=>{v.current={...v.current,requestContext:s}},[s]);const M=be=>be instanceof URL?be.toString():b1n(be),G=be=>{const we=be.reduce((Oe,ke)=>{if(typeof ke.content=="string")return Oe.push({type:"text",text:ke.content}),Oe;for(const Ne of ke.content)Ne.type==="text"?Oe.push({type:"text",text:Ne.text}):Ne.type==="file"?Oe.push({type:"file",data:M(Ne.data),mediaType:Ne.mimeType,...Ne.filename?{filename:Ne.filename}:{}}):Ne.type==="image"&&Oe.push({type:"file",data:M(Ne.image),mediaType:Ne.mimeType??"image/png"});return Oe},[]);return we.length===1&&we[0]?.type==="text"?we[0].text:we},q=g.useCallback(()=>{_.current=!0,c?.()},[c]),$=be=>be.flatMap(we=>typeof we.content=="string"?[we.content]:we.content.map(Oe=>Oe.type==="text"?Oe.text:Oe.type==="image"?"Image":Oe.filename?`File: ${Oe.filename}`:"File")).join(" ").replace(/\s+/g," ").trim()||"Attachment",z=g.useCallback(()=>{const be=x.current;be?.unsubscribe?be.unsubscribe():b.current?.abort(),x.current=null,b.current=null,S.current=void 0,k.current=null},[]),Z=g.useCallback(async(be,we)=>{E(Ne=>C1n({chunk:be,conversation:Ne,metadata:{mode:"stream"}}));const Oe=U1n(be);Oe!==void 0&&N(Oe);const ke=V1n(be);if(ke!==void 0&&N(ke),be.type==="data-user-message"&&nSn(be)&&(be.data?.type==="user-message"||be.data?.type==="user")&&typeof be.data?.id=="string"&&l?.(be.data.id),be.type==="start"&&(V(!0),"runId"in be&&typeof be.runId=="string"&&(f.current=be.runId)),be.type==="tool-call-approval"||be.type==="tool-call-suspended"){const Ne=be.payload?.toolCallId;typeof Ne=="string"&&(D.current.add(Ne),H(!0)),V(!1)}(be.type==="finish"||be.type==="abort"||be.type==="error")&&(D.current.clear(),H(!1),V(!1)),(we??p.current)?.(be)},[l]),K=g.useCallback(async({threadId:be,resourceId:we})=>{const Oe=`${e}:${we??""}:${be}`;if(S.current===Oe&&k.current){await k.current;return}z();const ke=new AbortController;b.current=ke,S.current=Oe;const Ne=()=>{b.current===ke&&(x.current=null,b.current=null,S.current=void 0,k.current=null)},Pe=new SP({...B.options,abortSignal:ke.signal}).getAgent(e);k.current=Pe.subscribeToThread({resourceId:we,threadId:be}).then(ie=>{const re=ie;if(b.current!==ke){re.unsubscribe();return}x.current=re,re.processDataStream({onChunk:se=>Z(se)}).catch(se=>{eJ(se)||(console.error("[useChat] Thread subscription failed",se),V(!1))}).finally(()=>{x.current===re&&(x.current=null),Ne()})}).catch(ie=>{if(Ne(),tJ(ie)){q();return}throw eJ(ie)||(console.error("[useChat] Thread subscription failed",ie),V(!1)),ie}),await k.current},[e,B,z,q,Z]);g.useEffect(()=>(_.current=!1,z),[e,t,n,z]),g.useEffect(()=>{if(!n||d){z();return}K({threadId:n,resourceId:t||e}).catch(be=>{eJ(be)||console.error("[useChat] Thread subscription failed",be)})},[e,z,K,t,n,d]);const ne=async({coreUserMessages:be,model:we,requestContext:Oe,threadId:ke,modelSettings:Ne,signal:Pe,onFinish:ie,tracingOptions:re,clientTools:se})=>{const{frequencyPenalty:de,presencePenalty:xe,maxRetries:Ce,maxTokens:Re,temperature:Me,topK:We,topP:je,instructions:Ee,providerOptions:_e,maxSteps:Ie,requireToolApproval:$e}=Ne||{},Ve=Oe??s,Je=se??a;v.current={model:we,requestContext:Ve},V(!0);const nt=new SP({...B.options,abortSignal:Pe}).getAgent(e),Ft=wo();f.current=Ft;const Ot=await nt.generate(be,{model:we,runId:Ft,maxSteps:Ie,modelSettings:{frequencyPenalty:de,presencePenalty:xe,maxRetries:Ce,maxOutputTokens:Re,temperature:Me,topK:We,topP:je},instructions:Ee,requestContext:Ve,...ke?{memory:{thread:ke,resource:t||e}}:{},providerOptions:_e,tracingOptions:re,requireToolApproval:$e,clientTools:Je});if(Ot.finishReason==="suspended"&&Ot.suspendPayload){const{toolCallId:Qt,toolName:at,args:_t}=Ot.suspendPayload;if(Ot.response?.uiMessages){const Zt=Q5(Ot.response.uiMessages,{mode:"generate",requireApprovalMetadata:{[at]:{toolCallId:Qt,toolName:at,args:_t}}});E(Qe=>[...Qe,...Zt])}V(!1);return}if(V(!1),Ot&&"uiMessages"in Ot.response&&Ot.response.uiMessages){const Qt=Q5(Ot.response.uiMessages,{mode:"generate"});ie?.(Qt),E(at=>[...at,...Qt])}},ee=async({coreUserMessages:be,model:we,requestContext:Oe,threadId:ke,onChunk:Ne,modelSettings:Pe,signal:ie,tracingOptions:re,clientTools:se,signalId:de,clientMessageId:xe})=>{const{frequencyPenalty:Ce,presencePenalty:Re,maxRetries:Me,maxTokens:We,temperature:je,topK:Ee,topP:_e,instructions:Ie,providerOptions:$e,maxSteps:Ve,requireToolApproval:Je}=Pe||{},nt=Oe??s,Ft=se??a,Ot={model:we,maxSteps:Ve,modelSettings:{frequencyPenalty:Ce,presencePenalty:Re,maxRetries:Me,maxOutputTokens:We,temperature:je,topK:Ee,topP:_e},instructions:Ie,providerOptions:$e,requireToolApproval:Je,tracingOptions:re};v.current={model:we,requestContext:nt},V(!0),y.current?.abort();const Qt=new AbortController;y.current=Qt,ie&&(ie.aborted?Qt.abort():ie.addEventListener("abort",()=>Qt.abort(),{once:!0}));const at=new SP({...B.options,abortSignal:Qt.signal}).getAgent(e),_t=async()=>{const mt=wo(),Rt=await at.stream(be,{model:we,runId:mt,maxSteps:Ve,untilIdle:!0,modelSettings:{frequencyPenalty:Ce,presencePenalty:Re,maxRetries:Me,maxOutputTokens:We,temperature:je,topK:Ee,topP:_e},instructions:Ie,requestContext:nt,...ke?{memory:{thread:ke,resource:t||e}}:{},providerOptions:$e,requireToolApproval:Je,tracingOptions:re,clientTools:Ft});p.current=Ne,f.current=mt,await Rt.processDataStream({onChunk:hn=>Z(hn,Ne)}),y.current===Qt&&(y.current=null),V(!1)};if(!ke||_.current||d){await _t();return}if(p.current=Ne,await K({threadId:ke,resourceId:t||e}),_.current){await _t();return}const Zt=de??wo(),Qe=G(be),ot=nt,pt={model:we,maxSteps:Ve,modelSettings:{frequencyPenalty:Ce,presencePenalty:Re,maxRetries:Me,maxOutputTokens:We,temperature:je,topK:Ee,topP:_e},instructions:Ie,requestContext:ot,providerOptions:$e,requireToolApproval:Je,tracingOptions:re};try{const mt=await at.sendMessage({message:xe?{contents:Qe,metadata:{[E$]:xe}}:Qe,resourceId:t||e,threadId:ke,ifIdle:{streamOptions:{...Ot,requestContext:ot,clientTools:Ft}}}),Rt=mt.signal&&typeof mt.signal=="object"&&"id"in mt.signal&&typeof mt.signal.id=="string"?mt.signal.id:Zt;i?.(Rt,$(be)),D.current.size>0&&V(!1)}catch(mt){if(tJ(mt)){i?.(Zt,$(be));try{await at.sendSignal({signal:{id:Zt,type:"user-message",contents:Qe},resourceId:t||e,threadId:ke,ifIdle:{streamOptions:pt}});return}catch(Rt){if(l?.(Zt),tJ(Rt)){q(),E(hn=>[...hn,ILe(be)]),await _t();return}throw Rt}}throw mt}y.current===Qt&&(y.current=null)},J=async({coreUserMessages:be,model:we,requestContext:Oe,threadId:ke,onNetworkChunk:Ne,modelSettings:Pe,signal:ie,tracingOptions:re})=>{const{frequencyPenalty:se,presencePenalty:de,maxRetries:xe,maxTokens:Ce,temperature:Re,topK:Me,topP:We,maxSteps:je}=Pe||{},Ee=Oe??s;v.current={model:we,requestContext:Ee},V(!0);const _e=new SP({...B.options,abortSignal:ie}).getAgent(e),Ie=wo(),$e=await _e.network(be,{model:we,maxSteps:je,modelSettings:{frequencyPenalty:se,presencePenalty:de,maxRetries:xe,maxOutputTokens:Ce,temperature:Re,topK:Me,topP:We},runId:Ie,requestContext:Ee,...ke?{memory:{thread:ke,resource:t||e}}:{},tracingOptions:re});m.current=Ne,h.current=Ie,await $e.processDataStream({onChunk:async Ve=>{E(Je=>JX({chunk:Ve,conversation:Je,metadata:{mode:"network"}})),Ne?.(Ve)}}),E(Ve=>Wb(Ve)),V(!1)};return{setMessages:E,sendMessage:async({mode:be="stream",...we})=>{const Oe=[{role:"user",content:[{type:"text",text:we.message}]}];we.coreUserMessages&&Oe.push(...we.coreUserMessages);const ke=ILe(Oe),Ne=be==="stream"&&we.threadId&&!_.current&&!d?`client-set-${wo()}`:void 0,Pe=Ne,ie=Ne;if(Pe){const re={...ke.content.metadata,mode:"stream",status:"pending",[E$]:ie},se={...ke,id:Ne,content:{...ke.content,metadata:re}};E(de=>[...de,se])}else E(re=>[...re,ke]);try{be==="generate"?await ne({...we,coreUserMessages:Oe}):be==="stream"?await ee({...we,coreUserMessages:Oe,signalId:Pe,clientMessageId:ie}):be==="network"&&await J({...we,coreUserMessages:Oe})}catch(re){throw V(!1),re}},isRunning:U,isAwaitingToolApproval:F,messages:C,tasks:T,approveToolCall:async(be,we)=>{const Oe=p.current,ke=f.current,Ne=v.current;if(!ke)return console.info("[approveToolCall] approveToolCall can only be called after a stream has started");V(!0),A(ie=>({...ie,[be]:{status:"approved"}}));const Pe=B.getAgent(e);if(S.current&&n){try{await Pe.sendToolApproval({resourceId:t||e,threadId:n,toolCallId:be,approved:!0,...Ne.model!==void 0?{streamOptions:{model:Ne.model}}:{},...we!==void 0?{resumeData:we}:{},requestContext:Ne.requestContext}),D.current.delete(be),H(D.current.size>0),V(!1)}catch(ie){throw A(re=>{const se={...re};return delete se[be],se}),V(!1),ie}return}try{await(we!==void 0?await Pe.resumeStream(we,{runId:ke,toolCallId:be,...Ne}):await Pe.approveToolCall({runId:ke,toolCallId:be,...Ne})).processDataStream({onChunk:async ie=>{await Z(ie,Oe)}}),V(!1)}catch(ie){throw A(re=>{const se={...re};return delete se[be],se}),V(!1),ie}},declineToolCall:async be=>{const we=p.current,Oe=f.current,ke=v.current;if(!Oe)return console.info("[declineToolCall] declineToolCall can only be called after a stream has started");V(!0),A(Pe=>({...Pe,[be]:{status:"declined"}}));const Ne=B.getAgent(e);if(S.current&&n){try{await Ne.sendToolApproval({resourceId:t||e,threadId:n,toolCallId:be,approved:!1,...ke.model!==void 0?{streamOptions:{model:ke.model}}:{},requestContext:ke.requestContext}),D.current.delete(be),H(D.current.size>0),V(!1)}catch(Pe){throw A(ie=>{const re={...ie};return delete re[be],re}),V(!1),Pe}return}await(await Ne.declineToolCall({runId:Oe,toolCallId:be,...ke})).processDataStream({onChunk:async Pe=>{await Z(Pe,we)}}),V(!1)},approveToolCallGenerate:async be=>{const we=f.current,Oe=v.current;if(!we)return console.info("[approveToolCallGenerate] approveToolCallGenerate can only be called after a generate has started");V(!0),A(Ne=>({...Ne,[be]:{status:"approved"}}));const ke=await B.getAgent(e).approveToolCallGenerate({runId:we,toolCallId:be,...Oe});if(ke&&"uiMessages"in ke.response&&ke.response.uiMessages){const Ne=Q5(ke.response.uiMessages,{mode:"generate"});E(Pe=>[...Pe,...Ne])}V(!1)},declineToolCallGenerate:async be=>{const we=f.current,Oe=v.current;if(!we)return console.info("[declineToolCallGenerate] declineToolCallGenerate can only be called after a generate has started");V(!0),A(Ne=>({...Ne,[be]:{status:"declined"}}));const ke=await B.getAgent(e).declineToolCallGenerate({runId:we,toolCallId:be,...Oe});if(ke&&"uiMessages"in ke.response&&ke.response.uiMessages){const Ne=Q5(ke.response.uiMessages,{mode:"generate"});E(Pe=>[...Pe,...Ne])}V(!1)},cancelRun:()=>{y.current?.abort(),y.current=null;const be=x.current;Promise.resolve(be?.abort?.()).catch(we=>{console.error("[useChat] Failed to abort thread subscription",we)}),z(),E(we=>Wb(we)),D.current.clear(),H(!1),V(!1),f.current=void 0,p.current=void 0,h.current=void 0,m.current=void 0,v.current={}},toolCallApprovals:I,approveNetworkToolCall:async(be,we)=>{const Oe=m.current,ke=we||h.current,Ne=v.current;if(!ke)return console.info("[approveNetworkToolCall] approveNetworkToolCall can only be called after a network stream has started");V(!0),L(Pe=>({...Pe,[we?`${we}-${be}`:be]:{status:"approved"}})),await(await B.getAgent(e).approveNetworkToolCall({runId:ke,...Ne})).processDataStream({onChunk:async Pe=>{E(ie=>JX({chunk:Pe,conversation:ie,metadata:{mode:"network"}})),Oe?.(Pe)}}),E(Pe=>Wb(Pe)),V(!1)},declineNetworkToolCall:async(be,we)=>{const Oe=m.current,ke=we||h.current,Ne=v.current;if(!ke)return console.info("[declineNetworkToolCall] declineNetworkToolCall can only be called after a network stream has started");V(!0),L(Pe=>({...Pe,[we?`${we}-${be}`:be]:{status:"declined"}})),await(await B.getAgent(e).declineNetworkToolCall({runId:ke,...Ne})).processDataStream({onChunk:async Pe=>{E(ie=>JX({chunk:Pe,conversation:ie,metadata:{mode:"network"}})),Oe?.(Pe)}}),E(Pe=>Wb(Pe)),V(!1)},networkToolCallApprovals:R}};function nT(e){const[t,n]=g.useState(!1),[r,s]=g.useState(!1),[a,i]=g.useState(!1),[l,c]=g.useState(null),[u,d]=g.useState(void 0),f=g.useRef(e);f.current=e;const p=g.useCallback(()=>{n(!1),s(!1),i(!1),c(null),d(void 0)},[]),h=g.useCallback(async m=>{n(!0),s(!1),i(!1),c(null);try{const v=await f.current(m);return d(v),s(!0),v}catch(v){throw c(v),i(!0),v}finally{n(!1)}},[]);return{mutate:g.useCallback(m=>{h(m).catch(()=>{})},[h]),mutateAsync:h,isPending:t,isSuccess:r,isError:a,error:l,data:u,reset:p}}function rSn({debugMode:e,tracingOptions:t,onError:n}){const r=Ze(),[s,a]=g.useState({}),[i,l]=g.useState(!1),c=g.useRef(null),u=g.useRef(null),d=g.useRef(null),f=g.useRef(null),p=g.useRef(!0);g.useEffect(()=>(p.current=!0,()=>{if(p.current=!1,c.current){try{c.current.releaseLock()}catch{}c.current=null}if(u.current){try{u.current.releaseLock()}catch{}u.current=null}if(d.current){try{d.current.releaseLock()}catch{}d.current=null}if(f.current){try{f.current.releaseLock()}catch{}f.current=null}}),[]);const h=g.useCallback((S,k,_)=>{if(S instanceof TypeError)return;const C=S instanceof Error?S:new Error(k);n?.(C,k),_?.(!1)},[n]),m=g.useCallback(S=>{if(S.type==="workflow-finish"){const k=S.payload?.workflowStatus,_=S.payload?.metadata;if(a(C=>({...C,status:k})),k==="failed")throw new Error(_?.errorMessage||"Workflow execution failed")}},[]),v=nT(async({workflowId:S,runId:k,inputData:_,initialState:C,requestContext:E,perStep:T})=>{if(c.current&&c.current.releaseLock(),!p.current)return;l(!0),a({input:_});const N=await(await r.getWorkflow(S).createRun({runId:k})).stream({inputData:_,initialState:C,requestContext:E,closeOnSuspend:!0,tracingOptions:t,perStep:T??e});if(!N)return h(new Error("No stream returned"),"No stream returned",l);const I=N.getReader();c.current=I;try{for(;p.current;){const{done:A,value:R}=await I.read();if(A)break;p.current&&(a(L=>Cw(L,R)),R.type==="workflow-step-start"&&l(!0),R.type==="workflow-step-suspended"&&l(!1),R.type==="workflow-finish"&&m(R))}}catch(A){h(A,"Error streaming workflow")}finally{p.current&&l(!1),c.current&&(c.current.releaseLock(),c.current=null)}}),y=nT(async({workflowId:S,runId:k,storeRunResult:_})=>{if(u.current&&u.current.releaseLock(),!p.current)return;if(l(!0),a(_||{}),_?.status==="suspended"){l(!1);return}const C=await(await r.getWorkflow(S).createRun({runId:k})).observeStream();if(!C)return h(new Error("No stream returned"),"No stream returned",l);const E=C.getReader();u.current=E;try{for(;p.current;){const{done:T,value:N}=await E.read();if(T)break;p.current&&(a(I=>Cw(I,N)),N.type==="workflow-step-start"&&l(!0),N.type==="workflow-step-suspended"&&l(!1),N.type==="workflow-finish"&&m(N))}}catch(T){h(T,"Error observing workflow")}finally{p.current&&l(!1),u.current&&(u.current.releaseLock(),u.current=null)}}),b=nT(async({workflowId:S,runId:k,step:_,resumeData:C,requestContext:E,perStep:T})=>{if(d.current&&d.current.releaseLock(),!p.current)return;l(!0);const N=await(await r.getWorkflow(S).createRun({runId:k})).resumeStream({step:_,resumeData:C,requestContext:E,tracingOptions:t,perStep:T??e});if(!N)return h(new Error("No stream returned"),"No stream returned",l);const I=N.getReader();d.current=I;try{for(;p.current;){const{done:A,value:R}=await I.read();if(A)break;p.current&&(a(L=>Cw(L,R)),R.type==="workflow-step-start"&&l(!0),R.type==="workflow-step-suspended"&&l(!1),R.type==="workflow-finish"&&m(R))}}catch(A){h(A,"Error resuming workflow stream")}finally{p.current&&l(!1),d.current&&(d.current.releaseLock(),d.current=null)}}),x=nT(async({workflowId:S,requestContext:k,runId:_,perStep:C,...E})=>{if(f.current&&f.current.releaseLock(),!p.current)return;l(!0);const T=await(await r.getWorkflow(S).createRun({runId:_})).timeTravelStream({...E,perStep:C??e,requestContext:k,tracingOptions:t});if(!T)return h(new Error("No stream returned"),"No stream returned",l);const N=T.getReader();f.current=N;try{for(;p.current;){const{done:I,value:A}=await N.read();if(I)break;p.current&&(a(R=>Cw(R,A)),A.type==="workflow-step-start"&&l(!0),A.type==="workflow-step-suspended"&&l(!1),A.type==="workflow-finish"&&m(A))}}catch(I){h(I,"Error time traveling workflow stream")}finally{p.current&&l(!1),f.current&&(f.current.releaseLock(),f.current=null)}});return{streamWorkflow:v,streamResult:s,isStreaming:i,observeWorkflowStream:y,closeStreamsAndReset:g.useCallback(()=>{if(l(!1),a({}),c.current){try{c.current.releaseLock()}catch{}c.current=null}if(u.current){try{u.current.releaseLock()}catch{}u.current=null}if(d.current){try{d.current.releaseLock()}catch{}d.current=null}if(f.current){try{f.current.releaseLock()}catch{}f.current=null}},[]),resumeWorkflowStream:b,timeTravelWorkflowStream:x}}function sSn(){const e=Ze();return nT(async({workflowId:t,prevRunId:n})=>{try{const{runId:r}=await e.getWorkflow(t).createRun({runId:n});return{runId:r}}catch(r){throw console.error("Error creating workflow run:",r),r}})}function aSn(){const e=Ze();return nT(async({workflowId:t,runId:n})=>{try{return(await e.getWorkflow(t).createRun({runId:n})).cancelRun()}catch(r){throw console.error("Error canceling workflow run:",r),r}})}const xh=(e,t)=>t?.(e)??null,iSn=({step:e,Step:t,MapStep:n,AgentStep:r,ToolStep:s,ForEachStep:a,ParallelStep:i,Conditional:l,LoopStep:c,SleepStep:u,SleepUntilStep:d,NestedWorkflowStep:f,UnknownStep:p})=>{switch(e.kind){case"step":return o.jsx(o.Fragment,{children:t?.(e)??xh(e,p)});case"map-step":return o.jsx(o.Fragment,{children:n?.(e)??xh(e,p)});case"agent-step":return o.jsx(o.Fragment,{children:r?.(e)??xh(e,p)});case"tool-step":return o.jsx(o.Fragment,{children:s?.(e)??xh(e,p)});case"foreach-step":return o.jsx(o.Fragment,{children:a?.(e)??xh(e,p)});case"parallel-step":return o.jsx(o.Fragment,{children:i?.(e)??xh(e,p)});case"conditional":return o.jsx(o.Fragment,{children:l?.(e)??xh(e,p)});case"loop-step":return o.jsx(o.Fragment,{children:c?.(e)??xh(e,p)});case"sleep-step":return o.jsx(o.Fragment,{children:u?.(e)??xh(e,p)});case"sleep-until-step":return o.jsx(o.Fragment,{children:d?.(e)??xh(e,p)});case"nested-workflow-step":return o.jsx(o.Fragment,{children:f?.(e)??xh(e,p)});default:return o.jsx(o.Fragment,{children:xh(e,p)})}};g.memo(iSn);async function oSn(e){const t=await navigator.mediaDevices.getUserMedia({audio:!0}),n=new MediaRecorder(t);let r=[];return n.ondataavailable=s=>{r.push(s.data)},n.onstop=()=>{const s=new Blob(r,{type:"audio/webm"}),a=new File([s],`recording-${Date.now()}.webm`,{type:"audio/webm",lastModified:Date.now()});t.getTracks().forEach(i=>i.stop()),e(a)},n}async function lSn(e,t){const n=new window.AudioContext,r=e.getReader(),s=[];try{for(;;){const{done:d,value:f}=await r.read();if(d)break;s.push(f)}const a=s.reduce((d,f)=>d+f.length,0),i=new Uint8Array(a);let l=0;for(const d of s)i.set(d,l),l+=d.length;const c=await n.decodeAudioData(i.buffer),u=n.createBufferSource();return u.buffer=c,u.onended=t??null,u.connect(n.destination),u.start(),()=>{u.onended=null,u.stop(),n.close()}}catch(a){throw await r.cancel().catch(()=>{}),await n.close().catch(()=>{}),a}finally{r.releaseLock()}}const cSn=({language:e="en-US",agentId:t,requestContext:n})=>{const r=Ze(),[s,a]=g.useState(null);g.useEffect(()=>{let c=!1;if(!t)return a(null),()=>{c=!0};const u=r.getAgent(t);return(async()=>{try{const f=await u.voice.getSpeakers(n);c||a(f.length>0?u:null)}catch{c||a(null)}})(),()=>{c=!0}},[t,r,n]);const i=uSn({language:e}),l=dSn({agent:s,language:e});return s?l:i},uSn=({language:e="en-US"})=>{const t=g.useRef(null),[n,r]=g.useState({isListening:!1,transcript:"",error:null}),s=()=>{t.current&&t.current.start()},a=()=>{t.current&&t.current.stop()};return g.useEffect(()=>{if(!("webkitSpeechRecognition"in window)&&!("SpeechRecognition"in window)){r(l=>({...l,error:"Speech Recognition not supported in this browser"}));return}const i=new(window.SpeechRecognition||window.webkitSpeechRecognition);return t.current=i,i.continuous=!0,i.lang=e,i.onstart=()=>{r(l=>({...l,isListening:!0,error:null}))},i.onresult=l=>{let c="";for(let u=l.resultIndex;u<l.results.length;u++){const d=l.results[u][0].transcript;l.results[u].isFinal&&(c+=d+" ")}r(u=>({...u,transcript:c}))},i.onerror=l=>{r(c=>({...c,error:`Error: ${l.error}`}))},i.onend=()=>r(l=>({...l,isListening:!1})),()=>{try{i.stop()}catch{}i.onstart=null,i.onresult=null,i.onerror=null,i.onend=null,t.current=null}},[e]),{...n,start:s,stop:a}},dSn=({agent:e,language:t})=>{const[n,r]=g.useState({isListening:!1,transcript:"",error:null}),s=g.useRef(null),a=g.useRef(0),i=g.useRef(!1);g.useEffect(()=>()=>{a.current+=1,i.current=!1,s.current?.stop(),s.current=null},[e]);const l=d=>f=>{!e||d!==a.current||(s.current=null,r(p=>({...p,isListening:!1})),e.voice.listen(f,{language:t}).then(p=>{d===a.current&&r(h=>({...h,transcript:p.text,error:null}))}).catch(p=>{if(d!==a.current)return;const h=p instanceof Error?p.message:"Failed to transcribe speech";r(m=>({...m,error:h}))}))};return{...n,start:()=>{if(!e||i.current||s.current)return;i.current=!0,a.current+=1;const d=a.current;oSn(l(d)).then(f=>{if(i.current=!1,d!==a.current){try{f.stop()}catch{}return}s.current=f,r(p=>({...p,isListening:!0,error:null})),f.start()}).catch(f=>{if(i.current=!1,d!==a.current)return;const p=f instanceof Error?f.message:"Failed to start speech recording";r(h=>({...h,isListening:!1,error:p}))})},stop:()=>{s.current?(s.current.stop(),s.current=null):i.current&&(a.current+=1),i.current=!1,r(d=>({...d,isListening:!1}))}}};const Fq=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,xwe=/^[\\/]{2}/;function bmt(e,t){return t+e.replace(/\\/g,"/")}const ALe="popstate";function RLe(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function fSn(e={}){function t(r,s){let a=s.state?.masked,{pathname:i,search:l,hash:c}=a||r.location;return j$("",{pathname:i,search:l,hash:c},s.state&&s.state.usr||null,s.state&&s.state.key||"default",a?{pathname:r.location.pathname,search:r.location.search,hash:r.location.hash}:void 0)}function n(r,s){return typeof s=="string"?s:my(s)}return hSn(t,n,null,e)}function ds(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function du(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function pSn(){return Math.random().toString(36).substring(2,10)}function PLe(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function j$(e,t,n=null,r,s){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?Iy(t):t,state:n,key:t&&t.key||r||pSn(),mask:s}}function my({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Iy(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function hSn(e,t,n,r={}){let{window:s=document.defaultView,v5Compat:a=!1}=r,i=s.history,l="POP",c=null,u=d();u==null&&(u=0,i.replaceState({...i.state,idx:u},""));function d(){return(i.state||{idx:null}).idx}function f(){l="POP";let y=d(),b=y==null?null:y-u;u=y,c&&c({action:l,location:v.location,delta:b})}function p(y,b){l="PUSH";let x=RLe(y)?y:j$(v.location,y,b);u=d()+1;let S=PLe(x,u),k=v.createHref(x.mask||x);try{i.pushState(S,"",k)}catch(_){if(_ instanceof DOMException&&_.name==="DataCloneError")throw _;s.location.assign(k)}a&&c&&c({action:l,location:v.location,delta:1})}function h(y,b){l="REPLACE";let x=RLe(y)?y:j$(v.location,y,b);u=d();let S=PLe(x,u),k=v.createHref(x.mask||x);i.replaceState(S,"",k),a&&c&&c({action:l,location:v.location,delta:0})}function m(y){return xmt(s,y)}let v={get action(){return l},get location(){return e(s,i)},listen(y){if(c)throw new Error("A history only accepts one active listener");return s.addEventListener(ALe,f),c=y,()=>{s.removeEventListener(ALe,f),c=null}},createHref(y){return t(s,y)},createURL:m,encodeLocation(y){let b=m(y);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:p,replace:h,go(y){return i.go(y)}};return v}function xmt(e,t,n=!1){let r="http://localhost";e&&(r=e.location.origin!=="null"?e.location.origin:e.location.href),ds(r,"No window.location.(origin|href) available to create URL");let s=typeof t=="string"?t:my(t);return s=s.replace(/ $/,"%20"),!n&&xwe.test(s)&&(s=r+s),new URL(s,r)}var $Le=class{#e=new Map;constructor(e){if(e)for(let[t,n]of e)this.set(t,n)}get(e){if(this.#e.has(e))return this.#e.get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw new Error("No value found for context")}set(e,t){this.#e.set(e,t)}};const mSn=new Set(["lazy","caseSensitive","path","id","index","children"]);function gSn(e){return mSn.has(e)}const vSn=new Set(["lazy","caseSensitive","path","id","index","middleware","children"]);function ySn(e){return vSn.has(e)}function bSn(e){return e.index===!0}function wmt(e){let t={};return e.Component&&Object.assign(t,{element:g.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:g.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:g.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}function N$(e,t=wmt,n=[],r={},s=!1){return e.map((a,i)=>{let l=[...n,String(i)],c=typeof a.id=="string"?a.id:l.join("-");if(ds(a.index!==!0||!a.children,"Cannot specify children on an index route"),ds(s||!r[c],`Found a route id collision on id "${c}". Route id's must be globally unique within Data Router usages`),bSn(a)){let u={...a,id:c};return r[c]=MLe(u,t(u)),u}else{let u={...a,id:c,children:void 0};return r[c]=MLe(u,t(u)),a.children&&(u.children=N$(a.children,t,l,r,s)),u}})}function MLe(e,t){return Object.assign(e,{...t,...typeof t.lazy=="object"&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function Smt(e,t,n="/"){return ng(e,t,n,!1)}function ng(e,t,n,r,s){let a=Ag((typeof t=="string"?Iy(t):t).pathname||"/",n);if(a==null)return null;let i=s??l8(e),l=null,c=ASn(a);for(let u=0;l==null&&u<i.length;++u)l=ISn(i[u],c,r);return l}function kmt(e,t){let{route:n,pathname:r,params:s}=e;return{id:n.id,pathname:r,params:s,loaderData:t[n.id],handle:n.handle}}function l8(e){let t=Omt(e);return xSn(t),t}function Omt(e,t=[],n=[],r="",s=!1){let a=(i,l,c=s,u)=>{let d={relativePath:u===void 0?i.path||"":u,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};if(d.relativePath.startsWith("/")){if(!d.relativePath.startsWith(r)&&c)return;ds(d.relativePath.startsWith(r),`Absolute route path "${d.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),d.relativePath=d.relativePath.slice(r.length)}let f=Jh([r,d.relativePath]),p=n.concat(d);i.children&&i.children.length>0&&(ds(i.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${f}".`),Omt(i.children,t,p,f,c)),!(i.path==null&&!i.index)&&t.push({path:f,score:jSn(f,i.index),routesMeta:p.map((h,m)=>{let[v,y]=Emt(h.relativePath,h.caseSensitive,m===p.length-1);return{...h,matcher:v,compiledParams:y}})})};return e.forEach((i,l)=>{if(i.path===""||!i.path?.includes("?"))a(i,l);else for(let c of _mt(i.path))a(i,l,!0,c)}),t}function _mt(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),a=n.replace(/\?$/,"");if(r.length===0)return s?[a,""]:[a];let i=_mt(r.join("/")),l=[];return l.push(...i.map(c=>c===""?a:[a,c].join("/"))),s&&l.push(...i),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function xSn(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:NSn(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const wSn=/^:[\w-]+$/,SSn=/^:[\w-]+/,kSn=3.5,OSn=3,_Sn=2,CSn=1,ESn=10,TSn=-2,DLe=e=>e==="*";function jSn(e,t){let n=e.split("/"),r=n.length;return n.some(DLe)&&(r+=TSn),t&&(r+=_Sn),n.filter(s=>!DLe(s)).reduce((s,a)=>s+(wSn.test(a)?OSn:SSn.test(a)?kSn:a===""?CSn:ESn),r)}function NSn(e,t){return e.length===t.length&&e.slice(0,-1).every((n,r)=>n===t[r])?e[e.length-1]-t[t.length-1]:0}function ISn(e,t,n=!1){let{routesMeta:r}=e,s={},a="/",i=[];for(let l=0;l<r.length;++l){let c=r[l],u=l===r.length-1,d=a==="/"?t:t.slice(a.length)||"/",f={path:c.relativePath,caseSensitive:c.caseSensitive,end:u},p=c.matcher&&c.compiledParams?Cmt(f,d,c.matcher,c.compiledParams):f7(f,d),h=c.route;if(!p&&u&&n&&!r[r.length-1].route.index&&(p=f7({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},d)),!p)return null;Object.assign(s,p.params),i.push({params:s,pathname:Jh([a,p.pathname]),pathnameBase:$Sn(Jh([a,p.pathnameBase])),route:h}),p.pathnameBase!=="/"&&(a=Jh([a,p.pathnameBase]))}return i}function f7(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Emt(e.path,e.caseSensitive,e.end);return Cmt(e,t,n,r)}function Cmt(e,t,n,r){let s=t.match(n);if(!s)return null;let a=s[0],i=a.replace(/(.)\/+$/,"$1"),l=s.slice(1);return{params:r.reduce((c,{paramName:u,isOptional:d},f)=>{if(u==="*"){let h=l[f]||"";i=a.slice(0,a.length-h.length).replace(/(.)\/+$/,"$1")}const p=l[f];return d&&!p?c[u]=void 0:c[u]=(p||"").replace(/%2F/g,"/"),c},{}),pathname:a,pathnameBase:i,pattern:e}}function Emt(e,t=!1,n=!0){du(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,i,l,c,u)=>{if(r.push({paramName:i,isOptional:l!=null}),l){let d=u.charAt(c+a.length);return d&&d!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(?=\/|$|\()/g,"(?:/$1)?");return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function ASn(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return du(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Ag(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function RSn({basename:e,pathname:t}){return t==="/"?e:Jh([e,t])}const wwe=e=>Fq.test(e);function PSn(e,t="/"){let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?Iy(e):e,a;return n?(n=Swe(n),n.startsWith("/")?a=LLe(n.substring(1),"/"):a=LLe(n,t)):a=t,{pathname:a,search:MSn(r),hash:DSn(s)}}function LLe(e,t){let n=jmt(t).split("/");return e.split("/").forEach(r=>{r===".."?n.length>1&&n.pop():r!=="."&&n.push(r)}),n.length>1?n.join("/"):"/"}function nJ(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function Tmt(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function zq(e){let t=Tmt(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function qD(e,t,n,r=!1){let s;typeof e=="string"?s=Iy(e):(s={...e},ds(!s.pathname||!s.pathname.includes("?"),nJ("?","pathname","search",s)),ds(!s.pathname||!s.pathname.includes("#"),nJ("#","pathname","hash",s)),ds(!s.search||!s.search.includes("#"),nJ("#","search","hash",s)));let a=e===""||s.pathname==="",i=a?"/":s.pathname,l;if(i==null)l=n;else{let f=t.length-1;if(!r&&i.startsWith("..")){let p=i.split("/");for(;p[0]==="..";)p.shift(),f-=1;s.pathname=p.join("/")}l=f>=0?t[f]:"/"}let c=PSn(s,l),u=i&&i!=="/"&&i.endsWith("/"),d=(a||i===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(u||d)&&(c.pathname+="/"),c}const Swe=e=>e.replace(/[\\/]{2,}/g,"/"),Jh=e=>Swe(e.join("/")),jmt=e=>e.replace(/\/+$/,""),$Sn=e=>jmt(e).replace(/^\/*/,"/"),MSn=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,DSn=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,aE=(e,t=302)=>{let n=t;typeof n=="number"?n={status:n}:typeof n.status>"u"&&(n.status=302);let r=new Headers(n.headers);return r.set("Location",e),new Response(null,{...n,headers:r})},LSn=["EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"];var HD=class{status;statusText;data;error;internal;constructor(e,t,n,r=!1){this.status=e,this.statusText=t||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function I$(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function ZN(e){return Jh(e.map(t=>t.route.path).filter(Boolean))||"/"}function kwe(e,t){let n=new URL(typeof e=="string"||e instanceof URL?e:e.url),r=typeof t=="string"?Iy(t):t;if(n.pathname=r.pathname||"/",r.search){let s=new URLSearchParams(r.search),a=s.getAll("index");s.delete("index");for(let l of a.filter(Boolean))s.append("index",l);let i=s.toString();n.search=i?`?${i}`:""}else n.search="";return n.hash=r.hash||"",n}const Nmt=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Imt(e,t){let n=e;if(typeof n!="string"||!Fq.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,s=!1;if(Nmt)try{let a=new URL(window.location.href),i=xwe.test(n)?new URL(bmt(n,a.protocol)):new URL(n),l=Ag(i.pathname,t);i.origin===a.origin&&l!=null?n=l+i.search+i.hash:s=!0}catch{du(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:s,to:n}}const Amt=Symbol("Uninstrumented");let o2=new WeakMap;function FSn(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(s=>s({id:t.id,index:t.index,path:t.path,instrument(a){a.lazy!=null&&n.lazy.push(a.lazy),a["lazy.loader"]!=null&&n["lazy.loader"].push(a["lazy.loader"]),a["lazy.action"]!=null&&n["lazy.action"].push(a["lazy.action"]),a["lazy.middleware"]!=null&&n["lazy.middleware"].push(a["lazy.middleware"]),a.middleware!=null&&n.middleware.push(a.middleware),a.loader!=null&&n.loader.push(a.loader),a.action!=null&&n.action.push(a.action)}}));let r={};if(typeof t.lazy=="function"&&n.lazy.length>0){let s=t.lazy;r.lazy=async(...a)=>$b(await _v(n.lazy,void 0,()=>s(...a),Mb))}if(typeof t.lazy=="object"){let s=t.lazy;if(typeof s.middleware=="function"&&n["lazy.middleware"].length>0){let a=s.middleware;r.lazy=Object.assign(r.lazy||{},{middleware:async(...i)=>$b(await _v(n["lazy.middleware"],void 0,()=>a(...i),Mb))})}if(typeof s.loader=="function"&&n["lazy.loader"].length>0){let a=s.loader;r.lazy=Object.assign(r.lazy||{},{loader:async(...i)=>$b(await _v(n["lazy.loader"],void 0,()=>a(...i),Mb))})}if(typeof s.action=="function"&&n["lazy.action"].length>0){let a=s.action;r.lazy=Object.assign(r.lazy||{},{action:async(...i)=>$b(await _v(n["lazy.action"],void 0,()=>a(...i),Mb))})}}if(typeof t.loader=="function"&&n.loader.length>0){let s=l2(t.loader),a=async(...i)=>$b(await _v(n.loader,rJ(i[0]),()=>s(...i),Mb));s.hydrate===!0&&(a.hydrate=!0),c2(a,s),r.loader=a}if(typeof t.action=="function"&&n.action.length>0){let s=l2(t.action),a=async(...i)=>$b(await _v(n.action,rJ(i[0]),()=>s(...i),Mb));c2(a,s),r.action=a}return t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(s=>{let a=l2(s),i=async(...l)=>$b(await _v(n.middleware,rJ(l[0]),()=>a(...l),Mb));return c2(i,a),i})),r}function zSn(e,t){let n={navigate:[],fetch:[]};if(t.forEach(r=>r({instrument(s){s.navigate!=null&&n.navigate.push(s.navigate),s.fetch!=null&&n.fetch.push(s.fetch)}})),n.navigate.length>0){let r=l2(e.navigate),s=async(...a)=>{let[i,l]=a,c,u={to:typeof i=="number"||typeof i=="string"?i:i?my(i):".",...BLe(e,l??{})};return $b(await _v(n.navigate,u,async()=>{if(typeof i=="number")return await r(...a);let d=FLe(e,f=>{c=f});try{return await r(...a)}finally{d()}},d=>({...Mb(d),meta:c})))};c2(s,r),e.navigate=s}if(n.fetch.length>0){let r=l2(e.fetch),s=async(...a)=>{let[i,l,c,u]=a,d;return $b(await _v(n.fetch,{href:c??".",fetcherKey:i,...BLe(e,u??{})},async()=>{let f=FLe(e,p=>{d=p});try{return await r(...a)}finally{f()}},f=>({...Mb(f),meta:d})))};c2(s,r),e.fetch=s}return e}function l2(e){return e[Amt]??e}function c2(e,t){e[Amt]=t}function FLe(e,t){return o2.set(e,t),()=>{o2.get(e)===t&&o2.delete(e)}}function zLe(e){let t=o2.get(e);return o2.delete(e),t}function $b(e){if(e.type==="error")throw e.value;return e.value}async function _v(e,t,n,r,s={result:null,innerResult:null},a=e.length-1){let i=e[a];if(i){let l,c=async()=>(l?console.error("You cannot call instrumented handlers more than once"):l=_v(e,t,n,r,s,a-1),await l,ds(s.innerResult,"Expected an inner result"),s.innerResult);try{await i(c,t)}catch(u){console.error("An instrumentation function threw an error:",u)}l||await c(),await l}else{try{s.result={type:"success",value:await n()}}catch(l){s.result={type:"error",value:l}}s.innerResult=r(s.result,t)}return s.result||(s.result={type:"error",value:new Error("No result assigned in instrumentation chain.")},s.innerResult=r(s.result,t)),s.result}function Mb(e){return e.type==="error"&&e.value instanceof Error?{status:"error",error:e.value}:{status:"success",error:void 0}}function rJ(e){let{request:t,context:n,params:r}=e;return{...e,request:BSn(t),params:{...r},context:USn(n)}}function BLe(e,t){return{currentUrl:my(e.state.location),..."formMethod"in t?{formMethod:t.formMethod}:{},..."formEncType"in t?{formEncType:t.formEncType}:{},..."formData"in t?{formData:t.formData}:{},..."body"in t?{body:t.body}:{}}}function BSn(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function USn(e){return{get:t=>e.get(t)}}const Rmt=["POST","PUT","PATCH","DELETE"],VSn=new Set(Rmt),qSn=["GET",...Rmt],HSn=new Set(qSn),Pmt=new Set([301,302,303,307,308]),WSn=new Set([307,308]),sJ={state:"idle",location:void 0,matches:void 0,historyAction:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},ZSn={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},aR={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},$mt="remix-router-transitions",Mmt=Symbol("ResetLoaderData");var GSn=class{#e;#t;#n;#r;constructor(t){this.#e=t,this.#t=l8(t)}get stableRoutes(){return this.#e}get activeRoutes(){return this.#n??this.#e}get branches(){return this.#r??this.#t}get hasHMRRoutes(){return this.#n!=null}setRoutes(t){this.#e=t,this.#t=l8(t)}setHmrRoutes(t){this.#n=t,this.#r=l8(t)}commitHmrRoutes(){this.#n&&(this.#e=this.#n,this.#t=this.#r,this.#n=void 0,this.#r=void 0)}};function QSn(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u";ds(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let r=e.hydrationRouteProperties||[],s=e.mapRouteProperties,a=s||(()=>({}));if(e.instrumentations){let Ae=e.instrumentations;a=Be=>({...s?.(Be),...FSn(Ae.map(Le=>Le.route).filter(Boolean),Be)})}let i={},l=new GSn(N$(e.routes,a,void 0,i)),c=e.basename||"/";c.startsWith("/")||(c=`/${c}`);let u=e.dataStrategy||ekn,d={...e.future},f=null,p=new Set,h=null,m=null,v=null,y=null,b=e.hydrationData!=null,x=ng(l.activeRoutes,e.history.location,c,!1,l.branches),S=!1,k=null,_,C;if(x==null&&!e.patchRoutesOnNavigation){let Ae=Nh(404,{pathname:e.history.location.pathname}),{matches:Be,route:Le}=Y5(l.activeRoutes);_=!0,C=!_,x=Be,k={[Le.id]:Ae}}else if(x&&!e.hydrationData&&ot(x,l.activeRoutes,e.history.location.pathname).active&&(x=null),x)if(x.some(Ae=>Ae.route.lazy))_=!1,C=!_;else if(!x.some(Ae=>Owe(Ae.route)))_=!0,C=!_;else{let Ae=e.hydrationData?e.hydrationData.loaderData:null,Be=e.hydrationData?e.hydrationData.errors:null,Le=x;if(Be){let et=x.findIndex(rt=>Be[rt.route.id]!==void 0);Le=Le.slice(0,et+1)}C=!1,_=!0,Le.forEach(et=>{let rt=Dmt(et.route,Ae,Be);C=C||rt.renderFallback,_=_&&!rt.shouldLoad})}else{_=!1,C=!_,x=[];let Ae=ot(null,l.activeRoutes,e.history.location.pathname);Ae.active&&Ae.matches&&(S=!0,x=Ae.matches)}let E,T={historyAction:e.history.action,location:e.history.location,matches:x,initialized:_,renderFallback:C,navigation:sJ,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||k,fetchers:new Map,blockers:new Map},N="POP",I=null,A=!1,R,L=!1,D=new Map,F=null,H=!1,B=!1,U=new Set,V=new Map,M=0,G=-1,q=new Map,$=new Set,z=new Map,Z=new Map,K=new Set,ne=new Map,ee,J=null;function ae(){if(f=e.history.listen(({action:Ae,location:Be,delta:Le})=>{if(ee){ee(),ee=void 0;return}du(ne.size===0||Le!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let et=Ot({currentLocation:T.location,nextLocation:Be,historyAction:Ae});if(et&&Le!=null){let rt=new Promise(qt=>{ee=qt});e.history.go(Le*-1),Ft(et,{state:"blocked",location:Be,proceed(){Ft(et,{state:"proceeding",proceed:void 0,reset:void 0,location:Be}),rt.then(()=>e.history.go(Le))},reset(){let qt=new Map(T.blockers);qt.set(et,aR),te({blockers:qt})}}),I?.resolve(),I=null;return}return me(Ae,Be)}),n){bkn(t,D);let Ae=()=>xkn(t,D);t.addEventListener("pagehide",Ae),F=()=>t.removeEventListener("pagehide",Ae)}return T.initialized||me("POP",T.location,{initialHydration:!0}),E}function pe(){f&&f(),F&&F(),p.clear(),R&&R.abort(),T.fetchers.forEach((Ae,Be)=>je(T.fetchers,Be)),T.blockers.forEach((Ae,Be)=>nt(Be))}function Y(Ae){if(p.add(Ae),h){let{newErrors:Be}=h;h=null,Ae(T,{deletedFetchers:[],newErrors:Be,viewTransitionOpts:void 0,flushSync:!1})}return()=>p.delete(Ae)}function te(Ae,Be={}){Ae.matches&&(Ae.matches=Ae.matches.map(rt=>{let qt=i[rt.route.id],Pt=rt.route;return Pt.element!==qt.element||Pt.errorElement!==qt.errorElement||Pt.hydrateFallbackElement!==qt.hydrateFallbackElement?{...rt,route:qt}:rt})),T={...T,...Ae};let Le=[],et=[];T.fetchers.forEach((rt,qt)=>{rt.state==="idle"&&(K.has(qt)?Le.push(qt):et.push(qt))}),K.forEach(rt=>{!T.fetchers.has(rt)&&!V.has(rt)&&Le.push(rt)}),p.size===0&&(h={newErrors:Ae.errors??null}),[...p].forEach(rt=>rt(T,{deletedFetchers:Le,newErrors:Ae.errors??null,viewTransitionOpts:Be.viewTransitionOpts,flushSync:Be.flushSync===!0})),Le.forEach(rt=>je(T.fetchers,rt)),et.forEach(rt=>T.fetchers.delete(rt))}function ue(Ae,Be,{flushSync:Le}={}){let et=T.actionData!=null&&T.navigation.formMethod!=null&&Eu(T.navigation.formMethod)&&T.navigation.state==="loading"&&Ae.state?._isRedirect!==!0,rt;Be.actionData?Object.keys(Be.actionData).length>0?rt=Be.actionData:rt=null:et?rt=T.actionData:rt=null;let qt=Be.loaderData?KLe(T.loaderData,Be.loaderData,Be.matches||[],Be.errors):T.loaderData,Pt=T.blockers;Pt.size>0&&!H&&(Pt=new Map(Pt),Pt.forEach((_n,Mn)=>Pt.set(Mn,aR)));let Dt=H?!1:Qe(Ae,Be.matches||T.matches),zt=A===!0||T.navigation.formMethod!=null&&Eu(T.navigation.formMethod)&&Ae.state?._isRedirect!==!0;l.commitHmrRoutes(),H||N==="POP"||(N==="PUSH"?e.history.push(Ae,Ae.state):N==="REPLACE"&&e.history.replace(Ae,Ae.state));let Bt;if(N==="POP"){let _n=D.get(T.location.pathname);_n&&_n.has(Ae.pathname)?Bt={currentLocation:T.location,nextLocation:Ae}:D.has(Ae.pathname)&&(Bt={currentLocation:Ae,nextLocation:T.location})}else if(L){let _n=D.get(T.location.pathname);_n?_n.add(Ae.pathname):(_n=new Set([Ae.pathname]),D.set(T.location.pathname,_n)),Bt={currentLocation:T.location,nextLocation:Ae}}te({...Be,actionData:rt,loaderData:qt,historyAction:N,location:Ae,initialized:!0,renderFallback:!1,navigation:sJ,revalidation:"idle",restoreScrollPosition:Dt,preventScrollReset:zt,blockers:Pt},{viewTransitionOpts:Bt,flushSync:Le===!0}),N="POP",A=!1,L=!1,H=!1,B=!1,I?.resolve(),I=null,J?.resolve(),J=null}async function fe(Ae,Be){if(I?.resolve(),I=null,typeof Ae=="number"){I||(I=n5e());let mr=I.promise;return e.history.go(Ae),mr}let Le=zLe(E),{path:et,submission:rt,error:qt}=ULe(!1,Nhe(T.location,T.matches,c,Ae,Be?.fromRouteId,Be?.relative),Be),Pt;Be?.mask&&(Pt={pathname:"",search:"",hash:"",...typeof Be.mask=="string"?Iy(Be.mask):{...T.location.mask,...Be.mask}});let Dt=T.location,zt=j$(Dt,et,Be&&Be.state,void 0,Pt);zt={...zt,...e.history.encodeLocation(zt)};let Bt=Be&&Be.replace!=null?Be.replace:void 0,_n="PUSH";Bt===!0?_n="REPLACE":Bt===!1||rt!=null&&Eu(rt.formMethod)&&rt.formAction===T.location.pathname+T.location.search&&(_n="REPLACE");let Mn=Be&&"preventScrollReset"in Be?Be.preventScrollReset===!0:void 0,Or=(Be&&Be.flushSync)===!0,cs=Ot({currentLocation:Dt,nextLocation:zt,historyAction:_n});if(cs){Ft(cs,{state:"blocked",location:zt,proceed(){Ft(cs,{state:"proceeding",proceed:void 0,reset:void 0,location:zt}),fe(Ae,Be)},reset(){let mr=new Map(T.blockers);mr.set(cs,aR),te({blockers:mr})}});return}await me(_n,zt,{submission:rt,pendingError:qt,preventScrollReset:Mn,replace:Be&&Be.replace,enableViewTransition:Be&&Be.viewTransition,flushSync:Or,callSiteDefaultShouldRevalidate:Be&&Be.defaultShouldRevalidate,instrumentationNavigateMetaReceiver:Le})}function ce(){J||(J=n5e()),xe(),te({revalidation:"loading"});let Ae=J.promise;return T.navigation.state==="submitting"?Ae:T.navigation.state==="idle"?(me(T.historyAction,T.location,{startUninterruptedRevalidation:!0}),Ae):(me(N||T.historyAction,T.navigation.location,{overrideNavigation:T.navigation,enableViewTransition:L===!0}),Ae)}async function me(Ae,Be,Le){R&&R.abort(),R=null,N=Ae,H=(Le&&Le.startUninterruptedRevalidation)===!0,Zt(T.location,T.matches),A=(Le&&Le.preventScrollReset)===!0,L=(Le&&Le.enableViewTransition)===!0;let et=l.activeRoutes,rt=Le?.initialHydration&&T.matches&&T.matches.length>0&&!S?T.matches:ng(et,Be,c,!1,l.branches),qt=(Le&&Le.flushSync)===!0;if(rt&&T.initialized&&!B&&ckn(T.location,Be)&&!(Le&&Le.submission&&Eu(Le.submission.formMethod))){ue(Be,{matches:rt},{flushSync:qt});return}let Pt=ot(rt,et,Be.pathname);if(Pt.active&&Pt.matches&&(rt=Pt.matches),Le?.instrumentationNavigateMetaReceiver){let ar=e5e(e.history,Be,rt);Le.instrumentationNavigateMetaReceiver(ar)}if(!rt){let{error:ar,notFoundMatches:Gs,route:Ms}=Qt(Be.pathname);ue(Be,{matches:Gs,loaderData:{},errors:{[Ms.id]:ar}},{flushSync:qt});return}let Dt=Le&&Le.overrideNavigation?{...Le.overrideNavigation,matches:rt,historyAction:Ae}:void 0;R=new AbortController;let zt=FE(e.history,Be,R.signal,Le&&Le.submission),Bt=e.getContext?await e.getContext():new $Le,_n;if(Le&&Le.pendingError)_n=[xw(rt).route.id,{type:"error",error:Le.pendingError}];else if(Le&&Le.submission&&Eu(Le.submission.formMethod)){let ar=await be(zt,Be,Le.submission,rt,Ae,Bt,Pt.active,Le&&Le.initialHydration===!0,{replace:Le.replace,flushSync:qt});if(ar.shortCircuited)return;if(ar.pendingActionResult){let[Gs,Ms]=ar.pendingActionResult;if(Sp(Ms)&&I$(Ms.error)&&Ms.error.status===404){R=null,ue(Be,{matches:ar.matches,loaderData:{},errors:{[Gs]:Ms.error}});return}}rt=ar.matches||rt,_n=ar.pendingActionResult,Dt=aJ(Be,rt,Ae,Le.submission),qt=!1,Pt.active=!1,zt=FE(e.history,zt.url,zt.signal)}let{shortCircuited:Mn,matches:Or,loaderData:cs,errors:mr,workingFetchers:hs}=await we(zt,Be,rt,Ae,Bt,Pt.active,Dt,Le&&Le.submission,Le&&Le.fetcherSubmission,Le&&Le.replace,Le&&Le.initialHydration===!0,qt,_n,Le&&Le.callSiteDefaultShouldRevalidate);Mn||(R=null,ue(Be,{matches:Or||rt,...XLe(_n),loaderData:cs,errors:mr,...hs?{fetchers:hs}:{}}))}async function be(Ae,Be,Le,et,rt,qt,Pt,Dt,zt={}){if(xe(),te({navigation:vkn(Be,et,rt,Le)},{flushSync:zt.flushSync===!0}),Pt){let Mn=await pt(et,Be.pathname,Ae.signal);if(Mn.type==="aborted")return{shortCircuited:!0};if(Mn.type==="error"){if(Mn.partialMatches.length===0){let{matches:cs,route:mr}=Y5(l.activeRoutes);return{matches:cs,pendingActionResult:[mr.id,{type:"error",error:Mn.error}]}}let Or=xw(Mn.partialMatches).route.id;return{matches:Mn.partialMatches,pendingActionResult:[Or,{type:"error",error:Mn.error}]}}else if(Mn.matches)et=Mn.matches;else{let{notFoundMatches:Or,error:cs,route:mr}=Qt(Be.pathname);return{matches:Or,pendingActionResult:[mr.id,{type:"error",error:cs}]}}}let Bt,_n=c8(et,Be);if(!_n.route.action&&!_n.route.lazy)Bt={type:"error",error:Nh(405,{method:Ae.method,pathname:Be.pathname,routeId:_n.route.id})};else{let Mn=await se(Ae,Be,PT(a,i,Ae,Be,et,_n,Dt?[]:r,qt),qt,null);if(Bt=Mn[_n.route.id],!Bt){for(let Or of et)if(Mn[Or.route.id]){Bt=Mn[Or.route.id];break}}if(Ae.signal.aborted)return{shortCircuited:!0}}if(Ak(Bt)){let Mn;return zt&&zt.replace!=null?Mn=zt.replace:Mn=GLe(Bt.response.headers.get("Location"),new URL(Ae.url),c,e.history)===T.location.pathname+T.location.search,await re(Ae,Bt,!0,{submission:Le,replace:Mn}),{shortCircuited:!0}}if(Sp(Bt)){let Mn=xw(et,_n.route.id);return(zt&&zt.replace)!==!0&&(N="PUSH"),{matches:et,pendingActionResult:[Mn.route.id,Bt,_n.route.id]}}return{matches:et,pendingActionResult:[_n.route.id,Bt]}}async function we(Ae,Be,Le,et,rt,qt,Pt,Dt,zt,Bt,_n,Mn,Or,cs){let mr=Pt||aJ(Be,Le,et,Dt),hs=Dt||zt||t5e(mr),ar=!H&&!_n;if(qt){if(ar){let Qs=Oe(Or);te({navigation:mr,...Qs!==void 0?{actionData:Qs}:{}},{flushSync:Mn})}let Qr=await pt(Le,Be.pathname,Ae.signal);if(Qr.type==="aborted")return{shortCircuited:!0};if(Qr.type==="error"){if(Qr.partialMatches.length===0){let{matches:Mi,route:Ro}=Y5(l.activeRoutes);return{matches:Mi,loaderData:{},errors:{[Ro.id]:Qr.error}}}let Qs=xw(Qr.partialMatches).route.id;return{matches:Qr.partialMatches,loaderData:{},errors:{[Qs]:Qr.error}}}else if(Qr.matches)Le=Qr.matches;else{let{error:Qs,notFoundMatches:Mi,route:Ro}=Qt(Be.pathname);return{matches:Mi,loaderData:{},errors:{[Ro.id]:Qs}}}}let Gs=l.activeRoutes,{dsMatches:Ms,revalidatingFetchers:$a}=VLe(Ae,rt,a,i,e.history,T,Le,hs,Be,_n?[]:r,_n===!0,B,U,K,z,$,Gs,c,e.patchRoutesOnNavigation!=null,l.branches,Or,cs);if(G=++M,!e.dataStrategy&&!Ms.some(Qr=>Qr.shouldLoad)&&!Ms.some(Qr=>Qr.route.middleware&&Qr.route.middleware.length>0)&&$a.length===0){let Qr=new Map(T.fetchers),Qs=$e(Qr);return ue(Be,{matches:Le,loaderData:{},errors:Or&&Sp(Or[1])?{[Or[0]]:Or[1].error}:null,...XLe(Or),...Qs?{fetchers:Qr}:{}},{flushSync:Mn}),{shortCircuited:!0}}if(ar){let Qr={};if(!qt){Qr.navigation=mr;let Qs=Oe(Or);Qs!==void 0&&(Qr.actionData=Qs)}$a.length>0&&(Qr.fetchers=ke($a)),te(Qr,{flushSync:Mn})}$a.forEach(Qr=>{_e(Qr.key),Qr.controller&&V.set(Qr.key,Qr.controller)});let na=()=>$a.forEach(Qr=>_e(Qr.key));R&&R.signal.addEventListener("abort",na);let{loaderResults:ai,fetcherResults:xl}=await de(Ms,$a,Ae,Be,rt);if(Ae.signal.aborted)return{shortCircuited:!0};R&&R.signal.removeEventListener("abort",na),$a.forEach(Qr=>V.delete(Qr.key));let uo=K5(ai);if(uo)return await re(Ae,uo.result,!0,{replace:Bt}),{shortCircuited:!0};if(uo=K5(xl),uo)return $.add(uo.key),await re(Ae,uo.result,!0,{replace:Bt}),{shortCircuited:!0};let Dc=new Map(T.fetchers),{loaderData:Zd,errors:Kf}=YLe(T,Le,ai,Or,$a,xl,Dc);_n&&T.errors&&(Kf={...T.errors,...Kf});let Xf=$e(Dc),Mm=Ve(G,Dc),ad=Xf||Mm||$a.length>0;return{matches:Le,loaderData:Zd,errors:Kf,...ad?{workingFetchers:Dc}:{}}}function Oe(Ae){if(Ae&&!Sp(Ae[1]))return{[Ae[0]]:Ae[1].data};if(T.actionData)return Object.keys(T.actionData).length===0?null:T.actionData}function ke(Ae){let Be=new Map(T.fetchers);return Ae.forEach(Le=>{let et=Be.get(Le.key),rt=iR(void 0,et?et.data:void 0);Be.set(Le.key,rt)}),Be}async function Ne(Ae,Be,Le,et){_e(Ae);let rt=(et&&et.flushSync)===!0,qt=zLe(E),Pt=l.activeRoutes,Dt=Nhe(T.location,T.matches,c,Le,Be,et?.relative),zt=ng(Pt,Dt,c,!1,l.branches),Bt=ot(zt,Pt,Dt);if(Bt.active&&Bt.matches&&(zt=Bt.matches),qt&&qt(e5e(e.history,Dt,zt)),!zt){Re(Ae,Be,Nh(404,{pathname:Dt}),{flushSync:rt});return}let{path:_n,submission:Mn,error:Or}=ULe(!0,Dt,et);if(Or){Re(Ae,Be,Or,{flushSync:rt});return}let cs=e.getContext?await e.getContext():new $Le,mr=(et&&et.preventScrollReset)===!0;if(Mn&&Eu(Mn.formMethod)){await Pe(Ae,Be,_n,zt,cs,Bt.active,rt,mr,Mn,et&&et.defaultShouldRevalidate);return}z.set(Ae,{routeId:Be,path:_n}),await ie(Ae,Be,_n,zt,cs,Bt.active,rt,mr,Mn)}async function Pe(Ae,Be,Le,et,rt,qt,Pt,Dt,zt,Bt){xe(),z.delete(Ae),Ce(Ae,ykn(zt,T.fetchers.get(Ae)),{flushSync:Pt});let _n=new AbortController,Mn=FE(e.history,Le,_n.signal,zt);if(qt){let ra=await pt(et,new URL(Mn.url).pathname,Mn.signal,Ae);if(ra.type==="aborted")return;if(ra.type==="error"){Re(Ae,Be,ra.error,{flushSync:Pt});return}else if(ra.matches)et=ra.matches;else{Re(Ae,Be,Nh(404,{pathname:Le}),{flushSync:Pt});return}}let Or=c8(et,Le);if(!Or.route.action&&!Or.route.lazy){Re(Ae,Be,Nh(405,{method:zt.formMethod,pathname:Le,routeId:Be}),{flushSync:Pt});return}V.set(Ae,_n);let cs=M,mr=PT(a,i,Mn,Le,et,Or,r,rt),hs=await se(Mn,Le,mr,rt,Ae),ar=hs[Or.route.id];if(!ar){for(let ra of mr)if(hs[ra.route.id]){ar=hs[ra.route.id];break}}if(Mn.signal.aborted){V.get(Ae)===_n&&V.delete(Ae);return}if(K.has(Ae)){if(Ak(ar)||Sp(ar)){Ce(Ae,xv(void 0));return}}else{if(Ak(ar))if(V.delete(Ae),G>cs){Ce(Ae,xv(void 0));return}else return $.add(Ae),Ce(Ae,iR(zt)),re(Mn,ar,!1,{fetcherSubmission:zt,preventScrollReset:Dt});if(Sp(ar)){Re(Ae,Be,ar.error);return}}let Gs=T.navigation.location||T.location,Ms=FE(e.history,Gs,_n.signal),$a=l.activeRoutes,na=T.navigation.state!=="idle"?ng($a,T.navigation.location,c,!1,l.branches):T.matches;ds(na,"Didn't find any matches after fetcher action");let ai=++M;q.set(Ae,ai);let{dsMatches:xl,revalidatingFetchers:uo}=VLe(Ms,rt,a,i,e.history,T,na,zt,Gs,r,!1,B,U,K,z,$,$a,c,e.patchRoutesOnNavigation!=null,l.branches,[Or.route.id,ar],Bt),Dc=iR(zt,ar.data),Zd=new Map(T.fetchers);Zd.set(Ae,Dc),uo.filter(ra=>ra.key!==Ae).forEach(ra=>{let mc=ra.key,Dm=Zd.get(mc),Qy=iR(void 0,Dm?Dm.data:void 0);Zd.set(mc,Qy),_e(mc),ra.controller&&V.set(mc,ra.controller)}),te({fetchers:Zd});let Kf=()=>uo.forEach(ra=>_e(ra.key));_n.signal.addEventListener("abort",Kf);let{loaderResults:Xf,fetcherResults:Mm}=await de(xl,uo,Ms,Gs,rt);if(_n.signal.aborted)return;_n.signal.removeEventListener("abort",Kf),q.delete(Ae),V.delete(Ae),uo.forEach(ra=>V.delete(ra.key));let ad=T.fetchers.has(Ae),Qr=ra=>{if(!ad)return ra;let mc=new Map(ra.fetchers);return mc.set(Ae,xv(ar.data)),{...ra,fetchers:mc}},Qs=K5(Xf);if(Qs)return T=Qr(T),re(Ms,Qs.result,!1,{preventScrollReset:Dt});if(Qs=K5(Mm),Qs)return $.add(Qs.key),T=Qr(T),re(Ms,Qs.result,!1,{preventScrollReset:Dt});let Mi=new Map(T.fetchers);ad&&Mi.set(Ae,xv(ar.data));let{loaderData:Ro,errors:wl}=YLe(T,na,Xf,void 0,uo,Mm,Mi);Ve(ai,Mi),T.navigation.state==="loading"&&ai>G?(ds(N,"Expected pending action"),R&&R.abort(),ue(T.navigation.location,{matches:na,loaderData:Ro,errors:wl,fetchers:Mi})):(te({errors:wl,loaderData:KLe(T.loaderData,Ro,na,wl),fetchers:Mi}),B=!1)}async function ie(Ae,Be,Le,et,rt,qt,Pt,Dt,zt){let Bt=T.fetchers.get(Ae);Ce(Ae,iR(zt,Bt?Bt.data:void 0),{flushSync:Pt});let _n=new AbortController,Mn=FE(e.history,Le,_n.signal);if(qt){let ar=await pt(et,new URL(Mn.url).pathname,Mn.signal,Ae);if(ar.type==="aborted")return;if(ar.type==="error"){Re(Ae,Be,ar.error,{flushSync:Pt});return}else if(ar.matches)et=ar.matches;else{Re(Ae,Be,Nh(404,{pathname:Le}),{flushSync:Pt});return}}let Or=c8(et,Le);V.set(Ae,_n);let cs=M,mr=await se(Mn,Le,PT(a,i,Mn,Le,et,Or,r,rt),rt,Ae),hs=mr[Or.route.id];if(!hs){for(let ar of et)if(mr[ar.route.id]){hs=mr[ar.route.id];break}}if(V.get(Ae)===_n&&V.delete(Ae),!Mn.signal.aborted){if(K.has(Ae)){Ce(Ae,xv(void 0));return}if(Ak(hs))if(G>cs){Ce(Ae,xv(void 0));return}else{$.add(Ae),await re(Mn,hs,!1,{preventScrollReset:Dt});return}if(Sp(hs)){Re(Ae,Be,hs.error);return}Ce(Ae,xv(hs.data))}}async function re(Ae,Be,Le,{submission:et,fetcherSubmission:rt,preventScrollReset:qt,replace:Pt}={}){Le||(I?.resolve(),I=null),Be.response.headers.has("X-Remix-Revalidate")&&(B=!0);let Dt=Be.response.headers.get("Location");ds(Dt,"Expected a Location header on the redirect Response"),Dt=GLe(Dt,new URL(Ae.url),c,e.history);let zt=j$(T.location,Dt,{_isRedirect:!0});if(n){let mr=!1;if(Be.response.headers.has("X-Remix-Reload-Document"))mr=!0;else if(wwe(Dt)){const hs=xmt(t,Dt,!0);mr=hs.origin!==t.location.origin||Ag(hs.pathname,c)==null}if(mr){Pt?t.location.replace(Dt):t.location.assign(Dt);return}}R=null;let Bt=Pt===!0||Be.response.headers.has("X-Remix-Replace")?"REPLACE":"PUSH",{formMethod:_n,formAction:Mn,formEncType:Or}=T.navigation;!et&&!rt&&_n&&Mn&&Or&&(et=t5e(T.navigation));let cs=et||rt;WSn.has(Be.response.status)&&cs&&Eu(cs.formMethod)?await me(Bt,zt,{submission:{...cs,formAction:Dt},preventScrollReset:qt||A,enableViewTransition:Le?L:void 0}):await me(Bt,zt,{overrideNavigation:aJ(zt,[],Bt,et),fetcherSubmission:rt,preventScrollReset:qt||A,enableViewTransition:Le?L:void 0})}async function se(Ae,Be,Le,et,rt){let qt,Pt={};try{qt=await nkn(u,Ae,Be,Le,rt,et,!1)}catch(Dt){return Le.filter(zt=>zt.shouldLoad).forEach(zt=>{Pt[zt.route.id]={type:"error",error:Dt}}),Pt}if(Ae.signal.aborted)return Pt;if(!Eu(Ae.method))for(let Dt of Le){if(qt[Dt.route.id]?.type==="error")break;!qt.hasOwnProperty(Dt.route.id)&&!T.loaderData.hasOwnProperty(Dt.route.id)&&(!T.errors||!T.errors.hasOwnProperty(Dt.route.id))&&Dt.shouldCallHandler()&&(qt[Dt.route.id]={type:"error",result:new Error(`No result returned from dataStrategy for route ${Dt.route.id}`)})}for(let[Dt,zt]of Object.entries(qt))if(pkn(zt)){let Bt=zt.result;Pt[Dt]={type:"redirect",response:ikn(Bt,Ae,Dt,Le,c)}}else Pt[Dt]=await akn(zt);return Pt}async function de(Ae,Be,Le,et,rt){let qt=se(Le,et,Ae,rt,null),Pt=Promise.all(Be.map(async Dt=>{if(Dt.matches&&Dt.match&&Dt.request&&Dt.controller){let zt=(await se(Dt.request,Dt.path,Dt.matches,rt,Dt.key))[Dt.match.route.id];return{[Dt.key]:zt}}else return Promise.resolve({[Dt.key]:{type:"error",error:Nh(404,{pathname:Dt.path})}})}));return{loaderResults:await qt,fetcherResults:(await Pt).reduce((Dt,zt)=>Object.assign(Dt,zt),{})}}function xe(){B=!0,z.forEach((Ae,Be)=>{V.has(Be)&&U.add(Be),_e(Be)})}function Ce(Ae,Be,Le={}){let et=new Map(T.fetchers);et.set(Ae,Be),te({fetchers:et},{flushSync:(Le&&Le.flushSync)===!0})}function Re(Ae,Be,Le,et={}){let rt=xw(T.matches,Be),qt=new Map(T.fetchers);je(qt,Ae),te({errors:{[rt.route.id]:Le},fetchers:qt},{flushSync:(et&&et.flushSync)===!0})}function Me(Ae){return Z.set(Ae,(Z.get(Ae)||0)+1),K.has(Ae)&&K.delete(Ae),T.fetchers.get(Ae)||ZSn}function We(Ae,Be){_e(Ae,Be?.reason),Ce(Ae,xv(null))}function je(Ae,Be){let Le=T.fetchers.get(Be);V.has(Be)&&!(Le&&Le.state==="loading"&&q.has(Be))&&_e(Be),z.delete(Be),q.delete(Be),$.delete(Be),K.delete(Be),U.delete(Be),Ae.delete(Be)}function Ee(Ae){let Be=(Z.get(Ae)||0)-1;Be<=0?(Z.delete(Ae),K.add(Ae)):Z.set(Ae,Be),te({fetchers:new Map(T.fetchers)})}function _e(Ae,Be){let Le=V.get(Ae);Le&&(Le.abort(Be),V.delete(Ae))}function Ie(Ae,Be){for(let Le of Ae){let et=Be.get(Le);ds(et,`Expected fetcher: ${Le}`);let rt=xv(et.data);Be.set(Le,rt)}}function $e(Ae){let Be=[],Le=!1;for(let et of $){let rt=Ae.get(et);ds(rt,`Expected fetcher: ${et}`),rt.state==="loading"&&($.delete(et),Be.push(et),Le=!0)}return Ie(Be,Ae),Le}function Ve(Ae,Be){let Le=[];for(let[et,rt]of q)if(rt<Ae){let qt=Be.get(et);ds(qt,`Expected fetcher: ${et}`),qt.state==="loading"&&(_e(et),q.delete(et),Le.push(et))}return Ie(Le,Be),Le.length>0}function Je(Ae,Be){let Le=T.blockers.get(Ae)||aR;return ne.get(Ae)!==Be&&ne.set(Ae,Be),Le}function nt(Ae){T.blockers.delete(Ae),ne.delete(Ae)}function Ft(Ae,Be){let Le=T.blockers.get(Ae)||aR;ds(Le.state==="unblocked"&&Be.state==="blocked"||Le.state==="blocked"&&Be.state==="blocked"||Le.state==="blocked"&&Be.state==="proceeding"||Le.state==="blocked"&&Be.state==="unblocked"||Le.state==="proceeding"&&Be.state==="unblocked",`Invalid blocker state transition: ${Le.state} -> ${Be.state}`);let et=new Map(T.blockers);et.set(Ae,Be),te({blockers:et})}function Ot({currentLocation:Ae,nextLocation:Be,historyAction:Le}){if(ne.size===0)return;ne.size>1&&du(!1,"A router only supports one blocker at a time");let et=Array.from(ne.entries()),[rt,qt]=et[et.length-1],Pt=T.blockers.get(rt);if(!(Pt&&Pt.state==="proceeding")&&qt({currentLocation:Ae,nextLocation:Be,historyAction:Le}))return rt}function Qt(Ae){let Be=Nh(404,{pathname:Ae}),Le=l.activeRoutes,{matches:et,route:rt}=Y5(Le);return{notFoundMatches:et,route:rt,error:Be}}function at(Ae,Be,Le){if(m=Ae,y=Be,v=Le||null,!b&&T.navigation===sJ){b=!0;let et=Qe(T.location,T.matches);et!=null&&te({restoreScrollPosition:et})}return()=>{m=null,y=null,v=null}}function _t(Ae,Be){return v&&v(Ae,Be.map(Le=>kmt(Le,T.loaderData)))||Ae.key}function Zt(Ae,Be){if(m&&y){let Le=_t(Ae,Be);m[Le]=y()}}function Qe(Ae,Be){if(m){let Le=_t(Ae,Be),et=m[Le];if(typeof et=="number")return et}return null}function ot(Ae,Be,Le){if(e.patchRoutesOnNavigation){let et=l.branches;if(Ae){if(Object.keys(Ae[0].params).length>0)return{active:!0,matches:ng(Be,Le,c,!0,et)}}else return{active:!0,matches:ng(Be,Le,c,!0,et)||[]}}return{active:!1,matches:null}}async function pt(Ae,Be,Le,et){if(!e.patchRoutesOnNavigation)return{type:"success",matches:Ae};let rt=Ae;for(;;){let qt=i;try{await e.patchRoutesOnNavigation({signal:Le,path:Be,matches:rt,fetcherKey:et,patch:(Bt,_n)=>{Le.aborted||qLe(Bt,_n,l,qt,a,!1)}})}catch(Bt){return{type:"error",error:Bt,partialMatches:rt}}if(Le.aborted)return{type:"aborted"};let Pt=l.branches,Dt=ng(l.activeRoutes,Be,c,!1,Pt),zt=null;if(Dt){if(Object.keys(Dt[0].params).length===0)return{type:"success",matches:Dt};if(zt=ng(l.activeRoutes,Be,c,!0,Pt),!(zt&&rt.length<zt.length&&mt(rt,zt.slice(0,rt.length))))return{type:"success",matches:Dt}}if(zt||(zt=ng(l.activeRoutes,Be,c,!0,Pt)),!zt||mt(rt,zt))return{type:"success",matches:null};rt=zt}}function mt(Ae,Be){return Ae.length===Be.length&&Ae.every((Le,et)=>Le.route.id===Be[et].route.id)}function Rt(Ae){i={},l.setHmrRoutes(N$(Ae,a,void 0,i))}function hn(Ae,Be,Le=!1){qLe(Ae,Be,l,i,a,Le),l.hasHMRRoutes||te({})}return E={get basename(){return c},get future(){return d},get state(){return T},get routes(){return l.stableRoutes},get branches(){return l.branches},get manifest(){return i},get window(){return t},initialize:ae,subscribe:Y,enableScrollRestoration:at,navigate:fe,fetch:Ne,revalidate:ce,createHref:Ae=>e.history.createHref(Ae),encodeLocation:Ae=>e.history.encodeLocation(Ae),getFetcher:Me,resetFetcher:We,deleteFetcher:Ee,dispose:pe,getBlocker:Je,deleteBlocker:nt,patchRoutes:hn,_internalFetchControllers:V,_internalSetRoutes:Rt,_internalSetStateDoNotUseOrYouWillBreakYourApp(Ae){te(Ae)}},e.instrumentations&&(E=zSn(E,e.instrumentations.map(Ae=>Ae.router).filter(Boolean))),E}function YSn(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function Nhe(e,t,n,r,s,a){let i,l;if(s){i=[];for(let u of t)if(i.push(u),u.route.id===s){l=u;break}}else i=t,l=t[t.length-1];let c=qD(r||".",zq(i),Ag(e.pathname,n)||e.pathname,a==="path");if(r==null&&(c.search=e.search,c.hash=e.hash),(r==null||r===""||r===".")&&l){let u=Cwe(c.search);if(l.route.index&&!u)c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index";else if(!l.route.index&&u){let d=new URLSearchParams(c.search),f=d.getAll("index");d.delete("index"),f.filter(h=>h).forEach(h=>d.append("index",h));let p=d.toString();c.search=p?`?${p}`:""}}return n!=="/"&&(c.pathname=RSn({basename:n,pathname:c.pathname})),my(c)}function ULe(e,t,n){if(!n||!YSn(n))return{path:t};if(n.formMethod&&!gkn(n.formMethod))return{path:t,error:Nh(405,{method:n.formMethod})};let r=()=>({path:t,error:Nh(400,{type:"invalid-body"})}),s=(n.formMethod||"get").toUpperCase(),a=Vmt(t);if(n.body!==void 0){if(n.formEncType==="text/plain"){if(!Eu(s))return r();let d=typeof n.body=="string"?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((f,[p,h])=>`${f}${p}=${h}
|
|
199
199
|
`,""):String(n.body);return{path:t,submission:{formMethod:s,formAction:a,formEncType:n.formEncType,formData:void 0,json:void 0,text:d}}}else if(n.formEncType==="application/json"){if(!Eu(s))return r();try{let d=typeof n.body=="string"?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:s,formAction:a,formEncType:n.formEncType,formData:void 0,json:d,text:void 0}}}catch{return r()}}}ds(typeof FormData=="function","FormData is not available in this environment");let i,l;if(n.formData)i=Rhe(n.formData),l=n.formData;else if(n.body instanceof FormData)i=Rhe(n.body),l=n.body;else if(n.body instanceof URLSearchParams)i=n.body,l=QLe(i);else if(n.body==null)i=new URLSearchParams,l=new FormData;else try{i=new URLSearchParams(n.body),l=QLe(i)}catch{return r()}let c={formMethod:s,formAction:a,formEncType:n&&n.formEncType||"application/x-www-form-urlencoded",formData:l,json:void 0,text:void 0};if(Eu(c.formMethod))return{path:t,submission:c};let u=Iy(t);return e&&u.search&&Cwe(u.search)&&i.append("index",""),u.search=`?${i}`,{path:my(u),submission:c}}function VLe(e,t,n,r,s,a,i,l,c,u,d,f,p,h,m,v,y,b,x,S,k,_){let C=k?Sp(k[1])?k[1].error:k[1].data:void 0,E=s.createURL(a.location),T=s.createURL(c),N;if(d&&a.errors){let H=Object.keys(a.errors)[0];N=i.findIndex(B=>B.route.id===H)}else if(k&&Sp(k[1])){let H=k[0];N=i.findIndex(B=>B.route.id===H)-1}let I=k?k[1].statusCode:void 0,A=I&&I>=400,R={currentUrl:E,currentParams:a.matches[0]?.params||{},nextUrl:T,nextParams:i[0].params,...l,actionResult:C,actionStatus:I},L=ZN(i),D=i.map((H,B)=>{let{route:U}=H,V=null;if(N!=null&&B>N)V=!1;else if(U.lazy)V=!0;else if(!Owe(U))V=!1;else if(d){let{shouldLoad:q}=Dmt(U,a.loaderData,a.errors);V=q}else KSn(a.loaderData,a.matches[B],H)&&(V=!0);if(V!==null)return Ihe(n,r,e,c,L,H,u,t,V);let M=!1;typeof _=="boolean"?M=_:A?M=!1:(f||E.pathname+E.search===T.pathname+T.search||E.search!==T.search||XSn(a.matches[B],H))&&(M=!0);let G={...R,defaultShouldRevalidate:M};return Ihe(n,r,e,c,L,H,u,t,u2(H,G),G,_)}),F=[];return m.forEach((H,B)=>{if(d||!i.some(Z=>Z.route.id===H.routeId)||h.has(B))return;let U=a.fetchers.get(B),V=U&&U.state!=="idle"&&U.data===void 0,M=ng(y,H.path,b??"/",!1,S);if(!M){if(x&&V)return;F.push({key:B,routeId:H.routeId,path:H.path,matches:null,match:null,request:null,controller:null});return}if(v.has(B))return;let G=c8(M,H.path),q=new AbortController,$=FE(s,H.path,q.signal),z=null;if(p.has(B))p.delete(B),z=PT(n,r,$,H.path,M,G,u,t);else if(V)f&&(z=PT(n,r,$,H.path,M,G,u,t));else{let Z;typeof _=="boolean"?Z=_:A?Z=!1:Z=f;let K={...R,defaultShouldRevalidate:Z};u2(G,K)&&(z=PT(n,r,$,H.path,M,G,u,t,K))}z&&F.push({key:B,routeId:H.routeId,path:H.path,matches:z,match:G,request:$,controller:q})}),{dsMatches:D,revalidatingFetchers:F}}function Owe(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function Dmt(e,t,n){if(e.lazy)return{shouldLoad:!0,renderFallback:!0};if(!Owe(e))return{shouldLoad:!1,renderFallback:!1};let r=t!=null&&e.id in t,s=n!=null&&n[e.id]!==void 0;if(!r&&s)return{shouldLoad:!1,renderFallback:!1};if(typeof e.loader=="function"&&e.loader.hydrate===!0)return{shouldLoad:!0,renderFallback:!r};let a=!r&&!s;return{shouldLoad:a,renderFallback:a}}function KSn(e,t,n){let r=!t||n.route.id!==t.route.id,s=!e.hasOwnProperty(n.route.id);return r||s}function XSn(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function u2(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}function qLe(e,t,n,r,s,a){let i;if(e){let u=r[e];ds(u,`No route found to patch children into: routeId = ${e}`),u.children||(u.children=[]),i=u.children}else i=n.activeRoutes;let l=[],c=[];if(t.forEach(u=>{let d=i.find(f=>Lmt(u,f));d?c.push({existingRoute:d,newRoute:u}):l.push(u)}),l.length>0){let u=N$(l,s,[e||"_","patch",String(i?.length||"0")],r);i.push(...u)}if(a&&c.length>0)for(let u=0;u<c.length;u++){let{existingRoute:d,newRoute:f}=c[u],p=d,[h]=N$([f],s,[],{},!0);Object.assign(p,{element:h.element?h.element:p.element,errorElement:h.errorElement?h.errorElement:p.errorElement,hydrateFallbackElement:h.hydrateFallbackElement?h.hydrateFallbackElement:p.hydrateFallbackElement})}n.hasHMRRoutes||n.setRoutes([...n.activeRoutes])}function Lmt(e,t){return"id"in e&&"id"in t&&e.id===t.id?!0:e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive?(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children?.every((n,r)=>t.children?.some(s=>Lmt(n,s)))??!1:!1}const HLe=new WeakMap,Fmt=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let s=n[t.id];if(ds(s,"No route found in manifest"),!s.lazy||typeof s.lazy!="object")return;let a=s.lazy[e];if(!a)return;let i=HLe.get(s);i||(i={},HLe.set(s,i));let l=i[e];if(l)return l;let c=(async()=>{let u=gSn(e),d=s[e]!==void 0;if(u)du(!u,"Route property "+e+" is not a supported lazy route property. This property will be ignored."),i[e]=Promise.resolve();else if(d)du(!1,`Route "${s.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let f=await a();f!=null&&(Object.assign(s,{[e]:f}),Object.assign(s,r(s)))}typeof s.lazy=="object"&&(s.lazy[e]=void 0,Object.values(s.lazy).every(f=>f===void 0)&&(s.lazy=void 0))})();return i[e]=c,c},WLe=new WeakMap;function JSn(e,t,n,r,s){let a=n[e.id];if(ds(a,"No route found in manifest"),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy=="function"){let d=WLe.get(a);if(d)return{lazyRoutePromise:d,lazyHandlerPromise:d};let f=(async()=>{ds(typeof e.lazy=="function","No lazy route function found");let p=await e.lazy(),h={};for(let m in p){let v=p[m];if(v===void 0)continue;let y=ySn(m),b=a[m]!==void 0;y?du(!y,"Route property "+m+" is not a supported property to be returned from a lazy route function. This property will be ignored."):b?du(!b,`Route "${a.id}" has a static property "${m}" defined but its lazy function is also returning a value for this property. The lazy route property "${m}" will be ignored.`):h[m]=v}Object.assign(a,h),Object.assign(a,{...r(a),lazy:void 0})})();return WLe.set(a,f),f.catch(()=>{}),{lazyRoutePromise:f,lazyHandlerPromise:f}}let i=Object.keys(e.lazy),l=[],c;for(let d of i){if(s&&s.includes(d))continue;let f=Fmt({key:d,route:e,manifest:n,mapRouteProperties:r});f&&(l.push(f),d===t&&(c=f))}let u=l.length>0?Promise.all(l).then(()=>{}):void 0;return u?.catch(()=>{}),c?.catch(()=>{}),{lazyRoutePromise:u,lazyHandlerPromise:c}}async function ZLe(e){let t=e.matches.filter(r=>r.shouldLoad),n={};return(await Promise.all(t.map(r=>r.resolve()))).forEach((r,s)=>{n[t[s].route.id]=r}),n}async function ekn(e){return e.matches.some(t=>t.route.middleware)?zmt(e,()=>ZLe(e)):ZLe(e)}function zmt(e,t){return tkn(e,t,r=>{if(mkn(r))throw r;return r},dkn,n);async function n(r,s,a){if(a)return Object.assign(a.value,{[s]:{type:"error",result:r}});{let{matches:i}=e,l=Math.min(Math.max(i.findIndex(u=>u.route.id===s),0),Math.max(i.findIndex(u=>u.shouldCallHandler()),0)),c=i[l].route.id;for(let u of i.slice(0,l+1))try{await u._lazyPromises?.route}catch{c=u.route.id;break}return{[xw(i,c).route.id]:{type:"error",result:r}}}}}async function tkn(e,t,n,r,s){let{matches:a,...i}=e;return await Bmt(i,a.flatMap(l=>l.route.middleware?l.route.middleware.map(c=>[l.route.id,c]):[]),t,n,r,s)}async function Bmt(e,t,n,r,s,a,i=0){let{request:l}=e;if(l.signal.aborted)throw l.signal.reason??new Error(`Request aborted: ${l.method} ${l.url}`);let c=t[i];if(!c)return await n();let[u,d]=c,f,p=async()=>{if(f)throw new Error("You may only call `next()` once per middleware");try{return f={value:await Bmt(e,t,n,r,s,a,i+1)},f.value}catch(h){return f={value:await a(h,u,f)},f.value}};try{let h=await d(e,p),m=h!=null?r(h):void 0;return s(m)?m:f?m??f.value:(f={value:await p()},f.value)}catch(h){return await a(h,u,f)}}function Umt(e,t,n,r,s){let a=Fmt({key:"middleware",route:r.route,manifest:t,mapRouteProperties:e}),i=JSn(r.route,Eu(n.method)?"action":"loader",t,e,s);return{middleware:a,route:i.lazyRoutePromise,handler:i.lazyHandlerPromise}}function Ihe(e,t,n,r,s,a,i,l,c,u=null,d){let f=!1,p=Umt(e,t,n,a,i);return{...a,_lazyPromises:p,shouldLoad:c,shouldRevalidateArgs:u,shouldCallHandler(h){return f=!0,u?typeof d=="boolean"?u2(a,{...u,defaultShouldRevalidate:d}):typeof h=="boolean"?u2(a,{...u,defaultShouldRevalidate:h}):u2(a,u):c},resolve(h){let{lazy:m,loader:v,middleware:y}=a.route,b=f||c||h&&!Eu(n.method)&&(m||v),x=y&&y.length>0&&!v&&!m;return b&&(Eu(n.method)||!x)?rkn({request:n,path:r,pattern:s,match:a,lazyHandlerPromise:p?.handler,lazyRoutePromise:p?.route,handlerOverride:h,scopedContext:l}):Promise.resolve({type:"data",result:void 0})}}}function PT(e,t,n,r,s,a,i,l,c=null){return s.map(u=>u.route.id!==a.route.id?{...u,shouldLoad:!1,shouldRevalidateArgs:c,shouldCallHandler:()=>!1,_lazyPromises:Umt(e,t,n,u,i),resolve:()=>Promise.resolve({type:"data",result:void 0})}:Ihe(e,t,n,r,ZN(s),u,i,l,!0,c))}async function nkn(e,t,n,r,s,a,i){r.some(d=>d._lazyPromises?.middleware)&&await Promise.all(r.map(d=>d._lazyPromises?.middleware));let l={request:t,url:kwe(t,n),pattern:ZN(r),params:r[0].params,context:a,matches:r},u=await e({...l,fetcherKey:s,runClientMiddleware:d=>{let f=l;return zmt(f,()=>d({...f,fetcherKey:s,runClientMiddleware:()=>{throw new Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))}});try{await Promise.all(r.flatMap(d=>[d._lazyPromises?.handler,d._lazyPromises?.route]))}catch{}return u}async function rkn({request:e,path:t,pattern:n,match:r,lazyHandlerPromise:s,lazyRoutePromise:a,handlerOverride:i,scopedContext:l}){let c,u,d=Eu(e.method),f=d?"action":"loader",p=h=>{let m,v=new Promise((x,S)=>m=S);u=()=>m(),e.signal.addEventListener("abort",u);let y=x=>typeof h!="function"?Promise.reject(new Error(`You cannot call the handler for a route which defines a boolean "${f}" [routeId: ${r.route.id}]`)):h({request:e,url:kwe(e,t),pattern:n,params:r.params,context:l},...x!==void 0?[x]:[]),b=(async()=>{try{return{type:"data",result:await(i?i(x=>y(x)):y())}}catch(x){return{type:"error",result:x}}})();return Promise.race([b,v])};try{let h=d?r.route.action:r.route.loader;if(s||a)if(h){let m,[v]=await Promise.all([p(h).catch(y=>{m=y}),s,a]);if(m!==void 0)throw m;c=v}else{await s;let m=d?r.route.action:r.route.loader;if(m)[c]=await Promise.all([p(m),a]);else if(f==="action"){let v=new URL(e.url),y=v.pathname+v.search;throw Nh(405,{method:e.method,pathname:y,routeId:r.route.id})}else return{type:"data",result:void 0}}else if(h)c=await p(h);else{let m=new URL(e.url);throw Nh(404,{pathname:m.pathname+m.search})}}catch(h){return{type:"error",result:h}}finally{u&&e.signal.removeEventListener("abort",u)}return c}async function skn(e){let t=e.headers.get("Content-Type");return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function akn(e){let{result:t,type:n}=e;if(_we(t)){let r;try{r=await skn(t)}catch(s){return{type:"error",error:s}}return n==="error"?{type:"error",error:new HD(t.status,t.statusText,r),statusCode:t.status,headers:t.headers}:{type:"data",data:r,statusCode:t.status,headers:t.headers}}return n==="error"?JLe(t)?t.data instanceof Error?{type:"error",error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"error",error:ukn(t),statusCode:I$(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"error",error:t,statusCode:I$(t)?t.status:void 0}:JLe(t)?{type:"data",data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"data",data:t}}function ikn(e,t,n,r,s){let a=e.headers.get("Location");if(ds(a,"Redirects returned/thrown from loaders/actions must have a Location header"),!wwe(a)){let i=r.slice(0,r.findIndex(l=>l.route.id===n)+1);a=Nhe(new URL(t.url),i,s,a),e.headers.set("Location",a)}return e}const okn=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function Ahe(e){try{return okn.includes(new URL(e).protocol)}catch{return!1}}function GLe(e,t,n,r){if(wwe(e)){let s=e,a=xwe.test(s)?new URL(bmt(s,t.protocol)):new URL(s);if(Ahe(a.toString()))throw new Error("Invalid redirect location");let i=Ag(a.pathname,n)!=null;if(a.origin===t.origin&&i)return Swe(a.pathname)+a.search+a.hash}try{if(Ahe(r.createURL(e).toString()))throw new Error("Invalid redirect location")}catch{}return e}function FE(e,t,n,r){let s=e.createURL(Vmt(t)).toString(),a={signal:n};if(r&&Eu(r.formMethod)){let{formMethod:i,formEncType:l}=r;a.method=i.toUpperCase(),l==="application/json"?(a.headers=new Headers({"Content-Type":l}),a.body=JSON.stringify(r.json)):l==="text/plain"?a.body=r.text:l==="application/x-www-form-urlencoded"&&r.formData?a.body=Rhe(r.formData):a.body=r.formData}return new Request(s,a)}function Rhe(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function QLe(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function lkn(e,t,n,r=!1,s=!1){let a={},i=null,l,c=!1,u={},d=n&&Sp(n[1])?n[1].error:void 0;return e.forEach(f=>{if(!(f.route.id in t))return;let p=f.route.id,h=t[p];if(ds(!Ak(h),"Cannot handle redirect results in processLoaderData"),Sp(h)){let m=h.error;if(d!==void 0&&(m=d,d=void 0),i=i||{},s)i[p]=m;else{let v=xw(e,p);i[v.route.id]==null&&(i[v.route.id]=m)}r||(a[p]=Mmt),c||(c=!0,l=I$(h.error)?h.error.status:500),h.headers&&(u[p]=h.headers)}else a[p]=h.data,h.statusCode&&h.statusCode!==200&&!c&&(l=h.statusCode),h.headers&&(u[p]=h.headers)}),d!==void 0&&n&&(i={[n[0]]:d},n[2]&&(a[n[2]]=void 0)),{loaderData:a,errors:i,statusCode:l||200,loaderHeaders:u}}function YLe(e,t,n,r,s,a,i){let{loaderData:l,errors:c}=lkn(t,n,r);return s.filter(u=>!u.matches||u.matches.some(d=>d.shouldLoad)).forEach(u=>{let{key:d,match:f,controller:p}=u;if(p&&p.signal.aborted)return;let h=a[d];if(ds(h,"Did not find corresponding fetcher result"),Sp(h)){let m=xw(e.matches,f?.route.id);c&&c[m.route.id]||(c={...c,[m.route.id]:h.error}),i.delete(d)}else if(Ak(h))ds(!1,"Unhandled fetcher revalidation redirect");else{let m=xv(h.data);i.set(d,m)}}),{loaderData:l,errors:c}}function KLe(e,t,n,r){let s=Object.entries(t).filter(([,a])=>a!==Mmt).reduce((a,[i,l])=>(a[i]=l,a),{});for(let a of n){let i=a.route.id;if(!t.hasOwnProperty(i)&&e.hasOwnProperty(i)&&a.route.loader&&(s[i]=e[i]),r&&r.hasOwnProperty(i))break}return s}function XLe(e){return e?Sp(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function xw(e,t){return(t?e.slice(0,e.findIndex(n=>n.route.id===t)+1):[...e]).reverse().find(n=>n.route.ErrorBoundary!=null||n.route.errorElement!=null)||e[0]}function Y5(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Nh(e,{pathname:t,routeId:n,method:r,type:s,message:a}={}){let i="Unknown Server Error",l="Unknown @remix-run/router error";return e===400?(i="Bad Request",r&&t&&n?l=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:s==="invalid-body"&&(l="Unable to encode submission body")):e===403?(i="Forbidden",l=`Route "${n}" does not match URL "${t}"`):e===404?(i="Not Found",l=`No route matches URL "${t}"`):e===405&&(i="Method Not Allowed",r&&t&&n?l=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(l=`Invalid request method "${r.toUpperCase()}"`)),new HD(e||500,i,new Error(l),!0)}function K5(e){let t=Object.entries(e);for(let n=t.length-1;n>=0;n--){let[r,s]=t[n];if(Ak(s))return{key:r,result:s}}}function Vmt(e){return my({...typeof e=="string"?Iy(e):e,hash:""})}function ckn(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function ukn(e){return new HD(e.init?.status??500,e.init?.statusText??"Internal Server Error",e.data)}function dkn(e){return e!=null&&typeof e=="object"&&Object.entries(e).every(([t,n])=>typeof t=="string"&&fkn(n))}function fkn(e){return e!=null&&typeof e=="object"&&"type"in e&&"result"in e&&(e.type==="data"||e.type==="error")}function pkn(e){return _we(e.result)&&Pmt.has(e.result.status)}function Sp(e){return e.type==="error"}function Ak(e){return(e&&e.type)==="redirect"}function JLe(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function _we(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function hkn(e){return Pmt.has(e)}function mkn(e){return _we(e)&&hkn(e.status)&&e.headers.has("Location")}function gkn(e){return HSn.has(e.toUpperCase())}function Eu(e){return VSn.has(e.toUpperCase())}function Cwe(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function c8(e,t){let n=typeof t=="string"?Iy(t).search:t.search;if(e[e.length-1].route.index&&Cwe(n||""))return e[e.length-1];let r=Tmt(e);return r[r.length-1]}function e5e(e,t,n){return{url:kwe(e.createURL(t),t),pattern:n?ZN(n):"",params:n?.[0]?.params?{...n[0].params}:{}}}function t5e(e){let{formMethod:t,formAction:n,formEncType:r,text:s,formData:a,json:i}=e;if(!(!t||!n||!r)){if(s!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:s};if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:a,json:void 0,text:void 0};if(i!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:i,text:void 0}}}function aJ(e,t,n,r){return r?{state:"loading",location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}:{state:"loading",location:e,matches:t,historyAction:n,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function vkn(e,t,n,r){return{state:"submitting",location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}}function iR(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function ykn(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function xv(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function bkn(e,t){try{let n=e.sessionStorage.getItem($mt);if(n){let r=JSON.parse(n);for(let[s,a]of Object.entries(r||{}))a&&Array.isArray(a)&&t.set(s,new Set(a||[]))}}catch{}}function xkn(e,t){if(t.size>0){let n={};for(let[r,s]of t)n[r]=[...s];try{e.sessionStorage.setItem($mt,JSON.stringify(n))}catch(r){du(!1,`Failed to save applied view transitions in sessionStorage (${r}).`)}}}function n5e(){let e,t,n=new Promise((r,s)=>{e=async a=>{r(a);try{await n}catch{}},t=async a=>{s(a);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}const A_=g.createContext(null);A_.displayName="DataRouter";const WD=g.createContext(null);WD.displayName="DataRouterState";const qmt=g.createContext(!1);function Hmt(){return g.useContext(qmt)}const Ewe=g.createContext({isTransitioning:!1});Ewe.displayName="ViewTransition";const Wmt=g.createContext(new Map);Wmt.displayName="Fetchers";const wkn=g.createContext(null);wkn.displayName="Await";const Sm=g.createContext(null);Sm.displayName="Navigation";const Bq=g.createContext(null);Bq.displayName="Location";const km=g.createContext({outlet:null,matches:[],isDataRoute:!1});km.displayName="Route";const Twe=g.createContext(null);Twe.displayName="RouteError";const Zmt="REACT_ROUTER_ERROR",Skn="REDIRECT",kkn="ROUTE_ERROR_RESPONSE";function Okn(e){if(e.startsWith(`${Zmt}:${Skn}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.location=="string"&&typeof t.reloadDocument=="boolean"&&typeof t.replace=="boolean")return t}catch{}}function _kn(e){if(e.startsWith(`${Zmt}:${kkn}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new HD(t.status,t.statusText,t.data)}catch{}}function Ckn(e,{relative:t}={}){ds(GN(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=g.useContext(Sm),{hash:s,pathname:a,search:i}=ZD(e,{relative:t}),l=a;return n!=="/"&&(l=a==="/"?n:Jh([n,a])),r.createHref({pathname:l,search:i,hash:s})}function GN(){return g.useContext(Bq)!=null}function Ho(){return ds(GN(),"useLocation() may be used only in the context of a <Router> component."),g.useContext(Bq).location}const Gmt="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function Ws(){let{isDataRoute:e}=g.useContext(km);return e?Ukn():Ekn()}function Ekn(){ds(GN(),"useNavigate() may be used only in the context of a <Router> component.");let e=g.useContext(A_),{basename:t,navigator:n}=g.useContext(Sm),{matches:r}=g.useContext(km),{pathname:s}=Ho(),a=JSON.stringify(zq(r)),i=g.useRef(!1);return g.useLayoutEffect(()=>{i.current=!0}),g.useCallback((l,c={})=>{if(du(i.current,Gmt),!i.current)return;if(typeof l=="number"){n.go(l);return}let u=qD(l,JSON.parse(a),s,c.relative==="path");e==null&&t!=="/"&&(u.pathname=u.pathname==="/"?t:Jh([t,u.pathname])),(c.replace?n.replace:n.push)(u,c.state,c)},[t,n,a,s,e])}const Tkn=g.createContext(null);function jkn(e){let t=g.useContext(km).outlet;return g.useMemo(()=>t&&g.createElement(Tkn.Provider,{value:e},t),[t,e])}function Sr(){let{matches:e}=g.useContext(km);return e[e.length-1]?.params??{}}function ZD(e,{relative:t}={}){let{matches:n}=g.useContext(km),{pathname:r}=Ho(),s=JSON.stringify(zq(n));return g.useMemo(()=>qD(e,JSON.parse(s),r,t==="path"),[e,s,r,t])}function Nkn(e,t,n){ds(GN(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:r}=g.useContext(Sm),{matches:s}=g.useContext(km),a=s[s.length-1],i=a?a.params:{};a&&a.pathname;let l=a?a.pathnameBase:"/";a&&a.route;let c=Ho(),u;u=c;let d=u.pathname||"/",f=d;if(l!=="/"){let m=l.replace(/^\//,"").split("/");f="/"+d.replace(/^\//,"").split("/").slice(m.length).join("/")}let p=n&&n.state.matches.length?n.state.matches.map(m=>Object.assign(m,{route:n.manifest[m.route.id]||m.route})):Smt(e,{pathname:f});return Mkn(p&&p.map(m=>Object.assign({},m,{params:Object.assign({},i,m.params),pathname:Jh([l,r.encodeLocation?r.encodeLocation(m.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:m.pathname]),pathnameBase:m.pathnameBase==="/"?l:Jh([l,r.encodeLocation?r.encodeLocation(m.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:m.pathnameBase])})),s,n)}function Ikn(){let e=Bkn(),t=I$(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null;return g.createElement(g.Fragment,null,g.createElement("h2",null,"Unexpected Application Error!"),g.createElement("h3",{style:{fontStyle:"italic"}},t),n?g.createElement("pre",{style:{padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"}},n):null,null)}const Akn=g.createElement(Ikn,null);var Rkn=class extends g.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static contextType=qmt;static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=_kn(e.digest);n&&(e=n)}let t=e!==void 0?g.createElement(km.Provider,{value:this.props.routeContext},g.createElement(Twe.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?g.createElement(Pkn,{error:e},t):t}};const iJ=new WeakMap;function Pkn({children:e,error:t}){let{basename:n}=g.useContext(Sm);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=Okn(t.digest);if(r){let s=iJ.get(t);if(s)throw s;let a=Imt(r.location,n),i=a.absoluteURL||a.to;if(Ahe(i))throw new Error("Invalid redirect location");if(Nmt&&!iJ.get(t))if(a.isExternal||r.reloadDocument)window.location.href=i;else{const l=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:r.replace}));throw iJ.set(t,l),l}return g.createElement("meta",{httpEquiv:"refresh",content:`0;url=${i}`})}}return e}function $kn({routeContext:e,match:t,children:n}){let r=g.useContext(A_);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),g.createElement(km.Provider,{value:e},n)}function Mkn(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let s=e,a=r?.errors;if(a!=null){let d=s.findIndex(f=>f.route.id&&a?.[f.route.id]!==void 0);ds(d>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(",")}`),s=s.slice(0,Math.min(s.length,d+1))}let i=!1,l=-1;if(n&&r){i=r.renderFallback;for(let d=0;d<s.length;d++){let f=s[d];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(l=d),f.route.id){let{loaderData:p,errors:h}=r,m=f.route.loader&&!p.hasOwnProperty(f.route.id)&&(!h||h[f.route.id]===void 0);if(f.route.lazy||m){n.isStatic&&(i=!0),l>=0?s=s.slice(0,l+1):s=[s[0]];break}}}}let c=n?.onError,u=r&&c?(d,f)=>{c(d,{location:r.location,params:r.matches?.[0]?.params??{},pattern:ZN(r.matches),errorInfo:f})}:void 0;return s.reduceRight((d,f,p)=>{let h,m=!1,v=null,y=null;r&&(h=a&&f.route.id?a[f.route.id]:void 0,v=f.route.errorElement||Akn,i&&(l<0&&p===0?(Vkn("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),m=!0,y=null):l===p&&(m=!0,y=f.route.hydrateFallbackElement||null)));let b=t.concat(s.slice(0,p+1)),x=()=>{let S;return h?S=v:m?S=y:f.route.Component?S=g.createElement(f.route.Component,null):f.route.element?S=f.route.element:S=d,g.createElement($kn,{match:f,routeContext:{outlet:d,matches:b,isDataRoute:r!=null},children:S})};return r&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?g.createElement(Rkn,{location:r.location,revalidation:r.revalidation,component:v,error:h,children:x(),routeContext:{outlet:null,matches:b,isDataRoute:!0},onError:u}):x()},null)}function jwe(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Dkn(e){let t=g.useContext(A_);return ds(t,jwe(e)),t}function Qmt(e){let t=g.useContext(WD);return ds(t,jwe(e)),t}function Lkn(e){let t=g.useContext(km);return ds(t,jwe(e)),t}function Nwe(e){let t=Lkn(e),n=t.matches[t.matches.length-1];return ds(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Fkn(){return Nwe("useRouteId")}function zkn(){let{matches:e,loaderData:t}=Qmt("useMatches");return g.useMemo(()=>e.map(n=>kmt(n,t)),[e,t])}function Bkn(){let e=g.useContext(Twe),t=Qmt("useRouteError"),n=Nwe("useRouteError");return e!==void 0?e:t.errors?.[n]}function Ukn(){let{router:e}=Dkn("useNavigate"),t=Nwe("useNavigate"),n=g.useRef(!1);return g.useLayoutEffect(()=>{n.current=!0}),g.useCallback(async(r,s={})=>{du(n.current,Gmt),n.current&&(typeof r=="number"?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...s}))},[e,t])}const r5e={};function Vkn(e,t,n){r5e[e]||(r5e[e]=!0,du(!1,n))}const s5e={};function a5e(e,t){!e&&!s5e[t]&&(s5e[t]=!0,console.warn(t))}const qkn=["HydrateFallback","hydrateFallbackElement"];var Hkn=class{status="pending";promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=n=>{this.status==="pending"&&(this.status="resolved",e(n))},this.reject=n=>{this.status==="pending"&&(this.status="rejected",t(n))}})}};function Wkn({router:e,flushSync:t,onError:n,useTransitions:r}){r=Hmt()||r;let[s,a]=g.useState(e.state),[i,l]=g.useOptimistic(s),[c,u]=g.useState(),[d,f]=g.useState({isTransitioning:!1}),[p,h]=g.useState(),[m,v]=g.useState(),[y,b]=g.useState(),x=g.useRef(new Map),S=g.useCallback((E,{deletedFetchers:T,newErrors:N,flushSync:I,viewTransitionOpts:A})=>{N&&n&&Object.values(N).forEach(L=>n(L,{location:E.location,params:E.matches[0]?.params??{},pattern:ZN(E.matches)})),E.fetchers.forEach((L,D)=>{L.data!==void 0&&x.current.set(D,L.data)}),T.forEach(L=>x.current.delete(L)),a5e(I===!1||t!=null,'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.');let R=e.window!=null&&e.window.document!=null&&typeof e.window.document.startViewTransition=="function";if(a5e(A==null||R,"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."),!A||!R){t&&I?t(()=>a(E)):r===!1?a(E):g.startTransition(()=>{r===!0&&l(L=>i5e(L,E)),a(E)});return}if(t&&I){t(()=>{m&&(p?.resolve(),m.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:A.currentLocation,nextLocation:A.nextLocation})});let L=e.window.document.startViewTransition(()=>{t(()=>a(E))});L.finished.finally(()=>{t(()=>{h(void 0),v(void 0),u(void 0),f({isTransitioning:!1})})}),t(()=>v(L));return}m?(p?.resolve(),m.skipTransition(),b({state:E,currentLocation:A.currentLocation,nextLocation:A.nextLocation})):(u(E),f({isTransitioning:!0,flushSync:!1,currentLocation:A.currentLocation,nextLocation:A.nextLocation}))},[e.window,t,m,p,r,l,n]);g.useLayoutEffect(()=>e.subscribe(S),[e,S]),g.useEffect(()=>{d.isTransitioning&&!d.flushSync&&h(new Hkn)},[d]),g.useEffect(()=>{if(p&&c&&e.window){let E=c,T=p.promise,N=e.window.document.startViewTransition(async()=>{r===!1?a(E):g.startTransition(()=>{r===!0&&l(I=>i5e(I,E)),a(E)}),await T});N.finished.finally(()=>{h(void 0),v(void 0),u(void 0),f({isTransitioning:!1})}),v(N)}},[c,p,e.window,r,l]),g.useEffect(()=>{p&&c&&i.location.key===c.location.key&&p.resolve()},[p,m,i.location,c]),g.useEffect(()=>{!d.isTransitioning&&y&&(u(y.state),f({isTransitioning:!0,flushSync:!1,currentLocation:y.currentLocation,nextLocation:y.nextLocation}),b(void 0))},[d.isTransitioning,y]);let k=g.useMemo(()=>({createHref:e.createHref,encodeLocation:e.encodeLocation,go:E=>e.navigate(E),push:(E,T,N)=>e.navigate(E,{state:T,preventScrollReset:N?.preventScrollReset}),replace:(E,T,N)=>e.navigate(E,{replace:!0,state:T,preventScrollReset:N?.preventScrollReset})}),[e]),_=e.basename||"/",C=g.useMemo(()=>({router:e,navigator:k,static:!1,basename:_,onError:n}),[e,k,_,n]);return g.createElement(g.Fragment,null,g.createElement(A_.Provider,{value:C},g.createElement(WD.Provider,{value:i},g.createElement(Wmt.Provider,{value:x.current},g.createElement(Ewe.Provider,{value:d},g.createElement(Qkn,{basename:_,location:i.location,navigationType:i.historyAction,navigator:k,useTransitions:r},g.createElement(Zkn,{routes:e.routes,manifest:e.manifest,future:e.future,state:i,isStatic:!1,onError:n})))))),null)}function i5e(e,t){return{...e,navigation:t.navigation.state!=="idle"?t.navigation:e.navigation,revalidation:t.revalidation!=="idle"?t.revalidation:e.revalidation,actionData:t.navigation.state!=="submitting"?t.actionData:e.actionData,fetchers:t.fetchers}}const Zkn=g.memo(Gkn);function Gkn({routes:e,manifest:t,future:n,state:r,isStatic:s,onError:a}){return Nkn(e,void 0,{manifest:t,state:r,isStatic:s,onError:a})}function Zu({to:e,replace:t,state:n,relative:r}){ds(GN(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=g.useContext(Sm);du(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:a}=g.useContext(km),{pathname:i}=Ho(),l=Ws(),c=qD(e,zq(a),i,r==="path"),u=JSON.stringify(c);return g.useEffect(()=>{l(JSON.parse(u),{replace:t,state:n,relative:r})},[l,u,r,t,n]),null}function Ox(e){return jkn(e.context)}function Qkn({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:s,static:a=!1,useTransitions:i}){ds(!GN(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),c=g.useMemo(()=>({basename:l,navigator:s,static:a,useTransitions:i,future:{}}),[l,s,a,i]);typeof n=="string"&&(n=Iy(n));let{pathname:u="/",search:d="",hash:f="",state:p=null,key:h="default",mask:m}=n,v=g.useMemo(()=>{let y=Ag(u,l);return y==null?null:{location:{pathname:y,search:d,hash:f,state:p,key:h,mask:m},navigationType:r}},[l,u,d,f,p,h,r,m]);return du(v!=null,`<Router basename="${l}"> is not able to match the URL "${u}${d}${f}" because it does not start with the basename, so the <Router> won't render anything.`),v==null?null:g.createElement(Sm.Provider,{value:c},g.createElement(Bq.Provider,{children:t,value:v}))}const u8="application/x-www-form-urlencoded";function Uq(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function Ykn(e){return Uq(e)&&e.tagName.toLowerCase()==="button"}function Kkn(e){return Uq(e)&&e.tagName.toLowerCase()==="form"}function Xkn(e){return Uq(e)&&e.tagName.toLowerCase()==="input"}function Jkn(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function eOn(e,t){return e.button===0&&(!t||t==="_self")&&!Jkn(e)}function Phe(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(s=>[n,s]):[[n,r]])},[]))}function tOn(e,t){let n=Phe(e);return t&&t.forEach((r,s)=>{n.has(s)||t.getAll(s).forEach(a=>{n.append(s,a)})}),n}let X5=null;function nOn(){if(X5===null)try{new FormData(document.createElement("form"),0),X5=!1}catch{X5=!0}return X5}const rOn=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function oJ(e){return e!=null&&!rOn.has(e)?(du(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${u8}"`),null):e}function sOn(e,t){let n,r,s,a,i;if(Kkn(e)){let l=e.getAttribute("action");r=l?Ag(l,t):null,n=e.getAttribute("method")||"get",s=oJ(e.getAttribute("enctype"))||u8,a=new FormData(e)}else if(Ykn(e)||Xkn(e)&&(e.type==="submit"||e.type==="image")){let l=e.form;if(l==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let c=e.getAttribute("formaction")||l.getAttribute("action");if(r=c?Ag(c,t):null,n=e.getAttribute("formmethod")||l.getAttribute("method")||"get",s=oJ(e.getAttribute("formenctype"))||oJ(l.getAttribute("enctype"))||u8,a=new FormData(l,e),!nOn()){let{name:u,type:d,value:f}=e;if(d==="image"){let p=u?`${u}.`:"";a.append(`${p}x`,"0"),a.append(`${p}y`,"0")}else u&&a.append(u,f)}}else{if(Uq(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n="get",r=null,s=u8,i=e}return a&&s==="text/plain"&&(i=a,a=void 0),{action:r,method:n.toLowerCase(),encType:s,formData:a,body:i}}function Iwe(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Ymt(e,t){let n=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n.pathname.endsWith("/")?n.pathname=`${n.pathname}_.${t}`:n.pathname=`${n.pathname}.${t}`,n}async function aOn(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function iOn(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function oOn(e,t,n){return dOn((await Promise.all(e.map(async r=>{let s=t.routes[r.route.id];if(s){let a=await aOn(s,n);return a.links?a.links():[]}return[]}))).flat(1).filter(iOn).filter(r=>r.rel==="stylesheet"||r.rel==="preload").map(r=>r.rel==="stylesheet"?{...r,rel:"prefetch",as:"style"}:{...r,rel:"prefetch"}))}function o5e(e,t,n,r,s,a){let i=(c,u)=>n[u]?c.route.id!==n[u].route.id:!0,l=(c,u)=>n[u].pathname!==c.pathname||n[u].route.path?.endsWith("*")&&n[u].params["*"]!==c.params["*"];return a==="assets"?t.filter((c,u)=>i(c,u)||l(c,u)):a==="data"?t.filter((c,u)=>{let d=r.routes[c.route.id];if(!d||!d.hasLoader)return!1;if(i(c,u)||l(c,u))return!0;if(c.route.shouldRevalidate){let f=c.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof f=="boolean")return f}return!0}):[]}function lOn(e,t,{includeHydrateFallback:n}={}){return cOn(e.map(r=>{let s=t.routes[r.route.id];if(!s)return[];let a=[s.module];return s.clientActionModule&&(a=a.concat(s.clientActionModule)),s.clientLoaderModule&&(a=a.concat(s.clientLoaderModule)),n&&s.hydrateFallbackModule&&(a=a.concat(s.hydrateFallbackModule)),s.imports&&(a=a.concat(s.imports)),a}).flat(1))}function cOn(e){return[...new Set(e)]}function uOn(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function dOn(e,t){let n=new Set;return new Set(t),e.reduce((r,s)=>{let a=JSON.stringify(uOn(s));return n.has(a)||(n.add(a),r.push({key:a,link:s})),r},[])}function fOn(){let e=g.useContext(A_);return Iwe(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function pOn(){let e=g.useContext(WD);return Iwe(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}const Awe=g.createContext(void 0);Awe.displayName="FrameworkContext";function Rwe(){let e=g.useContext(Awe);return Iwe(e,"You must render this element inside a <HydratedRouter> element"),e}function hOn(e,t){let n=g.useContext(Awe),[r,s]=g.useState(!1),[a,i]=g.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:u,onMouseLeave:d,onTouchStart:f}=t,p=g.useRef(null);g.useEffect(()=>{if(e==="render"&&i(!0),e==="viewport"){let v=b=>{b.forEach(x=>{i(x.isIntersecting)})},y=new IntersectionObserver(v,{threshold:.5});return p.current&&y.observe(p.current),()=>{y.disconnect()}}},[e]),g.useEffect(()=>{if(r){let v=setTimeout(()=>{i(!0)},100);return()=>{clearTimeout(v)}}},[r]);let h=()=>{s(!0)},m=()=>{s(!1),i(!1)};return n?e!=="intent"?[a,p,{}]:[a,p,{onFocus:oR(l,h),onBlur:oR(c,m),onMouseEnter:oR(u,h),onMouseLeave:oR(d,m),onTouchStart:oR(f,h)}]:[!1,p,{}]}function oR(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function mOn({page:e,...t}){let n=Hmt(),{nonce:r}=Rwe(),{router:s}=fOn(),a=g.useMemo(()=>Smt(s.routes,e,s.basename),[s.routes,e,s.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?g.createElement(vOn,{page:e,matches:a,...t}):g.createElement(yOn,{page:e,matches:a,...t})):null}function gOn(e){let{manifest:t,routeModules:n}=Rwe(),[r,s]=g.useState([]);return g.useEffect(()=>{let a=!1;return oOn(e,t,n).then(i=>{a||s(i)}),()=>{a=!0}},[e,t,n]),r}function vOn({page:e,matches:t,...n}){let r=Ho(),s=g.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let a=Ymt(e,"rsc"),i=!1,l=[];for(let c of t)typeof c.route.shouldRevalidate=="function"?i=!0:l.push(c.route.id);return i&&l.length>0&&a.searchParams.set("_routes",l.join(",")),[a.pathname+a.search]},[e,r,t]);return g.createElement(g.Fragment,null,s.map(a=>g.createElement("link",{key:a,rel:"prefetch",as:"fetch",href:a,...n})))}function yOn({page:e,matches:t,...n}){let r=Ho(),{manifest:s,routeModules:a}=Rwe(),{loaderData:i,matches:l}=pOn(),c=g.useMemo(()=>o5e(e,t,l,s,r,"data"),[e,t,l,s,r]),u=g.useMemo(()=>o5e(e,t,l,s,r,"assets"),[e,t,l,s,r]),d=g.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let h=new Set,m=!1;if(t.forEach(y=>{let b=s.routes[y.route.id];!b||!b.hasLoader||(!c.some(x=>x.route.id===y.route.id)&&y.route.id in i&&a[y.route.id]?.shouldRevalidate||b.hasClientLoader?m=!0:h.add(y.route.id))}),h.size===0)return[];let v=Ymt(e,"data");return m&&h.size>0&&v.searchParams.set("_routes",t.filter(y=>h.has(y.route.id)).map(y=>y.route.id).join(",")),[v.pathname+v.search]},[i,r,s,c,t,e,a]),f=g.useMemo(()=>lOn(u,s),[u,s]),p=gOn(u);return g.createElement(g.Fragment,null,d.map(h=>g.createElement("link",{key:h,rel:"prefetch",as:"fetch",href:h,...n})),f.map(h=>g.createElement("link",{key:h,rel:"modulepreload",href:h,...n})),p.map(({key:h,link:m})=>g.createElement("link",{key:h,nonce:n.nonce,...m,crossOrigin:m.crossOrigin??n.crossOrigin})))}function bOn(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}const xOn=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{xOn&&(window.__reactRouterVersion="8.3.0")}catch{}function wOn(e,t){return QSn({basename:t?.basename,getContext:t?.getContext,future:t?.future,history:fSn({window:t?.window}),hydrationData:t?.hydrationData||SOn(),routes:e,mapRouteProperties:wmt,hydrationRouteProperties:qkn,dataStrategy:t?.dataStrategy,patchRoutesOnNavigation:t?.patchRoutesOnNavigation,window:t?.window,instrumentations:t?.instrumentations}).initialize()}function SOn(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:kOn(e.errors)}),e}function kOn(e){if(!e)return null;let t=Object.entries(e),n={};for(let[r,s]of t)if(s&&s.__type==="RouteErrorResponse")n[r]=new HD(s.status,s.statusText,s.data,s.internal===!0);else if(s&&s.__type==="Error"){if(typeof s.__subType=="string"&&LSn.includes(s.__subType)){let a=window[s.__subType];if(typeof a=="function")try{let i=new a(s.message);i.stack="",n[r]=i}catch{}}if(n[r]==null){let a=new Error(s.message);a.stack="",n[r]=a}}else n[r]=s;return n}const ni=g.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:s,reloadDocument:a,replace:i,mask:l,state:c,target:u,to:d,preventScrollReset:f,viewTransition:p,defaultShouldRevalidate:h,...m},v){let{basename:y,navigator:b,useTransitions:x}=g.useContext(Sm),S=typeof d=="string"&&Fq.test(d),k=Imt(d,y);d=k.to;let _=Ckn(d,{relative:s}),C=Ho(),E=null;if(l){let F=qD(l,[],C.mask?C.mask.pathname:"/",!0);y!=="/"&&(F.pathname=F.pathname==="/"?y:Jh([y,F.pathname])),E=b.createHref(F)}let[T,N,I]=hOn(r,m),A=EOn(d,{replace:i,mask:l,state:c,target:u,preventScrollReset:f,relative:s,viewTransition:p,defaultShouldRevalidate:h,useTransitions:x});function R(F){t&&t(F),F.defaultPrevented||A(F)}let L=!(k.isExternal||a),D=g.createElement("a",{...m,...I,href:(L?E:void 0)||k.absoluteURL||_,onClick:L?R:t,ref:bOn(v,N),target:u,"data-discover":!S&&n==="render"?"true":void 0});return T&&!S?g.createElement(g.Fragment,null,D,g.createElement(mOn,{page:_})):D});ni.displayName="Link";const OOn=g.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:s=!1,style:a,to:i,viewTransition:l,children:c,...u},d){let f=ZD(i,{relative:u.relative}),p=Ho(),h=g.useContext(WD),{navigator:m,basename:v}=g.useContext(Sm),y=h!=null&&AOn(f)&&l===!0,b=m.encodeLocation?m.encodeLocation(f).pathname:f.pathname,x=p.pathname,S=h&&h.navigation&&h.navigation.location?h.navigation.location.pathname:null;n||(x=x.toLowerCase(),S=S?S.toLowerCase():null,b=b.toLowerCase()),S&&v&&(S=Ag(S,v)||S);const k=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let _=x===b||!s&&x.startsWith(b)&&x.charAt(k)==="/",C=S!=null&&(S===b||!s&&S.startsWith(b)&&S.charAt(k)==="/"),E={isActive:_,isPending:C,isTransitioning:y},T=_?t:void 0,N;typeof r=="function"?N=r(E):N=[r,_?"active":null,C?"pending":null,y?"transitioning":null].filter(Boolean).join(" ");let I=typeof a=="function"?a(E):a;return g.createElement(ni,{...u,"aria-current":T,className:N,ref:d,style:I,to:i,viewTransition:l},typeof c=="function"?c(E):c)});OOn.displayName="NavLink";const _On=g.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:s,state:a,method:i="get",action:l,onSubmit:c,relative:u,preventScrollReset:d,viewTransition:f,defaultShouldRevalidate:p,...h},m)=>{let{useTransitions:v}=g.useContext(Sm),y=NOn(),b=IOn(l,{relative:u}),x=i.toLowerCase()==="get"?"get":"post",S=typeof l=="string"&&Fq.test(l),k=_=>{if(c&&c(_),_.defaultPrevented)return;_.preventDefault();let C=_.nativeEvent.submitter,E=C?.getAttribute("formmethod")||i,T=()=>y(C||_.currentTarget,{fetcherKey:t,method:E,navigate:n,replace:s,state:a,relative:u,preventScrollReset:d,viewTransition:f,defaultShouldRevalidate:p});v&&n!==!1?g.startTransition(()=>T()):T()};return g.createElement("form",{ref:m,method:x,action:b,onSubmit:r?c:k,...h,"data-discover":!S&&e==="render"?"true":void 0})});_On.displayName="Form";function COn(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Kmt(e){let t=g.useContext(A_);return ds(t,COn(e)),t}function EOn(e,{target:t,replace:n,mask:r,state:s,preventScrollReset:a,relative:i,viewTransition:l,defaultShouldRevalidate:c,useTransitions:u}={}){let d=Ws(),f=Ho(),p=ZD(e,{relative:i});return g.useCallback(h=>{if(eOn(h,t)){h.preventDefault();let m=n!==void 0?n:my(f)===my(p),v=()=>d(e,{replace:m,mask:r,state:s,preventScrollReset:a,relative:i,viewTransition:l,defaultShouldRevalidate:c});u?g.startTransition(()=>v()):v()}},[f,d,p,n,r,s,t,e,a,i,l,c,u])}function si(e){du(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=g.useRef(Phe(e)),n=g.useRef(!1),r=Ho(),s=g.useMemo(()=>tOn(r.search,n.current?null:t.current),[r.search]),a=Ws();return[s,g.useCallback((i,l)=>{const c=Phe(typeof i=="function"?i(new URLSearchParams(s)):i);n.current=!0,a("?"+c,l)},[a,s])]}let TOn=0,jOn=()=>`__${String(++TOn)}__`;function NOn(){let{router:e}=Kmt("useSubmit"),{basename:t}=g.useContext(Sm),n=Fkn(),r=e.fetch,s=e.navigate;return g.useCallback(async(a,i={})=>{let{action:l,method:c,encType:u,formData:d,body:f}=sOn(a,t);i.navigate===!1?await r(i.fetcherKey||jOn(),n,i.action||l,{defaultShouldRevalidate:i.defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:d,body:f,formMethod:i.method||c,formEncType:i.encType||u,flushSync:i.flushSync}):await s(i.action||l,{defaultShouldRevalidate:i.defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:d,body:f,formMethod:i.method||c,formEncType:i.encType||u,replace:i.replace,state:i.state,fromRouteId:n,flushSync:i.flushSync,viewTransition:i.viewTransition})},[r,s,t,n])}function IOn(e,{relative:t}={}){let{basename:n}=g.useContext(Sm),r=g.useContext(km);ds(r,"useFormAction must be used inside a RouteContext");let[s]=r.matches.slice(-1),a={...ZD(e||".",{relative:t})},i=Ho();if(e==null){a.search=i.search;let l=new URLSearchParams(a.search),c=l.getAll("index");if(c.some(u=>u==="")){l.delete("index"),c.filter(d=>d).forEach(d=>l.append("index",d));let u=l.toString();a.search=u?`?${u}`:""}}return(!e||e===".")&&s.route.index&&(a.search=a.search?a.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(a.pathname=a.pathname==="/"?n:Jh([n,a.pathname])),my(a)}function AOn(e,{relative:t}={}){let n=g.useContext(Ewe);ds(n!=null,"`useViewTransitionState` must be used within `react-router/dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=Kmt("useViewTransitionState"),s=ZD(e,{relative:t});if(!n.isTransitioning)return!1;let a=Ag(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=Ag(n.nextLocation.pathname,r)||n.nextLocation.pathname;return f7(s.pathname,i)!=null||f7(s.pathname,a)!=null}const ROn={none:"0px",sm:"2px",md:"4px",lg:"6px",xl:"12px"},Zb={surface1:"var(--surface1)",surface2:"var(--surface2)",surface3:"var(--surface3)",surface4:"var(--surface4)",surface5:"var(--surface5)",surface6:"var(--surface6)",accent1:"var(--accent1)",accent2:"var(--accent2)",accent3:"var(--accent3)",accent5:"var(--accent5)",accent6:"var(--accent6)",accent1Dark:"var(--accent1Dark)",accent2Dark:"var(--accent2Dark)",accent3Dark:"var(--accent3Dark)",accent5Dark:"var(--accent5Dark)",accent6Dark:"var(--accent6Dark)",accent1Darker:"var(--accent1Darker)",accent2Darker:"var(--accent2Darker)",accent3Darker:"var(--accent3Darker)",accent5Darker:"var(--accent5Darker)",accent6Darker:"var(--accent6Darker)",neutral1:"var(--neutral1)",neutral2:"var(--neutral2)",neutral3:"var(--neutral3)",neutral4:"var(--neutral4)",neutral5:"var(--neutral5)",neutral6:"var(--neutral6)",error:"var(--error)",overlay:"var(--overlay)"},POn={border1:"var(--border1)",border2:"var(--border2)"},$On={"ui-xs":"0.625rem","ui-sm":"0.75rem","ui-smd":"0.8125rem","ui-md":"0.875rem","ui-lg":"1rem","header-xs":"1rem","header-sm":"1.125rem","header-md":"1.25rem","header-lg":"1.5rem","header-xl":"1.75rem"},MOn={"ui-xs":"160%","ui-sm":"150%","ui-smd":"150%","ui-md":"143%","ui-lg":"150%","header-xs":"137%","header-sm":"133%","header-md":"140%","header-lg":"133%","header-xl":"129%"},DOn={sm:"0 1px 2px rgba(0, 0, 0, 0.3)",md:"0 4px 6px rgba(0, 0, 0, 0.3)",lg:"0 10px 15px rgba(0, 0, 0, 0.4)",inner:"inset 0 2px 4px rgba(0, 0, 0, 0.3)",card:"0 2px 8px rgba(0, 0, 0, 0.4)",elevated:"0 8px 24px rgba(0, 0, 0, 0.5)",dialog:"0 16px 48px rgba(0, 0, 0, 0.6)"},LOn={accent1:"0 0 20px rgba(34, 197, 94, 0.25)",accent2:"0 0 20px rgba(239, 68, 68, 0.25)",focusRing:"0 0 0 3px rgba(34, 197, 94, 0.12)"},FOn={"icon-default":"16px","icon-lg":"20px","icon-sm":"12px","form-xs":"1.5rem","form-sm":"1.75rem","form-md":"2rem","form-default":"2.25rem","form-lg":"2.5rem","header-default":"48px","table-header":"28px","table-row":"56px","table-row-small":"40px","badge-default":"28px","avatar-sm":"24px","avatar-md":"32px","avatar-lg":"40px","dropdown-max-height":"300px"},zOn={0:"0rem",px:"0.0625rem","0.5":"0.125rem",1:"0.25rem","1.5":"0.375rem",2:"0.5rem","2.5":"0.625rem",3:"0.75rem","3.5":"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"};function Xmt(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t<s;t++)e[t]&&(n=Xmt(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Jmt(){for(var e,t,n=0,r="",s=arguments.length;n<s;n++)(e=arguments[n])&&(t=Xmt(e))&&(r&&(r+=" "),r+=t);return r}const BOn=(e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r<e.length;r++)n[r]=e[r];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},UOn=(e,t)=>({classGroupId:e,validator:t}),egt=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),p7="-",l5e=[],VOn="arbitrary..",qOn=e=>{const t=WOn(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return HOn(i);const l=i.split(p7),c=l[0]===""&&l.length>1?1:0;return tgt(l,c,t)},getConflictingClassGroupIds:(i,l)=>{if(l){const c=r[i],u=n[i];return c?u?BOn(u,c):c:u||l5e}return n[i]||l5e}}},tgt=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const s=e[t],a=n.nextPart.get(s);if(a){const u=tgt(e,t+1,a);if(u)return u}const i=n.validators;if(i===null)return;const l=t===0?e.join(p7):e.slice(t).join(p7),c=i.length;for(let u=0;u<c;u++){const d=i[u];if(d.validator(l))return d.classGroupId}},HOn=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?VOn+r:void 0})(),WOn=e=>{const{theme:t,classGroups:n}=e;return ZOn(n,t)},ZOn=(e,t)=>{const n=egt();for(const r in e){const s=e[r];Pwe(s,n,r,t)}return n},Pwe=(e,t,n,r)=>{const s=e.length;for(let a=0;a<s;a++){const i=e[a];GOn(i,t,n,r)}},GOn=(e,t,n,r)=>{if(typeof e=="string"){QOn(e,t,n);return}if(typeof e=="function"){YOn(e,t,n,r);return}KOn(e,t,n,r)},QOn=(e,t,n)=>{const r=e===""?t:ngt(t,e);r.classGroupId=n},YOn=(e,t,n,r)=>{if(XOn(e)){Pwe(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(UOn(n,e))},KOn=(e,t,n,r)=>{const s=Object.entries(e),a=s.length;for(let i=0;i<a;i++){const[l,c]=s[i];Pwe(c,ngt(t,l),n,r)}},ngt=(e,t)=>{let n=e;const r=t.split(p7),s=r.length;for(let a=0;a<s;a++){const i=r[a];let l=n.nextPart.get(i);l||(l=egt(),n.nextPart.set(i,l)),n=l}return n},XOn=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,JOn=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const s=(a,i)=>{n[a]=i,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(a){let i=n[a];if(i!==void 0)return i;if((i=r[a])!==void 0)return s(a,i),i},set(a,i){a in n?n[a]=i:s(a,i)}}},$he="!",c5e=":",e_n=[],u5e=(e,t,n,r,s)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:s}),t_n=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=s=>{const a=[];let i=0,l=0,c=0,u;const d=s.length;for(let v=0;v<d;v++){const y=s[v];if(i===0&&l===0){if(y===c5e){a.push(s.slice(c,v)),c=v+1;continue}if(y==="/"){u=v;continue}}y==="["?i++:y==="]"?i--:y==="("?l++:y===")"&&l--}const f=a.length===0?s:s.slice(c);let p=f,h=!1;f.endsWith($he)?(p=f.slice(0,-1),h=!0):f.startsWith($he)&&(p=f.slice(1),h=!0);const m=u&&u>c?u-c:void 0;return u5e(a,h,p,m)};if(t){const s=t+c5e,a=r;r=i=>i.startsWith(s)?a(i.slice(s.length)):u5e(e_n,!1,i,void 0,!0)}if(n){const s=r;r=a=>n({className:a,parseClassName:s})}return r},n_n=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let s=[];for(let a=0;a<n.length;a++){const i=n[a],l=i[0]==="[",c=t.has(i);l||c?(s.length>0&&(s.sort(),r.push(...s),s=[]),r.push(i)):s.push(i)}return s.length>0&&(s.sort(),r.push(...s)),r}},r_n=e=>({cache:JOn(e.cacheSize),parseClassName:t_n(e),sortModifiers:n_n(e),...qOn(e)}),s_n=/\s+/,a_n=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s,sortModifiers:a}=t,i=[],l=e.trim().split(s_n);let c="";for(let u=l.length-1;u>=0;u-=1){const d=l[u],{isExternal:f,modifiers:p,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:v}=n(d);if(f){c=d+(c.length>0?" "+c:c);continue}let y=!!v,b=r(y?m.substring(0,v):m);if(!b){if(!y){c=d+(c.length>0?" "+c:c);continue}if(b=r(m),!b){c=d+(c.length>0?" "+c:c);continue}y=!1}const x=p.length===0?"":p.length===1?p[0]:a(p).join(":"),S=h?x+$he:x,k=S+b;if(i.indexOf(k)>-1)continue;i.push(k);const _=s(b,y);for(let C=0;C<_.length;++C){const E=_[C];i.push(S+E)}c=d+(c.length>0?" "+c:c)}return c},i_n=(...e)=>{let t=0,n,r,s="";for(;t<e.length;)(n=e[t++])&&(r=rgt(n))&&(s&&(s+=" "),s+=r);return s},rgt=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=rgt(e[r]))&&(n&&(n+=" "),n+=t);return n},d5e=(e,...t)=>{let n,r,s,a;const i=c=>{const u=t.reduce((d,f)=>f(d),e());return n=r_n(u),r=n.cache.get,s=n.cache.set,a=l,l(c)},l=c=>{const u=r(c);if(u)return u;const d=a_n(c,n);return s(c,d),d};return a=i,(...c)=>a(i_n(...c))},o_n=[],Gl=e=>{const t=n=>n[e]||o_n;return t.isThemeGetter=!0,t},sgt=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,agt=/^\((?:(\w[\w-]*):)?(.+)\)$/i,l_n=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,c_n=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,u_n=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,d_n=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,f_n=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,p_n=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Q0=e=>l_n.test(e),gs=e=>!!e&&!Number.isNaN(Number(e)),Y0=e=>!!e&&Number.isInteger(Number(e)),lJ=e=>e.endsWith("%")&&gs(e.slice(0,-1)),gb=e=>c_n.test(e),igt=()=>!0,h_n=e=>u_n.test(e)&&!d_n.test(e),$we=()=>!1,m_n=e=>f_n.test(e),g_n=e=>p_n.test(e),v_n=e=>!qn(e)&&!Wn(e),y_n=e=>W1(e,cgt,$we),qn=e=>sgt.test(e),VS=e=>W1(e,ugt,h_n),f5e=e=>W1(e,C_n,gs),b_n=e=>W1(e,fgt,igt),x_n=e=>W1(e,dgt,$we),p5e=e=>W1(e,ogt,$we),w_n=e=>W1(e,lgt,g_n),J5=e=>W1(e,pgt,m_n),Wn=e=>agt.test(e),lR=e=>R_(e,ugt),S_n=e=>R_(e,dgt),h5e=e=>R_(e,ogt),k_n=e=>R_(e,cgt),O_n=e=>R_(e,lgt),e6=e=>R_(e,pgt,!0),__n=e=>R_(e,fgt,!0),W1=(e,t,n)=>{const r=sgt.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},R_=(e,t,n=!1)=>{const r=agt.exec(e);return r?r[1]?t(r[1]):n:!1},ogt=e=>e==="position"||e==="percentage",lgt=e=>e==="image"||e==="url",cgt=e=>e==="length"||e==="size"||e==="bg-size",ugt=e=>e==="length",C_n=e=>e==="number",dgt=e=>e==="family-name",fgt=e=>e==="number"||e==="weight",pgt=e=>e==="shadow",m5e=()=>{const e=Gl("color"),t=Gl("font"),n=Gl("text"),r=Gl("font-weight"),s=Gl("tracking"),a=Gl("leading"),i=Gl("breakpoint"),l=Gl("container"),c=Gl("spacing"),u=Gl("radius"),d=Gl("shadow"),f=Gl("inset-shadow"),p=Gl("text-shadow"),h=Gl("drop-shadow"),m=Gl("blur"),v=Gl("perspective"),y=Gl("aspect"),b=Gl("ease"),x=Gl("animate"),S=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],_=()=>[...k(),Wn,qn],C=()=>["auto","hidden","clip","visible","scroll"],E=()=>["auto","contain","none"],T=()=>[Wn,qn,c],N=()=>[Q0,"full","auto",...T()],I=()=>[Y0,"none","subgrid",Wn,qn],A=()=>["auto",{span:["full",Y0,Wn,qn]},Y0,Wn,qn],R=()=>[Y0,"auto",Wn,qn],L=()=>["auto","min","max","fr",Wn,qn],D=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],F=()=>["start","end","center","stretch","center-safe","end-safe"],H=()=>["auto",...T()],B=()=>[Q0,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...T()],U=()=>[Q0,"screen","full","dvw","lvw","svw","min","max","fit",...T()],V=()=>[Q0,"screen","full","lh","dvh","lvh","svh","min","max","fit",...T()],M=()=>[e,Wn,qn],G=()=>[...k(),h5e,p5e,{position:[Wn,qn]}],q=()=>["no-repeat",{repeat:["","x","y","space","round"]}],$=()=>["auto","cover","contain",k_n,y_n,{size:[Wn,qn]}],z=()=>[lJ,lR,VS],Z=()=>["","none","full",u,Wn,qn],K=()=>["",gs,lR,VS],ne=()=>["solid","dashed","dotted","double"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[gs,lJ,h5e,p5e],ae=()=>["","none",m,Wn,qn],pe=()=>["none",gs,Wn,qn],Y=()=>["none",gs,Wn,qn],te=()=>[gs,Wn,qn],ue=()=>[Q0,"full",...T()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[gb],breakpoint:[gb],color:[igt],container:[gb],"drop-shadow":[gb],ease:["in","out","in-out"],font:[v_n],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[gb],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[gb],shadow:[gb],spacing:["px",gs],text:[gb],"text-shadow":[gb],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Q0,qn,Wn,y]}],container:["container"],columns:[{columns:[gs,qn,Wn,l]}],"break-after":[{"break-after":S()}],"break-before":[{"break-before":S()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:_()}],overflow:[{overflow:C()}],"overflow-x":[{"overflow-x":C()}],"overflow-y":[{"overflow-y":C()}],overscroll:[{overscroll:E()}],"overscroll-x":[{"overscroll-x":E()}],"overscroll-y":[{"overscroll-y":E()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:N()}],"inset-x":[{"inset-x":N()}],"inset-y":[{"inset-y":N()}],start:[{"inset-s":N(),start:N()}],end:[{"inset-e":N(),end:N()}],"inset-bs":[{"inset-bs":N()}],"inset-be":[{"inset-be":N()}],top:[{top:N()}],right:[{right:N()}],bottom:[{bottom:N()}],left:[{left:N()}],visibility:["visible","invisible","collapse"],z:[{z:[Y0,"auto",Wn,qn]}],basis:[{basis:[Q0,"full","auto",l,...T()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[gs,Q0,"auto","initial","none",qn]}],grow:[{grow:["",gs,Wn,qn]}],shrink:[{shrink:["",gs,Wn,qn]}],order:[{order:[Y0,"first","last","none",Wn,qn]}],"grid-cols":[{"grid-cols":I()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":I()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":L()}],"auto-rows":[{"auto-rows":L()}],gap:[{gap:T()}],"gap-x":[{"gap-x":T()}],"gap-y":[{"gap-y":T()}],"justify-content":[{justify:[...D(),"normal"]}],"justify-items":[{"justify-items":[...F(),"normal"]}],"justify-self":[{"justify-self":["auto",...F()]}],"align-content":[{content:["normal",...D()]}],"align-items":[{items:[...F(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...F(),{baseline:["","last"]}]}],"place-content":[{"place-content":D()}],"place-items":[{"place-items":[...F(),"baseline"]}],"place-self":[{"place-self":["auto",...F()]}],p:[{p:T()}],px:[{px:T()}],py:[{py:T()}],ps:[{ps:T()}],pe:[{pe:T()}],pbs:[{pbs:T()}],pbe:[{pbe:T()}],pt:[{pt:T()}],pr:[{pr:T()}],pb:[{pb:T()}],pl:[{pl:T()}],m:[{m:H()}],mx:[{mx:H()}],my:[{my:H()}],ms:[{ms:H()}],me:[{me:H()}],mbs:[{mbs:H()}],mbe:[{mbe:H()}],mt:[{mt:H()}],mr:[{mr:H()}],mb:[{mb:H()}],ml:[{ml:H()}],"space-x":[{"space-x":T()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":T()}],"space-y-reverse":["space-y-reverse"],size:[{size:B()}],"inline-size":[{inline:["auto",...U()]}],"min-inline-size":[{"min-inline":["auto",...U()]}],"max-inline-size":[{"max-inline":["none",...U()]}],"block-size":[{block:["auto",...V()]}],"min-block-size":[{"min-block":["auto",...V()]}],"max-block-size":[{"max-block":["none",...V()]}],w:[{w:[l,"screen",...B()]}],"min-w":[{"min-w":[l,"screen","none",...B()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[i]},...B()]}],h:[{h:["screen","lh",...B()]}],"min-h":[{"min-h":["screen","lh","none",...B()]}],"max-h":[{"max-h":["screen","lh",...B()]}],"font-size":[{text:["base",n,lR,VS]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,__n,b_n]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",lJ,qn]}],"font-family":[{font:[S_n,x_n,t]}],"font-features":[{"font-features":[qn]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,Wn,qn]}],"line-clamp":[{"line-clamp":[gs,"none",Wn,f5e]}],leading:[{leading:[a,...T()]}],"list-image":[{"list-image":["none",Wn,qn]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Wn,qn]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:M()}],"text-color":[{text:M()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ne(),"wavy"]}],"text-decoration-thickness":[{decoration:[gs,"from-font","auto",Wn,VS]}],"text-decoration-color":[{decoration:M()}],"underline-offset":[{"underline-offset":[gs,"auto",Wn,qn]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:T()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Wn,qn]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Wn,qn]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:G()}],"bg-repeat":[{bg:q()}],"bg-size":[{bg:$()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Y0,Wn,qn],radial:["",Wn,qn],conic:[Y0,Wn,qn]},O_n,w_n]}],"bg-color":[{bg:M()}],"gradient-from-pos":[{from:z()}],"gradient-via-pos":[{via:z()}],"gradient-to-pos":[{to:z()}],"gradient-from":[{from:M()}],"gradient-via":[{via:M()}],"gradient-to":[{to:M()}],rounded:[{rounded:Z()}],"rounded-s":[{"rounded-s":Z()}],"rounded-e":[{"rounded-e":Z()}],"rounded-t":[{"rounded-t":Z()}],"rounded-r":[{"rounded-r":Z()}],"rounded-b":[{"rounded-b":Z()}],"rounded-l":[{"rounded-l":Z()}],"rounded-ss":[{"rounded-ss":Z()}],"rounded-se":[{"rounded-se":Z()}],"rounded-ee":[{"rounded-ee":Z()}],"rounded-es":[{"rounded-es":Z()}],"rounded-tl":[{"rounded-tl":Z()}],"rounded-tr":[{"rounded-tr":Z()}],"rounded-br":[{"rounded-br":Z()}],"rounded-bl":[{"rounded-bl":Z()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-bs":[{"border-bs":K()}],"border-w-be":[{"border-be":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ne(),"hidden","none"]}],"divide-style":[{divide:[...ne(),"hidden","none"]}],"border-color":[{border:M()}],"border-color-x":[{"border-x":M()}],"border-color-y":[{"border-y":M()}],"border-color-s":[{"border-s":M()}],"border-color-e":[{"border-e":M()}],"border-color-bs":[{"border-bs":M()}],"border-color-be":[{"border-be":M()}],"border-color-t":[{"border-t":M()}],"border-color-r":[{"border-r":M()}],"border-color-b":[{"border-b":M()}],"border-color-l":[{"border-l":M()}],"divide-color":[{divide:M()}],"outline-style":[{outline:[...ne(),"none","hidden"]}],"outline-offset":[{"outline-offset":[gs,Wn,qn]}],"outline-w":[{outline:["",gs,lR,VS]}],"outline-color":[{outline:M()}],shadow:[{shadow:["","none",d,e6,J5]}],"shadow-color":[{shadow:M()}],"inset-shadow":[{"inset-shadow":["none",f,e6,J5]}],"inset-shadow-color":[{"inset-shadow":M()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:M()}],"ring-offset-w":[{"ring-offset":[gs,VS]}],"ring-offset-color":[{"ring-offset":M()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":M()}],"text-shadow":[{"text-shadow":["none",p,e6,J5]}],"text-shadow-color":[{"text-shadow":M()}],opacity:[{opacity:[gs,Wn,qn]}],"mix-blend":[{"mix-blend":[...ee(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ee()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[gs]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":M()}],"mask-image-linear-to-color":[{"mask-linear-to":M()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":M()}],"mask-image-t-to-color":[{"mask-t-to":M()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":M()}],"mask-image-r-to-color":[{"mask-r-to":M()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":M()}],"mask-image-b-to-color":[{"mask-b-to":M()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":M()}],"mask-image-l-to-color":[{"mask-l-to":M()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":M()}],"mask-image-x-to-color":[{"mask-x-to":M()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":M()}],"mask-image-y-to-color":[{"mask-y-to":M()}],"mask-image-radial":[{"mask-radial":[Wn,qn]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"mask-image-radial-from-color":[{"mask-radial-from":M()}],"mask-image-radial-to-color":[{"mask-radial-to":M()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[gs]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":M()}],"mask-image-conic-to-color":[{"mask-conic-to":M()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:G()}],"mask-repeat":[{mask:q()}],"mask-size":[{mask:$()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Wn,qn]}],filter:[{filter:["","none",Wn,qn]}],blur:[{blur:ae()}],brightness:[{brightness:[gs,Wn,qn]}],contrast:[{contrast:[gs,Wn,qn]}],"drop-shadow":[{"drop-shadow":["","none",h,e6,J5]}],"drop-shadow-color":[{"drop-shadow":M()}],grayscale:[{grayscale:["",gs,Wn,qn]}],"hue-rotate":[{"hue-rotate":[gs,Wn,qn]}],invert:[{invert:["",gs,Wn,qn]}],saturate:[{saturate:[gs,Wn,qn]}],sepia:[{sepia:["",gs,Wn,qn]}],"backdrop-filter":[{"backdrop-filter":["","none",Wn,qn]}],"backdrop-blur":[{"backdrop-blur":ae()}],"backdrop-brightness":[{"backdrop-brightness":[gs,Wn,qn]}],"backdrop-contrast":[{"backdrop-contrast":[gs,Wn,qn]}],"backdrop-grayscale":[{"backdrop-grayscale":["",gs,Wn,qn]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[gs,Wn,qn]}],"backdrop-invert":[{"backdrop-invert":["",gs,Wn,qn]}],"backdrop-opacity":[{"backdrop-opacity":[gs,Wn,qn]}],"backdrop-saturate":[{"backdrop-saturate":[gs,Wn,qn]}],"backdrop-sepia":[{"backdrop-sepia":["",gs,Wn,qn]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":T()}],"border-spacing-x":[{"border-spacing-x":T()}],"border-spacing-y":[{"border-spacing-y":T()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Wn,qn]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[gs,"initial",Wn,qn]}],ease:[{ease:["linear","initial",b,Wn,qn]}],delay:[{delay:[gs,Wn,qn]}],animate:[{animate:["none",x,Wn,qn]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[v,Wn,qn]}],"perspective-origin":[{"perspective-origin":_()}],rotate:[{rotate:pe()}],"rotate-x":[{"rotate-x":pe()}],"rotate-y":[{"rotate-y":pe()}],"rotate-z":[{"rotate-z":pe()}],scale:[{scale:Y()}],"scale-x":[{"scale-x":Y()}],"scale-y":[{"scale-y":Y()}],"scale-z":[{"scale-z":Y()}],"scale-3d":["scale-3d"],skew:[{skew:te()}],"skew-x":[{"skew-x":te()}],"skew-y":[{"skew-y":te()}],transform:[{transform:[Wn,qn,"","none","gpu","cpu"]}],"transform-origin":[{origin:_()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ue()}],"translate-x":[{"translate-x":ue()}],"translate-y":[{"translate-y":ue()}],"translate-z":[{"translate-z":ue()}],"translate-none":["translate-none"],accent:[{accent:M()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:M()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Wn,qn]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":T()}],"scroll-mx":[{"scroll-mx":T()}],"scroll-my":[{"scroll-my":T()}],"scroll-ms":[{"scroll-ms":T()}],"scroll-me":[{"scroll-me":T()}],"scroll-mbs":[{"scroll-mbs":T()}],"scroll-mbe":[{"scroll-mbe":T()}],"scroll-mt":[{"scroll-mt":T()}],"scroll-mr":[{"scroll-mr":T()}],"scroll-mb":[{"scroll-mb":T()}],"scroll-ml":[{"scroll-ml":T()}],"scroll-p":[{"scroll-p":T()}],"scroll-px":[{"scroll-px":T()}],"scroll-py":[{"scroll-py":T()}],"scroll-ps":[{"scroll-ps":T()}],"scroll-pe":[{"scroll-pe":T()}],"scroll-pbs":[{"scroll-pbs":T()}],"scroll-pbe":[{"scroll-pbe":T()}],"scroll-pt":[{"scroll-pt":T()}],"scroll-pr":[{"scroll-pr":T()}],"scroll-pb":[{"scroll-pb":T()}],"scroll-pl":[{"scroll-pl":T()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Wn,qn]}],fill:[{fill:["none",...M()]}],"stroke-w":[{stroke:[gs,lR,VS,f5e]}],stroke:[{stroke:["none",...M()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},E_n=(e,{cacheSize:t,prefix:n,experimentalParseClassName:r,extend:s={},override:a={}})=>(EP(e,"cacheSize",t),EP(e,"prefix",n),EP(e,"experimentalParseClassName",r),t6(e.theme,a.theme),t6(e.classGroups,a.classGroups),t6(e.conflictingClassGroups,a.conflictingClassGroups),t6(e.conflictingClassGroupModifiers,a.conflictingClassGroupModifiers),EP(e,"orderSensitiveModifiers",a.orderSensitiveModifiers),n6(e.theme,s.theme),n6(e.classGroups,s.classGroups),n6(e.conflictingClassGroups,s.conflictingClassGroups),n6(e.conflictingClassGroupModifiers,s.conflictingClassGroupModifiers),hgt(e,s,"orderSensitiveModifiers"),e),EP=(e,t,n)=>{n!==void 0&&(e[t]=n)},t6=(e,t)=>{if(t)for(const n in t)EP(e,n,t[n])},n6=(e,t)=>{if(t)for(const n in t)hgt(e,t,n)},hgt=(e,t,n)=>{const r=t[n];r!==void 0&&(e[n]=e[n]?e[n].concat(r):r)},T_n=(e,...t)=>typeof e=="function"?d5e(m5e,e,...t):d5e(()=>E_n(m5e(),e),...t),j_n=Object.keys({...Zb,...POn}),N_n=Object.keys(zOn),I_n=Object.keys($On),A_n=Object.keys(MOn),R_n=Object.keys(ROn),qS=Object.keys(FOn),P_n=Object.keys(DOn).concat(Object.keys(LOn)),$_n=T_n({extend:{theme:{color:j_n,spacing:N_n,radius:R_n,leading:A_n,shadow:P_n},classGroups:{"font-size":[{text:I_n}],h:[{h:qS}],w:[{w:qS}],size:[{size:qS}],"min-h":[{"min-h":qS}],"min-w":[{"min-w":qS}],"max-h":[{"max-h":qS}],"max-w":[{"max-w":qS}]}}});function X(...e){return $_n(Jmt(e))}const g5e=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,v5e=Jmt,co=(e,t)=>n=>{var r;if(t?.variants==null)return v5e(e,n?.class,n?.className);const{variants:s,defaultVariants:a}=t,i=Object.keys(s).map(u=>{const d=n?.[u],f=a?.[u];if(d===null)return null;const p=g5e(d)||g5e(f);return s[u][p]}),l=n&&Object.entries(n).reduce((u,d)=>{let[f,p]=d;return p===void 0||(u[f]=p),u},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((u,d)=>{let{class:f,className:p,...h}=d;return Object.entries(h).every(m=>{let[v,y]=m;return Array.isArray(y)?y.includes({...a,...l}[v]):{...a,...l}[v]===y})?[...u,f,p]:u},[]);return v5e(e,i,c,n?.class,n?.className)},y5e={};function Nc(e,t){const n=g.useRef(y5e);return n.current===y5e&&(n.current=e(t)),n}const Mhe=[];let Dhe;function M_n(){return Dhe}function D_n(e){Mhe.push(e)}function Vq(e){const t=(n,r)=>{const s=Nc(L_n).current;let a;try{Dhe=s;for(const i of Mhe)i.before(s);a=e(n,r);for(const i of Mhe)i.after(s);s.didInitialize=!0}finally{Dhe=void 0}return a};return t.displayName=e.displayName||e.name,t}function Mwe(e){return g.forwardRef(Vq(e))}function L_n(){return{didInitialize:!1}}function P_(e){const t=g.useRef(!0);t.current&&(t.current=!1,e())}const F_n=()=>{},Mt=typeof document<"u"?g.useLayoutEffect:F_n;function z_n(e,t){return function(r,...s){const a=new URL(e);return a.searchParams.set("code",r.toString()),s.forEach(i=>a.searchParams.append("args[]",i)),`${t} error #${r}; visit ${a} for the full message.`}}const kr=z_n("https://base-ui.com/production-error","Base UI"),mgt=g.createContext(void 0);function GD(e){const t=g.useContext(mgt);if(t===void 0&&!e)throw new Error(kr(72));return t}const B_n=[];function Dwe(e){g.useEffect(e,B_n)}const cR=0;class pm{static create(){return new pm}currentId=cR;start(t,n){this.clear(),this.currentId=setTimeout(()=>{this.currentId=cR,n()},t)}isStarted(){return this.currentId!==cR}clear=()=>{this.currentId!==cR&&(clearTimeout(this.currentId),this.currentId=cR)};disposeEffect=()=>this.clear}function _o(){const e=Nc(pm.create).current;return Dwe(e.disposeEffect),e}const $_=typeof navigator<"u",cJ=U_n(),ggt=q_n(),Lwe=V_n(),qq=typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter:none"),Fwe=cJ.platform==="MacIntel"&&cJ.maxTouchPoints>1?!0:/iP(hone|ad|od)|iOS/.test(cJ.platform),b5e=$_&&/firefox/i.test(Lwe),vgt=$_&&/apple/i.test(navigator.vendor),A$=$_&&/android/i.test(ggt)||/android/i.test(Lwe),ygt=$_&&ggt.toLowerCase().startsWith("mac")&&!navigator.maxTouchPoints,bgt=Lwe.includes("jsdom/");function U_n(){if(!$_)return{platform:"",maxTouchPoints:-1};const e=navigator.userAgentData;return e?.platform?{platform:e.platform,maxTouchPoints:navigator.maxTouchPoints}:{platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??-1}}function V_n(){if(!$_)return"";const e=navigator.userAgentData;return e&&Array.isArray(e.brands)?e.brands.map(({brand:t,version:n})=>`${t}/${n}`).join(" "):navigator.userAgent}function q_n(){if(!$_)return"";const e=navigator.userAgentData;return e?.platform?e.platform:navigator.platform??""}function wc(e){e.preventDefault(),e.stopPropagation()}function H_n(e){return"nativeEvent"in e}function zwe(e){return e.pointerType===""&&e.isTrusted?!0:A$&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function xgt(e){return bgt?!1:!A$&&e.width===0&&e.height===0||A$&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType==="touch"}function TO(e,t){const n=["mouse","pen"];return t||n.push("",void 0),n.includes(e)}function W_n(e){const t=e.type;return t==="click"||t==="mousedown"||t==="keydown"||t==="keyup"}const Lhe="data-base-ui-focusable",wgt="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",Vw="ArrowLeft",qw="ArrowRight",Bwe="ArrowUp",QD="ArrowDown";function xc(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function gn(e,t){if(!e||!t)return!1;const n=t.getRootNode?.();if(e.contains(t))return!0;if(n&&yj(n)){let r=t;for(;r;){if(e===r)return!0;r=r.parentNode||r.host}}return!1}function Ti(e){return"composedPath"in e?e.composedPath()[0]:e.target}function h7(e,t){if(!Cr(e))return!1;const n=e;if(t.hasElement(n))return!n.hasAttribute("data-trigger-disabled");for(const[,r]of t.entries())if(gn(r,n))return!r.hasAttribute("data-trigger-disabled");return!1}function uJ(e,t){if(t==null)return!1;if("composedPath"in e)return e.composedPath().includes(t);const n=e;return n.target!=null&&t.contains(n.target)}function Z_n(e){return e.matches("html,body")}function Hq(e){return Ia(e)&&e.matches(wgt)}function G_n(e){return e?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${wgt}`)!=null}function Fhe(e){return e?e.getAttribute("role")==="combobox"&&Hq(e):!1}function Sgt(e){if(!e||bgt)return!0;try{return e.matches(":focus-visible")}catch{return!0}}function m7(e){return e?e.hasAttribute(Lhe)?e:e.querySelector(`[${Lhe}]`)||e:null}function Q_n(e,t){return t!=null&&!TO(t)?0:typeof e=="function"?e():e}function g7(e,t,n){const r=Q_n(e,n);return typeof r=="number"?r:r?.[t]}function x5e(e){return typeof e=="function"?e():e}function kgt(e,t){return t||e==="click"||e==="mousedown"}function Y_n(e){return e?.includes("mouse")&&e!=="mousedown"}function Sa(){}const Fh=Object.freeze([]),bs=Object.freeze({}),Mo="none",Rg="trigger-press",Ji="trigger-hover",Kk="trigger-focus",YD="outside-press",Hw="item-press",Uwe="close-press",w5e="track-press",Rk="input-change",Db="input-clear",K_n="input-press",_x="focus-out",M_="escape-key",X_n="close-watcher",v7="list-navigation",J_n="keyboard",eCn="drag",Ogt="cancel-open",TP="sibling-open",_gt="disabled",S5e="missing",k5e="initial",KD="imperative-action",r6="swipe",tCn="window-resize";function Yt(e,t,n,r){let s=!1,a=!1;const i=r??bs;return{reason:e,event:t??new Event("base-ui"),cancel(){s=!0},allowPropagation(){a=!0},get isCanceled(){return s},get isPropagationAllowed(){return a},trigger:n,...i}}function _k(e,t,n){const r=n??bs;return{reason:e,event:t??new Event("base-ui"),...r}}const Cgt=g.createContext({hasProvider:!1,timeoutMs:0,delayRef:{current:0},initialDelayRef:{current:0},timeout:new pm,currentIdRef:{current:null},currentContextRef:{current:null}});function nCn(e){const{children:t,delay:n,timeoutMs:r=0}=e,s=g.useRef(n),a=g.useRef(n),i=g.useRef(null),l=g.useRef(null),c=_o();return o.jsx(Cgt.Provider,{value:g.useMemo(()=>({hasProvider:!0,delayRef:s,initialDelayRef:a,currentIdRef:i,timeoutMs:r,currentContextRef:l,timeout:c}),[r,c]),children:t})}function rCn(e,t={open:!1}){const{open:n}=t,r="rootStore"in e?e.rootStore:e,s=r.useState("floatingId"),a=g.useContext(Cgt),{currentIdRef:i,delayRef:l,timeoutMs:c,initialDelayRef:u,currentContextRef:d,hasProvider:f,timeout:p}=a,[h,m]=g.useState(!1);return Mt(()=>{function v(){m(!1),d.current?.setIsInstantPhase(!1),i.current=null,d.current=null,l.current=u.current}if(i.current&&!n&&i.current===s){if(m(!1),c){const y=s;return p.start(c,()=>{r.select("open")||i.current&&i.current!==y||v()}),()=>{p.clear()}}v()}},[n,s,i,l,c,u,d,p,r]),Mt(()=>{if(!n)return;const v=d.current,y=i.current;p.clear(),d.current={onOpenChange:r.setOpen,setIsInstantPhase:m},i.current=s,l.current={open:0,close:g7(u.current,"close")},y!==null&&y!==s?(m(!0),v?.setIsInstantPhase(!0),v?.onOpenChange(!1,Yt(Mo))):(m(!1),v?.setIsInstantPhase(!1))},[n,s,r,i,l,u,d,p]),Mt(()=>()=>{d.current=null},[d]),g.useMemo(()=>({hasProvider:f,delayRef:l,isInstantPhase:h}),[f,l,h])}function qr(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}function ny(...e){return()=>{for(let t=0;t<e.length;t+=1){const n=e[t];n&&n()}}}function Gu(e,t,n,r){const s=Nc(Egt).current;return aCn(s,e,t,n,r)&&Tgt(s,[e,t,n,r]),s.callback}function sCn(e){const t=Nc(Egt).current;return iCn(t,e)&&Tgt(t,e),t.callback}function Egt(){return{callback:null,cleanup:null,refs:[]}}function aCn(e,t,n,r,s){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==s}function iCn(e,t){return e.refs.length!==t.length||e.refs.some((n,r)=>n!==t[r])}function Tgt(e,t){if(e.refs=t,t.every(n=>n==null)){e.callback=null;return}e.callback=n=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),n!=null){const r=Array(t.length).fill(null);for(let s=0;s<t.length;s+=1){const a=t[s];if(a!=null)switch(typeof a){case"function":{const i=a(n);typeof i=="function"&&(r[s]=i);break}case"object":{a.current=n;break}}}e.cleanup=()=>{for(let s=0;s<t.length;s+=1){const a=t[s];if(a!=null)switch(typeof a){case"function":{const i=r[s];typeof i=="function"?i():a(null);break}case"object":{a.current=null;break}}}}}}}function eo(e){const t=Nc(oCn,e).current;return t.next=e,Mt(t.effect),t}function oCn(e){const t={current:e,next:e,effect:()=>{t.current=t.next}};return t}const Vwe={...FN},dJ=Vwe.useInsertionEffect,lCn=dJ&&dJ!==Vwe.useLayoutEffect?dJ:e=>e();function xt(e){const t=Nc(cCn).current;return t.next=e,lCn(t.effect),t.trampoline}function cCn(){const e={next:void 0,callback:uCn,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function uCn(){}const s6=null;let dCn=class{callbacks=[];callbacksCount=0;nextId=1;startId=1;isScheduled=!1;tick=t=>{this.isScheduled=!1;const n=this.callbacks,r=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,r>0)for(let s=0;s<n.length;s+=1)n[s]?.(t)};request(t){const n=this.nextId;return this.nextId+=1,this.callbacks.push(t),this.callbacksCount+=1,!this.isScheduled&&(requestAnimationFrame(this.tick),this.isScheduled=!0),n}cancel(t){const n=t-this.startId;n<0||n>=this.callbacks.length||(this.callbacks[n]=null,this.callbacksCount-=1)}};const a6=new dCn;class cf{static create(){return new cf}static request(t){return a6.request(t)}static cancel(t){return a6.cancel(t)}currentId=s6;request(t){this.cancel(),this.currentId=a6.request(()=>{this.currentId=s6,t()})}cancel=()=>{this.currentId!==s6&&(a6.cancel(this.currentId),this.currentId=s6)};disposeEffect=()=>this.cancel}function h1(){const e=Nc(cf.create).current;return Dwe(e.disposeEffect),e}function pr(e){return e?.ownerDocument||document}const jgt={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1},m1={...jgt,position:"fixed",top:0,left:0},QN={...jgt,position:"absolute"},g1=g.forwardRef(function(t,n){const[r,s]=g.useState();Mt(()=>{vgt&&s("button")},[]);const a={tabIndex:0,role:r};return o.jsx("span",{...t,ref:n,style:m1,"aria-hidden":r?void 0:!0,...a,"data-base-ui-focus-guard":""})});function i6(e,t,n){return Math.floor(e/t)!==n}function R$(e,t){return t<0||t>=e.length}function d8(e,t){return _u(e.current,{disabledIndices:t})}function zhe(e,t){return _u(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function _u(e,{startingIndex:t=-1,decrement:n=!1,disabledIndices:r,amount:s=1}={}){let a=t;do a+=n?-s:s;while(a>=0&&a<=e.length-1&&cx(e,a,r));return a}function Ngt(e,{event:t,orientation:n,loopFocus:r,onLoop:s,rtl:a,cols:i,disabledIndices:l,minIndex:c,maxIndex:u,prevIndex:d,stopEvent:f=!1}){let p=d,h;if(t.key===Bwe?h="up":t.key===QD&&(h="down"),h){const m=[],v=[];let y=!1,b=0;{let N=null,I=-1;e.forEach((A,R)=>{if(A==null)return;b+=1;const L=A.closest('[role="row"]');L&&(y=!0),(L!==N||I===-1)&&(N=L,I+=1,m[I]=[]),m[I].push(R),v[R]=I})}let x=!1,S=0;if(y)for(const N of m){const I=N.length;I>S&&(S=I),I!==i&&(x=!0)}const k=x&&b<e.length,_=S||i,C=N=>{if(!x||d===-1)return;const I=v[d];if(I==null)return;const A=m[I].indexOf(d),R=N==="up"?-1:1;for(let L=I+R,D=0;D<m.length;D+=1,L+=R){if(L<0||L>=m.length){if(!r||k)return;if(L=L<0?m.length-1:0,s){const H=Math.min(A,m[L].length-1),B=m[L][H]??m[L][0],U=s(t,d,B);L=v[U]??L}}const F=m[L];for(let H=Math.min(A,F.length-1);H>=0;H-=1){const B=F[H];if(!cx(e,B,l))return B}}},E=N=>{if(!k||d===-1)return;const I=d%_,A=N==="up"?-_:_,R=u-u%_,L=Ik(u/_)+1;for(let D=d-I+A,F=0;F<L;F+=1,D+=A){if(D<0||D>u){if(!r)return;D=D<0?R:0}const H=Math.min(D+_-1,u);for(let B=Math.min(D+I,H);B>=D;B-=1)if(!cx(e,B,l))return B}};f&&wc(t);const T=C(h)??E(h);if(T!==void 0)p=T;else if(d===-1)p=h==="up"?u:c;else if(p=_u(e,{startingIndex:d,amount:_,decrement:h==="up",disabledIndices:l}),r){if(h==="up"&&(d-_<c||p<0)){const N=d%_,I=u%_,A=u-(I-N);I===N?p=u:p=I>N?A:A-_,s&&(p=s(t,d,p))}h==="down"&&d+_>u&&(p=_u(e,{startingIndex:d%_-_,amount:_,disabledIndices:l}),s&&(p=s(t,d,p)))}R$(e,p)&&(p=d)}if(n==="both"){const m=Ik(d/i);t.key===(a?Vw:qw)&&(f&&wc(t),d%i!==i-1?(p=_u(e,{startingIndex:d,disabledIndices:l}),r&&i6(p,i,m)&&(p=_u(e,{startingIndex:d-d%i-1,disabledIndices:l}),s&&(p=s(t,d,p)))):r&&(p=_u(e,{startingIndex:d-d%i-1,disabledIndices:l}),s&&(p=s(t,d,p))),i6(p,i,m)&&(p=d)),t.key===(a?qw:Vw)&&(f&&wc(t),d%i!==0?(p=_u(e,{startingIndex:d,decrement:!0,disabledIndices:l}),r&&i6(p,i,m)&&(p=_u(e,{startingIndex:d+(i-d%i),decrement:!0,disabledIndices:l}),s&&(p=s(t,d,p)))):r&&(p=_u(e,{startingIndex:d+(i-d%i),decrement:!0,disabledIndices:l}),s&&(p=s(t,d,p))),i6(p,i,m)&&(p=d));const v=Ik(u/i)===m;R$(e,p)&&(r&&v?(p=t.key===(a?qw:Vw)?u:_u(e,{startingIndex:d-d%i-1,disabledIndices:l}),s&&(p=s(t,d,p))):p=d)}return p}function Igt(e,t,n){const r=[];let s=0;return e.forEach(({width:a,height:i},l)=>{let c=!1;for(n&&(s=0);!c;){const u=[];for(let d=0;d<a;d+=1)for(let f=0;f<i;f+=1)u.push(s+d+f*t);s%t+a<=t&&u.every(d=>r[d]==null)?(u.forEach(d=>{r[d]=l}),c=!0):s+=1}}),[...r]}function Agt(e,t,n,r,s){if(e===-1)return-1;const a=n.indexOf(e),i=t[e];switch(s){case"tl":return a;case"tr":return i?a+i.width-1:a;case"bl":return i?a+(i.height-1)*r:a;case"br":return n.lastIndexOf(e);default:return-1}}function Rgt(e,t){return t.flatMap((n,r)=>e.includes(n)?[r]:[])}function cx(e,t,n){if(typeof n=="function"?n(t):n?.includes(t)??!1)return!0;const s=e[t];return s?Wq(s)?!n&&(s.hasAttribute("disabled")||s.getAttribute("aria-disabled")==="true"):!0:!1}function fCn(e){return e.visibility==="hidden"||e.visibility==="collapse"}function Wq(e,t=e?qu(e):null){return!e||!e.isConnected||!t||fCn(t)?!1:typeof e.checkVisibility=="function"?e.checkVisibility():t.display!=="none"&&t.display!=="contents"}const pCn='a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]';function hCn(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const n=e.getRootNode();return yj(n)?n.host:null}function Bhe(e){for(const t of Array.from(e.children))if(Vu(t)==="summary")return t;return null}function mCn(e,t){const n=Bhe(t);return!!n&&(e===n||gn(n,e))}function Pgt(e){const t=e?Vu(e):"";return e!=null&&e.matches(pCn)&&(t!=="summary"||e.parentElement!=null&&Vu(e.parentElement)==="details"&&Bhe(e.parentElement)===e)&&(t!=="details"||Bhe(e)==null)&&(t!=="input"||e.type!=="hidden")}function $gt(e){if(!Pgt(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=hCn(t)){const n=t!==e,r=Vu(t)==="slot";if(t.hasAttribute("inert")||n&&Vu(t)==="details"&&!t.open&&!mCn(e,t)||t.hasAttribute("hidden")||!r&&!gCn(t,n))return!1}return!0}function gCn(e,t){const n=qu(e);return t?n.display!=="none":Wq(e,n)}function Mgt(e){const t=e.tabIndex;if(t<0){const n=Vu(e);if(n==="details"||n==="audio"||n==="video"||Ia(e)&&e.isContentEditable)return 0}return t}function fJ(e){if(Vu(e)!=="input")return null;const t=e;return t.type==="radio"&&t.name!==""?t:null}function vCn(e,t){const n=fJ(e);if(!n)return!0;const r=t.find(s=>{const a=fJ(s);return a?.name===n.name&&a.form===n.form&&a.checked});return r?r===n:t.find(s=>{const a=fJ(s);return a?.name===n.name&&a.form===n.form})===n}function Dgt(e){if(Ia(e)&&Vu(e)==="slot"){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return Ia(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function Lgt(e,t){Dgt(e).forEach(n=>{Pgt(n)&&t.push(n),Lgt(n,t)})}function Fgt(e,t,n){Dgt(e).forEach(r=>{Ia(r)&&r.matches(t)&&n.push(r),Fgt(r,t,n)})}function qwe(e){return $gt(e)&&Mgt(e)>=0}function zgt(e){const t=[];return Lgt(e,t),t.filter($gt)}function XD(e){const t=zgt(e);return t.filter(n=>Mgt(n)>=0&&vCn(n,t))}function Bgt(e,t){const n=XD(e),r=n.length;if(r===0)return;const s=xc(pr(e)),a=n.indexOf(s),i=a===-1?t===1?0:r-1:a+t;return n[i]}function Hwe(e){return Bgt(pr(e).body,1)||e}function Ugt(e){return Bgt(pr(e).body,-1)||e}function Vgt(e,t){if(!e)return null;const n=XD(pr(e).body),r=n.length;if(r===0)return null;const s=n.indexOf(e);if(s===-1)return null;const a=(s+t+r)%r;return n[a]}function yCn(e){return Vgt(e,1)}function bCn(e){return Vgt(e,-1)}function $T(e,t){const n=t||e.currentTarget,r=e.relatedTarget;return!r||!gn(n,r)}function xCn(e){XD(e).forEach(n=>{n.dataset.tabindex=n.getAttribute("tabindex")||"",n.setAttribute("tabindex","-1")})}function O5e(e){const t=[];Fgt(e,"[data-tabindex]",t),t.forEach(n=>{const r=n.dataset.tabindex;delete n.dataset.tabindex,r?n.setAttribute("tabindex",r):n.removeAttribute("tabindex")})}function v1(e,t,n=!0){return e.filter(s=>s.parentId===t).flatMap(s=>[...!n||s.context?.open?[s]:[],...v1(e,s.id,n)])}function _5e(e,t){let n=[],r=e.find(s=>s.id===t)?.parentId;for(;r;){const s=e.find(a=>a.id===r);r=s?.parentId,s&&(n=n.concat(s))}return n}function P$(e){return`data-base-ui-${e}`}let o6=0;function f8(e,t={}){const{preventScroll:n=!1,sync:r=!1,shouldFocus:s}=t;cancelAnimationFrame(o6);function a(){s&&!s()||e?.focus({preventScroll:n})}if(r)return a(),Sa;const i=requestAnimationFrame(a);return o6=i,()=>{o6===i&&(cancelAnimationFrame(i),o6=0)}}const pJ={inert:new WeakMap,"aria-hidden":new WeakMap},C5e="data-base-ui-inert",Uhe={inert:new WeakSet,"aria-hidden":new WeakSet};let uR=new WeakMap,hJ=0;function wCn(e){return Uhe[e]}function qgt(e){return e?yj(e)?e.host:qgt(e.parentNode):null}const mJ=(e,t)=>t.map(n=>{if(e.contains(n))return n;const r=qgt(n);return e.contains(r)?r:null}).filter(n=>n!=null),E5e=e=>{const t=new Set;return e.forEach(n=>{let r=n;for(;r&&!t.has(r);)t.add(r),r=r.parentNode}),t},T5e=(e,t,n)=>{const r=[],s=a=>{!a||n.has(a)||Array.from(a.children).forEach(i=>{Vu(i)!=="script"&&(t.has(i)?s(i):r.push(i))})};return s(e),r};function SCn(e,t,n,r,{mark:s=!0,markerIgnoreElements:a=[]}){const i=r?"inert":n?"aria-hidden":null;let l=null,c=null;const u=mJ(t,e),d=s?mJ(t,a):[],f=new Set(d),p=s?T5e(t,E5e(u),new Set(u)).filter(v=>!f.has(v)):[],h=[],m=[];if(i){const v=pJ[i],y=wCn(i);c=y,l=v;const b=mJ(t,Array.from(t.querySelectorAll("[aria-live]"))),x=u.concat(b);T5e(t,E5e(x),new Set(x)).forEach(k=>{const _=k.getAttribute(i),C=_!==null&&_!=="false",E=(v.get(k)||0)+1;v.set(k,E),h.push(k),E===1&&C&&y.add(k),C||k.setAttribute(i,i==="inert"?"":"true")})}return s&&p.forEach(v=>{const y=(uR.get(v)||0)+1;uR.set(v,y),m.push(v),y===1&&v.setAttribute(C5e,"")}),hJ+=1,()=>{l&&h.forEach(v=>{const b=(l.get(v)||0)-1;l.set(v,b),b||(!c?.has(v)&&i&&v.removeAttribute(i),c?.delete(v))}),s&&m.forEach(v=>{const y=(uR.get(v)||0)-1;uR.set(v,y),y||v.removeAttribute(C5e)}),hJ-=1,hJ||(pJ.inert=new WeakMap,pJ["aria-hidden"]=new WeakMap,Uhe.inert=new WeakSet,Uhe["aria-hidden"]=new WeakSet,uR=new WeakMap)}}function j5e(e,t={}){const{ariaHidden:n=!1,inert:r=!1,mark:s=!0,markerIgnoreElements:a=[]}=t,i=pr(e[0]).body;return SCn(e,i,n,r,{mark:s,markerIgnoreElements:a})}let N5e=0;function kCn(e,t="mui"){const[n,r]=g.useState(e),s=e||n;return g.useEffect(()=>{n==null&&(N5e+=1,r(`${t}-${N5e}`))},[n,t]),s}const I5e=Vwe.useId;function y1(e,t){if(I5e!==void 0){const n=I5e();return e??(t?`${t}-${n}`:n)}return kCn(e,t)}const OCn=parseInt(g.version,10);function Wwe(e){return OCn>=e}function A5e(e){if(!g.isValidElement(e))return null;const t=e,n=t.props;return(Wwe(19)?n?.ref:t.ref)??null}function Vhe(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}function _Cn(e,t){const n={};for(const r in e){const s=e[r];if(t?.hasOwnProperty(r)){const a=t[r](s);a!=null&&Object.assign(n,a);continue}s===!0?n[`data-${r.toLowerCase()}`]="":s&&(n[`data-${r.toLowerCase()}`]=s.toString())}return n}function CCn(e,t){return typeof e=="function"?e(t):e}function Hgt(e,t){return typeof e=="function"?e(t):e}const Zwe={};function Fo(e,t,n,r,s){if(!n&&!r&&!s&&!e)return y7(t);let a=y7(e);return t&&(a=jP(a,t)),n&&(a=jP(a,n)),r&&(a=jP(a,r)),s&&(a=jP(a,s)),a}function ECn(e){if(e.length===0)return Zwe;if(e.length===1)return y7(e[0]);let t=y7(e[0]);for(let n=1;n<e.length;n+=1)t=jP(t,e[n]);return t}function y7(e){return Gwe(e)?{...Zgt(e,Zwe)}:TCn(e)}function jP(e,t){return Gwe(t)?Zgt(t,e):jCn(e,t)}function TCn(e){const t={...e};for(const n in t){const r=t[n];Wgt(n,r)&&(t[n]=Ggt(r))}return t}function jCn(e,t){if(!t)return e;for(const n in t){const r=t[n];switch(n){case"style":{e[n]=Vhe(e.style,r);break}case"className":{e[n]=Qgt(e.className,r);break}default:Wgt(n,r)?e[n]=NCn(e[n],r):e[n]=r}}return e}function Wgt(e,t){const n=e.charCodeAt(0),r=e.charCodeAt(1),s=e.charCodeAt(2);return n===111&&r===110&&s>=65&&s<=90&&(typeof t=="function"||typeof t>"u")}function Gwe(e){return typeof e=="function"}function Zgt(e,t){return Gwe(e)?e(t):e??Zwe}function NCn(e,t){return t?e?(...n)=>{const r=n[0];if(Ygt(r)){const a=r;b7(a);const i=t(...n);return a.baseUIHandlerPrevented||e?.(...n),i}const s=t(...n);return e?.(...n),s}:Ggt(t):e}function Ggt(e){return e&&((...t)=>{const n=t[0];return Ygt(n)&&b7(n),e(...t)})}function b7(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function Qgt(e,t){return t?e?t+" "+e:t:e}function Ygt(e){return e!=null&&typeof e=="object"&&"nativeEvent"in e}function Rn(e,t,n={}){const r=t.render,s=ICn(t,n);if(n.enabled===!1)return null;const a=n.state??bs;return PCn(e,r,s,a)}function ICn(e,t={}){const{className:n,style:r,render:s}=e,{state:a=bs,ref:i,props:l,stateAttributesMapping:c,enabled:u=!0}=t,d=u?CCn(n,a):void 0,f=u?Hgt(r,a):void 0,p=u?_Cn(a,c):bs,h=u&&l?ACn(l):void 0,m=u?Vhe(p,h)??{}:bs;return typeof document<"u"&&(u?Array.isArray(i)?m.ref=sCn([m.ref,A5e(s),...i]):m.ref=Gu(m.ref,A5e(s),i):Gu(null,null)),u?(d!==void 0&&(m.className=Qgt(m.className,d)),f!==void 0&&(m.style=Vhe(m.style,f)),m):bs}function ACn(e){return Array.isArray(e)?ECn(e):Fo(void 0,e)}const RCn=Symbol.for("react.lazy");function PCn(e,t,n,r){if(t){if(typeof t=="function")return t(n,r);const s=Fo(n,t.props);s.ref=n.ref;let a=t;return a?.$$typeof===RCn&&(a=g.Children.toArray(t)[0]),g.cloneElement(a,s)}if(e&&typeof e=="string")return $Cn(e,n);throw new Error(kr(8))}function $Cn(e,t){return e==="button"?g.createElement("button",{type:"button",...t,key:t.key}):e==="img"?g.createElement("img",{alt:"",...t,key:t.key}):g.createElement(e,t)}const MCn=500,Kgt=500,DCn={style:{transition:"none"}},Qwe="data-base-ui-click-trigger",LCn="data-base-ui-swipe-ignore",FCn=`[${LCn}]`,Ywe={fallbackAxisSide:"none"},Zq={fallbackAxisSide:"end"},zCn={clipPath:"inset(50%)",position:"fixed",top:0,left:0},Xgt=g.createContext(null),Jgt=()=>g.useContext(Xgt),BCn=P$("portal");function evt(e={}){const{ref:t,container:n,componentProps:r=bs,elementProps:s}=e,a=y1(),l=Jgt()?.portalNode,[c,u]=g.useState(null),[d,f]=g.useState(null),p=xt(y=>{y!==null&&f(y)}),h=g.useRef(null);Mt(()=>{if(n===null){h.current&&(h.current=null,f(null),u(null));return}if(a==null)return;const y=(n&&(r0e(n)?n:n.current))??l??document.body;if(y==null){h.current&&(h.current=null,f(null),u(null));return}h.current!==y&&(h.current=y,f(null),u(y))},[n,l,a]);const m=Rn("div",r,{ref:[t,p],props:[{id:a,[BCn]:""},s]});return{portalNode:d,portalSubtree:c&&m?bi.createPortal(m,c):null}}const JD=g.forwardRef(function(t,n){const{render:r,className:s,style:a,children:i,container:l,renderGuards:c,...u}=t,{portalNode:d,portalSubtree:f}=evt({container:l,ref:n,componentProps:t,elementProps:u}),p=g.useRef(null),h=g.useRef(null),m=g.useRef(null),v=g.useRef(null),[y,b]=g.useState(null),x=g.useRef(!1),S=y?.modal,k=y?.open,_=typeof c=="boolean"?c:!!y&&!y.modal&&y.open&&!!d;g.useEffect(()=>{if(!d||S)return;function E(T){d&&T.relatedTarget&&$T(T)&&(T.type==="focusin"?x.current&&(O5e(d),x.current=!1):(xCn(d),x.current=!0))}return ny(qr(d,"focusin",E,!0),qr(d,"focusout",E,!0))},[d,S]),g.useEffect(()=>{!d||k!==!1||(O5e(d),x.current=!1)},[k,d]);const C=g.useMemo(()=>({beforeOutsideRef:p,afterOutsideRef:h,beforeInsideRef:m,afterInsideRef:v,portalNode:d,setFocusManagerState:b}),[d]);return o.jsxs(g.Fragment,{children:[f,o.jsxs(Xgt.Provider,{value:C,children:[_&&d&&o.jsx(g1,{"data-type":"outside",ref:p,onFocus:E=>{if($T(E,d))m.current?.focus();else{const T=y?y.domReference:null;Ugt(T)?.focus()}}}),_&&d&&o.jsx("span",{"aria-owns":d.id,style:zCn}),d&&bi.createPortal(i,d),_&&d&&o.jsx(g1,{"data-type":"outside",ref:h,onFocus:E=>{if($T(E,d))v.current?.focus();else{const T=y?y.domReference:null;Hwe(T)?.focus(),y?.closeOnFocusOut&&y?.onOpenChange(!1,Yt(_x,E.nativeEvent))}}})]})]})});function tvt(){const e=new Map;return{emit(t,n){e.get(t)?.forEach(r=>r(n))},on(t,n){e.has(t)||e.set(t,new Set),e.get(t).add(n)},off(t,n){e.get(t)?.delete(n)}}}class Kwe{nodesRef={current:[]};events=tvt();addNode(t){this.nodesRef.current.push(t)}removeNode(t){const n=this.nodesRef.current.findIndex(r=>r===t);n!==-1&&this.nodesRef.current.splice(n,1)}}const nvt=g.createContext(null),rvt=g.createContext(null),Jx=()=>g.useContext(nvt)?.id||null,Z1=e=>{const t=g.useContext(rvt);return e??t};function Gq(e){const t=y1(),n=Z1(e),r=Jx();return Mt(()=>{if(!t)return;const s={id:t,parentId:r};return n?.addNode(s),()=>{n?.removeNode(s)}},[n,t,r]),t}function Xwe(e){const{children:t,id:n}=e,r=Jx();return o.jsx(nvt.Provider,{value:g.useMemo(()=>({id:n,parentId:r}),[n,r]),children:t})}function Jwe(e){const{children:t,externalTree:n}=e,r=Nc(()=>n??new Kwe).current;return o.jsx(rvt.Provider,{value:r,children:t})}function jb(e){return e==null?e:"current"in e?e.current:e}function UCn(e,t){const n=ta(Ti(e));return e instanceof n.KeyboardEvent?"keyboard":e instanceof n.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof n.MouseEvent?t||(e.detail===0?"keyboard":"mouse"):""}const R5e=20;let Ew=[];function e1e(){Ew=Ew.filter(e=>e.deref()?.isConnected)}function VCn(e){e1e(),e&&Vu(e)!=="body"&&(Ew.push(new WeakRef(e)),Ew.length>R5e&&(Ew=Ew.slice(-R5e)))}function gJ(){return e1e(),Ew[Ew.length-1]?.deref()}function qCn(e){return e?qwe(e)?e:XD(e)[0]||e:null}function P5e(e,t){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex")||!t.current.includes("floating")&&!e.getAttribute("role")?.includes("dialog"))return;const r=zgt(e).filter(a=>{const i=a.getAttribute("data-tabindex")||"";return qwe(a)||a.hasAttribute("data-tabindex")&&!i.startsWith("-")}),s=e.getAttribute("tabindex");t.current.includes("floating")||r.length===0?s!=="0"&&e.setAttribute("tabindex","0"):(s!=="-1"||e.hasAttribute("data-tabindex")&&e.getAttribute("data-tabindex")!=="-1")&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function YN(e){const{context:t,children:n,disabled:r=!1,initialFocus:s=!0,returnFocus:a=!0,restoreFocus:i=!1,modal:l=!0,closeOnFocusOut:c=!0,openInteractionType:u="",nextFocusableElement:d,previousFocusableElement:f,beforeContentFocusGuardRef:p,externalTree:h,getInsideElements:m}=e,v="rootStore"in t?t.rootStore:t,y=v.useState("open"),b=v.useState("domReferenceElement"),x=v.useState("floatingElement"),{events:S,dataRef:k}=v.context,_=xt(()=>k.current.floatingContext?.nodeId),C=s===!1,E=Fhe(b)&&C,T=g.useRef(["content"]),N=eo(s),I=eo(a),A=eo(u),R=Z1(h),L=Jgt(),D=g.useRef(!1),F=g.useRef(!1),H=g.useRef(!1),B=g.useRef(null),U=g.useRef(""),V=g.useRef(""),M=g.useRef(null),G=g.useRef(null),q=Gu(M,p,L?.beforeInsideRef),$=Gu(G,L?.afterInsideRef),z=_o(),Z=_o(),K=h1(),ne=L!=null,ee=m7(x),J=xt((Y=ee)=>Y?XD(Y):[]),ae=xt(()=>m?.().filter(Y=>Y!=null)??[]);g.useEffect(()=>{if(r||!l)return;function Y(ue){ue.key==="Tab"&&gn(ee,xc(pr(ee)))&&J().length===0&&!E&&wc(ue)}const te=pr(ee);return qr(te,"keydown",Y)},[r,ee,l,E,J]),g.useEffect(()=>{if(r||!y)return;const Y=pr(ee);function te(){H.current=!1}function ue(ce){const me=Ti(ce),be=ae(),we=gn(x,me)||gn(b,me)||gn(L?.portalNode,me)||be.some(Oe=>Oe===me||gn(Oe,me));H.current=!we,V.current=ce.pointerType||"keyboard",me?.closest(`[${Qwe}]`)&&(F.current=!0)}function fe(){V.current="keyboard"}return ny(qr(Y,"pointerdown",ue,!0),qr(Y,"pointerup",te,!0),qr(Y,"pointercancel",te,!0),qr(Y,"keydown",fe,!0))},[r,x,b,ee,y,L,ae]),g.useEffect(()=>{if(r||!c)return;const Y=pr(ee);function te(){F.current=!0,Z.start(0,()=>{F.current=!1})}function ue(be){const we=Ti(be);qwe(we)&&(B.current=we)}function fe(be){const we=be.relatedTarget,Oe=be.currentTarget,ke=Ti(be);queueMicrotask(()=>{const Ne=_(),Pe=v.context.triggerElements,ie=ae(),re=we?.hasAttribute(P$("focus-guard"))&&[M.current,G.current,L?.beforeInsideRef.current,L?.afterInsideRef.current,L?.beforeOutsideRef.current,L?.afterOutsideRef.current,jb(f),jb(d)].includes(we),se=!(gn(b,we)||gn(x,we)||gn(we,x)||gn(L?.portalNode,we)||ie.some(de=>de===we||gn(de,we))||we!=null&&Pe.hasElement(we)||Pe.hasMatchingElement(de=>gn(de,we))||re||R&&(v1(R.nodesRef.current,Ne).find(de=>gn(de.context?.elements.floating,we)||gn(de.context?.elements.domReference,we))||_5e(R.nodesRef.current,Ne).find(de=>[de.context?.elements.floating,m7(de.context?.elements.floating)].includes(we)||de.context?.elements.domReference===we)));if(Oe===b&&ee&&P5e(ee,T),i&&Oe!==b&&!Wq(ke)&&xc(Y)===Y.body){if(Ia(ee)&&(ee.focus(),i==="popup")){K.request(()=>{ee.focus()});return}const de=J(),xe=B.current,Ce=(xe&&de.includes(xe)?xe:null)||de[de.length-1]||ee;Ia(Ce)&&Ce.focus()}if(k.current.insideReactTree){k.current.insideReactTree=!1;return}(E||!l)&&we&&se&&!F.current&&(E||we!==gJ())&&(D.current=!0,v.setOpen(!1,Yt(_x,be)))})}function ce(){H.current||(k.current.insideReactTree=!0,z.start(0,()=>{k.current.insideReactTree=!1}))}const me=Ia(b)?b:null;if(!(!x&&!me))return ny(me&&qr(me,"focusout",fe),me&&qr(me,"pointerdown",te),x&&qr(x,"focusin",ue),x&&qr(x,"focusout",fe),x&&L&&qr(x,"focusout",ce,!0))},[r,b,x,ee,l,R,L,v,c,i,J,E,_,T,k,z,Z,K,d,f,ae]),g.useEffect(()=>{if(r||!x||!y)return;const Y=Array.from(L?.portalNode?.querySelectorAll(`[${P$("portal")}]`)||[]),ue=(R?_5e(R.nodesRef.current,_()):[]).find(Oe=>Fhe(Oe.context?.elements.domReference||null))?.context?.elements.domReference,ce=[...[x,...Y,M.current,G.current,L?.beforeOutsideRef.current,L?.afterOutsideRef.current,...ae()],ue,jb(f),jb(d),E?b:null].filter(Oe=>Oe!=null),me=j5e(ce,{ariaHidden:l||E,mark:!1}),be=[x,...Y].filter(Oe=>Oe!=null),we=j5e(be);return()=>{we(),me()}},[y,r,b,x,l,L,E,R,_,d,f,ae]),Mt(()=>{if(!y||r||!Ia(ee))return;const Y=pr(ee),te=xc(Y);queueMicrotask(()=>{const ue=N.current,fe=typeof ue=="function"?ue(A.current||""):ue;if(fe===void 0||fe===!1||gn(ee,te))return;let me=null;const be=()=>(me==null&&(me=J(ee)),me[0]||ee);let we;fe===!0||fe===null?we=be():we=jb(fe),we=we||be();const Oe=gn(ee,xc(Y));f8(we,{preventScroll:we===ee,shouldFocus(){if(Oe)return!0;const ke=xc(Y);return!(ke!==we&&gn(ee,ke))}})})},[r,y,ee,J,N,A]),Mt(()=>{if(r||!ee)return;const Y=pr(ee),te=xc(Y);VCn(te);function ue(ce){if(ce.open||(U.current=UCn(ce.nativeEvent,V.current)),ce.reason===Ji&&ce.nativeEvent.type==="mouseleave"&&(D.current=!0),ce.reason===YD)if(ce.nested)D.current=!1;else if(zwe(ce.nativeEvent)||xgt(ce.nativeEvent))D.current=!1;else{let me=!1;pr(ee).createElement("div").focus({get preventScroll(){return me=!0,!1}}),me?D.current=!1:D.current=!0}}S.on("openchange",ue);function fe(){const ce=I.current;let me=typeof ce=="function"?ce(U.current):ce;if(me===void 0||me===!1)return null;if(me===null&&(me=!0),typeof me=="boolean")return b?.isConnected?b:gJ()||null;const be=b?.isConnected?b:gJ();return jb(me)||be||null}return()=>{S.off("openchange",ue);const ce=xc(Y),me=ae(),be=gn(x,ce)||me.some(ke=>ke===ce||gn(ke,ce))||R&&v1(R.nodesRef.current,_(),!1).some(ke=>gn(ke.context?.elements.floating,ce)),we=I.current,Oe=fe();queueMicrotask(()=>{const ke=qCn(Oe),Ne=typeof we!="boolean";we&&!D.current&&Ia(ke)&&(!(!Ne&&ke!==ce&&ce!==Y.body)||be)&&ke.focus({preventScroll:!0}),D.current=!1})}},[r,x,ee,I,S,R,b,_,ae]),Mt(()=>{if(!qq||y||!x)return;const Y=xc(pr(x));!Ia(Y)||!Hq(Y)||gn(x,Y)&&Y.blur()},[y,x]),Mt(()=>{if(!(r||!L))return L.setFocusManagerState({modal:l,closeOnFocusOut:c,open:y,onOpenChange:v.setOpen,domReference:b}),()=>{L.setFocusManagerState(null)}},[r,L,l,y,v,c,b]),Mt(()=>{if(!(r||!ee))return P5e(ee,T),()=>{queueMicrotask(e1e)}},[r,ee,T]);const pe=!r&&(l?!E:!0)&&(ne||l);return o.jsxs(g.Fragment,{children:[pe&&o.jsx(g1,{"data-type":"inside",ref:q,onFocus:Y=>{if(l){const te=J();f8(te[te.length-1])}else L?.portalNode&&(D.current=!1,$T(Y,L.portalNode)?Hwe(b)?.focus():jb(f??L.beforeOutsideRef)?.focus())}}),n,pe&&o.jsx(g1,{"data-type":"inside",ref:$,onFocus:Y=>{l?f8(J()[0]):L?.portalNode&&(c&&(D.current=!0),$T(Y,L.portalNode)?Ugt(b)?.focus():jb(d??L.afterOutsideRef)?.focus())}})]})}function D_(e,t={}){const{enabled:n=!0,event:r="click",toggle:s=!0,ignoreMouse:a=!1,stickIfOpen:i=!0,touchOpenDelay:l=0,reason:c=Rg}=t,u="rootStore"in e?e.rootStore:e,d=u.context.dataRef,f=g.useRef(void 0),p=h1(),h=_o(),m=g.useMemo(()=>{function v(b,x,S,k){const _=Yt(c,x,S);b&&k==="touch"&&l>0?h.start(l,()=>{u.setOpen(!0,_)}):u.setOpen(b,_)}function y(b,x,S){const k=d.current.openEvent,_=u.select("domReferenceElement")!==x;return b&&_||!b||!s?!0:k&&i?!S(k.type):!1}return{onPointerDown(b){f.current=b.pointerType},onMouseDown(b){const x=f.current,S=b.nativeEvent,k=u.select("open");if(b.button!==0||r==="click"||TO(x,!0)&&a)return;const _=y(k,b.currentTarget,T=>T==="click"||T==="mousedown"),C=Ti(S);if(Hq(C)){v(_,S,C,x);return}const E=b.currentTarget;p.request(()=>{v(_,S,E,x)})},onClick(b){if(r==="mousedown-only")return;const x=f.current;if(r==="mousedown"&&x){f.current=void 0;return}if(TO(x,!0)&&a)return;const S=u.select("open"),k=y(S,b.currentTarget,_=>_==="click"||_==="mousedown"||_==="keydown"||_==="keyup");v(k,b.nativeEvent,b.currentTarget,x)},onKeyDown(){f.current=void 0}}},[d,r,a,c,u,i,s,p,h,l]);return g.useMemo(()=>n?{reference:m}:bs,[n,m])}function HCn(e,t){let n=null,r=null,s=!1;return{contextElement:e||void 0,getBoundingClientRect(){const a=e?.getBoundingClientRect()||{width:0,height:0,x:0,y:0},i=t.axis==="x"||t.axis==="both",l=t.axis==="y"||t.axis==="both",c=["mouseenter","mousemove"].includes(t.dataRef.current.openEvent?.type||"")&&t.pointerType!=="touch";let u=a.width,d=a.height,f=a.x,p=a.y;return n==null&&t.x&&i&&(n=a.x-t.x),r==null&&t.y&&l&&(r=a.y-t.y),f-=n||0,p-=r||0,u=0,d=0,!s||c?(u=t.axis==="y"?a.width:0,d=t.axis==="x"?a.height:0,f=i&&t.x!=null?t.x:f,p=l&&t.y!=null?t.y:p):s&&!c&&(d=t.axis==="x"?a.height:d,u=t.axis==="y"?a.width:u),s=!0,{width:u,height:d,x:f,y:p,top:p,right:f+u,bottom:p+d,left:f}}}}function $5e(e){return e!=null&&e.clientX!=null}function WCn(e,t={}){const{enabled:n=!0,axis:r="both"}=t,s="rootStore"in e?e.rootStore:e,a=s.useState("open"),i=s.useState("floatingElement"),l=s.useState("domReferenceElement"),c=s.context.dataRef,u=g.useRef(!1),d=g.useRef(null),[f,p]=g.useState(),[h,m]=g.useState([]),v=xt(k=>{s.set("positionReference",k)}),y=xt((k,_,C)=>{u.current||c.current.openEvent&&!$5e(c.current.openEvent)||s.set("positionReference",HCn(C??l,{x:k,y:_,axis:r,dataRef:c,pointerType:f}))}),b=xt(k=>{a?d.current||(y(k.clientX,k.clientY,k.currentTarget),m([])):y(k.clientX,k.clientY,k.currentTarget)}),x=TO(f)?i:a;g.useEffect(()=>{if(!n){v(l);return}if(!x)return;function k(){d.current?.(),d.current=null}const _=ta(i);function C(E){const T=Ti(E);gn(i,T)?k():y(E.clientX,E.clientY)}return!c.current.openEvent||$5e(c.current.openEvent)?d.current=qr(_,"mousemove",C):v(l),k},[x,n,i,c,l,s,y,v,h]),g.useEffect(()=>()=>{s.set("positionReference",null)},[s]),g.useEffect(()=>{n&&!i&&(u.current=!1)},[n,i]),g.useEffect(()=>{!n&&a&&(u.current=!0)},[n,a]);const S=g.useMemo(()=>{function k(_){p(_.pointerType)}return{onPointerDown:k,onPointerEnter:k,onMouseMove:b,onMouseEnter:b}},[b]);return g.useMemo(()=>n?{reference:S,trigger:S}:{},[n,S])}const ZCn={intentional:"onClick",sloppy:"onPointerDown"};function GCn(){return!1}function QCn(e){return{escapeKey:typeof e=="boolean"?e:e?.escapeKey??!1,outsidePress:typeof e=="boolean"?e:e?.outsidePress??!0}}function L_(e,t={}){const{enabled:n=!0,escapeKey:r=!0,outsidePress:s=!0,outsidePressEvent:a="sloppy",referencePress:i=GCn,referencePressEvent:l="sloppy",bubbles:c,externalTree:u}=t,d="rootStore"in e?e.rootStore:e,f=d.useState("open"),p=d.useState("floatingElement"),{dataRef:h}=d.context,m=Z1(u),v=xt(typeof s=="function"?s:()=>!1),y=typeof s=="function"?v:s,b=y!==!1,x=xt(()=>a),{escapeKey:S,outsidePress:k}=QCn(c),_=g.useRef(!1),C=g.useRef(!1),E=g.useRef(!1),T=g.useRef(!1),N=g.useRef(""),I=g.useRef(null),A=_o(),R=_o(),L=xt(()=>{R.clear(),h.current.insideReactTree=!1}),D=xt($=>{const z=h.current.floatingContext?.nodeId;return(m?v1(m.nodesRef.current,z):[]).some(K=>K.context?.open&&!K.context.dataRef.current[$])}),F=xt($=>uJ($,d.select("floatingElement"))||uJ($,d.select("domReferenceElement"))),H=xt($=>{i()&&d.setOpen(!1,Yt(Rg,$.nativeEvent))}),B=xt($=>{if(!f||!n||!r||$.key!=="Escape"||T.current||!S&&D("__escapeKeyBubbles"))return;const z=H_n($)?$.nativeEvent:$,Z=Yt(M_,z);d.setOpen(!1,Z),Z.isCanceled||$.preventDefault(),!S&&!Z.isPropagationAllowed&&$.stopPropagation()}),U=xt(()=>{h.current.insideReactTree=!0,R.start(0,L)}),V=xt($=>{if(!f||!n||$.button!==0)return;const z=Ti($.nativeEvent);gn(d.select("floatingElement"),z)&&(_.current||(_.current=!0,C.current=!1))}),M=xt($=>{!f||!n||($.defaultPrevented||$.nativeEvent.defaultPrevented)&&_.current&&(C.current=!0)});g.useEffect(()=>{if(!f||!n)return;h.current.__escapeKeyBubbles=S,h.current.__outsidePressBubbles=k;const $=new pm,z=new pm;function Z(){$.clear(),T.current=!0}function K(){$.start(hq()?5:0,()=>{T.current=!1})}function ne(){E.current=!0,z.start(0,()=>{E.current=!1})}function ee(){_.current=!1,C.current=!1}function J(){const re=N.current,se=re==="pen"||!re?"mouse":re,de=x(),xe=typeof de=="function"?de():de;return typeof xe=="string"?xe:xe[se]}function ae(re){const se=J();return se==="intentional"&&re.type!=="click"||se==="sloppy"&&re.type==="click"}function pe(re){const se=h.current.floatingContext?.nodeId,de=m&&v1(m.nodesRef.current,se).some(xe=>uJ(re,xe.context?.elements.floating));return F(re)||de}function Y(re){if(ae(re)){re.type!=="click"&&!F(re)&&(z.clear(),E.current=!1),L();return}if(h.current.insideReactTree){L();return}const se=Ti(re),de=`[${P$("inert")}]`,xe=Cr(se)?se.getRootNode():null,Ce=Array.from((yj(xe)?xe:pr(d.select("floatingElement"))).querySelectorAll(de)),Re=d.context.triggerElements;if(se&&(Re.hasElement(se)||Re.hasMatchingElement(We=>gn(We,se))))return;let Me=Cr(se)?se:null;for(;Me&&!ty(Me);){const We=fy(Me);if(ty(We)||!Cr(We))break;Me=We}if(!(Ce.length&&Cr(se)&&!Z_n(se)&&!gn(se,d.select("floatingElement"))&&Ce.every(We=>!gn(Me,We)))){if(Ia(se)&&!("touches"in re)){const We=ty(se),je=qu(se),Ee=/auto|scroll/,_e=We||Ee.test(je.overflowX),Ie=We||Ee.test(je.overflowY),$e=_e&&se.clientWidth>0&&se.scrollWidth>se.clientWidth,Ve=Ie&&se.clientHeight>0&&se.scrollHeight>se.clientHeight,Je=je.direction==="rtl",nt=Ve&&(Je?re.offsetX<=se.offsetWidth-se.clientWidth:re.offsetX>se.clientWidth),Ft=$e&&re.offsetY>se.clientHeight;if(nt||Ft)return}if(!pe(re)){if(J()==="intentional"&&E.current){z.clear(),E.current=!1;return}typeof y=="function"&&!y(re)||D("__outsidePressBubbles")||(d.setOpen(!1,Yt(YD,re)),L())}}}function te(re){J()!=="sloppy"||re.pointerType==="touch"||!d.select("open")||!n||F(re)||Y(re)}function ue(re){if(J()!=="sloppy"||!d.select("open")||!n||F(re))return;const se=re.touches[0];se&&(I.current={startTime:Date.now(),startX:se.clientX,startY:se.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},A.start(1e3,()=>{I.current&&(I.current.dismissOnTouchEnd=!1,I.current.dismissOnMouseDown=!1)}))}function fe(re,se){const de=Ti(re);if(!de)return;const xe=qr(de,re.type,()=>{se(re),xe()})}function ce(re){N.current="touch",fe(re,ue)}function me(re){A.clear(),re.type==="pointerdown"&&(N.current=re.pointerType),!(re.type==="mousedown"&&I.current&&!I.current.dismissOnMouseDown)&&fe(re,se=>{se.type==="pointerdown"?te(se):Y(se)})}function be(re){if(!_.current)return;const se=C.current;if(ee(),J()==="intentional"){if(re.type==="pointercancel"){se&&ne();return}if(!pe(re)){if(se){ne();return}typeof y=="function"&&!y(re)||(z.clear(),E.current=!0,L())}}}function we(re){if(J()!=="sloppy"||!I.current||F(re))return;const se=re.touches[0];if(!se)return;const de=Math.abs(se.clientX-I.current.startX),xe=Math.abs(se.clientY-I.current.startY),Ce=Math.sqrt(de*de+xe*xe);Ce>5&&(I.current.dismissOnTouchEnd=!0),Ce>10&&(Y(re),A.clear(),I.current=null)}function Oe(re){fe(re,we)}function ke(re){J()!=="sloppy"||!I.current||F(re)||(I.current.dismissOnTouchEnd&&Y(re),A.clear(),I.current=null)}function Ne(re){fe(re,ke)}const Pe=pr(p),ie=ny(r&&ny(qr(Pe,"keydown",B),qr(Pe,"compositionstart",Z),qr(Pe,"compositionend",K)),b&&ny(qr(Pe,"click",me,!0),qr(Pe,"pointerdown",me,!0),qr(Pe,"pointerup",be,!0),qr(Pe,"pointercancel",be,!0),qr(Pe,"mousedown",me,!0),qr(Pe,"mouseup",be,!0),qr(Pe,"touchstart",ce,!0),qr(Pe,"touchmove",Oe,!0),qr(Pe,"touchend",Ne,!0)));return()=>{ie(),$.clear(),z.clear(),ee(),E.current=!1}},[h,p,r,b,y,f,n,S,k,B,L,x,D,F,m,d,A]),g.useEffect(L,[y,L]);const G=g.useMemo(()=>({onKeyDown:B,[ZCn[l]]:H,...l!=="intentional"&&{onClick:H}}),[B,H,l]),q=g.useMemo(()=>({onKeyDown:B,onPointerDown:M,onMouseDown:M,onClickCapture:U,onMouseDownCapture($){U(),V($)},onPointerDownCapture($){U(),V($)},onMouseUpCapture:U,onTouchEndCapture:U,onTouchMoveCapture:U}),[B,U,V,M]);return g.useMemo(()=>n?{reference:G,floating:q,trigger:G}:{},[n,G,q])}function x7(e,t,n,r){return{left:e,top:t,right:n,bottom:r,x:e,y:t,width:n-e,height:r-t}}function YCn(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function svt(e){const t=[];let n,r=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const l of Array.from(e).sort((c,u)=>c.top-u.top)){if(r=Math.min(r,l.left),s=Math.min(s,l.top),a=Math.max(a,l.right),i=Math.max(i,l.bottom),!n||l.top-n.top>n.height/2)t.push(YCn(l));else{const c=t[t.length-1];c.left=Math.min(c.left,l.left),c.right=Math.max(c.right,l.right),c.bottom=Math.max(c.bottom,l.bottom),c.width=c.right-c.left,c.height=c.bottom-c.top}n=l}return{lines:t,fallback:x7(r,s,a,i)}}function avt(e,t,n){return e.findIndex(r=>t>r.left-2&&t<r.right+2&&n>r.top-2&&n<r.bottom+2)}function M5e(e){return x7(e.left,e.top,e.right,e.bottom)}function KCn(e,t,n){const{lines:r}=svt(e.getClientRects());if(r.length<2)return;const s=avt(r,t,n);return{x:t,y:n,lineIndex:s===-1?void 0:s,element:e}}function XCn(e,t,n){const{lines:r,fallback:s}=svt(e.getClientRects());if(r.length<2)return null;const a=n?.x,i=n?.y,l=t[0];if(n?.lineIndex!=null&&r[n.lineIndex])return M5e(r[n.lineIndex]);if(a!=null&&i!=null){const m=avt(r,a,i);if(m!==-1)return M5e(r[m])}if(r.length===2&&r[0].left>r[1].right&&a!=null&&i!=null)return s;if(l==="t"||l==="b"){const m=r[0],v=r[r.length-1],y=l==="t"?m:v;return x7(y.left,m.top,y.right,v.bottom)}const c=l==="l";let u=r[0].left,d=r[0].right,f=c?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,p=r[0],h=r[0];for(const m of r){u=Math.min(u,m.left),d=Math.max(d,m.right);const v=c?m.left:m.right;c&&v<f||!c&&v>f?(f=v,p=m,h=m):v===f&&(h=m)}return x7(u,p.top,d,h.bottom)}function JCn(e){return"contextElement"in e&&e.contextElement?e.contextElement:Cr(e)?e:void 0}function eEn(e,t){function n(s){ivt(e,s.currentTarget,s.clientX,s.clientY)}function r(s){t||n(s)}return{onFocus(){e.current=void 0},onMouseEnter:n,onMouseMove:r}}function ivt(e,t,n,r){const s=KCn(t,n,r);return e.current=s,s}function tEn(e){return{name:"inline",async fn(t){const n=t.elements.reference;if(typeof n?.getClientRects!="function")return{};const r=JCn(n),s=e.current,a=s?.element===n||s?.element===r?s:void 0,i=XCn(n,t.placement,a);if(!i||typeof t.platform.getElementRects!="function")return{};const l=await t.platform.getElementRects({reference:{contextElement:r,getBoundingClientRect(){return i}},floating:t.elements.floating,strategy:t.strategy});return t.rects.reference.x===l.reference.x&&t.rects.reference.y===l.reference.y&&t.rects.reference.width===l.reference.width&&t.rects.reference.height===l.reference.height?{}:{reset:{rects:l}}}}}const dt=(e,t,n,r,s,a,...i)=>{if(i.length>0)throw new Error(kr(1));let l;if(e)l=e;else throw new Error("Missing arguments");return l};function nEn(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!="function")throw new TypeError(t)}function rEn(e,t=`expected an object, instead received ${typeof e}`){if(typeof e!="object")throw new TypeError(t)}function sEn(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(n=>typeof n=="function")){const n=e.map(r=>typeof r=="function"?`function ${r.name||"unnamed"}()`:typeof r).join(", ");throw new TypeError(`${t}[${n}]`)}}var D5e=e=>Array.isArray(e)?e:[e];function aEn(e){const t=Array.isArray(e[0])?e[0]:e;return sEn(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function iEn(e,t){const n=[],{length:r}=e;for(let s=0;s<r;s++)n.push(e[s].apply(null,t));return n}var oEn=class{constructor(e){this.value=e}deref(){return this.value}},lEn=typeof WeakRef<"u"?WeakRef:oEn,cEn=0,L5e=1;function l6(){return{s:cEn,v:void 0,o:null,p:null}}function ovt(e,t={}){let n=l6();const{resultEqualityCheck:r}=t;let s,a=0;function i(){let l=n;const{length:c}=arguments;for(let f=0,p=c;f<p;f++){const h=arguments[f];if(typeof h=="function"||typeof h=="object"&&h!==null){let m=l.o;m===null&&(l.o=m=new WeakMap);const v=m.get(h);v===void 0?(l=l6(),m.set(h,l)):l=v}else{let m=l.p;m===null&&(l.p=m=new Map);const v=m.get(h);v===void 0?(l=l6(),m.set(h,l)):l=v}}const u=l;let d;if(l.s===L5e)d=l.v;else if(d=e.apply(null,arguments),a++,r){const f=s?.deref?.()??s;f!=null&&r(f,d)&&(d=f,a!==0&&a--),s=typeof d=="object"&&d!==null||typeof d=="function"?new lEn(d):d}return u.s=L5e,u.v=d,d}return i.clearCache=()=>{n=l6(),i.resetResultsCount()},i.resultsCount=()=>a,i.resetResultsCount=()=>{a=0},i}function uEn(e,...t){const n=typeof e=="function"?{memoize:e,memoizeOptions:t}:e,r=(...s)=>{let a=0,i=0,l,c={},u=s.pop();typeof u=="object"&&(c=u,u=s.pop()),nEn(u,`createSelector expects an output function after the inputs, but received: [${typeof u}]`);const d={...n,...c},{memoize:f,memoizeOptions:p=[],argsMemoize:h=ovt,argsMemoizeOptions:m=[]}=d,v=D5e(p),y=D5e(m),b=aEn(s),x=f(function(){return a++,u.apply(null,arguments)},...v),S=h(function(){i++;const _=iEn(b,arguments);return l=x.apply(null,_),l},...y);return Object.assign(S,{resultFunc:u,memoizedResultFunc:x,dependencies:b,dependencyRecomputations:()=>i,resetDependencyRecomputations:()=>{i=0},lastResult:()=>l,recomputations:()=>a,resetRecomputations:()=>{a=0},memoize:f,argsMemoize:h})};return Object.assign(r,{withTypes:()=>r}),r}var ct=uEn(ovt),dEn=Object.assign((e,t=ct)=>{rEn(e,`createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof e}`);const n=Object.keys(e),r=n.map(a=>e[a]);return t(r,(...a)=>a.reduce((i,l,c)=>(i[n[c]]=l,i),{}))},{withTypes:()=>dEn}),vJ={exports:{}},yJ={};var F5e;function fEn(){if(F5e)return yJ;F5e=1;var e=LN();function t(f,p){return f===p&&(f!==0||1/f===1/p)||f!==f&&p!==p}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,s=e.useEffect,a=e.useLayoutEffect,i=e.useDebugValue;function l(f,p){var h=p(),m=r({inst:{value:h,getSnapshot:p}}),v=m[0].inst,y=m[1];return a(function(){v.value=h,v.getSnapshot=p,c(v)&&y({inst:v})},[f,h,p]),s(function(){return c(v)&&y({inst:v}),f(function(){c(v)&&y({inst:v})})},[f]),i(h),h}function c(f){var p=f.getSnapshot;f=f.value;try{var h=p();return!n(f,h)}catch{return!0}}function u(f,p){return p()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?u:l;return yJ.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,yJ}var z5e;function lvt(){return z5e||(z5e=1,vJ.exports=fEn()),vJ.exports}var t1e=lvt(),bJ={exports:{}},xJ={};var B5e;function pEn(){if(B5e)return xJ;B5e=1;var e=LN(),t=lvt();function n(u,d){return u===d&&(u!==0||1/u===1/d)||u!==u&&d!==d}var r=typeof Object.is=="function"?Object.is:n,s=t.useSyncExternalStore,a=e.useRef,i=e.useEffect,l=e.useMemo,c=e.useDebugValue;return xJ.useSyncExternalStoreWithSelector=function(u,d,f,p,h){var m=a(null);if(m.current===null){var v={hasValue:!1,value:null};m.current=v}else v=m.current;m=l(function(){function b(C){if(!x){if(x=!0,S=C,C=p(C),h!==void 0&&v.hasValue){var E=v.value;if(h(E,C))return k=E}return k=C}if(E=k,r(S,C))return E;var T=p(C);return h!==void 0&&h(E,T)?(S=C,E):(S=C,k=T)}var x=!1,S,k,_=f===void 0?null:f;return[function(){return b(d())},_===null?void 0:function(){return b(_())}]},[d,f,p,h]);var y=s(u,m[0],m[1]);return i(function(){v.hasValue=!0,v.value=y},[y]),c(y),y},xJ}var U5e;function hEn(){return U5e||(U5e=1,bJ.exports=pEn()),bJ.exports}var n1e=hEn();const mEn=Bl(n1e),gEn=Wwe(19),vEn=gEn?bEn:xEn;function yt(e,t,n,r,s){return vEn(e,t,n,r,s)}function yEn(e,t,n,r,s){const a=g.useCallback(()=>t(e.getSnapshot(),n,r,s),[e,t,n,r,s]);return t1e.useSyncExternalStore(e.subscribe,a,a)}D_n({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let n=0;n<e.syncHooks.length;n+=1){const r=e.syncHooks[n],s=r.selector(r.store.state,r.a1,r.a2,r.a3);(r.didChange||!Object.is(r.value,s))&&(t=!0,r.value=s,r.didChange=!1)}return t&&(e.syncTick+=1),e.syncTick})},after(e){e.syncHooks.length>0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const n=new Set;for(const s of e.syncHooks)n.add(s.store);const r=[];for(const s of n)r.push(s.subscribe(t));return()=>{for(const s of r)s()}}),t1e.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot))}});function bEn(e,t,n,r,s){const a=M_n();if(!a)return yEn(e,t,n,r,s);const i=a.syncIndex;a.syncIndex+=1;let l;return a.didInitialize?(l=a.syncHooks[i],(l.store!==e||l.selector!==t||!Object.is(l.a1,n)||!Object.is(l.a2,r)||!Object.is(l.a3,s))&&(l.store!==e&&(a.didChangeStore=!0),l.store=e,l.selector=t,l.a1=n,l.a2=r,l.a3=s,l.didChange=!0)):(l={store:e,selector:t,a1:n,a2:r,a3:s,value:t(e.getSnapshot(),n,r,s),didChange:!1},a.syncHooks.push(l)),l.value}function xEn(e,t,n,r,s){return n1e.useSyncExternalStoreWithSelector(e.subscribe,e.getSnapshot,e.getSnapshot,a=>t(a,n,r,s))}class r1e{constructor(t){this.state=t,this.listeners=new Set,this.updateTick=0}subscribe=t=>(this.listeners.add(t),()=>{this.listeners.delete(t)});getSnapshot=()=>this.state;setState(t){if(this.state===t)return;this.state=t,this.updateTick+=1;const n=this.updateTick;for(const r of this.listeners){if(n!==this.updateTick)return;r(t)}}update(t){for(const n in t)if(!Object.is(this.state[n],t[n])){this.setState({...this.state,...t});return}}set(t,n){Object.is(this.state[t],n)||this.setState({...this.state,[t]:n})}notifyAll(){const t={...this.state};this.setState(t)}use(t,n,r,s){return yt(this,t,n,r,s)}}class KN extends r1e{constructor(t,n={},r){super(t),this.context=n,this.selectors=r}useSyncedValue(t,n){g.useDebugValue(t);const r=this;Mt(()=>{r.state[t]!==n&&r.set(t,n)},[r,t,n])}useSyncedValueWithCleanup(t,n){const r=this;Mt(()=>(r.state[t]!==n&&r.set(t,n),()=>{r.set(t,void 0)}),[r,t,n])}useSyncedValues(t){const n=this,r=Object.values(t);Mt(()=>{n.update(t)},[n,...r])}useControlledProp(t,n){g.useDebugValue(t);const r=this,s=n!==void 0;Mt(()=>{s&&!Object.is(r.state[t],n)&&r.setState({...r.state,[t]:n})},[r,t,n,s])}select(t,n,r,s){const a=this.selectors[t];return a(this.state,n,r,s)}useState(t,n,r,s){return g.useDebugValue(t),yt(this,this.selectors[t],n,r,s)}useContextCallback(t,n){g.useDebugValue(t);const r=xt(n??Sa);this.context[t]=r}useStateSetter(t){const n=g.useRef(void 0);return n.current===void 0&&(n.current=r=>{this.set(t,r)}),n.current}observe(t,n){let r;typeof t=="function"?r=t:r=this.selectors[t];let s=r(this.state);return n(s,s,this),this.subscribe(a=>{const i=r(a);if(!Object.is(s,i)){const l=s;s=i,n(i,l,this)}})}}function wEn(){const[,e]=g.useState({});return g.useCallback(()=>{e({})},[])}const SEn={open:dt(e=>e.open),transitionStatus:dt(e=>e.transitionStatus),domReferenceElement:dt(e=>e.domReferenceElement),referenceElement:dt(e=>e.positionReference??e.referenceElement),floatingElement:dt(e=>e.floatingElement),floatingId:dt(e=>e.floatingId)};class Qq extends KN{constructor(t){const{syncOnly:n,nested:r,onOpenChange:s,triggerElements:a,...i}=t;super({...i,positionReference:i.referenceElement,domReferenceElement:i.referenceElement},{onOpenChange:s,dataRef:{current:{}},events:tvt(),nested:r,triggerElements:a},SEn),this.syncOnly=n}syncOpenEvent=(t,n)=>{(!t||!this.state.open||n!=null&&W_n(n))&&(this.context.dataRef.current.openEvent=t?n:void 0)};dispatchOpenChange=(t,n)=>{this.syncOpenEvent(t,n.event);const r={open:t,reason:n.reason,nativeEvent:n.event,nested:this.context.nested,triggerElement:n.trigger};this.context.events.emit("openchange",r)};setOpen=(t,n)=>{if(this.syncOnly){this.context.onOpenChange?.(t,n);return}this.dispatchOpenChange(t,n),this.context.onOpenChange?.(t,n)}}function cvt(e){const{popupStore:t,treatPopupAsFloatingElement:n=!1,floatingRootContext:r,floatingId:s,nested:a,onOpenChange:i}=e,l=t.useState("open"),c=t.useState("activeTriggerElement"),u=t.useState(n?"popupElement":"positionerElement"),d=t.context.triggerElements,f=i,p=g.useRef(null);r===void 0&&p.current===null&&(p.current=new Qq({open:l,transitionStatus:void 0,referenceElement:c,floatingElement:u,triggerElements:d,onOpenChange:f,floatingId:s,syncOnly:!0,nested:a}));const h=r??p.current;return t.useSyncedValue("floatingId",s),Mt(()=>{const m={open:l,floatingId:s,referenceElement:c,floatingElement:u};Cr(c)&&(m.domReferenceElement=c),h.state.positionReference===h.state.referenceElement&&(m.positionReference=c),h.update(m)},[l,s,c,u,h]),h.context.onOpenChange=f,h.context.nested=a,h}function Vg(e,t=!1,n=!1){const[r,s]=g.useState(e&&t?"idle":void 0),[a,i]=g.useState(e);return e&&!a&&(i(!0),s("starting")),!e&&a&&r!=="ending"&&!n&&s("ending"),!e&&!a&&r==="ending"&&s(void 0),Mt(()=>{if(!e&&a&&r!=="ending"&&n){const l=cf.request(()=>{s("ending")});return()=>{cf.cancel(l)}}},[e,a,r,n]),Mt(()=>{if(!e||t)return;const l=cf.request(()=>{s(void 0)});return()=>{cf.cancel(l)}},[t,e]),Mt(()=>{if(!e||!t)return;e&&a&&r!=="idle"&&s("starting");const l=cf.request(()=>{s("idle")});return()=>{cf.cancel(l)}},[t,e,a,r]),{mounted:a,setMounted:i,transitionStatus:r}}let Pg=(function(e){return e.startingStyle="data-starting-style",e.endingStyle="data-ending-style",e})({});const kEn={[Pg.startingStyle]:""},OEn={[Pg.endingStyle]:""},ac={transitionStatus(e){return e==="starting"?kEn:e==="ending"?OEn:null}};function Yq(e,t=!1,n=!0){const r=h1();return xt((s,a=null)=>{r.cancel();const i=jb(e);if(i==null)return;const l=i,c=()=>{bi.flushSync(s)};if(typeof l.getAnimations!="function"||globalThis.BASE_UI_ANIMATIONS_DISABLED){s();return}function u(){Promise.all(l.getAnimations().map(d=>d.finished)).then(()=>{a?.aborted||c()}).catch(()=>{if(n){a?.aborted||c();return}const d=l.getAnimations();!a?.aborted&&d.length>0&&d.some(f=>f.pending||f.playState!=="finished")&&u()})}if(t){const d=Pg.startingStyle;if(!l.hasAttribute(d)){r.request(u);return}const f=new MutationObserver(()=>{l.hasAttribute(d)||(f.disconnect(),u())});f.observe(l,{attributes:!0,attributeFilter:[d]}),a?.addEventListener("abort",()=>f.disconnect(),{once:!0});return}r.request(u)})}function ic(e){const{enabled:t=!0,open:n,ref:r,onComplete:s}=e,a=xt(s),i=Yq(r,n,!1);g.useEffect(()=>{if(!t)return;const l=new AbortController;return i(a,l.signal),()=>{l.abort()}},[t,n,a,i])}const Ay={tabIndex:-1,[Lhe]:""};function Kq(e,t,n=!1){const r=y1(),s=Jx()!=null,a=g.useRef(null);e===void 0&&a.current===null&&(a.current=t(r,s));const i=e??a.current;return cvt({popupStore:i,treatPopupAsFloatingElement:n,floatingRootContext:i.state.floatingRootContext,floatingId:r,nested:s,onOpenChange:i.setOpen}),{store:i,internalStore:a.current}}function uvt(e,t){const n=g.useRef(null),r=g.useRef(null);return g.useCallback(s=>{if(e===void 0)return;let a=!1;if(n.current!==null){const i=n.current,l=r.current,c=t.context.triggerElements.getById(i);l&&c===l&&(t.context.triggerElements.delete(i),a=!0),n.current=null,r.current=null}if(s!==null&&(n.current=e,r.current=s,t.context.triggerElements.add(e,s),a=!0),a){const i=t.context.triggerElements.size;t.select("open")&&t.state.triggerCount!==i&&t.set("triggerCount",i)}},[t,e])}function Xq(e,t,n){const r=n?.id??null;(r||t)&&(e.activeTriggerId=r,e.activeTriggerElement=n??null)}function e3(e,t,n,r){const s=n.useState("isMountedByTrigger",e),a=uvt(e,n),i=xt(l=>{if(a(l),!l)return;const c=n.select("open"),u=n.select("activeTriggerId");if(u===e){n.update({activeTriggerElement:l,...c?r:null});return}u==null&&c&&n.update({activeTriggerId:e,activeTriggerElement:l,...r})});return Mt(()=>{s&&n.update({activeTriggerElement:t.current,...r})},[s,n,t,...Object.values(r)]),{registerTrigger:i,isMountedByThisTrigger:s}}function t3(e){const t=e.useState("open"),n=e.useState("triggerCount");Mt(()=>{if(!t){e.state.triggerCount!==0&&e.set("triggerCount",0);return}const r=e.context.triggerElements.size,s={};if(e.state.triggerCount!==r&&(s.triggerCount=r),!e.select("activeTriggerId")&&r===1){const a=e.context.triggerElements.entries().next();if(!a.done){const[i,l]=a.value;s.activeTriggerId=i,s.activeTriggerElement=l}}(s.triggerCount!==void 0||s.activeTriggerId!==void 0)&&e.update(s)},[t,e,n])}function n3(e,t,n){const{mounted:r,setMounted:s,transitionStatus:a}=Vg(e);t.useSyncedValues({mounted:r,transitionStatus:a});const i=xt(()=>{s(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),n?.(),t.context.onOpenChangeComplete?.(!1)}),l=t.useState("preventUnmountingOnClose");return ic({enabled:r&&!e&&!l,open:e,ref:t.context.popupRef,onComplete(){e||i()}}),{forceUnmount:i,transitionStatus:a}}function r3(e,t){e.useSyncedValues(t),Mt(()=>()=>{e.update({activeTriggerProps:bs,inactiveTriggerProps:bs,popupProps:bs})},[e])}function dvt(e,t){Mt(()=>{!t&&e.state.openMethod!==null&&e.set("openMethod",null)},[t,e]),Mt(()=>()=>{e.state.openMethod!==null&&e.set("openMethod",null)},[e])}class F_{constructor(){this.elementsSet=new Set,this.idMap=new Map}add(t,n){const r=this.idMap.get(t);r!==n&&(r!==void 0&&this.elementsSet.delete(r),this.elementsSet.add(n),this.idMap.set(t,n))}delete(t){const n=this.idMap.get(t);n&&(this.elementsSet.delete(n),this.idMap.delete(t))}hasElement(t){return this.elementsSet.has(t)}hasMatchingElement(t){for(const n of this.elementsSet)if(t(n))return!0;return!1}getById(t){return this.idMap.get(t)}entries(){return this.idMap.entries()}elements(){return this.elementsSet.values()}get size(){return this.idMap.size}}function _En(){return new Qq({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new F_,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0})}function s3(){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:_En(),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:bs,inactiveTriggerProps:bs,popupProps:bs}}function Jq(e,t,n=!1){return new Qq({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:n,onOpenChange:void 0})}const d2=dt(e=>e.triggerIdProp??e.activeTriggerId),s1e=dt(e=>e.openProp??e.open),V5e=dt(e=>(e.popupElement?.id??e.floatingId)||void 0);function fvt(e,t){return t!==void 0&&s1e(e)&&d2(e)===t}function CEn(e,t){return fvt(e,t)?!0:t!==void 0&&s1e(e)&&d2(e)==null&&e.triggerCount===1}const a3={open:s1e,mounted:dt(e=>e.mounted),transitionStatus:dt(e=>e.transitionStatus),floatingRootContext:dt(e=>e.floatingRootContext),triggerCount:dt(e=>e.triggerCount),preventUnmountingOnClose:dt(e=>e.preventUnmountingOnClose),payload:dt(e=>e.payload),activeTriggerId:d2,activeTriggerElement:dt(e=>e.mounted?e.activeTriggerElement:null),popupId:V5e,isTriggerActive:dt((e,t)=>t!==void 0&&d2(e)===t),isOpenedByTrigger:dt((e,t)=>fvt(e,t)),isMountedByTrigger:dt((e,t)=>t!==void 0&&d2(e)===t&&e.mounted),triggerProps:dt((e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps),triggerPopupId:dt((e,t)=>CEn(e,t)?V5e(e):void 0),popupProps:dt(e=>e.popupProps),popupElement:dt(e=>e.popupElement),positionerElement:dt(e=>e.positionerElement)};function a1e(e){const{open:t=!1,onOpenChange:n,elements:r={}}=e,s=y1(),a=Jx()!=null,i=Nc(()=>new Qq({open:t,transitionStatus:void 0,onOpenChange:n,referenceElement:r.reference??null,floatingElement:r.floating??null,triggerElements:new F_,floatingId:s,syncOnly:!1,nested:a})).current;return Mt(()=>{const l={open:t,floatingId:s};r.reference!==void 0&&(l.referenceElement=r.reference,l.domReferenceElement=Cr(r.reference)?r.reference:null),r.floating!==void 0&&(l.floatingElement=r.floating),i.update(l)},[t,s,r.reference,r.floating,i]),i.context.onOpenChange=n,i.context.nested=a,i}function EEn(e={}){const{nodeId:t,externalTree:n}=e,r=a1e(e),s=e.rootContext||r,a=s.useState("referenceElement"),i=s.useState("floatingElement"),l=s.useState("domReferenceElement"),c=s.useState("open"),u=s.useState("floatingId"),[d,f]=g.useState(null),[p,h]=g.useState(void 0),[m,v]=g.useState(void 0),y=g.useRef(null),b=Z1(n),x=g.useMemo(()=>({reference:a,floating:i,domReference:l}),[a,i,l]),S=cct({...e,elements:{...x,...d&&{reference:d}}}),k=Cr(p)?p:null,_=m===void 0?s.state.floatingElement:m;s.useSyncedValue("referenceElement",p??null),s.useSyncedValue("domReferenceElement",p===void 0?l:k),s.useSyncedValue("floatingElement",_);const C=g.useCallback(R=>{const L=Cr(R)?{getBoundingClientRect:()=>R.getBoundingClientRect(),getClientRects:()=>R.getClientRects(),contextElement:R}:R;f(L),S.refs.setReference(L)},[S.refs]),E=g.useCallback(R=>{(Cr(R)||R===null)&&(y.current=R,h(R)),(Cr(S.refs.reference.current)||S.refs.reference.current===null||R!==null&&!Cr(R))&&S.refs.setReference(R)},[S.refs,h]),T=g.useCallback(R=>{v(R),S.refs.setFloating(R)},[S.refs]),N=g.useMemo(()=>({...S.refs,setReference:E,setFloating:T,setPositionReference:C,domReference:y}),[S.refs,E,T,C]),I=g.useMemo(()=>({...S.elements,domReference:l}),[S.elements,l]),A=g.useMemo(()=>({...S,dataRef:s.context.dataRef,open:c,onOpenChange:s.setOpen,events:s.context.events,floatingId:u,refs:N,elements:I,nodeId:t,rootStore:s}),[S,N,I,t,s,c,u]);return Mt(()=>{l&&(y.current=l)},[l]),Mt(()=>{s.context.dataRef.current.floatingContext=A;const R=b?.nodesRef.current.find(L=>L.id===t);R&&(R.context=A)}),g.useMemo(()=>({...S,context:A,refs:N,elements:I,rootStore:s}),[S,N,I,A,s])}const wJ=ygt&&vgt;function i1e(e,t={}){const{enabled:n=!0,delay:r}=t,s="rootStore"in e?e.rootStore:e,{events:a,dataRef:i}=s.context,l=g.useRef(!1),c=g.useRef(null),u=g.useRef(!0),d=_o();g.useEffect(()=>{const p=s.select("domReferenceElement");if(!n)return;const h=ta(p);function m(){const b=s.select("domReferenceElement");!s.select("open")&&Ia(b)&&b===xc(pr(b))&&(l.current=!0)}function v(){u.current=!0}function y(){u.current=!1}return ny(qr(h,"blur",m),wJ&&qr(h,"keydown",v,!0),wJ&&qr(h,"pointerdown",y,!0))},[s,n]),g.useEffect(()=>{if(!n)return;function p(h){if(h.reason===Rg||h.reason===M_){const m=s.select("domReferenceElement");Cr(m)&&(c.current=m,l.current=!0)}}return a.on("openchange",p),()=>{a.off("openchange",p)}},[a,n,s]);const f=g.useMemo(()=>{function p(){l.current=!1,c.current=null}return{onMouseLeave(){p()},onFocus(h){const m=h.currentTarget;if(l.current){if(c.current===m)return;p()}const v=Ti(h.nativeEvent);if(Cr(v)){if(wJ&&!h.relatedTarget){if(!u.current&&!Hq(v))return}else if(!Sgt(v))return}const y=h7(h.relatedTarget,s.context.triggerElements),{nativeEvent:b,currentTarget:x}=h,S=typeof r=="function"?r():r;if(s.select("open")&&y||S===0||S===void 0){s.setOpen(!0,Yt(Kk,b,x));return}d.start(S,()=>{l.current||s.setOpen(!0,Yt(Kk,b,x))})},onBlur(h){p();const m=h.relatedTarget,v=h.nativeEvent,y=Cr(m)&&m.hasAttribute(P$("focus-guard"))&&m.getAttribute("data-type")==="outside";d.start(0,()=>{const b=s.select("domReferenceElement"),x=xc(pr(b));!m&&x===b||gn(i.current.floatingContext?.refs.floating.current,x)||gn(b,x)||y||h7(m??x,s.context.triggerElements)||s.setOpen(!1,Yt(Kk,v))})}}},[i,r,s,d]);return g.useMemo(()=>n?{reference:f,trigger:f}:{},[n,f])}class o1e{constructor(){this.pointerType=void 0,this.interactedInside=!1,this.handler=void 0,this.blockMouseMove=!0,this.performedPointerEventsMutation=!1,this.pointerEventsScopeElement=null,this.pointerEventsReferenceElement=null,this.pointerEventsFloatingElement=null,this.restTimeoutPending=!1,this.openChangeTimeout=new pm,this.restTimeout=new pm,this.handleCloseOptions=void 0}static create(){return new o1e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose}const w7=new WeakMap;function S7(e){if(!e.performedPointerEventsMutation)return;const t=e.pointerEventsScopeElement;t&&w7.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty("pointer-events"),e.pointerEventsReferenceElement?.style.removeProperty("pointer-events"),e.pointerEventsFloatingElement?.style.removeProperty("pointer-events"),w7.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function pvt(e,t){const{scopeElement:n,referenceElement:r,floatingElement:s}=t,a=w7.get(n);a&&a!==e&&S7(a),S7(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=s,w7.set(n,e),n.style.pointerEvents="none",r.style.pointerEvents="auto",s.style.pointerEvents="auto"}function l1e(e){const t=e.context.dataRef.current,n=Nc(()=>t.hoverInteractionState??o1e.create()).current;return t.hoverInteractionState||(t.hoverInteractionState=n),Dwe(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function eH(e,t={}){const{enabled:n=!0,closeDelay:r=0,nodeId:s}=t,a="rootStore"in e?e.rootStore:e,i=a.useState("open"),l=a.useState("floatingElement"),c=a.useState("domReferenceElement"),{dataRef:u}=a.context,d=Z1(),f=Jx(),p=l1e(a),h=_o(),m=xt(()=>kgt(u.current.openEvent?.type,p.interactedInside)),v=xt(()=>Y_n(u.current.openEvent?.type)),y=xt(()=>{S7(p)});Mt(()=>{i||(p.pointerType=void 0,p.restTimeoutPending=!1,p.interactedInside=!1,y())},[i,p,y]),g.useEffect(()=>y,[y]),Mt(()=>{if(n&&i&&p.handleCloseOptions?.blockPointerEvents&&v()&&Cr(c)&&l){const b=c,x=l,S=pr(l),k=d?.nodesRef.current.find(T=>T.id===f)?.context?.elements.floating;k&&(k.style.pointerEvents="");const _=p.pointerEventsScopeElement!==x?p.pointerEventsScopeElement:null,C=k!==x?k:null,E=p.handleCloseOptions?.getScope?.()??_??C??b.closest("[data-rootownerid]")??S.body;return pvt(p,{scopeElement:E,referenceElement:b,floatingElement:x}),()=>{y()}}},[n,i,c,l,p,v,d,f,y]),g.useEffect(()=>{if(!n)return;function b(){return!!(d&&f&&v1(d.nodesRef.current,f).length>0)}function x(T){const N=g7(r,"close",p.pointerType),I=()=>{a.setOpen(!1,Yt(Ji,T)),d?.events.emit("floating.closed",T)};N?p.openChangeTimeout.start(N,I):(p.openChangeTimeout.clear(),I())}function S(T){const N=Ti(T);if(!G_n(N)){p.interactedInside=!1;return}p.interactedInside=N?.closest("[aria-haspopup]")!=null}function k(){p.openChangeTimeout.clear(),h.clear(),d?.events.off("floating.closed",C),y()}function _(T){if(b()&&d){d.events.on("floating.closed",C);return}if(h7(T.relatedTarget,a.context.triggerElements))return;const N=u.current.floatingContext?.nodeId??s,I=T.relatedTarget;if(!(d&&N&&Cr(I)&&v1(d.nodesRef.current,N,!1).some(R=>gn(R.context?.elements.floating,I)))){if(p.handler){p.handler(T);return}y(),m()||x(T)}}function C(T){!d||!f||b()||h.start(0,()=>{d.events.off("floating.closed",C),a.setOpen(!1,Yt(Ji,T)),d.events.emit("floating.closed",T)})}const E=l;return ny(E&&qr(E,"mouseenter",k),E&&qr(E,"mouseleave",_),E&&qr(E,"pointerdown",S,!0),()=>{d?.events.off("floating.closed",C)})},[n,l,a,u,r,s,m,y,p,d,f,h])}const TEn={current:null};function i3(e,t={}){const{enabled:n=!0,delay:r=0,handleClose:s=null,mouseOnly:a=!1,restMs:i=0,move:l=!0,triggerElementRef:c=TEn,externalTree:u,isActiveTrigger:d=!0,getHandleCloseContext:f,isClosing:p,shouldOpen:h}=t,m="rootStore"in e?e.rootStore:e,{dataRef:v,events:y}=m.context,b=Z1(u),x=l1e(m),S=g.useRef(!1),k=eo(s),_=eo(r),C=eo(i),E=eo(n),T=eo(h),N=eo(p),I=xt(()=>kgt(v.current.openEvent?.type,x.interactedInside)),A=xt(()=>T.current?.()!==!1),R=xt((F,H,B)=>{const U=m.context.triggerElements;if(U.hasElement(H))return!F||!gn(F,H);if(!Cr(B))return!1;const V=B;return U.hasMatchingElement(M=>gn(M,V))&&(!F||!gn(F,V))}),L=xt(()=>{if(!x.handler)return;pr(m.select("domReferenceElement")).removeEventListener("mousemove",x.handler),x.handler=void 0}),D=xt(()=>{S7(x)});return d&&(x.handleCloseOptions=k.current?.__options),g.useEffect(()=>L,[L]),g.useEffect(()=>{if(!n)return;function F(H){H.open?S.current=!1:(S.current=H.reason===Ji,L(),x.openChangeTimeout.clear(),x.restTimeout.clear(),x.blockMouseMove=!0,x.restTimeoutPending=!1)}return y.on("openchange",F),()=>{y.off("openchange",F)}},[n,y,x,L]),g.useEffect(()=>{if(!n)return;function F(V,M=!0){const G=g7(_.current,"close",x.pointerType);G?x.openChangeTimeout.start(G,()=>{m.setOpen(!1,Yt(Ji,V)),b?.events.emit("floating.closed",V)}):M&&(x.openChangeTimeout.clear(),m.setOpen(!1,Yt(Ji,V)),b?.events.emit("floating.closed",V))}const H=c.current??(d?m.select("domReferenceElement"):null);if(!Cr(H))return;function B(V){if(x.openChangeTimeout.clear(),x.blockMouseMove=!1,a&&!TO(x.pointerType))return;const M=x5e(C.current),G=g7(_.current,"open",x.pointerType),q=Ti(V),$=V.currentTarget??null,z=m.select("domReferenceElement");let Z=$;if(Cr(q)&&!m.context.triggerElements.hasElement(q)){for(const ue of m.context.triggerElements.elements())if(gn(ue,q)){Z=ue;break}}Cr($)&&Cr(z)&&!m.context.triggerElements.hasElement($)&&gn($,z)&&(Z=z);const K=Z==null?!1:R(z,Z,q),ne=m.select("open"),ee=N.current?.()??m.select("transitionStatus")==="ending",J=!ne&&ee&&S.current,ae=!K&&Cr(Z)&&Cr(z)&&gn(z,Z)&&J,pe=M>0&&!G,Y=K&&(ne||J)||ae,te=!ne||K;if(Y){A()&&m.setOpen(!0,Yt(Ji,V,Z));return}pe||(G?x.openChangeTimeout.start(G,()=>{te&&A()&&m.setOpen(!0,Yt(Ji,V,Z))}):te&&A()&&m.setOpen(!0,Yt(Ji,V,Z)))}function U(V){if(I()){D();return}L();const M=m.select("domReferenceElement"),G=pr(M);x.restTimeout.clear(),x.restTimeoutPending=!1;const q=v.current.floatingContext??f?.();if(h7(V.relatedTarget,m.context.triggerElements))return;if(k.current&&q){m.select("open")||x.openChangeTimeout.clear();const z=c.current;x.handler=k.current({...q,tree:b,x:V.clientX,y:V.clientY,onClose(){D(),L(),E.current&&!I()&&z===m.select("domReferenceElement")&&F(V,!0)}}),G.addEventListener("mousemove",x.handler),x.handler(V);return}(x.pointerType!=="touch"||!gn(m.select("floatingElement"),V.relatedTarget))&&F(V)}return l?ny(qr(H,"mousemove",B,{once:!0}),qr(H,"mouseenter",B),qr(H,"mouseleave",U)):ny(qr(H,"mouseenter",B),qr(H,"mouseleave",U))},[L,D,v,_,m,n,k,x,d,R,I,a,l,C,c,b,E,f,N,A]),g.useMemo(()=>{if(!n)return;function F(H){x.pointerType=H.pointerType}return{onPointerDown:F,onPointerEnter:F,onMouseMove(H){const{nativeEvent:B}=H,U=H.currentTarget,V=m.select("domReferenceElement"),M=m.select("open"),G=R(V,U,H.target);if(a&&!TO(x.pointerType))return;if(M&&G&&x.handleCloseOptions?.blockPointerEvents){const z=m.select("floatingElement");if(z){const Z=x.handleCloseOptions?.getScope?.()??U.ownerDocument.body;pvt(x,{scopeElement:Z,referenceElement:U,floatingElement:z})}}const q=x5e(C.current);if(M&&!G||q===0||!G&&x.restTimeoutPending&&H.movementX**2+H.movementY**2<2)return;x.restTimeout.clear();function $(){if(x.restTimeoutPending=!1,I())return;const z=m.select("open");!x.blockMouseMove&&(!z||G)&&A()&&m.setOpen(!0,Yt(Ji,B,U))}x.pointerType==="touch"?bi.flushSync(()=>{$()}):G&&M?$():(x.restTimeoutPending=!0,x.restTimeout.start(q,$))}}},[n,x,I,R,a,m,C,A])}const jEn="Escape";function tH(e,t,n){switch(e){case"vertical":return t;case"horizontal":return n;default:return t||n}}function c6(e,t){return tH(t,e===Bwe||e===QD,e===Vw||e===qw)}function SJ(e,t,n){return tH(t,e===QD,n?e===Vw:e===qw)||e==="Enter"||e===" "||e===""}function NEn(e,t,n){return tH(t,n?e===Vw:e===qw,e===QD)}function IEn(e,t,n,r){const s=n?e===qw:e===Vw,a=e===Bwe;return t==="both"||t==="horizontal"&&r&&r>1?e===jEn:tH(t,s,a)}function c1e(e,t){const{listRef:n,activeIndex:r,onNavigate:s=()=>{},enabled:a=!0,selectedIndex:i=null,allowEscape:l=!1,loopFocus:c=!1,nested:u=!1,rtl:d=!1,virtual:f=!1,focusItemOnOpen:p="auto",focusItemOnHover:h=!0,openOnArrowKeyDown:m=!0,disabledIndices:v=void 0,orientation:y="vertical",parentOrientation:b,cols:x=1,id:S,resetOnPointerLeave:k=!0,externalTree:_}=t,C="rootStore"in e?e.rootStore:e,E=C.useState("open"),T=C.useState("floatingElement"),N=C.useState("domReferenceElement"),I=C.context.dataRef,A=m7(T),R=Fhe(N),L=eo(A),D=Jx(),F=Z1(_),H=g.useRef(p),B=g.useRef(i??-1),U=g.useRef(null),V=g.useRef(!0),M=xt(ie=>{s(B.current===-1?null:B.current,ie)}),G=g.useRef(M),q=g.useRef(!!T),$=g.useRef(E),z=g.useRef(!1),Z=g.useRef(!1),K=g.useRef(null),ne=eo(v),ee=eo(E),J=eo(i),ae=eo(k),pe=h1(),Y=h1(),te=xt(()=>{function ie(xe){f?F?.events.emit("virtualfocus",xe):K.current=f8(xe,{sync:z.current,preventScroll:!0})}const re=n.current[B.current],se=Z.current;re&&ie(re),(z.current?xe=>xe():xe=>pe.request(xe))(()=>{const xe=n.current[B.current]||re;if(!xe)return;re||ie(xe),we&&(se||!V.current)&&xe.scrollIntoView?.({block:"nearest",inline:"nearest"})})});Mt(()=>{I.current.orientation=y},[I,y]),Mt(()=>{a&&(E&&T?(B.current=i??-1,H.current&&i!=null&&(Z.current=!0,M())):q.current&&(B.current=-1,G.current()))},[a,E,T,i,M]),Mt(()=>{if(a){if(!E){z.current=!1;return}if(T)if(r==null){if(z.current=!1,J.current!=null)return;if(q.current&&(B.current=-1,te()),(!$.current||!q.current)&&H.current&&(U.current!=null||H.current===!0&&U.current==null)){let ie=0;const re=()=>{n.current[0]==null?(ie<2&&(ie?de=>Y.request(de):queueMicrotask)(re),ie+=1):(B.current=U.current==null||SJ(U.current,y,d)||u?d8(n):zhe(n),U.current=null,M())};re()}}else R$(n.current,r)||(B.current=r,te(),Z.current=!1)}},[a,E,T,r,J,u,n,y,d,M,te,Y]),Mt(()=>{if(!a||T||!F||f||!q.current)return;const ie=F.nodesRef.current,re=ie.find(xe=>xe.id===D)?.context?.elements.floating,se=xc(pr(T)),de=ie.some(xe=>xe.context&&gn(xe.context.elements.floating,se));re&&!de&&V.current&&re.focus({preventScroll:!0})},[a,T,F,D,f]),Mt(()=>{G.current=M,$.current=E,q.current=!!T}),Mt(()=>{E||(U.current=null,H.current=p)},[E,p]);const ue=r!=null,fe=xt(ie=>{if(!ee.current)return;const re=n.current.indexOf(ie.currentTarget);re!==-1&&(B.current!==re||r!==re)&&(B.current=re,M(ie))}),ce=xt(()=>b??F?.nodesRef.current.find(ie=>ie.id===D)?.context?.dataRef?.current.orientation),me=xt(()=>d8(n,ne.current)),be=xt(ie=>{if(V.current=!1,z.current=!0,ie.which===229||!ee.current&&ie.currentTarget===L.current)return;if(u&&IEn(ie.key,y,d,x)){c6(ie.key,ce())||wc(ie),C.setOpen(!1,Yt(v7,ie.nativeEvent)),Ia(N)&&(f?F?.events.emit("virtualfocus",N):N.focus());return}const re=B.current,se=d8(n,v),de=zhe(n,v);if(R||(ie.key==="Home"&&(wc(ie),B.current=se,M(ie)),ie.key==="End"&&(wc(ie),B.current=de,M(ie))),x>1){const xe=Array.from({length:n.current.length},()=>({width:1,height:1})),Ce=Igt(xe,x,!1),Re=Ce.findIndex(je=>je!=null&&!cx(n.current,je,v)),Me=Ce.reduce((je,Ee,_e)=>Ee!=null&&!cx(n.current,Ee,v)?_e:je,-1),We=Ce[Ngt(Ce.map(je=>je!=null?n.current[je]:null),{event:ie,orientation:y,loopFocus:c,rtl:d,cols:x,disabledIndices:Rgt([...(typeof v!="function"?v:null)||n.current.map((je,Ee)=>cx(n.current,Ee,v)?Ee:void 0),void 0],Ce),minIndex:Re,maxIndex:Me,prevIndex:Agt(B.current>de?se:B.current,xe,Ce,x,ie.key===QD?"bl":ie.key===(d?Vw:qw)?"tr":"tl"),stopEvent:!0})];if(We!=null&&(B.current=We,M(ie)),y==="both")return}if(c6(ie.key,y)){if(wc(ie),E&&!f&&xc(ie.currentTarget.ownerDocument)===ie.currentTarget){B.current=SJ(ie.key,y,d)?se:de,M(ie);return}SJ(ie.key,y,d)?c?re>=de?l&&re!==n.current.length?B.current=-1:(z.current=!1,B.current=se):B.current=_u(n.current,{startingIndex:re,disabledIndices:v}):B.current=Math.min(de,_u(n.current,{startingIndex:re,disabledIndices:v})):c?re<=se?l&&re!==-1?B.current=n.current.length:(z.current=!1,B.current=de):B.current=_u(n.current,{startingIndex:re,decrement:!0,disabledIndices:v}):B.current=Math.max(se,_u(n.current,{startingIndex:re,decrement:!0,disabledIndices:v})),R$(n.current,B.current)&&(B.current=-1),M(ie)}}),we=g.useMemo(()=>({onFocus(re){z.current=!0,fe(re)},onClick:({currentTarget:re})=>re.focus({preventScroll:!0}),onMouseMove(re){z.current=!0,Z.current=!1,h&&fe(re)},onPointerLeave(re){if(!ee.current||!V.current||re.pointerType==="touch")return;z.current=!0;const se=re.relatedTarget;if(!(!h||n.current.includes(se))&&ae.current&&(K.current?.(),K.current=null,B.current=-1,M(re),!f)){const de=L.current,xe=xc(pr(de));de&&gn(de,xe)&&de.focus({preventScroll:!0})}}}),[fe,ee,L,h,n,M,ae,f]),Oe=g.useMemo(()=>f&&E&&ue&&{"aria-activedescendant":`${S}-${r}`},[f,E,ue,S,r]),ke=g.useMemo(()=>({"aria-orientation":y==="both"?void 0:y,...R?{}:Oe,onKeyDown(ie){if(ie.key==="Tab"&&ie.shiftKey&&E&&!f){const re=Ti(ie.nativeEvent);if(re&&!gn(L.current,re))return;wc(ie),C.setOpen(!1,Yt(_x,ie.nativeEvent)),Ia(N)&&N.focus();return}be(ie)},onPointerMove(){V.current=!0}}),[Oe,be,L,y,R,C,E,f,N]),Ne=g.useMemo(()=>{function ie(de){C.setOpen(!0,Yt(v7,de.nativeEvent,de.currentTarget))}function re(de){p==="auto"&&zwe(de.nativeEvent)&&(H.current=!f)}function se(de){H.current=p,p==="auto"&&xgt(de.nativeEvent)&&(H.current=!0)}return{onKeyDown(de){const xe=C.select("open");V.current=!1;const Ce=de.key.startsWith("Arrow"),Re=NEn(de.key,ce(),d),Me=c6(de.key,y),We=(u?Re:Me)||de.key==="Enter"||de.key.trim()==="";if(f&&xe)return be(de);if(!(!xe&&!m&&Ce)){if(We){const je=c6(de.key,ce());U.current=u&&je?null:de.key}if(u){Re&&(wc(de),xe?(B.current=me(),M(de)):ie(de));return}Me&&(J.current!=null&&(B.current=J.current),wc(de),!xe&&m?ie(de):be(de),xe&&M(de))}},onFocus(de){C.select("open")&&!f&&(B.current=-1,M(de))},onPointerDown:se,onPointerEnter:se,onMouseDown:re,onClick:re}},[be,p,me,u,M,C,m,y,ce,d,J,f]),Pe=g.useMemo(()=>({...Oe,...Ne}),[Oe,Ne]);return g.useMemo(()=>a?{reference:Pe,floating:ke,item:we,trigger:Ne}:{},[a,Pe,ke,Ne,we])}function u1e(e,t){const{listRef:n,elementsRef:r,activeIndex:s,onMatch:a,onTyping:i,enabled:l=!0,resetMs:c=750,selectedIndex:u=null}=t,d="rootStore"in e?e.rootStore:e,f=d.useState("open"),p=_o(),h=g.useRef(""),m=g.useRef(u??s??-1),v=g.useRef(null),y=xt(S=>{function k(R){const L=r?.current[R];return!L||Wq(L)}function _(R,L,D=0){if(R.length===0)return-1;const F=(D%R.length+R.length)%R.length,H=L.toLocaleLowerCase();for(let B=0;B<R.length;B+=1){const U=(F+B)%R.length;if(!(!R[U]?.toLocaleLowerCase().startsWith(H)||!k(U)))return U}return-1}const C=n.current;if(h.current.length>0&&S.key===" "&&(wc(S),i?.(!0)),h.current.length>0&&h.current[0]!==" "&&_(C,h.current)===-1&&S.key!==" "&&i?.(!1),C==null||S.key.length!==1||S.ctrlKey||S.metaKey||S.altKey)return;f&&S.key!==" "&&(wc(S),i?.(!0));const E=h.current==="";E&&(m.current=u??s??-1),C.every(R=>R?R[0]?.toLocaleLowerCase()!==R[1]?.toLocaleLowerCase():!0)&&h.current===S.key&&(h.current="",m.current=v.current),h.current+=S.key,p.start(c,()=>{h.current="",m.current=v.current,i?.(!1)});const I=((E?u??s??-1:m.current)??0)+1,A=_(C,h.current,I);A!==-1?(a?.(A),v.current=A):S.key!==" "&&(h.current="",i?.(!1))}),b=xt(S=>{const k=S.relatedTarget,_=d.select("domReferenceElement"),C=d.select("floatingElement");gn(_,k)||gn(C,k)||(p.clear(),h.current="",m.current=v.current,i?.(!1))});Mt(()=>{!f&&u!==null||(p.clear(),v.current=null,h.current!==""&&(h.current=""))},[f,u,p]),Mt(()=>{f&&h.current===""&&(m.current=u??s??-1)},[f,u,s]);const x=g.useMemo(()=>({onKeyDown:y,onBlur:b}),[y,b]);return g.useMemo(()=>l?{reference:x,floating:x}:{},[l,x])}const q5e=.1,AEn=q5e*q5e,ci=.5;function u6(e,t,n,r,s,a){return r>=t!=a>=t&&e<=(s-n)*(t-r)/(a-r)+n}function d6(e,t,n,r,s,a,i,l,c,u){let d=!1;return u6(e,t,n,r,s,a)&&(d=!d),u6(e,t,s,a,i,l)&&(d=!d),u6(e,t,i,l,c,u)&&(d=!d),u6(e,t,c,u,n,r)&&(d=!d),d}function REn(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function f6(e,t,n,r,s,a){const i=Math.min(n,s),l=Math.max(n,s),c=Math.min(r,a),u=Math.max(r,a);return e>=i&&e<=l&&t>=c&&t<=u}function o3(e={}){const{blockPointerEvents:t=!1}=e,n=new pm,r=({x:s,y:a,placement:i,elements:l,onClose:c,nodeId:u,tree:d})=>{const f=i?.split("-")[0];let p=!1,h=null,m=null,v=typeof performance<"u"?performance.now():0;function y(x,S){const k=performance.now(),_=k-v;if(h===null||m===null||_===0)return h=x,m=S,v=k,!1;const C=x-h,E=S-m,T=C*C+E*E,N=_*_*AEn;return h=x,m=S,v=k,T<N}function b(){n.clear(),c()}return function(S){n.clear();const k=l.domReference,_=l.floating;if(!k||!_||f==null||s==null||a==null)return;const{clientX:C,clientY:E}=S,T=Ti(S),N=S.type==="mouseleave",I=gn(_,T),A=gn(k,T);if(I&&(p=!0,!N))return;if(A&&(p=!1,!N)){p=!0;return}if(N&&Cr(S.relatedTarget)&&gn(_,S.relatedTarget))return;function R(){return!!(d&&v1(d.nodesRef.current,u).length>0)}function L(){R()||b()}if(R())return;const D=k.getBoundingClientRect(),F=_.getBoundingClientRect(),H=s>F.right-F.width/2,B=a>F.bottom-F.height/2,U=F.width>D.width,V=F.height>D.height,M=(U?D:F).left,G=(U?D:F).right,q=(V?D:F).top,$=(V?D:F).bottom;if(f==="top"&&a>=D.bottom-1||f==="bottom"&&a<=D.top+1||f==="left"&&s>=D.right-1||f==="right"&&s<=D.left+1){L();return}let z=!1;switch(f){case"top":z=f6(C,E,M,D.top+1,G,F.bottom-1);break;case"bottom":z=f6(C,E,M,F.top+1,G,D.bottom-1);break;case"left":z=f6(C,E,F.right-1,$,D.left+1,q);break;case"right":z=f6(C,E,D.right-1,$,F.left+1,q);break}if(z)return;if(p&&!REn(C,E,D)){L();return}if(!N&&y(C,E)){L();return}let Z=!1;switch(f){case"top":{const K=U?ci/2:ci*4,ne=U||H?s+K:s-K,ee=U?s-K:H?s+K:s-K,J=a+ci+1,ae=H||U?F.bottom-ci:F.top,pe=H?U?F.bottom-ci:F.top:F.bottom-ci;Z=d6(C,E,ne,J,ee,J,F.left,ae,F.right,pe);break}case"bottom":{const K=U?ci/2:ci*4,ne=U||H?s+K:s-K,ee=U?s-K:H?s+K:s-K,J=a-ci,ae=H||U?F.top+ci:F.bottom,pe=H?U?F.top+ci:F.bottom:F.top+ci;Z=d6(C,E,ne,J,ee,J,F.left,ae,F.right,pe);break}case"left":{const K=V?ci/2:ci*4,ne=V||B?a+K:a-K,ee=V?a-K:B?a+K:a-K,J=s+ci+1,ae=B||V?F.right-ci:F.left,pe=B?V?F.right-ci:F.left:F.right-ci;Z=d6(C,E,ae,F.top,pe,F.bottom,J,ne,J,ee);break}case"right":{const K=V?ci/2:ci*4,ne=V||B?a+K:a-K,ee=V?a-K:B?a+K:a-K,J=s-ci,ae=B||V?F.left+ci:F.right,pe=B?V?F.left+ci:F.right:F.left+ci;Z=d6(C,E,J,ne,J,ee,ae,F.top,pe,F.bottom);break}}Z?p||n.start(40,L):L()}};return r.__options={...e,blockPointerEvents:t},r}const PEn={...a3,disabled:dt(e=>e.disabled),instantType:dt(e=>e.instantType),isInstantPhase:dt(e=>e.isInstantPhase),trackCursorAxis:dt(e=>e.trackCursorAxis),disableHoverablePopup:dt(e=>e.disableHoverablePopup),lastOpenChangeReason:dt(e=>e.openChangeReason),closeOnClick:dt(e=>e.closeOnClick),closeDelay:dt(e=>e.closeDelay),hasViewport:dt(e=>e.hasViewport)};class d1e extends KN{constructor(t,n,r=!1){const s=new F_,a={...$En(),...t};a.floatingRootContext=Jq(s,n,r),super(a,{popupRef:g.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:s},PEn)}setOpen=(t,n)=>{const r=n.reason,s=r===Ji,a=t&&r===Kk,i=!t&&(r===Rg||r===M_);if(n.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},this.context.onOpenChange?.(t,n),n.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(t,n);const l=()=>{const c={open:t,openChangeReason:r};a?c.instantType="focus":i?c.instantType="dismiss":r===Ji&&(c.instantType=void 0),Xq(c,t,n.trigger),this.update(c)};s?bi.flushSync(l):l()};cancelPendingOpen(t){this.state.floatingRootContext.dispatchOpenChange(!1,Yt(Rg,t))}static useStore(t,n){return Kq(t,(s,a)=>new d1e(n,s,a)).store}}function $En(){return{...s3(),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:"none",disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,hasViewport:!1}}const MEn=Vq(function(t){const{disabled:n=!1,defaultOpen:r=!1,open:s,disableHoverablePopup:a=!1,trackCursorAxis:i="none",actionsRef:l,onOpenChange:c,onOpenChangeComplete:u,handle:d,triggerId:f,defaultTriggerId:p=null,children:h}=t,m=d1e.useStore(d?.store,{open:r,openProp:s,activeTriggerId:p,triggerIdProp:f});P_(()=>{s===void 0&&m.state.open===!1&&r===!0&&m.update({open:!0,activeTriggerId:p})}),m.useControlledProp("openProp",s),m.useControlledProp("triggerIdProp",f),m.useContextCallback("onOpenChange",c),m.useContextCallback("onOpenChangeComplete",u);const v=m.useState("open"),y=!n&&v,b=m.useState("activeTriggerId"),x=m.useState("mounted"),S=m.useState("payload");m.useSyncedValues({trackCursorAxis:i,disableHoverablePopup:a}),m.useSyncedValue("disabled",n),t3(m);const{forceUnmount:k,transitionStatus:_}=n3(y,m),C=m.useState("isInstantPhase"),E=m.useState("instantType"),T=m.useState("lastOpenChangeReason"),N=g.useRef(null);Mt(()=>{v&&n&&m.setOpen(!1,Yt(_gt))},[v,n,m]),Mt(()=>{_==="ending"&&T===Mo||_!=="ending"&&C?(E!=="delay"&&(N.current=E),m.set("instantType","delay")):N.current!==null&&(m.set("instantType",N.current),N.current=null)},[_,C,T,E,m]),Mt(()=>{y&&b==null&&m.set("payload",void 0)},[m,b,y]);const I=g.useCallback(()=>{m.setOpen(!1,Yt(KD))},[m]);g.useImperativeHandle(l,()=>({unmount:k,close:I}),[k,I]);const A=y||x||!n&&i!=="none";return o.jsxs(mgt.Provider,{value:m,children:[A&&o.jsx(DEn,{store:m,disabled:n,trackCursorAxis:i}),typeof h=="function"?h({payload:S}):h]})});function DEn({store:e,disabled:t,trackCursorAxis:n}){const r=e.useState("floatingRootContext"),s=L_(r,{enabled:!t,referencePress:()=>e.select("closeOnClick")}),a=WCn(r,{enabled:!t&&n!=="none",axis:n==="none"?void 0:n}),i=g.useMemo(()=>Fo(a.reference,s.reference),[a.reference,s.reference]),l=g.useMemo(()=>Fo(a.trigger,s.trigger),[a.trigger,s.trigger]),c=g.useMemo(()=>Fo(Ay,a.floating,s.floating),[a.floating,s.floating]);return r3(e,{activeTriggerProps:i,inactiveTriggerProps:l,popupProps:c}),null}let Od=(function(e){return e.open="data-open",e.closed="data-closed",e[e.startingStyle=Pg.startingStyle]="startingStyle",e[e.endingStyle=Pg.endingStyle]="endingStyle",e.anchorHidden="data-anchor-hidden",e.side="data-side",e.align="data-align",e})({}),k7=(function(e){return e.popupOpen="data-popup-open",e.pressed="data-pressed",e})({});const LEn={[k7.popupOpen]:""},FEn={[k7.popupOpen]:"",[k7.pressed]:""},zEn={[Od.open]:""},BEn={[Od.closed]:""},UEn={[Od.anchorHidden]:""},XN={open(e){return e?LEn:null}},$$={open(e){return e?FEn:null}},zf={open(e){return e?zEn:BEn},anchorHidden(e){return e?UEn:null}};function qi(e){return y1(e,"base-ui")}const hvt=g.createContext(void 0);function VEn(){return g.useContext(hvt)}let qEn=(function(e){return e[e.popupOpen=k7.popupOpen]="popupOpen",e.triggerDisabled="data-trigger-disabled",e})({});const HEn=600,mvt="data-base-ui-tooltip-trigger";function H5e(e){if("composedPath"in e){const n=e.composedPath();for(let r=0;r<n.length;r+=1){const s=n[r];if(Cr(s))return s}}const t=e.target;return Cr(t)?t:null}function WEn(e){let t=e;for(;t;){if(t.hasAttribute(mvt))return t;const n=t.parentElement;if(n){t=n;continue}const r=t.getRootNode();t="host"in r&&Cr(r.host)?r.host:null}return null}const W5e=Mwe(function(t,n){const{render:r,className:s,style:a,handle:i,payload:l,disabled:c,delay:u,closeOnClick:d=!0,closeDelay:f,id:p,...h}=t,m=GD(!0),v=i?.store??m;if(!v)throw new Error(kr(82));const y=qi(p),b=v.useState("isTriggerActive",y),x=v.useState("isOpenedByTrigger",y),S=v.useState("floatingRootContext"),k=g.useRef(null),_=u??HEn,C=f??0,{registerTrigger:E,isMountedByThisTrigger:T}=e3(y,k,v,{payload:l,closeOnClick:d,closeDelay:C}),N=VEn(),{delayRef:I,isInstantPhase:A,hasProvider:R}=rCn(S,{open:x}),L=l1e(S);v.useSyncedValue("isInstantPhase",A);const D=v.useState("disabled"),F=c??D,H=eo(F),B=v.useState("trackCursorAxis"),U=v.useState("disableHoverablePopup"),V=g.useRef(!1),M=_o(),G=g.useRef(void 0);function q(){const Y=N?.delay,te=typeof I.current=="object"?I.current.open:void 0;let ue=_;return R&&(te!==0?ue=u??Y??_:ue=0),ue}function $(Y){const te=k.current;if(!te||!Y)return!1;const ue=WEn(Y);return ue!==null&&ue!==te&&gn(te,ue)}function z(Y){const te=$(Y);return V.current=te,te&&(L.openChangeTimeout.clear(),L.restTimeout.clear(),L.restTimeoutPending=!1,M.clear()),te}const Z=i3(S,{enabled:!F,mouseOnly:!0,move:!1,handleClose:!U&&B!=="both"?o3():null,restMs:q,delay(){const Y=typeof I.current=="object"?I.current.close:void 0;let te=C;return f==null&&R&&(te=Y),{close:te}},triggerElementRef:k,isActiveTrigger:b,isClosing:()=>v.select("transitionStatus")==="ending",shouldOpen(){return!V.current}}),K=i1e(S,{enabled:!F}).reference,ne=Y=>{const te=V.current,ue=H5e(Y),fe=z(ue),ce=k.current,me=ce&&ue&&gn(ce,ue);if(fe&&v.select("open")&&v.select("lastOpenChangeReason")===Ji){v.setOpen(!1,Yt(Ji,Y));return}if(te&&!fe&&me&&!H.current&&!v.select("open")&&ce&&TO(G.current)){const be=()=>{!V.current&&!H.current&&!v.select("open")&&v.setOpen(!0,Yt(Ji,Y,ce))},we=q();we===0?(M.clear(),be()):M.start(we,be)}},ee=v.useState("triggerProps",T);return Rn("button",t,{state:{open:x},ref:[n,E,k],props:[Z,K,T||B!=="none"?ee:void 0,{onMouseOver(Y){ne(Y.nativeEvent)},onFocus(Y){$(H5e(Y.nativeEvent))&&Y.preventBaseUIHandler()},onMouseLeave(){V.current=!1,M.clear(),G.current=void 0},onPointerEnter(Y){G.current=Y.pointerType},onPointerDown(Y){G.current=Y.pointerType,v.set("closeOnClick",d),d&&!v.select("open")&&v.cancelPendingOpen(Y.nativeEvent)},onClick(Y){d&&!v.select("open")&&v.cancelPendingOpen(Y.nativeEvent)},id:y,[qEn.triggerDisabled]:F?"":void 0,[mvt]:F?void 0:""},h],stateAttributesMapping:XN})}),gvt=g.createContext(void 0);function ZEn(){const e=g.useContext(gvt);if(e===void 0)throw new Error(kr(70));return e}const vvt=g.forwardRef(function(t,n){const{children:r,container:s,className:a,render:i,style:l,...c}=t,{portalNode:u,portalSubtree:d}=evt({container:s,ref:n,componentProps:t,elementProps:c});return!d&&!u?null:o.jsxs(g.Fragment,{children:[d,u&&bi.createPortal(r,u)]})}),GEn=g.forwardRef(function(t,n){const{keepMounted:r=!1,...s}=t;return GD().useState("mounted")||r?o.jsx(gvt.Provider,{value:r,children:o.jsx(vvt,{ref:n,...s})}):null}),yvt=g.createContext(void 0);function bvt(){const e=g.useContext(yvt);if(e===void 0)throw new Error(kr(71));return e}const QEn=g.createContext(void 0);function Ry(){return g.useContext(QEn)?.direction??"ltr"}const YEn=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:s,rects:a,platform:i,elements:l,middlewareData:c}=t,{element:u,padding:d=0,offsetParent:f="real"}=dy(e,t)||{};if(u==null)return{};const p=n0e(d),h={x:n,y:r},m=dq(s),v=uq(m),y=await i.getDimensions(u),b=m==="y",x=b?"top":"left",S=b?"bottom":"right",k=b?"clientHeight":"clientWidth",_=a.reference[v]+a.reference[m]-h[m]-a.floating[v],C=h[m]-a.reference[m],E=f==="real"?await i.getOffsetParent?.(u):l.floating;let T=l.floating[k]||a.floating[v];(!T||!await i.isElement?.(E))&&(T=l.floating[k]||a.floating[v]);const N=_/2-C/2,I=T/2-y[v]/2-1,A=Math.min(p[x],I),R=Math.min(p[S],I),L=A,D=T-y[v]-R,F=T/2-y[v]/2+N,H=v9(L,F,D),B=!c.arrow&&Kx(s)!=null&&F!==H&&a.reference[v]/2-(F<L?A:R)-y[v]/2<0,U=B?F<L?F-L:F-D:0;return{[m]:h[m]+U,data:{[m]:H,centerOffset:F-H-U,...B&&{alignmentOffset:U}},reset:B}}}),KEn=(e,t)=>({...YEn(e),options:[e,t]}),XEn={name:"hide",async fn(e){const{width:t,height:n,x:r,y:s}=e.rects.reference,a=t===0&&n===0&&r===0&&s===0;return{data:{referenceHidden:(await mct().fn(e)).data?.referenceHidden||a}}}},p8={sideX:"left",sideY:"top"},nH={name:"adaptiveOrigin",async fn(e){const{x:t,y:n,rects:{floating:r},elements:{floating:s},platform:a,strategy:i,placement:l}=e,c=ta(s),u=c.getComputedStyle(s);if(!(u.transitionDuration!=="0s"&&u.transitionDuration!==""))return{x:t,y:n,data:p8};const f=await a.getOffsetParent?.(s);let p={width:0,height:0};if(i==="fixed"&&c?.visualViewport)p={width:c.visualViewport.width,height:c.visualViewport.height};else if(f===c){const x=pr(s);p={width:x.documentElement.clientWidth,height:x.documentElement.clientHeight}}else await a.isElement?.(f)&&(p=await a.getDimensions(f));const h=Cf(l);let m=t,v=n;h==="left"&&(m=p.width-(t+r.width)),h==="top"&&(v=p.height-(n+r.height));const y=h==="left"?"right":p8.sideX,b=h==="top"?"bottom":p8.sideY;return{x:m,y:v,data:{sideX:y,sideY:b}}}};function xvt(e,t,n){const r=e==="inline-start"||e==="inline-end";return{top:"top",right:r?n?"inline-start":"inline-end":"right",bottom:"bottom",left:r?n?"inline-end":"inline-start":"left"}[t]}function Z5e(e,t,n){const{rects:r,placement:s}=e;return{side:xvt(t,Cf(s),n),align:Kx(s)||"center",anchor:{width:r.reference.width,height:r.reference.height},positioner:{width:r.floating.width,height:r.floating.height}}}function JN(e){const{anchor:t,positionMethod:n="absolute",side:r="bottom",sideOffset:s=0,align:a="center",alignOffset:i=0,collisionBoundary:l,collisionPadding:c=5,sticky:u=!1,arrowPadding:d=5,disableAnchorTracking:f=!1,inline:p,keepMounted:h=!1,floatingRootContext:m,mounted:v,collisionAvoidance:y,shiftCrossAxis:b=!1,nodeId:x,adaptiveOrigin:S,lazyFlip:k=!1,externalTree:_}=e,[C,E]=g.useState(null);!v&&C!==null&&E(null);const T=y.side||"flip",N=y.align||"flip",I=y.fallbackAxisSide||"end",A=typeof t=="function"?t:void 0,R=xt(A),L=A?R:t,D=eo(t),F=eo(v),B=Ry()==="rtl",U=C||{top:"top",right:"right",bottom:"bottom",left:"left","inline-end":B?"left":"right","inline-start":B?"right":"left"}[r],V=a==="center"?U:`${U}-${a}`;let M=c;const G=1,q=r==="bottom"?G:0,$=r==="top"?G:0,z=r==="right"?G:0,Z=r==="left"?G:0;typeof M=="number"?M={top:M+q,right:M+Z,bottom:M+$,left:M+z}:M&&(M={top:(M.top||0)+q,right:(M.right||0)+Z,bottom:(M.bottom||0)+$,left:(M.left||0)+z});const K={boundary:l==="clipping-ancestors"?"clippingAncestors":l,padding:M},ne=g.useRef(null),ee=eo(s),J=eo(i),ae=typeof s!="function"?s:0,pe=typeof i!="function"?i:0,Y=[];p&&Y.push(p),Y.push(uct(Je=>{const nt=Z5e(Je,r,B),Ft=typeof ee.current=="function"?ee.current(nt):ee.current,Ot=typeof J.current=="function"?J.current(nt):J.current;return{mainAxis:Ft,crossAxis:Ot,alignmentAxis:Ot}},[ae,pe,B,r]));const te=N==="none"&&T!=="shift",ue=!te&&(u||b||T==="shift"),fe=T==="none"?null:pct({...K,padding:{top:M.top+G,right:M.right+G,bottom:M.bottom+G,left:M.left+G},mainAxis:!b&&T==="flip",crossAxis:N==="flip"?"alignment":!1,fallbackAxisSideDirection:I}),ce=te?null:dct(Je=>{const nt=pr(Je.elements.floating).documentElement;return{...K,rootBoundary:b?{x:0,y:0,width:nt.clientWidth,height:nt.clientHeight}:void 0,mainAxis:N!=="none",crossAxis:ue,limiter:u||b?void 0:fct(Ft=>{if(!ne.current)return{};const{width:Ot,height:Qt}=ne.current.getBoundingClientRect(),at=$h(Cf(Ft.placement)),_t=at==="y"?Ot:Qt,Zt=at==="y"?M.left+M.right:M.top+M.bottom;return{offset:_t/2+Zt/2}})}},[K,u,b,M,N]);T==="shift"||N==="shift"||a==="center"?Y.push(ce,fe):Y.push(fe,ce),Y.push(hct({...K,apply({elements:{floating:Je},availableWidth:nt,availableHeight:Ft,rects:Ot}){if(!F.current)return;const Qt=Je.style;Qt.setProperty("--available-width",`${nt}px`),Qt.setProperty("--available-height",`${Ft}px`);const at=ta(Je).devicePixelRatio||1,{x:_t,y:Zt,width:Qe,height:ot}=Ot.reference,pt=(Math.round((_t+Qe)*at)-Math.round(_t*at))/at,mt=(Math.round((Zt+ot)*at)-Math.round(Zt*at))/at;Qt.setProperty("--anchor-width",`${pt}px`),Qt.setProperty("--anchor-height",`${mt}px`)}}),KEn(Je=>({element:ne.current||pr(Je.elements.floating).createElement("div"),padding:d,offsetParent:"floating"}),[d]),{name:"transformOrigin",fn(Je){const{elements:nt,middlewareData:Ft,placement:Ot,rects:Qt,y:at}=Je,_t=Cf(Ot),Zt=$h(_t),Qe=ne.current,ot=Ft.arrow?.x||0,pt=Ft.arrow?.y||0,mt=Qe?.clientWidth||0,Rt=Qe?.clientHeight||0,hn=ot+mt/2,Ae=pt+Rt/2,Be=Math.abs(Ft.shift?.y||0),Le=Qt.reference.height/2,et=typeof s=="function"?s(Z5e(Je,r,B)):s,rt=Be>et,qt={top:`${hn}px calc(100% + ${et}px)`,bottom:`${hn}px ${-et}px`,left:`calc(100% + ${et}px) ${Ae}px`,right:`${-et}px ${Ae}px`}[_t],Pt=`${hn}px ${Qt.reference.y+Le-at}px`;return nt.floating.style.setProperty("--transform-origin",ue&&Zt==="y"&&rt?Pt:qt),{}}},XEn,S),Mt(()=>{!v&&m&&m.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[v,m]);const me=g.useMemo(()=>({elementResize:!f&&typeof ResizeObserver<"u",layoutShift:!f&&typeof IntersectionObserver<"u"}),[f]),{refs:be,elements:we,x:Oe,y:ke,middlewareData:Ne,update:Pe,placement:ie,context:re,isPositioned:se,floatingStyles:de}=EEn({rootContext:m,open:h?v:void 0,placement:V,middleware:Y,strategy:n,whileElementsMounted:h?void 0:(...Je)=>bpe(...Je,me),nodeId:x,externalTree:_}),{sideX:xe,sideY:Ce}=Ne.adaptiveOrigin||p8,Re=se?n:"fixed",Me=g.useMemo(()=>{const Je=S?{position:Re,[xe]:Oe,[Ce]:ke}:{position:Re,...de};return se||(Je.opacity=0),Je},[S,Re,xe,Oe,Ce,ke,de,se]),We=g.useRef(null);Mt(()=>{if(!v)return;const Je=D.current,nt=typeof Je=="function"?Je():Je,Ot=(G5e(nt)?nt.current:nt)||null||null;Ot!==We.current&&(be.setPositionReference(Ot),We.current=Ot)},[v,be,L,D]),g.useEffect(()=>{if(!v)return;const Je=D.current;typeof Je!="function"&&G5e(Je)&&Je.current!==We.current&&(be.setPositionReference(Je.current),We.current=Je.current)},[v,be,L,D]),g.useEffect(()=>{if(h&&v&&we.domReference&&we.floating)return bpe(we.domReference,we.floating,Pe,me)},[h,v,we,Pe,me]);const je=Cf(ie),Ee=xvt(r,je,B),_e=Kx(ie)||"center",Ie=!!Ne.hide?.referenceHidden;Mt(()=>{k&&v&&se&&E(je)},[k,v,se,je]);const $e=g.useMemo(()=>({position:"absolute",top:Ne.arrow?.y,left:Ne.arrow?.x}),[Ne.arrow]),Ve=Ne.arrow?.centerOffset!==0;return g.useMemo(()=>({positionerStyles:Me,arrowStyles:$e,arrowRef:ne,arrowUncentered:Ve,side:Ee,align:_e,physicalSide:je,anchorHidden:Ie,refs:be,context:re,isPositioned:se,update:Pe}),[Me,$e,ne,Ve,Ee,_e,je,Ie,be,re,se,Pe])}function G5e(e){return e!=null&&"current"in e}function z_(e){return e==="starting"?DCn:bs}function eI(e,t,{styles:n,transitionStatus:r,props:s,refs:a,hidden:i,inert:l=!1}){const c={...n};return l&&(c.pointerEvents="none"),Rn("div",e,{state:t,ref:a,props:[{role:"presentation",hidden:i,style:c},z_(r),s],stateAttributesMapping:zf})}const JEn=g.forwardRef(function(t,n){const{render:r,className:s,anchor:a,positionMethod:i="absolute",side:l="top",align:c="center",sideOffset:u=0,alignOffset:d=0,collisionBoundary:f="clipping-ancestors",collisionPadding:p=5,arrowPadding:h=5,sticky:m=!1,disableAnchorTracking:v=!1,collisionAvoidance:y=Zq,style:b,...x}=t,S=GD(),k=ZEn(),_=S.useState("open"),C=S.useState("mounted"),E=S.useState("trackCursorAxis"),T=S.useState("disableHoverablePopup"),N=S.useState("floatingRootContext"),I=S.useState("instantType"),A=S.useState("transitionStatus"),R=S.useState("hasViewport"),L=JN({anchor:a,positionMethod:i,floatingRootContext:N,mounted:C,side:l,sideOffset:u,align:c,alignOffset:d,collisionBoundary:f,collisionPadding:p,sticky:m,arrowPadding:h,disableAnchorTracking:v,keepMounted:k,collisionAvoidance:y,adaptiveOrigin:R?nH:void 0}),D=g.useMemo(()=>({open:_,side:L.side,align:L.align,anchorHidden:L.anchorHidden,instant:E!=="none"?"tracking-cursor":I}),[_,L.side,L.align,L.anchorHidden,E,I]),F=eI(t,D,{styles:L.positionerStyles,transitionStatus:A,props:x,refs:[n,S.useStateSetter("positionerElement")],hidden:!C,inert:!_||E==="both"||T});return o.jsx(yvt.Provider,{value:L,children:F})}),eTn={...zf,...ac},tTn=g.forwardRef(function(t,n){const{render:r,className:s,style:a,...i}=t,l=GD(),{side:c,align:u}=bvt(),d=l.useState("open"),f=l.useState("instantType"),p=l.useState("transitionStatus"),h=l.useState("popupProps"),m=l.useState("floatingRootContext"),v=l.useState("disabled"),y=l.useState("closeDelay");ic({open:d,ref:l.context.popupRef,onComplete(){d&&l.context.onOpenChangeComplete?.(!0)}}),eH(m,{enabled:!v,closeDelay:y});const b=l.useStateSetter("popupElement");return Rn("div",t,{state:{open:d,side:c,align:u,instant:f,transitionStatus:p},ref:[n,l.context.popupRef,b],props:[h,z_(p),i],stateAttributesMapping:eTn})}),nTn=g.forwardRef(function(t,n){const{render:r,className:s,style:a,...i}=t,l=GD(),{arrowRef:c,side:u,align:d,arrowUncentered:f,arrowStyles:p}=bvt(),h=l.useState("open"),m=l.useState("instantType");return Rn("div",t,{state:{open:h,side:u,align:d,uncentered:f,instant:m},ref:[n,c],props:[{style:p,"aria-hidden":!0},i],stateAttributesMapping:zf})}),rTn=function(t){const{delay:n,closeDelay:r,timeout:s=400}=t,a=g.useMemo(()=>({delay:n,closeDelay:r}),[n,r]),i=g.useMemo(()=>({open:n,close:r}),[n,r]);return o.jsx(hvt.Provider,{value:a,children:o.jsx(nCn,{delay:i,timeoutMs:s,children:t.children})})};function tI(e){return Wwe(19)?e:e?"true":void 0}function sTn(e){const[t,n]=g.useState({current:e,previous:null});return e!==t.current&&n({current:e,previous:t.current}),t.previous}function Q5e(e){const t=qu(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const s=Ia(e),a=s?e.offsetWidth:n,i=s?e.offsetHeight:r;return(vj(n)!==a||vj(r)!==i)&&(n=a,r=i),{width:n,height:r}}function Ul({delay:e,delayDuration:t,timeout:n,skipDelayDuration:r,...s}){const a=e??t,i=n??r;return o.jsx(rTn,{...a!==void 0?{delay:a}:{},...i!==void 0?{timeout:i}:{},...s})}const Tn=MEn,kn=g.forwardRef(({asChild:e,render:t,children:n,...r},s)=>e&&g.isValidElement(n)?o.jsx(W5e,{ref:s,render:n,...r}):o.jsx(W5e,{ref:s,render:t,...r,children:n}));kn.displayName="TooltipTrigger";const On=g.forwardRef(({className:e,side:t="top",sideOffset:n=8,align:r="center",alignOffset:s=0,arrowPadding:a=10,anchor:i,positionMethod:l,collisionBoundary:c,collisionPadding:u,sticky:d,disableAnchorTracking:f,collisionAvoidance:p,children:h,...m},v)=>{const y={side:t,sideOffset:n,align:r,alignOffset:s,arrowPadding:a,anchor:i,positionMethod:l,collisionBoundary:c,collisionPadding:u,sticky:d,disableAnchorTracking:f,collisionAvoidance:p};return o.jsx(GEn,{children:o.jsx(JEn,{className:"isolate z-100",...y,children:o.jsxs(tTn,{ref:v,role:"tooltip",className:X("relative z-100 flex origin-(--transform-origin) flex-col rounded-lg border border-border1 bg-surface3 px-2.5 py-1.5 text-ui-sm leading-ui-sm text-neutral5 shadow-dialog transition-[transform,scale,opacity] duration-150","data-[starting-style]:scale-95 data-[starting-style]:opacity-0","data-[ending-style]:scale-95 data-[ending-style]:opacity-0","data-[instant]:transition-none",e),...m,children:[h,o.jsx(nTn,{className:X("flex","data-[side=top]:-bottom-2 data-[side=top]:rotate-180","data-[side=bottom]:-top-2","data-[side=left]:right-[-10px] data-[side=left]:rotate-90","data-[side=right]:left-[-10px] data-[side=right]:-rotate-90"),children:o.jsx(aTn,{})})]})})})});On.displayName="TooltipContent";function aTn(){return o.jsxs("svg",{width:"12",height:"8",viewBox:"0 0 12 8",fill:"none",overflow:"visible",children:[o.jsx("path",{d:"M0 7L4 2Q6 0 8 2L12 7L12 8L0 8Z",className:"fill-surface3"}),o.jsx("path",{d:"M0 7.5L4 2.5Q6 0.5 8 2.5L12 7.5",className:"stroke-border1 fill-none",strokeWidth:"1",strokeLinejoin:"round",strokeLinecap:"round"})]})}const iTn={sm:"[&>svg]:h-icon-sm [&>svg]:w-icon-sm",default:"[&>svg]:h-icon-default [&>svg]:w-icon-default",lg:"[&>svg]:h-icon-lg [&>svg]:w-icon-lg"},qe=({children:e,className:t,size:n="default",...r})=>o.jsx("span",{className:X("block",iTn[n],t),...r,children:e}),NP={xs:"h-form-xs",sm:"h-form-sm",md:"h-form-md",default:"h-form-default",lg:"h-form-lg"},ff={xs:"h-form-xs text-ui-xs",sm:"h-form-sm text-ui-sm",md:"h-form-md text-ui-md",default:"h-form-default text-ui-md",lg:"h-form-lg text-ui-lg"},wvt={default:"data-[popup-open]:bg-surface5 data-[popup-open]:text-neutral6",outline:"data-[popup-open]:bg-surface3 data-[popup-open]:text-neutral6 data-[popup-open]:border-border2",ghost:"data-[popup-open]:bg-neutral6/5 data-[popup-open]:text-neutral6"},Xk="disabled:opacity-50 disabled:cursor-not-allowed",f1e="focus-visible:border-neutral5/50",Svt="focus-within:border-neutral5/50",oTn=`outline-hidden focus-visible:outline-hidden ${f1e}`,kvt="[&:hover:not(:focus-visible)]:border-border2",Ovt="[&:hover:not(:focus-within)]:border-border2",O7="bg-surface-overlay-soft border border-border1 text-neutral5 hover:text-neutral6 hover:bg-surface-overlay-strong "+kvt+" outline-hidden focus-visible:outline-hidden focus-visible:bg-surface-overlay-strong "+f1e,_vt="bg-transparent border border-border1 text-neutral5 hover:text-neutral6 "+kvt+" outline-hidden focus-visible:outline-hidden "+f1e,Cvt="border-0 bg-transparent outline-hidden focus-visible:outline-hidden",p6=X("gap-[.75em] rounded-full","[&>svg]:mx-[-.3em] [&>svg]:size-[1.1em]","[&:hover>svg]:opacity-100 [&>svg]:opacity-50","[&>svg]:transition-opacity [&>svg]:duration-normal [&>svg]:ease-out-custom"),l3=co(X("inline-flex cursor-pointer items-center justify-center leading-0","transition-all duration-normal ease-out-custom",Xk,oTn),{variants:{variant:{default:"border border-border2 bg-surface3 text-neutral6 hover:bg-surface5 hover:text-neutral6 active:bg-surface6",primary:"border border-transparent bg-neutral6 font-medium text-surface1 hover:bg-neutral6/90 active:bg-neutral6/80",destructive:"border border-transparent bg-accent2 font-medium text-white hover:bg-accent2/90 active:bg-accent2/80","destructive-ghost":"border border-transparent bg-transparent text-accent2 hover:bg-accent2/10 hover:text-accent2 active:bg-accent2/15",ghost:"border border-transparent bg-transparent text-neutral4 hover:bg-neutral6/5 hover:text-neutral6 active:bg-neutral6/10",outline:"border border-border1 bg-transparent text-neutral5 hover:bg-surface3 hover:text-neutral6 active:bg-surface4"},size:{xs:X(ff.xs,"px-[.8em]",p6),sm:X(ff.sm,"px-[.9em]",p6),md:X(ff.md,"px-[.9em]",p6),lg:X(ff.default,"px-[1em]",p6),"icon-xs":X(NP.xs,"w-form-xs rounded-full"),"icon-sm":X(NP.sm,"w-form-sm rounded-full"),"icon-md":X(NP.md,"w-form-md rounded-full"),"icon-lg":X(NP.lg,"w-form-lg rounded-full")}},defaultVariants:{variant:"default",size:"md"}}),lTn={"icon-xs":"sm","icon-sm":"sm","icon-md":"default","icon-lg":"lg"};function Evt(e){const t=[];return ze.Children.forEach(e,n=>{ze.isValidElement(n)&&n.type===ze.Fragment?t.push(...Evt(n.props.children)):t.push(n)}),t}function cTn(e){const t=Evt(e);return t.length>0&&t.every(n=>ze.isValidElement(n))}function uTn(e){return typeof e=="string"&&e.startsWith("icon-")}const le=ze.forwardRef(({className:e,as:t,size:n,variant:r="default",disabled:s,children:a,tooltip:i,"aria-label":l,...c},u)=>{const d=t||"button",f=uTn(n),p=n??"md",h=!f&&cTn(a),m=l??((f||h)&&typeof i=="string"?i:void 0),v=f?o.jsx(qe,{size:lTn[n],children:a}):a,y=o.jsx(d,{ref:u,disabled:s,"aria-label":m,"data-variant":r,className:X(l3({variant:r,size:p}),h&&"[&>svg]:opacity-75",e),...c,children:v});return i?o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:y}),o.jsx(On,{children:i})]}):y});le.displayName="Button";function Lr({iconSlot:e,titleSlot:t,descriptionSlot:n,actionSlot:r,className:s,as:a="h3"}){return o.jsxs("div",{className:X("flex flex-col items-center justify-center px-6 py-10 text-center","duration-normal transition-opacity ease-out-custom",s),children:[e&&o.jsx("div",{className:"mb-4",children:e}),o.jsx(a,{className:"text-ui-md text-neutral5 font-medium",children:t}),n&&o.jsx("p",{className:"text-ui-sm text-neutral3 mt-1.5 max-w-md",children:n}),r&&o.jsx("div",{className:"mt-5",children:r})]})}const dTn=co("spinner inline-block text-neutral6",{variants:{size:{sm:"size-4",md:"size-6"},variant:{default:"",pulse:""}},defaultVariants:{size:"md",variant:"default"}});function en({className:e,size:t="md",variant:n="default","aria-label":r="Loading",role:s="status",...a}){const i=t??"md",l=n??"default";return o.jsx("svg",{...a,role:s,"aria-label":r,"data-size":i,"data-variant":l,className:X(dTn({size:i,variant:l}),e),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",children:l==="pulse"?o.jsxs(o.Fragment,{children:[o.jsx("circle",{className:"spinner-pulse-ring",cx:"12",cy:"12",r:"7"}),o.jsx("circle",{className:"spinner-pulse-core",cx:"12",cy:"12",r:"5"})]}):o.jsx("circle",{className:"spinner-ring",cx:"12",cy:"12",r:"8.5"})})}function fTn(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const pTn=e=>{switch(e){case"success":return gTn;case"info":return yTn;case"warning":return vTn;case"error":return bTn;default:return null}},hTn=Array(12).fill(0),mTn=({visible:e,className:t})=>ze.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ze.createElement("div",{className:"sonner-spinner"},hTn.map((n,r)=>ze.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),gTn=ze.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ze.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),vTn=ze.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ze.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),yTn=ze.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ze.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),bTn=ze.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ze.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),xTn=ze.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ze.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ze.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),wTn=()=>{const[e,t]=ze.useState(document.hidden);return ze.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let qhe=1;class STn{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...s}=t,a=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:qhe++,i=this.toasts.find(c=>c.id===a),l=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(a)&&this.dismissedToasts.delete(a),i?this.toasts=this.toasts.map(c=>c.id===a?(this.publish({...c,...t,id:a,title:r}),{...c,...t,id:a,dismissible:l,title:r}):c):this.addToast({title:r,...s,dismissible:l,id:a}),a},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const s=Promise.resolve(t instanceof Function?t():t);let a=r!==void 0,i;const l=s.then(async u=>{if(i=["resolve",u],ze.isValidElement(u))a=!1,this.create({id:r,type:"default",message:u});else if(OTn(u)&&!u.ok){a=!1;const f=typeof n.error=="function"?await n.error(`HTTP error! status: ${u.status}`):n.error,p=typeof n.description=="function"?await n.description(`HTTP error! status: ${u.status}`):n.description,m=typeof f=="object"&&!ze.isValidElement(f)?f:{message:f};this.create({id:r,type:"error",description:p,...m})}else if(u instanceof Error){a=!1;const f=typeof n.error=="function"?await n.error(u):n.error,p=typeof n.description=="function"?await n.description(u):n.description,m=typeof f=="object"&&!ze.isValidElement(f)?f:{message:f};this.create({id:r,type:"error",description:p,...m})}else if(n.success!==void 0){a=!1;const f=typeof n.success=="function"?await n.success(u):n.success,p=typeof n.description=="function"?await n.description(u):n.description,m=typeof f=="object"&&!ze.isValidElement(f)?f:{message:f};this.create({id:r,type:"success",description:p,...m})}}).catch(async u=>{if(i=["reject",u],n.error!==void 0){a=!1;const d=typeof n.error=="function"?await n.error(u):n.error,f=typeof n.description=="function"?await n.description(u):n.description,h=typeof d=="object"&&!ze.isValidElement(d)?d:{message:d};this.create({id:r,type:"error",description:f,...h})}}).finally(()=>{a&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),c=()=>new Promise((u,d)=>l.then(()=>i[0]==="reject"?d(i[1]):u(i[1])).catch(d));return typeof r!="string"&&typeof r!="number"?{unwrap:c}:Object.assign(r,{unwrap:c})},this.custom=(t,n)=>{const r=n?.id||qhe++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const af=new STn,kTn=(e,t)=>{const n=t?.id||qhe++;return af.addToast({title:e,...t,id:n}),n},OTn=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",_Tn=kTn,CTn=()=>af.toasts,ETn=()=>af.getActiveToasts(),iu=Object.assign(_Tn,{success:af.success,info:af.info,warning:af.warning,error:af.error,custom:af.custom,message:af.message,promise:af.promise,dismiss:af.dismiss,loading:af.loading},{getHistory:CTn,getToasts:ETn});fTn("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function h6(e){return e.label!==void 0}const TTn=3,jTn="24px",NTn="16px",Y5e=4e3,ITn=356,ATn=14,RTn=45,PTn=200;function uv(...e){return e.filter(Boolean).join(" ")}function $Tn(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const MTn=e=>{var t,n,r,s,a,i,l,c,u;const{invert:d,toast:f,unstyled:p,interacting:h,setHeights:m,visibleToasts:v,heights:y,index:b,toasts:x,expanded:S,removeToast:k,defaultRichColors:_,closeButton:C,style:E,cancelButtonStyle:T,actionButtonStyle:N,className:I="",descriptionClassName:A="",duration:R,position:L,gap:D,expandByDefault:F,classNames:H,icons:B,closeButtonAriaLabel:U="Close toast"}=e,[V,M]=ze.useState(null),[G,q]=ze.useState(null),[$,z]=ze.useState(!1),[Z,K]=ze.useState(!1),[ne,ee]=ze.useState(!1),[J,ae]=ze.useState(!1),[pe,Y]=ze.useState(!1),[te,ue]=ze.useState(0),[fe,ce]=ze.useState(0),me=ze.useRef(f.duration||R||Y5e),be=ze.useRef(null),we=ze.useRef(null),Oe=b===0,ke=b+1<=v,Ne=f.type,Pe=f.dismissible!==!1,ie=f.className||"",re=f.descriptionClassName||"",se=ze.useMemo(()=>y.findIndex(at=>at.toastId===f.id)||0,[y,f.id]),de=ze.useMemo(()=>{var at;return(at=f.closeButton)!=null?at:C},[f.closeButton,C]),xe=ze.useMemo(()=>f.duration||R||Y5e,[f.duration,R]),Ce=ze.useRef(0),Re=ze.useRef(0),Me=ze.useRef(0),We=ze.useRef(null),[je,Ee]=L.split("-"),_e=ze.useMemo(()=>y.reduce((at,_t,Zt)=>Zt>=se?at:at+_t.height,0),[y,se]),Ie=wTn(),$e=f.invert||d,Ve=Ne==="loading";Re.current=ze.useMemo(()=>se*D+_e,[se,_e]),ze.useEffect(()=>{me.current=xe},[xe]),ze.useEffect(()=>{z(!0)},[]),ze.useEffect(()=>{const at=we.current;if(at){const _t=at.getBoundingClientRect().height;return ce(_t),m(Zt=>[{toastId:f.id,height:_t,position:f.position},...Zt]),()=>m(Zt=>Zt.filter(Qe=>Qe.toastId!==f.id))}},[m,f.id]),ze.useLayoutEffect(()=>{if(!$)return;const at=we.current,_t=at.style.height;at.style.height="auto";const Zt=at.getBoundingClientRect().height;at.style.height=_t,ce(Zt),m(Qe=>Qe.find(pt=>pt.toastId===f.id)?Qe.map(pt=>pt.toastId===f.id?{...pt,height:Zt}:pt):[{toastId:f.id,height:Zt,position:f.position},...Qe])},[$,f.title,f.description,m,f.id,f.jsx,f.action,f.cancel]);const Je=ze.useCallback(()=>{K(!0),ue(Re.current),m(at=>at.filter(_t=>_t.toastId!==f.id)),setTimeout(()=>{k(f)},PTn)},[f,k,m,Re]);ze.useEffect(()=>{if(f.promise&&Ne==="loading"||f.duration===1/0||f.type==="loading")return;let at;return S||h||Ie?(()=>{if(Me.current<Ce.current){const Qe=new Date().getTime()-Ce.current;me.current=me.current-Qe}Me.current=new Date().getTime()})():me.current!==1/0&&(Ce.current=new Date().getTime(),at=setTimeout(()=>{f.onAutoClose==null||f.onAutoClose.call(f,f),Je()},me.current)),()=>clearTimeout(at)},[S,h,f,Ne,Ie,Je]),ze.useEffect(()=>{f.delete&&(Je(),f.onDismiss==null||f.onDismiss.call(f,f))},[Je,f.delete]);function nt(){var at;if(B?.loading){var _t;return ze.createElement("div",{className:uv(H?.loader,f==null||(_t=f.classNames)==null?void 0:_t.loader,"sonner-loader"),"data-visible":Ne==="loading"},B.loading)}return ze.createElement(mTn,{className:uv(H?.loader,f==null||(at=f.classNames)==null?void 0:at.loader),visible:Ne==="loading"})}const Ft=f.icon||B?.[Ne]||pTn(Ne);var Ot,Qt;return ze.createElement("li",{tabIndex:0,ref:we,className:uv(I,ie,H?.toast,f==null||(t=f.classNames)==null?void 0:t.toast,H?.default,H?.[Ne],f==null||(n=f.classNames)==null?void 0:n[Ne]),"data-sonner-toast":"","data-rich-colors":(Ot=f.richColors)!=null?Ot:_,"data-styled":!(f.jsx||f.unstyled||p),"data-mounted":$,"data-promise":!!f.promise,"data-swiped":pe,"data-removed":Z,"data-visible":ke,"data-y-position":je,"data-x-position":Ee,"data-index":b,"data-front":Oe,"data-swiping":ne,"data-dismissible":Pe,"data-type":Ne,"data-invert":$e,"data-swipe-out":J,"data-swipe-direction":G,"data-expanded":!!(S||F&&$),"data-testid":f.testId,style:{"--index":b,"--toasts-before":b,"--z-index":x.length-b,"--offset":`${Z?te:Re.current}px`,"--initial-height":F?"auto":`${fe}px`,...E,...f.style},onDragEnd:()=>{ee(!1),M(null),We.current=null},onPointerDown:at=>{at.button!==2&&(Ve||!Pe||(be.current=new Date,ue(Re.current),at.target.setPointerCapture(at.pointerId),at.target.tagName!=="BUTTON"&&(ee(!0),We.current={x:at.clientX,y:at.clientY})))},onPointerUp:()=>{var at,_t,Zt;if(J||!Pe)return;We.current=null;const Qe=Number(((at=we.current)==null?void 0:at.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),ot=Number(((_t=we.current)==null?void 0:_t.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),pt=new Date().getTime()-((Zt=be.current)==null?void 0:Zt.getTime()),mt=V==="x"?Qe:ot,Rt=Math.abs(mt)/pt;if(Math.abs(mt)>=RTn||Rt>.11){ue(Re.current),f.onDismiss==null||f.onDismiss.call(f,f),q(V==="x"?Qe>0?"right":"left":ot>0?"down":"up"),Je(),ae(!0);return}else{var hn,Ae;(hn=we.current)==null||hn.style.setProperty("--swipe-amount-x","0px"),(Ae=we.current)==null||Ae.style.setProperty("--swipe-amount-y","0px")}Y(!1),ee(!1),M(null)},onPointerMove:at=>{var _t,Zt,Qe;if(!We.current||!Pe||((_t=window.getSelection())==null?void 0:_t.toString().length)>0)return;const pt=at.clientY-We.current.y,mt=at.clientX-We.current.x;var Rt;const hn=(Rt=e.swipeDirections)!=null?Rt:$Tn(L);!V&&(Math.abs(mt)>1||Math.abs(pt)>1)&&M(Math.abs(mt)>Math.abs(pt)?"x":"y");let Ae={x:0,y:0};const Be=Le=>1/(1.5+Math.abs(Le)/20);if(V==="y"){if(hn.includes("top")||hn.includes("bottom"))if(hn.includes("top")&&pt<0||hn.includes("bottom")&&pt>0)Ae.y=pt;else{const Le=pt*Be(pt);Ae.y=Math.abs(Le)<Math.abs(pt)?Le:pt}}else if(V==="x"&&(hn.includes("left")||hn.includes("right")))if(hn.includes("left")&&mt<0||hn.includes("right")&&mt>0)Ae.x=mt;else{const Le=mt*Be(mt);Ae.x=Math.abs(Le)<Math.abs(mt)?Le:mt}(Math.abs(Ae.x)>0||Math.abs(Ae.y)>0)&&Y(!0),(Zt=we.current)==null||Zt.style.setProperty("--swipe-amount-x",`${Ae.x}px`),(Qe=we.current)==null||Qe.style.setProperty("--swipe-amount-y",`${Ae.y}px`)}},de&&!f.jsx&&Ne!=="loading"?ze.createElement("button",{"aria-label":U,"data-disabled":Ve,"data-close-button":!0,onClick:Ve||!Pe?()=>{}:()=>{Je(),f.onDismiss==null||f.onDismiss.call(f,f)},className:uv(H?.closeButton,f==null||(r=f.classNames)==null?void 0:r.closeButton)},(Qt=B?.close)!=null?Qt:xTn):null,(Ne||f.icon||f.promise)&&f.icon!==null&&(B?.[Ne]!==null||f.icon)?ze.createElement("div",{"data-icon":"",className:uv(H?.icon,f==null||(s=f.classNames)==null?void 0:s.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||nt():null,f.type!=="loading"?Ft:null):null,ze.createElement("div",{"data-content":"",className:uv(H?.content,f==null||(a=f.classNames)==null?void 0:a.content)},ze.createElement("div",{"data-title":"",className:uv(H?.title,f==null||(i=f.classNames)==null?void 0:i.title)},f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title),f.description?ze.createElement("div",{"data-description":"",className:uv(A,re,H?.description,f==null||(l=f.classNames)==null?void 0:l.description)},typeof f.description=="function"?f.description():f.description):null),ze.isValidElement(f.cancel)?f.cancel:f.cancel&&h6(f.cancel)?ze.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||T,onClick:at=>{h6(f.cancel)&&Pe&&(f.cancel.onClick==null||f.cancel.onClick.call(f.cancel,at),Je())},className:uv(H?.cancelButton,f==null||(c=f.classNames)==null?void 0:c.cancelButton)},f.cancel.label):null,ze.isValidElement(f.action)?f.action:f.action&&h6(f.action)?ze.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||N,onClick:at=>{h6(f.action)&&(f.action.onClick==null||f.action.onClick.call(f.action,at),!at.defaultPrevented&&Je())},className:uv(H?.actionButton,f==null||(u=f.classNames)==null?void 0:u.actionButton)},f.action.label):null)};function K5e(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function DTn(e,t){const n={};return[e,t].forEach((r,s)=>{const a=s===1,i=a?"--mobile-offset":"--offset",l=a?NTn:jTn;function c(u){["top","right","bottom","left"].forEach(d=>{n[`${i}-${d}`]=typeof u=="number"?`${u}px`:u})}typeof r=="number"||typeof r=="string"?c(r):typeof r=="object"?["top","right","bottom","left"].forEach(u=>{r[u]===void 0?n[`${i}-${u}`]=l:n[`${i}-${u}`]=typeof r[u]=="number"?`${r[u]}px`:r[u]}):c(l)}),n}const LTn=ze.forwardRef(function(t,n){const{id:r,invert:s,position:a="bottom-right",hotkey:i=["altKey","KeyT"],expand:l,closeButton:c,className:u,offset:d,mobileOffset:f,theme:p="light",richColors:h,duration:m,style:v,visibleToasts:y=TTn,toastOptions:b,dir:x=K5e(),gap:S=ATn,icons:k,containerAriaLabel:_="Notifications"}=t,[C,E]=ze.useState([]),T=ze.useMemo(()=>r?C.filter($=>$.toasterId===r):C.filter($=>!$.toasterId),[C,r]),N=ze.useMemo(()=>Array.from(new Set([a].concat(T.filter($=>$.position).map($=>$.position)))),[T,a]),[I,A]=ze.useState([]),[R,L]=ze.useState(!1),[D,F]=ze.useState(!1),[H,B]=ze.useState(p!=="system"?p:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),U=ze.useRef(null),V=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),M=ze.useRef(null),G=ze.useRef(!1),q=ze.useCallback($=>{E(z=>{var Z;return(Z=z.find(K=>K.id===$.id))!=null&&Z.delete||af.dismiss($.id),z.filter(({id:K})=>K!==$.id)})},[]);return ze.useEffect(()=>af.subscribe($=>{if($.dismiss){requestAnimationFrame(()=>{E(z=>z.map(Z=>Z.id===$.id?{...Z,delete:!0}:Z))});return}setTimeout(()=>{Glt.flushSync(()=>{E(z=>{const Z=z.findIndex(K=>K.id===$.id);return Z!==-1?[...z.slice(0,Z),{...z[Z],...$},...z.slice(Z+1)]:[$,...z]})})})}),[C]),ze.useEffect(()=>{if(p!=="system"){B(p);return}if(p==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?B("dark"):B("light")),typeof window>"u")return;const $=window.matchMedia("(prefers-color-scheme: dark)");try{$.addEventListener("change",({matches:z})=>{B(z?"dark":"light")})}catch{$.addListener(({matches:Z})=>{try{B(Z?"dark":"light")}catch(K){console.error(K)}})}},[p]),ze.useEffect(()=>{C.length<=1&&L(!1)},[C]),ze.useEffect(()=>{const $=z=>{var Z;if(i.every(ee=>z[ee]||z.code===ee)){var ne;L(!0),(ne=U.current)==null||ne.focus()}z.code==="Escape"&&(document.activeElement===U.current||(Z=U.current)!=null&&Z.contains(document.activeElement))&&L(!1)};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[i]),ze.useEffect(()=>{if(U.current)return()=>{M.current&&(M.current.focus({preventScroll:!0}),M.current=null,G.current=!1)}},[U.current]),ze.createElement("section",{ref:n,"aria-label":`${_} ${V}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},N.map(($,z)=>{var Z;const[K,ne]=$.split("-");return T.length?ze.createElement("ol",{key:$,dir:x==="auto"?K5e():x,tabIndex:-1,ref:U,className:u,"data-sonner-toaster":!0,"data-sonner-theme":H,"data-y-position":K,"data-x-position":ne,style:{"--front-toast-height":`${((Z=I[0])==null?void 0:Z.height)||0}px`,"--width":`${ITn}px`,"--gap":`${S}px`,...v,...DTn(d,f)},onBlur:ee=>{G.current&&!ee.currentTarget.contains(ee.relatedTarget)&&(G.current=!1,M.current&&(M.current.focus({preventScroll:!0}),M.current=null))},onFocus:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||G.current||(G.current=!0,M.current=ee.relatedTarget)},onMouseEnter:()=>L(!0),onMouseMove:()=>L(!0),onMouseLeave:()=>{D||L(!1)},onDragEnd:()=>L(!1),onPointerDown:ee=>{ee.target instanceof HTMLElement&&ee.target.dataset.dismissible==="false"||F(!0)},onPointerUp:()=>F(!1)},T.filter(ee=>!ee.position&&z===0||ee.position===$).map((ee,J)=>{var ae,pe;return ze.createElement(MTn,{key:ee.id,icons:k,index:J,toast:ee,defaultRichColors:h,duration:(ae=b?.duration)!=null?ae:m,className:b?.className,descriptionClassName:b?.descriptionClassName,invert:s,visibleToasts:y,closeButton:(pe=b?.closeButton)!=null?pe:c,interacting:D,position:$,style:b?.style,unstyled:b?.unstyled,classNames:b?.classNames,cancelButtonStyle:b?.cancelButtonStyle,actionButtonStyle:b?.actionButtonStyle,closeButtonAriaLabel:b?.closeButtonAriaLabel,removeToast:q,toasts:T.filter(Y=>Y.position==ee.position),heights:I.filter(Y=>Y.position==ee.position),setHeights:A,expandByDefault:l,gap:S,expanded:R,swipeDirections:t.swipeDirections})})):null}))}),p1e=({className:e,toastOptions:t,...n})=>o.jsx(LTn,{...n,closeButton:!0,richColors:!0,className:X("mastra-toaster",e),toastOptions:{duration:5e3,...t}}),rH=(e,t)=>Array.isArray(e)?e.map(t):t(e),Fe=(e,t={})=>{if(Array.isArray(e))return e.map(n=>iu(n,t));if(ze.isValidElement(e)||typeof e=="string")return iu(e,t);throw new Error("Invalid message type")};Fe.success=(e,t={})=>rH(e,n=>iu.success(n,t));Fe.error=(e,t={})=>rH(e,n=>iu.error(n,t));Fe.warning=(e,t={})=>rH(e,n=>iu.warning(n,t));Fe.info=(e,t={})=>rH(e,n=>iu.info(n,t));Fe.custom=(e,t={})=>iu(e,t);Fe.dismiss=e=>iu.dismiss(e);Fe.promise=({myPromise:e,loadingMessage:t,successMessage:n,errorMessage:r,onSuccess:s,onError:a,options:i={}})=>iu.promise(e,{loading:t??"Loading...",success:l=>(s?.(l),n),error:l=>(a?.(l),r||(l instanceof Error?l.message:"Error...")),...i});var B_=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},FTn={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},zTn=class{#e=FTn;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},Pk=new zTn;function BTn(e){setTimeout(e,0)}var jO=typeof window>"u"||"Deno"in globalThis;function Tu(){}function UTn(e,t){return typeof e=="function"?e(t):e}function Hhe(e){return typeof e=="number"&&e>=0&&e!==1/0}function Tvt(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ww(e,t){return typeof e=="function"?e(t):e}function Ih(e,t){return typeof e=="function"?e(t):e}function X5e(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:a,queryKey:i,stale:l}=e;if(i){if(r){if(t.queryHash!==h1e(i,t.options))return!1}else if(!M$(t.queryKey,i))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||s&&s!==t.state.fetchStatus||a&&!a(t))}function J5e(e,t){const{exact:n,status:r,predicate:s,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(NO(t.options.mutationKey)!==NO(a))return!1}else if(!M$(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function h1e(e,t){return(t?.queryKeyHashFn||NO)(e)}function NO(e){return JSON.stringify(e,(t,n)=>Whe(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function M$(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>M$(e[n],t[n])):!1}var VTn=Object.prototype.hasOwnProperty;function m1e(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=e6e(e)&&e6e(t);if(!r&&!(Whe(e)&&Whe(t)))return t;const a=(r?e:Object.keys(e)).length,i=r?t:Object.keys(t),l=i.length,c=r?new Array(l):{};let u=0;for(let d=0;d<l;d++){const f=r?d:i[d],p=e[f],h=t[f];if(p===h){c[f]=p,(r?d<a:VTn.call(e,f))&&u++;continue}if(p===null||h===null||typeof p!="object"||typeof h!="object"){c[f]=h;continue}const m=m1e(p,h,n+1);c[f]=m,m===p&&u++}return a===l&&u===a?e:c}function D$(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function e6e(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Whe(e){if(!t6e(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!t6e(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function t6e(e){return Object.prototype.toString.call(e)==="[object Object]"}function qTn(e){return new Promise(t=>{Pk.setTimeout(t,e)})}function Zhe(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?m1e(e,t):t}function HTn(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function WTn(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var U_=Symbol();function jvt(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===U_?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function g1e(e,t){return typeof e=="function"?e(...t):!!e}function ZTn(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??=t(),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var GTn=class extends B_{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!jO&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},v1e=new GTn;function Ghe(){let e,t;const n=new Promise((s,a)=>{e=s,t=a});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var QTn=BTn;function YTn(){let e=[],t=0,n=l=>{l()},r=l=>{l()},s=QTn;const a=l=>{t?e.push(l):s(()=>{n(l)})},i=()=>{const l=e;e=[],l.length&&s(()=>{r(()=>{l.forEach(c=>{n(c)})})})};return{batch:l=>{let c;t++;try{c=l()}finally{t--,t||i()}return c},batchCalls:l=>(...c)=>{a(()=>{l(...c)})},schedule:a,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{s=l}}}var nl=YTn(),KTn=class extends B_{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!jO&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#e}},_7=new KTn;function XTn(e){return Math.min(1e3*2**e,3e4)}function Nvt(e){return(e??"online")==="online"?_7.isOnline():!0}var Qhe=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Ivt(e){let t=!1,n=0,r;const s=Ghe(),a=()=>s.status!=="pending",i=v=>{if(!a()){const y=new Qhe(v);p(y),e.onCancel?.(y)}},l=()=>{t=!0},c=()=>{t=!1},u=()=>v1e.isFocused()&&(e.networkMode==="always"||_7.isOnline())&&e.canRun(),d=()=>Nvt(e.networkMode)&&e.canRun(),f=v=>{a()||(r?.(),s.resolve(v))},p=v=>{a()||(r?.(),s.reject(v))},h=()=>new Promise(v=>{r=y=>{(a()||u())&&v(y)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let v;const y=n===0?e.initialPromise:void 0;try{v=y??e.fn()}catch(b){v=Promise.reject(b)}Promise.resolve(v).then(f).catch(b=>{if(a())return;const x=e.retry??(jO?0:3),S=e.retryDelay??XTn,k=typeof S=="function"?S(n,b):S,_=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,b);if(t||!_){p(b);return}n++,e.onFail?.(n,b),qTn(k).then(()=>u()?void 0:h()).then(()=>{t?p(b):m()})})};return{promise:s,status:()=>s.status,cancel:i,continue:()=>(r?.(),s),cancelRetry:l,continueRetry:c,canStart:d,start:()=>(d()?m():h().then(m),s)}}var Avt=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Hhe(this.gcTime)&&(this.#e=Pk.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(jO?1/0:300*1e3))}clearGcTimeout(){this.#e&&(Pk.clearTimeout(this.#e),this.#e=void 0)}},JTn=class extends Avt{#e;#t;#n;#r;#s;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=r6e(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#s?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=r6e(this.options);t.data!==void 0&&(this.setState(n6e(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=Zhe(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(Tu).catch(Tu):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>Ih(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===U_||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ww(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Tvt(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#s&&(this.#o?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#s?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const l=this.observers.find(c=>c.options.queryFn);l&&this.setOptions(l.options)}const n=new AbortController,r=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},s=()=>{const l=jvt(this.options,t),u=(()=>{const d={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(d),d})();return this.#o=!1,this.options.persister?this.options.persister(l,u,this):l(u)},i=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:s};return r(l),l})();this.options.behavior?.onFetch(i,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta}),this.#s=Ivt({initialPromise:t?.initialPromise,fn:i.fetchFn,onCancel:l=>{l instanceof Qhe&&l.revert&&this.setState({...this.#t,fetchStatus:"idle"}),n.abort()},onFail:(l,c)=>{this.#i({type:"failed",failureCount:l,error:c})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0});try{const l=await this.#s.start();if(l===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(l),this.#n.config.onSuccess?.(l,this),this.#n.config.onSettled?.(l,this.state.error,this),l}catch(l){if(l instanceof Qhe){if(l.silent)return this.#s.promise;if(l.revert){if(this.state.data===void 0)throw l;return this.state.data}}throw this.#i({type:"error",error:l}),this.#n.config.onError?.(l,this),this.#n.config.onSettled?.(this.state.data,l,this),l}finally{this.scheduleGc()}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Rvt(n.data,this.options),fetchMeta:e.meta??null};case"success":const r={...n,...n6e(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?r:void 0,r;case"error":const s=e.error;return{...n,error:s,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),nl.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Rvt(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Nvt(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function n6e(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function r6e(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var sH=class extends B_{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=Ghe(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#s;#a;#o;#i;#l;#f;#p;#u;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),s6e(this.#t,this.options)?this.#m():this.updateResult(),this.#b())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Yhe(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Yhe(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#x(),this.#w(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ih(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),t._defaulted&&!D$(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&a6e(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||Ih(this.options.enabled,this.#t)!==Ih(t.enabled,this.#t)||Ww(this.options.staleTime,this.#t)!==Ww(t.staleTime,this.#t))&&this.#g();const s=this.#v();r&&(this.#t!==n||Ih(this.options.enabled,this.#t)!==Ih(t.enabled,this.#t)||s!==this.#c)&&this.#y(s)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return tjn(this,n)&&(this.#r=n,this.#a=this.options,this.#s=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(n,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(n,r))})}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Tu)),t}#g(){this.#x();const e=Ww(this.options.staleTime,this.#t);if(jO||this.#r.isStale||!Hhe(e))return;const n=Tvt(this.#r.dataUpdatedAt,e)+1;this.#u=Pk.setTimeout(()=>{this.#r.isStale||this.updateResult()},n)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#y(e){this.#w(),this.#c=e,!(jO||Ih(this.options.enabled,this.#t)===!1||!Hhe(this.#c)||this.#c===0)&&(this.#d=Pk.setInterval(()=>{(this.options.refetchIntervalInBackground||v1e.isFocused())&&this.#m()},this.#c))}#b(){this.#g(),this.#y(this.#v())}#x(){this.#u&&(Pk.clearTimeout(this.#u),this.#u=void 0)}#w(){this.#d&&(Pk.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#t,r=this.options,s=this.#r,a=this.#s,i=this.#a,c=e!==n?e.state:this.#n,{state:u}=e;let d={...u},f=!1,p;if(t._optimisticResults){const T=this.hasListeners(),N=!T&&s6e(e,t),I=T&&a6e(e,n,t,r);(N||I)&&(d={...d,...Rvt(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:h,errorUpdatedAt:m,status:v}=d;p=d.data;let y=!1;if(t.placeholderData!==void 0&&p===void 0&&v==="pending"){let T;s?.isPlaceholderData&&t.placeholderData===i?.placeholderData?(T=s.data,y=!0):T=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,T!==void 0&&(v="success",p=Zhe(s?.data,T,t),f=!0)}if(t.select&&p!==void 0&&!y)if(s&&p===a?.data&&t.select===this.#l)p=this.#f;else try{this.#l=t.select,p=t.select(p),p=Zhe(s?.data,p,t),this.#f=p,this.#i=null}catch(T){this.#i=T}this.#i&&(h=this.#i,p=this.#f,m=Date.now(),v="error");const b=d.fetchStatus==="fetching",x=v==="pending",S=v==="error",k=x&&b,_=p!==void 0,E={status:v,fetchStatus:d.fetchStatus,isPending:x,isSuccess:v==="success",isError:S,isInitialLoading:k,isLoading:k,data:p,dataUpdatedAt:d.dataUpdatedAt,error:h,errorUpdatedAt:m,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:d.dataUpdateCount>0||d.errorUpdateCount>0,isFetchedAfterMount:d.dataUpdateCount>c.dataUpdateCount||d.errorUpdateCount>c.errorUpdateCount,isFetching:b,isRefetching:b&&!x,isLoadingError:S&&!_,isPaused:d.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:S&&_,isStale:y1e(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Ih(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const T=E.data!==void 0,N=E.status==="error"&&!T,I=L=>{N?L.reject(E.error):T&&L.resolve(E.data)},A=()=>{const L=this.#o=E.promise=Ghe();I(L)},R=this.#o;switch(R.status){case"pending":e.queryHash===n.queryHash&&I(R);break;case"fulfilled":(N||E.data!==R.value)&&A();break;case"rejected":(!N||E.error!==R.reason)&&A();break}}return E}updateResult(){const e=this.#r,t=this.createResult(this.#t,this.options);if(this.#s=this.#t.state,this.#a=this.options,this.#s.data!==void 0&&(this.#p=this.#t),D$(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,s=typeof r=="function"?r():r;if(s==="all"||!s&&!this.#h.size)return!0;const a=new Set(s??this.#h);return this.options.throwOnError&&a.add("error"),Object.keys(this.#r).some(i=>{const l=i;return this.#r[l]!==e[l]&&a.has(l)})};this.#k({listeners:n()})}#S(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#b()}#k(e){nl.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function ejn(e,t){return Ih(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function s6e(e,t){return ejn(e,t)||e.state.data!==void 0&&Yhe(e,t,t.refetchOnMount)}function Yhe(e,t,n){if(Ih(t.enabled,e)!==!1&&Ww(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&y1e(e,t)}return!1}function a6e(e,t,n,r){return(e!==t||Ih(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&y1e(e,n)}function y1e(e,t){return Ih(t.enabled,e)!==!1&&e.isStaleByTime(Ww(t.staleTime,e))}function tjn(e,t){return!D$(e.getCurrentResult(),t)}function C7(e){return{onFetch:(t,n)=>{const r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],i=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},c=0;const u=async()=>{let d=!1;const f=m=>{ZTn(m,()=>t.signal,()=>d=!0)},p=jvt(t.options,t.fetchOptions),h=async(m,v,y)=>{if(d)return Promise.reject();if(v==null&&m.pages.length)return Promise.resolve(m);const x=(()=>{const C={client:t.client,queryKey:t.queryKey,pageParam:v,direction:y?"backward":"forward",meta:t.options.meta};return f(C),C})(),S=await p(x),{maxPages:k}=t.options,_=y?WTn:HTn;return{pages:_(m.pages,S,k),pageParams:_(m.pageParams,v,k)}};if(s&&a.length){const m=s==="backward",v=m?Pvt:Khe,y={pages:a,pageParams:i},b=v(r,y);l=await h(y,b,m)}else{const m=e??a.length;do{const v=c===0?i[0]??r.initialPageParam:Khe(r,l);if(c>0&&v==null)break;l=await h(l,v),c++}while(c<m)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function Khe(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Pvt(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function njn(e,t){return t?Khe(e,t)!=null:!1}function rjn(e,t){return!t||!e.getPreviousPageParam?!1:Pvt(e,t)!=null}var sjn=class extends sH{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:C7()})}getOptimisticResult(e){return e.behavior=C7(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){const{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:a,isError:i,isRefetchError:l}=r,c=n.fetchMeta?.fetchMore?.direction,u=i&&c==="forward",d=s&&c==="forward",f=i&&c==="backward",p=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:njn(t,n.data),hasPreviousPage:rjn(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:f,isFetchingPreviousPage:p,isRefetchError:l&&!u&&!f,isRefetching:a&&!d&&!p}}},ajn=class extends Avt{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||$vt(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#s({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Ivt({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(a,i)=>{this.#s({type:"failed",failureCount:a,error:i})},onPause:()=>{this.#s({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});const r=this.state.status==="pending",s=!this.#r.canStart();try{if(r)t();else{this.#s({type:"pending",variables:e,isPaused:s}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const i=await this.options.onMutate?.(e,n);i!==this.state.context&&this.#s({type:"pending",context:i,variables:e,isPaused:s})}const a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#s({type:"success",data:a}),a}catch(a){try{await this.#n.config.onError?.(a,e,this.state.context,this,n)}catch(i){Promise.reject(i)}try{await this.options.onError?.(a,e,this.state.context,n)}catch(i){Promise.reject(i)}try{await this.#n.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,n)}catch(i){Promise.reject(i)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,n)}catch(i){Promise.reject(i)}throw this.#s({type:"error",error:a}),a}finally{this.#n.runNext(this)}}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),nl.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function $vt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ijn=class extends B_{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){const r=new ajn({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);const t=m6(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=m6(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=m6(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(s=>s.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=m6(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){nl.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>J5e(t,n))}findAll(e={}){return this.getAll().filter(t=>J5e(e,t))}notify(e){nl.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return nl.batch(()=>Promise.all(e.map(t=>t.continue().catch(Tu))))}};function m6(e){return e.options.scope?.id}var ojn=class extends B_{#e;#t=void 0;#n;#r;constructor(t,n){super(),this.#e=t,this.setOptions(n),this.bindMethods(),this.#s()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){const n=this.options;this.options=this.#e.defaultMutationOptions(t),D$(this.options,n)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#n,observer:this}),n?.mutationKey&&this.options.mutationKey&&NO(n.mutationKey)!==NO(this.options.mutationKey)?this.reset():this.#n?.state.status==="pending"&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(t){this.#s(),this.#a(t)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#s(),this.#a()}mutate(t,n){return this.#r=n,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(t)}#s(){const t=this.#n?.state??$vt();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#a(t){nl.batch(()=>{if(this.#r&&this.hasListeners()){const n=this.#t.variables,r=this.#t.context,s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#r.onSuccess?.(t.data,n,r,s)}catch(a){Promise.reject(a)}try{this.#r.onSettled?.(t.data,null,n,r,s)}catch(a){Promise.reject(a)}}else if(t?.type==="error"){try{this.#r.onError?.(t.error,n,r,s)}catch(a){Promise.reject(a)}try{this.#r.onSettled?.(void 0,t.error,n,r,s)}catch(a){Promise.reject(a)}}}this.listeners.forEach(n=>{n(this.#t)})})}};function i6e(e,t){const n=new Set(t);return e.filter(r=>!n.has(r))}function ljn(e,t,n){const r=e.slice(0);return r[t]=n,r}var cjn=class extends B_{#e;#t;#n;#r;#s;#a;#o;#i;#l;#f=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#s=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#s.forEach(e=>{e.subscribe(t=>{this.#c(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#s.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,nl.batch(()=>{const n=this.#s,r=this.#d(this.#n);r.forEach(d=>d.observer.setOptions(d.defaultedQueryOptions));const s=r.map(d=>d.observer),a=s.map(d=>d.getCurrentResult()),i=n.length!==s.length,l=s.some((d,f)=>d!==n[f]),c=i||l,u=c?!0:a.some((d,f)=>{const p=this.#t[f];return!p||!D$(d,p)});!c&&!u||(c&&(this.#f=r,this.#s=s),this.#t=a,this.hasListeners()&&(c&&(i6e(n,s).forEach(d=>{d.destroy()}),i6e(s,n).forEach(d=>{d.subscribe(f=>{this.#c(d,f)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#s.map(e=>e.getCurrentQuery())}getObservers(){return this.#s}getOptimisticResult(e,t){const n=this.#d(e),r=n.map(a=>a.observer.getOptimisticResult(a.defaultedQueryOptions)),s=n.map(a=>a.defaultedQueryOptions.queryHash);return[r,a=>this.#u(a??r,t,s),()=>this.#p(r,n)]}#p(e,t){return t.map((n,r)=>{const s=e[r];return n.defaultedQueryOptions.notifyOnChangeProps?s:n.observer.trackResult(s,a=>{t.forEach(i=>{i.observer.trackProp(a)})})})}#u(e,t,n){if(t){const r=this.#l,s=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((a,i)=>a!==r[i]));return(!this.#a||this.#t!==this.#i||s||t!==this.#o)&&(this.#o=t,this.#i=this.#t,n!==void 0&&(this.#l=n),this.#a=m1e(this.#a,t(e))),this.#a}return e}#d(e){const t=new Map;this.#s.forEach(r=>{const s=r.options.queryHash;if(!s)return;const a=t.get(s);a?a.push(r):t.set(s,[r])});const n=[];return e.forEach(r=>{const s=this.#e.defaultQueryOptions(r),i=t.get(s.queryHash)?.shift()??new sH(this.#e,s);n.push({defaultedQueryOptions:s,observer:i})}),n}#c(e,t){const n=this.#s.indexOf(e);n!==-1&&(this.#t=ljn(this.#t,n,t),this.#h())}#h(){if(this.hasListeners()){const e=this.#a,t=this.#p(this.#t,this.#f),n=this.#u(t,this.#r?.combine);e!==n&&nl.batch(()=>{this.listeners.forEach(r=>{r(this.#t)})})}}},ujn=class extends B_{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){const r=t.queryKey,s=t.queryHash??h1e(r,t);let a=this.get(s);return a||(a=new JTn({client:e,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){nl.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>X5e(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>X5e(e,n)):t}notify(e){nl.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){nl.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){nl.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},djn=class{#e;#t;#n;#r;#s;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new ujn,this.#t=e.mutationCache||new ijn,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=v1e.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=_7.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ww(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),a=this.#e.get(r.queryHash)?.state.data,i=UTn(t,a);if(i!==void 0)return this.#e.build(this,r).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return nl.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;nl.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return nl.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=nl.batch(()=>this.#e.findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Tu).catch(Tu)}invalidateQueries(e,t={}){return nl.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=nl.batch(()=>this.#e.findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let a=s.fetch(void 0,n);return n.throwOnError||(a=a.catch(Tu)),s.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(Tu)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(Ww(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Tu).catch(Tu)}fetchInfiniteQuery(e){return e.behavior=C7(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Tu).catch(Tu)}ensureInfiniteQueryData(e){return e.behavior=C7(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return _7.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(NO(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{M$(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(NO(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{M$(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=h1e(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===U_&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Mvt=g.createContext(void 0),Br=e=>{const t=g.useContext(Mvt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},fjn=({client:e,children:t})=>(g.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),o.jsx(Mvt.Provider,{value:e,children:t})),Dvt=g.createContext(!1),Lvt=()=>g.useContext(Dvt);Dvt.Provider;function pjn(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var hjn=g.createContext(pjn()),Fvt=()=>g.useContext(hjn),zvt=(e,t,n)=>{const r=n?.state.error&&typeof e.throwOnError=="function"?g1e(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Bvt=e=>{g.useEffect(()=>{e.clearReset()},[e])},Uvt=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||g1e(n,[e.error,r])),Vvt=e=>{if(e.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},mjn=(e,t)=>e.isLoading&&e.isFetching&&!t,Xhe=(e,t)=>e?.suspense&&t.isPending,Jhe=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Cj({queries:e,...t},n){const r=Br(),s=Lvt(),a=Fvt(),i=g.useMemo(()=>e.map(v=>{const y=r.defaultQueryOptions(v);return y._optimisticResults=s?"isRestoring":"optimistic",y}),[e,r,s]);i.forEach(v=>{Vvt(v);const y=r.getQueryCache().get(v.queryHash);zvt(v,a,y)}),Bvt(a);const[l]=g.useState(()=>new cjn(r,i,t)),[c,u,d]=l.getOptimisticResult(i,t.combine),f=!s&&t.subscribed!==!1;g.useSyncExternalStore(g.useCallback(v=>f?l.subscribe(nl.batchCalls(v)):Tu,[l,f]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),g.useEffect(()=>{l.setQueries(i,t)},[i,t,l]);const h=c.some((v,y)=>Xhe(i[y],v))?c.flatMap((v,y)=>{const b=i[y];if(b&&Xhe(b,v)){const x=new sH(r,b);return Jhe(b,x,a)}return[]}):[];if(h.length>0)throw Promise.all(h);const m=c.find((v,y)=>{const b=i[y];return b&&Uvt({result:v,errorResetBoundary:a,throwOnError:b.throwOnError,query:r.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(m?.error)throw m.error;return u(d())}function qvt(e,t,n){const r=Lvt(),s=Fvt(),a=Br(),i=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(i);const l=a.getQueryCache().get(i.queryHash);i._optimisticResults=r?"isRestoring":"optimistic",Vvt(i),zvt(i,s,l),Bvt(s);const c=!a.getQueryCache().get(i.queryHash),[u]=g.useState(()=>new t(a,i)),d=u.getOptimisticResult(i),f=!r&&e.subscribed!==!1;if(g.useSyncExternalStore(g.useCallback(p=>{const h=f?u.subscribe(nl.batchCalls(p)):Tu;return u.updateResult(),h},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),g.useEffect(()=>{u.setOptions(i)},[i,u]),Xhe(i,d))throw Jhe(i,u,s);if(Uvt({result:d,errorResetBoundary:s,throwOnError:i.throwOnError,query:l,suspense:i.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(i,d),i.experimental_prefetchInRender&&!jO&&mjn(d,r)&&(c?Jhe(i,u,s):l?.promise)?.catch(Tu).finally(()=>{u.updateResult()}),i.notifyOnChangeProps?d:u.trackResult(d)}function gt(e,t){return qvt(e,sH)}function Dn(e,t){const n=Br(),[r]=g.useState(()=>new ojn(n,e));g.useEffect(()=>{r.setOptions(e)},[r,e]);const s=g.useSyncExternalStore(g.useCallback(i=>r.subscribe(nl.batchCalls(i)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=g.useCallback((i,l)=>{r.mutate(i,l).catch(Tu)},[r]);if(s.error&&g1e(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:a,mutateAsync:s.mutate}}function G1(e,t){return qvt(e,sjn)}const Q1=e=>{const t=Ze();return gt({queryKey:["builder-settings"],queryFn:()=>t.getBuilderSettings(),enabled:e?.enabled??!0})},gjn={active:!1},e0=()=>{const{data:e}=Q1();return e?.modelPolicy??gjn},vjn={visibleTools:null,visibleAgents:null,visibleWorkflows:null},yjn=()=>{const{data:e}=Q1(),t=e?.picker;return g.useMemo(()=>t?{visibleTools:t.visibleTools===null?null:new Set(t.visibleTools),visibleAgents:t.visibleAgents===null?null:new Set(t.visibleAgents),visibleWorkflows:t.visibleWorkflows===null?null:new Set(t.visibleWorkflows)}:vjn,[t])};function Om(e){return"user"in e&&e.user!==void 0}async function bjn(e){const{baseUrl:t="",headers:n={},apiPrefix:r}=e.options,s=(r||"/api").trim(),a=(s.startsWith("/")?s:`/${s}`).replace(/\/$/,""),i=await fetch(`${t}${a}/auth/capabilities`,{credentials:"include",headers:{...n,"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch auth capabilities: ${i.status}`);return i.json()}function oc(){const e=Ze();return gt({queryKey:["auth","capabilities"],queryFn:()=>bjn(e),staleTime:60*1e3,retry:!1})}async function xjn(e,{roleId:t}){const{baseUrl:n="",apiPrefix:r,headers:s={}}=e.options||{},a=(r??"/api").trim(),l=(a===""?"":a.startsWith("/")?a:`/${a}`).replace(/\/+$/,""),c=await fetch(`${n}${l}/auth/roles/${encodeURIComponent(t)}/permissions`,{credentials:"include",headers:{...s,"Content-Type":"application/json"}});if(!c.ok)throw new Error(`Failed to fetch role permissions: ${c.status}`);return c.json()}const Hvt=g.createContext(null);function wjn({children:e}){const t=Ze(),[n,r]=g.useState(null),[s,a]=g.useState(null),i=Dn({mutationFn:async({role:f})=>{const p=await xjn(t,{roleId:f.id});return{role:f,permissions:p.permissions}},onSuccess:({role:f,permissions:p})=>{r(f),a(p)}}),{mutateAsync:l,reset:c,isPending:u}=i,d=g.useMemo(()=>({impersonatedRole:n,impersonatedPermissions:s,isImpersonating:n!==null,startImpersonation:async h=>{await l({role:h})},stopImpersonation:()=>{r(null),a(null),c()},isSwitching:u}),[n,s,u,l,c]);return o.jsx(Hvt.Provider,{value:d,children:e})}function aH(){const e=g.useContext(Hvt);return e||{impersonatedRole:null,impersonatedPermissions:null,isImpersonating:!1,startImpersonation:async()=>{},stopImpersonation:()=>{},isSwitching:!1}}function Sjn(e,t){if(e==="*")return!0;const n=e.split(":"),r=t.split(":");if(n.length<2||r.length<2)return e===t;const[s,a,i]=n,[l,c,u]=r;return s==="*"?a==="*"?!0:a!==c?!1:i===void 0?!0:i===u:s!==l?!1:a==="*"?i===void 0?!0:i===u:a!==c?!1:i===void 0?!0:i===u}function kJ(e,t){return e.some(n=>Sjn(n,t))}function Wo(){const{data:e,isLoading:t}=oc(),{isImpersonating:n,impersonatedPermissions:r,impersonatedRole:s}=aH(),a=e&&Om(e),i=a?e.access:null,l=a?e.capabilities.rbac:!1,c=n&&s?[s.id]:i?.roles??[],u=n&&r?r:i?.permissions??[],d=f=>!l&&!n?!0:kJ(u,f);return{roles:c,permissions:u,isLoading:t,isAuthenticated:!!a,rbacEnabled:l,hasPermission:f=>d(f),hasAllPermissions:f=>!l&&!n?!0:f.every(p=>kJ(u,p)),hasAnyPermission:f=>!l&&!n?!0:f.some(p=>kJ(u,p)),hasRole:f=>!l&&!n?!0:c.includes(f),canEdit:f=>d(`${f}:write`),canDelete:f=>d(`${f}:delete`),canExecute:f=>d(`${f}:execute`)}}function Py(){const{hasAnyPermission:e,hasPermission:t,rbacEnabled:n}=Wo(),r=!n||e(["stored-agents:read","stored-agents:write"]),s=!n||e(["stored-agents:read","stored-agents:write"]),a=!n||t("stored-agents:write"),i=!n||e(["stored-agents:read","stored-agents:write"]),l=!n||t("stored-skills:read"),c=!n||e(["stored-agents:read","stored-skills:read"]),{data:u,isLoading:d,error:f}=Q1({enabled:s}),p=u?.enabled===!0,h=u?.features?.agent!==void 0;return{isLoading:s&&d,error:s?f:null,denialReason:r?f?"error":!p||!h?"not-configured":null:"permission-denied",isBuilderEnabled:p,hasAgentFeature:h,hasRequiredPermissions:r,canAccessAgentBuilder:r&&p&&h,canWrite:a,canExecute:i,canManageSkills:l,canUseFavorites:c,agentFeatures:u?.features?.agent}}const Wvt=g.createContext({Link:g.forwardRef(function(t,n){return null}),navigate:()=>{},paths:{agentLink:()=>"",agentsLink:()=>"",agentToolLink:()=>"",agentSkillLink:()=>"",agentThreadLink:()=>"",agentNewThreadLink:()=>"",workflowsLink:()=>"",workflowLink:()=>"",schedulesLink:()=>"",scheduleLink:()=>"",networkLink:()=>"",networkNewThreadLink:()=>"",networkThreadLink:()=>"",scorerLink:()=>"",cmsScorersCreateLink:()=>"",cmsScorerEditLink:()=>"",cmsAgentCreateLink:()=>"",cmsAgentEditLink:()=>"",promptBlockLink:()=>"",promptBlocksLink:()=>"",cmsPromptBlockCreateLink:()=>"",cmsPromptBlockEditLink:()=>"",toolLink:()=>"",skillLink:()=>"",workspacesLink:()=>"",workspaceLink:()=>"",workspaceSkillLink:()=>"",processorsLink:()=>"",processorLink:()=>"",mcpServerLink:()=>"",mcpServerToolLink:()=>"",workflowRunLink:()=>"",datasetLink:()=>"",datasetItemLink:()=>"",datasetExperimentLink:()=>"",experimentLink:()=>""}}),b1e=({children:e,Link:t,navigate:n,paths:r})=>o.jsx(Wvt.Provider,{value:{Link:t,navigate:n,paths:r},children:e}),xn=()=>{const e=g.useContext(Wvt);if(!e)throw new Error("useLinkComponent must be used within a LinkComponentProvider");return e},kjn=["/swagger-ui","/openapi.json"],Cx=g.forwardRef(({children:e,href:t,...n},r)=>t&&kjn.some(a=>t.startsWith(a))?o.jsx("a",{ref:r,href:t,...n,children:e}):o.jsx(ni,{ref:r,to:t??"",viewTransition:!0,...n,children:e})),Ojn=({paths:e})=>{const t=Ho(),{data:n,isLoading:r}=oc();if(r)return o.jsx("div",{className:"flex h-screen w-full items-center justify-center",children:o.jsx(en,{})});if(n?.enabled&&!Om(n)){const s=`${t.pathname}${t.search}${t.hash}`,a=`/login?redirect=${encodeURIComponent(s)}`;return o.jsx(Zu,{to:a,replace:!0})}return o.jsx(_jn,{paths:e})},_jn=({paths:e})=>{const t=Ws(),{isLoading:n,denialReason:r,hasAgentFeature:s}=Py();return n?o.jsx("div",{className:"flex h-screen w-full items-center justify-center",children:o.jsx(en,{})}):r==="permission-denied"?o.jsx(Cjn,{}):r==="error"?o.jsx("div",{className:"flex h-screen items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(_f,{}),titleSlot:"Error",descriptionSlot:"Failed to load Agent Builder configuration."})}):r==="not-configured"?o.jsx("div",{className:"flex h-screen items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(m9,{}),titleSlot:"Agent Builder Not Configured",descriptionSlot:"Agent Builder is not enabled. Contact your administrator to enable this feature."})}):s?o.jsx(Ul,{children:o.jsxs(b1e,{Link:Cx,navigate:t,paths:e,children:[o.jsx(Ox,{}),o.jsx(p1e,{position:"bottom-right"})]})}):o.jsx("div",{className:"flex h-screen items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(m9,{}),titleSlot:"No Features Enabled",descriptionSlot:"No Agent Builder features are configured."})})};function Cjn(){const{isImpersonating:e,impersonatedRole:t,stopImpersonation:n}=aH();return o.jsx("div",{className:"flex h-screen items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(Lr,{iconSlot:o.jsx(Nf,{}),titleSlot:"Access Denied",descriptionSlot:"You don't have permission to access the Agent Builder."}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(le,{as:Cx,href:"/agents",variant:"outline",size:"sm",children:[o.jsx(Rc,{className:"h-3.5 w-3.5"}),"Back to Studio"]}),e&&o.jsxs(le,{variant:"default",size:"sm",onClick:n,children:[o.jsx(Fu,{className:"h-3.5 w-3.5"}),"Exit ",t?.name," preview"]})]})]})})}const E7=[{route:"/agents",permission:"agents:read",name:"Agents"},{route:"/workflows",permission:"workflows:read",name:"Workflows"},{route:"/metrics",permission:"observability:read",name:"Metrics"},{route:"/intelligence",permission:"observability:read",name:"Intelligence"},{route:"/traces",permission:"observability:read",name:"Traces"},{route:"/logs",permission:"logs:read",name:"Logs"},{route:"/scorers",permission:"scores:read",name:"Scorers"},{route:"/datasets",permission:["datasets:read"],name:"Datasets"},{route:"/experiments",permission:["datasets:read"],name:"Experiments"},{route:"/tools",permission:"tools:read",name:"Tools"},{route:"/mcps",permission:"mcp:read",name:"MCP Servers"},{route:"/processors",permission:"processors:read",name:"Processors"},{route:"/prompts",permission:"stored-prompt-blocks:read",name:"Prompts"},{route:"/workspaces",permission:"workspaces:read",name:"Workspaces"},{route:"/request-context",permission:"*",name:"Request Context"},{route:"/settings",permission:"public",name:"Settings"},{route:"/resources",permission:"public",name:"Resources"}];function Ejn(e){return[...new Set(e.flatMap(t=>Array.isArray(t.permission)?t.permission:[t.permission]).filter(t=>t!=="public"))]}const Tjn=Ejn(E7);function T7(e){const t=E7.find(r=>r.route===e);return t?t.permission:E7.find(r=>e.startsWith(r.route+"/"))?.permission}function iH(e,t,n){return!e||e==="public"?!0:Array.isArray(e)?n(e):t(e)}function Zvt(e,t){const n=new Set;for(const{route:r,permission:s}of E7){if(s==="public")continue;const a=Array.isArray(s)?s.sort().join(","):s;if(!n.has(a)&&(n.add(a),iH(s,e,t)))return r}return"/resources"}function jjn({children:e}){const{pathname:t}=Ho(),{hasPermission:n,hasAnyPermission:r,rbacEnabled:s,isAuthenticated:a,isLoading:i}=Wo();if(i)return o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(en,{})});if(!s||!a)return o.jsx(o.Fragment,{children:e});const l=T7(t);if(!l||l==="public")return o.jsx(o.Fragment,{children:e});if(iH(l,n,r))return o.jsx(o.Fragment,{children:e});const c=Zvt(n,r);return c===t?o.jsx(o.Fragment,{children:e}):o.jsx(Zu,{to:c,replace:!0})}const Njn=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Gvt=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();var Ijn={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Ajn=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:s="",children:a,iconNode:i,...l},c)=>g.createElement("svg",{ref:c,...Ijn,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Gvt("lucide",s),...l},[...i.map(([u,d])=>g.createElement(u,d)),...Array.isArray(a)?a:[a]]));const rn=(e,t)=>{const n=g.forwardRef(({className:r,...s},a)=>g.createElement(Ajn,{ref:a,iconNode:t,className:Gvt(`lucide-${Njn(e)}`,r),...s}));return n.displayName=`${e}`,n};const Rjn=[["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 18h18",key:"1h113x"}],["path",{d:"M3 6h18",key:"d0wm0j"}]],j7=rn("AlignJustify",Rjn);const Pjn=[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]],L$=rn("AlignLeft",Pjn);const $jn=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],c3=rn("ArrowDown",$jn);const Mjn=[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]],Djn=rn("ArrowLeftRight",Mjn);const Ljn=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],oH=rn("ArrowLeft",Ljn);const Fjn=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],N7=rn("ArrowRight",Fjn);const zjn=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],lH=rn("ArrowUp",zjn);const Bjn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]],Qvt=rn("Ban",Bjn);const Ujn=[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]],Tw=rn("Braces",Ujn);const Vjn=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]],Yvt=rn("Brain",Vjn);const qjn=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],o6e=rn("Calendar",qjn);const Hjn=[["path",{d:"M8 6h10",key:"9lnwnk"}],["path",{d:"M6 12h9",key:"1g9pqf"}],["path",{d:"M11 18h7",key:"c8dzvl"}]],Wjn=rn("ChartNoAxesGantt",Hjn);const Zjn=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],gy=rn("Check",Zjn);const Gjn=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],cH=rn("ChevronDown",Gjn);const Qjn=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],x1e=rn("ChevronLeft",Qjn);const Yjn=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Ex=rn("ChevronRight",Yjn);const Kjn=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Xjn=rn("ChevronUp",Kjn);const Jjn=[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]],w1e=rn("ChevronsDownUp",Jjn);const eNn=[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]],tNn=rn("ChevronsDown",eNn);const nNn=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],rNn=rn("ChevronsLeft",nNn);const sNn=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],Kvt=rn("ChevronsRight",sNn);const aNn=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],uH=rn("ChevronsUpDown",aNn);const iNn=[["path",{d:"m17 11-5-5-5 5",key:"e8nh98"}],["path",{d:"m17 18-5-5-5 5",key:"2avn1x"}]],oNn=rn("ChevronsUp",iNn);const lNn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],cNn=rn("CircleCheck",lNn);const uNn=[["path",{d:"M15.6 2.7a10 10 0 1 0 5.7 5.7",key:"1e0p6d"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M13.4 10.6 19 5",key:"1kr7tw"}]],dNn=rn("CircleGauge",uNn);const fNn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]],I7=rn("CircleSlash",fNn);const pNn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],hNn=rn("CircleX",pNn);const mNn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Xvt=rn("Circle",mNn);const gNn=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]],vNn=rn("ClipboardList",gNn);const yNn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]],bNn=rn("Clock",yNn);const xNn=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]],wNn=rn("Columns3",xNn);const SNn=[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]],kNn=rn("Component",SNn);const ONn=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],S1e=rn("Copy",ONn);const _Nn=[["polyline",{points:"15 10 20 15 15 20",key:"1q7qjw"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]],CNn=rn("CornerDownRight",_Nn);const ENn=[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]],TNn=rn("Cpu",ENn);const jNn=[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]],NNn=rn("Download",jNn);const INn=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],ANn=rn("EllipsisVertical",INn);const RNn=[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}],["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}]],PNn=rn("EqualNot",RNn);const $Nn=[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}]],MNn=rn("Equal",$Nn);const DNn=[["path",{d:"m15 15 6 6",key:"1s409w"}],["path",{d:"m15 9 6-6",key:"ko1vev"}],["path",{d:"M21 16.2V21h-4.8",key:"1hrera"}],["path",{d:"M21 7.8V3h-4.8",key:"ul1q53"}],["path",{d:"M3 16.2V21h4.8",key:"1x04uo"}],["path",{d:"m3 21 6-6",key:"wwnumi"}],["path",{d:"M3 7.8V3h4.8",key:"1ijppm"}],["path",{d:"M9 9 3 3",key:"v551iv"}]],LNn=rn("Expand",DNn);const FNn=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],k1e=rn("ExternalLink",FNn);const zNn=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],BNn=rn("Eye",zNn);const UNn=[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]],eme=rn("FileInput",UNn);const VNn=[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2",key:"1vk7w2"}],["path",{d:"M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6",key:"1jink5"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]],tme=rn("FileOutput",VNn);const qNn=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Jvt=rn("FileText",qNn);const HNn=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]],WNn=rn("File",HNn);const ZNn=[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]],GNn=rn("Filter",ZNn);const QNn=[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3-3-3 3",key:"e37ymu"}],["path",{d:"m15 5-3 3-3-3",key:"19d6lf"}]],YNn=rn("FoldVertical",QNn);const KNn=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],XNn=rn("Folder",KNn);const JNn=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],eIn=rn("Gauge",JNn);const tIn=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],nIn=rn("GripVertical",tIn);const rIn=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],O1e=rn("Hash",rIn);const sIn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],_1e=rn("Info",sIn);const aIn=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],iIn=rn("Lightbulb",aIn);const oIn=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],eyt=rn("Link2",oIn);const lIn=[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]],cIn=rn("ListChecks",lIn);const uIn=[["path",{d:"M10 18h4",key:"1ulq68"}],["path",{d:"M11 6H3",key:"1u26ik"}],["path",{d:"M15 6h6",key:"1jlkvy"}],["path",{d:"M18 9V3",key:"xwwp7m"}],["path",{d:"M7 12h8",key:"7a1bxv"}]],dIn=rn("ListFilterPlus",uIn);const fIn=[["path",{d:"M21 12h-8",key:"1bmf0i"}],["path",{d:"M21 6H8",key:"1pqkrb"}],["path",{d:"M21 18h-8",key:"1tm79t"}],["path",{d:"M3 6v4c0 1.1.9 2 2 2h3",key:"1ywdgy"}],["path",{d:"M3 10v6c0 1.1.9 2 2 2h3",key:"2wc746"}]],pIn=rn("ListTree",fIn);const hIn=[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]],mIn=rn("ListX",hIn);const gIn=[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]],C1e=rn("List",gIn);const vIn=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],tyt=rn("LoaderCircle",vIn);const yIn=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],bIn=rn("Lock",yIn);const xIn=[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]],wIn=rn("LogIn",xIn);const SIn=[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]],kIn=rn("Logs",SIn);const OIn=[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]],_In=rn("Maximize2",OIn);const CIn=[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]],EIn=rn("Menu",CIn);const TIn=[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]],jIn=rn("Minimize2",TIn);const NIn=[["path",{d:"M5 12h14",key:"1ays0h"}]],IIn=rn("Minus",NIn);const AIn=[["path",{d:"M12 16h.01",key:"1drbdi"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z",key:"1fd625"}]],RIn=rn("OctagonAlert",AIn);const PIn=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],$In=rn("PanelRight",PIn);const MIn=[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]],DIn=rn("Pause",MIn);const LIn=[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]],FIn=rn("Play",LIn);const zIn=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],dH=rn("Plus",zIn);const BIn=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],UIn=rn("RotateCcw",BIn);const VIn=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],nyt=rn("Save",VIn);const qIn=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]],A7=rn("Search",qIn);const HIn=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]],WIn=rn("ShieldX",HIn);const ZIn=[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M10 12H3",key:"1ulcyk"}],["path",{d:"M10 18H3",key:"13769t"}],["circle",{cx:"17",cy:"15",r:"3",key:"1upz2a"}],["path",{d:"m21 19-1.9-1.9",key:"dwi7p8"}]],GIn=rn("TextSearch",ZIn);const QIn=[["path",{d:"M17 6.1H3",key:"wptmhv"}],["path",{d:"M21 12.1H3",key:"1j38uz"}],["path",{d:"M15.1 18H3",key:"1nb16a"}]],YIn=rn("Text",QIn);const KIn=[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]],E1e=rn("ToggleLeft",KIn);const XIn=[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]],ryt=rn("Trash2",XIn);const JIn=[["polyline",{points:"22 17 13.5 8.5 8.5 13.5 2 7",key:"1r2t7k"}],["polyline",{points:"16 17 22 17 22 11",key:"11uiuu"}]],eAn=rn("TrendingDown",JIn);const tAn=[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]],nAn=rn("TrendingUp",tAn);const rAn=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],u3=rn("TriangleAlert",rAn);const sAn=[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]],T1e=rn("Type",sAn);const aAn=[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m15 5-3-3-3 3",key:"itvq4r"}]],iAn=rn("UnfoldVertical",aAn);const oAn=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],lAn=rn("WandSparkles",oAn);const cAn=[["circle",{cx:"12",cy:"4.5",r:"2.5",key:"r5ysbb"}],["path",{d:"m10.2 6.3-3.9 3.9",key:"1nzqf6"}],["circle",{cx:"4.5",cy:"12",r:"2.5",key:"jydg6v"}],["path",{d:"M7 12h10",key:"b7w52i"}],["circle",{cx:"19.5",cy:"12",r:"2.5",key:"1piiel"}],["path",{d:"m13.8 17.7 3.9-3.9",key:"1wyg1y"}],["circle",{cx:"12",cy:"19.5",r:"2.5",key:"13o1pw"}]],uAn=rn("Waypoints",cAn);const dAn=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]],fAn=rn("Wrench",dAn);const pAn=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],fu=rn("X",pAn);function Hi({title:e,message:t,action:n}){return o.jsx("div",{className:"flex h-[30vh] items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center justify-center px-6 py-10 text-center",children:[o.jsx("div",{className:"mb-4",children:o.jsx(hNn,{className:"size-8 text-red-900"})}),o.jsx("h3",{className:"text-ui-md text-neutral4 font-medium",children:e}),o.jsx("p",{className:"text-ui-md text-neutral2 mt-1.5 max-w-md",children:t}),n&&o.jsx("div",{className:"flex items-center justify-center pt-4",children:n})]})})}const hAn=()=>{const e=Ze(),{data:t,isLoading:n,error:r}=oc(),s=!!(t&&Om(t)&&t.capabilities.rbac),{data:a,isLoading:i,error:l}=gt({queryKey:["permission-patterns"],queryFn:()=>e.getPermissionPatterns(),enabled:s,retry:!1,staleTime:1/0});return{patterns:g.useMemo(()=>new Set(a?.patterns??[]),[a]),isLoading:n||s&&i,error:r||l}},mAn=async(e="http://localhost:4111",t)=>{try{return{status:(await fetch(e,{headers:t})).ok?"active":"inactive"}}catch{return{status:"inactive"}}},gAn=(e="http://localhost:4111",t)=>gt({queryKey:["mastra-instance-status",e,t],queryFn:()=>mAn(e,t),retry:!1}),syt=g.createContext({baseUrl:"",headers:{},apiPrefix:void 0,isLoading:!1,setConfig:()=>{}}),fH=()=>g.useContext(syt),IP="mastra-studio-config",nme="auth_header",ayt="Authorization",vAn=()=>{if(typeof window>"u")return{};const e=new URL(window.location.href).searchParams.get(nme);return e?{[ayt]:e}:{}},yAn=()=>{if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has(nme)&&(e.searchParams.delete(nme),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`))},OJ=e=>{const{[ayt]:t,...n}=e.headers;return{...e,headers:n}},bAn=({children:e,endpoint:t="http://localhost:4111",defaultApiPrefix:n="/api"})=>{const[r]=g.useState(vAn),s=Object.keys(r).length>0,{data:a,isLoading:i,error:l}=gAn(t,r),[c,u]=g.useState({baseUrl:"",headers:r,apiPrefix:void 0,isLoading:!0});g.useEffect(()=>{yAn()},[]),g.useLayoutEffect(()=>{if(l&&!i)return u({baseUrl:"",headers:r,apiPrefix:void 0,isLoading:!1});if(!a?.status)return;const f=localStorage.getItem(IP);if(f){const p=JSON.parse(f);if(typeof p=="object"&&p!==null){const h={...p,headers:{...p.headers??{},...r},apiPrefix:p.apiPrefix??n};return s&&localStorage.setItem(IP,JSON.stringify(OJ(h))),u({...h,isLoading:!1})}}if(a.status==="active"){const p={baseUrl:t,headers:r,apiPrefix:n};return s&&localStorage.setItem(IP,JSON.stringify(OJ(p))),u({...p,isLoading:!1})}return u({baseUrl:"",headers:r,apiPrefix:void 0,isLoading:!1})},[a,t,n,i,l,r,s]);const d=f=>{u(p=>{const h={...p,...f},m=s?OJ(h):h;return localStorage.setItem(IP,JSON.stringify(m)),h})};return o.jsx(syt.Provider,{value:{...c,setConfig:d},children:e})};function xAn({children:e,baseUrl:t}){const{patterns:n,isLoading:r,error:s}=hAn();if(r)return o.jsx("div",{className:"flex h-screen w-full items-center justify-center",children:o.jsx(en,{})});if(s)return o.jsx(wAn,{error:s,baseUrl:t});if(n.size>0){for(const a of Tjn)if(!n.has(a))throw new Error(`Invalid permission pattern: "${a}". It is not in the server's PERMISSION_PATTERNS — check for a typo in route-permissions.ts.`)}return o.jsx(o.Fragment,{children:e})}const wAn=({error:e,baseUrl:t})=>{const n=[`Studio could not reach the Mastra server at ${t}. Check that the instance URL and API prefix in Settings are correct, and that the server is running.`,`Error: ${e.message}`],r=()=>{localStorage.removeItem(IP),window.location.reload()};return o.jsx("div",{className:"flex h-screen w-full items-center justify-center",children:o.jsx(Hi,{title:"Failed to load studio",message:n.join(`
|
|
200
200
|
|
|
@@ -231,7 +231,7 @@ attempted value: ${i}
|
|
|
231
231
|
\${}
|
|
232
232
|
}
|
|
233
233
|
}`,{label:"class",detail:"definition",type:"keyword"}),rf('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),rf('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],Z1t=Tke.concat([rf("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),rf("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),rf("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),N8e=new Kxt,G1t=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function xR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const FUn=["FunctionDeclaration"],zUn={FunctionDeclaration:xR("function"),ClassDeclaration:xR("class"),ClassExpression:()=>!0,EnumDeclaration:xR("constant"),TypeAliasDeclaration:xR("type"),NamespaceDeclaration:xR("namespace"),VariableDefinition(e,t){e.matchContext(FUn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function Q1t(e,t){let n=N8e.get(t);if(n)return n;let r=[],s=!0;function a(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(La.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=zUn[i.name];if(l&&l(i,a)||G1t.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of Q1t(e,i.node))r.push(l);return!1}}),N8e.set(t,r),r}const CB=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,jke=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function Y1t(e){let t=xi(e.state).resolveInner(e.pos,-1);if(jke.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&CB.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)G1t.has(s.name)&&(r=r.concat(Q1t(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:CB}}function Tee(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,i;if(a?.name=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if(a?.name=="MemberExpression"&&((r=i=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(i)),t=a;else return null}}function K1t(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=xi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?Tee(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?Tee(t,n.parent,""):jke.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&CB.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?Tee(t,n,""):e.explicit?{path:[],name:""}:null}function BUn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let i=Object.getPrototypeOf(e);if(!i)return r;e=i}}function UUn(e){let t=new Map;return n=>{let r=K1t(n);if(!r)return null;let s=e;for(let i of r.path)if(s=s[i],!s)return null;let a=t.get(s);return a||t.set(s,a=BUn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:CB}}}const em=zO.define({name:"javascript",parser:LUn.configure({props:[Z_.add({IfStatement:HT({except:/^\s*({|else\b)/}),TryStatement:HT({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:M8n,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:$8n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":HT({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),G_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":lke,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name=="JSXSelfClosingTag")return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){var t;let n=(t=e.firstChild)===null||t===void 0?void 0:t.nextSibling,r=e.lastChild;return!n||n.type.isError?null:{from:n.to,to:r.type.isError?e.to:r.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),X1t={test:e=>/^JSX/.test(e.name),facet:PH({commentTokens:{block:{open:"{/*",close:"*/}"}}})},Nke=em.configure({dialect:"ts"},"typescript"),Ike=em.configure({dialect:"jsx",props:[ake.add(e=>e.isTop?[X1t]:void 0)]}),Ake=em.configure({dialect:"jsx ts",props:[ake.add(e=>e.isTop?[X1t]:void 0)]},"typescript");let J1t=e=>({label:e,type:"keyword"});const eSt="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(J1t),VUn=eSt.concat(["declare","implements","private","protected","public"].map(J1t));function EB(e={}){let t=e.jsx?e.typescript?Ake:Ike:e.typescript?Nke:em,n=e.typescript?Z1t.concat(VUn):Tke.concat(eSt);return new UO(t,[em.data.of({autocomplete:w9n(jke,Xwt(n))}),em.data.of({autocomplete:Y1t}),e.jsx?tSt:[]])}function qUn(e){for(;;){if(e.name=="JSXOpenTag"||e.name=="JSXSelfClosingTag"||e.name=="JSXFragmentTag")return e;if(e.name=="JSXEscape"||!e.parent)return null;e=e.parent}}function I8e(e,t,n=e.length){for(let r=t?.firstChild;r;r=r.nextSibling)if(r.name=="JSXIdentifier"||r.name=="JSXBuiltin"||r.name=="JSXNamespacedName"||r.name=="JSXMemberExpression")return e.sliceString(r.from,Math.min(r.to,n));return""}const HUn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),tSt=It.inputHandler.of((e,t,n,r,s)=>{if((HUn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!em.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=xi(i).resolveInner(d-1,-1),p;if(f.name=="JSXStartTag"&&(f=f.parent),!(i.doc.sliceString(d-1,d)!=r||f.name=="JSXAttributeValue"&&f.to>d)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:d,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let h=f.parent,m=h.parent;if(m&&h.from==d-2&&((p=I8e(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${p}>`;return{range:bt.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let h=qUn(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=I8e(i.doc,h,d)))return{range:c,changes:{from:d,insert:`</${p}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function WUn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:i}of em.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let u of e.verify(r.sliceDoc(a,i),t))s.push(ZUn(u,r.doc,c))}return s}}function A8e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function ZUn(e,t,n){let r=A8e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?A8e(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:i}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(u,d){u.dispatch({changes:{from:d+l,to:d+c,insert:i},scrollIntoView:!0})}}]}return s}const W6=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:tSt,completionPath:K1t,esLint:WUn,javascript:EB,javascriptLanguage:em,jsxLanguage:Ike,localCompletionSource:Y1t,scopeCompletionSource:UUn,snippets:Tke,tsxLanguage:Ake,typescriptLanguage:Nke,typescriptSnippets:Z1t},Symbol.toStringTag,{value:"Module"})),wR=["_blank","_self","_top","_parent"],jee=["ascii","utf-8","utf-16","latin1","latin1"],Nee=["get","post","put","delete"],Iee=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],cp=["true","false"],tr={},GUn={a:{attrs:{href:null,ping:null,type:null,media:null,target:wR,hreflang:null}},abbr:tr,address:tr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:tr,aside:tr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:tr,base:{attrs:{href:null,target:wR}},bdi:tr,bdo:tr,blockquote:{attrs:{cite:null}},body:tr,br:tr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Iee,formmethod:Nee,formnovalidate:["novalidate"],formtarget:wR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:tr,center:tr,cite:tr,code:tr,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:tr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:tr,div:tr,dl:tr,dt:tr,em:tr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:tr,figure:tr,footer:tr,form:{attrs:{action:null,name:null,"accept-charset":jee,autocomplete:["on","off"],enctype:Iee,method:Nee,novalidate:["novalidate"],target:wR}},h1:tr,h2:tr,h3:tr,h4:tr,h5:tr,h6:tr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:tr,hgroup:tr,hr:tr,html:{attrs:{manifest:null}},i:tr,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Iee,formmethod:Nee,formnovalidate:["novalidate"],formtarget:wR,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:tr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:tr,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:tr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:jee,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:tr,noscript:tr,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:tr,param:{attrs:{name:null,value:null}},pre:tr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:tr,rt:tr,ruby:tr,samp:tr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:jee}},section:tr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:tr,source:{attrs:{src:null,type:null,media:null}},span:tr,strong:tr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:tr,summary:tr,sup:tr,table:tr,tbody:tr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:tr,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:tr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:tr,time:{attrs:{datetime:null}},title:tr,tr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:tr,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:tr},nSt={accesskey:null,class:null,contenteditable:cp,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:cp,autocorrect:cp,autocapitalize:cp,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":cp,"aria-autocomplete":["inline","list","both","none"],"aria-busy":cp,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":cp,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":cp,"aria-hidden":cp,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":cp,"aria-multiselectable":cp,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":cp,"aria-relevant":null,"aria-required":cp,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},rSt="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(e=>"on"+e);for(let e of rSt)nSt[e]=null;class vM{constructor(t,n){this.tags={...GUn,...t},this.globalAttrs={...nSt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}vM.default=new vM;function zj(e,t,n=e.length){if(!t)return"";let r=t.firstChild,s=r&&r.getChild("TagName");return s?e.sliceString(s.from,Math.min(s.to,n)):""}function Bj(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function sSt(e,t,n){let r=n.tags[zj(e,Bj(t))];return r?.children||n.allTags}function Rke(e,t){let n=[];for(let r=Bj(t);r&&!r.type.isTop;r=Bj(r.parent)){let s=zj(e,r);if(s&&r.lastChild.name=="CloseTag")break;s&&n.indexOf(s)<0&&(t.name=="EndTag"||t.from>=r.firstChild.to)&&n.push(s)}return n}const aSt=/^[:\-\.\w\u00b7-\uffff]*$/;function R8e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=Bj(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:sSt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(Rke(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function P8e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:Rke(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:aSt}}function QUn(e,t,n,r){let s=[],a=0;for(let i of sSt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of Rke(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function YUn(e,t,n,r,s){let a=Bj(n),i=a?t.tags[zj(e.doc,a)]:null,l=i&&i.attrs?Object.keys(i.attrs):[],c=i&&i.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(u=>({label:u,type:"property"})),validFor:aSt}}function KUn(e,t,n,r,s){var a;let i=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(i){let u=e.sliceDoc(i.from,i.to),d=t.globalAttrs[u];if(!d){let f=Bj(n),p=f?t.tags[zj(e.doc,f)]:null;d=p?.attrs&&p.attrs[u]}if(d){let f=e.sliceDoc(r,s).toLowerCase(),p='"',h='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,p="",h=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let m of d)l.push({label:m,apply:p+m+h,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function iSt(e,t){let{state:n,pos:r}=t,s=xi(n).resolveInner(r,-1),a=s.resolve(r);for(let i=r,l;a==s&&(l=s.childBefore(i));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,i=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?P8e(n,s,s.from,r):R8e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?R8e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?P8e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?YUn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?KUn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?QUn(n,e,s,r):null}function XUn(e){return iSt(vM.default,e)}function JUn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new vM(t,n):vM.default;return s=>iSt(r,s)}const eVn=em.parser.configure({top:"SingleExpression"}),oSt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:Nke.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:Ike.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:Ake.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:eVn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:em.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:_B.parser}],lSt=[{name:"style",parser:_B.parser.configure({top:"Styles"})}].concat(rSt.map(e=>({name:e,parser:em.parser}))),cSt=zO.define({name:"html",parser:_Bn.configure({props:[Z_.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),G_.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),Hwt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),E8=cSt.configure({wrap:z1t(oSt,lSt)});function tVn(e={}){let t="",n;e.matchClosingTags===!1&&(t="noMatch"),e.selfClosingTags===!0&&(t=(t?t+" ":"")+"selfClosing"),(e.nestedLanguages&&e.nestedLanguages.length||e.nestedAttributes&&e.nestedAttributes.length)&&(n=z1t((e.nestedLanguages||[]).concat(oSt),(e.nestedAttributes||[]).concat(lSt)));let r=n?cSt.configure({wrap:n,dialect:t}):t?E8.configure({dialect:t}):E8;return new UO(r,[E8.data.of({autocomplete:JUn(e)}),e.autoCloseTags!==!1?nVn:[],EB().support,oUn().support])}const $8e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),nVn=It.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!E8.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let p=i.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,m=xi(i).resolveInner(h,-1),v;if(p&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(v=zj(i.doc,y.parent,h))&&!$8e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`</${v}>`;return{range:c,changes:{from:h,to:b,insert:x}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==h-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(v=zj(i.doc,y,h))&&!$8e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`${v}>`;return{range:bt.cursor(h+x.length,-1),changes:{from:h,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),uSt=PH({commentTokens:{block:{open:"<!--",close:"-->"}}}),dSt=new Dr,fSt=E7n.configure({props:[G_.add(e=>!e.is("Block")||e.is("Document")||$ge(e)!=null||rVn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),dSt.add($ge),Z_.add({Document:()=>null}),Iw.add({Document:uSt})]});function $ge(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function rVn(e){return e.name=="OrderedList"||e.name=="BulletList"}function sVn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=$ge(r.type))!=null&&s<=t)break;n=r}return n.to}const aVn=Rwt.of((e,t,n)=>{for(let r=xi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(dSt);if(s==null)continue;let a=sVn(r,s);if(a>n)return{from:n,to:a}}return null});function Pke(e){return new Np(uSt,e,[],"markdown")}const pSt=Pke(fSt),iVn=fSt.configure([L7n,z7n,F7n,B7n,{props:[G_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),HO=Pke(iVn);function oVn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=ig.matchLanguageName(e,n,!0),r instanceof ig)return r.support?r.support.language.parser:BO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class Aee{constructor(t,n,r,s,a,i,l){this.node=t,this.from=n,this.to=r,this.spaceBefore=s,this.spaceAfter=a,this.type=i,this.item=l}blank(t,n=!0){let r=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(t!=null){for(;r.length<t;)r+=" ";return r}else{for(let s=this.to-this.from-r.length-this.spaceAfter.length;s>0;s--)r+=" ";return r+(n?this.spaceAfter:"")}}marker(t,n){let r=this.node.name=="OrderedList"?String(+mSt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function hSt(e,t){let n=[],r=[];for(let s=e;s;s=s.parent){if(s.name=="FencedCode")return r;(s.name=="ListItem"||s.name=="Blockquote")&&n.push(s)}for(let s=n.length-1;s>=0;s--){let a=n[s],i,l=t.lineAt(a.from),c=a.from-l.from;if(a.name=="Blockquote"&&(i=/^ *>( ?)/.exec(l.text.slice(c))))r.push(new Aee(a,c,c+i[0].length,"",i[1],">",null));else if(a.name=="ListItem"&&a.parent.name=="OrderedList"&&(i=/^( *)\d+([.)])( *)/.exec(l.text.slice(c)))){let u=i[3],d=i[0].length;u.length>=4&&(u=u.slice(0,u.length-4),d-=4),r.push(new Aee(a.parent,c,c+d,i[1],u,i[2],a))}else if(a.name=="ListItem"&&a.parent.name=="BulletList"&&(i=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(c)))){let u=i[4],d=i[0].length;u.length>4&&(u=u.slice(0,u.length-4),d-=4);let f=i[2];i[3]&&(f+=i[3].replace(/[xX]/," ")),r.push(new Aee(a.parent,c,c+d,i[1],u,f,a))}}return r}function mSt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function Ree(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=mSt(a,t),c=+l[2];if(s>=0){if(c!=s+1)return;n.push({from:a.from+l[1].length,to:a.from+l[0].length,insert:String(s+2+r)})}s=c}let i=a.nextSibling;if(!i)break;a=i}}function $ke(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(uI)!=" ")return e;let r=Dg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const gSt=(e={})=>({state:t,dispatch:n})=>{let r=xi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!HO.isActiveAt(t,l.from,-1)&&!HO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=hSt(r.resolveInner(c,-1),s);for(;d.length&&d[d.length-1].from>c-u.from;)d.pop();if(!d.length)return a={range:l};let f=d[d.length-1];if(f.to-f.spaceAfter.length>c-u.from)return a={range:l};let p=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&p){let b=f.node.firstChild,x=f.node.getChild("ListItem","ListItem");if(b.to>=c||x&&x.to<c||u.from>0&&!/[^\s>]/.test(s.lineAt(u.from-1).text)||e.nonTightLists===!1){let S=d.length>1?d[d.length-2]:null,k,_="";S&&S.item?(k=u.from+S.from,_=S.marker(s,1)):k=u.from+(S?S.to:0);let C=[{from:k,to:c,insert:_}];return f.node.name=="OrderedList"&&Ree(f.item,s,C,-2),S&&S.node.name=="OrderedList"&&Ree(S.item,s,C),{range:bt.cursor(k+_.length),changes:C}}else{let S=D8e(d,t,u);return{range:bt.cursor(c+S.length+1),changes:{from:u.from,insert:S+t.lineBreak}}}}if(f.node.name=="Blockquote"&&p&&u.from){let b=s.lineAt(u.from-1),x=/>\s*$/.exec(b.text);if(x&&x.index==f.from){let S=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(S),changes:S}}}let h=[];f.node.name=="OrderedList"&&Ree(f.item,s,h);let m=f.item&&f.item.from<u.from,v="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)v+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?Dg(u.text,4,d[b+1].from)-v.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return v=$ke(v,t),lVn(f.node,t.doc)&&(v=D8e(d,t,u)+t.lineBreak+v),h.push({from:y,to:c,insert:t.lineBreak+v}),{range:bt.cursor(y+v.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},vSt=gSt();function M8e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function lVn(e,t){if(e.name!="OrderedList"&&e.name!="BulletList")return!1;let n=e.firstChild,r=e.getChild("ListItem","ListItem");if(!r)return!1;let s=t.lineAt(n.to),a=t.lineAt(r.from),i=/^[\s>]*$/.test(s.text);return s.number+(i?0:1)<a.number}function D8e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Dg(n.text,4,e[s+1].from)-r.length:null,s<a);return $ke(r,t)}function cVn(e,t){let n=e.resolveInner(t,-1),r=t;M8e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(M8e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const ySt=({state:e,dispatch:t})=>{let n=xi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&HO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=hSt(cVn(n,i),l);if(u.length){let d=u[u.length-1],f=d.to-d.spaceAfter.length+(d.spaceAfter?1:0);if(i-c.from>f&&!/\S/.test(c.text.slice(f,i-c.from)))return{range:bt.cursor(c.from+f),changes:{from:c.from+f,to:i}};if(i-c.from==f&&(!d.item||c.from<=d.item.from||!/\S/.test(c.text.slice(0,d.to)))){let p=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let h=d.blank(Dg(c.text,4,d.to)-Dg(c.text,4,d.from));return p==c.from&&(h=$ke(h,e)),{range:bt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:bt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},bSt=[{key:"Enter",run:vSt},{key:"Backspace",run:ySt}],xSt=tVn({matchClosingTags:!1});function Mke(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=pSt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=xSt}=e;if(!(s instanceof LH))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,aVn],d;i&&u.push(wSt),n instanceof UO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?oVn(t,d):void 0;c.push(j7n({codeParser:f,htmlParser:l.language.parser})),r&&u.push(th.high(cI.of(bSt)));let p=Pke(s.configure(c));return a&&u.push(p.data.of({autocomplete:uVn})),new UO(p,u)}function uVn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=xi(t).resolveInner(n,-1);for(;s&&!s.type.isTop;){if(s.name=="CodeBlock"||s.name=="FencedCode"||s.name=="ProcessingInstructionBlock"||s.name=="CommentBlock"||s.name=="Link"||s.name=="Image")return null;s=s.parent}return{from:n-r[0].length,to:n,options:dVn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let Pee=null;function dVn(){if(Pee)return Pee;let e=XUn(new fke(us.create({extensions:xSt}),0,!0));return Pee=e?e.options:[]}const fVn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,wSt=It.domEventHandlers({paste:(e,t)=>{var n;let{main:r}=t.state.selection;if(r.empty)return!1;let s=(n=e.clipboardData)===null||n===void 0?void 0:n.getData("text/plain");if(!s||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(s)||(/^www\./.test(s)&&(s="https://"+s),!HO.isActiveAt(t.state,r.from,1)))return!1;let a=xi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||fVn.test(l.name))&&(i=!0)},leave:l=>{l.to<r.to&&(i=!0)}}),i?!1:(t.dispatch({changes:[{from:r.from,insert:"["},{from:r.to,insert:`](${s})`}],userEvent:"input.paste",scrollIntoView:!0}),!0)}}),pVn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:pSt,deleteMarkupBackward:ySt,insertNewlineContinueMarkup:vSt,insertNewlineContinueMarkupCommand:gSt,markdown:Mke,markdownKeymap:bSt,markdownLanguage:HO,pasteURLAsLink:wSt},Symbol.toStringTag,{value:"Module"}));function WO(){return WO=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},WO.apply(null,arguments)}var hVn=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,a=s===void 0?[]:s,i={".cm-gutters":{}},l={};r.background&&(l.backgroundColor=r.background),r.backgroundImage&&(l.backgroundImage=r.backgroundImage),r.foreground&&(l.color=r.foreground),r.fontSize&&(l.fontSize=r.fontSize),(r.background||r.foreground)&&(i["&"]=l),r.fontFamily&&(i["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(i[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(i[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(i[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(i[".cm-content"]={caretColor:r.caret},i[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var c={};r.gutterActiveForeground&&(c.color=r.gutterActiveForeground),r.lineHighlight&&(i[".cm-activeLine"]={backgroundColor:r.lineHighlight},c.backgroundColor=r.lineHighlight),i[".cm-activeLineGutter"]=c,r.selection&&(i["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(i["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var u=It.theme(i,{dark:t==="dark"}),d=Hg.define(a),f=[u,eS(d)];return f},mVn={background:"#282a36",foreground:"#f8f8f2",caret:"#f8f8f0",selection:"rgba(255, 255, 255, 0.1)",selectionMatch:"rgba(255, 255, 255, 0.2)",gutterBackground:"#282a36",gutterForeground:"#6D8A88",gutterBorder:"transparent",lineHighlight:"rgba(255, 255, 255, 0.1)"},gVn=[{tag:he.comment,color:"#6272a4"},{tag:he.string,color:"#f1fa8c"},{tag:he.atom,color:"#bd93f9"},{tag:he.meta,color:"#f8f8f2"},{tag:[he.keyword,he.operator,he.tagName],color:"#ff79c6"},{tag:[he.function(he.propertyName),he.propertyName],color:"#66d9ef"},{tag:[he.definition(he.variableName),he.function(he.variableName),he.className,he.attributeName],color:"#50fa7b"},{tag:he.atom,color:"#bd93f9"}],fI=e=>{var t=e||{},n=t.theme,r=n===void 0?"dark":n,s=t.settings,a=s===void 0?{}:s,i=t.styles,l=i===void 0?[]:i;return hVn({theme:r,settings:WO({},mVn,a),styles:[...gVn,...l]})};fI();function SSt(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}const vVn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=Lke(e.state,n.from);return r.line?yVn(e):r.block?xVn(e):!1};function Dke(e,t){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let s=e(t,n);return s?(r(n.update(s)),!0):!1}}const yVn=Dke(kVn,0),bVn=Dke(kSt,0),xVn=Dke((e,t)=>kSt(e,t,SVn(t)),0);function Lke(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const SR=50;function wVn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-SR,r),i=e.sliceDoc(s,s+SR),l=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(i)[0].length,u=a.length-l;if(a.slice(u-t.length,u)==t&&i.slice(c,c+n.length)==n)return{open:{pos:r-l,margin:l&&1},close:{pos:s+c,margin:c&&1}};let d,f;s-r<=2*SR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+SR),f=e.sliceDoc(s-SR,s));let p=/^\s*/.exec(d)[0].length,h=/\s*$/.exec(f)[0].length,m=f.length-h-n.length;return d.slice(p,p+t.length)==t&&f.slice(m,m+n.length)==n?{open:{pos:r+p+t.length,margin:/\s/.test(d.charAt(p+t.length))?1:0},close:{pos:s-h-n.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function SVn(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),s=n.to<=r.to?r:e.doc.lineAt(n.to);s.from>r.from&&s.from==n.to&&(s=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=s.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return t}function kSt(e,t,n=t.selection.ranges){let r=n.map(a=>Lke(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>wVn(t,r[i],a.from,a.to));if(e!=2&&!s.every(a=>a))return{changes:t.changes(n.map((a,i)=>s[i]?[]:[{from:a.from,insert:r[i].open+" "},{from:a.to,insert:" "+r[i].close}]))};if(e!=1&&s.some(a=>a)){let a=[];for(let i=0,l;i<s.length;i++)if(l=s[i]){let c=r[i],{open:u,close:d}=l;a.push({from:u.pos-c.open.length,to:u.pos+u.margin},{from:d.pos-d.margin,to:d.pos+c.close.length})}return{changes:a}}return null}function kVn(e,t,n=t.selection.ranges){let r=[],s=-1;e:for(let{from:a,to:i}of n){let l=r.length,c=1e9,u;for(let d=a;d<=i;){let f=t.doc.lineAt(d);if(u==null&&(u=Lke(t,f.from).line,!u))continue e;if(f.from>s&&(a==i||i>f.from)){s=f.from;let p=/^\s*/.exec(f.text)[0].length,h=p==f.length,m=f.text.slice(p,p+u.length)==u?p:-1;p<f.text.length&&p<c&&(c=p),r.push({line:f,comment:m,token:u,indent:p,empty:h,single:!1})}d=f.to+1}if(c<1e9)for(let d=l;d<r.length;d++)r[d].indent<r[d].line.text.length&&(r[d].indent=c);r.length==l+1&&(r[l].single=!0)}if(e!=2&&r.some(a=>a.comment<0&&(!a.empty||a.single))){let a=[];for(let{line:l,token:c,indent:u,empty:d,single:f}of r)(f||!d)&&a.push({from:l.from+u,insert:c+" "});let i=t.changes(a);return{changes:i,selection:t.selection.map(i,1)}}else if(e!=1&&r.some(a=>a.comment>=0)){let a=[];for(let{line:i,comment:l,token:c}of r)if(l>=0){let u=i.from+l,d=u+c.length;i.text[d-i.from]==" "&&d++,a.push({from:u,to:d})}return{changes:a}}return null}const Mge=Fy.define(),OVn=Fy.define(),_Vn=jn.define(),OSt=jn.define({combine(e){return zy(e,{minDepth:100,newGroupDelay:500,joinToEvent:(t,n)=>n},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(t,n)=>(r,s)=>t(r,s)||n(r,s)})}}),_St=bl.define({create(){return Wv.empty},update(e,t){let n=t.state.facet(OSt),r=t.annotation(Mge);if(r){let c=bf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=TB(d,d.length,n.minDepth,c):d=TSt(d,t.startState.selection),new Wv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(OVn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Pl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=bf.fromTransaction(t),i=t.annotation(Pl.time),l=t.annotation(Pl.userEvent);return a?e=e.addChanges(a,i,l,n,t):t.selection&&(e=e.addSelection(t.startState.selection,i,l,n.newGroupDelay)),(s=="full"||s=="after")&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(t=>t.toJSON()),undone:e.undone.map(t=>t.toJSON())}},fromJSON(e){return new Wv(e.done.map(bf.fromJSON),e.undone.map(bf.fromJSON))}});function CVn(e={}){return[_St,OSt.of(e),It.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?CSt:t.inputType=="historyRedo"?Dge:null;return r?(t.preventDefault(),r(n)):!1}})]}function FH(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(_St,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const CSt=FH(0,!1),Dge=FH(1,!1),EVn=FH(0,!0),TVn=FH(1,!0);class bf{constructor(t,n,r,s,a){this.changes=t,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=a}setSelAfter(t){return new bf(this.changes,this.effects,this.mapped,this.startSelection,t)}toJSON(){var t,n,r;return{changes:(t=this.changes)===null||t===void 0?void 0:t.toJSON(),mapped:(n=this.mapped)===null||n===void 0?void 0:n.toJSON(),startSelection:(r=this.startSelection)===null||r===void 0?void 0:r.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(t){return new bf(t.changes&&Al.fromJSON(t.changes),[],t.mapped&&ry.fromJSON(t.mapped),t.startSelection&&bt.fromJSON(t.startSelection),t.selectionsAfter.map(bt.fromJSON))}static fromTransaction(t,n){let r=qh;for(let s of t.startState.facet(_Vn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new bf(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,qh)}static selection(t){return new bf(void 0,qh,void 0,void 0,t)}}function TB(e,t,n,r){let s=t+1>n+20?t-n-1:0,a=e.slice(s,t);return a.push(r),a}function jVn(e,t){let n=[],r=!1;return e.iterChangedRanges((s,a)=>n.push(s,a)),t.iterChangedRanges((s,a,i,l)=>{for(let c=0;c<n.length;){let u=n[c++],d=n[c++];l>=u&&i<=d&&(r=!0)}}),r}function NVn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function ESt(e,t){return e.length?t.length?e.concat(t):e:t}const qh=[],IVn=200;function TSt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-IVn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),TB(e,e.length-1,1e9,n.setSelAfter(r)))}else return[bf.selection([t])]}function AVn(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function $ee(e,t){if(!e.length)return e;let n=e.length,r=qh;for(;n;){let s=RVn(e[n-1],t,r);if(s.changes&&!s.changes.empty||s.effects.length){let a=e.slice(0,n);return a[n-1]=s,a}else t=s.mapped,n--,r=s.selectionsAfter}return r.length?[bf.selection(r)]:qh}function RVn(e,t,n){let r=ESt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):qh,n);if(!e.changes)return bf.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new bf(s,xr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const PVn=/^(input\.type|delete)($|\.)/;class Wv{constructor(t,n,r=0,s=void 0){this.done=t,this.undone=n,this.prevTime=r,this.prevUserEvent=s}isolate(){return this.prevTime?new Wv(this.done,this.undone):this}addChanges(t,n,r,s,a){let i=this.done,l=i[i.length-1];return l&&l.changes&&!l.changes.empty&&t.changes&&(!r||PVn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,jVn(l.changes,t.changes))||r=="input.type.compose")?i=TB(i,i.length-1,s.minDepth,new bf(t.changes.compose(l.changes),ESt(xr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,qh)):i=TB(i,i.length,s.minDepth,t),new Wv(i,qh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:qh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&NVn(a[a.length-1],t)?this:new Wv(TSt(this.done,t),this.undone,n,r)}addMapping(t){return new Wv($ee(this.done,t),$ee(this.undone,t),this.prevTime,this.prevUserEvent)}pop(t,n,r){let s=t==0?this.done:this.undone;if(s.length==0)return null;let a=s[s.length-1],i=a.selectionsAfter[0]||(a.startSelection?a.startSelection.map(a.changes.invertedDesc,1):n.selection);if(r&&a.selectionsAfter.length)return n.update({selection:a.selectionsAfter[a.selectionsAfter.length-1],annotations:Mge.of({side:t,rest:AVn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?qh:s.slice(0,s.length-1);return a.mapped&&(l=$ee(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:Mge.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Wv.empty=new Wv(qh,qh);const $Vn=[{key:"Mod-z",run:CSt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Dge,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Dge,preventDefault:!0},{key:"Mod-u",run:EVn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:TVn,preventDefault:!0}];function pI(e,t){return bt.create(e.ranges.map(t),e.mainIndex)}function Wg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function Zg({state:e,dispatch:t},n){let r=pI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Wg(e,r)),!0)}function zH(e,t){return bt.cursor(t?e.to:e.from)}function jSt(e,t){return Zg(e,n=>n.empty?e.moveByChar(n,t):zH(n,t))}function nd(e){return e.textDirectionAt(e.state.selection.main.head)==Ci.LTR}const NSt=e=>jSt(e,!nd(e)),ISt=e=>jSt(e,nd(e));function ASt(e,t){return Zg(e,n=>n.empty?e.moveByGroup(n,t):zH(n,t))}const MVn=e=>ASt(e,!nd(e)),DVn=e=>ASt(e,nd(e));function LVn(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function BH(e,t,n){let r=xi(e).resolveInner(t.head),s=n?Dr.closedBy:Dr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;LVn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?Hv(e,r.from,1):Hv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,bt.cursor(l,n?-1:1)}const FVn=e=>Zg(e,t=>BH(e.state,t,!nd(e))),zVn=e=>Zg(e,t=>BH(e.state,t,nd(e)));function RSt(e,t){return Zg(e,n=>{if(!n.empty)return zH(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const PSt=e=>RSt(e,!1),$St=e=>RSt(e,!0);function MSt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(It.scrollMargins)){let i=a(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}s=e.scrollDOM.clientHeight-n-r}else s=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,s-5)}}function DSt(e,t){let n=MSt(e),{state:r}=e,s=pI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):zH(i,t));if(s.eq(r.selection))return!1;let a;if(n.selfScroll){let i=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;i&&i.top>c&&i.bottom<u&&(a=It.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Wg(r,s),{effects:a}),!0}const L8e=e=>DSt(e,!1),Lge=e=>DSt(e,!0);function tS(e,t,n){let r=e.lineBlockAt(t.head),s=e.moveToLineBoundary(t,n);if(s.head==t.head&&s.head!=(n?r.to:r.from)&&(s=e.moveToLineBoundary(t,n,!1)),!n&&s.head==r.from&&r.length){let a=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;a&&t.head!=r.from+a&&(s=bt.cursor(r.from+a))}return s}const BVn=e=>Zg(e,t=>tS(e,t,!0)),UVn=e=>Zg(e,t=>tS(e,t,!1)),VVn=e=>Zg(e,t=>tS(e,t,!nd(e))),qVn=e=>Zg(e,t=>tS(e,t,nd(e))),HVn=e=>Zg(e,t=>bt.cursor(e.lineBlockAt(t.head).from,1)),WVn=e=>Zg(e,t=>bt.cursor(e.lineBlockAt(t.head).to,-1));function ZVn(e,t,n){let r=!1,s=pI(e.selection,a=>{let i=Hv(e,a.head,-1)||Hv(e,a.head,1)||a.head>0&&Hv(e,a.head-1,1)||a.head<e.doc.length&&Hv(e,a.head+1,-1);if(!i||!i.end)return a;r=!0;let l=i.start.from==a.head?i.end.to:i.end.from;return bt.cursor(l)});return r?(t(Wg(e,s)),!0):!1}const GVn=({state:e,dispatch:t})=>ZVn(e,t);function Tm(e,t,n){let r=pI(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=bt.range(s.head,s.anchor));let a=n(s);return bt.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(Wg(e.state,r)),!0)}function LSt(e,t){return Tm(e,t,n=>e.moveByChar(n,t))}const FSt=e=>LSt(e,!nd(e)),zSt=e=>LSt(e,nd(e));function BSt(e,t){return Tm(e,t,n=>e.moveByGroup(n,t))}const QVn=e=>BSt(e,!nd(e)),YVn=e=>BSt(e,nd(e)),KVn=e=>{let t=!nd(e);return Tm(e,t,n=>BH(e.state,n,t))},XVn=e=>{let t=nd(e);return Tm(e,t,n=>BH(e.state,n,t))};function USt(e,t){return Tm(e,t,n=>e.moveVertically(n,t))}const VSt=e=>USt(e,!1),qSt=e=>USt(e,!0);function HSt(e,t){return Tm(e,t,n=>e.moveVertically(n,t,MSt(e).height))}const F8e=e=>HSt(e,!1),z8e=e=>HSt(e,!0),JVn=e=>Tm(e,!0,t=>tS(e,t,!0)),eqn=e=>Tm(e,!1,t=>tS(e,t,!1)),tqn=e=>{let t=!nd(e);return Tm(e,t,n=>tS(e,n,t))},nqn=e=>{let t=nd(e);return Tm(e,t,n=>tS(e,n,t))},rqn=e=>Tm(e,!1,t=>bt.cursor(e.lineBlockAt(t.head).from)),sqn=e=>Tm(e,!0,t=>bt.cursor(e.lineBlockAt(t.head).to)),B8e=({state:e,dispatch:t})=>(t(Wg(e,{anchor:0})),!0),U8e=({state:e,dispatch:t})=>(t(Wg(e,{anchor:e.doc.length})),!0),V8e=({state:e,dispatch:t})=>(t(Wg(e,{anchor:e.selection.main.anchor,head:0})),!0),q8e=({state:e,dispatch:t})=>(t(Wg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),aqn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),iqn=({state:e,dispatch:t})=>{let n=UH(e).map(({from:r,to:s})=>bt.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:bt.create(n),userEvent:"select"})),!0},oqn=({state:e,dispatch:t})=>{let n=pI(e.selection,r=>{let s=xi(e),a=s.resolveStack(r.from,1);if(r.empty){let i=s.resolveStack(r.from,-1);i.node.from>=a.node.from&&i.node.to<=a.node.to&&(a=i)}for(let i=a;i;i=i.next){let{node:l}=i;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&i.next)return bt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Wg(e,n)),!0)};function WSt(e,t){let{state:n}=e,r=n.selection,s=n.selection.ranges.slice();for(let a of n.selection.ranges){let i=n.doc.lineAt(a.head);if(t?i.to<e.state.doc.length:i.from>0)for(let l=a;;){let c=e.moveVertically(l,t);if(c.head<i.from||c.head>i.to){s.some(u=>u.head==c.head)||s.push(c);break}else{if(c.head==l.head)break;l=c}}}return s.length==r.ranges.length?!1:(e.dispatch(Wg(n,bt.create(s,s.length-1))),!0)}const lqn=e=>WSt(e,!1),cqn=e=>WSt(e,!0),uqn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=bt.create([n.main]):n.main.empty||(r=bt.create([bt.cursor(n.main.head)])),r?(t(Wg(e,r)),!0):!1};function A3(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(a=>{let{from:i,to:l}=a;if(i==l){let c=t(a);c<i?(n="delete.backward",c=Z6(e,c,!1)):c>i&&(n="delete.forward",c=Z6(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=Z6(e,i,!1),l=Z6(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:bt.cursor(i,i<a.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?It.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function Z6(e,t,n){if(e instanceof It)for(let r of e.state.facet(It.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const ZSt=(e,t,n)=>A3(e,r=>{let s=r.from,{state:a}=e,i=a.doc.lineAt(s),l,c;if(n&&!t&&s>i.from&&s<i.from+200&&!/[^ \t]/.test(l=i.text.slice(0,s-i.from))){if(l[l.length-1]==" ")return s-1;let u=Dg(l,a.tabSize),d=u%VO(a)||VO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Oc(i.text,s-i.from,t,t)+i.from,c==s&&i.number!=(t?a.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(i.text.slice(c-i.from,s-i.from))&&(c=Oc(i.text,c-i.from,!1,!1)+i.from);return c}),Fge=e=>ZSt(e,!1,!0),GSt=e=>ZSt(e,!0,!1),QSt=(e,t)=>A3(e,n=>{let r=n.head,{state:s}=e,a=s.doc.lineAt(r),i=s.charCategorizer(r);for(let l=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?s.doc.lines:1)&&(r+=t?1:-1);break}let c=Oc(a.text,r-a.from,t)+a.from,u=a.text.slice(Math.min(r,c)-a.from,Math.max(r,c)-a.from),d=i(u);if(l!=null&&d!=l)break;(u!=" "||r!=n.head)&&(l=d),r=c}return r}),YSt=e=>QSt(e,!1),dqn=e=>QSt(e,!0),fqn=e=>A3(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),pqn=e=>A3(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),hqn=e=>A3(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),mqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:ka.of(["",""])},range:bt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},gqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>{if(!r.empty||r.from==0||r.from==e.doc.length)return{range:r};let s=r.from,a=e.doc.lineAt(s),i=s==a.from?s-1:Oc(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Oc(a.text,s-a.from,!0)+a.from;return{changes:{from:i,to:l,insert:e.doc.slice(s,l).append(e.doc.slice(i,s))},range:bt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function UH(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=s.number){let i=t[t.length-1];i.to=a.to,i.ranges.push(r)}else t.push({from:s.from,to:a.to,ranges:[r]});n=a.number+1}return t}function KSt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of UH(e)){if(n?a.to==e.doc.length:a.from==0)continue;let i=e.doc.lineAt(n?a.to+1:a.from-1),l=i.length+1;if(n){r.push({from:a.to,to:i.to},{from:a.from,insert:i.text+e.lineBreak});for(let c of a.ranges)s.push(bt.range(Math.min(e.doc.length,c.anchor+l),Math.min(e.doc.length,c.head+l)))}else{r.push({from:i.from,to:a.from},{from:a.to,insert:e.lineBreak+i.text});for(let c of a.ranges)s.push(bt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:bt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const vqn=({state:e,dispatch:t})=>KSt(e,t,!1),yqn=({state:e,dispatch:t})=>KSt(e,t,!0);function XSt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of UH(e))n?r.push({from:a.from,insert:e.doc.slice(a.from,a.to)+e.lineBreak}):r.push({from:a.to,insert:e.lineBreak+e.doc.slice(a.from,a.to)});let s=e.changes(r);return t(e.update({changes:s,selection:e.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const bqn=({state:e,dispatch:t})=>XSt(e,t,!1),xqn=({state:e,dispatch:t})=>XSt(e,t,!0),wqn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(UH(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=pI(t.selection,s=>{let a;if(e.lineWrapping){let i=e.lineBlockAt(s.head),l=e.coordsAtPos(s.head,s.assoc||1);l&&(a=i.bottom+e.documentTop-l.bottom+e.defaultLineHeight/2)}return e.moveVertically(s,!0,a)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function Sqn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=xi(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),a;return r&&s&&r.to<=t&&s.from>=t&&(a=r.type.prop(Dr.closedBy))&&a.indexOf(s.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(s.from).from&&!/\S/.test(e.sliceDoc(r.to,s.from))?{from:r.to,to:s.from}:null}const H8e=JSt(!1),kqn=JSt(!0);function JSt(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(s=>{let{from:a,to:i}=s,l=t.doc.lineAt(a),c=!e&&a==i&&Sqn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new $H(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=ike(u,a);for(d==null&&(d=Dg(/^\s*/.exec(t.doc.lineAt(a).text)[0],t.tabSize));i<l.to&&/\s/.test(l.text[i-l.from]);)i++;c?{from:a,to:i}=c:a>l.from&&a<l.from+100&&!/\S/.test(l.text.slice(0,a))&&(a=l.from);let f=["",cM(t,d)];return c&&f.push(cM(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:ka.of(f)},range:bt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function Fke(e,t){let n=-1;return e.changeByRange(r=>{let s=[];for(let i=r.from;i<=r.to;){let l=e.doc.lineAt(i);l.number>n&&(r.empty||r.to>l.from)&&(t(l,s,r),n=l.number),i=l.to+1}let a=e.changes(s);return{changes:s,range:bt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const Oqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new $H(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=Fke(e,(a,i,l)=>{let c=ike(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=cM(e,c);(u!=d||l.from<a.from+u.length)&&(n[a.from]=c,i.push({from:a.from,to:a.from+u.length,insert:d}))});return s.changes.empty||t(e.update(s,{userEvent:"indent"})),!0},ekt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(Fke(e,(n,r)=>{r.push({from:n.from,insert:e.facet(uI)})}),{userEvent:"input.indent"})),!0),tkt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(Fke(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Dg(s,e.tabSize),i=0,l=cM(e,Math.max(0,a-VO(e)));for(;i<s.length&&i<l.length&&s.charCodeAt(i)==l.charCodeAt(i);)i++;r.push({from:n.from+i,to:n.from+s.length,insert:l.slice(i)})}),{userEvent:"delete.dedent"})),!0),_qn=e=>(e.setTabFocusMode(),!0),Cqn=[{key:"Ctrl-b",run:NSt,shift:FSt,preventDefault:!0},{key:"Ctrl-f",run:ISt,shift:zSt},{key:"Ctrl-p",run:PSt,shift:VSt},{key:"Ctrl-n",run:$St,shift:qSt},{key:"Ctrl-a",run:HVn,shift:rqn},{key:"Ctrl-e",run:WVn,shift:sqn},{key:"Ctrl-d",run:GSt},{key:"Ctrl-h",run:Fge},{key:"Ctrl-k",run:fqn},{key:"Ctrl-Alt-h",run:YSt},{key:"Ctrl-o",run:mqn},{key:"Ctrl-t",run:gqn},{key:"Ctrl-v",run:Lge}],Eqn=[{key:"ArrowLeft",run:NSt,shift:FSt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:MVn,shift:QVn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:VVn,shift:tqn,preventDefault:!0},{key:"ArrowRight",run:ISt,shift:zSt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:DVn,shift:YVn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:qVn,shift:nqn,preventDefault:!0},{key:"ArrowUp",run:PSt,shift:VSt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:B8e,shift:V8e},{mac:"Ctrl-ArrowUp",run:L8e,shift:F8e},{key:"ArrowDown",run:$St,shift:qSt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:U8e,shift:q8e},{mac:"Ctrl-ArrowDown",run:Lge,shift:z8e},{key:"PageUp",run:L8e,shift:F8e},{key:"PageDown",run:Lge,shift:z8e},{key:"Home",run:UVn,shift:eqn,preventDefault:!0},{key:"Mod-Home",run:B8e,shift:V8e},{key:"End",run:BVn,shift:JVn,preventDefault:!0},{key:"Mod-End",run:U8e,shift:q8e},{key:"Enter",run:H8e,shift:H8e},{key:"Mod-a",run:aqn},{key:"Backspace",run:Fge,shift:Fge,preventDefault:!0},{key:"Delete",run:GSt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:YSt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:dqn,preventDefault:!0},{mac:"Mod-Backspace",run:pqn,preventDefault:!0},{mac:"Mod-Delete",run:hqn,preventDefault:!0}].concat(Cqn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),Tqn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:FVn,shift:KVn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:zVn,shift:XVn},{key:"Alt-ArrowUp",run:vqn},{key:"Shift-Alt-ArrowUp",run:bqn},{key:"Alt-ArrowDown",run:yqn},{key:"Shift-Alt-ArrowDown",run:xqn},{key:"Mod-Alt-ArrowUp",run:lqn},{key:"Mod-Alt-ArrowDown",run:cqn},{key:"Escape",run:uqn},{key:"Mod-Enter",run:kqn},{key:"Alt-l",mac:"Ctrl-l",run:iqn},{key:"Mod-i",run:oqn,preventDefault:!0},{key:"Mod-[",run:tkt},{key:"Mod-]",run:ekt},{key:"Mod-Alt-\\",run:Oqn},{key:"Shift-Mod-k",run:wqn},{key:"Shift-Mod-\\",run:GVn},{key:"Mod-/",run:vVn},{key:"Alt-A",run:bVn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:_qn}].concat(Eqn),jqn={key:"Tab",run:ekt,shift:tkt},W8e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class $x{constructor(t,n,r=0,s=t.length,a,i){this.test=i,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(W8e(l)):W8e,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return uf(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=BSe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Pv(t);let s=this.normalize(n);if(s.length)for(let a=0,i=r,l=!0;;a++){let c=s.charCodeAt(a),u=this.match(c,i,l,this.bufferPos+this.bufferStart,a==s.length-1);if(u)return this.value=u,this;if(a==s.length-1)break;l&&a<n.length&&n.charCodeAt(a)==c?i++:l=!1}}}match(t,n,r,s,a){let i=null;for(let l=0;l<this.matches.length;){let c=this.matches[l],u=!1;this.query.charCodeAt(c.index)==t&&(c.index==this.query.length-1?i={from:c.from,to:s,precise:a&&c.precise}:(c.index++,u=!0)),u?l++:this.matches.splice(l,1)}return this.query.charCodeAt(0)==t&&(this.query.length==1?i={from:n,to:s,precise:r&&a}:this.matches.push({from:n,index:1,precise:r})),i&&this.test&&!this.test(i.from,i.to,this.buffer,this.bufferStart)&&(i=null),i}}typeof Symbol<"u"&&($x.prototype[Symbol.iterator]=function(){return this});const nkt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},zke="gm"+(/x/.unicode==null?"":"u");class rkt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=nkt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new skt(t,n,r,s,a);this.re=new RegExp(n,zke+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=jB(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=jB(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const Mee=new WeakMap;class ZT{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Mee.get(t);if(!s||s.from>=r||s.to<=n){let l=new ZT(n,t.sliceString(n,r));return Mee.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:i}=s;return i>n&&(a=t.sliceString(n,i)+a,i=n),s.to<r&&(a+=t.sliceString(s.to,r)),Mee.set(t,new ZT(i,a)),new ZT(n,a.slice(n-i,r-i))}}class skt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=nkt,this.matchPos=jB(t,s),this.re=new RegExp(n,zke+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=ZT.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this.matchPos=jB(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=ZT.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(rkt.prototype[Symbol.iterator]=skt.prototype[Symbol.iterator]=function(){return this});function Nqn(e){try{return new RegExp(e,zke),!0}catch{return!1}}function jB(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const Iqn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=f8n(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let i=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=i,p=d?+d.slice(1):0,h=u?+u:l.number;if(u&&f){let y=h/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*y)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),v=bt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,It.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},Aqn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Rqn=jn.define({combine(e){return zy(e,Aqn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function Pqn(e){return[Fqn,Lqn]}const $qn=An.mark({class:"cm-selectionMatch"}),Mqn=An.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function Z8e(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=So.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=So.Word)}function Dqn(e,t,n,r){return e(t.sliceDoc(n,n+1))==So.Word&&e(t.sliceDoc(r-1,r))==So.Word}const Lqn=Co.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(Rqn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return An.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return An.none;let c=n.wordAt(s.head);if(!c)return An.none;i=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return An.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(Z8e(i,n,s.from,s.to)&&Dqn(i,n,s.from,s.to)))return An.none}else if(a=n.sliceDoc(s.from,s.to),!a)return An.none}let l=[];for(let c of e.visibleRanges){let u=new $x(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||Z8e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(Mqn.range(d,f)):(d>=s.to||f<=s.from)&&l.push($qn.range(d,f)),l.length>t.maxMatches))return An.none}}return An.set(l)}},{decorations:e=>e.decorations}),Fqn=It.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),zqn=({state:e,dispatch:t})=>{let{selection:n}=e,r=bt.create(n.ranges.map(s=>e.wordAt(s.head)||bt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function Bqn(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let i=!1,l=new $x(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new $x(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const Uqn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return zqn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=Bqn(e,r);return s?(t(e.update({selection:e.selection.addRange(bt.range(s.from,s.to),!1),effects:It.scrollIntoView(s.to)})),!0):!1},hI=jn.define({combine(e){return zy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new nHn(t),scrollToMatch:t=>It.scrollIntoView(t)})}});class akt{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||Nqn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
|
|
234
|
-
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new Gqn(this):new Hqn(this)}getCursor(t,n=0,r){let s=t.doc?t:us.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?HE(this,s,n,r):qE(this,s,n,r)}}class ikt{constructor(t){this.spec=t}}function Vqn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function qE(e,t,n,r){let s;return e.wholeWord&&(s=qqn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=Vqn(e.test,t,s)),new $x(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function qqn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(NB(s,n-a))!=So.Word||t(IB(s,n-a))!=So.Word)&&(t(IB(s,r-a))!=So.Word||t(NB(s,r-a))!=So.Word))}class Hqn extends ikt{constructor(t){super(t)}nextMatch(t,n,r){let s=qE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=qE(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=qE(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=qE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=qE(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function Wqn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function HE(e,t,n,r){let s;return e.wholeWord&&(s=Zqn(t.charCategorizer(t.selection.main.head))),e.test&&(s=Wqn(e.test,t,s)),new rkt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function NB(e,t){return e.slice(Oc(e,t,!1),t)}function IB(e,t){return e.slice(t,Oc(e,t))}function Zqn(e){return(t,n,r)=>!r[0].length||(e(NB(r.input,r.index))!=So.Word||e(IB(r.input,r.index))!=So.Word)&&(e(IB(r.input,r.index+r[0].length))!=So.Word||e(NB(r.input,r.index+r[0].length))!=So.Word)}class Gqn extends ikt{nextMatch(t,n,r){let s=HE(this.spec,t,r,t.doc.length).next();return s.done&&(s=HE(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=HE(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=HE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=HE(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const yM=xr.define(),Bke=xr.define(),Yw=bl.define({create(e){return new Dee(zge(e).create(),null)},update(e,t){for(let n of t.effects)n.is(yM)?e=new Dee(n.value.create(),e.panel):n.is(Bke)&&(e=new Dee(e.query,n.value?Uke:null));return e},provide:e=>lM.from(e,t=>t.panel)});class Dee{constructor(t,n){this.query=t,this.panel=n}}const Qqn=An.mark({class:"cm-searchMatch"}),Yqn=An.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Kqn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Yw))}update(e){let t=e.state.field(Yw);(t!=e.startState.field(Yw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return An.none;let{view:n}=this,r=new Md;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(p=>p.from==u&&p.to==d);r.add(u,d,f?Yqn:Qqn)})}return r.finish()}},{decorations:e=>e.decorations});function R3(e){return t=>{let n=t.state.field(Yw,!1);return n&&n.query.spec.valid?e(t,n):ckt(t)}}const AB=R3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=bt.single(r.from,r.to),a=e.state.facet(hI);return e.dispatch({selection:s,effects:[Vke(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),lkt(e),!0}),RB=R3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=bt.single(s.from,s.to),i=e.state.facet(hI);return e.dispatch({selection:a,effects:[Vke(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),lkt(e),!0}),Xqn=R3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:bt.create(n.map(r=>bt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),Jqn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new $x(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(bt.range(l.value.from,l.value.to))}return t(e.update({selection:bt.create(a,i),userEvent:"select.search.matches"})),!0},G8e=R3((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(It.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=bt.single(i.from,i.to).map(f),d.push(Vke(e,i)),d.push(n.facet(hI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),eHn=R3((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:It.announce.of(r),userEvent:"input.replace.all"}),!0});function Uke(e){return e.state.facet(hI).createPanel(e)}function zge(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(hI);return new akt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function okt(e){let t=ske(e,Uke);return t&&t.dom.querySelector("[main-field]")}function lkt(e){let t=okt(e);t&&t==e.root.activeElement&&t.select()}const ckt=e=>{let t=e.state.field(Yw,!1);if(t&&t.panel){let n=okt(e);if(n&&n!=e.root.activeElement){let r=zge(e.state,t.query.spec);r.valid&&e.dispatch({effects:yM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Bke.of(!0),t?yM.of(zge(e.state,t.query.spec)):xr.appendConfig.of(sHn)]});return!0},ukt=e=>{let t=e.state.field(Yw,!1);if(!t||!t.panel)return!1;let n=ske(e,Uke);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Bke.of(!1)}),!0},tHn=[{key:"Mod-f",run:ckt,scope:"editor search-panel"},{key:"F3",run:AB,shift:RB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:AB,shift:RB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:ukt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Jqn},{key:"Mod-Alt-g",run:Iqn},{key:"Mod-d",run:Uqn,preventDefault:!0}];class nHn{constructor(t){this.view=t;let n=this.query=t.state.field(Yw).query.spec;this.commit=this.commit.bind(this),this.searchField=hi("input",{value:n.search,placeholder:up(t,"Find"),"aria-label":up(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=hi("input",{value:n.replace,placeholder:up(t,"Replace"),"aria-label":up(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=hi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=hi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=hi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return hi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=hi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>AB(t),[up(t,"next")]),r("prev",()=>RB(t),[up(t,"previous")]),r("select",()=>Xqn(t),[up(t,"all")]),hi("label",null,[this.caseField,up(t,"match case")]),hi("label",null,[this.reField,up(t,"regexp")]),hi("label",null,[this.wordField,up(t,"by word")]),...t.state.readOnly?[]:[hi("br"),this.replaceField,r("replace",()=>G8e(t),[up(t,"replace")]),r("replaceAll",()=>eHn(t),[up(t,"replace all")])],hi("button",{name:"close",onclick:()=>ukt(t),"aria-label":up(t,"close"),type:"button"},["×"])])}commit(){let t=new akt({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:yM.of(t)}))}keydown(t){Szn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?RB:AB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),G8e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(yM)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(hI).top}}function up(e,t){return e.state.phrase(t)}const G6=30,Q6=/[\s\.,:;?!]/;function Vke(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-G6),i=Math.min(s,n+G6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<G6;c++)if(!Q6.test(l[c+1])&&Q6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-G6;c--)if(!Q6.test(l[c-1])&&Q6.test(l[c])){l=l.slice(0,c);break}}return It.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const rHn=It.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),sHn=[Yw,th.low(Kqn),rHn];class Q8e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Ek{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(bM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Md,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=vHn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,An.widget({widget:new pHn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,An.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new Ek(u,n,Uj(u))}}function Uj(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new Q8e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new Q8e(r.from,a,r.diagnostic)}}),r}function aHn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(bM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(dkt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function iHn(e,t){return e.field(Ip,!1)?t:t.concat(xr.appendConfig.of(yHn))}const dkt=xr.define(),qke=xr.define(),fkt=xr.define(),Ip=bl.define({create(){return new Ek(An.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=Uj(n,e.selected.diagnostic,a)||Uj(n,null,a)}!n.size&&s&&t.state.facet(bM).autoPanel&&(s=null),e=new Ek(n,s,r)}for(let n of t.effects)if(n.is(dkt)){let r=t.state.facet(bM).autoPanel?n.value.length?xM.open:null:e.panel;e=Ek.init(n.value,r,t.state)}else n.is(qke)?e=new Ek(e.diagnostics,n.value?xM.open:null,e.selected):n.is(fkt)&&(e=new Ek(e.diagnostics,e.panel,n.value));return e},provide:e=>[lM.from(e,t=>t.panel),It.decorations.from(e,t=>t.diagnostics)]}),oHn=An.mark({class:"cm-lintRange cm-lintRange-active"});function lHn(e,t,n){let{diagnostics:r}=e.state.field(Ip),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(bM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:cHn(e,s)}}}:null}function cHn(e,t){return hi("ul",{class:"cm-tooltip-lint"},t.map(n=>hkt(e,n,!1)))}const uHn=e=>{let t=e.state.field(Ip,!1);(!t||!t.panel)&&e.dispatch({effects:iHn(e.state,[qke.of(!0)])});let n=ske(e,xM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},Y8e=e=>{let t=e.state.field(Ip,!1);return!t||!t.panel?!1:(e.dispatch({effects:qke.of(!1)}),!0)},dHn=e=>{let t=e.state.field(Ip,!1);if(!t)return!1;let n=e.state.selection.main,r=t.diagnostics.iter(n.to+1);return!r.value&&(r=t.diagnostics.iter(0),!r.value||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},fHn=[{key:"Mod-Shift-m",run:uHn,preventDefault:!0},{key:"F8",run:dHn}],bM=jn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...zy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:K8e,tooltipFilter:K8e,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function K8e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function pkt(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function hkt(e,t,n){var r;let s=n?pkt(t.actions):[];return hi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},hi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=Uj(e.state.field(Ip).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),hi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return hi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&hi("div",{class:"cm-diagnosticSource"},t.source))}class pHn extends nh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return hi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class X8e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=hkt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class xM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)Y8e(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=pkt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=Uj(this.view.state.field(Ip).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=hi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=hi("div",{class:"cm-panel-lint"},this.list,hi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>Y8e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ip).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Ip),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new X8e(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new X8e(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Ip),r=Uj(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:fkt.of(r)})}static open(t){return new xM(t)}}function hHn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function Y6(e){return hHn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const mHn=It.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Y6("#d11")},".cm-lintRange-warning":{backgroundImage:Y6("orange")},".cm-lintRange-info":{backgroundImage:Y6("#999")},".cm-lintRange-hint":{backgroundImage:Y6("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function gHn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function vHn(e){let t="hint",n=1;for(let r of e){let s=gHn(r.severity);s>n&&(n=s,t=r.severity)}return t}const yHn=[Ip,It.decorations.compute([Ip],e=>{let{selected:t,panel:n}=e.field(Ip);return!t||!n||t.from==t.to?An.none:An.set([oHn.range(t.from,t.to)])}),u8n(lHn,{hideOn:aHn}),mHn];var J8e=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(o7n)),t.defaultKeymap!==!1&&(a=a.concat(Tqn)),t.searchKeymap!==!1&&(a=a.concat(tHn)),t.historyKeymap!==!1&&(a=a.concat($Vn)),t.foldKeymap!==!1&&(a=a.concat(W8n)),t.completionKeymap!==!1&&(a=a.concat(l1t)),t.lintKeymap!==!1&&(a=a.concat(fHn));var i=[];return t.lineNumbers!==!1&&i.push(S8n()),t.highlightActiveLineGutter!==!1&&i.push(_8n()),t.highlightSpecialChars!==!1&&i.push(Lzn()),t.history!==!1&&i.push(CVn()),t.foldGutter!==!1&&i.push(Y8n()),t.drawSelection!==!1&&i.push(Tzn()),t.dropCursor!==!1&&i.push(Rzn()),t.allowMultipleSelections!==!1&&i.push(us.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(L8n()),t.syntaxHighlighting!==!1&&i.push(eS(e9n,{fallback:!0})),t.bracketMatching!==!1&&i.push(o9n()),t.closeBrackets!==!1&&i.push(r7n()),t.autocompletion!==!1&&i.push(o1t()),t.rectangularSelection!==!1&&i.push(Xzn()),s!==!1&&i.push(t8n()),t.highlightActiveLine!==!1&&i.push(qzn()),t.highlightSelectionMatches!==!1&&i.push(Pqn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(uI.of(" ".repeat(t.tabSize))),i.concat([cI.of(a.flat())]).filter(Boolean)};const bHn="#e5c07b",e9e="#e06c75",xHn="#56b6c2",wHn="#ffffff",T8="#abb2bf",Bge="#7d8799",SHn="#61afef",kHn="#98c379",t9e="#d19a66",OHn="#c678dd",_Hn="#21252b",n9e="#2c313a",r9e="#282c34",Lee="#353a42",CHn="#3E4451",s9e="#528bff",EHn=It.theme({"&":{color:T8,backgroundColor:r9e},".cm-content":{caretColor:s9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:s9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:CHn},".cm-panels":{backgroundColor:_Hn,color:T8},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:r9e,color:Bge,border:"none"},".cm-activeLineGutter":{backgroundColor:n9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Lee},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Lee,borderBottomColor:Lee},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:n9e,color:T8}}},{dark:!0}),THn=Hg.define([{tag:he.keyword,color:OHn},{tag:[he.name,he.deleted,he.character,he.propertyName,he.macroName],color:e9e},{tag:[he.function(he.variableName),he.labelName],color:SHn},{tag:[he.color,he.constant(he.name),he.standard(he.name)],color:t9e},{tag:[he.definition(he.name),he.separator],color:T8},{tag:[he.typeName,he.className,he.number,he.changed,he.annotation,he.modifier,he.self,he.namespace],color:bHn},{tag:[he.operator,he.operatorKeyword,he.url,he.escape,he.regexp,he.link,he.special(he.string)],color:xHn},{tag:[he.meta,he.comment],color:Bge},{tag:he.strong,fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:he.link,color:Bge,textDecoration:"underline"},{tag:he.heading,fontWeight:"bold",color:e9e},{tag:[he.atom,he.bool,he.special(he.variableName)],color:t9e},{tag:[he.processingInstruction,he.string,he.inserted],color:kHn},{tag:he.invalid,color:wHn}]),jHn=[EHn,eS(THn)];var NHn=It.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),IHn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(cI.of([jqn])),m&&(typeof m=="boolean"?v.unshift(J8e()):v.unshift(J8e(m))),p&&v.unshift(Gzn(p)),d){case"light":v.push(NHn);break;case"dark":v.push(jHn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(It.editable.of(!1)),c&&v.push(us.readOnly.of(!0)),[...v]},AHn=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(t=>!t.empty)});class RHn{constructor(t,n){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=n,this.timeoutMS=n,this.callbacks.push(t)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var t=this.callbacks.slice();this.callbacks.length=0,t.forEach(n=>{try{n()}catch(r){console.error("TimeoutLatch callback error:",r)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class a9e{constructor(){this.interval=null,this.latches=new Set}add(t){this.latches.add(t),this.start()}remove(t){this.latches.delete(t),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(t=>{t.tick(),t.isDone&&this.remove(t)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var Fee=null,PHn=()=>typeof window>"u"?new a9e:(Fee||(Fee=new a9e),Fee),$Hn=It.theme({"& .cm-scroller":{height:"100% !important"}}),i9e=null,zee=null;function MHn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===i9e||(i9e=i,zee=It.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),zee}var o9e=Fy.define(),DHn=200,LHn=[];function FHn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?LHn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,E=C===void 0?null:C,T=e.placeholder,N=T===void 0?"":T,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,F=D===void 0?!0:D,H=e.basicSetup,B=H===void 0?!0:H,U=e.root,V=e.initialState,M=g.useState(),G=M[0],q=M[1],$=g.useState(),z=$[0],Z=$[1],K=g.useState(),ne=K[0],ee=K[1],J=g.useState(()=>({current:null}))[0],ae=g.useState(()=>({current:null}))[0],pe=MHn(h,v,b,S,_,E),Y=It.updateListener.of(fe=>{if(fe.docChanged&&typeof r=="function"&&!fe.transactions.some(be=>be.annotation(o9e))){J.current?J.current.reset():(J.current=new RHn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},DHn),PHn().add(J.current));var ce=fe.state.doc,me=ce.toString();r(me,fe)}s&&s(AHn(fe))}),te=IHn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:F,basicSetup:B}),ue=[Y,...pe?[pe]:[],$Hn,...te];return i&&typeof i=="function"&&ue.push(It.updateListener.of(i)),ue=ue.concat(c),g.useLayoutEffect(()=>{if(G&&!ne){var fe={doc:t,selection:n,extensions:ue},ce=V?us.fromJSON(V.json,fe,V.fields):us.create(fe);if(ee(ce),!z){var me=new It({state:ce,parent:G,root:U});Z(me),a&&a(me,ce)}}return()=>{z&&(ee(void 0),Z(void 0))}},[G,ne]),g.useEffect(()=>{e.container&&q(e.container)},[e.container]),g.useEffect(()=>()=>{z&&(z.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[z]),g.useEffect(()=>{u&&z&&z.focus()},[u,z]),g.useEffect(()=>{z&&z.dispatch({effects:xr.reconfigure.of(ue)})},[f,c,h,v,b,S,_,E,N,A,L,F,B,r,i]),g.useEffect(()=>{if(t!==void 0){var fe=z?z.state.doc.toString():"";if(z&&t!==fe){var ce=J.current&&!J.current.isDone,me=()=>{z&&t!==z.state.doc.toString()&&z.dispatch({changes:{from:0,to:z.state.doc.toString().length,insert:t||""},annotations:[o9e.of(!0)]})};ce?ae.current=me:me()}}},[t,z]),{state:ne,setState:ee,view:z,setView:Z,container:G,setContainer:q}}var zHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Yu=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,E=e.indentWithTab,T=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=SSt(e,zHn),L=g.useRef(null),D=FHn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:E,editable:T,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),F=D.state,H=D.view,B=D.container,U=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:F,view:H}),[L,B,F,H]);var V=g.useCallback(G=>{L.current=G,U(G)},[U]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",WO({ref:V,className:""+M+(n?" "+n:"")},R))});Yu.displayName="CodeMirror";const BHn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let Bee=null;function UHn(){return Bee||(Bee=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Da(()=>import("./core-AeuPbg-Y.js"),__vite__mapDeps([0,1,2]),import.meta.url),Da(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Da(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Da(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Da(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Da(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Da(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Da(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Da(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Da(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Da(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Da(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Da(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Da(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Da(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Da(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Da(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Da(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Bee}async function VHn(e,t){const n=BHn[t?.toLowerCase()];if(!n)return null;const r=await UHn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function qHn(e){return new UO(cke.define(e))}const mkt=[ig.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Da(()=>Promise.resolve().then(()=>W6),void 0,import.meta.url).then(e=>e.javascript())}}),ig.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Da(()=>Promise.resolve().then(()=>b9n),void 0,import.meta.url).then(e=>e.json())}}),ig.of({name:"JSX",extensions:["jsx"],load(){return Da(()=>Promise.resolve().then(()=>W6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),ig.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Da(()=>Promise.resolve().then(()=>pVn),void 0,import.meta.url).then(e=>e.markdown())}}),ig.of({name:"TSX",extensions:["tsx"],load(){return Da(()=>Promise.resolve().then(()=>W6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),ig.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Da(()=>Promise.resolve().then(()=>W6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),ig.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Da(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>qHn(e.shell))}})];function HHn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function WHn(e){const t=HHn(e);return o1t({override:[ZHn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function ZHn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const GHn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,QHn=An.mark({class:"cm-variable-highlight"}),l9e=new wwt({regexp:GHn,decoration:()=>QHn}),YHn=Co.fromClass(class{decorations;constructor(e){this.decorations=l9e.createDeco(e)}update(e){this.decorations=l9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),KHn=YHn;function XHn(){const e=fI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[he.className,he.propertyName],color:"var(--neutral6)"},{tag:he.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[he.heading1,he.heading2,he.heading3,he.heading4,he.heading5,he.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:he.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:he.link,color:"var(--accent3)",textDecoration:"underline"},{tag:he.url,color:"var(--accent3)"},{tag:he.monospace,color:"var(--neutral6)"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:he.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=It.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function JHn(){const e=It.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Hg.define([{tag:[he.comment,he.bracket],color:"var(--neutral2)"},{tag:[he.string,he.meta,he.regexp],color:"var(--accent1)"},{tag:[he.atom,he.bool,he.special(he.variableName)],color:"var(--accent6)"},{tag:[he.keyword,he.operator,he.tagName],color:"var(--accent2)"},{tag:[he.function(he.propertyName),he.propertyName],color:"var(--accent5)"},{tag:[he.definition(he.variableName),he.function(he.variableName),he.className,he.attributeName],color:"var(--accent3)"},{tag:[he.variableName,he.number],color:"var(--accent5)"},{tag:[he.name,he.quote],color:"var(--accent1)"},{tag:he.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[he.heading1,he.heading2,he.heading3,he.heading4,he.heading5,he.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[he.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[he.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:he.link,color:"var(--accent3)",textDecoration:"underline"},{tag:he.url,color:"var(--accent3)"},{tag:he.monospace,color:"var(--neutral6)"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:[he.deleted],color:"var(--accent2)"},{tag:he.invalid,color:"var(--error)"},{tag:[he.standard(he.tagName)],color:"var(--accent1)"}]);return[e,eS(t)]}const a0=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?XHn():JHn(),[e])},eWn=co(X("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),tWn=th.highest(It.editorAttributes.of({style:"outline: none"})),nWn=th.highest(It.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),rWn=[tWn,nWn],Hr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=a0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const S=[...rWn];return f&&S.push(It.lineWrapping),a==="json"?S.push(Dp):a==="markdown"&&S.push(Mke({base:HO,codeLanguages:mkt})),i&&a==="markdown"&&S.push(KHn),c&&a==="markdown"&&S.push(WHn(c)),p===!1&&S.push(us.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:X(eWn({variant:h}),s),...m,children:[r&&o.jsx(za,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(Yu,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),sWn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},aWn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=a0(),{settings:r,setSettings:s}=gH(),a=r?.tracingOptions,i=g.useMemo(()=>sWn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(Yu,{value:l,onChange:d,theme:n,extensions:[Dp],className:X("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(le,{type:"button",onClick:f,children:"Save"})})]})},iWn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(qe,{children:o.jsx(oq,{})})})}),o.jsx(On,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Options"}),o.jsx(zs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Ir,{children:o.jsx(aWn,{onSaved:()=>t(!1)})})]})})]})};function oWn({status:e}){switch(e){case"running":return o.jsx(en,{});case"failed":return o.jsx(ws,{className:"text-accent2"});case"canceled":return o.jsx(Df,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(hj,{className:"text-neutral3"});case"suspended":return o.jsx(tq,{className:"text-accent3"});case"success":return o.jsx(da,{className:"text-accent1"});default:return o.jsx(hj,{className:"text-neutral3"})}}function gkt({status:e}){return o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(qe,{"aria-label":e,className:"shrink-0",children:o.jsx(oWn,{status:e})})}),o.jsx(On,{children:e})]})}var Uee,c9e;function Hke(){if(c9e)return Uee;c9e=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var p=f;p!==void 0;p=this.parent(p))if(p===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var p=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return Uee=r,Uee}var Vee,u9e;function lWn(){return u9e||(u9e=1,Vee="2.2.4"),Vee}var qee,d9e;function cWn(){return d9e||(d9e=1,qee={Graph:Hke(),version:lWn()}),qee}var Hee,f9e;function uWn(){if(f9e)return Hee;f9e=1;var e=Hke();Hee={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return Hee}var Wee,p9e;function dWn(){if(p9e)return Wee;p9e=1,Wee=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return Wee}var Zee,h9e;function vkt(){if(h9e)return Zee;h9e=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return Zee=e,Zee}var Gee,m9e;function ykt(){if(m9e)return Gee;m9e=1;var e=vkt();Gee=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return Gee}var Qee,g9e;function fWn(){if(g9e)return Qee;g9e=1;var e=ykt();Qee=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Qee}var Yee,v9e;function bkt(){if(v9e)return Yee;v9e=1,Yee=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return Yee}var Kee,y9e;function pWn(){if(y9e)return Kee;y9e=1;var e=bkt();Kee=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Kee}var Xee,b9e;function hWn(){if(b9e)return Xee;b9e=1,Xee=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return Xee}var Jee,x9e;function xkt(){if(x9e)return Jee;x9e=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return Jee=e,e.CycleException=t,Jee}var ete,w9e;function mWn(){if(w9e)return ete;w9e=1;var e=xkt();ete=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return ete}var tte,S9e;function wkt(){if(S9e)return tte;S9e=1,tte=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return tte}var nte,k9e;function gWn(){if(k9e)return nte;k9e=1;var e=wkt();nte=t;function t(n,r){return e(n,r,"post")}return nte}var rte,O9e;function vWn(){if(O9e)return rte;O9e=1;var e=wkt();rte=t;function t(n,r){return e(n,r,"pre")}return rte}var ste,_9e;function yWn(){if(_9e)return ste;_9e=1;var e=Hke(),t=vkt();ste=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return ste}var ate,C9e;function bWn(){return C9e||(C9e=1,ate={components:dWn(),dijkstra:ykt(),dijkstraAll:fWn(),findCycles:pWn(),floydWarshall:hWn(),isAcyclic:mWn(),postorder:gWn(),preorder:vWn(),prim:yWn(),tarjan:bkt(),topsort:xkt()}),ate}var ite,E9e;function Fg(){if(E9e)return ite;E9e=1;var e=cWn();return ite={Graph:e.Graph,json:uWn(),alg:bWn(),version:e.version},ite}var ote,T9e;function xWn(){if(T9e)return ote;T9e=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return ote=e,ote}var lte,j9e;function wWn(){if(j9e)return lte;j9e=1;let e=Fg().Graph,t=xWn();lte=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return lte}var cte,N9e;function Ml(){if(N9e)return cte;N9e=1;let e=Fg().Graph;cte={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:E};function t(T,N,I,A){for(var R=A;T.hasNode(R);)R=S(A);return I.dummy=N,T.setNode(R,I),R}function n(T){let N=new e().setGraph(T.graph());return T.nodes().forEach(I=>N.setNode(I,T.node(I))),T.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=T.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(T){let N=new e({multigraph:T.isMultigraph()}).setGraph(T.graph());return T.nodes().forEach(I=>{T.children(I).length||N.setNode(I,T.node(I))}),T.edges().forEach(I=>{N.setEdge(I,T.edge(I))}),N}function s(T){let N=T.nodes().map(I=>{let A={};return T.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function a(T){let N=T.nodes().map(I=>{let A={};return T.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function i(T,N){let I=T.x,A=T.y,R=N.x-I,L=N.y-A,D=T.width/2,F=T.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,B;return Math.abs(L)*D>Math.abs(R)*F?(L<0&&(F=-F),H=F*R/L,B=F):(R<0&&(D=-D),H=D,B=D*L/R),{x:I+H,y:A+B}}function l(T){let N=k(m(T)+1).map(()=>[]);return T.nodes().forEach(I=>{let A=T.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(T){let N=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);T.nodes().forEach(A=>{let R=T.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(T){let N=T.nodes().map(D=>T.node(D).rank),I=h(Math.min,N),A=[];T.nodes().forEach(D=>{let F=T.node(D).rank-I;A[F]||(A[F]=[]),A[F].push(D)});let R=0,L=T.graph().nodeRankFactor;Array.from(A).forEach((D,F)=>{D===void 0&&F%L!==0?--R:D!==void 0&&R&&D.forEach(H=>T.node(H).rank+=R)})}function d(T,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(T,"border",R,N)}function f(T,N=p){const I=[];for(let A=0;A<T.length;A+=N){const R=T.slice(A,A+N);I.push(R)}return I}const p=65535;function h(T,N){if(N.length>p){const I=f(N);return T.apply(null,I.map(A=>T.apply(null,A)))}else return T.apply(null,N)}function m(T){const I=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(T,N){let I={lhs:[],rhs:[]};return T.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(T,N){let I=Date.now();try{return N()}finally{console.log(T+" time: "+(Date.now()-I)+"ms")}}function b(T,N){return N()}let x=0;function S(T){var N=++x;return T+(""+N)}function k(T,N,I=1){N==null&&(N=T,T=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=T;A(L);L+=I)R.push(L);return R}function _(T,N){const I={};for(const A of N)T[A]!==void 0&&(I[A]=T[A]);return I}function C(T,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(T).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(T,N){return T.reduce((I,A,R)=>(I[A]=N[R],I),{})}return cte}var ute,I9e;function SWn(){if(I9e)return ute;I9e=1;let e=wWn(),t=Ml().uniqueId;ute={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return ute}var dte,A9e;function kWn(){if(A9e)return dte;A9e=1;let e=Ml();dte={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return dte}var fte,R9e;function PB(){if(R9e)return fte;R9e=1;const{applyWithChunking:e}=Ml();fte={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return fte}var pte,P9e;function Skt(){if(P9e)return pte;P9e=1;var e=Fg().Graph,t=PB().slack;pte=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return pte}var hte,$9e;function OWn(){if($9e)return hte;$9e=1;var e=Skt(),t=PB().slack,n=PB().longestPath,r=Fg().alg.preorder,s=Fg().alg.postorder,a=Ml().simplify;hte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,_;k=p(S);)_=h(S,x,k),m(S,x,k,_)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(x,S,_))}function c(x,S,k){var _=x.node(k),C=_.parent;x.edge(k,C).cutvalue=u(x,S,k)}function u(x,S,k){var _=x.node(k),C=_.parent,E=!0,T=S.edge(k,C),N=0;return T||(E=!1,T=S.edge(C,k)),N=T.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===E,D=S.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var F=x.edge(k,R).cutvalue;N+=L?-F:F}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,_,C){var E=k,T=x.node(_);return S[_]=!0,x.neighbors(_).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,_))}),T.low=E,T.lim=k++,C?T.parent=C:delete T.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var _=k.v,C=k.w;S.hasEdge(_,C)||(_=k.w,C=k.v);var E=x.node(_),T=x.node(C),N=E,I=!1;E.lim>T.lim&&(N=T,I=!0);var A=S.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(S,L)<t(S,R)?L:R)}function m(x,S,k,_){var C=k.v,E=k.w;x.removeEdge(C,E),x.setEdge(_.v,_.w,{}),d(x),l(x,S),v(x,S)}function v(x,S){var k=x.nodes().find(C=>!S.node(C).parent),_=r(x,k);_=_.slice(1),_.forEach(C=>{var E=x.node(C).parent,T=S.edge(C,E),N=!1;T||(T=S.edge(E,C),N=!0),S.node(C).rank=S.node(E).rank+(N?T.minlen:-T.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return hte}var mte,M9e;function _Wn(){if(M9e)return mte;M9e=1;var e=PB(),t=e.longestPath,n=Skt(),r=OWn();mte=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return mte}var gte,D9e;function CWn(){if(D9e)return gte;D9e=1,gte=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return gte}var vte,L9e;function EWn(){if(L9e)return vte;L9e=1;let e=Ml();vte={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,_=x.borderTop?u:2*u,C=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,v,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return vte}var yte,F9e;function TWn(){if(F9e)return yte;F9e=1;let e=Ml();yte=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return yte}var bte,z9e;function jWn(){if(z9e)return bte;z9e=1,bte={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return bte}var xte,B9e;function NWn(){if(B9e)return xte;B9e=1;let e=Ml();xte=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return xte}var wte,U9e;function IWn(){if(U9e)return wte;U9e=1;let e=Ml().zipObject;wte=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return wte}var Ste,V9e;function AWn(){if(V9e)return Ste;V9e=1,Ste=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return Ste}var kte,q9e;function RWn(){if(q9e)return kte;q9e=1;let e=Ml();kte=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return kte}var Ote,H9e;function PWn(){if(H9e)return Ote;H9e=1;let e=Ml();Ote=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return Ote}var _te,W9e;function $Wn(){if(W9e)return _te;W9e=1;let e=AWn(),t=RWn(),n=PWn();_te=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(x=>x!==p&&x!==h));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return _te}var Cte,Z9e;function MWn(){if(Z9e)return Cte;Z9e=1;let e=Fg().Graph,t=Ml();Cte=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return Cte}var Ete,G9e;function DWn(){if(G9e)return Ete;G9e=1,Ete=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return Ete}var Tte,Q9e;function LWn(){if(Q9e)return Tte;Q9e=1;let e=NWn(),t=IWn(),n=$Wn(),r=MWn(),s=DWn(),a=Fg().Graph,i=Ml();Tte=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:v,S%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,x=Object.assign({},y),b=_)}d(f,x)}function c(f,p,h){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return Tte}var jte,Y9e;function FWn(){if(Y9e)return jte;Y9e=1;let e=Fg().Graph,t=Ml();jte={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let x={};function S(k,_){let C=0,E=0,T=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:T;(R||I===N)&&(_.slice(E,A+1).forEach(D=>{y.predecessors(D).forEach(F=>{let H=y.node(F),B=H.order;(B<C||L<B)&&!(H.dummy&&y.node(D).dummy)&&a(x,F,D)})}),E=A+1,C=L)}),_}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(_,C,E,T,N){let I;t.range(C,E).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<T||L.order>N)&&a(x,R,I)})})}function k(_,C){let E=-1,T,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(T=y.node(R[0]).order,S(C,N,A,E,T),N=A,E=T)}S(C,N,C.length,T,_.length)}),C}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},_={},C={};return b.forEach(E=>{E.forEach((T,N)=>{k[T]=T,_[T]=T,C[T]=N})}),b.forEach(E=>{let T=-1;E.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>C[R]-C[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];_[N]===N&&T<C[D]&&!i(x,N,D)&&(_[D]=N,_[N]=k[N]=k[D],T=C[D])}}})}),{root:k,align:_}}function c(y,b,x,S,k){let _={},C=u(y,b,x,k),E=k?"borderLeft":"borderRight";function T(A,R){let L=C.nodes(),D=L.pop(),F={};for(;D;)F[D]?A(D):(F[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){_[A]=C.inEdges(A).reduce((R,L)=>Math.max(R,_[L.v]+C.edge(L)),0)}function I(A){let R=C.outEdges(A).reduce((D,F)=>Math.min(D,_[F.w]-C.edge(F)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(_[A]=Math.max(_[A],R))}return T(N,C.predecessors.bind(C)),T(I,C.successors.bind(C)),Object.keys(S).forEach(A=>_[A]=_[x[A]]),_}function u(y,b,x,S){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,S);return b.forEach(E=>{let T;E.forEach(N=>{let I=x[N];if(k.setNode(I),T){var A=x[T],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,T),R||0))}T=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([E,T])=>{let N=v(y,E)/2;k=Math.max(T+N,k),_=Math.min(T-N,_)});const C=k-_;return C<x[0]&&(x=[C,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let E=_+C,T=y[E];if(T===b)return;let N=Object.values(T),I=S-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(T,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(_=>_[S]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let T=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,T),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),S[C+E]=I})});let _=d(y,S);return f(S,_),p(S,y.graph().align)}function m(y,b,x){return(S,k,_)=>{let C=S.node(k),E=S.node(_),T=0,N;if(T+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":N=-C.width/2;break;case"r":N=C.width/2;break}if(N&&(T+=x?N:-N),N=0,T+=(C.dummy?b:y)/2,T+=(E.dummy?b:y)/2,T+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(T+=x?N:-N),N=0,T}}function v(y,b){return y.node(b).width}return jte}var Nte,K9e;function zWn(){if(K9e)return Nte;K9e=1;let e=Ml(),t=FWn().positionX;Nte=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Nte}var Ite,X9e;function BWn(){if(X9e)return Ite;X9e=1;let e=SWn(),t=kWn(),n=_Wn(),r=Ml().normalizeRanks,s=CWn(),a=Ml().removeEmptyRanks,i=EWn(),l=TWn(),c=jWn(),u=LWn(),d=zWn(),f=Ml(),p=Fg().Graph;Ite=h;function h($,z){let Z=z&&z.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>T($));Z(" runLayout",()=>m(K,Z,z)),Z(" updateInputGraph",()=>v($,K))})}function m($,z,Z){z(" makeSpaceForEdgeLabels",()=>N($)),z(" removeSelfEdges",()=>U($)),z(" acyclic",()=>e.run($)),z(" nestingGraph.run",()=>i.run($)),z(" rank",()=>n(f.asNonCompoundGraph($))),z(" injectEdgeLabelProxies",()=>I($)),z(" removeEmptyRanks",()=>a($)),z(" nestingGraph.cleanup",()=>i.cleanup($)),z(" normalizeRanks",()=>r($)),z(" assignRankMinMax",()=>A($)),z(" removeEdgeLabelProxies",()=>R($)),z(" normalize.run",()=>t.run($)),z(" parentDummyChains",()=>s($)),z(" addBorderSegments",()=>l($)),z(" order",()=>u($,Z)),z(" insertSelfEdges",()=>V($)),z(" adjustCoordinateSystem",()=>c.adjust($)),z(" position",()=>d($)),z(" positionSelfEdges",()=>M($)),z(" removeBorderNodes",()=>B($)),z(" normalize.undo",()=>t.undo($)),z(" fixupEdgeLabelCoords",()=>F($)),z(" undoCoordinateSystem",()=>c.undo($)),z(" translateGraph",()=>L($)),z(" assignNodeIntersects",()=>D($)),z(" reversePoints",()=>H($)),z(" acyclic.undo",()=>e.undo($))}function v($,z){$.nodes().forEach(Z=>{let K=$.node(Z),ne=z.node(Z);K&&(K.x=ne.x,K.y=ne.y,K.rank=ne.rank,z.children(Z).length&&(K.width=ne.width,K.height=ne.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),ne=z.edge(Z);K.points=ne.points,Object.hasOwn(ne,"x")&&(K.x=ne.x,K.y=ne.y)}),$.graph().width=z.graph().width,$.graph().height=z.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],S=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function T($){let z=new p({multigraph:!0,compound:!0}),Z=q($.graph());return z.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(K=>{let ne=q($.node(K));const ee=G(ne,S);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),z.setNode(K,ee),z.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let ne=q($.edge(K));z.setEdge(K,Object.assign({},C,G(ne,_),f.pick(ne,E)))}),z}function N($){let z=$.graph();z.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(z.rankdir==="TB"||z.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(z=>{let Z=$.edge(z);if(Z.width&&Z.height){let K=$.node(z.v),ee={rank:($.node(z.w).rank-K.rank)/2+K.rank,e:z};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let z=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,z=Math.max(z,K.maxRank))}),$.graph().maxRank=z}function R($){$.nodes().forEach(z=>{let Z=$.node(z);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(z))})}function L($){let z=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,ne=0,ee=$.graph(),J=ee.marginx||0,ae=ee.marginy||0;function pe(Y){let te=Y.x,ue=Y.y,fe=Y.width,ce=Y.height;z=Math.min(z,te-fe/2),Z=Math.max(Z,te+fe/2),K=Math.min(K,ue-ce/2),ne=Math.max(ne,ue+ce/2)}$.nodes().forEach(Y=>pe($.node(Y))),$.edges().forEach(Y=>{let te=$.edge(Y);Object.hasOwn(te,"x")&&pe(te)}),z-=J,K-=ae,$.nodes().forEach(Y=>{let te=$.node(Y);te.x-=z,te.y-=K}),$.edges().forEach(Y=>{let te=$.edge(Y);te.points.forEach(ue=>{ue.x-=z,ue.y-=K}),Object.hasOwn(te,"x")&&(te.x-=z),Object.hasOwn(te,"y")&&(te.y-=K)}),ee.width=Z-z+J,ee.height=ne-K+ae}function D($){$.edges().forEach(z=>{let Z=$.edge(z),K=$.node(z.v),ne=$.node(z.w),ee,J;Z.points?(ee=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],ee=ne,J=K),Z.points.unshift(f.intersectRect(K,ee)),Z.points.push(f.intersectRect(ne,J))})}function F($){$.edges().forEach(z=>{let Z=$.edge(z);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(z=>{let Z=$.edge(z);Z.reversed&&Z.points.reverse()})}function B($){$.nodes().forEach(z=>{if($.children(z).length){let Z=$.node(z),K=$.node(Z.borderTop),ne=$.node(Z.borderBottom),ee=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-ee.x),Z.height=Math.abs(ne.y-K.y),Z.x=ee.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(z=>{$.node(z).dummy==="border"&&$.removeNode(z)})}function U($){$.edges().forEach(z=>{if(z.v===z.w){var Z=$.node(z.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:z,label:$.edge(z)}),$.removeEdge(z)}})}function V($){var z=f.buildLayerMatrix($);z.forEach(Z=>{var K=0;Z.forEach((ne,ee)=>{var J=$.node(ne);J.order=ee+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:ee+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function M($){$.nodes().forEach(z=>{var Z=$.node(z);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),ne=K.x+K.width/2,ee=K.y,J=Z.x-ne,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(z),Z.label.points=[{x:ne+2*J/3,y:ee-ae},{x:ne+5*J/6,y:ee-ae},{x:ne+J,y:ee},{x:ne+5*J/6,y:ee+ae},{x:ne+2*J/3,y:ee+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,z){return f.mapValues(f.pick($,z),Number)}function q($){var z={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),z[Z]=K}),z}return Ite}var Ate,J9e;function UWn(){if(J9e)return Ate;J9e=1;let e=Ml(),t=Fg().Graph;Ate={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return Ate}var Rte,e7e;function VWn(){return e7e||(e7e=1,Rte="1.1.8"),Rte}var Pte,t7e;function qWn(){return t7e||(t7e=1,Pte={graphlib:Fg(),layout:BWn(),debug:UWn(),util:{time:Ml().time,notime:Ml().notime},version:VWn()}),Pte}var HWn=qWn();const n7e=Bl(HWn);function Hl(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Hl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var WWn={value:()=>{}};function VH(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new j8(n)}function j8(e){this._=e}function ZWn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}j8.prototype=VH.prototype={constructor:j8,on:function(e,t){var n=this._,r=ZWn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=GWn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=r7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=r7e(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new j8(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function GWn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function r7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=WWn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Uge="http://www.w3.org/1999/xhtml";const s7e={svg:"http://www.w3.org/2000/svg",xhtml:Uge,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function qH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),s7e.hasOwnProperty(t)?{space:s7e[t],local:e}:e}function QWn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Uge&&t.documentElement.namespaceURI===Uge?t.createElement(e):t.createElementNS(n,e)}}function YWn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function kkt(e){var t=qH(e);return(t.local?YWn:QWn)(t)}function KWn(){}function Wke(e){return e==null?KWn:function(){return this.querySelector(e)}}function XWn(e){typeof e!="function"&&(e=Wke(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Yp(r,this._parents)}function JWn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function eZn(){return[]}function Okt(e){return e==null?eZn:function(){return this.querySelectorAll(e)}}function tZn(e){return function(){return JWn(e.apply(this,arguments))}}function nZn(e){typeof e=="function"?e=tZn(e):e=Okt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new Yp(r,s)}function _kt(e){return function(){return this.matches(e)}}function Ckt(e){return function(t){return t.matches(e)}}var rZn=Array.prototype.find;function sZn(e){return function(){return rZn.call(this.children,e)}}function aZn(){return this.firstElementChild}function iZn(e){return this.select(e==null?aZn:sZn(typeof e=="function"?e:Ckt(e)))}var oZn=Array.prototype.filter;function lZn(){return Array.from(this.children)}function cZn(e){return function(){return oZn.call(this.children,e)}}function uZn(e){return this.selectAll(e==null?lZn:cZn(typeof e=="function"?e:Ckt(e)))}function dZn(e){typeof e!="function"&&(e=_kt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Yp(r,this._parents)}function Ekt(e){return new Array(e.length)}function fZn(){return new Yp(this._enter||this._groups.map(Ekt),this._parents)}function $B(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}$B.prototype={constructor:$B,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function pZn(e){return function(){return e}}function hZn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new $B(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function mZn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new $B(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function gZn(e){return e.__data__}function vZn(e,t){if(!arguments.length)return Array.from(this,gZn);var n=t?mZn:hZn,r=this._parents,s=this._groups;typeof e!="function"&&(e=pZn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],p=f.length,h=yZn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var x=0,S=0,k,_;x<m;++x)if(k=v[x]){for(x>=S&&(S=x+1);!(_=y[S])&&++S<m;);k._next=_||null}}return i=new Yp(i,r),i._enter=l,i._exit=c,i}function yZn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function bZn(){return new Yp(this._exit||this._groups.map(Ekt),this._parents)}function xZn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function wZn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Yp(l,this._parents)}function SZn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function kZn(e){e||(e=OZn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Yp(s,this._parents).order()}function OZn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function _Zn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function CZn(){return Array.from(this)}function EZn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function TZn(){let e=0;for(const t of this)++e;return e}function jZn(){return!this.node()}function NZn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function IZn(e){return function(){this.removeAttribute(e)}}function AZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function RZn(e,t){return function(){this.setAttribute(e,t)}}function PZn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function $Zn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function MZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function DZn(e,t){var n=qH(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?AZn:IZn:typeof t=="function"?n.local?MZn:$Zn:n.local?PZn:RZn)(n,t))}function Tkt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function LZn(e){return function(){this.style.removeProperty(e)}}function FZn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function zZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function BZn(e,t,n){return arguments.length>1?this.each((t==null?LZn:typeof t=="function"?zZn:FZn)(e,t,n??"")):Vj(this.node(),e)}function Vj(e,t){return e.style.getPropertyValue(t)||Tkt(e).getComputedStyle(e,null).getPropertyValue(t)}function UZn(e){return function(){delete this[e]}}function VZn(e,t){return function(){this[e]=t}}function qZn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function HZn(e,t){return arguments.length>1?this.each((t==null?UZn:typeof t=="function"?qZn:VZn)(e,t)):this.node()[e]}function jkt(e){return e.trim().split(/^|\s+/)}function Zke(e){return e.classList||new Nkt(e)}function Nkt(e){this._node=e,this._names=jkt(e.getAttribute("class")||"")}Nkt.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function Ikt(e,t){for(var n=Zke(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function Akt(e,t){for(var n=Zke(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function WZn(e){return function(){Ikt(this,e)}}function ZZn(e){return function(){Akt(this,e)}}function GZn(e,t){return function(){(t.apply(this,arguments)?Ikt:Akt)(this,e)}}function QZn(e,t){var n=jkt(e+"");if(arguments.length<2){for(var r=Zke(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?GZn:t?WZn:ZZn)(n,t))}function YZn(){this.textContent=""}function KZn(e){return function(){this.textContent=e}}function XZn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function JZn(e){return arguments.length?this.each(e==null?YZn:(typeof e=="function"?XZn:KZn)(e)):this.node().textContent}function eGn(){this.innerHTML=""}function tGn(e){return function(){this.innerHTML=e}}function nGn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function rGn(e){return arguments.length?this.each(e==null?eGn:(typeof e=="function"?nGn:tGn)(e)):this.node().innerHTML}function sGn(){this.nextSibling&&this.parentNode.appendChild(this)}function aGn(){return this.each(sGn)}function iGn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function oGn(){return this.each(iGn)}function lGn(e){var t=typeof e=="function"?e:kkt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function cGn(){return null}function uGn(e,t){var n=typeof e=="function"?e:kkt(e),r=t==null?cGn:typeof t=="function"?t:Wke(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function dGn(){var e=this.parentNode;e&&e.removeChild(this)}function fGn(){return this.each(dGn)}function pGn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function hGn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function mGn(e){return this.select(e?hGn:pGn)}function gGn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function vGn(e){return function(t){e.call(this,t,this.__data__)}}function yGn(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function bGn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function xGn(e,t,n){return function(){var r=this.__on,s,a=vGn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function wGn(e,t,n){var r=yGn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?xGn:bGn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function Rkt(e,t,n){var r=Tkt(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function SGn(e,t){return function(){return Rkt(this,e,t)}}function kGn(e,t){return function(){return Rkt(this,e,t.apply(this,arguments))}}function OGn(e,t){return this.each((typeof t=="function"?kGn:SGn)(e,t))}function*_Gn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var Pkt=[null];function Yp(e,t){this._groups=e,this._parents=t}function P3(){return new Yp([[document.documentElement]],Pkt)}function CGn(){return this}Yp.prototype=P3.prototype={constructor:Yp,select:XWn,selectAll:nZn,selectChild:iZn,selectChildren:uZn,filter:dZn,data:vZn,enter:fZn,exit:bZn,join:xZn,merge:wZn,selection:CGn,order:SZn,sort:kZn,call:_Zn,nodes:CZn,node:EZn,size:TZn,empty:jZn,each:NZn,attr:DZn,style:BZn,property:HZn,classed:QZn,text:JZn,html:rGn,raise:aGn,lower:oGn,append:lGn,insert:uGn,remove:fGn,clone:mGn,datum:gGn,on:wGn,dispatch:OGn,[Symbol.iterator]:_Gn};function Ep(e){return typeof e=="string"?new Yp([[document.querySelector(e)]],[document.documentElement]):new Yp([[e]],Pkt)}function EGn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function og(e,t){if(e=EGn(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const TGn={passive:!1},wM={capture:!0,passive:!1};function $te(e){e.stopImmediatePropagation()}function GT(e){e.preventDefault(),e.stopImmediatePropagation()}function $kt(e){var t=e.document.documentElement,n=Ep(e).on("dragstart.drag",GT,wM);"onselectstart"in t?n.on("selectstart.drag",GT,wM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Mkt(e,t){var n=e.document.documentElement,r=Ep(e).on("dragstart.drag",null);t&&(r.on("click.drag",GT,wM),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const K6=e=>()=>e;function Vge(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Vge.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function jGn(e){return!e.ctrlKey&&!e.button}function NGn(){return this.parentNode}function IGn(e,t){return t??{x:e.x,y:e.y}}function AGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function Dkt(){var e=jGn,t=NGn,n=IGn,r=AGn,s={},a=VH("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,TGn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=S(this,t.call(this,k,_),k,_,"mouse");C&&(Ep(k.view).on("mousemove.drag",m,wM).on("mouseup.drag",v,wM),$kt(k.view),$te(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(GT(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Ep(k.view).on("mousemove.drag mouseup.drag",null),Mkt(k.view,u),GT(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,E=t.call(this,k,_),T=C.length,N,I;for(N=0;N<T;++N)(I=S(this,E,k,_,C[N].identifier,C[N]))&&($te(k),I("start",k,C[N]))}}function b(k){var _=k.changedTouches,C=_.length,E,T;for(E=0;E<C;++E)(T=s[_[E].identifier])&&(GT(k),T("drag",k,_[E]))}function x(k){var _=k.changedTouches,C=_.length,E,T;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<C;++E)(T=s[_[E].identifier])&&($te(k),T("end",k,_[E]))}function S(k,_,C,E,T,N){var I=a.copy(),A=og(N||C,_),R,L,D;if((D=n.call(k,new Vge("beforestart",{sourceEvent:C,target:p,identifier:T,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function F(H,B,U){var V=A,M;switch(H){case"start":s[T]=F,M=i++;break;case"end":delete s[T],--i;case"drag":A=og(U||B,_),M=i;break}I.call(H,k,new Vge(H,{sourceEvent:B,subject:D,target:p,identifier:T,active:M,x:A[0]+R,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),E)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:K6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:K6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:K6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:K6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function Gke(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Lkt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function $3(){}var SM=.7,MB=1/SM,QT="\\s*([+-]?\\d+)\\s*",kM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",sy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",RGn=/^#([0-9a-f]{3,8})$/,PGn=new RegExp(`^rgb\\(${QT},${QT},${QT}\\)$`),$Gn=new RegExp(`^rgb\\(${sy},${sy},${sy}\\)$`),MGn=new RegExp(`^rgba\\(${QT},${QT},${QT},${kM}\\)$`),DGn=new RegExp(`^rgba\\(${sy},${sy},${sy},${kM}\\)$`),LGn=new RegExp(`^hsl\\(${kM},${sy},${sy}\\)$`),FGn=new RegExp(`^hsla\\(${kM},${sy},${sy},${kM}\\)$`),a7e={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Gke($3,ZO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:i7e,formatHex:i7e,formatHex8:zGn,formatHsl:BGn,formatRgb:o7e,toString:o7e});function i7e(){return this.rgb().formatHex()}function zGn(){return this.rgb().formatHex8()}function BGn(){return Fkt(this).formatHsl()}function o7e(){return this.rgb().formatRgb()}function ZO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=RGn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?l7e(t):n===3?new xf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?X6(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?X6(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=PGn.exec(e))?new xf(t[1],t[2],t[3],1):(t=$Gn.exec(e))?new xf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=MGn.exec(e))?X6(t[1],t[2],t[3],t[4]):(t=DGn.exec(e))?X6(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=LGn.exec(e))?d7e(t[1],t[2]/100,t[3]/100,1):(t=FGn.exec(e))?d7e(t[1],t[2]/100,t[3]/100,t[4]):a7e.hasOwnProperty(e)?l7e(a7e[e]):e==="transparent"?new xf(NaN,NaN,NaN,0):null}function l7e(e){return new xf(e>>16&255,e>>8&255,e&255,1)}function X6(e,t,n,r){return r<=0&&(e=t=n=NaN),new xf(e,t,n,r)}function UGn(e){return e instanceof $3||(e=ZO(e)),e?(e=e.rgb(),new xf(e.r,e.g,e.b,e.opacity)):new xf}function qge(e,t,n,r){return arguments.length===1?UGn(e):new xf(e,t,n,r??1)}function xf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Gke(xf,qge,Lkt($3,{brighter(e){return e=e==null?MB:Math.pow(MB,e),new xf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?SM:Math.pow(SM,e),new xf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new xf(rO(this.r),rO(this.g),rO(this.b),DB(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:c7e,formatHex:c7e,formatHex8:VGn,formatRgb:u7e,toString:u7e}));function c7e(){return`#${Fk(this.r)}${Fk(this.g)}${Fk(this.b)}`}function VGn(){return`#${Fk(this.r)}${Fk(this.g)}${Fk(this.b)}${Fk((isNaN(this.opacity)?1:this.opacity)*255)}`}function u7e(){const e=DB(this.opacity);return`${e===1?"rgb(":"rgba("}${rO(this.r)}, ${rO(this.g)}, ${rO(this.b)}${e===1?")":`, ${e})`}`}function DB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function rO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Fk(e){return e=rO(e),(e<16?"0":"")+e.toString(16)}function d7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new hg(e,t,n,r)}function Fkt(e){if(e instanceof hg)return new hg(e.h,e.s,e.l,e.opacity);if(e instanceof $3||(e=ZO(e)),!e)return new hg;if(e instanceof hg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new hg(i,l,c,e.opacity)}function qGn(e,t,n,r){return arguments.length===1?Fkt(e):new hg(e,t,n,r??1)}function hg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Gke(hg,qGn,Lkt($3,{brighter(e){return e=e==null?MB:Math.pow(MB,e),new hg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?SM:Math.pow(SM,e),new hg(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new xf(Mte(e>=240?e-240:e+120,s,r),Mte(e,s,r),Mte(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new hg(f7e(this.h),J6(this.s),J6(this.l),DB(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=DB(this.opacity);return`${e===1?"hsl(":"hsla("}${f7e(this.h)}, ${J6(this.s)*100}%, ${J6(this.l)*100}%${e===1?")":`, ${e})`}`}}));function f7e(e){return e=(e||0)%360,e<0?e+360:e}function J6(e){return Math.max(0,Math.min(1,e||0))}function Mte(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const Qke=e=>()=>e;function HGn(e,t){return function(n){return e+n*t}}function WGn(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function ZGn(e){return(e=+e)==1?zkt:function(t,n){return n-t?WGn(t,n,e):Qke(isNaN(t)?n:t)}}function zkt(e,t){var n=t-e;return n?HGn(e,n):Qke(isNaN(e)?t:e)}const LB=(function e(t){var n=ZGn(t);function r(s,a){var i=n((s=qge(s)).r,(a=qge(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=zkt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function GGn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function QGn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function YGn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=px(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function KGn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function cg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function XGn(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=px(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Hge=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Dte=new RegExp(Hge.source,"g");function JGn(e){return function(){return e}}function eQn(e){return function(t){return e(t)+""}}function Bkt(e,t){var n=Hge.lastIndex=Dte.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Hge.exec(e))&&(s=Dte.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:cg(r,s)})),n=Dte.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?eQn(c[0].x):JGn(t):(t=c.length,function(u){for(var d=0,f;d<t;++d)l[(f=c[d]).i]=f.x(u);return l.join("")})}function px(e,t){var n=typeof t,r;return t==null||n==="boolean"?Qke(t):(n==="number"?cg:n==="string"?(r=ZO(t))?(t=r,LB):Bkt:t instanceof ZO?LB:t instanceof Date?KGn:QGn(t)?GGn:Array.isArray(t)?YGn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?XGn:cg)(e,t)}function Yke(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var p7e=180/Math.PI,Wge={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Ukt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*p7e,skewX:Math.atan(c)*p7e,scaleX:i,scaleY:l}}var eF;function tQn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Wge:Ukt(t.a,t.b,t.c,t.d,t.e,t.f)}function nQn(e){return e==null||(eF||(eF=document.createElementNS("http://www.w3.org/2000/svg","g")),eF.setAttribute("transform",e),!(e=eF.transform.baseVal.consolidate()))?Wge:(e=e.matrix,Ukt(e.a,e.b,e.c,e.d,e.e,e.f))}function Vkt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:cg(u,f)},{i:v-2,x:cg(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:cg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:cg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:cg(u,f)},{i:v-2,x:cg(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var rQn=Vkt(tQn,"px, ","px)","deg)"),sQn=Vkt(nQn,", ",")",")"),aQn=1e-12;function h7e(e){return((e=Math.exp(e))+1/e)/2}function iQn(e){return((e=Math.exp(e))-1/e)/2}function oQn(e){return((e=Math.exp(2*e))-1)/(e+1)}const N8=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<aQn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var x=Math.sqrt(v),S=(p*p-u*u+r*v)/(2*u*n*x),k=(p*p-u*u-r*v)/(2*p*n*x),_=Math.log(Math.sqrt(S*S+1)-S),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(E){var T=E*b,N=h7e(_),I=u/(n*x)*(N*oQn(t*T+_)-iQn(_));return[l+I*h,c+I*m,u*N/h7e(t*T+_)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function lQn(e,t){t===void 0&&(t=e,e=px);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var qj=0,zP=0,kR=0,qkt=1e3,FB,BP,zB=0,GO=0,HH=0,OM=typeof performance=="object"&&performance.now?performance:Date,Hkt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Kke(){return GO||(Hkt(cQn),GO=OM.now()+HH)}function cQn(){GO=0}function BB(){this._call=this._time=this._next=null}BB.prototype=Wkt.prototype={constructor:BB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Kke():+n)+(t==null?0:+t),!this._next&&BP!==this&&(BP?BP._next=this:FB=this,BP=this),this._call=e,this._time=n,Zge()},stop:function(){this._call&&(this._call=null,this._time=1/0,Zge())}};function Wkt(e,t,n){var r=new BB;return r.restart(e,t,n),r}function uQn(){Kke(),++qj;for(var e=FB,t;e;)(t=GO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--qj}function m7e(){GO=(zB=OM.now())+HH,qj=zP=0;try{uQn()}finally{qj=0,fQn(),GO=0}}function dQn(){var e=OM.now(),t=e-zB;t>qkt&&(HH-=t,zB=e)}function fQn(){for(var e,t=FB,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:FB=n);BP=e,Zge(r)}function Zge(e){if(!qj){zP&&(zP=clearTimeout(zP));var t=e-GO;t>24?(e<1/0&&(zP=setTimeout(m7e,e-OM.now()-HH)),kR&&(kR=clearInterval(kR))):(kR||(zB=OM.now(),kR=setInterval(dQn,qkt)),qj=1,Hkt(m7e))}}function g7e(e,t,n){var r=new BB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var pQn=VH("start","end","cancel","interrupt"),hQn=[],Zkt=0,v7e=1,Gge=2,I8=3,y7e=4,Qge=5,A8=6;function WH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;mQn(e,n,{name:t,index:r,group:s,on:pQn,tween:hQn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:Zkt})}function Xke(e,t){var n=Gg(e,t);if(n.state>Zkt)throw new Error("too late; already scheduled");return n}function By(e,t){var n=Gg(e,t);if(n.state>I8)throw new Error("too late; already running");return n}function Gg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function mQn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=Wkt(a,0,n.time);function a(u){n.state=v7e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==v7e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===I8)return g7e(i);h.state===y7e?(h.state=A8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=A8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(g7e(function(){n.state===I8&&(n.state=y7e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Gge,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Gge){for(n.state=I8,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=Qge,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===Qge&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=A8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function R8(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Gge&&r.state<Qge,r.state=A8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function gQn(e){return this.each(function(){R8(this,e)})}function vQn(e,t){var n,r;return function(){var s=By(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function yQn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=By(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function bQn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Gg(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?vQn:yQn)(n,e,t))}function Jke(e,t,n){var r=e._id;return e.each(function(){var s=By(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Gg(s,r).value[t]}}function Gkt(e,t){var n;return(typeof t=="number"?cg:t instanceof ZO?LB:(n=ZO(t))?(t=n,LB):Bkt)(e,t)}function xQn(e){return function(){this.removeAttribute(e)}}function wQn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function SQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function kQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function OQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function _Qn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function CQn(e,t){var n=qH(e),r=n==="transform"?sQn:Gkt;return this.attrTween(e,typeof t=="function"?(n.local?_Qn:OQn)(n,r,Jke(this,"attr."+e,t)):t==null?(n.local?wQn:xQn)(n):(n.local?kQn:SQn)(n,r,t))}function EQn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function TQn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function jQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&TQn(e,a)),n}return s._value=t,s}function NQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&EQn(e,a)),n}return s._value=t,s}function IQn(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=qH(e);return this.tween(n,(r.local?jQn:NQn)(r,t))}function AQn(e,t){return function(){Xke(this,e).delay=+t.apply(this,arguments)}}function RQn(e,t){return t=+t,function(){Xke(this,e).delay=t}}function PQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?AQn:RQn)(t,e)):Gg(this.node(),t).delay}function $Qn(e,t){return function(){By(this,e).duration=+t.apply(this,arguments)}}function MQn(e,t){return t=+t,function(){By(this,e).duration=t}}function DQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?$Qn:MQn)(t,e)):Gg(this.node(),t).duration}function LQn(e,t){if(typeof t!="function")throw new Error;return function(){By(this,e).ease=t}}function FQn(e){var t=this._id;return arguments.length?this.each(LQn(t,e)):Gg(this.node(),t).ease}function zQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;By(this,e).ease=n}}function BQn(e){if(typeof e!="function")throw new Error;return this.each(zQn(this._id,e))}function UQn(e){typeof e!="function"&&(e=_kt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Mx(r,this._parents,this._name,this._id)}function VQn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new Mx(i,this._parents,this._name,this._id)}function qQn(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function HQn(e,t,n){var r,s,a=qQn(t)?Xke:By;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function WQn(e,t){var n=this._id;return arguments.length<2?Gg(this.node(),n).on.on(e):this.each(HQn(n,e,t))}function ZQn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function GQn(){return this.on("end.remove",ZQn(this._id))}function QQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Wke(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,WH(u[p],t,n,p,u,Gg(d,n)));return new Mx(a,this._parents,t,n)}function YQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Okt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=Gg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&WH(h,t,n,v,p,m);a.push(p),i.push(d)}return new Mx(a,i,t,n)}var KQn=P3.prototype.constructor;function XQn(){return new KQn(this._groups,this._parents)}function JQn(e,t){var n,r,s;return function(){var a=Vj(this,e),i=(this.style.removeProperty(e),Vj(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function Qkt(e){return function(){this.style.removeProperty(e)}}function eYn(e,t,n){var r,s=n+"",a;return function(){var i=Vj(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function tYn(e,t,n){var r,s,a;return function(){var i=Vj(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),Vj(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function nYn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=By(this,e),u=c.on,d=c.value[a]==null?l||(l=Qkt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function rYn(e,t,n){var r=(e+="")=="transform"?rQn:Gkt;return t==null?this.styleTween(e,JQn(e,r)).on("end.style."+e,Qkt(e)):typeof t=="function"?this.styleTween(e,tYn(e,r,Jke(this,"style."+e,t))).each(nYn(this._id,e)):this.styleTween(e,eYn(e,r,t),n).on("end.style."+e,null)}function sYn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function aYn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&sYn(e,i,n)),r}return a._value=t,a}function iYn(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,aYn(e,t,n??""))}function oYn(e){return function(){this.textContent=e}}function lYn(e){return function(){var t=e(this);this.textContent=t??""}}function cYn(e){return this.tween("text",typeof e=="function"?lYn(Jke(this,"text",e)):oYn(e==null?"":e+""))}function uYn(e){return function(t){this.textContent=e.call(this,t)}}function dYn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&uYn(s)),t}return r._value=e,r}function fYn(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,dYn(e))}function pYn(){for(var e=this._name,t=this._id,n=Ykt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=Gg(c,t);WH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Mx(r,this._parents,e,n)}function hYn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=By(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var mYn=0;function Mx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Ykt(){return++mYn}var xb=P3.prototype;Mx.prototype={constructor:Mx,select:QQn,selectAll:YQn,selectChild:xb.selectChild,selectChildren:xb.selectChildren,filter:UQn,merge:VQn,selection:XQn,transition:pYn,call:xb.call,nodes:xb.nodes,node:xb.node,size:xb.size,empty:xb.empty,each:xb.each,on:WQn,attr:CQn,attrTween:IQn,style:rYn,styleTween:iYn,text:cYn,textTween:fYn,remove:GQn,tween:bQn,delay:PQn,duration:DQn,ease:FQn,easeVarying:BQn,end:hYn,[Symbol.iterator]:xb[Symbol.iterator]};function gYn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var vYn={time:null,delay:0,duration:250,ease:gYn};function yYn(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function bYn(e){var t,n;e instanceof Mx?(t=e._id,e=e._name):(t=Ykt(),(n=vYn).time=Kke(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&WH(c,e,t,u,i,n||yYn(c,t));return new Mx(r,this._parents,e,t)}P3.prototype.interrupt=gQn;P3.prototype.transition=bYn;const tF=e=>()=>e;function xYn(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function tx(e,t,n){this.k=e,this.x=t,this.y=n}tx.prototype={constructor:tx,scale:function(e){return e===1?this:new tx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new tx(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var ZH=new tx(1,0,0);Kkt.prototype=tx.prototype;function Kkt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return ZH;return e.__zoom}function Lte(e){e.stopImmediatePropagation()}function OR(e){e.preventDefault(),e.stopImmediatePropagation()}function wYn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function SYn(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function b7e(){return this.__zoom||ZH}function kYn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function OYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function _Yn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function Xkt(){var e=wYn,t=SYn,n=_Yn,r=kYn,s=OYn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=N8,u=VH("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(D){D.property("__zoom",b7e).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,F,H,B){var U=D.selection?D.selection():D;U.property("__zoom",b7e),D!==U?_(D,F,H,B):U.interrupt().each(function(){C(this,arguments).event(B).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},b.scaleBy=function(D,F,H,B){b.scaleTo(D,function(){var U=this.__zoom.k,V=typeof F=="function"?F.apply(this,arguments):F;return U*V},H,B)},b.scaleTo=function(D,F,H,B){b.transform(D,function(){var U=t.apply(this,arguments),V=this.__zoom,M=H==null?k(U):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),q=typeof F=="function"?F.apply(this,arguments):F;return n(S(x(V,q),M,G),U,i)},H,B)},b.translateBy=function(D,F,H,B){b.transform(D,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,B)},b.translateTo=function(D,F,H,B,U){b.transform(D,function(){var V=t.apply(this,arguments),M=this.__zoom,G=B==null?k(V):typeof B=="function"?B.apply(this,arguments):B;return n(ZH.translate(G[0],G[1]).scale(M.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},B,U)};function x(D,F){return F=Math.max(a[0],Math.min(a[1],F)),F===D.k?D:new tx(F,D.x,D.y)}function S(D,F,H){var B=F[0]-H[0]*D.k,U=F[1]-H[1]*D.k;return B===D.x&&U===D.y?D:new tx(D.k,B,U)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,F,H,B){D.on("start.zoom",function(){C(this,arguments).event(B).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(B).end()}).tween("zoom",function(){var U=this,V=arguments,M=C(U,V).event(B),G=t.apply(U,V),q=H==null?k(G):typeof H=="function"?H.apply(U,V):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),z=U.__zoom,Z=typeof F=="function"?F.apply(U,V):F,K=c(z.invert(q).concat($/z.k),Z.invert(q).concat($/Z.k));return function(ne){if(ne===1)ne=Z;else{var ee=K(ne),J=$/ee[2];ne=new tx(J,q[0]-ee[0]*J,q[1]-ee[1]*J)}M.zoom(null,ne)}})}function C(D,F,H){return!H&&D.__zooming||new E(D,F)}function E(D,F){this.that=D,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,F),this.taps=0}E.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,F){return this.mouse&&D!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var F=Ep(this.that).datum();u.call(D,this.that,new xYn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),F)}};function T(D,...F){if(!e.apply(this,arguments))return;var H=C(this,F).event(D),B=this.__zoom,U=Math.max(a[0],Math.min(a[1],B.k*Math.pow(2,r.apply(this,arguments)))),V=og(D);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=B.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(B.k===U)return;H.mouse=[V,B.invert(V)],R8(this),H.start()}OR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(B,U),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...F){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,B=C(this,F,!0).event(D),U=Ep(D.view).on("mousemove.zoom",q,!0).on("mouseup.zoom",$,!0),V=og(D,H),M=D.clientX,G=D.clientY;$kt(D.view),Lte(D),B.mouse=[V,this.__zoom.invert(V)],R8(this),B.start();function q(z){if(OR(z),!B.moved){var Z=z.clientX-M,K=z.clientY-G;B.moved=Z*Z+K*K>v}B.event(z).zoom("mouse",n(S(B.that.__zoom,B.mouse[0]=og(z,H),B.mouse[1]),B.extent,i))}function $(z){U.on("mousemove.zoom mouseup.zoom",null),Mkt(z.view,B.moved),OR(z),B.event(z).end()}}function I(D,...F){if(e.apply(this,arguments)){var H=this.__zoom,B=og(D.changedTouches?D.changedTouches[0]:D,this),U=H.invert(B),V=H.k*(D.shiftKey?.5:2),M=n(S(x(H,V),B,U),t.apply(this,F),i);OR(D),l>0?Ep(this).transition().duration(l).call(_,M,B,D):Ep(this).call(b.transform,M,B,D)}}function A(D,...F){if(e.apply(this,arguments)){var H=D.touches,B=H.length,U=C(this,F,D.changedTouches.length===B).event(D),V,M,G,q;for(Lte(D),M=0;M<B;++M)G=H[M],q=og(G,this),q=[q,this.__zoom.invert(q),G.identifier],U.touch0?!U.touch1&&U.touch0[2]!==q[2]&&(U.touch1=q,U.taps=0):(U.touch0=q,V=!0,U.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(U.taps<2&&(f=q[0],d=setTimeout(function(){d=null},h)),R8(this),U.start())}}function R(D,...F){if(this.__zooming){var H=C(this,F).event(D),B=D.changedTouches,U=B.length,V,M,G,q;for(OR(D),V=0;V<U;++V)M=B[V],G=og(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],z=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],ne=(ne=Z[0]-$[0])*ne+(ne=Z[1]-$[1])*ne,ee=(ee=K[0]-z[0])*ee+(ee=K[1]-z[1])*ee;M=x(M,Math.sqrt(ne/ee)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],q=[(z[0]+K[0])/2,(z[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],q=H.touch0[1];else return;H.zoom("touch",n(S(M,G,q),H.extent,i))}}function L(D,...F){if(this.__zooming){var H=C(this,F).event(D),B=D.changedTouches,U=B.length,V,M;for(Lte(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),V=0;V<U;++V)M=B[V],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=og(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Ep(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:tF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:tF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:tF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:tF([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const wy={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},_M=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Jkt=["Enter"," ","Escape"],eOt={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var Hj;(function(e){e.Strict="strict",e.Loose="loose"})(Hj||(Hj={}));var sO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(sO||(sO={}));var CM;(function(e){e.Partial="partial",e.Full="full"})(CM||(CM={}));const tOt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var kw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(kw||(kw={}));var EM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(EM||(EM={}));var sr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(sr||(sr={}));const x7e={[sr.Left]:sr.Right,[sr.Right]:sr.Left,[sr.Top]:sr.Bottom,[sr.Bottom]:sr.Top};function nOt(e){return e===null?null:e?"valid":"invalid"}const rOt=e=>"id"in e&&"source"in e&&"target"in e,CYn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),eOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),M3=(e,t=[0,0])=>{const{width:n,height:r}=i0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},EYn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):eOe(s)?s:t.nodeLookup.get(s.id));const l=i?UB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return GH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return QH(n)},D3=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=GH(n,UB(s)),r=!0)}),r?QH(n):{x:0,y:0,width:0,height:0}},tOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...F3(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=TM(l,Zj(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},TYn=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function jYn(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function NYn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=jYn(e,i),c=D3(l),u=nOe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function sOt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",wy.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&Gj(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=Gj(f)?QO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",wy.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function IYn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=TYn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const Wj=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),QO=(e={x:0,y:0},t,n)=>({x:Wj(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Wj(e.y,t[0][1],t[1][1]-(n?.height??0))});function aOt(e,t,n){const{width:r,height:s}=i0(n),{x:a,y:i}=n.internals.positionAbsolute;return QO(e,[[a,i],[a+r,i+s]],t)}const w7e=(e,t,n)=>e<t?Wj(Math.abs(e-t),1,t)/t:e>n?-Wj(Math.abs(e-n),1,t)/t:0,iOt=(e,t,n=15,r=40)=>{const s=w7e(e.x,r,t.width-r)*n,a=w7e(e.y,r,t.height-r)*n;return[s,a]},GH=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Yge=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),QH=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Zj=(e,t=[0,0])=>{const{x:n,y:r}=eOe(e)?e.internals.positionAbsolute:M3(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},UB=(e,t=[0,0])=>{const{x:n,y:r}=eOe(e)?e.internals.positionAbsolute:M3(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},oOt=(e,t)=>QH(GH(Yge(e),Yge(t))),TM=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},S7e=e=>xg(e.width)&&xg(e.height)&&xg(e.x)&&xg(e.y),xg=e=>!isNaN(e)&&isFinite(e),AYn=(e,t)=>{},L3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),F3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?L3(l,i):l},VB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function uE(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function RYn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=uE(e,n),s=uE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=uE(e.top??e.y??0,n),s=uE(e.bottom??e.y??0,n),a=uE(e.left??e.x??0,t),i=uE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function PYn(e,t,n,r,s,a){const{x:i,y:l}=VB(e,[t,n,r]),{x:c,y:u}=VB({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const nOe=(e,t,n,r,s,a)=>{const i=RYn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=Wj(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=PYn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},jM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function Gj(e){return e!=null&&e!=="parent"}function i0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function lOt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function cOt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function k7e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function $Yn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function MYn(e){return{...eOt,...e||{}}}function S2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=wg(e),l=F3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?L3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const rOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),uOt=e=>e?.getRootNode?.()||window?.document,DYn=["INPUT","SELECT","TEXTAREA"];function dOt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:DYn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const fOt=e=>"clientX"in e,wg=(e,t)=>{const n=fOt(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},O7e=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...rOe(i)}})};function pOt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function nF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function _7e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case sr.Left:return[t-nF(t-r,a),n];case sr.Right:return[t+nF(r-t,a),n];case sr.Top:return[t,n-nF(n-s,a)];case sr.Bottom:return[t,n+nF(s-n,a)]}}function sOe({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,curvature:i=.25}){const[l,c]=_7e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=_7e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=pOt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,p,h,m]}function hOt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function LYn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function FYn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=GH(UB(e),UB(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return TM(i,QH(a))>0}const zYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,BYn=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),UYn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||zYn;let s;return rOt(e)?s={...e}:s={...e,id:r(e)},BYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function mOt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=hOt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const C7e={[sr.Left]:{x:-1,y:0},[sr.Right]:{x:1,y:0},[sr.Top]:{x:0,y:-1},[sr.Bottom]:{x:0,y:1}},VYn=({source:e,sourcePosition:t=sr.Bottom,target:n})=>t===sr.Left||t===sr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},E7e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function qYn({source:e,sourcePosition:t=sr.Bottom,target:n,targetPosition:r=sr.Top,center:s,offset:a,stepPosition:i}){const l=C7e[t],c=C7e[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=VYn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=hOt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const T=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?T:N:m=p==="x"?N:T}else{const T=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:T:m=l.y===h?T:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const F=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*F:x[p]=(d[p]>n[p]?-1:1)*F}}if(t!==r){const D=p==="x"?"y":"x",F=l[p]===c[D],H=u[D]>d[D],B=u[D]<d[D];(l[p]===1&&(!F&&H||F&&B)||l[p]!==1&&(!F&&B||F&&H))&&(m=p==="x"?T:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+x.x,y:d.y+x.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],v,y,S,k]}function HYn(e,t,n,r){const s=Math.min(E7e(e,t)/2,E7e(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Kge({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=qYn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=HYn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function T7e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function WYn(e){const{sourceNode:t,targetNode:n}=e;if(!T7e(t)||!T7e(n))return null;const r=t.internals.handleBounds||j7e(t.handles),s=n.internals.handleBounds||j7e(n.handles),a=N7e(r?.source??[],e.sourceHandle),i=N7e(e.connectionMode===Hj.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",wy.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||sr.Bottom,c=i?.position||sr.Top,u=YO(t,a,l),d=YO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function j7e(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function YO(e,t,n=sr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??i0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case sr.Top:return{x:s+i/2,y:a};case sr.Right:return{x:s+i,y:a+l/2};case sr.Bottom:return{x:s+i/2,y:a+l};case sr.Left:return{x:s,y:a+l/2}}}function N7e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Xge(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function ZYn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=Xge(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const gOt=1e3,GYn=10,aOe={nodeOrigin:[0,0],nodeExtent:_M,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},QYn={...aOe,checkEquality:!0};function iOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function YYn(e,t,n){const r=iOe(aOe,n);for(const s of e.values())if(s.parentId)lOe(s,e,t,r);else{const a=M3(s,r.nodeOrigin),i=Gj(s.extent)?s.extent:r.nodeExtent,l=QO(a,i,i0(s));s.internals.positionAbsolute=l}}function KYn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function oOe(e){return e==="manual"}function Jge(e,t,n,r={}){const s=iOe(QYn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!oOe(s.zIndexMode)?gOt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const p=M3(d,s.nodeOrigin),h=Gj(d.extent)?d.extent:s.nodeExtent,m=QO(p,h,i0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:KYn(d,f),z:vOt(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&lOe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function XYn(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function lOe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=iOe(aOe,r),u=e.parentId,d=t.get(u);if(!d){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}XYn(e,n),s&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++s.i,d.internals.z=d.internals.z+s.i*GYn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!oOe(c)?gOt:0,{x:p,y:h,z:m}=JYn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function vOt(e,t,n){const r=xg(e.zIndex)?e.zIndex:0;return oOe(n)?r:r+(e.selected?t:0)}function JYn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=i0(e),u=M3(e,n),d=Gj(e.extent)?QO(u,e.extent,c):u;let f=QO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=aOt(f,c,t));const p=vOt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function cOe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??Zj(l),u=oOt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=i0(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function eKn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=rOe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=Gj(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=aOt(k,v,t.get(m.parentId)):S&&(k=QO(k,S,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:O7e("source",h.nodeElement,x,f,m.id),target:O7e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&lOe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:Zj(_,s)}))}}if(p.length>0){const h=cOe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function tKn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function I7e(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function yOt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;I7e("source",c,d,e,s,i),I7e("target",c,u,e,a,l),t.set(r.id,r)}}function bOt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:bOt(n,t):!1}function A7e(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function nKn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!bOt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Fte({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function rKn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=L3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function sKn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,p=null,h=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:E=0}){p=Ep(k);function T({x:R,y:L}){const{nodeLookup:D,nodeExtent:F,snapGrid:H,snapToGrid:B,nodeOrigin:U,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:q}=t();a={x:R,y:L};let $=!1;const z=l.size>1,Z=z&&F?Yge(D3(l)):null,K=z&&B?rKn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[ne,ee]of l){if(!D.has(ne))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};B&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:L3(J,H));let ae=null;if(z&&F&&!ee.extent&&Z){const{positionAbsolute:te}=ee.internals,ue=te.x-Z.x+F[0][0],fe=te.x+ee.measured.width-Z.x2+F[1][0],ce=te.y-Z.y+F[0][1],me=te.y+ee.measured.height-Z.y2+F[1][1];ae=[[ue,ce],[fe,me]]}const{position:pe,positionAbsolute:Y}=sOt({nodeId:ne,nextPosition:J,nodeLookup:D,nodeExtent:ae||F,nodeOrigin:U,onError:G});$=$||ee.position.x!==pe.x||ee.position.y!==pe.y,ee.position=pe,ee.internals.positionAbsolute=Y}if(m=m||$,!!$&&(q(l,!0),v&&(r||V||!C&&M))){const[ne,ee]=Fte({nodeId:C,dragItems:l,nodeLookup:D});r?.(v,l,ne,ee),V?.(v,ne,ee),C||M?.(v,ee)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:F}=t();if(!F){c=!1,cancelAnimationFrame(i);return}const[H,B]=iOt(u,d,D);(H!==0||B!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-B/R[2],await L({x:H,y:B})&&T(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:F,transform:H,snapGrid:B,snapToGrid:U,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:q}=t();f=!0,(!V||!_)&&!D&&C&&(L.get(C)?.selected||q()),_&&V&&C&&e?.(C);const $=S2(R.sourceEvent,{transform:H,snapGrid:B,snapToGrid:U,containerBounds:d});if(a=$,l=nKn(L,F,$,C),l.size>0&&(n||M||!C&&G)){const[z,Z]=Fte({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,z,Z),M?.(R.sourceEvent,z,Z),C||G?.(R.sourceEvent,Z)}}const A=Dkt().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:F,snapGrid:H,snapToGrid:B}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,D===0&&I(R),a=S2(R.sourceEvent,{transform:F,snapGrid:H,snapToGrid:B,containerBounds:d}),u=wg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:F,snapToGrid:H,nodeDragThreshold:B,nodeLookup:U}=t(),V=S2(R.sourceEvent,{transform:D,snapGrid:F,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!U.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=wg(R.sourceEvent,d),G=M.x-u.x,q=M.y-u.y;Math.sqrt(G*G+q*q)>B&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=wg(R.sourceEvent,d),T(V))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:F,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||F||!C&&H){const[B,U]=Fte({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,B,U),F?.(R.sourceEvent,B,U),C||H?.(R.sourceEvent,U)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!A7e(L,`.${x}`,k))&&(!S||A7e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function aKn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())TM(s,Zj(a))>0&&r.push(a);return r}const iKn=250;function oKn(e,t,n,r){let s=[],a=1/0;const i=aKn(e,n,t+iKn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=YO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function xOt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...YO(i,c,c.position,!0)}:c}function wOt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function lKn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const SOt=()=>!0;function cKn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=SOt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:E=1,handleDomNode:T}){const N=uOt(e.target);let I=0,A;const{x:R,y:L}=wg(e),D=wOt(a,T),F=l?.getBoundingClientRect();let H=!1;if(!F||!D)return;const B=xOt(s,D,r,c,t);if(!B)return;let U=wg(e,F),V=!1,M=null,G=!1,q=null;function $(){if(!d||!F)return;const[pe,Y]=iOt(U,F,C);p({x:pe,y:Y}),I=requestAnimationFrame($)}const z={...B,nodeId:s,type:D,position:B.position},Z=c.get(s);let ne={inProgress:!0,isValid:null,from:YO(Z,z,sr.Left,!0),fromHandle:z,fromPosition:z.position,fromNode:Z,to:U,toHandle:null,toPosition:x7e[z.position],toNode:null,pointer:U};function ee(){H=!0,S(ne),m?.(e,{nodeId:s,handleId:r,handleType:D})}E===0&&ee();function J(pe){if(!H){const{x:me,y:be}=wg(pe),we=me-R,Oe=be-L;if(!(we*we+Oe*Oe>E*E))return;ee()}if(!_()||!z){ae(pe);return}const Y=k();U=wg(pe,F),A=oKn(F3(U,Y,!1,[1,1]),n,c,z),V||($(),V=!0);const te=kOt(pe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});q=te.handleDomNode,M=te.connection,G=lKn(!!A,te.isValid);const ue=c.get(s),fe=ue?YO(ue,z,sr.Left,!0):ne.from,ce={...ne,from:fe,isValid:G,to:te.toHandle&&G?VB({x:te.toHandle.x,y:te.toHandle.y},Y):U,toHandle:te.toHandle,toPosition:G&&te.toHandle?te.toHandle.position:x7e[z.position],toNode:te.toHandle?c.get(te.toHandle.nodeId):null,pointer:U};S(ce),ne=ce}function ae(pe){if(!("touches"in pe&&pe.touches.length>0)){if(H){(A||q)&&M&&G&&v?.(M);const{inProgress:Y,...te}=ne,ue={...te,toPosition:ne.toHandle?ne.toPosition:null};y?.(pe,ue),a&&x?.(pe,ue)}h(),cancelAnimationFrame(I),V=!1,G=!1,M=null,q=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",J),N.addEventListener("touchend",ae)}function kOt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=SOt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=wg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=wOt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!S||!x)return b;const E={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=E;const N=_&&C&&(n===Hj.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(E),b.toHandle=xOt(S,x,k,d,n,!0)}return b}const eve={onPointerDown:cKn,isValid:kOt};function uKn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Ep(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=S.sourceEvent.ctrlKey&&jM()?10:1,C=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,C*_);t.scaleTo(E)};let v=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(v=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const _=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),T={x:k[0]-C[0]*E,y:k[1]-C[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:T.x,y:T.y,zoom:k[2]},N,l)},x=Xkt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:og}}const YH=e=>({x:e.x,y:e.y,zoom:e.k}),zte=({x:e,y:t,zoom:n})=>ZH.translate(e,t).scale(n),dT=(e,t)=>e.target.closest(`.${t}`),OOt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),dKn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Bte=(e,t=0,n=dKn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},_Ot=e=>{const t=e.ctrlKey&&jM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function fKn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(dT(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=og(d),b=_Ot(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===sO.Vertical?0:d.deltaX*p,m=s===sO.Horizontal?0:d.deltaY*p;!jM()&&d.shiftKey&&s!==sO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=YH(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function pKn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=dT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function hKn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=YH(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function mKn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&OOt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,YH(a.transform))}}function gKn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&OOt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=YH(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function vKn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(dT(f,`${u}-flow__node`)||dT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||dT(f,l)&&m||dT(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function yKn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=Xkt().scaleExtent([t,n]).translateExtent(r),p=Ep(e).call(f);x({x:s.x,y:s.y,zoom:Wj(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(_Ot);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?px:N8).transform(Bte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:F,panOnDrag:H,panOnScrollMode:B,panOnScrollSpeed:U,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:q,zoomActivationKeyPressed:$,lib:z,onTransformChange:Z,connectionInProgress:K,paneClickDistance:ne,selectionOnDrag:ee}){D&&!u.isZoomingOrPanning&&b();const J=F&&!$&&!D;f.clickDistance(ee?1/0:!xg(ne)||ne<0?0:ne);const ae=J?fKn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:B,panOnScrollSpeed:U,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):pKn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=hKn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const te=mKn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",te);const ue=gKn({zoomPanValues:u,panOnDrag:H,panOnScroll:F,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",ue)}const pe=vKn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:F,zoomOnDoubleClick:q,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:z,connectionInProgress:K});f.filter(pe),q?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=zte(A),F=f?.constrain()(D,R,L);return F&&await v(F),new Promise(H=>H(F))}async function S(A,R){const L=zte(A);return await v(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=zte(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function _(){const A=p?Kkt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?px:N8).scaleTo(Bte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?px:N8).scaleBy(Bte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!xg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:E,setScaleExtent:T,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var Qj;(function(e){e.Line="line",e.Handle="handle"})(Qj||(Qj={}));function bKn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function R7e(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function J0(e,t){return Math.max(0,t-e)}function ew(e,t){return Math.max(0,e-t)}function rF(e,t,n){return Math.max(0,t-e,e-n)}function P7e(e,t){return e?!t:t}function xKn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:_,height:C,aspectRatio:E}=e;let T=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-T:T),A=C+(u?-N:N),R=-a[0]*_,L=-a[1]*C;let D=rF(I,v,y),F=rF(A,b,x);if(i){let U=0,V=0;c&&T<0?U=J0(S+T+R,i[0][0]):!c&&T>0&&(U=ew(S+I+R,i[1][0])),u&&N<0?V=J0(k+N+L,i[0][1]):!u&&N>0&&(V=ew(k+A+L,i[1][1])),D=Math.max(D,U),F=Math.max(F,V)}if(l){let U=0,V=0;c&&T>0?U=ew(S+T,l[0][0]):!c&&T<0&&(U=J0(S+I,l[1][0])),u&&N>0?V=ew(k+N,l[0][1]):!u&&N<0&&(V=J0(k+A,l[1][1])),D=Math.max(D,U),F=Math.max(F,V)}if(s){if(d){const U=rF(I/E,b,x)*E;if(D=Math.max(D,U),i){let V=0;!c&&!u||c&&!u&&p?V=ew(k+L+I/E,i[1][1])*E:V=J0(k+L+(c?T:-T)/E,i[0][1])*E,D=Math.max(D,V)}if(l){let V=0;!c&&!u||c&&!u&&p?V=J0(k+I/E,l[1][1])*E:V=ew(k+(c?T:-T)/E,l[0][1])*E,D=Math.max(D,V)}}if(f){const U=rF(A*E,v,y)/E;if(F=Math.max(F,U),i){let V=0;!c&&!u||u&&!c&&p?V=ew(S+A*E+R,i[1][0])/E:V=J0(S+(u?N:-N)*E+R,i[0][0])/E,F=Math.max(F,V)}if(l){let V=0;!c&&!u||u&&!c&&p?V=J0(S+A*E,l[1][0])/E:V=ew(S+(u?N:-N)*E,l[0][0])/E,F=Math.max(F,V)}}}N=N+(N<0?F:-F),T=T+(T<0?D:-D),s&&(p?I>A*E?N=(P7e(c,u)?-T:T)/E:T=(P7e(c,u)?-N:N)*E:d?(N=T/E,u=c):(T=N*E,c=u));const H=c?S+T:S,B=u?k+N:k;return{width:_+(c?-T:T),height:C+(u?-N:N),x:a[0]*T*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+B}}const COt={width:0,height:0,x:0,y:0},wKn={...COt,pointerX:0,pointerY:0,aspectRatio:1};function SKn(e){return[[0,0],[e.measured.width,e.measured.height]]}function kKn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function OKn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Ep(e);let i={controlDirection:R7e("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...COt},x={...wKn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:R7e(u)};let S,k=null,_=[],C,E,T,N=!1;const I=Dkt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:F,nodeOrigin:H,paneDomNode:B}=n();if(S=R.get(t),!S)return;k=B?.getBoundingClientRect()??null;const{xSnapped:U,ySnapped:V}=S2(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:F,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:U,pointerY:V,aspectRatio:b.width/b.height},C=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(C=R.get(S.parentId),E=C&&S.extent==="parent"?SKn(C):void 0),_=[],T=void 0;for(const[M,G]of R)if(G.parentId===t&&(_.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const q=kKn(G,S,G.origin??H);T?T=[[Math.min(q[0][0],T[0][0]),Math.min(q[0][1],T[0][1])],[Math.max(q[1][0],T[1][0]),Math.max(q[1][1],T[1][1])]]:T=q}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:F}=n(),H=S2(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),B=[];if(!S)return;const{x:U,y:V,width:M,height:G}=b,q={},$=S.origin??F,{width:z,height:Z,x:K,y:ne}=xKn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,T),ee=z!==M,J=Z!==G,ae=K!==U&&ee,pe=ne!==V&&J;if(!ae&&!pe&&!ee&&!J)return;if((ae||pe||$[0]===1||$[1]===1)&&(q.x=ae?K:b.x,q.y=pe?ne:b.y,b.x=q.x,b.y=q.y,_.length>0)){const fe=K-U,ce=ne-V;for(const me of _)me.position={x:me.position.x-fe+$[0]*(z-M),y:me.position.y-ce+$[1]*(Z-G)},B.push(me)}if((ee||J)&&(q.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?z:b.width,q.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=q.width,b.height=q.height),C&&S.expandParent){const fe=$[0]*(q.width??0);q.x&&q.x<fe&&(b.x=fe,x.x=x.x-(q.x-fe));const ce=$[1]*(q.height??0);q.y&&q.y<ce&&(b.y=ce,x.y=x.y-(q.y-ce))}const Y=bKn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...b,direction:Y};y?.(A,te)!==!1&&(N=!0,m?.(A,te),r(q,B))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const _Kn={},$7e=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(_Kn?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},u=t=e(r,s,c);return c},CKn=e=>e?$7e(e):$7e,{useDebugValue:EKn}=ze,{useSyncExternalStoreWithSelector:TKn}=mEn,jKn=e=>e;function EOt(e,t=jKn,n){const r=TKn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return EKn(r),r}const M7e=(e,t)=>{const n=CKn(e),r=(s,a=t)=>EOt(n,s,a);return Object.assign(r,n),r},NKn=(e,t)=>e?M7e(e,t):M7e;function io(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const KH=g.createContext(null),IKn=KH.Provider,TOt=wy.error001();function Us(e,t){const n=g.useContext(KH);if(n===null)throw new Error(TOt);return EOt(n,e,t)}function To(){const e=g.useContext(KH);if(e===null)throw new Error(TOt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const D7e={display:"none"},AKn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},jOt="react-flow__node-desc",NOt="react-flow__edge-desc",RKn="react-flow__aria-live",PKn=e=>e.ariaLiveMessage,$Kn=e=>e.ariaLabelConfig;function MKn({rfId:e}){const t=Us(PKn);return o.jsx("div",{id:`${RKn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:AKn,children:t})}function DKn({rfId:e,disableKeyboardA11y:t}){const n=Us($Kn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${jOt}-${e}`,style:D7e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${NOt}-${e}`,style:D7e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(MKn,{rfId:e})]})}const z3=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Hl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});z3.displayName="Panel";function LKn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(z3,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const FKn=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},sF=e=>e.id;function zKn(e,t){return io(e.selectedNodes.map(sF),t.selectedNodes.map(sF))&&io(e.selectedEdges.map(sF),t.selectedEdges.map(sF))}function BKn({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Us(FKn,zKn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const UKn=e=>!!e.onSelectionChangeHandlers;function VKn({onSelectionChange:e}){const t=Us(UKn);return e||t?o.jsx(BKn,{onSelectionChange:e}):null}const tve=typeof window<"u"?g.useLayoutEffect:g.useEffect,IOt=[0,0],qKn={x:0,y:0,zoom:1},HKn=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],L7e=[...HKn,"rfId"],WKn=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),F7e={translateExtent:_M,nodeOrigin:IOt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function ZKn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Us(WKn,io),u=To();tve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=F7e,l()}),[]);const d=g.useRef(F7e);return tve(()=>{for(const f of L7e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:MYn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},L7e.map(f=>e[f])),null}function z7e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function GKn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=z7e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:z7e()?.matches?"dark":"light"}const B7e=typeof document<"u"?document:null;function NM(e=null,t={target:B7e,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
234
|
+
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new Gqn(this):new Hqn(this)}getCursor(t,n=0,r){let s=t.doc?t:us.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?HE(this,s,n,r):qE(this,s,n,r)}}class ikt{constructor(t){this.spec=t}}function Vqn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function qE(e,t,n,r){let s;return e.wholeWord&&(s=qqn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=Vqn(e.test,t,s)),new $x(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function qqn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(NB(s,n-a))!=So.Word||t(IB(s,n-a))!=So.Word)&&(t(IB(s,r-a))!=So.Word||t(NB(s,r-a))!=So.Word))}class Hqn extends ikt{constructor(t){super(t)}nextMatch(t,n,r){let s=qE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=qE(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=qE(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=qE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=qE(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function Wqn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function HE(e,t,n,r){let s;return e.wholeWord&&(s=Zqn(t.charCategorizer(t.selection.main.head))),e.test&&(s=Wqn(e.test,t,s)),new rkt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function NB(e,t){return e.slice(Oc(e,t,!1),t)}function IB(e,t){return e.slice(t,Oc(e,t))}function Zqn(e){return(t,n,r)=>!r[0].length||(e(NB(r.input,r.index))!=So.Word||e(IB(r.input,r.index))!=So.Word)&&(e(IB(r.input,r.index+r[0].length))!=So.Word||e(NB(r.input,r.index+r[0].length))!=So.Word)}class Gqn extends ikt{nextMatch(t,n,r){let s=HE(this.spec,t,r,t.doc.length).next();return s.done&&(s=HE(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=HE(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=HE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=HE(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const yM=xr.define(),Bke=xr.define(),Yw=bl.define({create(e){return new Dee(zge(e).create(),null)},update(e,t){for(let n of t.effects)n.is(yM)?e=new Dee(n.value.create(),e.panel):n.is(Bke)&&(e=new Dee(e.query,n.value?Uke:null));return e},provide:e=>lM.from(e,t=>t.panel)});class Dee{constructor(t,n){this.query=t,this.panel=n}}const Qqn=An.mark({class:"cm-searchMatch"}),Yqn=An.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Kqn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Yw))}update(e){let t=e.state.field(Yw);(t!=e.startState.field(Yw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return An.none;let{view:n}=this,r=new Md;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(p=>p.from==u&&p.to==d);r.add(u,d,f?Yqn:Qqn)})}return r.finish()}},{decorations:e=>e.decorations});function R3(e){return t=>{let n=t.state.field(Yw,!1);return n&&n.query.spec.valid?e(t,n):ckt(t)}}const AB=R3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=bt.single(r.from,r.to),a=e.state.facet(hI);return e.dispatch({selection:s,effects:[Vke(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),lkt(e),!0}),RB=R3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=bt.single(s.from,s.to),i=e.state.facet(hI);return e.dispatch({selection:a,effects:[Vke(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),lkt(e),!0}),Xqn=R3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:bt.create(n.map(r=>bt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),Jqn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new $x(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(bt.range(l.value.from,l.value.to))}return t(e.update({selection:bt.create(a,i),userEvent:"select.search.matches"})),!0},G8e=R3((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(It.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=bt.single(i.from,i.to).map(f),d.push(Vke(e,i)),d.push(n.facet(hI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),eHn=R3((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:It.announce.of(r),userEvent:"input.replace.all"}),!0});function Uke(e){return e.state.facet(hI).createPanel(e)}function zge(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(hI);return new akt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function okt(e){let t=ske(e,Uke);return t&&t.dom.querySelector("[main-field]")}function lkt(e){let t=okt(e);t&&t==e.root.activeElement&&t.select()}const ckt=e=>{let t=e.state.field(Yw,!1);if(t&&t.panel){let n=okt(e);if(n&&n!=e.root.activeElement){let r=zge(e.state,t.query.spec);r.valid&&e.dispatch({effects:yM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Bke.of(!0),t?yM.of(zge(e.state,t.query.spec)):xr.appendConfig.of(sHn)]});return!0},ukt=e=>{let t=e.state.field(Yw,!1);if(!t||!t.panel)return!1;let n=ske(e,Uke);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Bke.of(!1)}),!0},tHn=[{key:"Mod-f",run:ckt,scope:"editor search-panel"},{key:"F3",run:AB,shift:RB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:AB,shift:RB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:ukt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Jqn},{key:"Mod-Alt-g",run:Iqn},{key:"Mod-d",run:Uqn,preventDefault:!0}];class nHn{constructor(t){this.view=t;let n=this.query=t.state.field(Yw).query.spec;this.commit=this.commit.bind(this),this.searchField=hi("input",{value:n.search,placeholder:up(t,"Find"),"aria-label":up(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=hi("input",{value:n.replace,placeholder:up(t,"Replace"),"aria-label":up(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=hi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=hi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=hi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return hi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=hi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>AB(t),[up(t,"next")]),r("prev",()=>RB(t),[up(t,"previous")]),r("select",()=>Xqn(t),[up(t,"all")]),hi("label",null,[this.caseField,up(t,"match case")]),hi("label",null,[this.reField,up(t,"regexp")]),hi("label",null,[this.wordField,up(t,"by word")]),...t.state.readOnly?[]:[hi("br"),this.replaceField,r("replace",()=>G8e(t),[up(t,"replace")]),r("replaceAll",()=>eHn(t),[up(t,"replace all")])],hi("button",{name:"close",onclick:()=>ukt(t),"aria-label":up(t,"close"),type:"button"},["×"])])}commit(){let t=new akt({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:yM.of(t)}))}keydown(t){Szn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?RB:AB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),G8e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(yM)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(hI).top}}function up(e,t){return e.state.phrase(t)}const G6=30,Q6=/[\s\.,:;?!]/;function Vke(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-G6),i=Math.min(s,n+G6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<G6;c++)if(!Q6.test(l[c+1])&&Q6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-G6;c--)if(!Q6.test(l[c-1])&&Q6.test(l[c])){l=l.slice(0,c);break}}return It.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const rHn=It.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),sHn=[Yw,th.low(Kqn),rHn];class Q8e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Ek{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(bM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Md,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=vHn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,An.widget({widget:new pHn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,An.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new Ek(u,n,Uj(u))}}function Uj(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new Q8e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new Q8e(r.from,a,r.diagnostic)}}),r}function aHn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(bM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(dkt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function iHn(e,t){return e.field(Ip,!1)?t:t.concat(xr.appendConfig.of(yHn))}const dkt=xr.define(),qke=xr.define(),fkt=xr.define(),Ip=bl.define({create(){return new Ek(An.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=Uj(n,e.selected.diagnostic,a)||Uj(n,null,a)}!n.size&&s&&t.state.facet(bM).autoPanel&&(s=null),e=new Ek(n,s,r)}for(let n of t.effects)if(n.is(dkt)){let r=t.state.facet(bM).autoPanel?n.value.length?xM.open:null:e.panel;e=Ek.init(n.value,r,t.state)}else n.is(qke)?e=new Ek(e.diagnostics,n.value?xM.open:null,e.selected):n.is(fkt)&&(e=new Ek(e.diagnostics,e.panel,n.value));return e},provide:e=>[lM.from(e,t=>t.panel),It.decorations.from(e,t=>t.diagnostics)]}),oHn=An.mark({class:"cm-lintRange cm-lintRange-active"});function lHn(e,t,n){let{diagnostics:r}=e.state.field(Ip),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(bM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:cHn(e,s)}}}:null}function cHn(e,t){return hi("ul",{class:"cm-tooltip-lint"},t.map(n=>hkt(e,n,!1)))}const uHn=e=>{let t=e.state.field(Ip,!1);(!t||!t.panel)&&e.dispatch({effects:iHn(e.state,[qke.of(!0)])});let n=ske(e,xM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},Y8e=e=>{let t=e.state.field(Ip,!1);return!t||!t.panel?!1:(e.dispatch({effects:qke.of(!1)}),!0)},dHn=e=>{let t=e.state.field(Ip,!1);if(!t)return!1;let n=e.state.selection.main,r=t.diagnostics.iter(n.to+1);return!r.value&&(r=t.diagnostics.iter(0),!r.value||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},fHn=[{key:"Mod-Shift-m",run:uHn,preventDefault:!0},{key:"F8",run:dHn}],bM=jn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...zy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:K8e,tooltipFilter:K8e,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function K8e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function pkt(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function hkt(e,t,n){var r;let s=n?pkt(t.actions):[];return hi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},hi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=Uj(e.state.field(Ip).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),hi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return hi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&hi("div",{class:"cm-diagnosticSource"},t.source))}class pHn extends nh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return hi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class X8e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=hkt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class xM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)Y8e(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=pkt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=Uj(this.view.state.field(Ip).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=hi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=hi("div",{class:"cm-panel-lint"},this.list,hi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>Y8e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ip).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Ip),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new X8e(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new X8e(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Ip),r=Uj(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:fkt.of(r)})}static open(t){return new xM(t)}}function hHn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function Y6(e){return hHn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const mHn=It.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Y6("#d11")},".cm-lintRange-warning":{backgroundImage:Y6("orange")},".cm-lintRange-info":{backgroundImage:Y6("#999")},".cm-lintRange-hint":{backgroundImage:Y6("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function gHn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function vHn(e){let t="hint",n=1;for(let r of e){let s=gHn(r.severity);s>n&&(n=s,t=r.severity)}return t}const yHn=[Ip,It.decorations.compute([Ip],e=>{let{selected:t,panel:n}=e.field(Ip);return!t||!n||t.from==t.to?An.none:An.set([oHn.range(t.from,t.to)])}),u8n(lHn,{hideOn:aHn}),mHn];var J8e=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(o7n)),t.defaultKeymap!==!1&&(a=a.concat(Tqn)),t.searchKeymap!==!1&&(a=a.concat(tHn)),t.historyKeymap!==!1&&(a=a.concat($Vn)),t.foldKeymap!==!1&&(a=a.concat(W8n)),t.completionKeymap!==!1&&(a=a.concat(l1t)),t.lintKeymap!==!1&&(a=a.concat(fHn));var i=[];return t.lineNumbers!==!1&&i.push(S8n()),t.highlightActiveLineGutter!==!1&&i.push(_8n()),t.highlightSpecialChars!==!1&&i.push(Lzn()),t.history!==!1&&i.push(CVn()),t.foldGutter!==!1&&i.push(Y8n()),t.drawSelection!==!1&&i.push(Tzn()),t.dropCursor!==!1&&i.push(Rzn()),t.allowMultipleSelections!==!1&&i.push(us.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(L8n()),t.syntaxHighlighting!==!1&&i.push(eS(e9n,{fallback:!0})),t.bracketMatching!==!1&&i.push(o9n()),t.closeBrackets!==!1&&i.push(r7n()),t.autocompletion!==!1&&i.push(o1t()),t.rectangularSelection!==!1&&i.push(Xzn()),s!==!1&&i.push(t8n()),t.highlightActiveLine!==!1&&i.push(qzn()),t.highlightSelectionMatches!==!1&&i.push(Pqn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(uI.of(" ".repeat(t.tabSize))),i.concat([cI.of(a.flat())]).filter(Boolean)};const bHn="#e5c07b",e9e="#e06c75",xHn="#56b6c2",wHn="#ffffff",T8="#abb2bf",Bge="#7d8799",SHn="#61afef",kHn="#98c379",t9e="#d19a66",OHn="#c678dd",_Hn="#21252b",n9e="#2c313a",r9e="#282c34",Lee="#353a42",CHn="#3E4451",s9e="#528bff",EHn=It.theme({"&":{color:T8,backgroundColor:r9e},".cm-content":{caretColor:s9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:s9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:CHn},".cm-panels":{backgroundColor:_Hn,color:T8},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:r9e,color:Bge,border:"none"},".cm-activeLineGutter":{backgroundColor:n9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Lee},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Lee,borderBottomColor:Lee},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:n9e,color:T8}}},{dark:!0}),THn=Hg.define([{tag:he.keyword,color:OHn},{tag:[he.name,he.deleted,he.character,he.propertyName,he.macroName],color:e9e},{tag:[he.function(he.variableName),he.labelName],color:SHn},{tag:[he.color,he.constant(he.name),he.standard(he.name)],color:t9e},{tag:[he.definition(he.name),he.separator],color:T8},{tag:[he.typeName,he.className,he.number,he.changed,he.annotation,he.modifier,he.self,he.namespace],color:bHn},{tag:[he.operator,he.operatorKeyword,he.url,he.escape,he.regexp,he.link,he.special(he.string)],color:xHn},{tag:[he.meta,he.comment],color:Bge},{tag:he.strong,fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:he.link,color:Bge,textDecoration:"underline"},{tag:he.heading,fontWeight:"bold",color:e9e},{tag:[he.atom,he.bool,he.special(he.variableName)],color:t9e},{tag:[he.processingInstruction,he.string,he.inserted],color:kHn},{tag:he.invalid,color:wHn}]),jHn=[EHn,eS(THn)];var NHn=It.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),IHn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(cI.of([jqn])),m&&(typeof m=="boolean"?v.unshift(J8e()):v.unshift(J8e(m))),p&&v.unshift(Gzn(p)),d){case"light":v.push(NHn);break;case"dark":v.push(jHn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(It.editable.of(!1)),c&&v.push(us.readOnly.of(!0)),[...v]},AHn=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(t=>!t.empty)});class RHn{constructor(t,n){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=n,this.timeoutMS=n,this.callbacks.push(t)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var t=this.callbacks.slice();this.callbacks.length=0,t.forEach(n=>{try{n()}catch(r){console.error("TimeoutLatch callback error:",r)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class a9e{constructor(){this.interval=null,this.latches=new Set}add(t){this.latches.add(t),this.start()}remove(t){this.latches.delete(t),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(t=>{t.tick(),t.isDone&&this.remove(t)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var Fee=null,PHn=()=>typeof window>"u"?new a9e:(Fee||(Fee=new a9e),Fee),$Hn=It.theme({"& .cm-scroller":{height:"100% !important"}}),i9e=null,zee=null;function MHn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===i9e||(i9e=i,zee=It.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),zee}var o9e=Fy.define(),DHn=200,LHn=[];function FHn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?LHn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,E=C===void 0?null:C,T=e.placeholder,N=T===void 0?"":T,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,F=D===void 0?!0:D,H=e.basicSetup,B=H===void 0?!0:H,U=e.root,V=e.initialState,M=g.useState(),G=M[0],q=M[1],$=g.useState(),z=$[0],Z=$[1],K=g.useState(),ne=K[0],ee=K[1],J=g.useState(()=>({current:null}))[0],ae=g.useState(()=>({current:null}))[0],pe=MHn(h,v,b,S,_,E),Y=It.updateListener.of(fe=>{if(fe.docChanged&&typeof r=="function"&&!fe.transactions.some(be=>be.annotation(o9e))){J.current?J.current.reset():(J.current=new RHn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},DHn),PHn().add(J.current));var ce=fe.state.doc,me=ce.toString();r(me,fe)}s&&s(AHn(fe))}),te=IHn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:F,basicSetup:B}),ue=[Y,...pe?[pe]:[],$Hn,...te];return i&&typeof i=="function"&&ue.push(It.updateListener.of(i)),ue=ue.concat(c),g.useLayoutEffect(()=>{if(G&&!ne){var fe={doc:t,selection:n,extensions:ue},ce=V?us.fromJSON(V.json,fe,V.fields):us.create(fe);if(ee(ce),!z){var me=new It({state:ce,parent:G,root:U});Z(me),a&&a(me,ce)}}return()=>{z&&(ee(void 0),Z(void 0))}},[G,ne]),g.useEffect(()=>{e.container&&q(e.container)},[e.container]),g.useEffect(()=>()=>{z&&(z.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[z]),g.useEffect(()=>{u&&z&&z.focus()},[u,z]),g.useEffect(()=>{z&&z.dispatch({effects:xr.reconfigure.of(ue)})},[f,c,h,v,b,S,_,E,N,A,L,F,B,r,i]),g.useEffect(()=>{if(t!==void 0){var fe=z?z.state.doc.toString():"";if(z&&t!==fe){var ce=J.current&&!J.current.isDone,me=()=>{z&&t!==z.state.doc.toString()&&z.dispatch({changes:{from:0,to:z.state.doc.toString().length,insert:t||""},annotations:[o9e.of(!0)]})};ce?ae.current=me:me()}}},[t,z]),{state:ne,setState:ee,view:z,setView:Z,container:G,setContainer:q}}var zHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Yu=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,E=e.indentWithTab,T=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=SSt(e,zHn),L=g.useRef(null),D=FHn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:E,editable:T,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),F=D.state,H=D.view,B=D.container,U=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:F,view:H}),[L,B,F,H]);var V=g.useCallback(G=>{L.current=G,U(G)},[U]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",WO({ref:V,className:""+M+(n?" "+n:"")},R))});Yu.displayName="CodeMirror";const BHn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let Bee=null;function UHn(){return Bee||(Bee=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Da(()=>import("./core-CEXVmTJJ.js"),__vite__mapDeps([0,1,2]),import.meta.url),Da(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Da(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Da(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Da(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Da(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Da(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Da(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Da(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Da(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Da(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Da(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Da(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Da(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Da(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Da(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Da(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Da(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Bee}async function VHn(e,t){const n=BHn[t?.toLowerCase()];if(!n)return null;const r=await UHn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function qHn(e){return new UO(cke.define(e))}const mkt=[ig.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Da(()=>Promise.resolve().then(()=>W6),void 0,import.meta.url).then(e=>e.javascript())}}),ig.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Da(()=>Promise.resolve().then(()=>b9n),void 0,import.meta.url).then(e=>e.json())}}),ig.of({name:"JSX",extensions:["jsx"],load(){return Da(()=>Promise.resolve().then(()=>W6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),ig.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Da(()=>Promise.resolve().then(()=>pVn),void 0,import.meta.url).then(e=>e.markdown())}}),ig.of({name:"TSX",extensions:["tsx"],load(){return Da(()=>Promise.resolve().then(()=>W6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),ig.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Da(()=>Promise.resolve().then(()=>W6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),ig.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Da(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>qHn(e.shell))}})];function HHn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function WHn(e){const t=HHn(e);return o1t({override:[ZHn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function ZHn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const GHn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,QHn=An.mark({class:"cm-variable-highlight"}),l9e=new wwt({regexp:GHn,decoration:()=>QHn}),YHn=Co.fromClass(class{decorations;constructor(e){this.decorations=l9e.createDeco(e)}update(e){this.decorations=l9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),KHn=YHn;function XHn(){const e=fI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[he.className,he.propertyName],color:"var(--neutral6)"},{tag:he.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[he.heading1,he.heading2,he.heading3,he.heading4,he.heading5,he.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:he.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:he.link,color:"var(--accent3)",textDecoration:"underline"},{tag:he.url,color:"var(--accent3)"},{tag:he.monospace,color:"var(--neutral6)"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:he.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=It.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function JHn(){const e=It.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Hg.define([{tag:[he.comment,he.bracket],color:"var(--neutral2)"},{tag:[he.string,he.meta,he.regexp],color:"var(--accent1)"},{tag:[he.atom,he.bool,he.special(he.variableName)],color:"var(--accent6)"},{tag:[he.keyword,he.operator,he.tagName],color:"var(--accent2)"},{tag:[he.function(he.propertyName),he.propertyName],color:"var(--accent5)"},{tag:[he.definition(he.variableName),he.function(he.variableName),he.className,he.attributeName],color:"var(--accent3)"},{tag:[he.variableName,he.number],color:"var(--accent5)"},{tag:[he.name,he.quote],color:"var(--accent1)"},{tag:he.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[he.heading1,he.heading2,he.heading3,he.heading4,he.heading5,he.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[he.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[he.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:he.link,color:"var(--accent3)",textDecoration:"underline"},{tag:he.url,color:"var(--accent3)"},{tag:he.monospace,color:"var(--neutral6)"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:[he.deleted],color:"var(--accent2)"},{tag:he.invalid,color:"var(--error)"},{tag:[he.standard(he.tagName)],color:"var(--accent1)"}]);return[e,eS(t)]}const a0=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?XHn():JHn(),[e])},eWn=co(X("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),tWn=th.highest(It.editorAttributes.of({style:"outline: none"})),nWn=th.highest(It.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),rWn=[tWn,nWn],Hr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=a0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const S=[...rWn];return f&&S.push(It.lineWrapping),a==="json"?S.push(Dp):a==="markdown"&&S.push(Mke({base:HO,codeLanguages:mkt})),i&&a==="markdown"&&S.push(KHn),c&&a==="markdown"&&S.push(WHn(c)),p===!1&&S.push(us.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:X(eWn({variant:h}),s),...m,children:[r&&o.jsx(za,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(Yu,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),sWn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},aWn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=a0(),{settings:r,setSettings:s}=gH(),a=r?.tracingOptions,i=g.useMemo(()=>sWn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(Yu,{value:l,onChange:d,theme:n,extensions:[Dp],className:X("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(le,{type:"button",onClick:f,children:"Save"})})]})},iWn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(qe,{children:o.jsx(oq,{})})})}),o.jsx(On,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Options"}),o.jsx(zs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Ir,{children:o.jsx(aWn,{onSaved:()=>t(!1)})})]})})]})};function oWn({status:e}){switch(e){case"running":return o.jsx(en,{});case"failed":return o.jsx(ws,{className:"text-accent2"});case"canceled":return o.jsx(Df,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(hj,{className:"text-neutral3"});case"suspended":return o.jsx(tq,{className:"text-accent3"});case"success":return o.jsx(da,{className:"text-accent1"});default:return o.jsx(hj,{className:"text-neutral3"})}}function gkt({status:e}){return o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(qe,{"aria-label":e,className:"shrink-0",children:o.jsx(oWn,{status:e})})}),o.jsx(On,{children:e})]})}var Uee,c9e;function Hke(){if(c9e)return Uee;c9e=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var p=f;p!==void 0;p=this.parent(p))if(p===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var p=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return Uee=r,Uee}var Vee,u9e;function lWn(){return u9e||(u9e=1,Vee="2.2.4"),Vee}var qee,d9e;function cWn(){return d9e||(d9e=1,qee={Graph:Hke(),version:lWn()}),qee}var Hee,f9e;function uWn(){if(f9e)return Hee;f9e=1;var e=Hke();Hee={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return Hee}var Wee,p9e;function dWn(){if(p9e)return Wee;p9e=1,Wee=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return Wee}var Zee,h9e;function vkt(){if(h9e)return Zee;h9e=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return Zee=e,Zee}var Gee,m9e;function ykt(){if(m9e)return Gee;m9e=1;var e=vkt();Gee=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return Gee}var Qee,g9e;function fWn(){if(g9e)return Qee;g9e=1;var e=ykt();Qee=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Qee}var Yee,v9e;function bkt(){if(v9e)return Yee;v9e=1,Yee=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return Yee}var Kee,y9e;function pWn(){if(y9e)return Kee;y9e=1;var e=bkt();Kee=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Kee}var Xee,b9e;function hWn(){if(b9e)return Xee;b9e=1,Xee=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return Xee}var Jee,x9e;function xkt(){if(x9e)return Jee;x9e=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return Jee=e,e.CycleException=t,Jee}var ete,w9e;function mWn(){if(w9e)return ete;w9e=1;var e=xkt();ete=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return ete}var tte,S9e;function wkt(){if(S9e)return tte;S9e=1,tte=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return tte}var nte,k9e;function gWn(){if(k9e)return nte;k9e=1;var e=wkt();nte=t;function t(n,r){return e(n,r,"post")}return nte}var rte,O9e;function vWn(){if(O9e)return rte;O9e=1;var e=wkt();rte=t;function t(n,r){return e(n,r,"pre")}return rte}var ste,_9e;function yWn(){if(_9e)return ste;_9e=1;var e=Hke(),t=vkt();ste=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return ste}var ate,C9e;function bWn(){return C9e||(C9e=1,ate={components:dWn(),dijkstra:ykt(),dijkstraAll:fWn(),findCycles:pWn(),floydWarshall:hWn(),isAcyclic:mWn(),postorder:gWn(),preorder:vWn(),prim:yWn(),tarjan:bkt(),topsort:xkt()}),ate}var ite,E9e;function Fg(){if(E9e)return ite;E9e=1;var e=cWn();return ite={Graph:e.Graph,json:uWn(),alg:bWn(),version:e.version},ite}var ote,T9e;function xWn(){if(T9e)return ote;T9e=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return ote=e,ote}var lte,j9e;function wWn(){if(j9e)return lte;j9e=1;let e=Fg().Graph,t=xWn();lte=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return lte}var cte,N9e;function Ml(){if(N9e)return cte;N9e=1;let e=Fg().Graph;cte={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:E};function t(T,N,I,A){for(var R=A;T.hasNode(R);)R=S(A);return I.dummy=N,T.setNode(R,I),R}function n(T){let N=new e().setGraph(T.graph());return T.nodes().forEach(I=>N.setNode(I,T.node(I))),T.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=T.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(T){let N=new e({multigraph:T.isMultigraph()}).setGraph(T.graph());return T.nodes().forEach(I=>{T.children(I).length||N.setNode(I,T.node(I))}),T.edges().forEach(I=>{N.setEdge(I,T.edge(I))}),N}function s(T){let N=T.nodes().map(I=>{let A={};return T.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function a(T){let N=T.nodes().map(I=>{let A={};return T.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function i(T,N){let I=T.x,A=T.y,R=N.x-I,L=N.y-A,D=T.width/2,F=T.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,B;return Math.abs(L)*D>Math.abs(R)*F?(L<0&&(F=-F),H=F*R/L,B=F):(R<0&&(D=-D),H=D,B=D*L/R),{x:I+H,y:A+B}}function l(T){let N=k(m(T)+1).map(()=>[]);return T.nodes().forEach(I=>{let A=T.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(T){let N=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);T.nodes().forEach(A=>{let R=T.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(T){let N=T.nodes().map(D=>T.node(D).rank),I=h(Math.min,N),A=[];T.nodes().forEach(D=>{let F=T.node(D).rank-I;A[F]||(A[F]=[]),A[F].push(D)});let R=0,L=T.graph().nodeRankFactor;Array.from(A).forEach((D,F)=>{D===void 0&&F%L!==0?--R:D!==void 0&&R&&D.forEach(H=>T.node(H).rank+=R)})}function d(T,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(T,"border",R,N)}function f(T,N=p){const I=[];for(let A=0;A<T.length;A+=N){const R=T.slice(A,A+N);I.push(R)}return I}const p=65535;function h(T,N){if(N.length>p){const I=f(N);return T.apply(null,I.map(A=>T.apply(null,A)))}else return T.apply(null,N)}function m(T){const I=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(T,N){let I={lhs:[],rhs:[]};return T.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(T,N){let I=Date.now();try{return N()}finally{console.log(T+" time: "+(Date.now()-I)+"ms")}}function b(T,N){return N()}let x=0;function S(T){var N=++x;return T+(""+N)}function k(T,N,I=1){N==null&&(N=T,T=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=T;A(L);L+=I)R.push(L);return R}function _(T,N){const I={};for(const A of N)T[A]!==void 0&&(I[A]=T[A]);return I}function C(T,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(T).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(T,N){return T.reduce((I,A,R)=>(I[A]=N[R],I),{})}return cte}var ute,I9e;function SWn(){if(I9e)return ute;I9e=1;let e=wWn(),t=Ml().uniqueId;ute={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return ute}var dte,A9e;function kWn(){if(A9e)return dte;A9e=1;let e=Ml();dte={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return dte}var fte,R9e;function PB(){if(R9e)return fte;R9e=1;const{applyWithChunking:e}=Ml();fte={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return fte}var pte,P9e;function Skt(){if(P9e)return pte;P9e=1;var e=Fg().Graph,t=PB().slack;pte=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return pte}var hte,$9e;function OWn(){if($9e)return hte;$9e=1;var e=Skt(),t=PB().slack,n=PB().longestPath,r=Fg().alg.preorder,s=Fg().alg.postorder,a=Ml().simplify;hte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,_;k=p(S);)_=h(S,x,k),m(S,x,k,_)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(x,S,_))}function c(x,S,k){var _=x.node(k),C=_.parent;x.edge(k,C).cutvalue=u(x,S,k)}function u(x,S,k){var _=x.node(k),C=_.parent,E=!0,T=S.edge(k,C),N=0;return T||(E=!1,T=S.edge(C,k)),N=T.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===E,D=S.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var F=x.edge(k,R).cutvalue;N+=L?-F:F}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,_,C){var E=k,T=x.node(_);return S[_]=!0,x.neighbors(_).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,_))}),T.low=E,T.lim=k++,C?T.parent=C:delete T.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var _=k.v,C=k.w;S.hasEdge(_,C)||(_=k.w,C=k.v);var E=x.node(_),T=x.node(C),N=E,I=!1;E.lim>T.lim&&(N=T,I=!0);var A=S.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(S,L)<t(S,R)?L:R)}function m(x,S,k,_){var C=k.v,E=k.w;x.removeEdge(C,E),x.setEdge(_.v,_.w,{}),d(x),l(x,S),v(x,S)}function v(x,S){var k=x.nodes().find(C=>!S.node(C).parent),_=r(x,k);_=_.slice(1),_.forEach(C=>{var E=x.node(C).parent,T=S.edge(C,E),N=!1;T||(T=S.edge(E,C),N=!0),S.node(C).rank=S.node(E).rank+(N?T.minlen:-T.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return hte}var mte,M9e;function _Wn(){if(M9e)return mte;M9e=1;var e=PB(),t=e.longestPath,n=Skt(),r=OWn();mte=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return mte}var gte,D9e;function CWn(){if(D9e)return gte;D9e=1,gte=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return gte}var vte,L9e;function EWn(){if(L9e)return vte;L9e=1;let e=Ml();vte={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,_=x.borderTop?u:2*u,C=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,v,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return vte}var yte,F9e;function TWn(){if(F9e)return yte;F9e=1;let e=Ml();yte=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return yte}var bte,z9e;function jWn(){if(z9e)return bte;z9e=1,bte={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return bte}var xte,B9e;function NWn(){if(B9e)return xte;B9e=1;let e=Ml();xte=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return xte}var wte,U9e;function IWn(){if(U9e)return wte;U9e=1;let e=Ml().zipObject;wte=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return wte}var Ste,V9e;function AWn(){if(V9e)return Ste;V9e=1,Ste=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return Ste}var kte,q9e;function RWn(){if(q9e)return kte;q9e=1;let e=Ml();kte=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return kte}var Ote,H9e;function PWn(){if(H9e)return Ote;H9e=1;let e=Ml();Ote=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return Ote}var _te,W9e;function $Wn(){if(W9e)return _te;W9e=1;let e=AWn(),t=RWn(),n=PWn();_te=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(x=>x!==p&&x!==h));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return _te}var Cte,Z9e;function MWn(){if(Z9e)return Cte;Z9e=1;let e=Fg().Graph,t=Ml();Cte=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return Cte}var Ete,G9e;function DWn(){if(G9e)return Ete;G9e=1,Ete=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return Ete}var Tte,Q9e;function LWn(){if(Q9e)return Tte;Q9e=1;let e=NWn(),t=IWn(),n=$Wn(),r=MWn(),s=DWn(),a=Fg().Graph,i=Ml();Tte=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:v,S%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,x=Object.assign({},y),b=_)}d(f,x)}function c(f,p,h){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return Tte}var jte,Y9e;function FWn(){if(Y9e)return jte;Y9e=1;let e=Fg().Graph,t=Ml();jte={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let x={};function S(k,_){let C=0,E=0,T=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:T;(R||I===N)&&(_.slice(E,A+1).forEach(D=>{y.predecessors(D).forEach(F=>{let H=y.node(F),B=H.order;(B<C||L<B)&&!(H.dummy&&y.node(D).dummy)&&a(x,F,D)})}),E=A+1,C=L)}),_}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(_,C,E,T,N){let I;t.range(C,E).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<T||L.order>N)&&a(x,R,I)})})}function k(_,C){let E=-1,T,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(T=y.node(R[0]).order,S(C,N,A,E,T),N=A,E=T)}S(C,N,C.length,T,_.length)}),C}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},_={},C={};return b.forEach(E=>{E.forEach((T,N)=>{k[T]=T,_[T]=T,C[T]=N})}),b.forEach(E=>{let T=-1;E.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>C[R]-C[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];_[N]===N&&T<C[D]&&!i(x,N,D)&&(_[D]=N,_[N]=k[N]=k[D],T=C[D])}}})}),{root:k,align:_}}function c(y,b,x,S,k){let _={},C=u(y,b,x,k),E=k?"borderLeft":"borderRight";function T(A,R){let L=C.nodes(),D=L.pop(),F={};for(;D;)F[D]?A(D):(F[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){_[A]=C.inEdges(A).reduce((R,L)=>Math.max(R,_[L.v]+C.edge(L)),0)}function I(A){let R=C.outEdges(A).reduce((D,F)=>Math.min(D,_[F.w]-C.edge(F)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(_[A]=Math.max(_[A],R))}return T(N,C.predecessors.bind(C)),T(I,C.successors.bind(C)),Object.keys(S).forEach(A=>_[A]=_[x[A]]),_}function u(y,b,x,S){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,S);return b.forEach(E=>{let T;E.forEach(N=>{let I=x[N];if(k.setNode(I),T){var A=x[T],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,T),R||0))}T=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([E,T])=>{let N=v(y,E)/2;k=Math.max(T+N,k),_=Math.min(T-N,_)});const C=k-_;return C<x[0]&&(x=[C,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let E=_+C,T=y[E];if(T===b)return;let N=Object.values(T),I=S-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(T,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(_=>_[S]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let T=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,T),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),S[C+E]=I})});let _=d(y,S);return f(S,_),p(S,y.graph().align)}function m(y,b,x){return(S,k,_)=>{let C=S.node(k),E=S.node(_),T=0,N;if(T+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":N=-C.width/2;break;case"r":N=C.width/2;break}if(N&&(T+=x?N:-N),N=0,T+=(C.dummy?b:y)/2,T+=(E.dummy?b:y)/2,T+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(T+=x?N:-N),N=0,T}}function v(y,b){return y.node(b).width}return jte}var Nte,K9e;function zWn(){if(K9e)return Nte;K9e=1;let e=Ml(),t=FWn().positionX;Nte=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Nte}var Ite,X9e;function BWn(){if(X9e)return Ite;X9e=1;let e=SWn(),t=kWn(),n=_Wn(),r=Ml().normalizeRanks,s=CWn(),a=Ml().removeEmptyRanks,i=EWn(),l=TWn(),c=jWn(),u=LWn(),d=zWn(),f=Ml(),p=Fg().Graph;Ite=h;function h($,z){let Z=z&&z.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>T($));Z(" runLayout",()=>m(K,Z,z)),Z(" updateInputGraph",()=>v($,K))})}function m($,z,Z){z(" makeSpaceForEdgeLabels",()=>N($)),z(" removeSelfEdges",()=>U($)),z(" acyclic",()=>e.run($)),z(" nestingGraph.run",()=>i.run($)),z(" rank",()=>n(f.asNonCompoundGraph($))),z(" injectEdgeLabelProxies",()=>I($)),z(" removeEmptyRanks",()=>a($)),z(" nestingGraph.cleanup",()=>i.cleanup($)),z(" normalizeRanks",()=>r($)),z(" assignRankMinMax",()=>A($)),z(" removeEdgeLabelProxies",()=>R($)),z(" normalize.run",()=>t.run($)),z(" parentDummyChains",()=>s($)),z(" addBorderSegments",()=>l($)),z(" order",()=>u($,Z)),z(" insertSelfEdges",()=>V($)),z(" adjustCoordinateSystem",()=>c.adjust($)),z(" position",()=>d($)),z(" positionSelfEdges",()=>M($)),z(" removeBorderNodes",()=>B($)),z(" normalize.undo",()=>t.undo($)),z(" fixupEdgeLabelCoords",()=>F($)),z(" undoCoordinateSystem",()=>c.undo($)),z(" translateGraph",()=>L($)),z(" assignNodeIntersects",()=>D($)),z(" reversePoints",()=>H($)),z(" acyclic.undo",()=>e.undo($))}function v($,z){$.nodes().forEach(Z=>{let K=$.node(Z),ne=z.node(Z);K&&(K.x=ne.x,K.y=ne.y,K.rank=ne.rank,z.children(Z).length&&(K.width=ne.width,K.height=ne.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),ne=z.edge(Z);K.points=ne.points,Object.hasOwn(ne,"x")&&(K.x=ne.x,K.y=ne.y)}),$.graph().width=z.graph().width,$.graph().height=z.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],S=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function T($){let z=new p({multigraph:!0,compound:!0}),Z=q($.graph());return z.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(K=>{let ne=q($.node(K));const ee=G(ne,S);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),z.setNode(K,ee),z.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let ne=q($.edge(K));z.setEdge(K,Object.assign({},C,G(ne,_),f.pick(ne,E)))}),z}function N($){let z=$.graph();z.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(z.rankdir==="TB"||z.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(z=>{let Z=$.edge(z);if(Z.width&&Z.height){let K=$.node(z.v),ee={rank:($.node(z.w).rank-K.rank)/2+K.rank,e:z};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let z=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,z=Math.max(z,K.maxRank))}),$.graph().maxRank=z}function R($){$.nodes().forEach(z=>{let Z=$.node(z);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(z))})}function L($){let z=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,ne=0,ee=$.graph(),J=ee.marginx||0,ae=ee.marginy||0;function pe(Y){let te=Y.x,ue=Y.y,fe=Y.width,ce=Y.height;z=Math.min(z,te-fe/2),Z=Math.max(Z,te+fe/2),K=Math.min(K,ue-ce/2),ne=Math.max(ne,ue+ce/2)}$.nodes().forEach(Y=>pe($.node(Y))),$.edges().forEach(Y=>{let te=$.edge(Y);Object.hasOwn(te,"x")&&pe(te)}),z-=J,K-=ae,$.nodes().forEach(Y=>{let te=$.node(Y);te.x-=z,te.y-=K}),$.edges().forEach(Y=>{let te=$.edge(Y);te.points.forEach(ue=>{ue.x-=z,ue.y-=K}),Object.hasOwn(te,"x")&&(te.x-=z),Object.hasOwn(te,"y")&&(te.y-=K)}),ee.width=Z-z+J,ee.height=ne-K+ae}function D($){$.edges().forEach(z=>{let Z=$.edge(z),K=$.node(z.v),ne=$.node(z.w),ee,J;Z.points?(ee=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],ee=ne,J=K),Z.points.unshift(f.intersectRect(K,ee)),Z.points.push(f.intersectRect(ne,J))})}function F($){$.edges().forEach(z=>{let Z=$.edge(z);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(z=>{let Z=$.edge(z);Z.reversed&&Z.points.reverse()})}function B($){$.nodes().forEach(z=>{if($.children(z).length){let Z=$.node(z),K=$.node(Z.borderTop),ne=$.node(Z.borderBottom),ee=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-ee.x),Z.height=Math.abs(ne.y-K.y),Z.x=ee.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(z=>{$.node(z).dummy==="border"&&$.removeNode(z)})}function U($){$.edges().forEach(z=>{if(z.v===z.w){var Z=$.node(z.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:z,label:$.edge(z)}),$.removeEdge(z)}})}function V($){var z=f.buildLayerMatrix($);z.forEach(Z=>{var K=0;Z.forEach((ne,ee)=>{var J=$.node(ne);J.order=ee+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:ee+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function M($){$.nodes().forEach(z=>{var Z=$.node(z);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),ne=K.x+K.width/2,ee=K.y,J=Z.x-ne,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(z),Z.label.points=[{x:ne+2*J/3,y:ee-ae},{x:ne+5*J/6,y:ee-ae},{x:ne+J,y:ee},{x:ne+5*J/6,y:ee+ae},{x:ne+2*J/3,y:ee+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,z){return f.mapValues(f.pick($,z),Number)}function q($){var z={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),z[Z]=K}),z}return Ite}var Ate,J9e;function UWn(){if(J9e)return Ate;J9e=1;let e=Ml(),t=Fg().Graph;Ate={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return Ate}var Rte,e7e;function VWn(){return e7e||(e7e=1,Rte="1.1.8"),Rte}var Pte,t7e;function qWn(){return t7e||(t7e=1,Pte={graphlib:Fg(),layout:BWn(),debug:UWn(),util:{time:Ml().time,notime:Ml().notime},version:VWn()}),Pte}var HWn=qWn();const n7e=Bl(HWn);function Hl(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Hl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var WWn={value:()=>{}};function VH(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new j8(n)}function j8(e){this._=e}function ZWn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}j8.prototype=VH.prototype={constructor:j8,on:function(e,t){var n=this._,r=ZWn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=GWn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=r7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=r7e(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new j8(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function GWn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function r7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=WWn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Uge="http://www.w3.org/1999/xhtml";const s7e={svg:"http://www.w3.org/2000/svg",xhtml:Uge,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function qH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),s7e.hasOwnProperty(t)?{space:s7e[t],local:e}:e}function QWn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Uge&&t.documentElement.namespaceURI===Uge?t.createElement(e):t.createElementNS(n,e)}}function YWn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function kkt(e){var t=qH(e);return(t.local?YWn:QWn)(t)}function KWn(){}function Wke(e){return e==null?KWn:function(){return this.querySelector(e)}}function XWn(e){typeof e!="function"&&(e=Wke(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Yp(r,this._parents)}function JWn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function eZn(){return[]}function Okt(e){return e==null?eZn:function(){return this.querySelectorAll(e)}}function tZn(e){return function(){return JWn(e.apply(this,arguments))}}function nZn(e){typeof e=="function"?e=tZn(e):e=Okt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new Yp(r,s)}function _kt(e){return function(){return this.matches(e)}}function Ckt(e){return function(t){return t.matches(e)}}var rZn=Array.prototype.find;function sZn(e){return function(){return rZn.call(this.children,e)}}function aZn(){return this.firstElementChild}function iZn(e){return this.select(e==null?aZn:sZn(typeof e=="function"?e:Ckt(e)))}var oZn=Array.prototype.filter;function lZn(){return Array.from(this.children)}function cZn(e){return function(){return oZn.call(this.children,e)}}function uZn(e){return this.selectAll(e==null?lZn:cZn(typeof e=="function"?e:Ckt(e)))}function dZn(e){typeof e!="function"&&(e=_kt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Yp(r,this._parents)}function Ekt(e){return new Array(e.length)}function fZn(){return new Yp(this._enter||this._groups.map(Ekt),this._parents)}function $B(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}$B.prototype={constructor:$B,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function pZn(e){return function(){return e}}function hZn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new $B(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function mZn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new $B(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function gZn(e){return e.__data__}function vZn(e,t){if(!arguments.length)return Array.from(this,gZn);var n=t?mZn:hZn,r=this._parents,s=this._groups;typeof e!="function"&&(e=pZn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],p=f.length,h=yZn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var x=0,S=0,k,_;x<m;++x)if(k=v[x]){for(x>=S&&(S=x+1);!(_=y[S])&&++S<m;);k._next=_||null}}return i=new Yp(i,r),i._enter=l,i._exit=c,i}function yZn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function bZn(){return new Yp(this._exit||this._groups.map(Ekt),this._parents)}function xZn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function wZn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Yp(l,this._parents)}function SZn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function kZn(e){e||(e=OZn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Yp(s,this._parents).order()}function OZn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function _Zn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function CZn(){return Array.from(this)}function EZn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function TZn(){let e=0;for(const t of this)++e;return e}function jZn(){return!this.node()}function NZn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function IZn(e){return function(){this.removeAttribute(e)}}function AZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function RZn(e,t){return function(){this.setAttribute(e,t)}}function PZn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function $Zn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function MZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function DZn(e,t){var n=qH(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?AZn:IZn:typeof t=="function"?n.local?MZn:$Zn:n.local?PZn:RZn)(n,t))}function Tkt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function LZn(e){return function(){this.style.removeProperty(e)}}function FZn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function zZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function BZn(e,t,n){return arguments.length>1?this.each((t==null?LZn:typeof t=="function"?zZn:FZn)(e,t,n??"")):Vj(this.node(),e)}function Vj(e,t){return e.style.getPropertyValue(t)||Tkt(e).getComputedStyle(e,null).getPropertyValue(t)}function UZn(e){return function(){delete this[e]}}function VZn(e,t){return function(){this[e]=t}}function qZn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function HZn(e,t){return arguments.length>1?this.each((t==null?UZn:typeof t=="function"?qZn:VZn)(e,t)):this.node()[e]}function jkt(e){return e.trim().split(/^|\s+/)}function Zke(e){return e.classList||new Nkt(e)}function Nkt(e){this._node=e,this._names=jkt(e.getAttribute("class")||"")}Nkt.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function Ikt(e,t){for(var n=Zke(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function Akt(e,t){for(var n=Zke(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function WZn(e){return function(){Ikt(this,e)}}function ZZn(e){return function(){Akt(this,e)}}function GZn(e,t){return function(){(t.apply(this,arguments)?Ikt:Akt)(this,e)}}function QZn(e,t){var n=jkt(e+"");if(arguments.length<2){for(var r=Zke(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?GZn:t?WZn:ZZn)(n,t))}function YZn(){this.textContent=""}function KZn(e){return function(){this.textContent=e}}function XZn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function JZn(e){return arguments.length?this.each(e==null?YZn:(typeof e=="function"?XZn:KZn)(e)):this.node().textContent}function eGn(){this.innerHTML=""}function tGn(e){return function(){this.innerHTML=e}}function nGn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function rGn(e){return arguments.length?this.each(e==null?eGn:(typeof e=="function"?nGn:tGn)(e)):this.node().innerHTML}function sGn(){this.nextSibling&&this.parentNode.appendChild(this)}function aGn(){return this.each(sGn)}function iGn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function oGn(){return this.each(iGn)}function lGn(e){var t=typeof e=="function"?e:kkt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function cGn(){return null}function uGn(e,t){var n=typeof e=="function"?e:kkt(e),r=t==null?cGn:typeof t=="function"?t:Wke(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function dGn(){var e=this.parentNode;e&&e.removeChild(this)}function fGn(){return this.each(dGn)}function pGn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function hGn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function mGn(e){return this.select(e?hGn:pGn)}function gGn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function vGn(e){return function(t){e.call(this,t,this.__data__)}}function yGn(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function bGn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function xGn(e,t,n){return function(){var r=this.__on,s,a=vGn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function wGn(e,t,n){var r=yGn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?xGn:bGn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function Rkt(e,t,n){var r=Tkt(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function SGn(e,t){return function(){return Rkt(this,e,t)}}function kGn(e,t){return function(){return Rkt(this,e,t.apply(this,arguments))}}function OGn(e,t){return this.each((typeof t=="function"?kGn:SGn)(e,t))}function*_Gn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var Pkt=[null];function Yp(e,t){this._groups=e,this._parents=t}function P3(){return new Yp([[document.documentElement]],Pkt)}function CGn(){return this}Yp.prototype=P3.prototype={constructor:Yp,select:XWn,selectAll:nZn,selectChild:iZn,selectChildren:uZn,filter:dZn,data:vZn,enter:fZn,exit:bZn,join:xZn,merge:wZn,selection:CGn,order:SZn,sort:kZn,call:_Zn,nodes:CZn,node:EZn,size:TZn,empty:jZn,each:NZn,attr:DZn,style:BZn,property:HZn,classed:QZn,text:JZn,html:rGn,raise:aGn,lower:oGn,append:lGn,insert:uGn,remove:fGn,clone:mGn,datum:gGn,on:wGn,dispatch:OGn,[Symbol.iterator]:_Gn};function Ep(e){return typeof e=="string"?new Yp([[document.querySelector(e)]],[document.documentElement]):new Yp([[e]],Pkt)}function EGn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function og(e,t){if(e=EGn(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const TGn={passive:!1},wM={capture:!0,passive:!1};function $te(e){e.stopImmediatePropagation()}function GT(e){e.preventDefault(),e.stopImmediatePropagation()}function $kt(e){var t=e.document.documentElement,n=Ep(e).on("dragstart.drag",GT,wM);"onselectstart"in t?n.on("selectstart.drag",GT,wM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Mkt(e,t){var n=e.document.documentElement,r=Ep(e).on("dragstart.drag",null);t&&(r.on("click.drag",GT,wM),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const K6=e=>()=>e;function Vge(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Vge.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function jGn(e){return!e.ctrlKey&&!e.button}function NGn(){return this.parentNode}function IGn(e,t){return t??{x:e.x,y:e.y}}function AGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function Dkt(){var e=jGn,t=NGn,n=IGn,r=AGn,s={},a=VH("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,TGn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=S(this,t.call(this,k,_),k,_,"mouse");C&&(Ep(k.view).on("mousemove.drag",m,wM).on("mouseup.drag",v,wM),$kt(k.view),$te(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(GT(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Ep(k.view).on("mousemove.drag mouseup.drag",null),Mkt(k.view,u),GT(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,E=t.call(this,k,_),T=C.length,N,I;for(N=0;N<T;++N)(I=S(this,E,k,_,C[N].identifier,C[N]))&&($te(k),I("start",k,C[N]))}}function b(k){var _=k.changedTouches,C=_.length,E,T;for(E=0;E<C;++E)(T=s[_[E].identifier])&&(GT(k),T("drag",k,_[E]))}function x(k){var _=k.changedTouches,C=_.length,E,T;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<C;++E)(T=s[_[E].identifier])&&($te(k),T("end",k,_[E]))}function S(k,_,C,E,T,N){var I=a.copy(),A=og(N||C,_),R,L,D;if((D=n.call(k,new Vge("beforestart",{sourceEvent:C,target:p,identifier:T,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function F(H,B,U){var V=A,M;switch(H){case"start":s[T]=F,M=i++;break;case"end":delete s[T],--i;case"drag":A=og(U||B,_),M=i;break}I.call(H,k,new Vge(H,{sourceEvent:B,subject:D,target:p,identifier:T,active:M,x:A[0]+R,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),E)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:K6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:K6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:K6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:K6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function Gke(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Lkt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function $3(){}var SM=.7,MB=1/SM,QT="\\s*([+-]?\\d+)\\s*",kM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",sy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",RGn=/^#([0-9a-f]{3,8})$/,PGn=new RegExp(`^rgb\\(${QT},${QT},${QT}\\)$`),$Gn=new RegExp(`^rgb\\(${sy},${sy},${sy}\\)$`),MGn=new RegExp(`^rgba\\(${QT},${QT},${QT},${kM}\\)$`),DGn=new RegExp(`^rgba\\(${sy},${sy},${sy},${kM}\\)$`),LGn=new RegExp(`^hsl\\(${kM},${sy},${sy}\\)$`),FGn=new RegExp(`^hsla\\(${kM},${sy},${sy},${kM}\\)$`),a7e={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Gke($3,ZO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:i7e,formatHex:i7e,formatHex8:zGn,formatHsl:BGn,formatRgb:o7e,toString:o7e});function i7e(){return this.rgb().formatHex()}function zGn(){return this.rgb().formatHex8()}function BGn(){return Fkt(this).formatHsl()}function o7e(){return this.rgb().formatRgb()}function ZO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=RGn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?l7e(t):n===3?new xf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?X6(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?X6(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=PGn.exec(e))?new xf(t[1],t[2],t[3],1):(t=$Gn.exec(e))?new xf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=MGn.exec(e))?X6(t[1],t[2],t[3],t[4]):(t=DGn.exec(e))?X6(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=LGn.exec(e))?d7e(t[1],t[2]/100,t[3]/100,1):(t=FGn.exec(e))?d7e(t[1],t[2]/100,t[3]/100,t[4]):a7e.hasOwnProperty(e)?l7e(a7e[e]):e==="transparent"?new xf(NaN,NaN,NaN,0):null}function l7e(e){return new xf(e>>16&255,e>>8&255,e&255,1)}function X6(e,t,n,r){return r<=0&&(e=t=n=NaN),new xf(e,t,n,r)}function UGn(e){return e instanceof $3||(e=ZO(e)),e?(e=e.rgb(),new xf(e.r,e.g,e.b,e.opacity)):new xf}function qge(e,t,n,r){return arguments.length===1?UGn(e):new xf(e,t,n,r??1)}function xf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Gke(xf,qge,Lkt($3,{brighter(e){return e=e==null?MB:Math.pow(MB,e),new xf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?SM:Math.pow(SM,e),new xf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new xf(rO(this.r),rO(this.g),rO(this.b),DB(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:c7e,formatHex:c7e,formatHex8:VGn,formatRgb:u7e,toString:u7e}));function c7e(){return`#${Fk(this.r)}${Fk(this.g)}${Fk(this.b)}`}function VGn(){return`#${Fk(this.r)}${Fk(this.g)}${Fk(this.b)}${Fk((isNaN(this.opacity)?1:this.opacity)*255)}`}function u7e(){const e=DB(this.opacity);return`${e===1?"rgb(":"rgba("}${rO(this.r)}, ${rO(this.g)}, ${rO(this.b)}${e===1?")":`, ${e})`}`}function DB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function rO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Fk(e){return e=rO(e),(e<16?"0":"")+e.toString(16)}function d7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new hg(e,t,n,r)}function Fkt(e){if(e instanceof hg)return new hg(e.h,e.s,e.l,e.opacity);if(e instanceof $3||(e=ZO(e)),!e)return new hg;if(e instanceof hg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new hg(i,l,c,e.opacity)}function qGn(e,t,n,r){return arguments.length===1?Fkt(e):new hg(e,t,n,r??1)}function hg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Gke(hg,qGn,Lkt($3,{brighter(e){return e=e==null?MB:Math.pow(MB,e),new hg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?SM:Math.pow(SM,e),new hg(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new xf(Mte(e>=240?e-240:e+120,s,r),Mte(e,s,r),Mte(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new hg(f7e(this.h),J6(this.s),J6(this.l),DB(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=DB(this.opacity);return`${e===1?"hsl(":"hsla("}${f7e(this.h)}, ${J6(this.s)*100}%, ${J6(this.l)*100}%${e===1?")":`, ${e})`}`}}));function f7e(e){return e=(e||0)%360,e<0?e+360:e}function J6(e){return Math.max(0,Math.min(1,e||0))}function Mte(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const Qke=e=>()=>e;function HGn(e,t){return function(n){return e+n*t}}function WGn(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function ZGn(e){return(e=+e)==1?zkt:function(t,n){return n-t?WGn(t,n,e):Qke(isNaN(t)?n:t)}}function zkt(e,t){var n=t-e;return n?HGn(e,n):Qke(isNaN(e)?t:e)}const LB=(function e(t){var n=ZGn(t);function r(s,a){var i=n((s=qge(s)).r,(a=qge(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=zkt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function GGn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function QGn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function YGn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=px(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function KGn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function cg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function XGn(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=px(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Hge=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Dte=new RegExp(Hge.source,"g");function JGn(e){return function(){return e}}function eQn(e){return function(t){return e(t)+""}}function Bkt(e,t){var n=Hge.lastIndex=Dte.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Hge.exec(e))&&(s=Dte.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:cg(r,s)})),n=Dte.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?eQn(c[0].x):JGn(t):(t=c.length,function(u){for(var d=0,f;d<t;++d)l[(f=c[d]).i]=f.x(u);return l.join("")})}function px(e,t){var n=typeof t,r;return t==null||n==="boolean"?Qke(t):(n==="number"?cg:n==="string"?(r=ZO(t))?(t=r,LB):Bkt:t instanceof ZO?LB:t instanceof Date?KGn:QGn(t)?GGn:Array.isArray(t)?YGn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?XGn:cg)(e,t)}function Yke(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var p7e=180/Math.PI,Wge={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Ukt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*p7e,skewX:Math.atan(c)*p7e,scaleX:i,scaleY:l}}var eF;function tQn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Wge:Ukt(t.a,t.b,t.c,t.d,t.e,t.f)}function nQn(e){return e==null||(eF||(eF=document.createElementNS("http://www.w3.org/2000/svg","g")),eF.setAttribute("transform",e),!(e=eF.transform.baseVal.consolidate()))?Wge:(e=e.matrix,Ukt(e.a,e.b,e.c,e.d,e.e,e.f))}function Vkt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:cg(u,f)},{i:v-2,x:cg(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:cg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:cg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:cg(u,f)},{i:v-2,x:cg(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var rQn=Vkt(tQn,"px, ","px)","deg)"),sQn=Vkt(nQn,", ",")",")"),aQn=1e-12;function h7e(e){return((e=Math.exp(e))+1/e)/2}function iQn(e){return((e=Math.exp(e))-1/e)/2}function oQn(e){return((e=Math.exp(2*e))-1)/(e+1)}const N8=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<aQn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var x=Math.sqrt(v),S=(p*p-u*u+r*v)/(2*u*n*x),k=(p*p-u*u-r*v)/(2*p*n*x),_=Math.log(Math.sqrt(S*S+1)-S),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(E){var T=E*b,N=h7e(_),I=u/(n*x)*(N*oQn(t*T+_)-iQn(_));return[l+I*h,c+I*m,u*N/h7e(t*T+_)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function lQn(e,t){t===void 0&&(t=e,e=px);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var qj=0,zP=0,kR=0,qkt=1e3,FB,BP,zB=0,GO=0,HH=0,OM=typeof performance=="object"&&performance.now?performance:Date,Hkt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Kke(){return GO||(Hkt(cQn),GO=OM.now()+HH)}function cQn(){GO=0}function BB(){this._call=this._time=this._next=null}BB.prototype=Wkt.prototype={constructor:BB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Kke():+n)+(t==null?0:+t),!this._next&&BP!==this&&(BP?BP._next=this:FB=this,BP=this),this._call=e,this._time=n,Zge()},stop:function(){this._call&&(this._call=null,this._time=1/0,Zge())}};function Wkt(e,t,n){var r=new BB;return r.restart(e,t,n),r}function uQn(){Kke(),++qj;for(var e=FB,t;e;)(t=GO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--qj}function m7e(){GO=(zB=OM.now())+HH,qj=zP=0;try{uQn()}finally{qj=0,fQn(),GO=0}}function dQn(){var e=OM.now(),t=e-zB;t>qkt&&(HH-=t,zB=e)}function fQn(){for(var e,t=FB,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:FB=n);BP=e,Zge(r)}function Zge(e){if(!qj){zP&&(zP=clearTimeout(zP));var t=e-GO;t>24?(e<1/0&&(zP=setTimeout(m7e,e-OM.now()-HH)),kR&&(kR=clearInterval(kR))):(kR||(zB=OM.now(),kR=setInterval(dQn,qkt)),qj=1,Hkt(m7e))}}function g7e(e,t,n){var r=new BB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var pQn=VH("start","end","cancel","interrupt"),hQn=[],Zkt=0,v7e=1,Gge=2,I8=3,y7e=4,Qge=5,A8=6;function WH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;mQn(e,n,{name:t,index:r,group:s,on:pQn,tween:hQn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:Zkt})}function Xke(e,t){var n=Gg(e,t);if(n.state>Zkt)throw new Error("too late; already scheduled");return n}function By(e,t){var n=Gg(e,t);if(n.state>I8)throw new Error("too late; already running");return n}function Gg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function mQn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=Wkt(a,0,n.time);function a(u){n.state=v7e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==v7e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===I8)return g7e(i);h.state===y7e?(h.state=A8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=A8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(g7e(function(){n.state===I8&&(n.state=y7e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Gge,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Gge){for(n.state=I8,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=Qge,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===Qge&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=A8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function R8(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Gge&&r.state<Qge,r.state=A8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function gQn(e){return this.each(function(){R8(this,e)})}function vQn(e,t){var n,r;return function(){var s=By(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function yQn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=By(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function bQn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Gg(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?vQn:yQn)(n,e,t))}function Jke(e,t,n){var r=e._id;return e.each(function(){var s=By(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Gg(s,r).value[t]}}function Gkt(e,t){var n;return(typeof t=="number"?cg:t instanceof ZO?LB:(n=ZO(t))?(t=n,LB):Bkt)(e,t)}function xQn(e){return function(){this.removeAttribute(e)}}function wQn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function SQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function kQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function OQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function _Qn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function CQn(e,t){var n=qH(e),r=n==="transform"?sQn:Gkt;return this.attrTween(e,typeof t=="function"?(n.local?_Qn:OQn)(n,r,Jke(this,"attr."+e,t)):t==null?(n.local?wQn:xQn)(n):(n.local?kQn:SQn)(n,r,t))}function EQn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function TQn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function jQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&TQn(e,a)),n}return s._value=t,s}function NQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&EQn(e,a)),n}return s._value=t,s}function IQn(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=qH(e);return this.tween(n,(r.local?jQn:NQn)(r,t))}function AQn(e,t){return function(){Xke(this,e).delay=+t.apply(this,arguments)}}function RQn(e,t){return t=+t,function(){Xke(this,e).delay=t}}function PQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?AQn:RQn)(t,e)):Gg(this.node(),t).delay}function $Qn(e,t){return function(){By(this,e).duration=+t.apply(this,arguments)}}function MQn(e,t){return t=+t,function(){By(this,e).duration=t}}function DQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?$Qn:MQn)(t,e)):Gg(this.node(),t).duration}function LQn(e,t){if(typeof t!="function")throw new Error;return function(){By(this,e).ease=t}}function FQn(e){var t=this._id;return arguments.length?this.each(LQn(t,e)):Gg(this.node(),t).ease}function zQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;By(this,e).ease=n}}function BQn(e){if(typeof e!="function")throw new Error;return this.each(zQn(this._id,e))}function UQn(e){typeof e!="function"&&(e=_kt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Mx(r,this._parents,this._name,this._id)}function VQn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new Mx(i,this._parents,this._name,this._id)}function qQn(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function HQn(e,t,n){var r,s,a=qQn(t)?Xke:By;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function WQn(e,t){var n=this._id;return arguments.length<2?Gg(this.node(),n).on.on(e):this.each(HQn(n,e,t))}function ZQn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function GQn(){return this.on("end.remove",ZQn(this._id))}function QQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Wke(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,WH(u[p],t,n,p,u,Gg(d,n)));return new Mx(a,this._parents,t,n)}function YQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Okt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=Gg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&WH(h,t,n,v,p,m);a.push(p),i.push(d)}return new Mx(a,i,t,n)}var KQn=P3.prototype.constructor;function XQn(){return new KQn(this._groups,this._parents)}function JQn(e,t){var n,r,s;return function(){var a=Vj(this,e),i=(this.style.removeProperty(e),Vj(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function Qkt(e){return function(){this.style.removeProperty(e)}}function eYn(e,t,n){var r,s=n+"",a;return function(){var i=Vj(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function tYn(e,t,n){var r,s,a;return function(){var i=Vj(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),Vj(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function nYn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=By(this,e),u=c.on,d=c.value[a]==null?l||(l=Qkt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function rYn(e,t,n){var r=(e+="")=="transform"?rQn:Gkt;return t==null?this.styleTween(e,JQn(e,r)).on("end.style."+e,Qkt(e)):typeof t=="function"?this.styleTween(e,tYn(e,r,Jke(this,"style."+e,t))).each(nYn(this._id,e)):this.styleTween(e,eYn(e,r,t),n).on("end.style."+e,null)}function sYn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function aYn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&sYn(e,i,n)),r}return a._value=t,a}function iYn(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,aYn(e,t,n??""))}function oYn(e){return function(){this.textContent=e}}function lYn(e){return function(){var t=e(this);this.textContent=t??""}}function cYn(e){return this.tween("text",typeof e=="function"?lYn(Jke(this,"text",e)):oYn(e==null?"":e+""))}function uYn(e){return function(t){this.textContent=e.call(this,t)}}function dYn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&uYn(s)),t}return r._value=e,r}function fYn(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,dYn(e))}function pYn(){for(var e=this._name,t=this._id,n=Ykt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=Gg(c,t);WH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Mx(r,this._parents,e,n)}function hYn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=By(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var mYn=0;function Mx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Ykt(){return++mYn}var xb=P3.prototype;Mx.prototype={constructor:Mx,select:QQn,selectAll:YQn,selectChild:xb.selectChild,selectChildren:xb.selectChildren,filter:UQn,merge:VQn,selection:XQn,transition:pYn,call:xb.call,nodes:xb.nodes,node:xb.node,size:xb.size,empty:xb.empty,each:xb.each,on:WQn,attr:CQn,attrTween:IQn,style:rYn,styleTween:iYn,text:cYn,textTween:fYn,remove:GQn,tween:bQn,delay:PQn,duration:DQn,ease:FQn,easeVarying:BQn,end:hYn,[Symbol.iterator]:xb[Symbol.iterator]};function gYn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var vYn={time:null,delay:0,duration:250,ease:gYn};function yYn(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function bYn(e){var t,n;e instanceof Mx?(t=e._id,e=e._name):(t=Ykt(),(n=vYn).time=Kke(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&WH(c,e,t,u,i,n||yYn(c,t));return new Mx(r,this._parents,e,t)}P3.prototype.interrupt=gQn;P3.prototype.transition=bYn;const tF=e=>()=>e;function xYn(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function tx(e,t,n){this.k=e,this.x=t,this.y=n}tx.prototype={constructor:tx,scale:function(e){return e===1?this:new tx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new tx(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var ZH=new tx(1,0,0);Kkt.prototype=tx.prototype;function Kkt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return ZH;return e.__zoom}function Lte(e){e.stopImmediatePropagation()}function OR(e){e.preventDefault(),e.stopImmediatePropagation()}function wYn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function SYn(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function b7e(){return this.__zoom||ZH}function kYn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function OYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function _Yn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function Xkt(){var e=wYn,t=SYn,n=_Yn,r=kYn,s=OYn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=N8,u=VH("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(D){D.property("__zoom",b7e).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,F,H,B){var U=D.selection?D.selection():D;U.property("__zoom",b7e),D!==U?_(D,F,H,B):U.interrupt().each(function(){C(this,arguments).event(B).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},b.scaleBy=function(D,F,H,B){b.scaleTo(D,function(){var U=this.__zoom.k,V=typeof F=="function"?F.apply(this,arguments):F;return U*V},H,B)},b.scaleTo=function(D,F,H,B){b.transform(D,function(){var U=t.apply(this,arguments),V=this.__zoom,M=H==null?k(U):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),q=typeof F=="function"?F.apply(this,arguments):F;return n(S(x(V,q),M,G),U,i)},H,B)},b.translateBy=function(D,F,H,B){b.transform(D,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,B)},b.translateTo=function(D,F,H,B,U){b.transform(D,function(){var V=t.apply(this,arguments),M=this.__zoom,G=B==null?k(V):typeof B=="function"?B.apply(this,arguments):B;return n(ZH.translate(G[0],G[1]).scale(M.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},B,U)};function x(D,F){return F=Math.max(a[0],Math.min(a[1],F)),F===D.k?D:new tx(F,D.x,D.y)}function S(D,F,H){var B=F[0]-H[0]*D.k,U=F[1]-H[1]*D.k;return B===D.x&&U===D.y?D:new tx(D.k,B,U)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,F,H,B){D.on("start.zoom",function(){C(this,arguments).event(B).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(B).end()}).tween("zoom",function(){var U=this,V=arguments,M=C(U,V).event(B),G=t.apply(U,V),q=H==null?k(G):typeof H=="function"?H.apply(U,V):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),z=U.__zoom,Z=typeof F=="function"?F.apply(U,V):F,K=c(z.invert(q).concat($/z.k),Z.invert(q).concat($/Z.k));return function(ne){if(ne===1)ne=Z;else{var ee=K(ne),J=$/ee[2];ne=new tx(J,q[0]-ee[0]*J,q[1]-ee[1]*J)}M.zoom(null,ne)}})}function C(D,F,H){return!H&&D.__zooming||new E(D,F)}function E(D,F){this.that=D,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,F),this.taps=0}E.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,F){return this.mouse&&D!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var F=Ep(this.that).datum();u.call(D,this.that,new xYn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),F)}};function T(D,...F){if(!e.apply(this,arguments))return;var H=C(this,F).event(D),B=this.__zoom,U=Math.max(a[0],Math.min(a[1],B.k*Math.pow(2,r.apply(this,arguments)))),V=og(D);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=B.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(B.k===U)return;H.mouse=[V,B.invert(V)],R8(this),H.start()}OR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(B,U),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...F){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,B=C(this,F,!0).event(D),U=Ep(D.view).on("mousemove.zoom",q,!0).on("mouseup.zoom",$,!0),V=og(D,H),M=D.clientX,G=D.clientY;$kt(D.view),Lte(D),B.mouse=[V,this.__zoom.invert(V)],R8(this),B.start();function q(z){if(OR(z),!B.moved){var Z=z.clientX-M,K=z.clientY-G;B.moved=Z*Z+K*K>v}B.event(z).zoom("mouse",n(S(B.that.__zoom,B.mouse[0]=og(z,H),B.mouse[1]),B.extent,i))}function $(z){U.on("mousemove.zoom mouseup.zoom",null),Mkt(z.view,B.moved),OR(z),B.event(z).end()}}function I(D,...F){if(e.apply(this,arguments)){var H=this.__zoom,B=og(D.changedTouches?D.changedTouches[0]:D,this),U=H.invert(B),V=H.k*(D.shiftKey?.5:2),M=n(S(x(H,V),B,U),t.apply(this,F),i);OR(D),l>0?Ep(this).transition().duration(l).call(_,M,B,D):Ep(this).call(b.transform,M,B,D)}}function A(D,...F){if(e.apply(this,arguments)){var H=D.touches,B=H.length,U=C(this,F,D.changedTouches.length===B).event(D),V,M,G,q;for(Lte(D),M=0;M<B;++M)G=H[M],q=og(G,this),q=[q,this.__zoom.invert(q),G.identifier],U.touch0?!U.touch1&&U.touch0[2]!==q[2]&&(U.touch1=q,U.taps=0):(U.touch0=q,V=!0,U.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(U.taps<2&&(f=q[0],d=setTimeout(function(){d=null},h)),R8(this),U.start())}}function R(D,...F){if(this.__zooming){var H=C(this,F).event(D),B=D.changedTouches,U=B.length,V,M,G,q;for(OR(D),V=0;V<U;++V)M=B[V],G=og(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],z=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],ne=(ne=Z[0]-$[0])*ne+(ne=Z[1]-$[1])*ne,ee=(ee=K[0]-z[0])*ee+(ee=K[1]-z[1])*ee;M=x(M,Math.sqrt(ne/ee)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],q=[(z[0]+K[0])/2,(z[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],q=H.touch0[1];else return;H.zoom("touch",n(S(M,G,q),H.extent,i))}}function L(D,...F){if(this.__zooming){var H=C(this,F).event(D),B=D.changedTouches,U=B.length,V,M;for(Lte(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),V=0;V<U;++V)M=B[V],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=og(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Ep(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:tF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:tF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:tF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:tF([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const wy={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},_M=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Jkt=["Enter"," ","Escape"],eOt={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var Hj;(function(e){e.Strict="strict",e.Loose="loose"})(Hj||(Hj={}));var sO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(sO||(sO={}));var CM;(function(e){e.Partial="partial",e.Full="full"})(CM||(CM={}));const tOt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var kw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(kw||(kw={}));var EM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(EM||(EM={}));var sr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(sr||(sr={}));const x7e={[sr.Left]:sr.Right,[sr.Right]:sr.Left,[sr.Top]:sr.Bottom,[sr.Bottom]:sr.Top};function nOt(e){return e===null?null:e?"valid":"invalid"}const rOt=e=>"id"in e&&"source"in e&&"target"in e,CYn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),eOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),M3=(e,t=[0,0])=>{const{width:n,height:r}=i0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},EYn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):eOe(s)?s:t.nodeLookup.get(s.id));const l=i?UB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return GH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return QH(n)},D3=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=GH(n,UB(s)),r=!0)}),r?QH(n):{x:0,y:0,width:0,height:0}},tOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...F3(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=TM(l,Zj(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},TYn=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function jYn(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function NYn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=jYn(e,i),c=D3(l),u=nOe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function sOt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",wy.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&Gj(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=Gj(f)?QO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",wy.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function IYn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=TYn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const Wj=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),QO=(e={x:0,y:0},t,n)=>({x:Wj(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Wj(e.y,t[0][1],t[1][1]-(n?.height??0))});function aOt(e,t,n){const{width:r,height:s}=i0(n),{x:a,y:i}=n.internals.positionAbsolute;return QO(e,[[a,i],[a+r,i+s]],t)}const w7e=(e,t,n)=>e<t?Wj(Math.abs(e-t),1,t)/t:e>n?-Wj(Math.abs(e-n),1,t)/t:0,iOt=(e,t,n=15,r=40)=>{const s=w7e(e.x,r,t.width-r)*n,a=w7e(e.y,r,t.height-r)*n;return[s,a]},GH=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Yge=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),QH=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Zj=(e,t=[0,0])=>{const{x:n,y:r}=eOe(e)?e.internals.positionAbsolute:M3(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},UB=(e,t=[0,0])=>{const{x:n,y:r}=eOe(e)?e.internals.positionAbsolute:M3(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},oOt=(e,t)=>QH(GH(Yge(e),Yge(t))),TM=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},S7e=e=>xg(e.width)&&xg(e.height)&&xg(e.x)&&xg(e.y),xg=e=>!isNaN(e)&&isFinite(e),AYn=(e,t)=>{},L3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),F3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?L3(l,i):l},VB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function uE(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function RYn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=uE(e,n),s=uE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=uE(e.top??e.y??0,n),s=uE(e.bottom??e.y??0,n),a=uE(e.left??e.x??0,t),i=uE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function PYn(e,t,n,r,s,a){const{x:i,y:l}=VB(e,[t,n,r]),{x:c,y:u}=VB({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const nOe=(e,t,n,r,s,a)=>{const i=RYn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=Wj(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=PYn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},jM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function Gj(e){return e!=null&&e!=="parent"}function i0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function lOt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function cOt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function k7e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function $Yn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function MYn(e){return{...eOt,...e||{}}}function S2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=wg(e),l=F3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?L3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const rOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),uOt=e=>e?.getRootNode?.()||window?.document,DYn=["INPUT","SELECT","TEXTAREA"];function dOt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:DYn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const fOt=e=>"clientX"in e,wg=(e,t)=>{const n=fOt(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},O7e=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...rOe(i)}})};function pOt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function nF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function _7e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case sr.Left:return[t-nF(t-r,a),n];case sr.Right:return[t+nF(r-t,a),n];case sr.Top:return[t,n-nF(n-s,a)];case sr.Bottom:return[t,n+nF(s-n,a)]}}function sOe({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,curvature:i=.25}){const[l,c]=_7e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=_7e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=pOt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,p,h,m]}function hOt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function LYn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function FYn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=GH(UB(e),UB(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return TM(i,QH(a))>0}const zYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,BYn=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),UYn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||zYn;let s;return rOt(e)?s={...e}:s={...e,id:r(e)},BYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function mOt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=hOt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const C7e={[sr.Left]:{x:-1,y:0},[sr.Right]:{x:1,y:0},[sr.Top]:{x:0,y:-1},[sr.Bottom]:{x:0,y:1}},VYn=({source:e,sourcePosition:t=sr.Bottom,target:n})=>t===sr.Left||t===sr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},E7e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function qYn({source:e,sourcePosition:t=sr.Bottom,target:n,targetPosition:r=sr.Top,center:s,offset:a,stepPosition:i}){const l=C7e[t],c=C7e[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=VYn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=hOt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const T=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?T:N:m=p==="x"?N:T}else{const T=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:T:m=l.y===h?T:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const F=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*F:x[p]=(d[p]>n[p]?-1:1)*F}}if(t!==r){const D=p==="x"?"y":"x",F=l[p]===c[D],H=u[D]>d[D],B=u[D]<d[D];(l[p]===1&&(!F&&H||F&&B)||l[p]!==1&&(!F&&B||F&&H))&&(m=p==="x"?T:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+x.x,y:d.y+x.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],v,y,S,k]}function HYn(e,t,n,r){const s=Math.min(E7e(e,t)/2,E7e(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Kge({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=qYn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=HYn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function T7e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function WYn(e){const{sourceNode:t,targetNode:n}=e;if(!T7e(t)||!T7e(n))return null;const r=t.internals.handleBounds||j7e(t.handles),s=n.internals.handleBounds||j7e(n.handles),a=N7e(r?.source??[],e.sourceHandle),i=N7e(e.connectionMode===Hj.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",wy.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||sr.Bottom,c=i?.position||sr.Top,u=YO(t,a,l),d=YO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function j7e(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function YO(e,t,n=sr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??i0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case sr.Top:return{x:s+i/2,y:a};case sr.Right:return{x:s+i,y:a+l/2};case sr.Bottom:return{x:s+i/2,y:a+l};case sr.Left:return{x:s,y:a+l/2}}}function N7e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Xge(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function ZYn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=Xge(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const gOt=1e3,GYn=10,aOe={nodeOrigin:[0,0],nodeExtent:_M,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},QYn={...aOe,checkEquality:!0};function iOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function YYn(e,t,n){const r=iOe(aOe,n);for(const s of e.values())if(s.parentId)lOe(s,e,t,r);else{const a=M3(s,r.nodeOrigin),i=Gj(s.extent)?s.extent:r.nodeExtent,l=QO(a,i,i0(s));s.internals.positionAbsolute=l}}function KYn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function oOe(e){return e==="manual"}function Jge(e,t,n,r={}){const s=iOe(QYn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!oOe(s.zIndexMode)?gOt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const p=M3(d,s.nodeOrigin),h=Gj(d.extent)?d.extent:s.nodeExtent,m=QO(p,h,i0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:KYn(d,f),z:vOt(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&lOe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function XYn(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function lOe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=iOe(aOe,r),u=e.parentId,d=t.get(u);if(!d){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}XYn(e,n),s&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++s.i,d.internals.z=d.internals.z+s.i*GYn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!oOe(c)?gOt:0,{x:p,y:h,z:m}=JYn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function vOt(e,t,n){const r=xg(e.zIndex)?e.zIndex:0;return oOe(n)?r:r+(e.selected?t:0)}function JYn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=i0(e),u=M3(e,n),d=Gj(e.extent)?QO(u,e.extent,c):u;let f=QO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=aOt(f,c,t));const p=vOt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function cOe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??Zj(l),u=oOt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=i0(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function eKn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=rOe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=Gj(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=aOt(k,v,t.get(m.parentId)):S&&(k=QO(k,S,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:O7e("source",h.nodeElement,x,f,m.id),target:O7e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&lOe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:Zj(_,s)}))}}if(p.length>0){const h=cOe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function tKn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function I7e(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function yOt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;I7e("source",c,d,e,s,i),I7e("target",c,u,e,a,l),t.set(r.id,r)}}function bOt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:bOt(n,t):!1}function A7e(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function nKn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!bOt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Fte({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function rKn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=L3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function sKn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,p=null,h=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:E=0}){p=Ep(k);function T({x:R,y:L}){const{nodeLookup:D,nodeExtent:F,snapGrid:H,snapToGrid:B,nodeOrigin:U,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:q}=t();a={x:R,y:L};let $=!1;const z=l.size>1,Z=z&&F?Yge(D3(l)):null,K=z&&B?rKn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[ne,ee]of l){if(!D.has(ne))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};B&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:L3(J,H));let ae=null;if(z&&F&&!ee.extent&&Z){const{positionAbsolute:te}=ee.internals,ue=te.x-Z.x+F[0][0],fe=te.x+ee.measured.width-Z.x2+F[1][0],ce=te.y-Z.y+F[0][1],me=te.y+ee.measured.height-Z.y2+F[1][1];ae=[[ue,ce],[fe,me]]}const{position:pe,positionAbsolute:Y}=sOt({nodeId:ne,nextPosition:J,nodeLookup:D,nodeExtent:ae||F,nodeOrigin:U,onError:G});$=$||ee.position.x!==pe.x||ee.position.y!==pe.y,ee.position=pe,ee.internals.positionAbsolute=Y}if(m=m||$,!!$&&(q(l,!0),v&&(r||V||!C&&M))){const[ne,ee]=Fte({nodeId:C,dragItems:l,nodeLookup:D});r?.(v,l,ne,ee),V?.(v,ne,ee),C||M?.(v,ee)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:F}=t();if(!F){c=!1,cancelAnimationFrame(i);return}const[H,B]=iOt(u,d,D);(H!==0||B!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-B/R[2],await L({x:H,y:B})&&T(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:F,transform:H,snapGrid:B,snapToGrid:U,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:q}=t();f=!0,(!V||!_)&&!D&&C&&(L.get(C)?.selected||q()),_&&V&&C&&e?.(C);const $=S2(R.sourceEvent,{transform:H,snapGrid:B,snapToGrid:U,containerBounds:d});if(a=$,l=nKn(L,F,$,C),l.size>0&&(n||M||!C&&G)){const[z,Z]=Fte({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,z,Z),M?.(R.sourceEvent,z,Z),C||G?.(R.sourceEvent,Z)}}const A=Dkt().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:F,snapGrid:H,snapToGrid:B}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,D===0&&I(R),a=S2(R.sourceEvent,{transform:F,snapGrid:H,snapToGrid:B,containerBounds:d}),u=wg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:F,snapToGrid:H,nodeDragThreshold:B,nodeLookup:U}=t(),V=S2(R.sourceEvent,{transform:D,snapGrid:F,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!U.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=wg(R.sourceEvent,d),G=M.x-u.x,q=M.y-u.y;Math.sqrt(G*G+q*q)>B&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=wg(R.sourceEvent,d),T(V))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:F,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||F||!C&&H){const[B,U]=Fte({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,B,U),F?.(R.sourceEvent,B,U),C||H?.(R.sourceEvent,U)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!A7e(L,`.${x}`,k))&&(!S||A7e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function aKn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())TM(s,Zj(a))>0&&r.push(a);return r}const iKn=250;function oKn(e,t,n,r){let s=[],a=1/0;const i=aKn(e,n,t+iKn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=YO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function xOt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...YO(i,c,c.position,!0)}:c}function wOt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function lKn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const SOt=()=>!0;function cKn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=SOt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:E=1,handleDomNode:T}){const N=uOt(e.target);let I=0,A;const{x:R,y:L}=wg(e),D=wOt(a,T),F=l?.getBoundingClientRect();let H=!1;if(!F||!D)return;const B=xOt(s,D,r,c,t);if(!B)return;let U=wg(e,F),V=!1,M=null,G=!1,q=null;function $(){if(!d||!F)return;const[pe,Y]=iOt(U,F,C);p({x:pe,y:Y}),I=requestAnimationFrame($)}const z={...B,nodeId:s,type:D,position:B.position},Z=c.get(s);let ne={inProgress:!0,isValid:null,from:YO(Z,z,sr.Left,!0),fromHandle:z,fromPosition:z.position,fromNode:Z,to:U,toHandle:null,toPosition:x7e[z.position],toNode:null,pointer:U};function ee(){H=!0,S(ne),m?.(e,{nodeId:s,handleId:r,handleType:D})}E===0&&ee();function J(pe){if(!H){const{x:me,y:be}=wg(pe),we=me-R,Oe=be-L;if(!(we*we+Oe*Oe>E*E))return;ee()}if(!_()||!z){ae(pe);return}const Y=k();U=wg(pe,F),A=oKn(F3(U,Y,!1,[1,1]),n,c,z),V||($(),V=!0);const te=kOt(pe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});q=te.handleDomNode,M=te.connection,G=lKn(!!A,te.isValid);const ue=c.get(s),fe=ue?YO(ue,z,sr.Left,!0):ne.from,ce={...ne,from:fe,isValid:G,to:te.toHandle&&G?VB({x:te.toHandle.x,y:te.toHandle.y},Y):U,toHandle:te.toHandle,toPosition:G&&te.toHandle?te.toHandle.position:x7e[z.position],toNode:te.toHandle?c.get(te.toHandle.nodeId):null,pointer:U};S(ce),ne=ce}function ae(pe){if(!("touches"in pe&&pe.touches.length>0)){if(H){(A||q)&&M&&G&&v?.(M);const{inProgress:Y,...te}=ne,ue={...te,toPosition:ne.toHandle?ne.toPosition:null};y?.(pe,ue),a&&x?.(pe,ue)}h(),cancelAnimationFrame(I),V=!1,G=!1,M=null,q=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",J),N.addEventListener("touchend",ae)}function kOt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=SOt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=wg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=wOt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!S||!x)return b;const E={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=E;const N=_&&C&&(n===Hj.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(E),b.toHandle=xOt(S,x,k,d,n,!0)}return b}const eve={onPointerDown:cKn,isValid:kOt};function uKn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Ep(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=S.sourceEvent.ctrlKey&&jM()?10:1,C=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,C*_);t.scaleTo(E)};let v=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(v=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const _=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),T={x:k[0]-C[0]*E,y:k[1]-C[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:T.x,y:T.y,zoom:k[2]},N,l)},x=Xkt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:og}}const YH=e=>({x:e.x,y:e.y,zoom:e.k}),zte=({x:e,y:t,zoom:n})=>ZH.translate(e,t).scale(n),dT=(e,t)=>e.target.closest(`.${t}`),OOt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),dKn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Bte=(e,t=0,n=dKn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},_Ot=e=>{const t=e.ctrlKey&&jM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function fKn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(dT(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=og(d),b=_Ot(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===sO.Vertical?0:d.deltaX*p,m=s===sO.Horizontal?0:d.deltaY*p;!jM()&&d.shiftKey&&s!==sO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=YH(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function pKn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=dT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function hKn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=YH(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function mKn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&OOt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,YH(a.transform))}}function gKn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&OOt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=YH(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function vKn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(dT(f,`${u}-flow__node`)||dT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||dT(f,l)&&m||dT(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function yKn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=Xkt().scaleExtent([t,n]).translateExtent(r),p=Ep(e).call(f);x({x:s.x,y:s.y,zoom:Wj(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(_Ot);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?px:N8).transform(Bte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:F,panOnDrag:H,panOnScrollMode:B,panOnScrollSpeed:U,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:q,zoomActivationKeyPressed:$,lib:z,onTransformChange:Z,connectionInProgress:K,paneClickDistance:ne,selectionOnDrag:ee}){D&&!u.isZoomingOrPanning&&b();const J=F&&!$&&!D;f.clickDistance(ee?1/0:!xg(ne)||ne<0?0:ne);const ae=J?fKn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:B,panOnScrollSpeed:U,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):pKn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=hKn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const te=mKn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",te);const ue=gKn({zoomPanValues:u,panOnDrag:H,panOnScroll:F,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",ue)}const pe=vKn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:F,zoomOnDoubleClick:q,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:z,connectionInProgress:K});f.filter(pe),q?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=zte(A),F=f?.constrain()(D,R,L);return F&&await v(F),new Promise(H=>H(F))}async function S(A,R){const L=zte(A);return await v(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=zte(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function _(){const A=p?Kkt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?px:N8).scaleTo(Bte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?px:N8).scaleBy(Bte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!xg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:E,setScaleExtent:T,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var Qj;(function(e){e.Line="line",e.Handle="handle"})(Qj||(Qj={}));function bKn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function R7e(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function J0(e,t){return Math.max(0,t-e)}function ew(e,t){return Math.max(0,e-t)}function rF(e,t,n){return Math.max(0,t-e,e-n)}function P7e(e,t){return e?!t:t}function xKn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:_,height:C,aspectRatio:E}=e;let T=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-T:T),A=C+(u?-N:N),R=-a[0]*_,L=-a[1]*C;let D=rF(I,v,y),F=rF(A,b,x);if(i){let U=0,V=0;c&&T<0?U=J0(S+T+R,i[0][0]):!c&&T>0&&(U=ew(S+I+R,i[1][0])),u&&N<0?V=J0(k+N+L,i[0][1]):!u&&N>0&&(V=ew(k+A+L,i[1][1])),D=Math.max(D,U),F=Math.max(F,V)}if(l){let U=0,V=0;c&&T>0?U=ew(S+T,l[0][0]):!c&&T<0&&(U=J0(S+I,l[1][0])),u&&N>0?V=ew(k+N,l[0][1]):!u&&N<0&&(V=J0(k+A,l[1][1])),D=Math.max(D,U),F=Math.max(F,V)}if(s){if(d){const U=rF(I/E,b,x)*E;if(D=Math.max(D,U),i){let V=0;!c&&!u||c&&!u&&p?V=ew(k+L+I/E,i[1][1])*E:V=J0(k+L+(c?T:-T)/E,i[0][1])*E,D=Math.max(D,V)}if(l){let V=0;!c&&!u||c&&!u&&p?V=J0(k+I/E,l[1][1])*E:V=ew(k+(c?T:-T)/E,l[0][1])*E,D=Math.max(D,V)}}if(f){const U=rF(A*E,v,y)/E;if(F=Math.max(F,U),i){let V=0;!c&&!u||u&&!c&&p?V=ew(S+A*E+R,i[1][0])/E:V=J0(S+(u?N:-N)*E+R,i[0][0])/E,F=Math.max(F,V)}if(l){let V=0;!c&&!u||u&&!c&&p?V=J0(S+A*E,l[1][0])/E:V=ew(S+(u?N:-N)*E,l[0][0])/E,F=Math.max(F,V)}}}N=N+(N<0?F:-F),T=T+(T<0?D:-D),s&&(p?I>A*E?N=(P7e(c,u)?-T:T)/E:T=(P7e(c,u)?-N:N)*E:d?(N=T/E,u=c):(T=N*E,c=u));const H=c?S+T:S,B=u?k+N:k;return{width:_+(c?-T:T),height:C+(u?-N:N),x:a[0]*T*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+B}}const COt={width:0,height:0,x:0,y:0},wKn={...COt,pointerX:0,pointerY:0,aspectRatio:1};function SKn(e){return[[0,0],[e.measured.width,e.measured.height]]}function kKn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function OKn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Ep(e);let i={controlDirection:R7e("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...COt},x={...wKn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:R7e(u)};let S,k=null,_=[],C,E,T,N=!1;const I=Dkt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:F,nodeOrigin:H,paneDomNode:B}=n();if(S=R.get(t),!S)return;k=B?.getBoundingClientRect()??null;const{xSnapped:U,ySnapped:V}=S2(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:F,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:U,pointerY:V,aspectRatio:b.width/b.height},C=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(C=R.get(S.parentId),E=C&&S.extent==="parent"?SKn(C):void 0),_=[],T=void 0;for(const[M,G]of R)if(G.parentId===t&&(_.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const q=kKn(G,S,G.origin??H);T?T=[[Math.min(q[0][0],T[0][0]),Math.min(q[0][1],T[0][1])],[Math.max(q[1][0],T[1][0]),Math.max(q[1][1],T[1][1])]]:T=q}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:F}=n(),H=S2(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),B=[];if(!S)return;const{x:U,y:V,width:M,height:G}=b,q={},$=S.origin??F,{width:z,height:Z,x:K,y:ne}=xKn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,T),ee=z!==M,J=Z!==G,ae=K!==U&&ee,pe=ne!==V&&J;if(!ae&&!pe&&!ee&&!J)return;if((ae||pe||$[0]===1||$[1]===1)&&(q.x=ae?K:b.x,q.y=pe?ne:b.y,b.x=q.x,b.y=q.y,_.length>0)){const fe=K-U,ce=ne-V;for(const me of _)me.position={x:me.position.x-fe+$[0]*(z-M),y:me.position.y-ce+$[1]*(Z-G)},B.push(me)}if((ee||J)&&(q.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?z:b.width,q.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=q.width,b.height=q.height),C&&S.expandParent){const fe=$[0]*(q.width??0);q.x&&q.x<fe&&(b.x=fe,x.x=x.x-(q.x-fe));const ce=$[1]*(q.height??0);q.y&&q.y<ce&&(b.y=ce,x.y=x.y-(q.y-ce))}const Y=bKn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...b,direction:Y};y?.(A,te)!==!1&&(N=!0,m?.(A,te),r(q,B))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const _Kn={},$7e=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(_Kn?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},u=t=e(r,s,c);return c},CKn=e=>e?$7e(e):$7e,{useDebugValue:EKn}=ze,{useSyncExternalStoreWithSelector:TKn}=mEn,jKn=e=>e;function EOt(e,t=jKn,n){const r=TKn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return EKn(r),r}const M7e=(e,t)=>{const n=CKn(e),r=(s,a=t)=>EOt(n,s,a);return Object.assign(r,n),r},NKn=(e,t)=>e?M7e(e,t):M7e;function io(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const KH=g.createContext(null),IKn=KH.Provider,TOt=wy.error001();function Us(e,t){const n=g.useContext(KH);if(n===null)throw new Error(TOt);return EOt(n,e,t)}function To(){const e=g.useContext(KH);if(e===null)throw new Error(TOt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const D7e={display:"none"},AKn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},jOt="react-flow__node-desc",NOt="react-flow__edge-desc",RKn="react-flow__aria-live",PKn=e=>e.ariaLiveMessage,$Kn=e=>e.ariaLabelConfig;function MKn({rfId:e}){const t=Us(PKn);return o.jsx("div",{id:`${RKn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:AKn,children:t})}function DKn({rfId:e,disableKeyboardA11y:t}){const n=Us($Kn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${jOt}-${e}`,style:D7e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${NOt}-${e}`,style:D7e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(MKn,{rfId:e})]})}const z3=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Hl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});z3.displayName="Panel";function LKn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(z3,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const FKn=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},sF=e=>e.id;function zKn(e,t){return io(e.selectedNodes.map(sF),t.selectedNodes.map(sF))&&io(e.selectedEdges.map(sF),t.selectedEdges.map(sF))}function BKn({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Us(FKn,zKn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const UKn=e=>!!e.onSelectionChangeHandlers;function VKn({onSelectionChange:e}){const t=Us(UKn);return e||t?o.jsx(BKn,{onSelectionChange:e}):null}const tve=typeof window<"u"?g.useLayoutEffect:g.useEffect,IOt=[0,0],qKn={x:0,y:0,zoom:1},HKn=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],L7e=[...HKn,"rfId"],WKn=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),F7e={translateExtent:_M,nodeOrigin:IOt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function ZKn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Us(WKn,io),u=To();tve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=F7e,l()}),[]);const d=g.useRef(F7e);return tve(()=>{for(const f of L7e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:MYn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},L7e.map(f=>e[f])),null}function z7e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function GKn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=z7e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:z7e()?.matches?"dark":"light"}const B7e=typeof document<"u"?document:null;function NM(e=null,t={target:B7e,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
235
235
|
`).replace(`
|
|
236
236
|
|
|
237
237
|
`,`
|
|
@@ -639,7 +639,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
|
|
|
639
639
|
}
|
|
640
640
|
]`})]})]})}function mps({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border-accent2/30 rounded-md border p-3",children:[o.jsxs("div",{className:"text-accent2 mb-2 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(_f,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function gps({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[p,h]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=Uds(),{batchInsertItems:b}=Ii(),x=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),S=g.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&Fe.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),_=g.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),C=i&&i.items.length>0&&i.errors.length===0,E=()=>{switch(s){case"upload":return o.jsx(hps,{onFileSelect:x,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(mps,{errors:i.errors}),o.jsx("div",{className:"text-neutral4 text-sm",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-neutral4 text-sm",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(pps,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(en,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},T=()=>{switch(s){case"upload":return o.jsx(le,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(le,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(le,{variant:"primary",onClick:S,disabled:!C,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(le,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(vr,{open:t,onOpenChange:_,children:o.jsxs(yr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(br,{children:[o.jsx(hr,{children:N[s]}),o.jsx(zs,{children:"Import dataset items from a JSON file."})]}),o.jsx(Ir,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:E()}),o.jsx(sc,{className:"flex justify-end gap-2 px-6 pt-4",children:T()})]})})}const EAe=e=>{const t=Ze(),{data:n}=OD(e),r=n?.experiments;return gt({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:l.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},vps=e=>{const t=Ze(),{data:n}=OD(e),r=n?.experiments;return gt({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:l.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function yps(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function nVt({datasetId:e,experimentId:t,featuredItemId:n}){const r=Ze(),{data:s}=r0(e),{data:a,isLoading:i}=EAe(e),{data:l,isLoading:c}=vps(e),u=g.useMemo(()=>t?(a??[]).filter(je=>je.experimentId===t):a,[a,t]),d=g.useMemo(()=>t?(l??[]).filter(je=>je.experimentId===t):l,[l,t]),{updateExperimentResult:f}=Ii(),[p,h]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,v]=g.useState(null),[y,b]=g.useState(new Set),[x,S]=g.useState(!1),[k,_]=g.useState(!1),[C,E]=g.useState(!1),[T,N]=g.useState(""),[I,A]=g.useState(""),[R,L]=g.useState(""),[D,F]=g.useState([]),[H,B]=g.useState(!1),[U,V]=g.useState(null),M=g.useMemo(()=>U??u??[],[U,u]);g.useEffect(()=>{V(null)},[e,t]),g.useEffect(()=>{u&&U===null&&V(u)},[u,U]);const G=g.useMemo(()=>{const je=new Set;if(s?.tags)for(const Ee of s.tags)je.add(Ee);for(const Ee of M)for(const _e of Ee.tags)je.add(_e);return[...je].sort()},[s,M]),q=g.useCallback(je=>{!s||!e||(s.tags??[]).includes(je)},[s,e]),$=g.useMemo(()=>m?m==="__untagged__"?M.filter(je=>je.tags.length===0):M.filter(je=>je.tags.includes(m)):M,[M,m]),z=g.useMemo(()=>{const je=new Map;for(const Ee of M)for(const _e of Ee.tags)je.set(_e,(je.get(_e)??0)+1);return[...je.entries()].sort((Ee,_e)=>_e[1]-Ee[1])},[M]),Z=g.useMemo(()=>M.filter(je=>je.tags.length===0).length,[M]),K=g.useMemo(()=>{let je=0;return m&&je++,x&&je++,je},[m,x]),ne=g.useCallback((je,Ee)=>{V(Ie=>(Ie??[]).map($e=>$e.id===je?{...$e,tags:Ee}:$e));const _e=M.find(Ie=>Ie.id===je);_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,tags:Ee})},[M,f]),ee=g.useCallback((je,Ee)=>{const _e=M.find(Ie=>Ie.id===je);_e?.traceId&&Ee!==void 0&&r.createFeedback({feedback:{traceId:_e.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:Ee==="positive"?1:-1,experimentId:_e.experimentId??void 0,sourceId:_e.id}}).catch(()=>{}),V(Ie=>(Ie??[]).map($e=>$e.id===je?{...$e,rating:Ee}:$e))},[M,r]),J=g.useCallback((je,Ee)=>{const _e=M.find(Ie=>Ie.id===je);_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,comment:Ee}),_e?.traceId&&r.createFeedback({feedback:{traceId:_e.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:Ee,comment:Ee,experimentId:_e.experimentId??void 0,sourceId:_e.id}}).catch(()=>{}),V(Ie=>(Ie??[]).map($e=>$e.id===je?{...$e,comment:Ee}:$e))},[M,r,f]),ae=g.useCallback(je=>{const Ee=M.find(_e=>_e.id===je);V(_e=>(_e??[]).filter(Ie=>Ie.id!==je)),b(_e=>{const Ie=new Set(_e);return Ie.delete(je),Ie}),p===je&&h(null),Ee?.experimentId&&Ee?.datasetId&&f.mutate({datasetId:Ee.datasetId,experimentId:Ee.experimentId,resultId:Ee.id,status:null})},[M,f,p]),pe=g.useCallback(je=>{const Ee=M.find(_e=>_e.id===je);V(_e=>(_e??[]).filter(Ie=>Ie.id!==je)),b(_e=>{const Ie=new Set(_e);return Ie.delete(je),Ie}),p===je&&h(null),Ee?.experimentId&&Ee?.datasetId&&f.mutate({datasetId:Ee.datasetId,experimentId:Ee.experimentId,resultId:Ee.id,status:"complete"})},[M,f,p]),Y=g.useMemo(()=>{const je=x?d??[]:$;return!x||!m?je:m==="__untagged__"?je.filter(Ee=>Ee.tags.length===0):je.filter(Ee=>Ee.tags.includes(m))},[x,d,$,m]),te=x?c:!1,ue=g.useMemo(()=>new Set(Y.map(je=>je.id)),[Y]),fe=g.useMemo(()=>[...y].filter(je=>ue.has(je)).length,[y,ue]),ce=Y.length>0&&fe===Y.length,me=fe>0&&!ce,be=g.useCallback(je=>{b(Ee=>{const _e=new Set(Ee);return _e.has(je)?_e.delete(je):_e.add(je),_e})},[]),we=g.useCallback(()=>{b(ce?new Set:new Set(Y.map(je=>je.id)))},[ce,Y]),Oe=g.useCallback(je=>{for(const Ee of y){const _e=M.find(Ie=>Ie.id===Ee);_e&&!_e.tags.includes(je)&&ne(Ee,[..._e.tags,je])}},[M,y,ne]),ke=g.useCallback(je=>{for(const Ee of y){const _e=M.find(Ie=>Ie.id===Ee);_e&&_e.tags.includes(je)&&ne(Ee,_e.tags.filter(Ie=>Ie!==je))}},[M,y,ne]),Ne=g.useCallback(()=>{for(const je of y)pe(je);b(new Set)},[y,pe]),Pe=g.useCallback(()=>{for(const je of y)ae(je);b(new Set)},[y,ae]),ie=g.useCallback(()=>{N(""),E(!0)},[]),re=g.useCallback(async()=>{if(!(!I||!R)){_(!0),E(!1);try{const je=M.filter(_e=>y.has(_e.id));if(je.length===0){_(!1);return}const Ee=await r.clusterFailures({modelId:`${I}/${R}`,items:je.map(_e=>({id:_e.id,input:_e.input,output:_e.output??void 0,error:typeof _e.error=="string"?_e.error:_e.error?String(_e.error):void 0,scores:_e.scores,existingTags:_e.tags.length>0?_e.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:T||void 0});Ee.proposedTags&&Ee.proposedTags.length>0&&(F(Ee.proposedTags.map(_e=>({..._e,accepted:!0}))),B(!0))}catch(je){console.error("Analysis failed:",je)}finally{_(!1)}}},[I,R,M,y,r,G,T]),se=g.useCallback(()=>{for(const je of D){if(!je.accepted)continue;const Ee=M.find(_e=>_e.id===je.itemId);if(Ee){const _e=[...new Set([...Ee.tags,...je.tags])];ne(Ee.id,_e)}}B(!1)},[D,M,ne]),de=g.useCallback(je=>{h(Ee=>Ee===je?null:je)},[]),xe=g.useMemo(()=>p?Y.find(je=>je.id===p)??null:null,[p,Y]),Ce=p?Y.findIndex(je=>je.id===p):-1,Re=Ce>0?()=>h(Y[Ce-1].id):void 0,Me=Ce>=0&&Ce<Y.length-1?()=>h(Y[Ce+1].id):void 0,We="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(en,{className:"h-6 w-6"})}):o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[o.jsx(vr,{open:C,onOpenChange:E,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Analyze Items"}),o.jsx(zs,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Lt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(qy,{value:I,onValueChange:A})]}),o.jsxs("div",{children:[o.jsx(Lt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Hy,{llmId:I,value:R,onValueChange:L})]})]}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:[y.size," item",y.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Lt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx($l,{value:T,onChange:je=>N(je.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(sc,{children:[o.jsx(le,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),o.jsxs(le,{onClick:re,disabled:!I||!R||k,children:[k?o.jsx(en,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(vr,{open:H,onOpenChange:B,children:o.jsxs(yr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Review Proposed Tags"}),o.jsxs(zs,{children:[D.filter(je=>je.accepted).length," of ",D.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:D.map((je,Ee)=>{const _e=M.find(Ie=>Ie.id===je.itemId);return o.jsx("div",{className:X("p-3 border rounded-lg",!je.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Bo,{checked:je.accepted,onCheckedChange:Ie=>F($e=>$e.map((Ve,Je)=>Je===Ee?{...Ve,accepted:!!Ie}:Ve))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 block truncate",children:_e?typeof _e.input=="string"?_e.input.slice(0,100):JSON.stringify(_e.input).slice(0,100):je.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:je.tags.map((Ie,$e)=>o.jsx(DBt,{tag:Ie,onRename:Ve=>F(Je=>Je.map((nt,Ft)=>Ft===Ee?{...nt,tags:nt.tags.map((Ot,Qt)=>Qt===$e?Ve:Ot)}:nt)),onRemove:()=>F(Ve=>Ve.map((Je,nt)=>nt===Ee?{...Je,tags:Je.tags.filter((Ft,Ot)=>Ot!==$e)}:Je))},`${Ie}-${$e}`))}),je.reason&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:je.reason})]})]})},je.itemId)})}),o.jsxs(sc,{children:[o.jsx(le,{variant:"outline",onClick:()=>B(!1),children:"Cancel"}),o.jsxs(le,{onClick:se,disabled:D.filter(je=>je.accepted).length===0,children:["Accept ",D.filter(je=>je.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",xe&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid w-full content-start gap-8 overflow-y-auto",children:[o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(lt,{children:[o.jsx(lt.Trigger,{asChild:!0,children:o.jsxs(le,{variant:"outline",size:"md",children:[o.jsx(ylt,{}),"Filter",K>0&&o.jsx("span",{className:X("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:K})]})}),o.jsxs(lt.Content,{align:"start",className:X("min-w-48"),children:[o.jsxs(lt.Sub,{children:[o.jsxs(lt.SubTrigger,{children:["Status",x&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(lt.SubContent,{children:[o.jsx(lt.CheckboxItem,{checked:!x,onCheckedChange:()=>{S(!1),h(null)},onSelect:je=>je.preventDefault(),children:"Review Queue"}),o.jsx(lt.CheckboxItem,{checked:x,onCheckedChange:()=>{S(!0),h(null)},onSelect:je=>je.preventDefault(),children:"Completed"})]})]}),o.jsxs(lt.Sub,{children:[o.jsxs(lt.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(lt.SubContent,{children:[o.jsx(lt.CheckboxItem,{checked:!m,onCheckedChange:()=>v(null),onSelect:je=>je.preventDefault(),children:"All"}),Z>0&&o.jsx(lt.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>v(m==="__untagged__"?null:"__untagged__"),onSelect:je=>je.preventDefault(),children:"Untagged"}),z.length>0&&o.jsx(lt.Separator,{}),z.map(([je])=>o.jsx(lt.CheckboxItem,{checked:m===je,onCheckedChange:()=>v(m===je?null:je),onSelect:Ee=>Ee.preventDefault(),children:je},je))]})]}),K>0&&o.jsxs(o.Fragment,{children:[o.jsx(lt.Separator,{}),o.jsxs(lt.Item,{onSelect:()=>{v(null),S(!1),h(null)},children:[o.jsx(ws,{}),"Clear all filters"]})]})]})]}),K>0&&o.jsxs(le,{variant:"outline",size:"md",onClick:()=>{v(null),S(!1),h(null)},children:[o.jsx(ws,{}),"Reset"]})]}),!x&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(MBt,{selectedCount:y.size,vocabulary:G,onApplyTag:Oe,onRemoveTag:ke,onNewTag:je=>Oe(je)}),o.jsxs(lt,{children:[o.jsx(lt.Trigger,{asChild:!0,children:o.jsxs(le,{disabled:k,children:[k?o.jsx(en,{className:"h-4 w-4"}):o.jsx(qe,{size:"sm",children:o.jsx(Na,{})}),"Actions"]})}),o.jsxs(lt.Content,{align:"end",children:[o.jsxs(lt.Item,{onSelect:Ne,children:[o.jsx(qe,{size:"sm",children:o.jsx(hO,{})}),"Complete"]}),o.jsxs(lt.Item,{onSelect:Pe,children:[o.jsx(qe,{size:"sm",children:o.jsx(mu,{})}),"Remove"]}),o.jsx(lt.Separator,{}),o.jsxs(lt.Item,{onSelect:ie,children:[o.jsx(qe,{size:"sm",children:o.jsx(Ng,{})}),"Analyze"]})]})]})]})]}),te?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(en,{className:"h-6 w-6"})}):Y.length===0?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsxs("div",{className:"px-8 text-center",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block",children:x?"No completed reviews yet":"No items to review"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:x?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(ge,{columns:We,className:"min-w-0",children:[o.jsxs(ge.Top,{hasLeadingCell:!0,children:[x?o.jsx(ge.TopCell,{children:" "}):o.jsx(ge.TopSelectCell,{checked:ce?!0:me?"indeterminate":!1,onToggle:()=>we(),"aria-label":"Select all"}),o.jsxs(ge.TopCells,{colStart:2,children:[o.jsx(ge.TopCell,{children:"Input"}),o.jsx(ge.TopCell,{children:"Comment"}),o.jsx(ge.TopCell,{children:"Tags"}),o.jsx(ge.TopCell,{children:"Rating"}),o.jsx(ge.TopCell,{children:"Scores"})]})]}),Y.map(je=>{const Ee=je.scores?Object.entries(je.scores):[],_e=p===je.id,Ie=o.jsxs(o.Fragment,{children:[o.jsx(ge.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:yps(je.input,200)})}),o.jsx(ge.Cell,{height:"compact",className:"min-w-0",children:je.comment?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 truncate",children:je.comment}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(ge.Cell,{height:"compact",className:"min-w-0",children:je.tags.length>0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 truncate",children:je.tags.join(", ")}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(ge.Cell,{height:"compact",children:[je.rating==="positive"&&o.jsx(qe,{size:"sm",className:"text-positive1",children:o.jsx(Qxe,{})}),je.rating==="negative"&&o.jsx(qe,{size:"sm",className:"text-negative1",children:o.jsx(Gxe,{})}),!je.rating&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(ge.Cell,{height:"compact",children:Ee.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(om,{})}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Ee[0][1].toFixed(2)}),Ee.length>1&&o.jsxs(ln,{variant:"default",children:["+",Ee.length-1]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(ge.RowWrapper,{children:[x?o.jsx(ge.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":je.error?"Error":"Success",title:je.error?"Error":"Success",className:X("w-2 h-2 rounded-full",je.error?"bg-red-700":"bg-green-600")})}):o.jsx(ge.SelectCell,{checked:y.has(je.id),onToggle:()=>be(je.id),"aria-label":`Select item ${je.id}`}),o.jsx(ge.RowButton,{flushLeft:!0,colStart:2,featured:_e,onClick:()=>de(je.id),children:Ie})]},je.id)})]})]}),xe&&o.jsx($Bt,{item:xe,isCompleted:x,tagVocabulary:G,onRate:je=>ee(xe.id,je),onSetTags:je=>{ne(xe.id,je);for(const Ee of je)G.includes(Ee)||q(Ee)},onComment:je=>J(xe.id,je),onRemove:()=>ae(xe.id),onComplete:x?void 0:()=>pe(xe.id),onPrevious:Re,onNext:Me,onClose:()=>h(null)})]})]})}function bps({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=xn(),[s,a]=si(),{tab:i,activeVersion:l,handleTabChange:c}=_Ae(s,a),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[S,k]=g.useState([]),[_,C]=g.useState(!1),[E,T]=g.useState([]),[N,I]=g.useState(0),[A,R]=g.useState(null),[L,D]=g.useState(""),[F]=hSe(L,300),{data:H}=r0(e),{data:B=[],total:U,isLoading:V,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:q}=z1(e,F||void 0,l),{total:$}=z1(e,void 0,l),[z,Z]=g.useState({}),{data:K,isLoading:ne}=OD(e,void 0,z),{data:ee}=OD(e),{deleteItems:J}=Ii(),ae=K?.experiments??[],pe=ee?.experiments??[],Y=xfs({hasSearchQuery:!!F,filteredItemsLength:B.length,unfilteredItemsTotal:$,itemsTotal:U}),{data:te}=EAe(e),ue=te?.length??0,fe=se=>{R(se)},ce=()=>{R(null)},me=se=>{y(se),m(!0)},be=se=>{k(se),x(!0)},we=se=>{x(se),se||(k([]),I(de=>de+1))},Oe=se=>{r(`/datasets/${e}/items?items=${se.join(",")}`)},ke=se=>{r(`/datasets/${e}/versions?ids=${se.join(",")}`)},Ne=se=>{T(se),C(!0)},Pe=async()=>{await J.mutateAsync({datasetId:e,itemIds:E}),Fe.success(`Deleted ${E.length} items`),C(!1),T([]),I(se=>se+1)},ie=se=>{m(!1),y([]),I(de=>de+1),n?.(se)},re=se=>{m(se),se||(y([]),I(de=>de+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(pc,{defaultTab:"items",value:i,onValueChange:c,className:"grid h-full grid-rows-[auto_1fr]",children:[o.jsxs(fc,{children:[o.jsxs(jr,{value:"items",children:["Items ",o.jsx(ea,{color:"gray",children:Y})]}),o.jsxs(jr,{value:"experiments",children:["Experiments",o.jsx(ea,{color:"gray",children:ae.length})]}),o.jsxs(jr,{value:"review",children:["Review",ue>0&&o.jsx(ea,{color:"orange",children:ue})]})]}),o.jsx(Xr,{value:"items",className:"mt-5 grid overflow-auto pb-0",children:o.jsx(fps,{datasetId:e,items:B,isLoading:V,featuredItemId:A,onItemSelect:fe,onItemClose:ce,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ne,onCreateDatasetClick:me,onAddToDatasetClick:be,onCompareItemsClick:Oe,datasetName:H?.name,clearSelectionTrigger:N,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:q,searchQuery:L,activeSearchQuery:F,onSearchChange:D,currentDatasetVersion:H?.version,onCompareVersionsClick:ke})}),o.jsx(Xr,{value:"experiments",className:"mt-5 grid overflow-auto pb-0",children:o.jsx(Dfs,{experiments:ae,allExperiments:pe,isLoading:ne,datasetId:e,filters:z,onFiltersChange:Z})}),o.jsx(Xr,{value:"review",className:"mt-2 overflow-auto pb-0",children:o.jsx(nVt,{datasetId:e})})]}),o.jsx(jfs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(gps,{datasetId:e,open:f,onOpenChange:p}),o.jsx(afs,{open:h,onOpenChange:re,items:v,onSuccess:ie}),o.jsx(ifs,{open:b,onOpenChange:we,items:S,currentDatasetId:e}),o.jsx(At,{open:_,onOpenChange:C,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Items"}),o.jsxs(At.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:Pe,children:J.isPending?"Deleting...":"Delete"})]})]})})]})}function xps(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function uie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function wps({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,S]=g.useState(null),{addItem:k}=Ii(),_=()=>{a("{}"),l(""),u(""),f(""),h(!1),v([]),b(""),S(null)},C=R=>{R||_(),n(R)},E=async R=>{R.preventDefault();let L;try{L=JSON.parse(s)}catch{Fe.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Fe.error("Ground Truth must be valid JSON");return}let F;if(c.trim())try{F=JSON.parse(c)}catch{Fe.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const U=JSON.parse(d);if(!Array.isArray(U)){Fe.error("Tool Mocks must be a JSON array");return}H=U}catch{Fe.error("Tool Mocks must be valid JSON");return}let B;if(y.trim())try{B=JSON.parse(y)}catch{Fe.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:D,expectedTrajectory:F,toolMocks:H,scorerIds:p?m:void 0,requestContext:B}),Fe.success("Item added successfully"),C(!1),r?.()}catch(U){const V=xps(U);V?S(V):Fe.error(`Failed to add item: ${U instanceof Error?U.message:"Unknown error"}`)}},T=R=>{a(R),x?.field==="input"&&S(null)},N=R=>{l(R),x?.field==="groundTruth"&&S(null)},I=R=>{f(R),x?.field==="toolMocks"&&S(null)},A=()=>{C(!1)};return o.jsx(vr,{open:t,onOpenChange:C,children:o.jsxs(yr,{className:"max-w-lg",children:[o.jsx(br,{children:o.jsx(hr,{children:"Add Item"})}),o.jsx(Ir,{children:o.jsxs("form",{onSubmit:E,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Lt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Hr,{value:s,onChange:T,showCopyButton:!1,className:"min-h-[120px]"}),x?.field==="input"&&o.jsx(uie,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Lt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Hr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[80px]"}),x?.field==="groundTruth"&&o.jsx(uie,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Lt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Hr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Lt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Hr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[80px]"}),x?.field==="toolMocks"&&o.jsx(uie,{field:"toolMocks",errors:x.errors})]}),o.jsx(JUt,{overrideEnabled:p,onOverrideEnabledChange:h,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Lt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Hr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(le,{type:"button",onClick:A,children:"Cancel"}),o.jsx(le,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})})]})})}function Sps({item:e}){return o.jsx(ha,{withMargins:!1,children:o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{size:"smaller",children:[o.jsx(zN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(za,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ha.Description,{children:[o.jsxs(Oo,{children:[o.jsx(ult,{})," Created ",or(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Oo,{children:[o.jsx(w_,{})," Version v",e.datasetVersion]})]})]})})}function TAe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs($Ie,{children:[o.jsx(Os.CodeSection,{title:"Input",icon:o.jsx(mO,{}),codeStr:t}),o.jsx(Os.CodeSection,{title:"Ground Truth",icon:o.jsx(Cg,{}),codeStr:n}),s&&o.jsx(Os.CodeSection,{title:"Expected Trajectory",icon:o.jsx(Hxe,{}),codeStr:s}),o.jsx(Os.CodeSection,{title:"Scorers",icon:o.jsx(Bxe,{}),codeStr:e.scorerIds===void 0?"Inherited from dataset":JSON.stringify(e.scorerIds,null,2)}),o.jsx(Os.CodeSection,{title:"Metadata",icon:o.jsx(VN,{}),codeStr:r})]})}const kps=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Ops({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Im(),{data:l,isLoading:c}=Wy(),{data:u,isLoading:d}=uh(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Lt,{children:"Target Type"}),o.jsx(Ll,{options:kps,value:e,onValueChange:h,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Lt,{children:m}),o.jsx(Ll,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function _ps({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return hm(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?o.jsxs("div",{className:"space-y-2",children:[o.jsx(Lt,{children:"Request Context"}),o.jsx(C3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-sm",children:"Failed to parse request context schema"})}function Cps({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=g.useRef(null),[l,c]=g.useState(""),[u,d]=g.useState(""),[f,p]=g.useState([]),[h,m]=g.useState({}),[v,y]=g.useState(""),{triggerExperiment:b}=Ii(),x=!!(n&&Object.keys(n).length>0),S=l&&u,k=b.isPending,_=()=>{c(""),d(""),p([]),m({}),y("")},C=()=>{if(x){const N=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return N.length>0?Object.fromEntries(N):void 0}if(v.trim()){let N;try{N=JSON.parse(v)}catch{throw new Error("Request Context must be valid JSON")}if(!N||typeof N!="object"||Array.isArray(N))throw new Error("Request Context must be a JSON object");return N}},E=async()=>{if(!S)return;let N;try{N=C()}catch(I){const A=I instanceof Error?I.message:"Request Context must be valid JSON";iu.error(A);return}try{const I=await b.mutateAsync({datasetId:e,targetType:l,targetId:u,scorerIds:f.length>0?f:void 0,version:t,requestContext:N});iu.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),_()}catch(I){const A=I instanceof Error?I.message:"Failed to trigger experiment";iu.error(A)}},T=()=>{k||(s(!1),_())};return o.jsx(vr,{open:r,onOpenChange:T,children:o.jsxs(yr,{ref:i,children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Experiment"}),o.jsx(zs,{children:t?`Execute items from ${or(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs(Ir,{className:"grid gap-6",children:[o.jsx(Ops,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(XUt,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),x?o.jsx(_ps,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Lt,{children:"Request Context (JSON, optional)"}),o.jsx(Hr,{value:v,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(sc,{className:"px-6 pt-4",children:[o.jsx(le,{onClick:T,disabled:k,children:"Cancel"}),o.jsx(le,{variant:"primary",onClick:E,disabled:!S||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(en,{className:"h-4 w-4"}),"Running..."]}):"Run"})]})]})})}const Eps=e=>{const t=Ze();return gt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},enabled:!!e})},jAe=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),o.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]});function die(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Tps({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,a=[...t.map(i=>({outcome:"served",toolName:i.toolName,args:i.args})),...r.map(i=>({outcome:"live",toolName:i.toolName,args:i.args})),...n.map(i=>({outcome:"unconsumed",toolName:i.toolName,args:i.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx(wn.SectionHeading,{icon:o.jsx(Wp,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(Sn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(Sn.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",die(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>die(i.args)).join(", ")]})]})}),o.jsx("div",{className:"border-border1 divide-border1 divide-y rounded border text-sm",children:a.map((i,l)=>o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[o.jsxs("span",{className:"min-w-0 truncate",children:[o.jsx("span",{className:"text-neutral4 font-mono",children:i.toolName}),o.jsx("span",{className:"text-neutral3 ml-2 font-mono text-xs",children:die(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${jps(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function jps(e){switch(e){case"served":return"bg-accent1/10 text-accent1";case"live":return"bg-orange-500/10 text-orange-400";case"unconsumed":return"bg-neutral3/10 text-neutral4"}}function Nps({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=g.useState(!1),m=d??p,v=f??h,y=!!e?.error,b=Nz(e?.input),x=Nz(e?.output),S=Nz(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",_=Array.isArray(e.tags)?e.tags:[];return o.jsxs(wn,{collapsed:m,children:[o.jsxs(wn.Header,{children:[o.jsxs(wn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[f&&o.jsx(le,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>v(!m),children:m?o.jsx(hlt,{}):o.jsx(plt,{})}),o.jsx(wn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(le,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx(jAe,{}),"Trace"]}),o.jsx(wn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(wn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(Ut,{children:[o.jsx(Ut.Key,{children:"Item Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Ut.Key,{children:"Created"}),o.jsx(Ut.Value,{children:or(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(Sn,{variant:"destructive",title:"Error",children:o.jsx(Sn.Message,{children:Nz(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(ge,{columns:"1fr 1fr",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Scorer"}),o.jsx(ge.TopCell,{children:"Score"})]}),t.map(C=>o.jsxs(ge.RowButton,{featured:c===C.id,onClick:()=>l?.(C.id),children:[o.jsx(ge.Cell,{height:"compact",children:C.scorerId}),o.jsx(ge.MonoCell,{children:C.score.toFixed(3)})]},C.id))]}),e.toolMockReport&&o.jsx(Tps,{report:e.toolMockReport}),(e.status||_.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(wn.SectionHeading,{icon:o.jsx(VN,{}),className:"mb-2",children:"Review"}),(e.status||_.length>0)&&o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),_.map(C=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:C},C))]}),k&&o.jsx("div",{children:o.jsxs(le,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(nq,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(le,{size:"sm",onClick:i,children:[o.jsx(Oa,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(wn.CodeSection,{title:"Input",icon:o.jsx(zN,{}),codeStr:b}),o.jsx(wn.CodeSection,{title:"Output",icon:o.jsx(Cg,{}),codeStr:x}),o.jsx(wn.CodeSection,{title:"Ground Truth",icon:o.jsx(Zxe,{}),codeStr:S})]})]})]})}function Nz(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Ips({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const p=!!(d&&f),h=[p?"auto":"",...s.map(v=>v.size)].filter(Boolean).join(" "),m=s.some(v=>v.name==="input");return t?o.jsx(ol,{columns:h}):o.jsxs(ge,{columns:h,className:"min-w-0",children:[o.jsxs(ge.Top,{hasLeadingCell:p,children:[p&&o.jsx(ge.TopCell,{children:" "}),p?o.jsx(ge.TopCells,{colStart:2,children:s.map(v=>o.jsx(ge.TopCell,{children:v.label},v.name))}):s.map(v=>o.jsx(ge.TopCell,{children:v.label},v.name))]}),e.length===0?o.jsx(ge.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(v=>{const y=!!v.error,b=v.id===n,x=o.jsxs(o.Fragment,{children:[o.jsx(ge.IdCell,{id:v.itemId}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("div",{className:"relative flex h-full w-10 items-center justify-center bg-transparent",children:o.jsx("div",{role:"img","aria-label":y?"Error":"Success",className:X("w-2 h-2 rounded-full",y?"bg-red-700":"bg-green-600")})})}),o.jsx(On,{children:y?"Error":"Success"})]})}),m&&o.jsx(ge.MonoCell,{children:Rps(Aps(v.input),200)}),i?.map(S=>{const _=a?.[v.itemId]?.find(C=>C.scorerId===S);return o.jsx(ge.Cell,{height:"compact",className:"text-neutral3 text-ui-smd font-mono",children:_!=null?_.score.toFixed(3):"-"},S)})]});return p?o.jsxs(ge.RowWrapper,{children:[o.jsx(ge.SelectCell,{checked:d.has(v.id),onToggle:()=>f(v.id),"aria-label":`Select result ${v.itemId}`}),o.jsx(ge.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(v.id),children:x})]},v.id):o.jsx(ge.RowButton,{featured:b,onClick:()=>r(v.id),children:x},v.id)}),o.jsx(ge.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Aps(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Rps(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Pps(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function $ps({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=g.useState(!1),u=a??l,d=i??c,f=Pps(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(wn,{collapsed:u,children:[o.jsxs(wn.Header,{children:[o.jsxs(wn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[i&&o.jsx(le,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx(hlt,{}):o.jsx(plt,{})}),(n||t)&&o.jsx(wn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(le,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx(jAe,{}),"Trace"]}),o.jsx(wn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(wn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(wn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(om,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(wn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(jh,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(wn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(jh,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(wn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(jh,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(wn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(jh,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const yet=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function Mps({scoresByItemId:e,experimentStatus:t}){const n=g.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Lr,{iconSlot:o.jsx(om,{className:"text-neutral3 h-8 w-8"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(bn,{children:[o.jsxs(bn.Header,{columns:yet,children:[o.jsx(bn.HeaderCol,{children:"Scorer"}),o.jsx(bn.HeaderCol,{children:"Avg Score"}),o.jsx(bn.HeaderCol,{children:"Items Scored"})]}),o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:n.map(({scorerId:r,avg:s,count:a})=>o.jsxs(bn.Row,{columns:yet,children:[o.jsx(bn.TextCell,{children:r}),o.jsx(bn.TextCell,{className:"font-mono",children:s.toFixed(3)}),o.jsx(bn.TextCell,{className:"font-mono",children:a})]},r))})})]})}function rVt({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=g.useState(null),[d,f]=g.useState(null),[p,h]=g.useState(void 0),[m,v]=g.useState(null),[y,b]=g.useState(new Set),[x,S]=g.useState(!1),[k,_]=g.useState(!1),[C,E]=g.useState(!1),[T,N]=g.useState(!1),{updateExperimentResult:I}=Ii(),A=g.useCallback(re=>{b(se=>{const de=new Set(se);return de.has(re)?de.delete(re):de.add(re),de})},[]),R=g.useCallback(()=>b(new Set),[]),L=g.useCallback(()=>{const re=r.filter(se=>!!se.error).map(se=>se.id);b(new Set(re))},[r]),D=g.useCallback(async re=>{if(x||re.length===0)return;S(!0);let se=0;const de=new Set;try{for(const xe of re)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:xe,status:"needs-review"}),se++,de.add(xe)}catch{}}finally{S(!1)}de.size>0&&b(xe=>{const Ce=new Set(xe);for(const Re of de)Ce.delete(Re);return Ce}),se>0&&Fe(`${se} result${se>1?"s":""} flagged for review`)},[t,e,x,I]),F=r.find(re=>re.id===c)??null,[H,B]=g.useState("summary"),[U,V]=g.useState(null),M=re=>{B(re),re!=="reviews"&&V(null)},{data:G}=EAe(t),q=(G??[]).filter(re=>re.experimentId===e).length,{data:$}=IBt(e,n),z=g.useMemo(()=>{if(!$)return[];const re=new Set;for(const se of Object.values($))for(const de of se)re.add(de.scorerId);return[...re].sort()},[$]),Z=re=>{u(re),f(null),h(void 0),v(null)},K=re=>{Z(re===c?null:re)},ne=()=>{Z(null)},ee=()=>{if(!F)return;const re=r.findIndex(se=>se.id===F.id);if(re>=0&&re<r.length-1)return()=>Z(r[re+1].id)},J=()=>{if(!F)return;const re=r.findIndex(se=>se.id===F.id);if(re>0)return()=>Z(r[re-1].id)},ae=F?$?.[F.itemId]:void 0,pe=ae?.find(re=>re.id===m)??null,Y=re=>{v(re===m?null:re),f(null),h(void 0)},te=()=>{if(!m||!ae)return;const re=ae.findIndex(se=>se.id===m);if(re>=0&&re<ae.length-1)return()=>v(ae[re+1].id)},ue=()=>{if(!m||!ae)return;const re=ae.findIndex(se=>se.id===m);if(re>0)return()=>v(ae[re-1].id)},{data:fe,isLoading:ce}=Eps(d),me=fe?.spans,{data:be,isLoading:we}=kL(d,p),Oe=be?.span,{handlePreviousSpan:ke,handleNextSpan:Ne}=SAe(me,p??null,h),Pe=(()=>{const re=[],se=!!pe,de=!!d;return re.push(k?"auto":se||de?"2fr":"1fr"),se&&re.push(T?"auto":"3fr"),de&&re.push(C?"auto":"3fr"),de&&p&&re.push("3fr"),re.join(" ")})(),ie=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...z.map(re=>({name:re,label:re,size:"12rem"}))],[z]);return o.jsxs(pc,{defaultTab:"summary",value:H,onValueChange:M,className:"grid h-full grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"summary",children:"Summary"}),o.jsx(jr,{value:"results",children:"Results"}),o.jsxs(jr,{value:"reviews",children:["Reviews",q>0&&o.jsx(ea,{color:"orange",children:q})]})]}),o.jsx(Xr,{value:"summary",className:"mt-5 overflow-y-auto",children:o.jsx(Mps,{scoresByItemId:$,experimentStatus:n})}),o.jsx(Xr,{value:"reviews",className:"mt-2 overflow-auto pb-0",children:o.jsx(nVt,{datasetId:t,experimentId:e,featuredItemId:U})}),o.jsxs(Xr,{value:"results",className:"mt-2 grid grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"bg-surface3 flex items-center gap-2 px-4 py-2",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(le,{variant:"outline",size:"sm",disabled:x,onClick:()=>D([...y]),children:[o.jsx(qe,{size:"sm",children:o.jsx(nq,{})}),"Flag for Review"]}),o.jsx(le,{variant:"ghost",size:"sm",onClick:R,children:"Clear"})]}),r.length>0&&y.size===0&&!s&&o.jsx("div",{className:"flex items-center gap-2 px-4 py-2",children:o.jsx(le,{variant:"ghost",size:"sm",onClick:L,children:"Select loaded failures"})})]}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",F&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"flex w-full overflow-y-auto",children:o.jsx("div",{className:"grid w-full content-start gap-8 overflow-y-auto",children:o.jsx(Ips,{results:r,isLoading:s,featuredResultId:c,onResultClick:K,columns:ie,scoresByItemId:$,scorerIds:z,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:A})})}),F&&o.jsxs("div",{className:"grid max-h-full min-h-0 content-start gap-4 overflow-auto",style:{gridTemplateRows:Pe},children:[o.jsx(Nps,{result:F,scores:ae,onPrevious:J(),onNext:ee(),onClose:ne,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{F.traceId&&(f(F.traceId),h(void 0),v(null),_(!0),E(!1))},onOpenInReview:()=>{V(F.id),B("reviews")},onFlagForReview:re=>D([re]),collapsed:k,onCollapsedChange:_}),pe&&o.jsx($ps,{score:pe,onNext:te(),onPrevious:ue(),onClose:()=>v(null),onShowTrace:()=>{pe.traceId&&(f(pe.traceId),h(void 0),_(!0),N(!0),E(!1))},collapsed:T,onCollapsedChange:N}),d&&o.jsxs(o.Fragment,{children:[o.jsx(hAe,{traceId:d,spans:me,isLoading:ce,onClose:()=>{f(null),h(void 0),_(!1),N(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:C,onCollapsedChange:E,LinkComponent:Cx,traceHref:`/traces/${d}`}),p&&o.jsx(dAe,{traceId:d,spanId:p,span:Oe,isLoading:we,onPrevious:ke,onNext:Ne,onClose:()=>h(void 0)})]})]})]})]})]})}const Dps={pending:o.jsx(hj,{}),running:o.jsx(hpe,{}),completed:o.jsx(da,{}),failed:o.jsx(ws,{})};function Lps({experiment:e,className:t}){const n=e.status,r=e.totalItems-e.succeededCount-e.failedCount;return o.jsxs("div",{className:X("grid justify-items-end gap-3",t),children:[o.jsxs("div",{className:"text-ui-lg text-neutral4 bg-surface5 flex items-center gap-2 rounded-lg p-1 px-3 capitalize",children:[o.jsx("span",{className:X("w-5 h-5 flex items-center justify-center rounded-full text-black","[&>svg]:w-4 [&>svg]:h-4",{"bg-green-700":n==="completed","bg-red-700":n==="failed","bg-cyan-600":n==="running","bg-yellow-600":n==="pending"}),children:Dps[n]}),e.status]}),o.jsxs("div",{className:X("flex items-center gap-3 text-neutral3 text-ui-md ","[&>span]:flex [&>span]:gap-1 [&>span]:items-center ","[&_b]:text-neutral4 [&_b]:font-semibold"),children:[o.jsxs("span",{children:["Total: ",o.jsx("b",{children:e.totalItems})]}),o.jsxs("span",{children:["Succeeded: ",o.jsx("b",{children:e.succeededCount})]}),o.jsxs("span",{children:["Failed: ",o.jsx("b",{children:e.failedCount})]}),(n==="pending"||n==="running")&&o.jsxs("span",{children:["Pending: ",o.jsx("b",{children:r})]})]})]})}function Fps({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs(Mr,{spacing:"close",children:[o.jsxs(le,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx(lH,{})," Prev"]}),o.jsxs(le,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(c3,{})]})]})}function NAe({delta:e}){const t=e>0?o.jsx(ea,{size:"small",color:"green",intensity:"muted",children:o.jsx(ND,{})}):e<0?o.jsx(ea,{size:"small",color:"red",intensity:"muted",children:o.jsx(vZt,{})}):null;return o.jsxs("span",{className:X("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function Iz(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function zps({item:e,baselineId:t,contenderId:n,baselineVersion:r,contenderVersion:s,onPrevious:a,onNext:i,onClose:l}){const c=e.results[t],u=e.results[n],d=!!(c&&u),f=new Set;if(c)for(const h of Object.keys(c.scores))f.add(h);if(u)for(const h of Object.keys(u.scores))f.add(h);const p=[...f].sort();return o.jsxs(Yr,{withLeftSeparator:!0,children:[o.jsxs(Yr.Toolbar,{children:[o.jsx(Fps,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx(Mr,{children:o.jsx(le,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(ws,{})})})]}),o.jsxs(Yr.Content,{className:"pb-6",children:[o.jsx(ha,{withMargins:!1,children:o.jsx(ha.Column,{children:o.jsxs(ha.Title,{size:"smaller",children:[o.jsx(zN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs($Ie,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-neutral5 text-sm font-medium",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,v=u?.scores[h]??null,y=m!=null&&v!=null?v-m:null;return o.jsxs("div",{className:"bg-surface2 flex items-center justify-between gap-4 rounded-lg px-3 py-2",children:[o.jsx("span",{className:"text-neutral5 text-sm font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-neutral3 text-sm",children:[m!=null?m.toFixed(3):"-"," →"," ",v!=null?v.toFixed(3):"-"]}),y!=null&&o.jsx(NAe,{delta:y})]})]},h)})})]}),o.jsx(Os.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(ea,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(Cg,{}),codeStr:Iz(c?.output)}),o.jsx(Os.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(ea,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(Cg,{}),codeStr:Iz(u?.output)}),o.jsx(Os.CodeSection,{title:"Item Input",icon:o.jsx(mO,{}),codeStr:Iz(e.input)}),o.jsx(Os.CodeSection,{title:"Item Ground Truth",icon:o.jsx(Zxe,{}),codeStr:Iz(e.groundTruth)})]})}):o.jsx(Sn,{variant:"warning",title:"Comparison not available",children:o.jsx(Sn.Message,{children:(()=>{const h=c?"Contender":"Baseline",m=c?s:r;return o.jsxs(o.Fragment,{children:["The ",h," experiment was run against dataset",m!=null?` v. ${m}`:"",", which does not contain this item."]})})()})})]})]})}function Bps({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Yr,{children:o.jsxs(bn,{children:[o.jsxs(bn.Header,{columns:a,children:[o.jsx(bn.HeaderCol,{children:"Item ID"}),!s&&r.map(l=>o.jsx(bn.HeaderCol,{className:"flex justify-center",children:l},l))]}),o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:e.map(l=>{const c=l.results[t],u=l.results[n],d=!!(c&&u);return o.jsx(bn.Row,{children:o.jsxs(bn.RowButton,{item:{id:l.itemId},columns:a,isFeatured:s===l.itemId,onClick:i,children:[o.jsx(bn.IdCell,{id:l.itemId,className:d?"":"text-neutral1"}),!s&&o.jsx(o.Fragment,{children:r.map(f=>{const p=c?.scores[f]??null,h=u?.scores[f]??null,m=p!=null&&h!=null?h-p:null;return o.jsx(bn.Cell,{className:"flex items-center justify-center gap-5 font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-neutral2 flex min-w-24 items-center",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(NAe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const Ups={baseline:{label:"Baseline",color:"purple",customStyle:"items-end justify-items-end [&>div]:justify-end border-r-0 rounded-r-none"},contender:{label:"Contender",color:"cyan",customStyle:"items-start justify-items-start [&>div]:justify-start border-l-0 rounded-l-none"}};function bet({datasetId:e,experiment:t,type:n}){const{Link:r}=xn(),{label:s,color:a,customStyle:i}=Ups[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null,c=lS(t.id)??t.id,u=t.name||c,d=o.jsx(le,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"min-w-0 truncate",children:u})});return o.jsxs("div",{className:`border-border1 grid gap-3 rounded-lg border-2 p-5 ${i}`,children:[o.jsxs("div",{className:"flex w-full items-center gap-3 overflow-clip",children:[n==="contender"&&o.jsxs(ea,{size:"small",color:a,children:[s,o.jsx(xm,{})]}),t.description?o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:d}),o.jsx(On,{children:t.description})]}):d,n==="baseline"&&o.jsxs(ea,{size:"small",color:a,children:[o.jsx(Rc,{})," ",s]})]}),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Oo,{children:[o.jsx(fpe,{})," ",c]}),o.jsxs(Oo,{children:[o.jsx(Zxe,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(Oo,{children:[o.jsx(aq,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(Oo,{children:[o.jsx(dlt,{})," ",or(l,"MMM d, yyyy HH:mm")]})]})]})}function Vps({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=g.useState(null),{data:i,isLoading:l,error:c}=Ads(e,t,n),{data:u}=WV(e,t),{data:d}=WV(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=g.useMemo(()=>{if(!i)return[];const E=new Set;for(const T of i.items)for(const N of Object.values(T.results))if(N)for(const I of Object.keys(N.scores))E.add(I);return[...E].sort()},[i]),h=g.useMemo(()=>{if(!i||p.length===0)return[];const E=i.baselineId,T=t===E?n:t;return p.map(N=>{let I=0,A=0,R=0,L=0;for(const B of i.items){const U=B.results[E]?.scores[N],V=B.results[T]?.scores[N];U!=null&&(I+=U,R++),V!=null&&(A+=V,L++)}const D=R>0?I/R:null,F=L>0?A/L:null,H=D!=null&&F!=null?F-D:null;return{scorerId:N,avgA:D,avgB:F,delta:H}})},[i,p,t,n]),m=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"baselineAvg",label:"Baseline Avg",size:"1fr"},{name:"comparisonAvg",label:"Comparison Avg",size:"1fr"},{name:"delta",label:"Delta",size:"1fr"}],v=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(E=>({name:E,label:E,size:"1fr"}))],[p,s]),y=i?.items.find(E=>E.itemId===s)??null,b=E=>{a(E===s?null:E)},x=()=>{a(null)},S=()=>{if(!i||!s)return;const E=i.items.findIndex(T=>T.itemId===s);if(E>=0&&E<i.items.length-1)return()=>a(i.items[E+1].itemId)},k=()=>{if(!i||!s)return;const E=i.items.findIndex(T=>T.itemId===s);if(E>0)return()=>a(i.items[E-1].itemId)};if(l)return o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(en,{})});if(c)return o.jsx(Sn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Sn.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"});const _=i.baselineId,C=t===_?n:t;return o.jsxs("div",{className:"grid gap-10",children:[u&&d&&o.jsxs("div",{className:X("relative grid xl:grid-cols-[1fr_auto_1fr] gap-4 xl:gap-0"),children:[o.jsx(bet,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"before:bg-border1 relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:w-[2px] before:-translate-x-1/2",children:o.jsx("div",{className:"bg-surface2 relative z-1 rounded-lg p-2",children:o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(le,{onClick:r,children:"VS"})}),o.jsx(On,{children:"Switch the order"})]})})}),o.jsx(bet,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(Sn,{variant:"warning",title:"Version mismatch",children:o.jsxs(Sn.Message,{children:["These experiments used different dataset versions (v",u.datasetVersion," vs v",d.datasetVersion,"). Results may not be directly comparable."]})}),h.length>0&&o.jsxs(bn,{children:[o.jsxs(bn.Header,{columns:m,children:[o.jsx(bn.HeaderCol,{children:"Scorer"}),o.jsx(bn.HeaderCol,{className:"flex justify-center",children:o.jsxs(fJe,{children:[o.jsx(ea,{color:"purple",size:"small",intensity:"muted",children:"Baseline"}),o.jsx(ea,{color:"purple",size:"small",children:"Avg"})]})}),o.jsx(bn.HeaderCol,{className:"flex justify-center",children:o.jsxs(fJe,{children:[o.jsx(ea,{color:"cyan",size:"small",intensity:"muted",children:"Contender"}),o.jsx(ea,{color:"cyan",size:"small",children:"Avg"})]})}),o.jsx(bn.HeaderCol,{className:"flex justify-center",children:"Delta"})]}),o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:h.map(({scorerId:E,avgA:T,avgB:N,delta:I})=>o.jsxs(bn.Row,{columns:m,children:[o.jsx(bn.TextCell,{children:E}),o.jsx(bn.TextCell,{className:"text-center font-mono",children:T!=null?T.toFixed(3):"-"}),o.jsx(bn.TextCell,{className:"text-center font-mono",children:N!=null?N.toFixed(3):"-"}),o.jsx(bn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(NAe,{delta:I}):"-"})]},E))})})]}),o.jsxs(cy,{className:X({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(Bps,{items:i.items,baselineId:_,contenderId:C,scorerIds:p,featuredItemId:s,columns:v,onItemClick:b}),!!y&&o.jsx(zps,{item:y,baselineId:_,contenderId:C,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:S(),onClose:x})]})]})}function qps({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=OAe(e,t),[l,c]=g.useState(!1),[u,d]=g.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(x=>{const S=new Set(x);if(S.has(b))S.delete(b);else if(S.size>=2){const[k]=Array.from(S);return new Set([k,b])}else S.add(b);return S})},m=()=>{c(!1),d(new Set)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Yr,{className:"min-w-56",children:[l?o.jsx(Yr.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(Mr,{children:[o.jsx(le,{onClick:m,children:"Cancel"}),o.jsx(le,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(Yr.Toolbar,{children:o.jsxs(le,{onClick:v,className:"w-full",children:[o.jsx(r1,{})," Compare Ver."]})})}),i?o.jsx(Hps,{}):o.jsxs(bn,{children:[o.jsx(bn.Header,{children:o.jsx(bn.HeaderCol,{children:"Item Version History"})}),o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:a?.map(b=>{const x=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(bn.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(bn.LabelCell,{children:o.jsx(Bo,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(x)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(bn.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",children:o.jsx(bn.VersionCell,{version:b.datasetVersion,date:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function Hps(){return o.jsxs(bn,{children:[o.jsx(bn.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(bn.HeaderCol,{children:"Item Version History"})}),o.jsx(bn.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(bn.Row,{children:o.jsx(bn.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(bn.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function Wps(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${or(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function Zps({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=QIe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${Wps(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Yr.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Cc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Cc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const Gps=[{name:"id",label:"ID",size:"1fr"},{name:"versionA",label:"Version A",size:"1fr"},{name:"versionB",label:"Version B",size:"1fr"},{name:"compare",label:"Compare",size:"10rem"}],Qps={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Zr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(Clt,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(zGt,{}),tooltip:"Same in both versions"}};function fie({red:e=!1,tooltip:t}){return o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(EZt,{className:X("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx(On,{children:t})]})}function uk({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{color:n,icon:r,tooltip:s}=Qps[e];return o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx(ea,{color:n,size:"small",children:r})]})}),o.jsx(On,{children:s})]})}function Yps(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Kps({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=xn(),l=t>n;return o.jsx(bn,{children:o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=Yps(u,d);return o.jsxs(bn.Row,{columns:Gps,children:[o.jsx(bn.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(bn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!d&&l?o.jsx(uk,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(uk,{variant:"changed",version:u.datasetVersion}):o.jsx(uk,{version:u.datasetVersion})}):o.jsx(bn.Cell,{className:"flex items-center justify-center",children:o.jsx(fie,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(bn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!u&&!l?o.jsx(uk,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(uk,{variant:"changed",version:d.datasetVersion}):o.jsx(uk,{version:d.datasetVersion})}):o.jsx(bn.Cell,{className:"flex items-center justify-center",children:o.jsx(fie,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(bn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",children:o.jsx(uk,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(bn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(bn.Cell,{children:o.jsx(fie,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const xet={needsReview:"#facc15",complete:"#22c55e"},Xps=[{label:"Needs Review",color:xet.needsReview},{label:"Reviewed",color:xet.complete}];function Jps({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;p+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:x,values:[m.needsReview,m.complete]})}return{data:h,maxVal:f,totalInPipeline:p}},[e,t,n]),c=a.length>0;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Gt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Gt.Loading,{}):s?o.jsx(Gt.Error,{message:"Failed to load review data"}):o.jsx(Gt.Content,{children:c?o.jsx(RN,{data:a,segments:Xps,maxVal:i,fmt:u=>String(u)}):o.jsx(Gt.NoData,{message:"No items have been sent to review yet"})})]})}function IAe(){const e=Ze();return gt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function sVt(e){const t=new Map;if(!e?.counts)return t;for(const n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}function ehs(e,t){const n=new Map,r=sVt(e);if(!r.size||!t)return n;for(const s of t){const a=r.get(s.id);if(!a||!s.datasetId||a.needsReview+a.complete===0)continue;const l=n.get(s.datasetId)??{needsReview:0,complete:0};l.needsReview+=a.needsReview,l.complete+=a.complete,n.set(s.datasetId,l)}return n}function ths(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}const nhs=10;function rhs(){const[e,t]=g.useState(!1),[n,r]=g.useState(""),[s,a]=g.useState("all"),[i,l]=g.useState("all"),[c,u]=g.useState("all"),[d,f]=g.useState(0),{data:p,isLoading:h,error:m}=qg({page:d,perPage:nhs}),{data:v,isLoading:y,error:b}=_Q(),{data:x}=IAe(),S=g.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,_=g.useMemo(()=>v?.experiments??[],[v?.experiments]),C=g.useMemo(()=>Yds(S),[S]),E=g.useMemo(()=>ehs(x,_),[x,_]),T=h||y,N=m||b,I=()=>t(!0),A=g.useCallback(()=>f(V=>V+1),[]),R=g.useCallback(()=>f(V=>Math.max(0,V-1)),[]),L=g.useCallback(V=>{r(V),f(0)},[]),D=g.useCallback(V=>{a(V),f(0)},[]),F=g.useCallback(V=>{l(V),f(0)},[]),H=g.useCallback(V=>{u(V),f(0)},[]);if(N&&xs(N))return o.jsx(cr,{children:o.jsx(Zs,{})});if(N&&Ss(N))return o.jsx(cr,{children:o.jsx($s,{resource:"datasets"})});if(N)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load datasets",message:N.message})});if(S.length===0&&!T&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(cr,{children:o.jsx(tfs,{onCreateClick:I})}),o.jsx(dxe,{open:e,onOpenChange:t})]});const B=s!=="all"||i!=="all"||c!=="all"||n!=="",U=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(sfs,{search:n,onSearchChange:L,targetFilter:s,onTargetFilterChange:D,experimentFilter:i,onExperimentFilterChange:F,tagFilter:c,onTagFilterChange:H,tagOptions:C,onReset:U,hasActiveFilters:B,onCreateClick:I})}),o.jsx(efs,{datasets:S,experiments:_,reviewByDataset:E,isLoading:T,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:A,onPrevPage:R}),o.jsx(dxe,{open:e,onOpenChange:t})]})}function Az({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function shs(){const{datasetId:e}=Sr(),t=Ws(),[n,r]=si(),{activeVersion:s}=_Ae(n,r),[a,i]=g.useState(!1),[l,c]=g.useState(!1),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),{data:v,error:y,isLoading:b}=r0(e),{data:x=[],isLoading:S}=z1(e,void 0,s),k=!S&&x.length===0;if(b)return null;if(y&&xs(y))return o.jsx(Az,{children:o.jsx(Zs,{})});if(y&&Ss(y))return o.jsx(Az,{children:o.jsx($s,{resource:"datasets"})});if(y&&CEe(y)||!b&&!y&&!v)return o.jsx(Az,{children:o.jsx(Lr,{iconSlot:o.jsx(uy,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(le,{as:ni,to:"/datasets",children:[o.jsx(Rc,{}),"Back to Datasets"]})})});if(y)return o.jsx(Az,{children:o.jsx(Hi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const _=E=>{t(`/datasets/${e}/experiments/${E}`)},C=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Vt,{height:"full",children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{children:[o.jsxs(Vt.Column,{children:[v?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:v.description}),o.jsxs(Ut,{numOfCol:2,children:[o.jsx(Ut.Key,{children:"Created at"}),o.jsx(Ut.Value,{children:v?.createdAt?or(new Date(v.createdAt),"MMM d, yyyy"):""}),o.jsx(Ut.Key,{children:"Latest version"}),o.jsxs(Ut.Value,{children:["v",v?.version??""]})]})]}),o.jsx(Vt.Column,{children:o.jsxs(Mr,{children:[k?o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsxs(le,{variant:"primary",children:[o.jsx(Hp,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx(On,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(le,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(Hp,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(lt,{children:[o.jsx(lt.Trigger,{asChild:!0,children:o.jsx(le,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(AD,{})})}),o.jsxs(lt.Content,{align:"end",className:"w-48",children:[o.jsxs(lt.Item,{onSelect:()=>d(!0),children:[o.jsx(lm,{})," Edit Dataset"]}),o.jsxs(lt.Item,{onSelect:()=>m(!0),children:[o.jsx(im,{})," Duplicate Dataset"]}),o.jsxs(lt.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(mu,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Vt.MainArea,{children:o.jsx(bps,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(Cps,{datasetId:e,version:s??void 0,requestContextSchema:v?.requestContextSchema,open:a,onOpenChange:i,onSuccess:_}),o.jsx(wps,{datasetId:e,open:l,onOpenChange:c}),v&&o.jsx(ufs,{open:u,onOpenChange:d,dataset:{id:v.id,name:v.name,description:v?.description||"",targetType:v.targetType,inputSchema:v.inputSchema,groundTruthSchema:v.groundTruthSchema,requestContextSchema:v.requestContextSchema}}),v&&o.jsx(ofs,{open:h,onOpenChange:m,sourceDatasetId:v.id,sourceDatasetName:v.name,sourceDatasetDescription:v.description,sourceDatasetTargetType:v.targetType}),v&&o.jsx(ffs,{open:f,onOpenChange:p,datasetId:v.id,datasetName:v.name,onSuccess:C})]})}function aVt({experiment:e}){const{Link:t,paths:n}=xn(),{data:r}=Im(),{data:s}=Wy(),{data:a}=uh(),i=()=>{switch(e.targetType){case"agent":return n.agentLink(e.targetId);case"workflow":return n.workflowLink(e.targetId);case"scorer":return n.scorerLink(e.targetId);default:return"#"}},l=()=>{const u=e.targetId;if(!u)return u;switch(e.targetType){case"agent":return r?.[u]?.name??u;case"workflow":return s?.[u]?.name??u;case"scorer":return a?.[u]?.scorer?.config?.name??u;default:return u}},c=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{children:[o.jsx(Vt.Column,{children:o.jsxs(Ut,{numOfCol:2,children:[e.name&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Name"}),o.jsx(Ut.Value,{children:e.name})]}),e.description&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Description"}),o.jsx(Ut.Value,{children:e.description})]}),o.jsx(Ut.Key,{children:"Created at"}),o.jsx(Ut.Value,{children:or(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Completed at"}),o.jsx(Ut.Value,{children:or(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(Ut.Key,{children:"Target"}),o.jsx(Ut.ValueLink,{href:i(),as:t,children:l()}),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Version"}),c?o.jsx(Ut.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(Ut.Value,{children:e.agentVersion})]})]})}),o.jsx(Vt.Column,{children:o.jsx(Lps,{experiment:e})})]})})}function Rz({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function ahs(){const{datasetId:e,experimentId:t}=Sr(),{data:n,isLoading:r,error:s}=WV(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=oQ({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&xs(s)?o.jsx(Rz,{children:o.jsx(Zs,{})}):s&&Ss(s)?o.jsx(Rz,{children:o.jsx($s,{resource:"datasets"})}):s&&CEe(s)||!r&&!s&&!n?o.jsx(Rz,{children:o.jsx(Lr,{iconSlot:o.jsx($xe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(le,{as:ni,to:`/datasets/${e}?tab=experiments`,children:[o.jsx(Rc,{}),"Back to Dataset"]})})}):s?o.jsx(Rz,{children:o.jsx(Hi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Vt,{height:"full",children:[o.jsx(aVt,{experiment:n}),o.jsx(Vt.MainArea,{children:o.jsx(rVt,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function ihs(){const{datasetId:e}=Sr(),[t,n]=si(),{error:r}=r0(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&xs(r)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):r&&Ss(r)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})}):!e||!s||!a?o.jsx(fs,{children:o.jsx(_y,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(fs,{children:o.jsx(_y,{children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[100rem] content-start px-12",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(r1,{})," Dataset Experiments Comparison"]}),o.jsxs(ha.Description,{children:["Comparing"," ",o.jsx(ni,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(ni,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ha.Column,{children:o.jsxs(le,{as:ni,to:`/datasets/${e}`,children:[o.jsx(Rc,{}),"Back to Dataset"]})})]}),o.jsx(Vps,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function ohs(){const{datasetId:e,itemId:t}=Sr(),{Link:n}=xn(),r=Ws(),{data:s,isLoading:a,error:i}=OAe(e??"",t??""),{updateItem:l,deleteItem:c}=Ii(),{data:u}=r0(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=g.useState(null),m=g.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",scorerOverrideEnabled:!1,scorerIds:[],requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",scorerOverrideEnabled:d.scorerIds!==void 0,scorerIds:d.scorerIds??[],requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),v=d?.datasetVersion??0,[y,b]=g.useState(!1),[x,S]=g.useState(m.input),[k,_]=g.useState(m.groundTruth),[C,E]=g.useState(m.metadata),[T,N]=g.useState(m.trajectory),[I,A]=g.useState(m.toolMocks),[R,L]=g.useState(m.scorerOverrideEnabled),[D,F]=g.useState(m.scorerIds),[H,B]=g.useState(m.requestContext),[U,V]=g.useState(v);v!==U&&(V(v),S(m.input),_(m.groundTruth),E(m.metadata),N(m.trajectory),A(m.toolMocks),L(m.scorerOverrideEnabled),F(m.scorerIds),B(m.requestContext));const[M,G]=g.useState(!1),q=Y=>{h(f?Y:Y.isLatest?null:Y)},$=()=>{h(null)},z=!f&&p!=null,Z=()=>{z||b(!0)},K=()=>{z||G(!0)},ne=async()=>{if(!e||!t)return;let Y;try{Y=JSON.parse(x)}catch{Fe.error("Input must be valid JSON");return}let te;if(k.trim())try{te=JSON.parse(k)}catch{Fe.error("Ground Truth must be valid JSON");return}let ue;if(C.trim())try{ue=JSON.parse(C)}catch{Fe.error("Metadata must be valid JSON");return}let fe;const ce=T!==m.trajectory;if(ce&&T.trim())try{fe=JSON.parse(T)}catch{Fe.error("Expected Trajectory must be valid JSON");return}let me;const be=I!==m.toolMocks;if(be&&I.trim())try{const Pe=JSON.parse(I);if(!Array.isArray(Pe)){Fe.error("Tool Mocks must be a JSON array");return}me=Pe}catch{Fe.error("Tool Mocks must be valid JSON");return}let we;const Oe=H!==m.requestContext;if(Oe&&H.trim())try{we=JSON.parse(H)}catch{Fe.error("Request Context must be valid JSON");return}const ke=R!==m.scorerOverrideEnabled||R&&(D.length!==m.scorerIds.length||D.some((Pe,ie)=>Pe!==m.scorerIds[ie])),Ne=R?D:null;try{await l.mutateAsync({datasetId:e,itemId:t,input:Y,groundTruth:te,metadata:ue,...ce?{expectedTrajectory:fe??null}:{},...be?{toolMocks:me??[]}:{},...ke?{scorerIds:Ne}:{},...Oe?{requestContext:we}:{}}),Fe.success("Item updated successfully"),b(!1)}catch(Pe){Fe.error(`Failed to update item: ${Pe instanceof Error?Pe.message:"Unknown error"}`)}},ee=()=>{d&&(S(JSON.stringify(d.input,null,2)),_(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),E(d.metadata?JSON.stringify(d.metadata,null,2):""),N(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),A(d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):""),L(d.scorerIds!==void 0),F(d.scorerIds??[]),B(d.requestContext?JSON.stringify(d.requestContext,null,2):"")),b(!1)},J=async()=>{if(!(!e||!t))try{await c.mutateAsync({datasetId:e,itemId:t}),Fe.success("Item deleted successfully"),G(!1),r(`/datasets/${e}`)}catch(Y){Fe.error(`Failed to delete item: ${Y instanceof Error?Y.message:"Unknown error"}`)}},ae=p??d,pe=ae?{id:t??"",datasetId:e??"",datasetVersion:ae.datasetVersion,input:ae.input,groundTruth:ae.groundTruth,expectedTrajectory:ae.expectedTrajectory,scorerIds:ae.scorerIds,metadata:ae.metadata,createdAt:ae.createdAt,updatedAt:ae.updatedAt}:null;return i&&xs(i)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):i&&Ss(i)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(fs,{children:o.jsx(_y,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Item not found"})})}):o.jsxs(o.Fragment,{children:[o.jsx(fs,{children:o.jsx("div",{className:"h-full overflow-hidden px-6 pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[60rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(zN,{}),t," ",o.jsx(za,{content:t})]}),o.jsx(ha.Description,{children:o.jsxs(Oo,{children:["Item of ",o.jsx(uy,{})," ",u?.name]})}),o.jsxs(ha.Description,{children:[o.jsxs(Oo,{children:[o.jsx(ult,{})," Created at"," ",d?.createdAt?or(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(Oo,{children:[o.jsx(w_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ha.Column,{children:!y&&!f&&o.jsxs(Mr,{children:[o.jsxs(le,{onClick:Z,disabled:z,title:z?"Return to latest version to edit":void 0,children:[o.jsx(Clt,{})," Edit"]}),o.jsxs(le,{onClick:K,disabled:z,title:z?"Return to latest version to delete":void 0,children:[o.jsx(mu,{})," Delete"]})]})})]}),o.jsxs(cy,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Yr,{withRightSeparator:!y,children:[f&&d&&o.jsx(Sn,{variant:"destructive",title:"Item deleted",children:o.jsxs(Sn.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&z&&p&&o.jsx(Sn,{variant:"warning",title:"Previous version",action:o.jsxs(Sn.Button,{onClick:$,children:[o.jsx(alt,{})," Return to the latest version"]}),children:o.jsxs(Sn.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(eVt,{inputValue:x,setInputValue:S,groundTruthValue:k,setGroundTruthValue:_,metadataValue:C,setMetadataValue:E,trajectoryValue:T,setTrajectoryValue:N,toolMocksValue:I,setToolMocksValue:A,scorerOverrideEnabled:R,setScorerOverrideEnabled:L,selectedScorerIds:D,setSelectedScorerIds:F,requestContextValue:H,setRequestContextValue:B,validationErrors:null,onSave:ne,onCancel:ee,isSaving:l.isPending}):pe?o.jsx(TAe,{item:pe,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Yr,{children:o.jsx(qps,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:q,onCompareVersionsClick:Y=>{r(`/datasets/${e}/items/${t}/versions?ids=${Y.join(",")}`)},activeVersion:p?.datasetVersion??null})})]})]})})}),o.jsx(At,{open:M,onOpenChange:G,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Item"}),o.jsx(At.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:J,children:c.isPending?"Deleting...":"Delete"})]})]})})]})}function wet(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function lhs(){const{datasetId:e}=Sr(),[t,n]=si(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=r0(e??""),{Link:i}=xn(),[l,c]=g.useState(!1),{data:u}=ZV(e??"",r[0]??""),{data:d}=ZV(e??"",r[1]??"");return a&&xs(a)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):a&&Ss(a)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})}):!e||r.length<2?o.jsx(fs,{children:o.jsx(_y,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(fs,{children:[o.jsx(My,{owner:"dataset-items-compare",children:o.jsxs(le,{as:ni,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(Rc,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:X("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":l}),children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(r1,{}),"Compare Dataset Items"]}),o.jsx(ha.Description,{children:o.jsxs(Oo,{children:["Comparing ",r.length," items of"," ",o.jsx(ni,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ha.Column,{children:o.jsx(Mr,{children:o.jsx(le,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(Mxe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(AGt,{})," Diff View"]})})})})]}),o.jsx(cy,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(g.Fragment,{children:[o.jsx(chs,{datasetId:e,itemId:f,Link:i,idx:p,itemIds:r,showContent:!l,onItemChange:h=>{const m=[...r];m[p]=h,n({items:m.join(",")})}}),p==0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},f))}),l&&u&&d&&o.jsx(ZTe,{codeA:wet(u),codeB:wet(d)})]})})]})}function chs({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=ZV(e,t),{data:u}=z1(e),d=new Set(s.filter((p,h)=>h!==r)),f=(u??[]).map(p=>({value:p.id,label:p.id,disabled:d.has(p.id)}));return o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{className:"flex gap-4",children:[o.jsxs(ma,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(va,{"aria-label":"Item",children:o.jsx(ga,{placeholder:"Select item"})}),o.jsx(ya,{children:f.map(p=>o.jsx(Rr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(le,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(w_,{}),"Versions"]})]}),i&&o.jsx(Yr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Sps,{item:l}),o.jsx(TAe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function ket(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,scorerIds:e.scorerIds??null,metadata:e.metadata??null},null,2)}function uhs(){const{datasetId:e,itemId:t}=Sr(),[n,r]=si(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=r0(e??""),{Link:u}=xn(),{data:d}=OAe(e??"",t??""),{data:f}=vxe(e??"",t??"",i[0]??0,l?.version),{data:p}=vxe(e??"",t??"",i[1]??0,l?.version);return c&&xs(c)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):c&&Ss(c)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(fs,{children:o.jsx(_y,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(fs,{children:[o.jsx(My,{owner:"dataset-item-versions-compare",children:o.jsxs(le,{as:ni,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(Rc,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:X("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(r1,{}),"Compare Dataset Item Versions"]}),o.jsx(ha.Description,{children:o.jsxs(Oo,{children:["Comparing ",i.length," versions of"," ",o.jsx(ni,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ha.Column,{children:o.jsx(Mr,{children:o.jsx(le,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(Mxe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(vQt,{})," Diff View"]})})})})]}),o.jsx(cy,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(dhs,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(ZTe,{codeA:ket(f),codeB:ket(p)})]})})]})}function dhs({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=vxe(e,t,n,r),p=new Set(a.filter((v,y)=>y!==l)),h=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",or(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(ea,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,scorerIds:d.scorerIds,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(w_,{className:"h-6 w-6 opacity-50"}),o.jsxs(ma,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(va,{"aria-label":"Version",className:"w-full",children:o.jsx(ga,{placeholder:"Select version"})}),o.jsx(ya,{children:h.map(v=>o.jsx(Rr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(Yr.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(TAe,{item:m,Link:i})})]})}function fhs(){const{datasetId:e}=Sr(),[t]=si(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=Ws(),{data:s,error:a}=r0(e??""),i=z1(e??"",void 0,n[0]??null),l=z1(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),p=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&xs(a))return o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})});if(a&&Ss(a))return o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(fs,{children:o.jsx(_y,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(fs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(iKt,{})," Compare Dataset Versions"]}),o.jsx(ha.Description,{children:o.jsxs(Oo,{children:[o.jsx(w_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ha.Column,{children:o.jsxs(le,{as:ni,to:`/datasets/${e}`,children:[o.jsx(Rc,{}),"Back to Dataset"]})})]}),o.jsx(cy,{children:o.jsxs(Yr,{children:[o.jsx(Zps,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(Kps,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function yxe({children:e,className:t}){return o.jsx("div",{className:X("flex flex-wrap gap-8",t),children:e})}function phs(e){if(!e||e.length<2)return null;const t=[...e].sort((i,l)=>new Date(i.createdAt).getTime()-new Date(l.createdAt).getTime()),n=Math.floor(t.length/2),r=n,s=t.length-n;if(r===0)return null;const a=(s-r)/r*100;return{changePct:Math.round(a*10)/10,prevValue:String(r)}}function hhs({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=phs(n);return o.jsxs(o.Fragment,{children:[o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Scorers"}),i?o.jsx(es.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(f)}),o.jsx(es.NoChange,{message:"Static count"})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Datasets"}),l?o.jsx(es.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(p)}),o.jsx(es.NoChange,{message:"Static count"})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Avg Score"}),u?o.jsx(es.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(r)}),m?o.jsx(es.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(es.NoChange,{})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Experiments"}),c?o.jsx(es.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(h)}),v?o.jsx(es.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(es.NoChange,{})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Needs Review"}),d?o.jsx(es.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(a)}),a>0?o.jsx(es.NoChange,{message:"items pending review"}):o.jsx(es.NoChange,{message:"All caught up"})]}):o.jsx(es.NoData,{})]})]})}const Oet="minmax(9rem,1fr) 1fr auto auto auto auto auto auto auto";function mhs(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const ghs={completed:"success",running:"warning",failed:"error",pending:"neutral"};function vhs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=xn(),u=g.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=g.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=g.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",v=!p||h.id.toLowerCase().includes(p)||(h.name??"").toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return v&&y&&b})},[d,s,u,a,i]);return r?o.jsx(ol,{columns:Oet}):o.jsxs(ge,{columns:Oet,variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Experiment"}),o.jsx(ge.TopCell,{children:"Dataset"}),o.jsx(ge.TopCell,{children:"Target"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{className:"text-center",children:"Items"}),o.jsx(ge.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(ge.TopCell,{className:"text-center",children:"Failed"}),o.jsx(ge.TopCell,{className:"text-center",children:"Review"}),o.jsx(ge.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??lS(p.datasetId)??p.datasetId:"—",m=p.status??"pending",v=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,x=b>0?Math.round(v/b*100):0;return o.jsxs(ge.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(ge.Cell,{children:o.jsx(KUt,{experiment:p})}),o.jsx(ge.TextCell,{children:h}),o.jsx(ge.Cell,{children:o.jsxs("span",{className:"truncate",children:[p.targetType," ",p.targetId]})}),o.jsx(ge.Cell,{children:o.jsx(kg,{variant:ghs[m]??"neutral",withDot:!0,children:m})}),o.jsx(ge.TextCell,{className:"text-center",children:b}),o.jsx(ge.TextCell,{className:"text-center",children:o.jsxs("span",{className:v>0?"text-accent1":"",children:[v," (",x,"%)"]})}),o.jsx(ge.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(ge.Cell,{className:"text-center",children:(()=>{const S=n?.get(p.id);if(!S)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=S.needsReview+S.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):S.needsReview>0?o.jsxs(ea,{size:"small",color:"yellow",children:[S.needsReview," pending"]}):o.jsxs(ea,{size:"small",color:"green",children:[S.complete,"/",k," reviewed"]})})()}),o.jsx(ge.TextCell,{children:mhs(p.createdAt)})]},p.id)})]})}const yhs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function bhs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const Pz={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},xhs=[{label:"Completed",color:Pz.completed},{label:"Running",color:Pz.running},{label:"Pending",color:Pz.pending},{label:"Failed",color:Pz.failed}];function whs({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Gt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Gt.Loading,{}):r?o.jsx(Gt.Error,{message:"Failed to load experiments data"}):o.jsx(Gt.Content,{children:i?o.jsx(RN,{data:s,segments:xhs,maxVal:a,fmt:l=>String(l)}):o.jsx(Gt.NoData,{message:"No experiments have been run yet"})})]})}const Shs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Df,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsx("div",{className:"flex flex-col items-center gap-2",children:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Oa,{})]})})})});function khs({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(Uf,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs(Mr,{children:[o.jsx(Cc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...yhs],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Cc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(le,{onClick:l,size:"sm",variant:"default",children:[o.jsx(ws,{className:"size-3"})," Reset"]})]})]})}function Ohs(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=uh(),{data:l,isLoading:c,error:u}=qg(),{data:d,isLoading:f,error:p}=_Q(),{data:h,isLoading:m,isError:v,error:y}=Hrs(n),{data:b,isLoading:x,isError:S,error:k}=IAe(),_=l?.datasets,C=d?.experiments,E=g.useMemo(()=>ths(b),[b]),T=i||u||p||y||k;return T&&xs(T)?o.jsx(cr,{children:o.jsx(Zs,{})}):T&&Ss(T)?o.jsx(cr,{children:o.jsx($s,{resource:"evaluation"})}):T?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load evaluation data",message:T.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{children:o.jsx(h4,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(N,I)=>r(A=>I==="from"?{...A,start:N}:{...A,end:N})})})})}),o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(yxe,{children:o.jsx(hhs,{scorers:s,datasets:_,experiments:C,avgScore:h?.avgScore??null,prevAvgScore:h?.prevAvgScore??null,totalNeedsReview:E.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(trs,{summaryData:h?.summaryData??[],overTimeData:h?.overTimeData??[],scorerNames:h?.scorerNames??[],avgScore:h?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(rfs,{experiments:C,isLoading:f,isError:!!p}),o.jsx(whs,{experiments:C,datasets:_,isLoading:f,isError:!!p})]}),o.jsx(Jps,{reviewSummary:b,experiments:C,datasets:_,isLoading:x,isError:!!S})]})]})}function _hs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState("all"),{data:i,isLoading:l,error:c}=qg(),{data:u,isLoading:d,error:f}=_Q(),{data:p}=IAe(),h=g.useMemo(()=>i?.datasets??[],[i?.datasets]),m=g.useMemo(()=>u?.experiments??[],[u?.experiments]),v=g.useMemo(()=>bhs(h),[h]),y=g.useMemo(()=>sVt(p),[p]),b=l||d,x=f||c;if(x&&xs(x))return o.jsx(cr,{children:o.jsx(Zs,{})});if(f&&Ss(f))return o.jsx(cr,{children:o.jsx($s,{resource:"experiments"})});if(c&&Ss(c))return o.jsx(cr,{children:o.jsx($s,{resource:"datasets"})});if(x)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load experiments",message:x.message})});if(m.length===0&&!b)return o.jsx(cr,{children:o.jsx(Shs,{})});const S=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(khs,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:v,onReset:k,hasActiveFilters:S})}),o.jsx(vhs,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function $z({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function Chs(){const{experimentId:e}=Sr(),{data:t,isLoading:n}=_Q(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=WV(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=oQ({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&xs(l)?o.jsx($z,{children:o.jsx(Zs,{})}):l&&Ss(l)?o.jsx($z,{children:o.jsx($s,{resource:"datasets"})}):l&&CEe(l)||!n&&!s||!i&&!l&&!a?o.jsx($z,{children:o.jsx(Lr,{iconSlot:o.jsx($xe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(le,{as:ni,to:"/experiments",children:[o.jsx(Rc,{}),"Back to Experiments"]})})}):l?o.jsx($z,{children:o.jsx(Hi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Vt,{height:"full",children:[o.jsx(aVt,{experiment:a}),o.jsx(Vt.MainArea,{children:o.jsx(rVt,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function Ehs({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"font-mono text-xs",children:e.connectionId}),o.jsxs("div",{className:"text-xs text-gray-500",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),o.jsx("button",{type:"button",className:"text-red-600 underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function iVt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Ehs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Ths({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,a])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(iVt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function jhs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:a,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-lg font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):a?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):i?o.jsx("p",{className:"text-red-600",children:String(i)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(Ths,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(iVt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Nhs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>p(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>h(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const _et=e=>e.authorId?.trim()||"shared",Ihs=(e,t)=>{if(!t||new Set(e.map(_et)).size<=1)return null;const r=new Map;for(const a of e){const i=_et(a);r.set(i,[...r.get(i)??[],a])}const s=Array.from(r.entries());return s.sort(([a],[i])=>a==="shared"?1:i==="shared"?-1:a.localeCompare(i)),s},Ahs=["*","tool-providers:*","tool-providers:admin"];function Rhs(){const{data:e}=Nm();return e?.permissions?.some(t=>Ahs.includes(t))??!1}function Phs(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=BI(),l=NZ(e||null),c=oDt(e||null,n||null),u=iDt(),d=rDt(),f=Rhs(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>Ihs(m,f),[m,f]),y=S=>{t(S),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=S=>{d.mutate({providerId:e,connectionId:S})};return o.jsxs("div",{className:"p-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(Nhs,{providers:p,toolkits:h,providerId:e,toolkit:n,label:s,providersLoading:i.isLoading,providersError:i.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:a,onConnect:b}),o.jsx(jhs,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function $hs({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsxs("div",{className:"w-full max-w-sm space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[o.jsx(rm,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function oVt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=oc(),{mutate:i,isPending:l,error:c}=OAr(),{mutate:u,isPending:d,error:f}=CAr(),{mutate:p,isPending:h}=f$t(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,S]=g.useState(""),[k,_]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,E=C.type==="sso"||C.type==="both",T=C.type==="credentials"||C.type==="both",N=C.sso,I=C.signUpEnabled!==!1,A=m==="signin"||!I,R=A?l:d,L=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=cQ("/")},F=M=>{M.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},B=()=>{v(A?"signup":"signin")},U=C.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Nf,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:C.description})]}):null,V=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs($hs,{title:A?"Sign in to Mastra Studio":"Create your account",description:U,errorBanner:V,children:[T&&o.jsxs("form",{onSubmit:F,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 block text-sm",children:"Name"}),o.jsx(En,{id:"name",type:"text",value:y,onChange:M=>b(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"text-neutral4 block text-sm",children:"Email"}),o.jsx(En,{id:"email",type:"email",value:x,onChange:M=>S(M.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"text-neutral4 block text-sm",children:"Password"}),o.jsx(En,{id:"password",type:"password",value:k,onChange:M=>_(M.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:L.message}),o.jsx(le,{type:"submit",disabled:R,className:"w-full",size:"lg",children:R?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:B,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),E&&T&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),E&&N&&o.jsxs(le,{onClick:H,disabled:h,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),h?"Redirecting...":N.text||"Sign in"]})]})}function Mhs(){const[e]=si(),t=Ws(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",a=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(oVt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}function Dhs({collapsed:e,children:t}){return o.jsx("section",{className:X("flex flex-col overflow-hidden rounded-xl border border-border1 bg-surface2",e?"h-auto":"h-full"),children:t})}function Lhs({onClick:e,tooltip:t="Close panel",className:n}){return o.jsx(le,{size:"md",onClick:e,"aria-label":"Close Panel",tooltip:t,className:n,children:o.jsx(fu,{})})}function Fhs(){return fI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[he.className,he.propertyName]}]})}function zhs(){const e=It.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.75rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-activeLineGutter":{backgroundColor:"transparent"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"}}),t=Hg.define([{tag:[he.comment,he.bracket],color:"var(--neutral2)"},{tag:[he.string,he.meta,he.regexp],color:"var(--accent1)"},{tag:[he.atom,he.bool,he.special(he.variableName)],color:"var(--accent6)"},{tag:[he.keyword,he.operator,he.tagName],color:"var(--accent2)"},{tag:[he.function(he.propertyName),he.propertyName],color:"var(--accent5)"},{tag:[he.definition(he.variableName),he.function(he.variableName),he.className,he.attributeName],color:"var(--accent3)"},{tag:[he.variableName,he.number],color:"var(--accent5)"},{tag:[he.name,he.quote],color:"var(--accent1)"}]);return[e,eS(t)]}const Bhs=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?Fhs():zhs(),[e])};function Uhs({codeStr:e="",title:t,icon:n,simplified:r=!1,className:s}){const a=Bhs(),[i,l]=g.useState(!1),c=g.useMemo(()=>{try{const f=JSON.parse(e);return bxe(f||"")}catch{return!1}},[e]),u=i?e?.replace(/\\n/g,`
|
|
641
641
|
`):e,d=r||i;return!e||e==="null"?null:o.jsxs("div",{className:X("flex flex-col gap-2",s),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:X("flex items-center gap-1.5 text-ui-xs tracking-widest text-neutral2 uppercase","[&>svg]:size-3.5"),children:[n,t]}),o.jsxs(Mr,{children:[o.jsx(za,{content:e||"No content",size:"sm"}),c&&o.jsx(le,{size:"sm","aria-label":i?"Show escaped newlines":"Show multiline text",onClick:()=>l(f=>!f),children:i?o.jsx(L$,{}):o.jsx(j7,{})})]})]}),o.jsx("div",{className:"border-border1 bg-surface3 text-ui-sm text-neutral4 max-h-[30vh] overflow-hidden overflow-y-auto rounded-lg border p-3 break-all dark:border-white/10 dark:bg-black/20",children:d?o.jsx("div",{className:"text-neutral4 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:u})}):o.jsx(Yu,{extensions:[Lj(),It.lineWrapping],theme:a,value:e,editable:!1})})]})}function bxe(e){if(typeof e=="string"){const t=e.indexOf(`
|
|
642
|
-
`);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>bxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>bxe(t))}return!1}function Vhs({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function qhs({className:e,children:t}){return o.jsx("div",{className:X("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function Hhs({className:e,children:t}){return o.jsx("h3",{className:X("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function Whs({className:e,children:t}){return o.jsx("dl",{className:X("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function Zhs({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function Ghs({className:e,children:t}){return o.jsx("dd",{className:X("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function Qhs({className:e,children:t}){return o.jsx("dt",{className:X("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const Yhs=Object.assign(Whs,{Key:Zhs,Value:Ghs,Header:Qhs});function Khs({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(en,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function Xhs({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const Bi=Object.assign(Dhs,{Header:qhs,Heading:Hhs,CloseButton:Lhs,LoadingData:Khs,NoData:Xhs,Content:Vhs,KeyValueList:Yhs,CodeSection:Uhs}),hp=Bi.KeyValueList;function Jhs(e){return e instanceof Date?e:new Date(e)}function ems({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=Jhs(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Bi,{collapsed:d,children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Log ",o.jsx("b",{children:or(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(uH,{}):o.jsx(w1e,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(le,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(lH,{})}),o.jsx(le,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(c3,{})})]}),o.jsx(Bi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Bi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:X("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(N7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(za,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(N7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(za,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(hp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Entity Type"}),o.jsx(hp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Entity Name"}),o.jsx(hp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Service"}),o.jsx(hp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Environment"}),o.jsx(hp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Source"}),o.jsx(hp.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(hp.Key,{children:v}),o.jsx(hp.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Bi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function tms({error:e,resource:t,errorTitle:n}){if(xs(e))return o.jsx(Zs,{});if(Ss(e))return o.jsx($s,{resource:t});if(v4(e))return o.jsx(Lr,{iconSlot:o.jsx(I7,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(g4(e,"logs"))return o.jsx(Lr,{iconSlot:o.jsx(I7,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Hi,{title:n,message:r??"Unknown error"})}function nms({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:X("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const rms={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function sms({level:e}){const t=rms[e];return o.jsx(jo,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function ams({entityType:e,className:t}){const n=X("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Vo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(td,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Bd,{className:n,"aria-hidden":!0});default:return null}}function ims({entityType:e,entityName:t}){const n=e??"";return o.jsxs(jo,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(ams,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function oms({message:e}){return o.jsx(jo,{height:"compact",className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function lms({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(jo,{height:"compact",children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(yTe,{children:t})}const Ql=Object.assign(C4,{Top:DZ,TopCell:cC,TopCellWithTooltip:LZ,TopCellSmart:GDt,RowWrapper:STe,RowButton:E4,RowLink:ZDt,Spacer:kTe,NoMatch:MZ,DateCell:bTe,TimeCell:xTe,LevelCell:sms,EntityCell:ims,MessageCell:oms,DataCell:lms,NextPageLoading:$Z}),Cet="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",cms=36,ums=8;function dms({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=LUt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>cms,overscan:ums}),d=g.useRef(t);if(g.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ol,{columns:Cet});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Ql,{columns:Cet,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ql.Top,{children:[o.jsx(Ql.TopCell,{children:"Date"}),o.jsx(Ql.TopCell,{children:"Time"}),o.jsx(Ql.TopCell,{children:"Level"}),o.jsx(Ql.TopCell,{children:"Entity"}),o.jsx(Ql.TopCell,{children:"Message"}),o.jsx(Ql.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ql.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ql.Spacer,{height:h}),f.map(v=>{const y=e[v.index];if(!y)return null;const b=a.get(y);if(!b)return null;const x=b===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":v.index,onClick:()=>l(y),featured:x,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Ql.DateCell,{timestamp:y.timestamp}),o.jsx(Ql.TimeCell,{timestamp:y.timestamp}),o.jsx(Ql.LevelCell,{level:y.level}),o.jsx(Ql.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Ql.MessageCell,{message:y.message}),o.jsx(Ql.DataCell,{data:y.data})]},b)}),o.jsx(Ql.Spacer,{height:m})]}),o.jsx(Ql.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function fms({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>pms(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(cAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(oAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function pms(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}const hms={"last-24h":"the last 24 hours","last-3d":"the last 3 days","last-7d":"the last 7 days","last-14d":"the last 14 days","last-30d":"the last 30 days"},pie="MMM d, yyyy HH:mm",hie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function mms({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${hms[e]}`,description:hie}:t&&n?{title:`No logs between ${or(t,pie)} and ${or(n,pie)}`,description:hie}:t?{title:`No logs since ${or(t,pie)}`,description:hie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const gms=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=mms({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(I7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(k1e,{})]})})})},vms=20,yms=1e4;function bms(e,t,n){if(e?.pagination?.hasMore)return n+1}function xms(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function wms(e){return g4(e.state.error,"logs")||v4(e.state.error)?!1:yms}const Sms=({filters:e}={})=>{const t=Ze(),{inView:n,setRef:r}=Q_(),s=G1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:vms},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:bms,select:xms,retry:!1,refetchInterval:wms}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},Mz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},lVt=[{label:"Agent",entityType:Mz.AGENT},{label:"Workflow",entityType:Mz.WORKFLOW},{label:"Scorer",entityType:Mz.SCORER},{label:"Ingest",entityType:Mz.INGEST}],kms=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Gx="rootEntityType",Xb="datePreset",Jb="dateFrom",ex="dateTo",Oms=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Nl={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},OL=Object.keys(Nl),AAe=new Set(["tags"]),RAe="mastra:logs:saved-filters";function _ms(e,t=RAe){const n=Nms(e),r=e.get(Xb);r&&n.set(Xb,r);const s=e.get(Jb);s&&n.set(Jb,s);const a=e.get(ex);a&&n.set(ex,a);try{localStorage.setItem(t,n.toString())}catch{}}function Cms(e=RAe){try{localStorage.removeItem(e)}catch{}}function Eet(e=RAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Ems(e){if(e.has(Xb)||e.has(Jb)||e.has(ex)||e.has(Gx))return!0;for(const t of OL)if(e.has(Nl[t]))return!0;return!1}function Tms({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:lVt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"level",label:"Level",kind:"pick-multi",searchable:!1,options:kms.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function jms(e){const t=[],n=new Map([[Gx,"rootEntityType"]]);for(const s of OL)n.set(Nl[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),AAe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Nms(e){const t=new URLSearchParams,n=e.get(Gx);n&&t.set(Gx,n);for(const r of OL){const s=Nl[r];if(AAe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function Ims(e,t){e.delete(Gx);for(const n of OL)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Gx,n.value);continue}const r=Nl[n.fieldId];if(r){if(AAe.has(n.fieldId)&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function Ams({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function Rms(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}const Pms="Filters setting for Logs saved",$ms="Filters setting for Logs cleared up";function Mms(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Eet(r)!==null),c=g.useCallback(()=>{_ms(e,r),l(!0);const f=s?.saved??Pms;f!==!1&&Fe.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Cms(r),l(!1);const f=s?.cleared??$ms;f!==!1&&Fe.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Ems(e)))return;const f=Eet(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Dms(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function Lms(e){const t=new Map;for(const n of e){if(n.logId){t.set(n,n.logId);continue}const r=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,Dms(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Fms(e,t,n,r){const s=g.useMemo(()=>Lms(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const xxe="logId",wxe="traceId",Sxe="spanId",hP=1440*60*1e3,zms={"last-24h":hP,"last-3d":3*hP,"last-7d":7*hP,"last-14d":14*hP,"last-30d":30*hP};function Dz(e){e.delete(xxe),e.delete(wxe),e.delete(Sxe)}function Bms(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(Xb);return _&&Oms.has(_)?_:"last-24h"},[e]),a=e.get(Jb),i=e.get(ex),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=zms[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(xxe),f=e.get(wxe),p=e.get(Sxe),h=g.useMemo(()=>lVt.find(_=>_.entityType===e.get(Gx)),[e]),m=g.useMemo(()=>jms(e),[e]),v=g.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);for(const[T,N]of Object.entries(_)){const I=T==="logId"?xxe:T==="traceId"?wxe:Sxe;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);return Ims(E,_),Dz(E),E},{replace:!0})},[t]),b=y,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const E=C==="from"?Jb:ex;t(T=>{const N=new URLSearchParams(T);return _?N.set(E,_.toISOString()):N.delete(E),Dz(N),N},{replace:!0})},[t]),S=g.useCallback(_=>{u.current=_,t(C=>{const E=new URLSearchParams(C);return _==="last-24h"?(E.delete(Xb),E.delete(Jb),E.delete(ex)):_==="custom"?E.set(Xb,"custom"):(E.set(Xb,_),E.delete(Jb),E.delete(ex)),Dz(E),E},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(Gx);for(const E of OL)C.delete(Nl[E]);return C.delete(Xb),C.delete(Jb),C.delete(ex),Dz(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,x,S,k,y])}const _b=Bi.KeyValueList;function Ums({spanId:e,span:t,isLoading:n,onClose:r}){const s=OQ(t?.startedAt,t?.endedAt),a=KV(t?.startedAt),i=KV(t?.endedAt);return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading span..."}):t?o.jsxs(Bi.Content,{children:[o.jsxs(_b,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(_b.Key,{children:"Type"}),o.jsx(_b.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(_b.Key,{children:"Started"}),o.jsx(_b.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(_b.Key,{children:"Ended"}),o.jsx(_b.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(_b.Key,{children:"Duration"}),o.jsx(_b.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Bi.CodeSection,{title:"Input",icon:o.jsx(eme,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Output",icon:o.jsx(tme,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Metadata",icon:o.jsx(Tw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Attributes",icon:o.jsx(Tw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Bi.NoData,{children:"Span not found."})]})}function Vms({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>pAe(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(fAe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Bi.NoData,{children:"No spans found for this trace."}):o.jsx(Bi.Content,{children:o.jsx($Ut,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function qms(){const[e,t]=si(),n=Bms(e,t),r=Mms(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=xAe(),{data:d=[],isPending:f}=vAe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=yAe(),{data:m=[],isPending:v}=bAe(),y=g.useMemo(()=>Tms({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>Ams({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E}=Sms({filters:b}),{logIdMap:T,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Fms(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=wAe(n.featuredTraceId??null),{data:F,isLoading:H}=kL(n.featuredTraceId??"",n.featuredSpanId??""),B=g.useCallback(()=>n.applyFilterTokens(Rms(y,n.filterTokens)),[y,n]),U=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),M=g.useCallback((K,ne)=>n.handleFeaturedChange({traceId:K,spanId:ne}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),q=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),z=o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(h4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(uAe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(fms,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:B,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(tms,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(gms,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(nms,{logCollapsed:i,listSlot:o.jsx(dms,{logs:x,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E,logIdMap:T,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(ems,{log:N,onClose:U,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Vms,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(Ums,{spanId:n.featuredSpanId,span:F?.span,isLoading:H,onClose:q}):null})]})}function Hms({server:e}){const{paths:t,Link:n}=xn(),s=Ze().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=i7t(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=Yh(e.name,50);return o.jsxs(ge.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(ge.NameCell,{children:f}),o.jsx(ge.DescriptionCell,{children:a}),o.jsx(ge.TextCell,{className:"text-center",children:u||""}),o.jsx(ge.TextCell,{className:"text-center",children:c||""}),o.jsx(ge.TextCell,{className:"text-center",children:d||""})]})}function Wms({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ol,{columns:"auto 1fr auto auto auto"}):o.jsxs(ge,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"URL"}),o.jsx(ge.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ge.TopCellSmart,{long:"Tools",short:o.jsx(Bd,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ge.TopCellSmart,{long:"Workflows",short:o.jsx(td,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ge.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(Hms,{server:s},s.id))]})}const Zms=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Df,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Oa,{})]})})}),Gms=()=>{const{data:e=[],isLoading:t,error:n}=eQ(),[r,s]=g.useState("");return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"MCP servers"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(cr,{children:o.jsx(Zms,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Uf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(Wms,{mcpServers:e,isLoading:t,search:r})]})},Qms=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function Yms({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=xn(),i=g.useMemo(()=>Qms(e,t),[e,t]),l=g.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ol,{columns:"auto 1fr auto"}):o.jsxs(ge,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"Description"}),o.jsx(ge.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ge.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=Yh(c.id,50),d=Yh(c.description??"",200),f=c.agents.length;return o.jsxs(ge.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(ge.NameCell,{children:u}),o.jsx(ge.DescriptionCell,{children:d}),o.jsx(ge.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Kms=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Df,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Oa,{})]})})}),Xms=()=>{const e=Ze();return Dn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new j_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Fe.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Jms=({toolId:e})=>{const{canExecute:t}=Wo(),n=t("tools"),{data:r={}}=Im(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=MIr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=Xms(),{requestContext:p}=ps();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Fe.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?hm(Tx(c?.inputSchema)):vs({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(St,{className:"mb-4 h-8 w-48"}),o.jsx(St,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(LIe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function egs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=FI(),{data:p={},isLoading:h,isError:m,error:v}=Im(),{navigate:y,paths:b}=xn();g.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";Fe.error(`Error loading tools: ${_}`)}},[d,f]),g.useEffect(()=>{if(m){const _=v instanceof Error?v.message:"Failed to load agents";Fe.error(`Error loading agents: ${_}`)}},[m,v]);const x=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{x.has(C.id)||x.set(C.id,C)})}),Object.values(c).forEach(_=>{x.has(_.id)||x.set(_.id,_)});const S=Array.from(x.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(Ll,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const tgs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(_y,{children:o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(_y,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(ln,{icon:o.jsx(AUt,{className:"text-neutral6"}),className:"text-neutral4! rounded-r-sm",children:"Version"}),o.jsx(ln,{className:"text-neutral4! rounded-l-sm",children:t.version_detail.version})]}),o.jsx(ye,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(ngs,{server:t})})]})},ngs=({server:e})=>{const{data:t={},isLoading:n}=i7t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(vC,{})}),o.jsx(ye,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(sgs,{tool:a,serverId:e.id},s)})})]})};function rgs(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const sgs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=xn(),a=$7t[e.toolType||"tool"],i=rgs(e._meta);return o.jsxs(qf,{onClick:()=>n.current?.click(),children:[o.jsx(aDt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Wf,{children:[o.jsx(Hf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(ln,{className:"py-0 text-[10px]",children:"App"})]})}),o.jsx(ah,{children:e.description})]})]})},ags=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=eQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(tgs,{isLoading:n,server:r})})};function igs(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const ogs=({toolId:e,serverId:t})=>{const{canExecute:n}=Wo(),r=n("tools"),s=Ze(),{data:a,isLoading:i,error:l}=IIe(t,e),{mutateAsync:c,isPending:u,data:d}=Hes(t,e),f=a?igs(a._meta):void 0,{data:p}=gt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Fe.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(St,{className:"mb-4 h-8 w-48"}),o.jsx(St,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=hm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Fe.error("Failed to process tool input schema."),v=vs({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(a7t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(LIe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},lgs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=IIe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(ogs,{toolId:t,serverId:e})})},cVt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],PN="rootEntityType",$N={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},CQ=Object.keys($N),PAe="mastra:metrics:saved-filters";function cgs(e){const t=hgs(e);try{localStorage.setItem(PAe,t.toString())}catch{}}function ugs(){try{localStorage.removeItem(PAe)}catch{}}function uVt(){try{const e=localStorage.getItem(PAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function dgs(e){if(e.has(PN))return!0;for(const t of CQ)if(e.has($N[t]))return!0;return!1}function fgs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:cVt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function pgs(e){const t=[],n=new Map([[PN,"rootEntityType"]]);for(const s of CQ)n.set($N[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function hgs(e){const t=new URLSearchParams,n=e.getAll(PN);for(const r of n)t.append(PN,r);for(const r of CQ){const s=$N[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function mgs(e,t){e.delete(PN);for(const n of CQ)e.delete($N[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?PN:$N[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const ggs="Any";function Tet(e){const t=e.trim();return t===""||t===ggs}const vgs=new Set(cVt.map(e=>e.entityType));function jet(e){const t=e.trim();return vgs.has(t)?t:void 0}function ygs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Tet(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?jet(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Tet(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=jet(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const dVt=[{label:"Last 24 hours",value:"24h"},{label:"Last 3 days",value:"3d"},{label:"Last 7 days",value:"7d"},{label:"Last 14 days",value:"14d"},{label:"Last 30 days",value:"30d"}],bgs=new Set(dVt.map(e=>e.value));function xgs(e){return typeof e=="string"&&(bgs.has(e)||e==="custom")}const fVt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function EQ(){return g.useContext(fVt)}function wgs(e,t){return e!=="custom"?dVt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${or(t.from,"MMM d, yyyy")} – ${or(t.to,"MMM d, yyyy")}`:or(t.from,"MMM d, yyyy"):"Custom range"}function Sgs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>ygs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=wgs(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(fVt.Provider,{value:m,children:e})}const kgs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Ogs(e){switch(e){case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return"last-24h"}}function _gs(e){switch(e){case"last-3d":return"3d";case"last-7d":return"7d";case"last-14d":return"14d";case"last-30d":return"30d";case"custom":return"custom";default:return"24h"}}function Cgs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=EQ(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(h4,{preset:Ogs(e),onPresetChange:i=>{const l=_gs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:kgs})}const kxe=1440*60*1e3,Egs={"24h":kxe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Tgs(e,t,n){if(e!=="custom"){const r=Egs[e]??kxe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-kxe),end:t?.to??new Date(n)}}function $m(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=EQ(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>Tgs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function pVt(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function _L({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(BNn,{})})}function jgs({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(kIn,{})})}const Ngs=[{dataKey:"p50",label:"p50",color:qp.blue,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p50,0)/e.length)}`:"0",suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:qp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function Igs(e){return e==="agents"||e==="workflows"||e==="tools"}function mie({data:e,onPointClick:t}){return e.length===0?o.jsx(Gt.NoData,{message:"No latency data yet"}):o.jsx(qV,{data:e,series:Ngs,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function Ags({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Gt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Gt.Actions,{children:h}):null]}),t?o.jsx(Gt.Loading,{}):n?o.jsx(Gt.Error,{message:"Failed to load latency data"}):o.jsx(Gt.Content,{children:m?o.jsxs(pc,{value:p,onValueChange:b=>{Igs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(jr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(jr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(mie,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(mie,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(mie,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Gt.NoData,{message:"No latency data yet"})})]})}function Rgs(e){switch(e){case"24h":return"last-24h";case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return}}function Pgs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function hVt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=Rgs(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function mVt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Net({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set($w,"branches"),hVt(a,Mw,Dw,Lw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Wx,i),r.status&&a.set(Zx,r.status),$o(a,jl.entityName,r.entityName??n.entityName),$o(a,jl.threadId,r.threadId??n.threadId),$o(a,jl.resourceId,r.resourceId??n.resourceId),$o(a,jl.entityId,n.entityId),$o(a,jl.runId,n.runId),$o(a,jl.sessionId,n.sessionId),$o(a,jl.requestId,n.requestId),$o(a,jl.userId,n.userId),$o(a,jl.organizationId,n.organizationId),$o(a,jl.experimentId,n.experimentId),$o(a,jl.serviceName,n.serviceName),$o(a,jl.environment,n.environment),mVt(a,jl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function $gs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;hVt(a,Xb,Jb,ex,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Gx,i),$o(a,Nl.entityName,r.entityName??n.entityName),$o(a,Nl.threadId,r.threadId??n.threadId),$o(a,Nl.resourceId,r.resourceId??n.resourceId),$o(a,Nl.runId,n.runId),$o(a,Nl.sessionId,n.sessionId),$o(a,Nl.requestId,n.requestId),$o(a,Nl.userId,n.userId),$o(a,Nl.organizationId,n.organizationId),$o(a,Nl.experimentId,n.experimentId),$o(a,Nl.serviceName,n.serviceName),$o(a,Nl.environment,n.environment),mVt(a,Nl.tags,n.tags),r.status==="error"&&a.append(Nl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function rA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=EQ(),a=g.useCallback((c={})=>Net({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>$gs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=Pgs(u,d);return Net({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const gVt="1h";async function gie(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:gVt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function Mgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([gie(e,"mastra_agent_duration_ms",t),gie(e,"mastra_workflow_duration_ms",t),gie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:gVt}}})}const Iet={agents:Ec.AGENT,workflows:Ec.WORKFLOW_RUN,tools:Ec.TOOL};function Dgs(){const{data:e,isLoading:t,isError:n}=Mgs(),{getTracesHref:r,getBucketTracesHref:s}=rA(),{Link:a}=xn(),i=Ws();return o.jsx(Ags,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Iet[l]},c.tsMs,"1h"))},actions:l=>o.jsx(_L,{href:r({rootEntityType:Iet[l]}),LinkComponent:a})})}function Lgs(e){return e==="threads"||e==="resources"}function vie(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Fgs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Gt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Gt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Gt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Gt.Loading,{}):m.isError?o.jsx(Gt.Error,{message:"Failed to load memory data"}):o.jsx(Gt.Content,{children:o.jsxs(pc,{defaultTab:"threads",value:i,onValueChange:y=>{Lgs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"threads",children:"Threads"}),o.jsx(jr,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(ge,{columns:"auto auto auto auto auto",...pxe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:vie(y.threadId)}),o.jsx(ge.NumberCell,{children:y.resourceId?vie(y.resourceId):"—"}),o.jsx(ge.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ge.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(ge.NumberCell,{children:y.cost!=null?Vp(y.cost,y.costUnit):"—"})]});return b?o.jsx(ge.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ge.RowStatic,{children:x},y.key)})]}):o.jsx(Gt.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(ge,{columns:"auto auto auto auto",...pxe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:vie(y.resourceId)}),o.jsx(ge.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ge.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(ge.NumberCell,{children:y.cost!=null?Vp(y.cost,y.costUnit):"—"})]});return b?o.jsx(ge.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ge.RowStatic,{children:x},y.key)})]}):o.jsx(Gt.NoData,{message:"No resource activity yet"})})]})})]})}const yie=20;function zgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:yie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:yie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:yie})]),l=new Map,c=d=>nA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const bie=20;function Bgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:bie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:bie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:bie})]),l=new Map,c=d=>nA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function Ugs(){const e=zgs(),t=Bgs(),{getTracesHref:n}=rA(),{Link:r}=xn();return o.jsx(Fgs,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function CL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(es,{children:[o.jsx(es.Label,{children:e}),o.jsx(es.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(es.Error,{}):s?o.jsx(es.Loading,{}):i?r!=null?o.jsx(es.Change,{changePct:r,prevValue:n}):o.jsx(es.NoChange,{}):o.jsx(es.NoData,{})]})}function Vgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function qgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function Hgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function Wgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function Zgs(){const{data:e,isLoading:t,isError:n}=pVt();return o.jsx(CL,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Ggs(){const{data:e,isLoading:t,isError:n}=Hgs();return o.jsx(CL,{label:"Total Model Cost",value:e?.cost!=null?Vp(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Vp(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Qgs(){const{data:e,isLoading:t,isError:n}=Wgs();return o.jsx(CL,{label:"Total Tokens",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Ygs(){const{data:e,isLoading:t,isError:n}=qgs();return o.jsx(CL,{label:"Total Threads",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Kgs(){const{data:e,isLoading:t,isError:n}=Vgs();return o.jsx(CL,{label:"Total Resources",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Xgs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Jgs(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(cAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(oAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Jgs(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}function evs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Vp(l):"—":c.size===1?u=l>0?Vp(l,[...c][0]):"—":u="Mixed",o.jsx(Gt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Gt.Actions,{children:s}):null]}),t?o.jsx(Gt.Loading,{}):n?o.jsx(Gt.Error,{message:"Failed to load model usage data"}):o.jsx(Gt.Content,{children:i?o.jsxs(ge,{columns:"auto auto auto auto auto auto",...pxe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Model"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(ge.NumberCell,{children:l.input}),o.jsx(ge.NumberCell,{children:l.output}),o.jsx(ge.NumberCell,{children:l.cacheRead}),o.jsx(ge.NumberCell,{children:l.cacheWrite}),o.jsx(ge.NumberCell,{highlight:!0,children:l.cost!=null?Vp(l.cost,l.costUnit):"—"})]});return c?o.jsx(ge.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ge.RowStatic,{children:u},l.model)})]}):o.jsx(Gt.NoData,{message:"No model usage data yet"})})]})}function tvs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>nA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:al(f.input),output:al(f.output),cacheRead:al(f.cacheRead),cacheWrite:al(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function nvs(){const{data:e,isLoading:t,isError:n}=tvs(),{getTracesHref:r}=rA(),{Link:s}=xn();return o.jsx(evs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Ec.AGENT}),actions:o.jsx(_L,{href:r({rootEntityType:Ec.AGENT}),LinkComponent:s})})}function rvs(e){return e==="tokens"||e==="cost"}function svs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&v>0;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Gt.Summary,{value:Vp(v,m),label:"Total cost"}):o.jsx(Gt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Gt.Actions,{children:s}):null]}),t?o.jsx(Gt.Loading,{}):n?o.jsx(Gt.Error,{message:"Failed to load token usage data"}):o.jsx(Gt.Content,{children:u?o.jsxs(pc,{defaultTab:"tokens",value:i,onValueChange:b=>{rvs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"tokens",children:"Tokens"}),o.jsx(jr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(RN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:qp.blueDark},{label:"Output",color:qp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:al})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(RN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:qp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Vp(b,m)}):o.jsx(Gt.NoData,{message:"No cost data yet"})})]}):o.jsx(Gt.NoData,{message:"No token usage data yet"})})]})}function avs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>nA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function ivs(){const{data:e,isLoading:t,isError:n}=avs(),{getTracesHref:r}=rA(),{Link:s}=xn();return o.jsx(svs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Ec.AGENT,entityName:a.name}),actions:o.jsx(_L,{href:r({rootEntityType:Ec.AGENT}),LinkComponent:s})})}function Oxe(e,t=al){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const ovs=[{dataKey:"input",label:"Input tokens",color:qp.blue,aggregate:Oxe("input")},{dataKey:"output",label:"Output tokens",color:qp.yellow,aggregate:Oxe("output")}];function lvs(e){return e==="tokens"||e==="cost"}function cvs({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:qp.purple,aggregate:Oxe("cost",k=>Vp(k,v))}];return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Gt.Summary,{value:Vp(y,v),label:"Total cost"}):o.jsx(Gt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Gt.Actions,{children:s}):null]}),n?o.jsx(Gt.Loading,{}):r?o.jsx(Gt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Gt.Content,{children:u?o.jsxs(pc,{defaultTab:"tokens",value:a,onValueChange:k=>{lvs(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"tokens",children:"Tokens"}),o.jsx(jr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(qV,{data:c,series:ovs})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(qV,{data:p,series:S}):o.jsx(Gt.NoData,{message:"No cost data yet"})})]}):o.jsx(Gt.NoData,{message:"No token usage data yet"})})]})}function uvs(e){return e==="24h"?"1h":"1d"}function dvs(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function Aet(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function fvs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function pvs(){const e=Ze(),{datePreset:t,filters:n,filterKey:r}=$m(),s=uvs(t);return gt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Aet(l,a.series[0],"input"),Aet(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:dvs(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:fvs(u)}}),interval:s}}})}function hvs(){const{data:e,isLoading:t,isError:n}=pvs(),{getTracesHref:r}=rA(),{Link:s}=xn();return o.jsx(cvs,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(_L,{href:r(),LinkComponent:s})})}function xie({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(RN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:qp.blueDark},{label:"Errors",color:qp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:al})}function mvs({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Gt.Summary,{value:al(f),label:"Total runs"}),u?o.jsx(Gt.Actions,{children:u}):null]}),t?o.jsx(Gt.Loading,{}):n?o.jsx(Gt.Error,{message:"Failed to load trace volume data"}):o.jsx(Gt.Content,{children:d?o.jsxs(pc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"agents",children:"Agents"}),o.jsx(jr,{value:"workflows",children:"Workflows"}),o.jsx(jr,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(xie,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Gt.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(xie,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Gt.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(xie,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Gt.NoData,{message:"No tool data yet"})})]}):o.jsx(Gt.NoData,{message:"No trace volume data yet"})})]})}async function wie(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=nA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function gvs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([wie(e,"mastra_agent_duration_ms",t),wie(e,"mastra_workflow_duration_ms",t),wie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const Lz={agents:Ec.AGENT,workflows:Ec.WORKFLOW_RUN,tools:Ec.TOOL};function vvs(){const{data:e,isLoading:t,isError:n}=gvs(),{getTracesHref:r,getLogsHref:s}=rA(),{Link:a}=xn();return o.jsx(mvs,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:Lz[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:Lz[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(_L,{href:r({rootEntityType:Lz[i]}),LinkComponent:a}),o.jsx(jgs,{href:s({rootEntityType:Lz[i],status:"error"}),LinkComponent:a})]})})}const Sie="period",Fz="dateFrom",zz="dateTo";function yvs(){const[e,t]=si(),n=e.get(Sie),r=xgs(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(Fz)),p=d(e.get(zz));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>pgs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Sie):p.set(Sie,d),d!=="custom"&&(p.delete(Fz),p.delete(zz)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(Fz,d.from.toISOString()):p.delete(Fz),d?.to?p.set(zz,d.to.toISOString()):p.delete(zz),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return mgs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,dgs(e)))return;const d=uVt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Sgs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(bvs,{})})}function bvs(){const[e]=si(),{error:t,isLoading:n}=pVt(),{filterTokens:r,setFilterTokens:s}=EQ(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=kAe(),{data:d,isLoading:f}=xAe(),{data:p,isLoading:h}=vAe(),{data:m,isLoading:v}=bAe(),{data:y,isLoading:b}=yAe(),x=g.useMemo(()=>fgs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[S,k]=g.useState(()=>uVt()!==null),_=g.useCallback(()=>{cgs(e),k(!0),Fe.success("Filters setting for Metrics saved")},[e]),C=g.useCallback(()=>{ugs(),k(!1),Fe.success("Filters setting for Metrics cleared up")},[]),E=g.useCallback(()=>{s([])},[s]),T=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&xs(t)?o.jsx(cr,{children:o.jsx(Zs,{})}):t&&Ss(t)?o.jsx(cr,{children:o.jsx($s,{resource:"metrics"})}):t?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Cgs,{}),o.jsx(uAe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(Xgs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:T,onRemoveAll:E,onSave:_,onRemoveSaved:S?C:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(Sn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Sn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(yxe,{children:[o.jsx(Zgs,{}),o.jsx(Ggs,{}),o.jsx(Qgs,{}),o.jsx(Ygs,{}),o.jsx(Kgs,{})]}),o.jsxs(yxe,{children:[o.jsx(nvs,{}),o.jsx(ivs,{}),o.jsx(hvs,{}),o.jsx(Ugs,{}),o.jsx(vvs,{}),o.jsx(Dgs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Df,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Oa,{})]})})})]})}const xvs=50;function wvs(){const{paths:e}=xn(),{isCmsAvailable:t}=uS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=D7t({page:s,perPage:xvs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=g.useCallback(()=>{u||a(v=>v+1)},[u]),h=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&xs(c)?o.jsx(cr,{children:o.jsx(Zs,{})}):c&&Ss(c)?o.jsx(cr,{children:o.jsx($s,{resource:"prompt blocks"})}):c?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(cr,{children:o.jsx(Jss,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Uf,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(le,{as:ni,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Zr,{}),"Create Prompt"]})]})}),o.jsx(Xss,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function Svs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx(Its,{children:o.jsx(Hbe,{})})})})}const kvs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:DGt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:llt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Oa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:mj,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:glt,href:"https://mastra.ai/cloud",external:!0},{title:"Talk to our Sales team",description:"Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.",icon:clt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Ovs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:kvs.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(Oa,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function _vs(){const{data:e={},isLoading:t,error:n}=uh(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&xs(n))return o.jsx(cr,{children:o.jsx(Zs,{})});if(n&&Ss(n))return o.jsx(cr,{children:o.jsx($s,{resource:"scorers"})});if(n)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(cr,{children:o.jsx(irs,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(lrs,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(ars,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Cvs(){const{scorerId:e}=Sr(),[t,n]=si(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=Mns(e),{data:d={},isLoading:f,error:p}=Im(),{isLoading:h,error:m}=Wy(),{data:v=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k}=$ns({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=g.useMemo(()=>c?.agentIds?.filter(V=>d[V]).map(V=>({value:V,label:d[V].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=g.useMemo(()=>c?.workflowIds?.map(V=>({value:V,label:V,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),T=t.get("entity")??"all",N=E.find(V=>V.value===T);N&&N.value!==i?.value&&l(N),g.useEffect(()=>{if(u){const V=u instanceof Error?u.message:"Failed to load scorer";Fe.error(`Error loading scorer: ${V}`)}},[u]),g.useEffect(()=>{if(p){const V=p instanceof Error?p.message:"Failed to load agents";Fe.error(`Error loading agents: ${V}`)}},[p]),g.useEffect(()=>{if(m){const V=m instanceof Error?m.message:"Failed to load workflows";Fe.error(`Error loading workflows: ${V}`)}},[m]);const I=V=>{V?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",V.value),G})};g.useEffect(()=>{const V=t.get("scoreId")??void 0;if(V===s)return;if(!V){a(void 0);return}v.find(G=>G.id===V)&&a(V)},[t,v]);const A=g.useCallback(V=>{a(V||void 0),n(M=>{const G=new URLSearchParams(M);return V?G.set("scoreId",V):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=xs(u)||xs(p)||xs(m),L=u&&Ss(u),D=!R&&!L&&(u||p||m),F=!y&&v.length===0,H=i?.value!=="all",B=c?.scorer?.source==="stored"?o.jsx(My,{owner:"scorer-detail",children:o.jsxs(le,{variant:"default",as:ni,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(lm,{})," Edit"]})}):null;if(R||L||D||F&&!H){const V=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Vt,{width:"wide",height:"full",children:[B,o.jsx(Vt.MainArea,{isCentered:!0,children:R?o.jsx(Zs,{}):L?o.jsx($s,{resource:"scorers"}):D?o.jsx(Hi,{title:"Failed to load scorer",message:V}):o.jsx(Tns,{})})]})}return o.jsxs(Vt,{width:"wide",children:[B,o.jsx(Vt.TopArea,{children:o.jsx(jns,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(V=>{const M=new URLSearchParams(V);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(Ens,{scores:v,isLoading:y,selectedScoreId:s,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function Evs({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:X("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Lt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-neutral3 text-sm",children:t})]}),s]})}const vVt=[{value:"dark",label:"Dark",Icon:mYt},{value:"light",label:"Light",Icon:EKt},{value:"system",label:"System",Icon:klt}],Tvs=e=>vVt.some(t=>t.value===e);function jvs({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const Nvs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=fH(),{theme:r,setTheme:s}=q_();return o.jsx(Vt,{width:"narrow",children:o.jsxs(Vt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(_be,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Evs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ma,{value:r,onValueChange:a=>{Tvs(a)&&s(a)},children:[o.jsx(va,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ga,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(ya,{children:vVt.map(a=>o.jsx(Rr,{value:a.value,children:o.jsx(jvs,{option:a})},a.value))})]})})}),o.jsx(_be,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(r3t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Ivs(){const[e]=si(),t=Ws(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(oVt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const yVt=e=>o.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})});function Avs(e){return e.replace(/\/$/,"").split("/").pop()}function TQ({children:e,className:t}){return o.jsx("div",{className:X("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function Rvs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:X("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:X("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:X("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:X("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:X("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:X("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:X("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Vo,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Bd,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Olt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(qN,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(vC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:X("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(yVt,{})," ",Avs(a.githubUrl)]})})]},a.slug)})})}function Pvs({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:X("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:X("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(yN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Cc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Cc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(le,{onClick:c,children:["Reset ",o.jsx(ws,{})]})]})}function $vs(){const{data:e,isLoading:t}=Lnr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(fs,{children:[o.jsx(F1e,{children:o.jsxs(Iyt,{children:[o.jsx(qe,{children:o.jsx(Jv,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Pvs,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Rvs,{templates:y,linkComponent:ni,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Mvs="1.60.1-alpha.0";function Dvs({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(_f,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(fQt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(TQ,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function Lvs({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(TQ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:X("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(_lt,{})]}),o.jsx(Cc,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:X("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(en,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(IO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(IO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(p7t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(le,{className:X("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(en,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(xm,{})]})})]})})}function Fvs({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:X("grid mt-8 items-center"),children:o.jsxs("div",{className:X("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(Jv,{}),o.jsx("h2",{className:X({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:X("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:X("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(Yx,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Fxe,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(yVt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(PIe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Ret(e){switch(e){case"running":return o.jsx(en,{size:"sm","aria-hidden":!0});case"success":return o.jsx(gy,{"aria-hidden":!0});case"failed":return o.jsx(fu,{"aria-hidden":!0});default:return null}}function zvs(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function Bvs({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:X("flex size-4 items-center justify-center self-center [&>svg]:size-4",Wr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(zvs,{}):Ret(e)}):o.jsx("span",{className:X("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Wr.colors,Wr.transform,Wr.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:Ret(e)})}function Uvs({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Wr.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:X("flex min-w-6 justify-end text-ui-md",Wr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:X("text-ui-md",Wr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:X("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(Bvs,{status:e.status,variant:r})]})}function Vvs({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(Uvs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function qvs({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:X("relative flex h-8 items-center justify-end",Wr.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:X("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",Wr.colors,Wr.transform,Wr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(en,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",Wr.colors),children:[n," of ",t," steps completed"]})]})}function Hvs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(TQ,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(qvs,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:X("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(_Yt,{}),l||"Something went wrong"]}),u&&o.jsx(Vvs,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(en,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Wvs({name:e,installedEntities:t}){return o.jsxs(TQ,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(_lt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx(PIe,{data:t})]})}function Zvs(){const{templateSlug:e}=Sr(),[t,n]=si(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[E,T]=g.useState([]),{data:N,isLoading:I}=Fnr({repoOrSlug:e,owner:"mastra-ai"}),R=Mvs?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=znr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:F,isLoading:H}=Bnr(),{mutateAsync:B,isPending:U}=Unr(),{mutateAsync:V}=Vnr(),{streamInstall:M,streamResult:G,isStreaming:q}=Hnr(F),{observeInstall:$,streamResult:z,isStreaming:Z}=Wnr(F);g.useEffect(()=>{const te=t.get("runId");te&&!v&&!h&&!q&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:te}),x(te),V({runId:te}).then(ue=>{const fe=ue.snapshot;if(fe?.status==="success"&&fe?.result?.success)y(!0);else if(fe?.result?.success===!1)if(fe?.result?.validationResults&&!fe?.result?.validationResults?.valid&&fe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:me,errors:be}=fe.result.validationResults,we=`Template installation completed but ${me} validation issue${me>1?"s":""} remain unresolved.`;m(we),T(be||[])}else{const me=fe?.result?.message||fe?.result?.error||"Template installation failed";m(typeof me=="string"?me:String(me))}}).catch(ue=>{console.error("❌ Failed to fetch run details:",ue),m("Failed to retrieve installation status after reload")}))},[t,v,h,q,Z,V]),g.useEffect(()=>{const te=t.get("runId"),ue=t.get("resume"),fe=t.get("provider");if(te&&ue==="true"&&fe&&!q&&!Z&&!S&&!_&&F){x(te),k(!0);try{V({runId:te}).then(ce=>{if(ce.snapshot?.status==="running")return $.mutateAsync({runId:te})}).then(()=>{n(ce=>{const me=new URLSearchParams(ce);return me.delete("resume"),me})}).catch(ce=>{console.error("❌ Failed to resume template installation:",ce),ce.message?.includes("404")||ce.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(ce){console.error("❌ Auto-resume failed with error:",ce),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,q,Z,S,_,F,V,$,n]);const K=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],ne=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(te=>te).join(", "):"n/a",icon:o.jsx(Bd,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(te=>te).join(", "):"n/a",icon:o.jsx(Vo,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(te=>te).join(", "):"n/a",icon:o.jsx(qN,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Lv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(VN,{})}],ee=[{...ne[0]},{...ne[1]},{...ne[2]}].filter(te=>te.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const te=G||z;te?.phase==="error"&&te?.error&&m(typeof te.error=="string"?te.error:String(te.error))},[G?.phase,G?.error,z?.phase,z?.error]);const J=te=>{s(te)},ae=async te=>(i(te.provider),c(te.modelId),{message:"Model updated successfully"}),pe=async()=>{const te=Object.entries(u).reduce((ue,[fe,ce])=>(ce===""&&ue.push(fe),ue),[]);if(te.length>0){p(te);return}if(N){m(null),y(!1),x(""),C(!0);try{const fe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ce}=await B({});x(ce),n(me=>{const be=new URLSearchParams(me);return be.set("runId",ce),be.set("resume","true"),be.set("provider",r||"openai"),be}),await M.mutateAsync({inputData:fe,selectedModel:{provider:a,modelId:l},runId:ce})}catch(ue){C(!1),m(ue?.message||"Template installation failed"),console.error("Template installation failed",ue)}}},Y=te=>{const{name:ue,value:fe}=te.target;fe.trim()===""?p(ce=>[...ce,ue]):p(ce=>ce.filter(me=>me!==ue)),d(ce=>({...ce,[ue]:fe}))};return o.jsx(fs,{children:o.jsx("div",{className:X("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(Fvs,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:ne,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(q||Z)&&o.jsx(Hvs,{name:N.title,streamResult:Z?z:G,runId:b,workflowInfo:F}),v&&o.jsx(Wvs,{name:N.title,installedEntities:ee,linkComponent:ni}),h&&o.jsx(Dvs,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||z?.validationResults?.errors}),!q&&!Z&&!v&&!h&&o.jsx(Lvs,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:pe,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:U,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Gvs=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(gss,{toolId:e,agentId:t})})},Qvs=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Jms,{toolId:e})})};function Yvs(){const{traceId:e}=Sr(),[t,n]=si(),r=Ws(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=g.useState(s??null),[d,f]=g.useState(),[p,h]=g.useState(i),[m,v]=g.useState(0),[y,b]=g.useState(!1),{data:x,isLoading:S,error:k}=wAe(e),_=g.useMemo(()=>x?.spans??[],[x?.spans]),C=g.useMemo(()=>_.find(Y=>Y.parentSpanId==null),[_]),E=kAe(),T=mxe({traceIds:[e],enabled:!E.isLoading&&E.supportsMetrics,autoRefetch:!1}),{data:N,isLoading:I}=kL(e,c??"");g.useEffect(()=>v(0),[e,c]);const{data:A,isLoading:R}=uh(),{data:L,isLoading:D}=A7t({traceId:e,spanId:c??void 0,page:m}),[F,H]=g.useState(0);g.useEffect(()=>H(0),[e,c]);const{data:B,isLoading:U}=ZUt({traceId:e,page:F});g.useEffect(()=>{if(l&&L?.scores&&!d){const Y=L.scores.find(te=>te.id===l);Y&&f(Y)}},[l,L?.scores,d]);const V=g.useCallback(Y=>{const te=new URLSearchParams(t);for(const[ue,fe]of Object.entries(Y))fe===null||fe===""?te.delete(ue):te.set(ue,fe);n(te,{replace:!0})},[t,n]),M=g.useCallback(Y=>{const te=Y??null,ue=te===c;u(te),ue||(f(void 0),h("details"),V({spanId:te,tab:null,scoreId:null}))},[c,V]),G=g.useCallback(()=>{u(null),f(void 0),h("details"),V({spanId:null,tab:null,scoreId:null})},[V]),q=g.useCallback(Y=>{u(Y),f(void 0),h("details"),V({spanId:Y,tab:null,scoreId:null})},[V]),{handlePreviousSpan:$,handleNextSpan:z}=SAe(_,c,q),Z=g.useCallback(Y=>{const te=Y;h(te),f(void 0),V({tab:te==="details"?null:te,scoreId:null})},[V]),K=g.useCallback(Y=>{f(Y),V({scoreId:Y.id})},[V]),ne=g.useCallback(()=>{f(void 0),V({scoreId:null})},[V]),ee=g.useCallback(()=>{r("/traces")},[r]),J=g.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),V({spanId:C.spanId,tab:"scoring",scoreId:null})):V({tab:"scoring"})},[C,c,V]),ae=C?o.jsx(My,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(le,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:J,children:[o.jsx(aGt,{}),"Evaluate"]}),o.jsxs(le,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(Nd,{}),"Save"]})]})}):null,pe=C?o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{children:o.jsx(IUt,{rootSpan:C,usage:T.data?.get(e),numOfCol:3})})}):null;return k?o.jsxs(Vt,{height:"full",children:[ae,pe&&o.jsx(Vt.TopArea,{children:pe}),o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(MUt,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Vt,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[ae,pe&&o.jsx(Vt.TopArea,{children:pe}),o.jsx(UUt,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:X("mt-4 grid min-h-0 items-stretch gap-4 overflow-hidden",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(hAe,{traceId:e,spans:_,isLoading:S,onClose:ee,onSpanSelect:M,onEvaluateTrace:J,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&o.jsxs("div",{className:X("grid h-full max-h-full min-h-0 gap-4 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(dAe,{traceId:e,spanId:c,span:N?.span,isLoading:I,onClose:G,onPrevious:$,onNext:z,activeTab:p,onTabChange:Z,feedbackTabBadge:B?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(qUt,{feedbackData:B,onPageChange:H,isLoadingFeedbackData:U}),scoringTabBadge:L?.pagination?.total??void 0,scoringTabSlot:({span:Y,traceId:te,spanId:ue})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(WUt,{traceId:te,isTopLevelSpan:!Y.parentSpanId,spanId:ue,entityType:Y.attributes?.agentId||Y.entityType===Ec.AGENT?"Agent":Y.attributes?.workflowId||Y.entityType===Ec.WORKFLOW_RUN?"Workflow":void 0,scorers:A,isLoadingScorers:R}),o.jsx(HUt,{scoresData:L,onPageChange:v,isLoadingScoresData:D,onScoreSelect:K})]})}),d&&o.jsx(RIe,{score:d,onClose:ne})]})]})]})}function Kvs(){const{data:e,isLoading:t,error:n}=Wy(),[r,s]=g.useState("");return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"workflows"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(cr,{children:o.jsx(zqr,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Uf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(le,{as:ni,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(ID,{}),"Schedules"]})]})}),o.jsx(Fqr,{workflows:e||{},isLoading:t,search:r})]})}const Xvs={active:"bg-accent1",paused:"bg-accent3"},Jvs={active:"text-accent1",paused:"text-accent3"},bVt=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Xvs[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Jvs[e]}`,children:e})]}),uj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),H2=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function xVt({status:e}){const{icon:t,color:n}=eys(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function eys(e){switch(e){case"success":return{icon:o.jsx(da,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(ws,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(en,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(tq,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Df,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(hj,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const Pet="auto auto auto auto 1fr";function tys(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function nys(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const rys=3e4,sys=5*6e4;function ays({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=xn();return t?o.jsx(ol,{columns:Pet}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ge,{columns:Pet,className:"min-w-0",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Run"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{children:"Started"}),o.jsx(ge.TopCell,{children:"Duration"}),o.jsx(ge.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=nys(u),f=`Scheduled ${uj(c.scheduledFireAt)} — published ${uj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),v=!p&&m>rys&&m<=sys,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),x=o.jsx("span",{className:b?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(ge.Cell,{height:"compact",children:x}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(_f,{size:14}),"publish failed"]}):c.run?o.jsx(xVt,{status:c.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),h?o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(_f,{size:14})})}),o.jsx(On,{children:h})]}):null]})}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:H2(c.actualFireAt)}),v?o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(_f,{size:14})})}),o.jsxs(On,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(ge.Cell,{height:"compact",children:c.run?o.jsx("span",{children:tys(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ge.Cell,{height:"compact",children:" "})]});return b?o.jsx(ge.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(ge.RowStatic,{children:S},y)}),o.jsx(ge.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const iys=e=>{const t=Ze();return gt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},$et=25,oys=e=>{const t=Ze(),{inView:n,setRef:r}=Q_(),s=G1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:$et,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<$et))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},lys=e=>{const t=Ze(),n=Br();return Dn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),Fe.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Fe.error(r.message)}})};function Bz({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function cys(){const{scheduleId:e}=Sr(),{paths:t}=xn(),{data:n,error:r}=iys(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=oys(e),d=lys(e);if(r&&xs(r))return o.jsx(cr,{children:o.jsx(Zs,{})});if(r&&Ss(r))return o.jsx(cr,{children:o.jsx($s,{resource:"schedules"})});if(r)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{className:"justify-end",children:o.jsxs(Vt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(le,{as:ni,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Rc,{}),"Back to schedules"]}),f?o.jsx(le,{as:ni,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(le,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(Vxe,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Hp,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(Bz,{label:p?"Agent":"Workflow",children:f?o.jsx(ni,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(ni,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(Bz,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(Bz,{label:"Status",children:o.jsx(bVt,{status:n.status})}),o.jsx(Bz,{label:"Next fire",children:o.jsx("span",{title:uj(n.nextFireAt),children:H2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ye,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Hi,{title:"Failed to load trigger history",message:i.message}):o.jsx(ays,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Met="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function uys({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=xn(),a=g.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(ol,{columns:Met}):o.jsxs(ge,{columns:Met,variant:"striped",className:"min-w-0",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Target"}),o.jsx(ge.TopCell,{children:"Schedule ID"}),o.jsx(ge.TopCell,{children:"Cron"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{children:"Next fire"}),o.jsx(ge.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ge.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ge.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(ge.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(ge.NameCell,{children:i.workflowId??i.agentId}),o.jsx(ge.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:i.id,children:i.id})}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(ge.Cell,{height:"compact",children:o.jsx(bVt,{status:i.status})}),o.jsx(ge.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:uj(i.nextFireAt),children:H2(i.nextFireAt)})}),o.jsx(ge.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(xVt,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:uj(i.lastFireAt),children:i.lastFireAt?H2(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:uj(i.lastFireAt),children:H2(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function dys({workflowId:e}={}){const{data:t,isLoading:n,error:r}=D1e(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Hi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(Uf,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(uys,{schedules:t??[],isLoading:n,search:s})})]})}function fys(){const[e]=si(),t=e.get("workflowId")??void 0,{error:n}=D1e(t?{workflowId:t}:{});return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"schedules"})}):o.jsx(Vt,{children:o.jsx("div",{className:"h-full",children:o.jsx(dys,{workflowId:t})})})}function pys({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=fOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=i_t(r),[d]=o_t(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=z4t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(a_t,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(oje,{position:"bottom-left"}),o.jsx(c_t,{variant:ay.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(en,{})})})}function hys(){const{stepDetail:e,closeStepDetail:t}=iW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(h9,{className:"h-4 w-4",style:{color:Iu.map}}),e.type==="nested-graph"&&o.jsx(td,{className:"h-4 w-4",style:{color:Iu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(ws,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(U2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(dOe,{children:o.jsx(pys,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function mys(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function gys(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);if(n.length===1)return n[0]}return t}function vys({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ye,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(qe,{children:o.jsx(tq,{})}),"Step suspended"]}),o.jsx(ln,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?hm(Tx(i.resumeSchema)):lf(fr(),vf());return o.jsx(yys,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function yys({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(vYt,{})}),"The step is asking"]}),o.jsxs(Ld,{open:a,onOpenChange:i,children:[o.jsxs(Ku,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(qe,{children:o.jsx(aa,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:gys(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:mys(e.suspendPayload)})]}),o.jsx(Xu,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Hr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(xYt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(WB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Hp,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function bys(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(ql),{runId:a}=Sr(),i=g_t(e,r??""),l=eer(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(vys,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const xys=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),wys=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),Sys=e=>e.includes("."),kys=e=>e==="input"||e.endsWith(".input"),Oys=1;function _ys(e){return`${Number((e/1e3).toPrecision(3))}s`}function Cys(e,t){const n=Object.entries(e).filter(([i])=>!kys(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,p=Math.max(d/a*100,Oys);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:Sys(i)}})}const Eys=({status:e})=>o.jsxs(qe,{children:[e==="success"&&o.jsx(xys,{className:"text-accent1"}),e==="failed"&&o.jsx(wys,{className:"text-accent2"}),e==="suspended"&&o.jsx(tq,{className:"text-accent3"}),e==="waiting"&&o.jsx(ppe,{className:"text-accent5"}),e==="skipped"&&o.jsx(ppe,{className:"text-icon3"}),e==="running"&&o.jsx(ca,{className:"text-accent6 animate-spin"})]}),Tys={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function wVt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const Det=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},jys=e=>{const t=e;return I4t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},Nys=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=jys(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:X("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(Eys,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(wKt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(EV,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:wVt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${Tys[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(bKt,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:_ys(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function Iys(){const{steps:e}=P4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=bH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Vyt(f,{enabled:!l});const p=Cys(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Na,{className:X("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(Nys,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:Det(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:Det(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(y_t,{data:u.data,title:`${wVt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Ays=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=iW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(G4t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(bys,{}),o.jsx(Iys,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(hys,{})})]})},Let=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=V3(e);return r&&xs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})}):r&&Ss(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"workflows"})}):o.jsx(NOe,{children:o.jsx(Ays,{workflowId:e,workflow:t??void 0,isLoading:n})})};function Rys(e,t){if(e==null)return{};var n,r,s=SSt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function _xe(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Pys(e){if(Array.isArray(e))return _xe(e)}function $ys(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Mys(e,t){if(e){if(typeof e=="string")return _xe(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_xe(e,t):void 0}}function Dys(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
642
|
+
`);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>bxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>bxe(t))}return!1}function Vhs({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function qhs({className:e,children:t}){return o.jsx("div",{className:X("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function Hhs({className:e,children:t}){return o.jsx("h3",{className:X("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function Whs({className:e,children:t}){return o.jsx("dl",{className:X("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function Zhs({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function Ghs({className:e,children:t}){return o.jsx("dd",{className:X("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function Qhs({className:e,children:t}){return o.jsx("dt",{className:X("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const Yhs=Object.assign(Whs,{Key:Zhs,Value:Ghs,Header:Qhs});function Khs({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(en,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function Xhs({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const Bi=Object.assign(Dhs,{Header:qhs,Heading:Hhs,CloseButton:Lhs,LoadingData:Khs,NoData:Xhs,Content:Vhs,KeyValueList:Yhs,CodeSection:Uhs}),hp=Bi.KeyValueList;function Jhs(e){return e instanceof Date?e:new Date(e)}function ems({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=Jhs(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Bi,{collapsed:d,children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Log ",o.jsx("b",{children:or(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(uH,{}):o.jsx(w1e,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(le,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(lH,{})}),o.jsx(le,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(c3,{})})]}),o.jsx(Bi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Bi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:X("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(N7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(za,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(N7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(za,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(hp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Entity Type"}),o.jsx(hp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Entity Name"}),o.jsx(hp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Service"}),o.jsx(hp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Environment"}),o.jsx(hp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Source"}),o.jsx(hp.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(hp.Key,{children:v}),o.jsx(hp.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Bi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function tms({error:e,resource:t,errorTitle:n}){if(xs(e))return o.jsx(Zs,{});if(Ss(e))return o.jsx($s,{resource:t});if(v4(e))return o.jsx(Lr,{iconSlot:o.jsx(I7,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(g4(e,"logs"))return o.jsx(Lr,{iconSlot:o.jsx(I7,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Hi,{title:n,message:r??"Unknown error"})}function nms({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:X("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const rms={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function sms({level:e}){const t=rms[e];return o.jsx(jo,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function ams({entityType:e,className:t}){const n=X("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Vo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(td,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Bd,{className:n,"aria-hidden":!0});default:return null}}function ims({entityType:e,entityName:t}){const n=e??"";return o.jsxs(jo,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(ams,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function oms({message:e}){return o.jsx(jo,{height:"compact",className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function lms({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(jo,{height:"compact",children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(yTe,{children:t})}const Ql=Object.assign(C4,{Top:DZ,TopCell:cC,TopCellWithTooltip:LZ,TopCellSmart:GDt,RowWrapper:STe,RowButton:E4,RowLink:ZDt,Spacer:kTe,NoMatch:MZ,DateCell:bTe,TimeCell:xTe,LevelCell:sms,EntityCell:ims,MessageCell:oms,DataCell:lms,NextPageLoading:$Z}),Cet="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",cms=36,ums=8;function dms({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=LUt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>cms,overscan:ums}),d=g.useRef(t);if(g.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ol,{columns:Cet});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Ql,{columns:Cet,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ql.Top,{children:[o.jsx(Ql.TopCell,{children:"Date"}),o.jsx(Ql.TopCell,{children:"Time"}),o.jsx(Ql.TopCell,{children:"Level"}),o.jsx(Ql.TopCell,{children:"Entity"}),o.jsx(Ql.TopCell,{children:"Message"}),o.jsx(Ql.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ql.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ql.Spacer,{height:h}),f.map(v=>{const y=e[v.index];if(!y)return null;const b=a.get(y);if(!b)return null;const x=b===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":v.index,onClick:()=>l(y),featured:x,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Ql.DateCell,{timestamp:y.timestamp}),o.jsx(Ql.TimeCell,{timestamp:y.timestamp}),o.jsx(Ql.LevelCell,{level:y.level}),o.jsx(Ql.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Ql.MessageCell,{message:y.message}),o.jsx(Ql.DataCell,{data:y.data})]},b)}),o.jsx(Ql.Spacer,{height:m})]}),o.jsx(Ql.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function fms({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>pms(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(cAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(oAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function pms(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}const hms={"last-24h":"the last 24 hours","last-3d":"the last 3 days","last-7d":"the last 7 days","last-14d":"the last 14 days","last-30d":"the last 30 days"},pie="MMM d, yyyy HH:mm",hie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function mms({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${hms[e]}`,description:hie}:t&&n?{title:`No logs between ${or(t,pie)} and ${or(n,pie)}`,description:hie}:t?{title:`No logs since ${or(t,pie)}`,description:hie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const gms=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=mms({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(I7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(k1e,{})]})})})},vms=20,yms=1e4;function bms(e,t,n){if(e?.pagination?.hasMore)return n+1}function xms(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function wms(e){return g4(e.state.error,"logs")||v4(e.state.error)?!1:yms}const Sms=({filters:e}={})=>{const t=Ze(),{inView:n,setRef:r}=Q_(),s=G1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:vms},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:bms,select:xms,retry:!1,refetchInterval:wms}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},Mz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},lVt=[{label:"Agent",entityType:Mz.AGENT},{label:"Workflow",entityType:Mz.WORKFLOW},{label:"Scorer",entityType:Mz.SCORER},{label:"Ingest",entityType:Mz.INGEST}],kms=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Gx="rootEntityType",Xb="datePreset",Jb="dateFrom",ex="dateTo",Oms=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Nl={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},OL=Object.keys(Nl),AAe=new Set(["tags"]),RAe="mastra:logs:saved-filters";function _ms(e,t=RAe){const n=Nms(e),r=e.get(Xb);r&&n.set(Xb,r);const s=e.get(Jb);s&&n.set(Jb,s);const a=e.get(ex);a&&n.set(ex,a);try{localStorage.setItem(t,n.toString())}catch{}}function Cms(e=RAe){try{localStorage.removeItem(e)}catch{}}function Eet(e=RAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Ems(e){if(e.has(Xb)||e.has(Jb)||e.has(ex)||e.has(Gx))return!0;for(const t of OL)if(e.has(Nl[t]))return!0;return!1}function Tms({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:lVt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"level",label:"Level",kind:"pick-multi",searchable:!1,options:kms.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function jms(e){const t=[],n=new Map([[Gx,"rootEntityType"]]);for(const s of OL)n.set(Nl[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),AAe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Nms(e){const t=new URLSearchParams,n=e.get(Gx);n&&t.set(Gx,n);for(const r of OL){const s=Nl[r];if(AAe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function Ims(e,t){e.delete(Gx);for(const n of OL)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Gx,n.value);continue}const r=Nl[n.fieldId];if(r){if(AAe.has(n.fieldId)&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function Ams({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function Rms(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}const Pms="Filters setting for Logs saved",$ms="Filters setting for Logs cleared up";function Mms(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Eet(r)!==null),c=g.useCallback(()=>{_ms(e,r),l(!0);const f=s?.saved??Pms;f!==!1&&Fe.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Cms(r),l(!1);const f=s?.cleared??$ms;f!==!1&&Fe.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Ems(e)))return;const f=Eet(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Dms(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function Lms(e){const t=new Map;for(const n of e){if(n.logId){t.set(n,n.logId);continue}const r=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,Dms(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Fms(e,t,n,r){const s=g.useMemo(()=>Lms(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const xxe="logId",wxe="traceId",Sxe="spanId",hP=1440*60*1e3,zms={"last-24h":hP,"last-3d":3*hP,"last-7d":7*hP,"last-14d":14*hP,"last-30d":30*hP};function Dz(e){e.delete(xxe),e.delete(wxe),e.delete(Sxe)}function Bms(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(Xb);return _&&Oms.has(_)?_:"last-24h"},[e]),a=e.get(Jb),i=e.get(ex),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=zms[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(xxe),f=e.get(wxe),p=e.get(Sxe),h=g.useMemo(()=>lVt.find(_=>_.entityType===e.get(Gx)),[e]),m=g.useMemo(()=>jms(e),[e]),v=g.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);for(const[T,N]of Object.entries(_)){const I=T==="logId"?xxe:T==="traceId"?wxe:Sxe;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);return Ims(E,_),Dz(E),E},{replace:!0})},[t]),b=y,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const E=C==="from"?Jb:ex;t(T=>{const N=new URLSearchParams(T);return _?N.set(E,_.toISOString()):N.delete(E),Dz(N),N},{replace:!0})},[t]),S=g.useCallback(_=>{u.current=_,t(C=>{const E=new URLSearchParams(C);return _==="last-24h"?(E.delete(Xb),E.delete(Jb),E.delete(ex)):_==="custom"?E.set(Xb,"custom"):(E.set(Xb,_),E.delete(Jb),E.delete(ex)),Dz(E),E},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(Gx);for(const E of OL)C.delete(Nl[E]);return C.delete(Xb),C.delete(Jb),C.delete(ex),Dz(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,x,S,k,y])}const _b=Bi.KeyValueList;function Ums({spanId:e,span:t,isLoading:n,onClose:r}){const s=OQ(t?.startedAt,t?.endedAt),a=KV(t?.startedAt),i=KV(t?.endedAt);return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading span..."}):t?o.jsxs(Bi.Content,{children:[o.jsxs(_b,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(_b.Key,{children:"Type"}),o.jsx(_b.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(_b.Key,{children:"Started"}),o.jsx(_b.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(_b.Key,{children:"Ended"}),o.jsx(_b.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(_b.Key,{children:"Duration"}),o.jsx(_b.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Bi.CodeSection,{title:"Input",icon:o.jsx(eme,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Output",icon:o.jsx(tme,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Metadata",icon:o.jsx(Tw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Attributes",icon:o.jsx(Tw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Bi.NoData,{children:"Span not found."})]})}function Vms({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>pAe(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(fAe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Bi.NoData,{children:"No spans found for this trace."}):o.jsx(Bi.Content,{children:o.jsx($Ut,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function qms(){const[e,t]=si(),n=Bms(e,t),r=Mms(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=xAe(),{data:d=[],isPending:f}=vAe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=yAe(),{data:m=[],isPending:v}=bAe(),y=g.useMemo(()=>Tms({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>Ams({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E}=Sms({filters:b}),{logIdMap:T,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Fms(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=wAe(n.featuredTraceId??null),{data:F,isLoading:H}=kL(n.featuredTraceId??"",n.featuredSpanId??""),B=g.useCallback(()=>n.applyFilterTokens(Rms(y,n.filterTokens)),[y,n]),U=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),M=g.useCallback((K,ne)=>n.handleFeaturedChange({traceId:K,spanId:ne}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),q=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),z=o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(h4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(uAe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(fms,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:B,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(tms,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(gms,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(nms,{logCollapsed:i,listSlot:o.jsx(dms,{logs:x,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E,logIdMap:T,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(ems,{log:N,onClose:U,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Vms,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(Ums,{spanId:n.featuredSpanId,span:F?.span,isLoading:H,onClose:q}):null})]})}function Hms({server:e}){const{paths:t,Link:n}=xn(),s=Ze().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=i7t(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=Yh(e.name,50);return o.jsxs(ge.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(ge.NameCell,{children:f}),o.jsx(ge.DescriptionCell,{children:a}),o.jsx(ge.TextCell,{className:"text-center",children:u||""}),o.jsx(ge.TextCell,{className:"text-center",children:c||""}),o.jsx(ge.TextCell,{className:"text-center",children:d||""})]})}function Wms({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ol,{columns:"auto 1fr auto auto auto"}):o.jsxs(ge,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"URL"}),o.jsx(ge.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ge.TopCellSmart,{long:"Tools",short:o.jsx(Bd,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ge.TopCellSmart,{long:"Workflows",short:o.jsx(td,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ge.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(Hms,{server:s},s.id))]})}const Zms=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Df,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Oa,{})]})})}),Gms=()=>{const{data:e=[],isLoading:t,error:n}=eQ(),[r,s]=g.useState("");return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"MCP servers"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(cr,{children:o.jsx(Zms,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Uf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(Wms,{mcpServers:e,isLoading:t,search:r})]})},Qms=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function Yms({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=xn(),i=g.useMemo(()=>Qms(e,t),[e,t]),l=g.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ol,{columns:"auto 1fr auto"}):o.jsxs(ge,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Name"}),o.jsx(ge.TopCell,{children:"Description"}),o.jsx(ge.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ge.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=Yh(c.id,50),d=Yh(c.description??"",200),f=c.agents.length;return o.jsxs(ge.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(ge.NameCell,{children:u}),o.jsx(ge.DescriptionCell,{children:d}),o.jsx(ge.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Kms=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Df,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Oa,{})]})})}),Xms=()=>{const e=Ze();return Dn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new j_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Fe.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Jms=({toolId:e})=>{const{canExecute:t}=Wo(),n=t("tools"),{data:r={}}=Im(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=MIr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=Xms(),{requestContext:p}=ps();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Fe.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?hm(Tx(c?.inputSchema)):vs({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(St,{className:"mb-4 h-8 w-48"}),o.jsx(St,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(LIe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function egs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=FI(),{data:p={},isLoading:h,isError:m,error:v}=Im(),{navigate:y,paths:b}=xn();g.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";Fe.error(`Error loading tools: ${_}`)}},[d,f]),g.useEffect(()=>{if(m){const _=v instanceof Error?v.message:"Failed to load agents";Fe.error(`Error loading agents: ${_}`)}},[m,v]);const x=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{x.has(C.id)||x.set(C.id,C)})}),Object.values(c).forEach(_=>{x.has(_.id)||x.set(_.id,_)});const S=Array.from(x.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(Ll,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const tgs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(_y,{children:o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(_y,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(ln,{icon:o.jsx(AUt,{className:"text-neutral6"}),className:"text-neutral4! rounded-r-sm",children:"Version"}),o.jsx(ln,{className:"text-neutral4! rounded-l-sm",children:t.version_detail.version})]}),o.jsx(ye,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(ngs,{server:t})})]})},ngs=({server:e})=>{const{data:t={},isLoading:n}=i7t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(vC,{})}),o.jsx(ye,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(sgs,{tool:a,serverId:e.id},s)})})]})};function rgs(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const sgs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=xn(),a=$7t[e.toolType||"tool"],i=rgs(e._meta);return o.jsxs(qf,{onClick:()=>n.current?.click(),children:[o.jsx(aDt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Wf,{children:[o.jsx(Hf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(ln,{className:"py-0 text-[10px]",children:"App"})]})}),o.jsx(ah,{children:e.description})]})]})},ags=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=eQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(tgs,{isLoading:n,server:r})})};function igs(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const ogs=({toolId:e,serverId:t})=>{const{canExecute:n}=Wo(),r=n("tools"),s=Ze(),{data:a,isLoading:i,error:l}=IIe(t,e),{mutateAsync:c,isPending:u,data:d}=Hes(t,e),f=a?igs(a._meta):void 0,{data:p}=gt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Fe.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(St,{className:"mb-4 h-8 w-48"}),o.jsx(St,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=hm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Fe.error("Failed to process tool input schema."),v=vs({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(a7t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(LIe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},lgs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=IIe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(ogs,{toolId:t,serverId:e})})},cVt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],PN="rootEntityType",$N={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},CQ=Object.keys($N),PAe="mastra:metrics:saved-filters";function cgs(e){const t=hgs(e);try{localStorage.setItem(PAe,t.toString())}catch{}}function ugs(){try{localStorage.removeItem(PAe)}catch{}}function uVt(){try{const e=localStorage.getItem(PAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function dgs(e){if(e.has(PN))return!0;for(const t of CQ)if(e.has($N[t]))return!0;return!1}function fgs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:cVt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function pgs(e){const t=[],n=new Map([[PN,"rootEntityType"]]);for(const s of CQ)n.set($N[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function hgs(e){const t=new URLSearchParams,n=e.getAll(PN);for(const r of n)t.append(PN,r);for(const r of CQ){const s=$N[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function mgs(e,t){e.delete(PN);for(const n of CQ)e.delete($N[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?PN:$N[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const ggs="Any";function Tet(e){const t=e.trim();return t===""||t===ggs}const vgs=new Set(cVt.map(e=>e.entityType));function jet(e){const t=e.trim();return vgs.has(t)?t:void 0}function ygs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Tet(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?jet(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Tet(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=jet(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const dVt=[{label:"Last 24 hours",value:"24h"},{label:"Last 3 days",value:"3d"},{label:"Last 7 days",value:"7d"},{label:"Last 14 days",value:"14d"},{label:"Last 30 days",value:"30d"}],bgs=new Set(dVt.map(e=>e.value));function xgs(e){return typeof e=="string"&&(bgs.has(e)||e==="custom")}const fVt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function EQ(){return g.useContext(fVt)}function wgs(e,t){return e!=="custom"?dVt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${or(t.from,"MMM d, yyyy")} – ${or(t.to,"MMM d, yyyy")}`:or(t.from,"MMM d, yyyy"):"Custom range"}function Sgs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>ygs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=wgs(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(fVt.Provider,{value:m,children:e})}const kgs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Ogs(e){switch(e){case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return"last-24h"}}function _gs(e){switch(e){case"last-3d":return"3d";case"last-7d":return"7d";case"last-14d":return"14d";case"last-30d":return"30d";case"custom":return"custom";default:return"24h"}}function Cgs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=EQ(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(h4,{preset:Ogs(e),onPresetChange:i=>{const l=_gs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:kgs})}const kxe=1440*60*1e3,Egs={"24h":kxe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Tgs(e,t,n){if(e!=="custom"){const r=Egs[e]??kxe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-kxe),end:t?.to??new Date(n)}}function $m(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=EQ(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>Tgs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function pVt(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function _L({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(BNn,{})})}function jgs({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(kIn,{})})}const Ngs=[{dataKey:"p50",label:"p50",color:qp.blue,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p50,0)/e.length)}`:"0",suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:qp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function Igs(e){return e==="agents"||e==="workflows"||e==="tools"}function mie({data:e,onPointClick:t}){return e.length===0?o.jsx(Gt.NoData,{message:"No latency data yet"}):o.jsx(qV,{data:e,series:Ngs,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function Ags({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Gt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Gt.Actions,{children:h}):null]}),t?o.jsx(Gt.Loading,{}):n?o.jsx(Gt.Error,{message:"Failed to load latency data"}):o.jsx(Gt.Content,{children:m?o.jsxs(pc,{value:p,onValueChange:b=>{Igs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(jr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(jr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(mie,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(mie,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(mie,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Gt.NoData,{message:"No latency data yet"})})]})}function Rgs(e){switch(e){case"24h":return"last-24h";case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return}}function Pgs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function hVt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=Rgs(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function mVt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Net({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set($w,"branches"),hVt(a,Mw,Dw,Lw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Wx,i),r.status&&a.set(Zx,r.status),$o(a,jl.entityName,r.entityName??n.entityName),$o(a,jl.threadId,r.threadId??n.threadId),$o(a,jl.resourceId,r.resourceId??n.resourceId),$o(a,jl.entityId,n.entityId),$o(a,jl.runId,n.runId),$o(a,jl.sessionId,n.sessionId),$o(a,jl.requestId,n.requestId),$o(a,jl.userId,n.userId),$o(a,jl.organizationId,n.organizationId),$o(a,jl.experimentId,n.experimentId),$o(a,jl.serviceName,n.serviceName),$o(a,jl.environment,n.environment),mVt(a,jl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function $gs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;hVt(a,Xb,Jb,ex,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Gx,i),$o(a,Nl.entityName,r.entityName??n.entityName),$o(a,Nl.threadId,r.threadId??n.threadId),$o(a,Nl.resourceId,r.resourceId??n.resourceId),$o(a,Nl.runId,n.runId),$o(a,Nl.sessionId,n.sessionId),$o(a,Nl.requestId,n.requestId),$o(a,Nl.userId,n.userId),$o(a,Nl.organizationId,n.organizationId),$o(a,Nl.experimentId,n.experimentId),$o(a,Nl.serviceName,n.serviceName),$o(a,Nl.environment,n.environment),mVt(a,Nl.tags,n.tags),r.status==="error"&&a.append(Nl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function rA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=EQ(),a=g.useCallback((c={})=>Net({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>$gs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=Pgs(u,d);return Net({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const gVt="1h";async function gie(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:gVt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function Mgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([gie(e,"mastra_agent_duration_ms",t),gie(e,"mastra_workflow_duration_ms",t),gie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:gVt}}})}const Iet={agents:Ec.AGENT,workflows:Ec.WORKFLOW_RUN,tools:Ec.TOOL};function Dgs(){const{data:e,isLoading:t,isError:n}=Mgs(),{getTracesHref:r,getBucketTracesHref:s}=rA(),{Link:a}=xn(),i=Ws();return o.jsx(Ags,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Iet[l]},c.tsMs,"1h"))},actions:l=>o.jsx(_L,{href:r({rootEntityType:Iet[l]}),LinkComponent:a})})}function Lgs(e){return e==="threads"||e==="resources"}function vie(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Fgs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Gt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Gt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Gt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Gt.Loading,{}):m.isError?o.jsx(Gt.Error,{message:"Failed to load memory data"}):o.jsx(Gt.Content,{children:o.jsxs(pc,{defaultTab:"threads",value:i,onValueChange:y=>{Lgs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"threads",children:"Threads"}),o.jsx(jr,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(ge,{columns:"auto auto auto auto auto",...pxe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:vie(y.threadId)}),o.jsx(ge.NumberCell,{children:y.resourceId?vie(y.resourceId):"—"}),o.jsx(ge.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ge.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(ge.NumberCell,{children:y.cost!=null?Vp(y.cost,y.costUnit):"—"})]});return b?o.jsx(ge.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ge.RowStatic,{children:x},y.key)})]}):o.jsx(Gt.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(ge,{columns:"auto auto auto auto",...pxe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:vie(y.resourceId)}),o.jsx(ge.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ge.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(ge.NumberCell,{children:y.cost!=null?Vp(y.cost,y.costUnit):"—"})]});return b?o.jsx(ge.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ge.RowStatic,{children:x},y.key)})]}):o.jsx(Gt.NoData,{message:"No resource activity yet"})})]})})]})}const yie=20;function zgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:yie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:yie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:yie})]),l=new Map,c=d=>nA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const bie=20;function Bgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:bie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:bie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:bie})]),l=new Map,c=d=>nA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function Ugs(){const e=zgs(),t=Bgs(),{getTracesHref:n}=rA(),{Link:r}=xn();return o.jsx(Fgs,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function CL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(es,{children:[o.jsx(es.Label,{children:e}),o.jsx(es.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(es.Error,{}):s?o.jsx(es.Loading,{}):i?r!=null?o.jsx(es.Change,{changePct:r,prevValue:n}):o.jsx(es.NoChange,{}):o.jsx(es.NoData,{})]})}function Vgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function qgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function Hgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function Wgs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function Zgs(){const{data:e,isLoading:t,isError:n}=pVt();return o.jsx(CL,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Ggs(){const{data:e,isLoading:t,isError:n}=Hgs();return o.jsx(CL,{label:"Total Model Cost",value:e?.cost!=null?Vp(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Vp(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Qgs(){const{data:e,isLoading:t,isError:n}=Wgs();return o.jsx(CL,{label:"Total Tokens",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Ygs(){const{data:e,isLoading:t,isError:n}=qgs();return o.jsx(CL,{label:"Total Threads",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Kgs(){const{data:e,isLoading:t,isError:n}=Vgs();return o.jsx(CL,{label:"Total Resources",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Xgs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Jgs(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(cAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(oAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Jgs(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}function evs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Vp(l):"—":c.size===1?u=l>0?Vp(l,[...c][0]):"—":u="Mixed",o.jsx(Gt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Gt.Actions,{children:s}):null]}),t?o.jsx(Gt.Loading,{}):n?o.jsx(Gt.Error,{message:"Failed to load model usage data"}):o.jsx(Gt.Content,{children:i?o.jsxs(ge,{columns:"auto auto auto auto auto auto",...pxe,children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{sticky:"start",children:"Model"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ge.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ge.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(ge.NumberCell,{children:l.input}),o.jsx(ge.NumberCell,{children:l.output}),o.jsx(ge.NumberCell,{children:l.cacheRead}),o.jsx(ge.NumberCell,{children:l.cacheWrite}),o.jsx(ge.NumberCell,{highlight:!0,children:l.cost!=null?Vp(l.cost,l.costUnit):"—"})]});return c?o.jsx(ge.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ge.RowStatic,{children:u},l.model)})]}):o.jsx(Gt.NoData,{message:"No model usage data yet"})})]})}function tvs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>nA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:al(f.input),output:al(f.output),cacheRead:al(f.cacheRead),cacheWrite:al(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function nvs(){const{data:e,isLoading:t,isError:n}=tvs(),{getTracesHref:r}=rA(),{Link:s}=xn();return o.jsx(evs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Ec.AGENT}),actions:o.jsx(_L,{href:r({rootEntityType:Ec.AGENT}),LinkComponent:s})})}function rvs(e){return e==="tokens"||e==="cost"}function svs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&v>0;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Gt.Summary,{value:Vp(v,m),label:"Total cost"}):o.jsx(Gt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Gt.Actions,{children:s}):null]}),t?o.jsx(Gt.Loading,{}):n?o.jsx(Gt.Error,{message:"Failed to load token usage data"}):o.jsx(Gt.Content,{children:u?o.jsxs(pc,{defaultTab:"tokens",value:i,onValueChange:b=>{rvs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"tokens",children:"Tokens"}),o.jsx(jr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(RN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:qp.blueDark},{label:"Output",color:qp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:al})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(RN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:qp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Vp(b,m)}):o.jsx(Gt.NoData,{message:"No cost data yet"})})]}):o.jsx(Gt.NoData,{message:"No token usage data yet"})})]})}function avs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>nA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function ivs(){const{data:e,isLoading:t,isError:n}=avs(),{getTracesHref:r}=rA(),{Link:s}=xn();return o.jsx(svs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Ec.AGENT,entityName:a.name}),actions:o.jsx(_L,{href:r({rootEntityType:Ec.AGENT}),LinkComponent:s})})}function Oxe(e,t=al){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const ovs=[{dataKey:"input",label:"Input tokens",color:qp.blue,aggregate:Oxe("input")},{dataKey:"output",label:"Output tokens",color:qp.yellow,aggregate:Oxe("output")}];function lvs(e){return e==="tokens"||e==="cost"}function cvs({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:qp.purple,aggregate:Oxe("cost",k=>Vp(k,v))}];return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Gt.Summary,{value:Vp(y,v),label:"Total cost"}):o.jsx(Gt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Gt.Actions,{children:s}):null]}),n?o.jsx(Gt.Loading,{}):r?o.jsx(Gt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Gt.Content,{children:u?o.jsxs(pc,{defaultTab:"tokens",value:a,onValueChange:k=>{lvs(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"tokens",children:"Tokens"}),o.jsx(jr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(qV,{data:c,series:ovs})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(qV,{data:p,series:S}):o.jsx(Gt.NoData,{message:"No cost data yet"})})]}):o.jsx(Gt.NoData,{message:"No token usage data yet"})})]})}function uvs(e){return e==="24h"?"1h":"1d"}function dvs(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function Aet(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function fvs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function pvs(){const e=Ze(),{datePreset:t,filters:n,filterKey:r}=$m(),s=uvs(t);return gt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Aet(l,a.series[0],"input"),Aet(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:dvs(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:fvs(u)}}),interval:s}}})}function hvs(){const{data:e,isLoading:t,isError:n}=pvs(),{getTracesHref:r}=rA(),{Link:s}=xn();return o.jsx(cvs,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(_L,{href:r(),LinkComponent:s})})}function xie({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(RN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:qp.blueDark},{label:"Errors",color:qp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:al})}function mvs({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Gt,{children:[o.jsxs(Gt.TopBar,{children:[o.jsx(Gt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Gt.Summary,{value:al(f),label:"Total runs"}),u?o.jsx(Gt.Actions,{children:u}):null]}),t?o.jsx(Gt.Loading,{}):n?o.jsx(Gt.Error,{message:"Failed to load trace volume data"}):o.jsx(Gt.Content,{children:d?o.jsxs(pc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"agents",children:"Agents"}),o.jsx(jr,{value:"workflows",children:"Workflows"}),o.jsx(jr,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(xie,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Gt.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(xie,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Gt.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(xie,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Gt.NoData,{message:"No tool data yet"})})]}):o.jsx(Gt.NoData,{message:"No trace volume data yet"})})]})}async function wie(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=nA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function gvs(){const e=Ze(),{filters:t,filterKey:n}=$m();return gt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([wie(e,"mastra_agent_duration_ms",t),wie(e,"mastra_workflow_duration_ms",t),wie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const Lz={agents:Ec.AGENT,workflows:Ec.WORKFLOW_RUN,tools:Ec.TOOL};function vvs(){const{data:e,isLoading:t,isError:n}=gvs(),{getTracesHref:r,getLogsHref:s}=rA(),{Link:a}=xn();return o.jsx(mvs,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:Lz[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:Lz[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(_L,{href:r({rootEntityType:Lz[i]}),LinkComponent:a}),o.jsx(jgs,{href:s({rootEntityType:Lz[i],status:"error"}),LinkComponent:a})]})})}const Sie="period",Fz="dateFrom",zz="dateTo";function yvs(){const[e,t]=si(),n=e.get(Sie),r=xgs(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(Fz)),p=d(e.get(zz));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>pgs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Sie):p.set(Sie,d),d!=="custom"&&(p.delete(Fz),p.delete(zz)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(Fz,d.from.toISOString()):p.delete(Fz),d?.to?p.set(zz,d.to.toISOString()):p.delete(zz),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return mgs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,dgs(e)))return;const d=uVt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Sgs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(bvs,{})})}function bvs(){const[e]=si(),{error:t,isLoading:n}=pVt(),{filterTokens:r,setFilterTokens:s}=EQ(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=kAe(),{data:d,isLoading:f}=xAe(),{data:p,isLoading:h}=vAe(),{data:m,isLoading:v}=bAe(),{data:y,isLoading:b}=yAe(),x=g.useMemo(()=>fgs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[S,k]=g.useState(()=>uVt()!==null),_=g.useCallback(()=>{cgs(e),k(!0),Fe.success("Filters setting for Metrics saved")},[e]),C=g.useCallback(()=>{ugs(),k(!1),Fe.success("Filters setting for Metrics cleared up")},[]),E=g.useCallback(()=>{s([])},[s]),T=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&xs(t)?o.jsx(cr,{children:o.jsx(Zs,{})}):t&&Ss(t)?o.jsx(cr,{children:o.jsx($s,{resource:"metrics"})}):t?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Cgs,{}),o.jsx(uAe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(Xgs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:T,onRemoveAll:E,onSave:_,onRemoveSaved:S?C:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(Sn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Sn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(yxe,{children:[o.jsx(Zgs,{}),o.jsx(Ggs,{}),o.jsx(Qgs,{}),o.jsx(Ygs,{}),o.jsx(Kgs,{})]}),o.jsxs(yxe,{children:[o.jsx(nvs,{}),o.jsx(ivs,{}),o.jsx(hvs,{}),o.jsx(Ugs,{}),o.jsx(vvs,{}),o.jsx(Dgs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Df,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Oa,{})]})})})]})}const xvs=50;function wvs(){const{paths:e}=xn(),{isCmsAvailable:t}=uS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=D7t({page:s,perPage:xvs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=g.useCallback(()=>{u||a(v=>v+1)},[u]),h=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&xs(c)?o.jsx(cr,{children:o.jsx(Zs,{})}):c&&Ss(c)?o.jsx(cr,{children:o.jsx($s,{resource:"prompt blocks"})}):c?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(cr,{children:o.jsx(Jss,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Uf,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(le,{as:ni,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Zr,{}),"Create Prompt"]})]})}),o.jsx(Xss,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function Svs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx(Its,{children:o.jsx(Hbe,{})})})})}const kvs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:DGt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:llt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Oa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:mj,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:glt,href:"https://mastra.ai/cloud",external:!0},{title:"Talk to our Sales team",description:"Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.",icon:clt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Ovs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:kvs.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(Oa,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function _vs(){const{data:e={},isLoading:t,error:n}=uh(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&xs(n))return o.jsx(cr,{children:o.jsx(Zs,{})});if(n&&Ss(n))return o.jsx(cr,{children:o.jsx($s,{resource:"scorers"})});if(n)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(cr,{children:o.jsx(irs,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(lrs,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(ars,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Cvs(){const{scorerId:e}=Sr(),[t,n]=si(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=Mns(e),{data:d={},isLoading:f,error:p}=Im(),{isLoading:h,error:m}=Wy(),{data:v=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k}=$ns({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=g.useMemo(()=>c?.agentIds?.filter(V=>d[V]).map(V=>({value:V,label:d[V].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=g.useMemo(()=>c?.workflowIds?.map(V=>({value:V,label:V,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),T=t.get("entity")??"all",N=E.find(V=>V.value===T);N&&N.value!==i?.value&&l(N),g.useEffect(()=>{if(u){const V=u instanceof Error?u.message:"Failed to load scorer";Fe.error(`Error loading scorer: ${V}`)}},[u]),g.useEffect(()=>{if(p){const V=p instanceof Error?p.message:"Failed to load agents";Fe.error(`Error loading agents: ${V}`)}},[p]),g.useEffect(()=>{if(m){const V=m instanceof Error?m.message:"Failed to load workflows";Fe.error(`Error loading workflows: ${V}`)}},[m]);const I=V=>{V?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",V.value),G})};g.useEffect(()=>{const V=t.get("scoreId")??void 0;if(V===s)return;if(!V){a(void 0);return}v.find(G=>G.id===V)&&a(V)},[t,v]);const A=g.useCallback(V=>{a(V||void 0),n(M=>{const G=new URLSearchParams(M);return V?G.set("scoreId",V):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=xs(u)||xs(p)||xs(m),L=u&&Ss(u),D=!R&&!L&&(u||p||m),F=!y&&v.length===0,H=i?.value!=="all",B=c?.scorer?.source==="stored"?o.jsx(My,{owner:"scorer-detail",children:o.jsxs(le,{variant:"default",as:ni,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(lm,{})," Edit"]})}):null;if(R||L||D||F&&!H){const V=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Vt,{width:"wide",height:"full",children:[B,o.jsx(Vt.MainArea,{isCentered:!0,children:R?o.jsx(Zs,{}):L?o.jsx($s,{resource:"scorers"}):D?o.jsx(Hi,{title:"Failed to load scorer",message:V}):o.jsx(Tns,{})})]})}return o.jsxs(Vt,{width:"wide",children:[B,o.jsx(Vt.TopArea,{children:o.jsx(jns,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(V=>{const M=new URLSearchParams(V);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(Ens,{scores:v,isLoading:y,selectedScoreId:s,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function Evs({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:X("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Lt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-neutral3 text-sm",children:t})]}),s]})}const vVt=[{value:"dark",label:"Dark",Icon:mYt},{value:"light",label:"Light",Icon:EKt},{value:"system",label:"System",Icon:klt}],Tvs=e=>vVt.some(t=>t.value===e);function jvs({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const Nvs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=fH(),{theme:r,setTheme:s}=q_();return o.jsx(Vt,{width:"narrow",children:o.jsxs(Vt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(_be,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Evs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ma,{value:r,onValueChange:a=>{Tvs(a)&&s(a)},children:[o.jsx(va,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ga,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(ya,{children:vVt.map(a=>o.jsx(Rr,{value:a.value,children:o.jsx(jvs,{option:a})},a.value))})]})})}),o.jsx(_be,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(r3t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Ivs(){const[e]=si(),t=Ws(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(oVt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const yVt=e=>o.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})});function Avs(e){return e.replace(/\/$/,"").split("/").pop()}function TQ({children:e,className:t}){return o.jsx("div",{className:X("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function Rvs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:X("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:X("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:X("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:X("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:X("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:X("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:X("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Vo,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Bd,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Olt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(qN,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(vC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:X("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(yVt,{})," ",Avs(a.githubUrl)]})})]},a.slug)})})}function Pvs({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:X("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:X("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(yN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Cc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Cc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(le,{onClick:c,children:["Reset ",o.jsx(ws,{})]})]})}function $vs(){const{data:e,isLoading:t}=Lnr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(fs,{children:[o.jsx(F1e,{children:o.jsxs(Iyt,{children:[o.jsx(qe,{children:o.jsx(Jv,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Pvs,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Rvs,{templates:y,linkComponent:ni,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Mvs="1.61.0-alpha.1";function Dvs({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(_f,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(fQt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(TQ,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function Lvs({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(TQ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:X("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(_lt,{})]}),o.jsx(Cc,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:X("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(en,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(IO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(IO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(p7t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(le,{className:X("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(en,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(xm,{})]})})]})})}function Fvs({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:X("grid mt-8 items-center"),children:o.jsxs("div",{className:X("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(Jv,{}),o.jsx("h2",{className:X({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:X("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:X("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(Yx,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Fxe,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(yVt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(PIe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Ret(e){switch(e){case"running":return o.jsx(en,{size:"sm","aria-hidden":!0});case"success":return o.jsx(gy,{"aria-hidden":!0});case"failed":return o.jsx(fu,{"aria-hidden":!0});default:return null}}function zvs(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function Bvs({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:X("flex size-4 items-center justify-center self-center [&>svg]:size-4",Wr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(zvs,{}):Ret(e)}):o.jsx("span",{className:X("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Wr.colors,Wr.transform,Wr.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:Ret(e)})}function Uvs({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Wr.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:X("flex min-w-6 justify-end text-ui-md",Wr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:X("text-ui-md",Wr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:X("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(Bvs,{status:e.status,variant:r})]})}function Vvs({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(Uvs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function qvs({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:X("relative flex h-8 items-center justify-end",Wr.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:X("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",Wr.colors,Wr.transform,Wr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(en,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",Wr.colors),children:[n," of ",t," steps completed"]})]})}function Hvs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(TQ,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(qvs,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:X("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(_Yt,{}),l||"Something went wrong"]}),u&&o.jsx(Vvs,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(en,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Wvs({name:e,installedEntities:t}){return o.jsxs(TQ,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(_lt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx(PIe,{data:t})]})}function Zvs(){const{templateSlug:e}=Sr(),[t,n]=si(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[E,T]=g.useState([]),{data:N,isLoading:I}=Fnr({repoOrSlug:e,owner:"mastra-ai"}),R=Mvs?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=znr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:F,isLoading:H}=Bnr(),{mutateAsync:B,isPending:U}=Unr(),{mutateAsync:V}=Vnr(),{streamInstall:M,streamResult:G,isStreaming:q}=Hnr(F),{observeInstall:$,streamResult:z,isStreaming:Z}=Wnr(F);g.useEffect(()=>{const te=t.get("runId");te&&!v&&!h&&!q&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:te}),x(te),V({runId:te}).then(ue=>{const fe=ue.snapshot;if(fe?.status==="success"&&fe?.result?.success)y(!0);else if(fe?.result?.success===!1)if(fe?.result?.validationResults&&!fe?.result?.validationResults?.valid&&fe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:me,errors:be}=fe.result.validationResults,we=`Template installation completed but ${me} validation issue${me>1?"s":""} remain unresolved.`;m(we),T(be||[])}else{const me=fe?.result?.message||fe?.result?.error||"Template installation failed";m(typeof me=="string"?me:String(me))}}).catch(ue=>{console.error("❌ Failed to fetch run details:",ue),m("Failed to retrieve installation status after reload")}))},[t,v,h,q,Z,V]),g.useEffect(()=>{const te=t.get("runId"),ue=t.get("resume"),fe=t.get("provider");if(te&&ue==="true"&&fe&&!q&&!Z&&!S&&!_&&F){x(te),k(!0);try{V({runId:te}).then(ce=>{if(ce.snapshot?.status==="running")return $.mutateAsync({runId:te})}).then(()=>{n(ce=>{const me=new URLSearchParams(ce);return me.delete("resume"),me})}).catch(ce=>{console.error("❌ Failed to resume template installation:",ce),ce.message?.includes("404")||ce.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(ce){console.error("❌ Auto-resume failed with error:",ce),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,q,Z,S,_,F,V,$,n]);const K=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],ne=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(te=>te).join(", "):"n/a",icon:o.jsx(Bd,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(te=>te).join(", "):"n/a",icon:o.jsx(Vo,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(te=>te).join(", "):"n/a",icon:o.jsx(qN,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Lv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(VN,{})}],ee=[{...ne[0]},{...ne[1]},{...ne[2]}].filter(te=>te.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const te=G||z;te?.phase==="error"&&te?.error&&m(typeof te.error=="string"?te.error:String(te.error))},[G?.phase,G?.error,z?.phase,z?.error]);const J=te=>{s(te)},ae=async te=>(i(te.provider),c(te.modelId),{message:"Model updated successfully"}),pe=async()=>{const te=Object.entries(u).reduce((ue,[fe,ce])=>(ce===""&&ue.push(fe),ue),[]);if(te.length>0){p(te);return}if(N){m(null),y(!1),x(""),C(!0);try{const fe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ce}=await B({});x(ce),n(me=>{const be=new URLSearchParams(me);return be.set("runId",ce),be.set("resume","true"),be.set("provider",r||"openai"),be}),await M.mutateAsync({inputData:fe,selectedModel:{provider:a,modelId:l},runId:ce})}catch(ue){C(!1),m(ue?.message||"Template installation failed"),console.error("Template installation failed",ue)}}},Y=te=>{const{name:ue,value:fe}=te.target;fe.trim()===""?p(ce=>[...ce,ue]):p(ce=>ce.filter(me=>me!==ue)),d(ce=>({...ce,[ue]:fe}))};return o.jsx(fs,{children:o.jsx("div",{className:X("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(Fvs,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:ne,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(q||Z)&&o.jsx(Hvs,{name:N.title,streamResult:Z?z:G,runId:b,workflowInfo:F}),v&&o.jsx(Wvs,{name:N.title,installedEntities:ee,linkComponent:ni}),h&&o.jsx(Dvs,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||z?.validationResults?.errors}),!q&&!Z&&!v&&!h&&o.jsx(Lvs,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:pe,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:U,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Gvs=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(gss,{toolId:e,agentId:t})})},Qvs=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Jms,{toolId:e})})};function Yvs(){const{traceId:e}=Sr(),[t,n]=si(),r=Ws(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=g.useState(s??null),[d,f]=g.useState(),[p,h]=g.useState(i),[m,v]=g.useState(0),[y,b]=g.useState(!1),{data:x,isLoading:S,error:k}=wAe(e),_=g.useMemo(()=>x?.spans??[],[x?.spans]),C=g.useMemo(()=>_.find(Y=>Y.parentSpanId==null),[_]),E=kAe(),T=mxe({traceIds:[e],enabled:!E.isLoading&&E.supportsMetrics,autoRefetch:!1}),{data:N,isLoading:I}=kL(e,c??"");g.useEffect(()=>v(0),[e,c]);const{data:A,isLoading:R}=uh(),{data:L,isLoading:D}=A7t({traceId:e,spanId:c??void 0,page:m}),[F,H]=g.useState(0);g.useEffect(()=>H(0),[e,c]);const{data:B,isLoading:U}=ZUt({traceId:e,page:F});g.useEffect(()=>{if(l&&L?.scores&&!d){const Y=L.scores.find(te=>te.id===l);Y&&f(Y)}},[l,L?.scores,d]);const V=g.useCallback(Y=>{const te=new URLSearchParams(t);for(const[ue,fe]of Object.entries(Y))fe===null||fe===""?te.delete(ue):te.set(ue,fe);n(te,{replace:!0})},[t,n]),M=g.useCallback(Y=>{const te=Y??null,ue=te===c;u(te),ue||(f(void 0),h("details"),V({spanId:te,tab:null,scoreId:null}))},[c,V]),G=g.useCallback(()=>{u(null),f(void 0),h("details"),V({spanId:null,tab:null,scoreId:null})},[V]),q=g.useCallback(Y=>{u(Y),f(void 0),h("details"),V({spanId:Y,tab:null,scoreId:null})},[V]),{handlePreviousSpan:$,handleNextSpan:z}=SAe(_,c,q),Z=g.useCallback(Y=>{const te=Y;h(te),f(void 0),V({tab:te==="details"?null:te,scoreId:null})},[V]),K=g.useCallback(Y=>{f(Y),V({scoreId:Y.id})},[V]),ne=g.useCallback(()=>{f(void 0),V({scoreId:null})},[V]),ee=g.useCallback(()=>{r("/traces")},[r]),J=g.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),V({spanId:C.spanId,tab:"scoring",scoreId:null})):V({tab:"scoring"})},[C,c,V]),ae=C?o.jsx(My,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(le,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:J,children:[o.jsx(aGt,{}),"Evaluate"]}),o.jsxs(le,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(Nd,{}),"Save"]})]})}):null,pe=C?o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{children:o.jsx(IUt,{rootSpan:C,usage:T.data?.get(e),numOfCol:3})})}):null;return k?o.jsxs(Vt,{height:"full",children:[ae,pe&&o.jsx(Vt.TopArea,{children:pe}),o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(MUt,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Vt,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[ae,pe&&o.jsx(Vt.TopArea,{children:pe}),o.jsx(UUt,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:X("mt-4 grid min-h-0 items-stretch gap-4 overflow-hidden",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(hAe,{traceId:e,spans:_,isLoading:S,onClose:ee,onSpanSelect:M,onEvaluateTrace:J,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&o.jsxs("div",{className:X("grid h-full max-h-full min-h-0 gap-4 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(dAe,{traceId:e,spanId:c,span:N?.span,isLoading:I,onClose:G,onPrevious:$,onNext:z,activeTab:p,onTabChange:Z,feedbackTabBadge:B?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(qUt,{feedbackData:B,onPageChange:H,isLoadingFeedbackData:U}),scoringTabBadge:L?.pagination?.total??void 0,scoringTabSlot:({span:Y,traceId:te,spanId:ue})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(WUt,{traceId:te,isTopLevelSpan:!Y.parentSpanId,spanId:ue,entityType:Y.attributes?.agentId||Y.entityType===Ec.AGENT?"Agent":Y.attributes?.workflowId||Y.entityType===Ec.WORKFLOW_RUN?"Workflow":void 0,scorers:A,isLoadingScorers:R}),o.jsx(HUt,{scoresData:L,onPageChange:v,isLoadingScoresData:D,onScoreSelect:K})]})}),d&&o.jsx(RIe,{score:d,onClose:ne})]})]})]})}function Kvs(){const{data:e,isLoading:t,error:n}=Wy(),[r,s]=g.useState("");return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"workflows"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(cr,{children:o.jsx(zqr,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Uf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(le,{as:ni,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(ID,{}),"Schedules"]})]})}),o.jsx(Fqr,{workflows:e||{},isLoading:t,search:r})]})}const Xvs={active:"bg-accent1",paused:"bg-accent3"},Jvs={active:"text-accent1",paused:"text-accent3"},bVt=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Xvs[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Jvs[e]}`,children:e})]}),uj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),H2=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function xVt({status:e}){const{icon:t,color:n}=eys(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function eys(e){switch(e){case"success":return{icon:o.jsx(da,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(ws,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(en,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(tq,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Df,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(hj,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const Pet="auto auto auto auto 1fr";function tys(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function nys(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const rys=3e4,sys=5*6e4;function ays({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=xn();return t?o.jsx(ol,{columns:Pet}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ge,{columns:Pet,className:"min-w-0",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Run"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{children:"Started"}),o.jsx(ge.TopCell,{children:"Duration"}),o.jsx(ge.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=nys(u),f=`Scheduled ${uj(c.scheduledFireAt)} — published ${uj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),v=!p&&m>rys&&m<=sys,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),x=o.jsx("span",{className:b?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(ge.Cell,{height:"compact",children:x}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(_f,{size:14}),"publish failed"]}):c.run?o.jsx(xVt,{status:c.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),h?o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(_f,{size:14})})}),o.jsx(On,{children:h})]}):null]})}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:H2(c.actualFireAt)}),v?o.jsxs(Tn,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(_f,{size:14})})}),o.jsxs(On,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(ge.Cell,{height:"compact",children:c.run?o.jsx("span",{children:tys(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ge.Cell,{height:"compact",children:" "})]});return b?o.jsx(ge.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(ge.RowStatic,{children:S},y)}),o.jsx(ge.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const iys=e=>{const t=Ze();return gt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},$et=25,oys=e=>{const t=Ze(),{inView:n,setRef:r}=Q_(),s=G1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:$et,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<$et))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},lys=e=>{const t=Ze(),n=Br();return Dn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),Fe.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Fe.error(r.message)}})};function Bz({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function cys(){const{scheduleId:e}=Sr(),{paths:t}=xn(),{data:n,error:r}=iys(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=oys(e),d=lys(e);if(r&&xs(r))return o.jsx(cr,{children:o.jsx(Zs,{})});if(r&&Ss(r))return o.jsx(cr,{children:o.jsx($s,{resource:"schedules"})});if(r)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{className:"justify-end",children:o.jsxs(Vt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(le,{as:ni,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Rc,{}),"Back to schedules"]}),f?o.jsx(le,{as:ni,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(le,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(Vxe,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Hp,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(Bz,{label:p?"Agent":"Workflow",children:f?o.jsx(ni,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(ni,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(Bz,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(Bz,{label:"Status",children:o.jsx(bVt,{status:n.status})}),o.jsx(Bz,{label:"Next fire",children:o.jsx("span",{title:uj(n.nextFireAt),children:H2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ye,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Hi,{title:"Failed to load trigger history",message:i.message}):o.jsx(ays,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Met="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function uys({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=xn(),a=g.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(ol,{columns:Met}):o.jsxs(ge,{columns:Met,variant:"striped",className:"min-w-0",children:[o.jsxs(ge.Top,{children:[o.jsx(ge.TopCell,{children:"Target"}),o.jsx(ge.TopCell,{children:"Schedule ID"}),o.jsx(ge.TopCell,{children:"Cron"}),o.jsx(ge.TopCell,{children:"Status"}),o.jsx(ge.TopCell,{children:"Next fire"}),o.jsx(ge.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ge.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ge.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(ge.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(ge.NameCell,{children:i.workflowId??i.agentId}),o.jsx(ge.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:i.id,children:i.id})}),o.jsx(ge.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(ge.Cell,{height:"compact",children:o.jsx(bVt,{status:i.status})}),o.jsx(ge.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:uj(i.nextFireAt),children:H2(i.nextFireAt)})}),o.jsx(ge.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(xVt,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:uj(i.lastFireAt),children:i.lastFireAt?H2(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:uj(i.lastFireAt),children:H2(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function dys({workflowId:e}={}){const{data:t,isLoading:n,error:r}=D1e(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Hi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(Uf,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(uys,{schedules:t??[],isLoading:n,search:s})})]})}function fys(){const[e]=si(),t=e.get("workflowId")??void 0,{error:n}=D1e(t?{workflowId:t}:{});return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"schedules"})}):o.jsx(Vt,{children:o.jsx("div",{className:"h-full",children:o.jsx(dys,{workflowId:t})})})}function pys({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=fOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=i_t(r),[d]=o_t(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=z4t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(a_t,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(oje,{position:"bottom-left"}),o.jsx(c_t,{variant:ay.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(en,{})})})}function hys(){const{stepDetail:e,closeStepDetail:t}=iW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(h9,{className:"h-4 w-4",style:{color:Iu.map}}),e.type==="nested-graph"&&o.jsx(td,{className:"h-4 w-4",style:{color:Iu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(ws,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(U2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(dOe,{children:o.jsx(pys,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function mys(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function gys(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);if(n.length===1)return n[0]}return t}function vys({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ye,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(qe,{children:o.jsx(tq,{})}),"Step suspended"]}),o.jsx(ln,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?hm(Tx(i.resumeSchema)):lf(fr(),vf());return o.jsx(yys,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function yys({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(vYt,{})}),"The step is asking"]}),o.jsxs(Ld,{open:a,onOpenChange:i,children:[o.jsxs(Ku,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(qe,{children:o.jsx(aa,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:gys(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:mys(e.suspendPayload)})]}),o.jsx(Xu,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Hr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(xYt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(WB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Hp,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function bys(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(ql),{runId:a}=Sr(),i=g_t(e,r??""),l=eer(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(vys,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const xys=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),wys=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),Sys=e=>e.includes("."),kys=e=>e==="input"||e.endsWith(".input"),Oys=1;function _ys(e){return`${Number((e/1e3).toPrecision(3))}s`}function Cys(e,t){const n=Object.entries(e).filter(([i])=>!kys(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,p=Math.max(d/a*100,Oys);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:Sys(i)}})}const Eys=({status:e})=>o.jsxs(qe,{children:[e==="success"&&o.jsx(xys,{className:"text-accent1"}),e==="failed"&&o.jsx(wys,{className:"text-accent2"}),e==="suspended"&&o.jsx(tq,{className:"text-accent3"}),e==="waiting"&&o.jsx(ppe,{className:"text-accent5"}),e==="skipped"&&o.jsx(ppe,{className:"text-icon3"}),e==="running"&&o.jsx(ca,{className:"text-accent6 animate-spin"})]}),Tys={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function wVt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const Det=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},jys=e=>{const t=e;return I4t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},Nys=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=jys(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:X("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(Eys,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(wKt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(EV,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:wVt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${Tys[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(bKt,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:_ys(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function Iys(){const{steps:e}=P4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=bH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Vyt(f,{enabled:!l});const p=Cys(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Na,{className:X("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(Nys,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:Det(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:Det(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(y_t,{data:u.data,title:`${wVt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Ays=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=iW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(G4t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(bys,{}),o.jsx(Iys,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(hys,{})})]})},Let=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=V3(e);return r&&xs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})}):r&&Ss(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"workflows"})}):o.jsx(NOe,{children:o.jsx(Ays,{workflowId:e,workflow:t??void 0,isLoading:n})})};function Rys(e,t){if(e==null)return{};var n,r,s=SSt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function _xe(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Pys(e){if(Array.isArray(e))return _xe(e)}function $ys(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Mys(e,t){if(e){if(typeof e=="string")return _xe(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_xe(e,t):void 0}}function Dys(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
643
643
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Cxe(e){return Pys(e)||$ys(e)||Mys(e)||Dys()}function ED(e){"@babel/helpers - typeof";return ED=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ED(e)}function Lys(e,t){if(ED(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(ED(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Fys(e){var t=Lys(e,"string");return ED(t)=="symbol"?t:t+""}function SVt(e,t,n){return(t=Fys(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fet(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function OT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Fet(Object(n),!0).forEach(function(r){SVt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Fet(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function zys(e){var t=e.length;if(t===0||t===1)return e;if(t===2)return[e[0],e[1],"".concat(e[0],".").concat(e[1]),"".concat(e[1],".").concat(e[0])];if(t===3)return[e[0],e[1],e[2],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0])];if(t>=4)return[e[0],e[1],e[2],e[3],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[2],".").concat(e[3]),"".concat(e[3],".").concat(e[0]),"".concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[0]),"".concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[3],".").concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[2],".").concat(e[1],".").concat(e[0])]}var kie={};function Bys(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return kie[t]||(kie[t]=zys(e)),kie[t]}function Uys(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(a){return a!=="token"}),s=Bys(r);return s.reduce(function(a,i){return OT(OT({},a),n[i])},t)}function zet(e){return e.join(" ")}function Vys(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return kVt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function kVt(e){var t=e.node,n=e.stylesheet,r=e.style,s=r===void 0?{}:r,a=e.useInlineStyles,i=e.key,l=t.properties,c=t.type,u=t.tagName,d=t.value;if(c==="text")return d;if(u){var f=Vys(n,a),p;if(!a)p=OT(OT({},l),{},{className:zet(l.className)});else{var h=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(S){b.includes(S)||b.push(S)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],v=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=OT(OT({},l),{},{className:zet(v)||void 0,style:Uys(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return ze.createElement(u,WO({key:i},p),y)}}const qys=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var Hys=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function Bet(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function Fw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Bet(Object(n),!0).forEach(function(r){SVt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Bet(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var Wys=/\n/g;function Zys(e){return e.match(Wys)}function Gys(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return ze.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
|
|
644
644
|
`))})}function Qys(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,s=r===void 0?{float:"left",paddingRight:"10px"}:r,a=e.numberStyle,i=a===void 0?{}:a,l=e.startingLineNumber;return ze.createElement("code",{style:Object.assign({},n,s)},Gys({lines:t.replace(/\n$/,"").split(`
|
|
645
645
|
`),style:i,startingLineNumber:l}))}function Yys(e){return"".concat(e.toString().length,".25em")}function OVt(e,t){return{type:"element",tagName:"span",properties:{key:"line-number--".concat(e),className:["comment","linenumber","react-syntax-highlighter-line-number"],style:t},children:[{type:"text",value:e}]}}function _Vt(e,t,n){var r={display:"inline-block",minWidth:Yys(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=Fw(Fw({},r),s);return a}function u9(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,s=e.largestLineNumber,a=e.showInlineLineNumbers,i=e.lineProps,l=i===void 0?{}:i,c=e.className,u=c===void 0?[]:c,d=e.showLineNumbers,f=e.wrapLongLines,p=e.wrapLines,h=p===void 0?!1:p,m=h?Fw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(Cxe(m.className.trim().split(/\s+/)),Cxe(u)):u,n&&a){var v=_Vt(r,n,s);t.unshift(OVt(n,v))}return f&d&&(m.style=Fw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function CVt(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],r=0;r<e.length;r++){var s=e[r];if(s.type==="text")n.push(u9({children:[s],className:Cxe(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);CVt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function Kys(e,t,n,r,s,a,i,l,c){var u,d=CVt(e.value),f=[],p=-1,h=0;function m(_,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return u9({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:E,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(_,C){if(r&&C&&s){var E=_Vt(l,C,i);_.unshift(OVt(C,E))}return _}function y(_,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||E.length>0?m(_,C,E):v(_,C)}for(var b=function(){var C=d[h],E=C.children[0].value,T=Zys(E);if(T){var N=E.split(`
|