@mastra/deployer-cloud 1.71.0-alpha.1 → 1.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-CGlHLIis.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]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-CaKkm_q3.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 Bo}from"./preload-helper-PPVm8Dsz.js";function Nrn(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 o=Object.getOwnPropertyDescriptor(r,s);o&&Object.defineProperty(e,s,o.get?o:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var G7=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var pte={exports:{}},PP={};var c3e;function Irn(){if(c3e)return PP;c3e=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,o){var i=null;if(o!==void 0&&(i=""+o),s.key!==void 0&&(i=""+s.key),"key"in s){o={};for(var l in s)l!=="key"&&(o[l]=s[l])}else o=s;return s=o.ref,{$$typeof:e,type:r,key:i,ref:s!==void 0?s:null,props:o}}return PP.Fragment=t,PP.jsx=n,PP.jsxs=n,PP}var u3e;function Arn(){return u3e||(u3e=1,pte.exports=Irn()),pte.exports}var a=Arn(),hte={exports:{}},Qr={},d3e;function Rrn(){if(d3e)return Qr;d3e=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"),o=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(L){return L===null||typeof L!="object"?null:(L=h&&L[h]||L["@@iterator"],typeof L=="function"?L:null)}var y={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,b={};function x(L,R,M){this.props=L,this.context=R,this.refs=b,this.updater=M||y}x.prototype.isReactComponent={},x.prototype.setState=function(L,R){if(typeof L!="object"&&typeof L!="function"&&L!=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,L,R,"setState")},x.prototype.forceUpdate=function(L){this.updater.enqueueForceUpdate(this,L,"forceUpdate")};function w(){}w.prototype=x.prototype;function k(L,R,M){this.props=L,this.context=R,this.refs=b,this.updater=M||y}var _=k.prototype=new w;_.constructor=k,v(_,x.prototype),_.isPureReactComponent=!0;var C=Array.isArray;function T(){}var E={H:null,A:null,T:null,S:null},I=Object.prototype.hasOwnProperty;function N(L,R,M){var U=M.ref;return{$$typeof:t,type:L,key:R,ref:U!==void 0?U:null,props:M}}function A(L,R){return N(L.type,R,L.props)}function P(L){return typeof L=="object"&&L!==null&&L.$$typeof===t}function F(L){var R={"=":"=0",":":"=2"};return"$"+L.replace(/[=:]/g,function(M){return R[M]})}var D=/\/+/g;function H(L,R){return typeof L=="object"&&L!==null&&L.key!=null?F(""+L.key):R.toString(36)}function q(L){switch(L.status){case"fulfilled":return L.value;case"rejected":throw L.reason;default:switch(typeof L.status=="string"?L.then(T,T):(L.status="pending",L.then(function(R){L.status==="pending"&&(L.status="fulfilled",L.value=R)},function(R){L.status==="pending"&&(L.status="rejected",L.reason=R)})),L.status){case"fulfilled":return L.value;case"rejected":throw L.reason}}throw L}function V(L,R,M,U,Q){var te=typeof L;(te==="undefined"||te==="boolean")&&(L=null);var K=!1;if(L===null)K=!0;else switch(te){case"bigint":case"string":case"number":K=!0;break;case"object":switch(L.$$typeof){case t:case n:K=!0;break;case f:return K=L._init,V(K(L._payload),R,M,U,Q)}}if(K)return Q=Q(L),K=U===""?"."+H(L,0):U,C(Q)?(M="",K!=null&&(M=K.replace(D,"$&/")+"/"),V(Q,R,M,"",function(le){return le})):Q!=null&&(P(Q)&&(Q=A(Q,M+(Q.key==null||L&&L.key===Q.key?"":(""+Q.key).replace(D,"$&/")+"/")+K)),R.push(Q)),1;K=0;var ee=U===""?".":U+":";if(C(L))for(var ne=0;ne<L.length;ne++)U=L[ne],te=ee+H(U,ne),K+=V(U,R,M,te,Q);else if(ne=m(L),typeof ne=="function")for(L=ne.call(L),ne=0;!(U=L.next()).done;)U=U.value,te=ee+H(U,ne++),K+=V(U,R,M,te,Q);else if(te==="object"){if(typeof L.then=="function")return V(q(L),R,M,U,Q);throw R=String(L),Error("Objects are not valid as a React child (found: "+(R==="[object Object]"?"object with keys {"+Object.keys(L).join(", ")+"}":R)+"). If you meant to render a collection of children, use an array instead.")}return K}function B(L,R,M){if(L==null)return L;var U=[],Q=0;return V(L,U,"","",function(te){return R.call(M,te,Q++)}),U}function Z(L){if(L._status===-1){var R=L._result;R=R(),R.then(function(M){(L._status===0||L._status===-1)&&(L._status=1,L._result=M)},function(M){(L._status===0||L._status===-1)&&(L._status=2,L._result=M)}),L._status===-1&&(L._status=0,L._result=R)}if(L._status===1)return L._result.default;throw L._result}var z=typeof reportError=="function"?reportError:function(L){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var R=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof L=="object"&&L!==null&&typeof L.message=="string"?String(L.message):String(L),error:L});if(!window.dispatchEvent(R))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",L);return}console.error(L)},Y={map:B,forEach:function(L,R,M){B(L,function(){R.apply(this,arguments)},M)},count:function(L){var R=0;return B(L,function(){R++}),R},toArray:function(L){return B(L,function(R){return R})||[]},only:function(L){if(!P(L))throw Error("React.Children.only expected to receive a single React element child.");return L}};return Qr.Activity=p,Qr.Children=Y,Qr.Component=x,Qr.Fragment=r,Qr.Profiler=o,Qr.PureComponent=k,Qr.StrictMode=s,Qr.Suspense=u,Qr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=E,Qr.__COMPILER_RUNTIME={__proto__:null,c:function(L){return E.H.useMemoCache(L)}},Qr.cache=function(L){return function(){return L.apply(null,arguments)}},Qr.cacheSignal=function(){return null},Qr.cloneElement=function(L,R,M){if(L==null)throw Error("The argument must be a React element, but you passed "+L+".");var U=v({},L.props),Q=L.key;if(R!=null)for(te in R.key!==void 0&&(Q=""+R.key),R)!I.call(R,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&R.ref===void 0||(U[te]=R[te]);var te=arguments.length-2;if(te===1)U.children=M;else if(1<te){for(var K=Array(te),ee=0;ee<te;ee++)K[ee]=arguments[ee+2];U.children=K}return N(L.type,Q,U)},Qr.createContext=function(L){return L={$$typeof:l,_currentValue:L,_currentValue2:L,_threadCount:0,Provider:null,Consumer:null},L.Provider=L,L.Consumer={$$typeof:i,_context:L},L},Qr.createElement=function(L,R,M){var U,Q={},te=null;if(R!=null)for(U in R.key!==void 0&&(te=""+R.key),R)I.call(R,U)&&U!=="key"&&U!=="__self"&&U!=="__source"&&(Q[U]=R[U]);var K=arguments.length-2;if(K===1)Q.children=M;else if(1<K){for(var ee=Array(K),ne=0;ne<K;ne++)ee[ne]=arguments[ne+2];Q.children=ee}if(L&&L.defaultProps)for(U in K=L.defaultProps,K)Q[U]===void 0&&(Q[U]=K[U]);return N(L,te,Q)},Qr.createRef=function(){return{current:null}},Qr.forwardRef=function(L){return{$$typeof:c,render:L}},Qr.isValidElement=P,Qr.lazy=function(L){return{$$typeof:f,_payload:{_status:-1,_result:L},_init:Z}},Qr.memo=function(L,R){return{$$typeof:d,type:L,compare:R===void 0?null:R}},Qr.startTransition=function(L){var R=E.T,M={};E.T=M;try{var U=L(),Q=E.S;Q!==null&&Q(M,U),typeof U=="object"&&U!==null&&typeof U.then=="function"&&U.then(T,z)}catch(te){z(te)}finally{R!==null&&M.types!==null&&(R.types=M.types),E.T=R}},Qr.unstable_useCacheRefresh=function(){return E.H.useCacheRefresh()},Qr.use=function(L){return E.H.use(L)},Qr.useActionState=function(L,R,M){return E.H.useActionState(L,R,M)},Qr.useCallback=function(L,R){return E.H.useCallback(L,R)},Qr.useContext=function(L){return E.H.useContext(L)},Qr.useDebugValue=function(){},Qr.useDeferredValue=function(L,R){return E.H.useDeferredValue(L,R)},Qr.useEffect=function(L,R){return E.H.useEffect(L,R)},Qr.useEffectEvent=function(L){return E.H.useEffectEvent(L)},Qr.useId=function(){return E.H.useId()},Qr.useImperativeHandle=function(L,R,M){return E.H.useImperativeHandle(L,R,M)},Qr.useInsertionEffect=function(L,R){return E.H.useInsertionEffect(L,R)},Qr.useLayoutEffect=function(L,R){return E.H.useLayoutEffect(L,R)},Qr.useMemo=function(L,R){return E.H.useMemo(L,R)},Qr.useOptimistic=function(L,R){return E.H.useOptimistic(L,R)},Qr.useReducer=function(L,R,M){return E.H.useReducer(L,R,M)},Qr.useRef=function(L){return E.H.useRef(L)},Qr.useState=function(L){return E.H.useState(L)},Qr.useSyncExternalStore=function(L,R,M){return E.H.useSyncExternalStore(L,R,M)},Qr.useTransition=function(){return E.H.useTransition()},Qr.version="19.2.7",Qr}var f3e;function uA(){return f3e||(f3e=1,hte.exports=Rrn()),hte.exports}var g=uA();const $e=Dm(g),dA=Nrn({__proto__:null,default:$e},[g]);var mte={exports:{}},$P={},gte={exports:{}},vte={};var p3e;function Prn(){return p3e||(p3e=1,(function(e){function t(q,V){var B=q.length;q.push(V);e:for(;0<B;){var Z=B-1>>>1,z=q[Z];if(0<s(z,V))q[Z]=V,q[B]=z,B=Z;else break e}}function n(q){return q.length===0?null:q[0]}function r(q){if(q.length===0)return null;var V=q[0],B=q.pop();if(B!==V){q[0]=B;e:for(var Z=0,z=q.length,Y=z>>>1;Z<Y;){var L=2*(Z+1)-1,R=q[L],M=L+1,U=q[M];if(0>s(R,B))M<z&&0>s(U,R)?(q[Z]=U,q[M]=B,Z=M):(q[Z]=R,q[L]=B,Z=L);else if(M<z&&0>s(U,B))q[Z]=U,q[M]=B,Z=M;else break e}}return V}function s(q,V){var B=q.sortIndex-V.sortIndex;return B!==0?B:q.id-V.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.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,y=!1,v=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;function k(q){for(var V=n(u);V!==null;){if(V.callback===null)r(u);else if(V.startTime<=q)r(u),V.sortIndex=V.expirationTime,t(c,V);else break;V=n(u)}}function _(q){if(y=!1,k(q),!m)if(n(c)!==null)m=!0,C||(C=!0,P());else{var V=n(u);V!==null&&H(_,V.startTime-q)}}var C=!1,T=-1,E=5,I=-1;function N(){return v?!0:!(e.unstable_now()-I<E)}function A(){if(v=!1,C){var q=e.unstable_now();I=q;var V=!0;try{e:{m=!1,y&&(y=!1,x(T),T=-1),h=!0;var B=p;try{t:{for(k(q),f=n(c);f!==null&&!(f.expirationTime>q&&N());){var Z=f.callback;if(typeof Z=="function"){f.callback=null,p=f.priorityLevel;var z=Z(f.expirationTime<=q);if(q=e.unstable_now(),typeof z=="function"){f.callback=z,k(q),V=!0;break t}f===n(c)&&r(c),k(q)}else r(c);f=n(c)}if(f!==null)V=!0;else{var Y=n(u);Y!==null&&H(_,Y.startTime-q),V=!1}}break e}finally{f=null,p=B,h=!1}V=void 0}}finally{V?P():C=!1}}}var P;if(typeof w=="function")P=function(){w(A)};else if(typeof MessageChannel<"u"){var F=new MessageChannel,D=F.port2;F.port1.onmessage=A,P=function(){D.postMessage(null)}}else P=function(){b(A,0)};function H(q,V){T=b(function(){q(e.unstable_now())},V)}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(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125<q?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<q?Math.floor(1e3/q):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(q){switch(p){case 1:case 2:case 3:var V=3;break;default:V=p}var B=p;p=V;try{return q()}finally{p=B}},e.unstable_requestPaint=function(){v=!0},e.unstable_runWithPriority=function(q,V){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var B=p;p=q;try{return V()}finally{p=B}},e.unstable_scheduleCallback=function(q,V,B){var Z=e.unstable_now();switch(typeof B=="object"&&B!==null?(B=B.delay,B=typeof B=="number"&&0<B?Z+B:Z):B=Z,q){case 1:var z=-1;break;case 2:z=250;break;case 5:z=1073741823;break;case 4:z=1e4;break;default:z=5e3}return z=B+z,q={id:d++,callback:V,priorityLevel:q,startTime:B,expirationTime:z,sortIndex:-1},B>Z?(q.sortIndex=B,t(u,q),n(c)===null&&q===n(u)&&(y?(x(T),T=-1):y=!0,H(_,B-Z))):(q.sortIndex=z,t(c,q),m||h||(m=!0,C||(C=!0,P()))),q},e.unstable_shouldYield=N,e.unstable_wrapCallback=function(q){var V=p;return function(){var B=p;p=V;try{return q.apply(this,arguments)}finally{p=B}}}})(vte)),vte}var h3e;function $rn(){return h3e||(h3e=1,gte.exports=Prn()),gte.exports}var yte={exports:{}},Pu={};var m3e;function Mrn(){if(m3e)return Pu;m3e=1;var e=uA();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 o(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 Pu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Pu.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 o(c,u,null,d)},Pu.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()}},Pu.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))},Pu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},Pu.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})}},Pu.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)},Pu.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})}},Pu.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)},Pu.requestFormReset=function(c){r.d.r(c)},Pu.unstable_batchedUpdates=function(c,u){return c(u)},Pu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},Pu.useFormStatus=function(){return i.H.useHostTransitionStatus()},Pu.version="19.2.7",Pu}var g3e;function eht(){if(g3e)return yte.exports;g3e=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(),yte.exports=Mrn(),yte.exports}var v3e;function Drn(){if(v3e)return $P;v3e=1;var e={env:{}};var t=$rn(),n=uA(),r=eht();function s(S){var O="https://react.dev/errors/"+S;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 #"+S+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(S){return!(!S||S.nodeType!==1&&S.nodeType!==9&&S.nodeType!==11)}function i(S){var O=S,j=S;if(S.alternate)for(;O.return;)O=O.return;else{S=O;do O=S,(O.flags&4098)!==0&&(j=O.return),S=O.return;while(S)}return O.tag===3?j:null}function l(S){if(S.tag===13){var O=S.memoizedState;if(O===null&&(S=S.alternate,S!==null&&(O=S.memoizedState)),O!==null)return O.dehydrated}return null}function c(S){if(S.tag===31){var O=S.memoizedState;if(O===null&&(S=S.alternate,S!==null&&(O=S.memoizedState)),O!==null)return O.dehydrated}return null}function u(S){if(i(S)!==S)throw Error(s(188))}function d(S){var O=S.alternate;if(!O){if(O=i(S),O===null)throw Error(s(188));return O!==S?null:S}for(var j=S,$=O;;){var G=j.return;if(G===null)break;var X=G.alternate;if(X===null){if($=G.return,$!==null){j=$;continue}break}if(G.child===X.child){for(X=G.child;X;){if(X===j)return u(G),S;if(X===$)return u(G),O;X=X.sibling}throw Error(s(188))}if(j.return!==$.return)j=G,$=X;else{for(var oe=!1,Se=G.child;Se;){if(Se===j){oe=!0,j=G,$=X;break}if(Se===$){oe=!0,$=G,j=X;break}Se=Se.sibling}if(!oe){for(Se=X.child;Se;){if(Se===j){oe=!0,j=X,$=G;break}if(Se===$){oe=!0,$=X,j=G;break}Se=Se.sibling}if(!oe)throw Error(s(189))}}if(j.alternate!==$)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?S:O}function f(S){var O=S.tag;if(O===5||O===26||O===27||O===6)return S;for(S=S.child;S!==null;){if(O=f(S),O!==null)return O;S=S.sibling}return null}var p=Object.assign,h=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),y=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),w=Symbol.for("react.consumer"),k=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),N=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),P=Symbol.iterator;function F(S){return S===null||typeof S!="object"?null:(S=P&&S[P]||S["@@iterator"],typeof S=="function"?S:null)}var D=Symbol.for("react.client.reference");function H(S){if(S==null)return null;if(typeof S=="function")return S.$$typeof===D?null:S.displayName||S.name||null;if(typeof S=="string")return S;switch(S){case v:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case C:return"Suspense";case T:return"SuspenseList";case N:return"Activity"}if(typeof S=="object")switch(S.$$typeof){case y:return"Portal";case k:return S.displayName||"Context";case w:return(S._context.displayName||"Context")+".Consumer";case _:var O=S.render;return S=S.displayName,S||(S=O.displayName||O.name||"",S=S!==""?"ForwardRef("+S+")":"ForwardRef"),S;case E:return O=S.displayName||null,O!==null?O:H(S.type)||"Memo";case I:O=S._payload,S=S._init;try{return H(S(O))}catch{}}return null}var q=Array.isArray,V=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Z={pending:!1,data:null,method:null,action:null},z=[],Y=-1;function L(S){return{current:S}}function R(S){0>Y||(S.current=z[Y],z[Y]=null,Y--)}function M(S,O){Y++,z[Y]=S.current,S.current=O}var U=L(null),Q=L(null),te=L(null),K=L(null);function ee(S,O){switch(M(te,O),M(Q,S),M(U,null),O.nodeType){case 9:case 11:S=(S=O.documentElement)&&(S=S.namespaceURI)?A4e(S):0;break;default:if(S=O.tagName,O=O.namespaceURI)O=A4e(O),S=R4e(O,S);else switch(S){case"svg":S=1;break;case"math":S=2;break;default:S=0}}R(U),M(U,S)}function ne(){R(U),R(Q),R(te)}function le(S){S.memoizedState!==null&&M(K,S);var O=U.current,j=R4e(O,S.type);O!==j&&(M(Q,S),M(U,j))}function J(S){Q.current===S&&(R(U),R(Q)),K.current===S&&(R(K),NP._currentValue=Z)}var re,se;function ie(S){if(re===void 0)try{throw Error()}catch(j){var O=j.stack.trim().match(/\n( *(at )?)/);re=O&&O[1]||"",se=-1<j.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+re+S+se}var fe=!1;function he(S,O){if(!S||fe)return"";fe=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var $={DetermineComponentFrameRoot:function(){try{if(O){var Dt=function(){throw Error()};if(Object.defineProperty(Dt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Dt,[])}catch(yt){var ut=yt}Reflect.construct(S,[],Dt)}else{try{Dt.call()}catch(yt){ut=yt}S.call(Dt.prototype)}}else{try{throw Error()}catch(yt){ut=yt}(Dt=S())&&typeof Dt.catch=="function"&&Dt.catch(function(){})}}catch(yt){if(yt&&ut&&typeof yt.stack=="string")return[yt.stack,ut.stack]}return[null,null]}};$.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var G=Object.getOwnPropertyDescriptor($.DetermineComponentFrameRoot,"name");G&&G.configurable&&Object.defineProperty($.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var X=$.DetermineComponentFrameRoot(),oe=X[0],Se=X[1];if(oe&&Se){var We=oe.split(`
@@ -246,7 +246,7 @@ attempted value: ${i}
246
246
  \${}
247
247
  }
248
248
  }`,{label:"class",detail:"definition",type:"keyword"}),gf('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),gf('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],ujt=QEe.concat([gf("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),gf("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),gf("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),tqe=new pCt,djt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function a$(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const Qnr=["FunctionDeclaration"],Ynr={FunctionDeclaration:a$("function"),ClassDeclaration:a$("class"),ClassExpression:()=>!0,EnumDeclaration:a$("constant"),TypeAliasDeclaration:a$("type"),NamespaceDeclaration:a$("namespace"),VariableDefinition(e,t){e.matchContext(Qnr)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function fjt(e,t){let n=tqe.get(t);if(n)return n;let r=[],s=!0;function o(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(Uo.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=Ynr[i.name];if(l&&l(i,o)||djt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of fjt(e,i.node))r.push(l);return!1}}),tqe.set(t,r),r}const mq=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,YEe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function pjt(e){let t=gi(e.state).resolveInner(e.pos,-1);if(YEe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&mq.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)djt.has(s.name)&&(r=r.concat(fjt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:mq}}function dse(e,t,n){var r;let s=[];for(;;){let o=t.firstChild,i;if(o?.name=="VariableName")return s.push(e(o)),{path:s.reverse(),name:n};if(o?.name=="MemberExpression"&&((r=i=o.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(i)),t=o;else return null}}function hjt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=gi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?dse(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?dse(t,n.parent,""):YEe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&mq.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?dse(t,n,""):e.explicit?{path:[],name:""}:null}function Knr(e,t){let n=e,r=[],s=new Set;for(let o=0;;o++){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:-o})}let i=Object.getPrototypeOf(e);if(!i)return r;e=i}}function Xnr(e){let t=new Map;return n=>{let r=hjt(n);if(!r)return null;let s=e;for(let i of r.path)if(s=s[i],!s)return null;let o=t.get(s);return o||t.set(s,o=Knr(s,!r.path.length)),{from:n.pos-r.name.length,options:o,validFor:mq}}}const hm=Y_.define({name:"javascript",parser:Gnr.configure({props:[aE.add({IfStatement:iN({except:/^\s*({|else\b)/}),TryStatement:iN({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:WXn,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:HXn({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":iN({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}}),lE.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":TEe,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:"$"}}),mjt={test:e=>/^JSX/.test(e.name),facet:eQ({commentTokens:{block:{open:"{/*",close:"*/}"}}})},KEe=hm.configure({dialect:"ts"},"typescript"),XEe=hm.configure({dialect:"jsx",props:[_Ee.add(e=>e.isTop?[mjt]:void 0)]}),JEe=hm.configure({dialect:"jsx ts",props:[_Ee.add(e=>e.isTop?[mjt]:void 0)]},"typescript");let gjt=e=>({label:e,type:"keyword"});const vjt="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(gjt),Jnr=vjt.concat(["declare","implements","private","protected","public"].map(gjt));function gq(e={}){let t=e.jsx?e.typescript?JEe:XEe:e.typescript?KEe:hm,n=e.typescript?ujt.concat(Jnr):QEe.concat(vjt);return new X_(t,[hm.data.of({autocomplete:IJn(YEe,mTt(n))}),hm.data.of({autocomplete:pjt}),e.jsx?yjt:[]])}function err(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 nqe(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 trr=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),yjt=Bt.inputHandler.of((e,t,n,r,s)=>{if((trr?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!hm.isActiveAt(e.state,t,-1))return!1;let o=s(),{state:i}=o,l=i.changeByRange(c=>{var u;let{head:d}=c,f=gi(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=nqe(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let y=`${p}>`;return{range:St.cursor(d+y.length,-1),changes:{from:d,insert:y}}}}else if(r==">"){let h=err(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=nqe(i.doc,h,d)))return{range:c,changes:{from:d,insert:`</${p}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([o,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function nrr(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:o,to:i}of hm.findRegions(r)){let l=r.doc.lineAt(o),c={line:l.number-1,col:o-l.from,pos:o};for(let u of e.verify(r.sliceDoc(o,i),t))s.push(rrr(u,r.doc,c))}return s}}function rqe(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function rrr(e,t,n){let r=rqe(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?rqe(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:o,text:i}=e.fix,l=o[0]+n.pos-r,c=o[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 w9=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:yjt,completionPath:hjt,esLint:nrr,javascript:gq,javascriptLanguage:hm,jsxLanguage:XEe,localCompletionSource:pjt,scopeCompletionSource:Xnr,snippets:QEe,tsxLanguage:JEe,typescriptLanguage:KEe,typescriptSnippets:ujt},Symbol.toStringTag,{value:"Module"})),l$=["_blank","_self","_top","_parent"],fse=["ascii","utf-8","utf-16","latin1","latin1"],pse=["get","post","put","delete"],hse=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],fp=["true","false"],ar={},srr={a:{attrs:{href:null,ping:null,type:null,media:null,target:l$,hreflang:null}},abbr:ar,address:ar,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:ar,aside:ar,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:ar,base:{attrs:{href:null,target:l$}},bdi:ar,bdo:ar,blockquote:{attrs:{cite:null}},body:ar,br:ar,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:hse,formmethod:pse,formnovalidate:["novalidate"],formtarget:l$,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:ar,center:ar,cite:ar,code:ar,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:ar,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:ar,div:ar,dl:ar,dt:ar,em:ar,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:ar,figure:ar,footer:ar,form:{attrs:{action:null,name:null,"accept-charset":fse,autocomplete:["on","off"],enctype:hse,method:pse,novalidate:["novalidate"],target:l$}},h1:ar,h2:ar,h3:ar,h4:ar,h5:ar,h6:ar,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:ar,hgroup:ar,hr:ar,html:{attrs:{manifest:null}},i:ar,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:hse,formmethod:pse,formnovalidate:["novalidate"],formtarget:l$,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:ar,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:ar,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:ar,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:fse,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:ar,noscript:ar,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:ar,param:{attrs:{name:null,value:null}},pre:ar,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:ar,rt:ar,ruby:ar,samp:ar,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:fse}},section:ar,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:ar,source:{attrs:{src:null,type:null,media:null}},span:ar,strong:ar,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:ar,summary:ar,sup:ar,table:ar,tbody:ar,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:ar,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:ar,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:ar,time:{attrs:{datetime:null}},title:ar,tr:ar,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:ar,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:ar},bjt={accesskey:null,class:null,contenteditable:fp,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:fp,autocorrect:fp,autocapitalize:fp,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":fp,"aria-autocomplete":["inline","list","both","none"],"aria-busy":fp,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":fp,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":fp,"aria-hidden":fp,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":fp,"aria-multiselectable":fp,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":fp,"aria-relevant":null,"aria-required":fp,"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},xjt="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 xjt)bjt[e]=null;let jL=class{constructor(t,n){this.tags={...srr,...t},this.globalAttrs={...bjt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}};jL.default=new jL;function fI(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 pI(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function wjt(e,t,n){let r=n.tags[fI(e,pI(t))];return r?.children||n.allTags}function eTe(e,t){let n=[];for(let r=pI(t);r&&!r.type.isTop;r=pI(r.parent)){let s=fI(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 Sjt=/^[:\-\.\w\u00b7-\uffff]*$/;function sqe(e,t,n,r,s){let o=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=pI(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:wjt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(eTe(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+o,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function oqe(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:eTe(e.doc,t).map((o,i)=>({label:o,apply:o+s,type:"type",boost:99-i})),validFor:Sjt}}function orr(e,t,n,r){let s=[],o=0;for(let i of wjt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of eTe(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-o++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function irr(e,t,n,r,s){let o=pI(n),i=o?t.tags[fI(e.doc,o)]: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:Sjt}}function arr(e,t,n,r,s){var o;let i=(o=n.parent)===null||o===void 0?void 0:o.getChild("AttributeName"),l=[],c;if(i){let u=e.sliceDoc(i.from,i.to),d=t.globalAttrs[u];if(!d){let f=pI(n),p=f?t.tags[fI(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 kjt(e,t){let{state:n,pos:r}=t,s=gi(n).resolveInner(r,-1),o=s.resolve(r);for(let i=r,l;o==s&&(l=s.childBefore(i));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;o=s=l,i=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?oqe(n,s,s.from,r):sqe(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?sqe(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?oqe(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?irr(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?arr(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(o.name=="Element"||o.name=="Text"||o.name=="Document")?orr(n,e,s,r):null}function lrr(e){return kjt(jL.default,e)}function crr(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new jL(t,n):jL.default;return s=>kjt(r,s)}const urr=hm.parser.configure({top:"SingleExpression"}),Ojt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:KEe.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:XEe.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:JEe.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:urr},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:hm.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:hq.parser}],_jt=[{name:"style",parser:hq.parser.configure({top:"Styles"})}].concat(xjt.map(e=>({name:e,parser:hm.parser}))),Cjt=Y_.define({name:"html",parser:$tr.configure({props:[aE.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}}),lE.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}}}),lTt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),s7=Cjt.configure({wrap:rjt(Ojt,_jt)});function drr(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=rjt((e.nestedLanguages||[]).concat(Ojt),(e.nestedAttributes||[]).concat(_jt)));let r=n?Cjt.configure({wrap:n,dialect:t}):t?s7.configure({dialect:t}):s7;return new X_(r,[s7.data.of({autocomplete:crr(e)}),e.autoCloseTags!==!1?frr:[],gq().support,vnr().support])}const iqe=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),frr=Bt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!s7.isActiveAt(e.state,t,-1))return!1;let o=s(),{state:i}=o,l=i.changeByRange(c=>{var u,d,f;let p=i.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,m=gi(i).resolveInner(h,-1),y;if(p&&r==">"&&m.name=="EndTag"){let v=m.parent;if(((d=(u=v.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(y=fI(i.doc,v.parent,h))&&!iqe.has(y)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`</${y}>`;return{range:c,changes:{from:h,to:b,insert:x}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let v=m.parent;if(m.from==h-2&&((f=v.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(y=fI(i.doc,v,h))&&!iqe.has(y)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`${y}>`;return{range:St.cursor(h+x.length,-1),changes:{from:h,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([o,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),Ejt=eQ({commentTokens:{block:{open:"<!--",close:"-->"}}}),Tjt=new $r,jjt=Der.configure({props:[lE.add(e=>!e.is("Block")||e.is("Document")||zbe(e)!=null||prr(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),Tjt.add(zbe),aE.add({Document:()=>null}),fS.add({Document:Ejt})]});function zbe(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function prr(e){return e.name=="OrderedList"||e.name=="BulletList"}function hrr(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=zbe(r.type))!=null&&s<=t)break;n=r}return n.to}const mrr=YEt.of((e,t,n)=>{for(let r=gi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(Tjt);if(s==null)continue;let o=hrr(r,s);if(o>n)return{from:n,to:o}}return null});function tTe(e){return new $p(Ejt,e,[],"markdown")}const Njt=tTe(jjt),grr=jjt.configure([Ger,Yer,Qer,Ker,{props:[lE.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),hI=tTe(grr);function vrr(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:K_.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class mse{constructor(t,n,r,s,o,i,l){this.node=t,this.from=n,this.to=r,this.spaceBefore=s,this.spaceAfter=o,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(+Ajt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function Ijt(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 o=n[s],i,l=t.lineAt(o.from),c=o.from-l.from;if(o.name=="Blockquote"&&(i=/^ *>( ?)/.exec(l.text.slice(c))))r.push(new mse(o,c,c+i[0].length,"",i[1],">",null));else if(o.name=="ListItem"&&o.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 mse(o.parent,c,c+d,i[1],u,i[2],o))}else if(o.name=="ListItem"&&o.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 mse(o.parent,c,c+d,i[1],u,f,o))}}return r}function Ajt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function gse(e,t,n,r=0){for(let s=-1,o=e;;){if(o.name=="ListItem"){let l=Ajt(o,t),c=+l[2];if(s>=0){if(c!=s+1)return;n.push({from:o.from+l[1].length,to:o.from+l[0].length,insert:String(s+2+r)})}s=c}let i=o.nextSibling;if(!i)break;o=i}}function nTe(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(WA)!=" ")return e;let r=ov(e,4,n),s="";for(let o=r;o>0;)o>=4?(s+=" ",o-=4):(s+=" ",o--);return s+e.slice(n)}const Rjt=(e={})=>({state:t,dispatch:n})=>{let r=gi(t),{doc:s}=t,o=null,i=t.changeByRange(l=>{if(!l.empty||!hI.isActiveAt(t,l.from,-1)&&!hI.isActiveAt(t,l.from,1))return o={range:l};let c=l.from,u=s.lineAt(c),d=Ijt(r.resolveInner(c,-1),s);for(;d.length&&d[d.length-1].from>c-u.from;)d.pop();if(!d.length)return o={range:l};let f=d[d.length-1];if(f.to-f.spaceAfter.length>c-u.from)return o={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 w=d.length>1?d[d.length-2]:null,k,_="";w&&w.item?(k=u.from+w.from,_=w.marker(s,1)):k=u.from+(w?w.to:0);let C=[{from:k,to:c,insert:_}];return f.node.name=="OrderedList"&&gse(f.item,s,C,-2),w&&w.node.name=="OrderedList"&&gse(w.item,s,C),{range:St.cursor(k+_.length),changes:C}}else{let w=lqe(d,t,u);return{range:St.cursor(c+w.length+1),changes:{from:u.from,insert:w+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 w=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(w),changes:w}}}let h=[];f.node.name=="OrderedList"&&gse(f.item,s,h);let m=f.item&&f.item.from<u.from,y="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)y+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?ov(u.text,4,d[b+1].from)-y.length:null);let v=c;for(;v>u.from&&/\s/.test(u.text.charAt(v-u.from-1));)v--;return y=nTe(y,t),yrr(f.node,t.doc)&&(y=lqe(d,t,u)+t.lineBreak+y),h.push({from:v,to:c,insert:t.lineBreak+y}),{range:St.cursor(v+y.length+1),changes:h}});return o?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},Pjt=Rjt();function aqe(e){return e.name=="QuoteMark"||e.name=="ListMark"}function yrr(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),o=t.lineAt(r.from),i=/^[\s>]*$/.test(s.text);return s.number+(i?0:1)<o.number}function lqe(e,t,n){let r="";for(let s=0,o=e.length-2;s<=o;s++)r+=e[s].blank(s<o?ov(n.text,4,e[s+1].from)-r.length:null,s<o);return nTe(r,t)}function brr(e,t){let n=e.resolveInner(t,-1),r=t;aqe(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(aqe(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const $jt=({state:e,dispatch:t})=>{let n=gi(e),r=null,s=e.changeByRange(o=>{let i=o.from,{doc:l}=e;if(o.empty&&hI.isActiveAt(e,o.from)){let c=l.lineAt(i),u=Ijt(brr(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:St.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(ov(c.text,4,d.to)-ov(c.text,4,d.from));return p==c.from&&(h=nTe(h,e)),{range:St.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:St.cursor(p),changes:{from:p,to:i}}}}}return r={range:o}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},Mjt=[{key:"Enter",run:Pjt},{key:"Backspace",run:$jt}],Djt=drr({matchClosingTags:!1});function Ljt(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=Njt,completeHTMLTags:o=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=Djt}=e;if(!(s instanceof sQ))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,mrr],d;i&&u.push(Fjt),n instanceof X_?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?vrr(t,d):void 0;c.push(Fer({codeParser:f,htmlParser:l.language.parser})),r&&u.push(dh.high(HA.of(Mjt)));let p=tTe(s.configure(c));return o&&u.push(p.data.of({autocomplete:xrr})),new X_(p,u)}function xrr(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=gi(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:wrr(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let vse=null;function wrr(){if(vse)return vse;let e=lrr(new REe(vs.create({extensions:Djt}),0,!0));return vse=e?e.options:[]}const Srr=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,Fjt=Bt.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),!hI.isActiveAt(t.state,r.from,1)))return!1;let o=gi(t.state),i=!1;return o.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||Srr.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)}}),krr=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:Njt,deleteMarkupBackward:$jt,insertNewlineContinueMarkup:Pjt,insertNewlineContinueMarkupCommand:Rjt,markdown:Ljt,markdownKeymap:Mjt,markdownLanguage:hI,pasteURLAsLink:Fjt},Symbol.toStringTag,{value:"Module"}));function tC(){return tC=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},tC.apply(null,arguments)}var Orr=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,o=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=Bt.theme(i,{dark:t==="dark"}),d=$0.define(o),f=[u,ZA(d)];return f},_rr={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)"},Crr=[{tag:pe.comment,color:"#6272a4"},{tag:pe.string,color:"#f1fa8c"},{tag:pe.atom,color:"#bd93f9"},{tag:pe.meta,color:"#f8f8f2"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"#ff79c6"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"#66d9ef"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"#50fa7b"},{tag:pe.atom,color:"#bd93f9"}],oQ=e=>{var t=e||{},n=t.theme,r=n===void 0?"dark":n,s=t.settings,o=s===void 0?{}:s,i=t.styles,l=i===void 0?[]:i;return Orr({theme:r,settings:tC({},_rr,o),styles:[...Crr,...l]})};oQ();function zjt(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 Err=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=sTe(e.state,n.from);return r.line?Trr(e):r.block?Nrr(e):!1};function rTe(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 Trr=rTe(Rrr,0),jrr=rTe(Bjt,0),Nrr=rTe((e,t)=>Bjt(e,t,Arr(t)),0);function sTe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const c$=50;function Irr(e,{open:t,close:n},r,s){let o=e.sliceDoc(r-c$,r),i=e.sliceDoc(s,s+c$),l=/\s*$/.exec(o)[0].length,c=/^\s*/.exec(i)[0].length,u=o.length-l;if(o.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*c$?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+c$),f=e.sliceDoc(s-c$,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 Arr(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 o=t.length-1;o>=0&&t[o].to>r.from?t[o].to=s.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return t}function Bjt(e,t,n=t.selection.ranges){let r=n.map(o=>sTe(t,o.from).block);if(!r.every(o=>o))return null;let s=n.map((o,i)=>Irr(t,r[i],o.from,o.to));if(e!=2&&!s.every(o=>o))return{changes:t.changes(n.map((o,i)=>s[i]?[]:[{from:o.from,insert:r[i].open+" "},{from:o.to,insert:" "+r[i].close}]))};if(e!=1&&s.some(o=>o)){let o=[];for(let i=0,l;i<s.length;i++)if(l=s[i]){let c=r[i],{open:u,close:d}=l;o.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:o}}return null}function Rrr(e,t,n=t.selection.ranges){let r=[],s=-1;e:for(let{from:o,to:i}of n){let l=r.length,c=1e9,u;for(let d=o;d<=i;){let f=t.doc.lineAt(d);if(u==null&&(u=sTe(t,f.from).line,!u))continue e;if(f.from>s&&(o==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(o=>o.comment<0&&(!o.empty||o.single))){let o=[];for(let{line:l,token:c,indent:u,empty:d,single:f}of r)(f||!d)&&o.push({from:l.from+u,insert:c+" "});let i=t.changes(o);return{changes:i,selection:t.selection.map(i,1)}}else if(e!=1&&r.some(o=>o.comment>=0)){let o=[];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++,o.push({from:u,to:d})}return{changes:o}}return null}const Bbe=gb.define(),Prr=gb.define(),$rr=En.define(),Ujt=En.define({combine(e){return vb(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)})}}),Vjt=Vl.define({create(){return Oy.empty},update(e,t){let n=t.state.facet(Ujt),r=t.annotation(Bbe);if(r){let c=Rf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=vq(d,d.length,n.minDepth,c):d=Wjt(d,t.startState.selection),new Oy(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(Prr);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Pl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let o=Rf.fromTransaction(t),i=t.annotation(Pl.time),l=t.annotation(Pl.userEvent);return o?e=e.addChanges(o,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 Oy(e.done.map(Rf.fromJSON),e.undone.map(Rf.fromJSON))}});function Mrr(e={}){return[Vjt,Ujt.of(e),Bt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?qjt:t.inputType=="historyRedo"?Ube:null;return r?(t.preventDefault(),r(n)):!1}})]}function iQ(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(Vjt,!1);if(!s)return!1;let o=s.pop(e,n,t);return o?(r(o),!0):!1}}const qjt=iQ(0,!1),Ube=iQ(1,!1),Drr=iQ(0,!0),Lrr=iQ(1,!0);class Rf{constructor(t,n,r,s,o){this.changes=t,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=o}setSelAfter(t){return new Rf(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 Rf(t.changes&&Al.fromJSON(t.changes),[],t.mapped&&Py.fromJSON(t.mapped),t.startSelection&&St.fromJSON(t.startSelection),t.selectionsAfter.map(St.fromJSON))}static fromTransaction(t,n){let r=tm;for(let s of t.startState.facet($rr)){let o=s(t);o.length&&(r=r.concat(o))}return!r.length&&t.changes.empty?null:new Rf(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,tm)}static selection(t){return new Rf(void 0,tm,void 0,void 0,t)}}function vq(e,t,n,r){let s=t+1>n+20?t-n-1:0,o=e.slice(s,t);return o.push(r),o}function Frr(e,t){let n=[],r=!1;return e.iterChangedRanges((s,o)=>n.push(s,o)),t.iterChangedRanges((s,o,i,l)=>{for(let c=0;c<n.length;){let u=n[c++],d=n[c++];l>=u&&i<=d&&(r=!0)}}),r}function zrr(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function Hjt(e,t){return e.length?t.length?e.concat(t):e:t}const tm=[],Brr=200;function Wjt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-Brr));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),vq(e,e.length-1,1e9,n.setSelAfter(r)))}else return[Rf.selection([t])]}function Urr(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 yse(e,t){if(!e.length)return e;let n=e.length,r=tm;for(;n;){let s=Vrr(e[n-1],t,r);if(s.changes&&!s.changes.empty||s.effects.length){let o=e.slice(0,n);return o[n-1]=s,o}else t=s.mapped,n--,r=s.selectionsAfter}return r.length?[Rf.selection(r)]:tm}function Vrr(e,t,n){let r=Hjt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):tm,n);if(!e.changes)return Rf.selection(r);let s=e.changes.map(t),o=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(o):o;return new Rf(s,Sr.mapEffects(e.effects,t),i,e.startSelection.map(o),r)}const qrr=/^(input\.type|delete)($|\.)/;class Oy{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 Oy(this.done,this.undone):this}addChanges(t,n,r,s,o){let i=this.done,l=i[i.length-1];return l&&l.changes&&!l.changes.empty&&t.changes&&(!r||qrr.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(o,Frr(l.changes,t.changes))||r=="input.type.compose")?i=vq(i,i.length-1,s.minDepth,new Rf(t.changes.compose(l.changes),Hjt(Sr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,tm)):i=vq(i,i.length,s.minDepth,t),new Oy(i,tm,n,r)}addSelection(t,n,r,s){let o=this.done.length?this.done[this.done.length-1].selectionsAfter:tm;return o.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&zrr(o[o.length-1],t)?this:new Oy(Wjt(this.done,t),this.undone,n,r)}addMapping(t){return new Oy(yse(this.done,t),yse(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 o=s[s.length-1],i=o.selectionsAfter[0]||(o.startSelection?o.startSelection.map(o.changes.invertedDesc,1):n.selection);if(r&&o.selectionsAfter.length)return n.update({selection:o.selectionsAfter[o.selectionsAfter.length-1],annotations:Bbe.of({side:t,rest:Urr(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(o.changes){let l=s.length==1?tm:s.slice(0,s.length-1);return o.mapped&&(l=yse(l,o.mapped)),n.update({changes:o.changes,selection:o.startSelection,effects:o.effects,annotations:Bbe.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Oy.empty=new Oy(tm,tm);const Hrr=[{key:"Mod-z",run:qjt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Ube,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Ube,preventDefault:!0},{key:"Mod-u",run:Drr,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:Lrr,preventDefault:!0}];function QA(e,t){return St.create(e.ranges.map(t),e.mainIndex)}function yv(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function bv({state:e,dispatch:t},n){let r=QA(e.selection,n);return r.eq(e.selection,!0)?!1:(t(yv(e,r)),!0)}function aQ(e,t){return St.cursor(t?e.to:e.from)}function Zjt(e,t){return bv(e,n=>n.empty?e.moveByChar(n,t):aQ(n,t))}function sd(e){return e.textDirectionAt(e.state.selection.main.head)==Oi.LTR}const Gjt=e=>Zjt(e,!sd(e)),Qjt=e=>Zjt(e,sd(e));function Yjt(e,t){return bv(e,n=>n.empty?e.moveByGroup(n,t):aQ(n,t))}const Wrr=e=>Yjt(e,!sd(e)),Zrr=e=>Yjt(e,sd(e));function Grr(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 lQ(e,t,n){let r=gi(e).resolveInner(t.head),s=n?$r.closedBy:$r.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;Grr(e,u,s)?r=u:c=n?u.to:u.from}let o=r.type.prop(s),i,l;return o&&(i=n?ky(e,r.from,1):ky(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,St.cursor(l,n?-1:1)}const Qrr=e=>bv(e,t=>lQ(e.state,t,!sd(e))),Yrr=e=>bv(e,t=>lQ(e.state,t,sd(e)));function Kjt(e,t){return bv(e,n=>{if(!n.empty)return aQ(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const Xjt=e=>Kjt(e,!1),Jjt=e=>Kjt(e,!0);function eNt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let o of e.state.facet(Bt.scrollMargins)){let i=o(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 tNt(e,t){let n=eNt(e),{state:r}=e,s=QA(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):aQ(i,t));if(s.eq(r.selection))return!1;let o;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&&(o=Bt.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(yv(r,s),{effects:o}),!0}const cqe=e=>tNt(e,!1),Vbe=e=>tNt(e,!0);function Y1(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 o=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;o&&t.head!=r.from+o&&(s=St.cursor(r.from+o))}return s}const Krr=e=>bv(e,t=>Y1(e,t,!0)),Xrr=e=>bv(e,t=>Y1(e,t,!1)),Jrr=e=>bv(e,t=>Y1(e,t,!sd(e))),esr=e=>bv(e,t=>Y1(e,t,sd(e))),tsr=e=>bv(e,t=>St.cursor(e.lineBlockAt(t.head).from,1)),nsr=e=>bv(e,t=>St.cursor(e.lineBlockAt(t.head).to,-1));function rsr(e,t,n){let r=!1,s=QA(e.selection,o=>{let i=ky(e,o.head,-1)||ky(e,o.head,1)||o.head>0&&ky(e,o.head-1,1)||o.head<e.doc.length&&ky(e,o.head+1,-1);if(!i||!i.end)return o;r=!0;let l=i.start.from==o.head?i.end.to:i.end.from;return St.cursor(l)});return r?(t(yv(e,s)),!0):!1}const ssr=({state:e,dispatch:t})=>rsr(e,t);function Zm(e,t,n){let r=QA(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=St.range(s.head,s.anchor));let o=n(s);return St.range(s.anchor,o.head,o.goalColumn,o.bidiLevel||void 0,o.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(yv(e.state,r)),!0)}function nNt(e,t){return Zm(e,t,n=>e.moveByChar(n,t))}const rNt=e=>nNt(e,!sd(e)),sNt=e=>nNt(e,sd(e));function oNt(e,t){return Zm(e,t,n=>e.moveByGroup(n,t))}const osr=e=>oNt(e,!sd(e)),isr=e=>oNt(e,sd(e)),asr=e=>{let t=!sd(e);return Zm(e,t,n=>lQ(e.state,n,t))},lsr=e=>{let t=sd(e);return Zm(e,t,n=>lQ(e.state,n,t))};function iNt(e,t){return Zm(e,t,n=>e.moveVertically(n,t))}const aNt=e=>iNt(e,!1),lNt=e=>iNt(e,!0);function cNt(e,t){return Zm(e,t,n=>e.moveVertically(n,t,eNt(e).height))}const uqe=e=>cNt(e,!1),dqe=e=>cNt(e,!0),csr=e=>Zm(e,!0,t=>Y1(e,t,!0)),usr=e=>Zm(e,!1,t=>Y1(e,t,!1)),dsr=e=>{let t=!sd(e);return Zm(e,t,n=>Y1(e,n,t))},fsr=e=>{let t=sd(e);return Zm(e,t,n=>Y1(e,n,t))},psr=e=>Zm(e,!1,t=>St.cursor(e.lineBlockAt(t.head).from)),hsr=e=>Zm(e,!0,t=>St.cursor(e.lineBlockAt(t.head).to)),fqe=({state:e,dispatch:t})=>(t(yv(e,{anchor:0})),!0),pqe=({state:e,dispatch:t})=>(t(yv(e,{anchor:e.doc.length})),!0),hqe=({state:e,dispatch:t})=>(t(yv(e,{anchor:e.selection.main.anchor,head:0})),!0),mqe=({state:e,dispatch:t})=>(t(yv(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),msr=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),gsr=({state:e,dispatch:t})=>{let n=cQ(e).map(({from:r,to:s})=>St.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:St.create(n),userEvent:"select"})),!0},vsr=({state:e,dispatch:t})=>{let n=QA(e.selection,r=>{let s=gi(e),o=s.resolveStack(r.from,1);if(r.empty){let i=s.resolveStack(r.from,-1);i.node.from>=o.node.from&&i.node.to<=o.node.to&&(o=i)}for(let i=o;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 St.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(yv(e,n)),!0)};function uNt(e,t){let{state:n}=e,r=n.selection,s=n.selection.ranges.slice();for(let o of n.selection.ranges){let i=n.doc.lineAt(o.head);if(t?i.to<e.state.doc.length:i.from>0)for(let l=o;;){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(yv(n,St.create(s,s.length-1))),!0)}const ysr=e=>uNt(e,!1),bsr=e=>uNt(e,!0),xsr=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=St.create([n.main]):n.main.empty||(r=St.create([St.cursor(n.main.head)])),r?(t(yv(e,r)),!0):!1};function e5(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(o=>{let{from:i,to:l}=o;if(i==l){let c=t(o);c<i?(n="delete.backward",c=S9(e,c,!1)):c>i&&(n="delete.forward",c=S9(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=S9(e,i,!1),l=S9(e,l,!0);return i==l?{range:o}:{changes:{from:i,to:l},range:St.cursor(i,i<o.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?Bt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function S9(e,t,n){if(e instanceof Bt)for(let r of e.state.facet(Bt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,o)=>{s<t&&o>t&&(t=n?o:s)});return t}const dNt=(e,t,n)=>e5(e,r=>{let s=r.from,{state:o}=e,i=o.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=ov(l,o.tabSize),d=u%J_(o)||J_(o);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Tc(i.text,s-i.from,t,t)+i.from,c==s&&i.number!=(t?o.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(i.text.slice(c-i.from,s-i.from))&&(c=Tc(i.text,c-i.from,!1,!1)+i.from);return c}),qbe=e=>dNt(e,!1,!0),fNt=e=>dNt(e,!0,!1),pNt=(e,t)=>e5(e,n=>{let r=n.head,{state:s}=e,o=s.doc.lineAt(r),i=s.charCategorizer(r);for(let l=null;;){if(r==(t?o.to:o.from)){r==n.head&&o.number!=(t?s.doc.lines:1)&&(r+=t?1:-1);break}let c=Tc(o.text,r-o.from,t)+o.from,u=o.text.slice(Math.min(r,c)-o.from,Math.max(r,c)-o.from),d=i(u);if(l!=null&&d!=l)break;(u!=" "||r!=n.head)&&(l=d),r=c}return r}),hNt=e=>pNt(e,!1),wsr=e=>pNt(e,!0),Ssr=e=>e5(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),ksr=e=>e5(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),Osr=e=>e5(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),_sr=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:eo.of(["",""])},range:St.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},Csr=({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,o=e.doc.lineAt(s),i=s==o.from?s-1:Tc(o.text,s-o.from,!1)+o.from,l=s==o.to?s+1:Tc(o.text,s-o.from,!0)+o.from;return{changes:{from:i,to:l,insert:e.doc.slice(s,l).append(e.doc.slice(i,s))},range:St.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function cQ(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),o=e.doc.lineAt(r.to);if(!r.empty&&r.to==o.from&&(o=e.doc.lineAt(r.to-1)),n>=s.number){let i=t[t.length-1];i.to=o.to,i.ranges.push(r)}else t.push({from:s.from,to:o.to,ranges:[r]});n=o.number+1}return t}function mNt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let o of cQ(e)){if(n?o.to==e.doc.length:o.from==0)continue;let i=e.doc.lineAt(n?o.to+1:o.from-1),l=i.length+1;if(n){r.push({from:o.to,to:i.to},{from:o.from,insert:i.text+e.lineBreak});for(let c of o.ranges)s.push(St.range(Math.min(e.doc.length,c.anchor+l),Math.min(e.doc.length,c.head+l)))}else{r.push({from:i.from,to:o.from},{from:o.to,insert:e.lineBreak+i.text});for(let c of o.ranges)s.push(St.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:St.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const Esr=({state:e,dispatch:t})=>mNt(e,t,!1),Tsr=({state:e,dispatch:t})=>mNt(e,t,!0);function gNt(e,t,n){if(e.readOnly)return!1;let r=[];for(let o of cQ(e))n?r.push({from:o.from,insert:e.doc.slice(o.from,o.to)+e.lineBreak}):r.push({from:o.to,insert:e.lineBreak+e.doc.slice(o.from,o.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 jsr=({state:e,dispatch:t})=>gNt(e,t,!1),Nsr=({state:e,dispatch:t})=>gNt(e,t,!0),Isr=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(cQ(t).map(({from:s,to:o})=>(s>0?s--:o<t.doc.length&&o++,{from:s,to:o}))),r=QA(t.selection,s=>{let o;if(e.lineWrapping){let i=e.lineBlockAt(s.head),l=e.coordsAtPos(s.head,s.assoc||1);l&&(o=i.bottom+e.documentTop-l.bottom+e.defaultLineHeight/2)}return e.moveVertically(s,!0,o)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function Asr(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=gi(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),o;return r&&s&&r.to<=t&&s.from>=t&&(o=r.type.prop($r.closedBy))&&o.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 gqe=vNt(!1),Rsr=vNt(!0);function vNt(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(s=>{let{from:o,to:i}=s,l=t.doc.lineAt(o),c=!e&&o==i&&Asr(t,o);e&&(o=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new tQ(t,{simulateBreak:o,simulateDoubleBreak:!!c}),d=CEe(u,o);for(d==null&&(d=ov(/^\s*/.exec(t.doc.lineAt(o).text)[0],t.tabSize));i<l.to&&/\s/.test(l.text[i-l.from]);)i++;c?{from:o,to:i}=c:o>l.from&&o<l.from+100&&!/\S/.test(l.text.slice(0,o))&&(o=l.from);let f=["",wL(t,d)];return c&&f.push(wL(t,u.lineIndent(l.from,-1))),{changes:{from:o,to:i,insert:eo.of(f)},range:St.cursor(o+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function oTe(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 o=e.changes(s);return{changes:s,range:St.range(o.mapPos(r.anchor,1),o.mapPos(r.head,1))}})}const Psr=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new tQ(e,{overrideIndentation:o=>{let i=n[o];return i??-1}}),s=oTe(e,(o,i,l)=>{let c=CEe(r,o.from);if(c==null)return;/\S/.test(o.text)||(c=0);let u=/^\s*/.exec(o.text)[0],d=wL(e,c);(u!=d||l.from<o.from+u.length)&&(n[o.from]=c,i.push({from:o.from,to:o.from+u.length,insert:d}))});return s.changes.empty||t(e.update(s,{userEvent:"indent"})),!0},yNt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(oTe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(WA)})}),{userEvent:"input.indent"})),!0),bNt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(oTe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let o=ov(s,e.tabSize),i=0,l=wL(e,Math.max(0,o-J_(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),$sr=e=>(e.setTabFocusMode(),!0),Msr=[{key:"Ctrl-b",run:Gjt,shift:rNt,preventDefault:!0},{key:"Ctrl-f",run:Qjt,shift:sNt},{key:"Ctrl-p",run:Xjt,shift:aNt},{key:"Ctrl-n",run:Jjt,shift:lNt},{key:"Ctrl-a",run:tsr,shift:psr},{key:"Ctrl-e",run:nsr,shift:hsr},{key:"Ctrl-d",run:fNt},{key:"Ctrl-h",run:qbe},{key:"Ctrl-k",run:Ssr},{key:"Ctrl-Alt-h",run:hNt},{key:"Ctrl-o",run:_sr},{key:"Ctrl-t",run:Csr},{key:"Ctrl-v",run:Vbe}],Dsr=[{key:"ArrowLeft",run:Gjt,shift:rNt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Wrr,shift:osr,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Jrr,shift:dsr,preventDefault:!0},{key:"ArrowRight",run:Qjt,shift:sNt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Zrr,shift:isr,preventDefault:!0},{mac:"Cmd-ArrowRight",run:esr,shift:fsr,preventDefault:!0},{key:"ArrowUp",run:Xjt,shift:aNt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:fqe,shift:hqe},{mac:"Ctrl-ArrowUp",run:cqe,shift:uqe},{key:"ArrowDown",run:Jjt,shift:lNt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:pqe,shift:mqe},{mac:"Ctrl-ArrowDown",run:Vbe,shift:dqe},{key:"PageUp",run:cqe,shift:uqe},{key:"PageDown",run:Vbe,shift:dqe},{key:"Home",run:Xrr,shift:usr,preventDefault:!0},{key:"Mod-Home",run:fqe,shift:hqe},{key:"End",run:Krr,shift:csr,preventDefault:!0},{key:"Mod-End",run:pqe,shift:mqe},{key:"Enter",run:gqe,shift:gqe},{key:"Mod-a",run:msr},{key:"Backspace",run:qbe,shift:qbe,preventDefault:!0},{key:"Delete",run:fNt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:hNt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:wsr,preventDefault:!0},{mac:"Mod-Backspace",run:ksr,preventDefault:!0},{mac:"Mod-Delete",run:Osr,preventDefault:!0}].concat(Msr.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),Lsr=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Qrr,shift:asr},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Yrr,shift:lsr},{key:"Alt-ArrowUp",run:Esr},{key:"Shift-Alt-ArrowUp",run:jsr},{key:"Alt-ArrowDown",run:Tsr},{key:"Shift-Alt-ArrowDown",run:Nsr},{key:"Mod-Alt-ArrowUp",run:ysr},{key:"Mod-Alt-ArrowDown",run:bsr},{key:"Escape",run:xsr},{key:"Mod-Enter",run:Rsr},{key:"Alt-l",mac:"Ctrl-l",run:gsr},{key:"Mod-i",run:vsr,preventDefault:!0},{key:"Mod-[",run:bNt},{key:"Mod-]",run:yNt},{key:"Mod-Alt-\\",run:Psr},{key:"Shift-Mod-k",run:Isr},{key:"Shift-Mod-\\",run:ssr},{key:"Mod-/",run:Err},{key:"Alt-A",run:jrr},{key:"Ctrl-m",mac:"Shift-Alt-m",run:$sr}].concat(Dsr),Fsr={key:"Tab",run:yNt,shift:bNt},vqe=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class mI{constructor(t,n,r=0,s=t.length,o,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=o?l=>o(vqe(l)):vqe,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 Of(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=aEe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=dy(t);let s=this.normalize(n);if(s.length)for(let o=0,i=r,l=!0;;o++){let c=s.charCodeAt(o),u=this.match(c,i,l,this.bufferPos+this.bufferStart,o==s.length-1);if(u)return this.value=u,this;if(o==s.length-1)break;l&&o<n.length&&n.charCodeAt(o)==c?i++:l=!1}}}match(t,n,r,s,o){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:o&&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&&o}: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"&&(mI.prototype[Symbol.iterator]=function(){return this});const xNt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},iTe="gm"+(/x/.unicode==null?"":"u");class wNt{constructor(t,n,r,s=0,o=t.length){if(this.text=t,this.to=o,this.curLine="",this.done=!1,this.value=xNt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new SNt(t,n,r,s,o);this.re=new RegExp(n,iTe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=yq(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=yq(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 bse=new WeakMap;class lN{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=bse.get(t);if(!s||s.from>=r||s.to<=n){let l=new lN(n,t.sliceString(n,r));return bse.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:o,from:i}=s;return i>n&&(o=t.sliceString(n,i)+o,i=n),s.to<r&&(o+=t.sliceString(s.to,r)),bse.set(t,new lN(i,o)),new lN(n,o.slice(n-i,r-i))}}class SNt{constructor(t,n,r,s,o){this.text=t,this.to=o,this.done=!1,this.value=xNt,this.matchPos=yq(t,s),this.re=new RegExp(n,iTe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=lN.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=yq(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=lN.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(wNt.prototype[Symbol.iterator]=SNt.prototype[Symbol.iterator]=function(){return this});function zsr(e){try{return new RegExp(e,iTe),!0}catch{return!1}}function yq(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 Bsr=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=kXn(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(o=>{let i=o&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(o.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 v=h/100;c&&(v=v*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*v)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),y=St.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,Bt.scrollIntoView(y.from,{y:"center"})],selection:y})}),!0},Usr={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Vsr=En.define({combine(e){return vb(e,Usr,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function qsr(e){return[Qsr,Gsr]}const Hsr=Ln.mark({class:"cm-selectionMatch"}),Wsr=Ln.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function yqe(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=ba.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=ba.Word)}function Zsr(e,t,n,r){return e(t.sliceDoc(n,n+1))==ba.Word&&e(t.sliceDoc(r-1,r))==ba.Word}const Gsr=ka.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(Vsr),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Ln.none;let s=r.main,o,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return Ln.none;let c=n.wordAt(s.head);if(!c)return Ln.none;i=n.charCategorizer(s.head),o=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return Ln.none;if(t.wholeWords){if(o=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(yqe(i,n,s.from,s.to)&&Zsr(i,n,s.from,s.to)))return Ln.none}else if(o=n.sliceDoc(s.from,s.to),!o)return Ln.none}let l=[];for(let c of e.visibleRanges){let u=new mI(n.doc,o,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||yqe(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(Wsr.range(d,f)):(d>=s.to||f<=s.from)&&l.push(Hsr.range(d,f)),l.length>t.maxMatches))return Ln.none}}return Ln.set(l)}},{decorations:e=>e.decorations}),Qsr=Bt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Ysr=({state:e,dispatch:t})=>{let{selection:n}=e,r=St.create(n.ranges.map(s=>e.wordAt(s.head)||St.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function Ksr(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),o=s&&s.from==n.from&&s.to==n.to;for(let i=!1,l=new mI(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new mI(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(o){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const Xsr=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(o=>o.from===o.to))return Ysr({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(o=>e.sliceDoc(o.from,o.to)!=r))return!1;let s=Ksr(e,r);return s?(t(e.update({selection:e.selection.addRange(St.range(s.from,s.to),!1),effects:Bt.scrollIntoView(s.to)})),!0):!1},YA=En.define({combine(e){return vb(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new por(t),scrollToMatch:t=>Bt.scrollIntoView(t)})}});class kNt{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||zsr(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"?`
249
- `: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 sor(this):new tor(this)}getCursor(t,n=0,r){let s=t.doc?t:vs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?aj(this,s,n,r):ij(this,s,n,r)}}class ONt{constructor(t){this.spec=t}}function Jsr(e,t,n){return(r,s,o,i)=>{if(n&&!n(r,s,o,i))return!1;let l=r>=i&&s<=i+o.length?o.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function ij(e,t,n,r){let s;return e.wholeWord&&(s=eor(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=Jsr(e.test,t,s)),new mI(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:o=>o.toLowerCase(),s)}function eor(e,t){return(n,r,s,o)=>((o>n||o+s.length<r)&&(o=Math.max(0,n-2),s=e.sliceString(o,Math.min(e.length,r+2))),(t(bq(s,n-o))!=ba.Word||t(xq(s,n-o))!=ba.Word)&&(t(xq(s,r-o))!=ba.Word||t(bq(s,r-o))!=ba.Word))}class tor extends ONt{constructor(t){super(t)}nextMatch(t,n,r){let s=ij(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let o=Math.min(t.doc.length,n+this.spec.unquoted.length);s=ij(this.spec,t,0,o).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let o=Math.max(n,s-1e4-this.spec.unquoted.length),i=ij(this.spec,t,o,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(o==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=ij(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 o=ij(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!o.next().done;)s(o.value.from,o.value.to)}}function nor(e,t,n){return(r,s,o)=>(!n||n(r,s,o))&&e(o[0],t,r,s)}function aj(e,t,n,r){let s;return e.wholeWord&&(s=ror(t.charCategorizer(t.selection.main.head))),e.test&&(s=nor(e.test,t,s)),new wNt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function bq(e,t){return e.slice(Tc(e,t,!1),t)}function xq(e,t){return e.slice(t,Tc(e,t))}function ror(e){return(t,n,r)=>!r[0].length||(e(bq(r.input,r.index))!=ba.Word||e(xq(r.input,r.index))!=ba.Word)&&(e(xq(r.input,r.index+r[0].length))!=ba.Word||e(bq(r.input,r.index+r[0].length))!=ba.Word)}class sor extends ONt{nextMatch(t,n,r){let s=aj(this.spec,t,r,t.doc.length).next();return s.done&&(s=aj(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let o=Math.max(n,r-s*1e4),i=aj(this.spec,t,o,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(o==n||l.from>o+10))return l;if(o==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 o=+r.slice(0,s);if(o>0&&o<t.match.length)return t.match[o]+r.slice(s)}return n})}matchAll(t,n){let r=aj(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 o=aj(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!o.next().done;)s(o.value.from,o.value.to)}}const NL=Sr.define(),aTe=Sr.define(),jS=Vl.define({create(e){return new xse(Hbe(e).create(),null)},update(e,t){for(let n of t.effects)n.is(NL)?e=new xse(n.value.create(),e.panel):n.is(aTe)&&(e=new xse(e.query,n.value?lTe:null));return e},provide:e=>xL.from(e,t=>t.panel)});class xse{constructor(t,n){this.query=t,this.panel=n}}const oor=Ln.mark({class:"cm-searchMatch"}),ior=Ln.mark({class:"cm-searchMatch cm-searchMatch-selected"}),aor=ka.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(jS))}update(e){let t=e.state.field(jS);(t!=e.startState.field(jS)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Ln.none;let{view:n}=this,r=new Wf;for(let s=0,o=n.visibleRanges,i=o.length;s<i;s++){let{from:l,to:c}=o[s];for(;s<i-1&&c>o[s+1].from-500;)c=o[++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?ior:oor)})}return r.finish()}},{decorations:e=>e.decorations});function t5(e){return t=>{let n=t.state.field(jS,!1);return n&&n.query.spec.valid?e(t,n):ENt(t)}}const wq=t5((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=St.single(r.from,r.to),o=e.state.facet(YA);return e.dispatch({selection:s,effects:[cTe(e,r),o.scrollToMatch(s.main,e)],userEvent:"select.search"}),CNt(e),!0}),Sq=t5((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let o=St.single(s.from,s.to),i=e.state.facet(YA);return e.dispatch({selection:o,effects:[cTe(e,s),i.scrollToMatch(o.main,e)],userEvent:"select.search"}),CNt(e),!0}),lor=t5((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:St.create(n.map(r=>St.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),cor=({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,o=[],i=0;for(let l=new mI(e.doc,e.sliceDoc(r,s));!l.next().done;){if(o.length>1e3)return!1;l.value.from==r&&(i=o.length),o.push(St.range(l.value.from,l.value.to))}return t(e.update({selection:St.create(o,i),userEvent:"select.search.matches"})),!0},bqe=t5((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let o=t.nextMatch(n,r,r);if(!o)return!1;let i=o,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(Bt.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=St.single(i.from,i.to).map(f),d.push(cTe(e,i)),d.push(n.facet(YA).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),uor=t5((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:o,to:i,precise:l}=s;l&&n.push({from:o,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:Bt.announce.of(r),userEvent:"input.replace.all"}),!0});function lTe(e){return e.state.facet(YA).createPanel(e)}function Hbe(e,t){var n,r,s,o,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(YA);return new kNt({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:(o=t?.regexp)!==null&&o!==void 0?o:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function _Nt(e){let t=OEe(e,lTe);return t&&t.dom.querySelector("[main-field]")}function CNt(e){let t=_Nt(e);t&&t==e.root.activeElement&&t.select()}const ENt=e=>{let t=e.state.field(jS,!1);if(t&&t.panel){let n=_Nt(e);if(n&&n!=e.root.activeElement){let r=Hbe(e.state,t.query.spec);r.valid&&e.dispatch({effects:NL.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[aTe.of(!0),t?NL.of(Hbe(e.state,t.query.spec)):Sr.appendConfig.of(mor)]});return!0},TNt=e=>{let t=e.state.field(jS,!1);if(!t||!t.panel)return!1;let n=OEe(e,lTe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:aTe.of(!1)}),!0},dor=[{key:"Mod-f",run:ENt,scope:"editor search-panel"},{key:"F3",run:wq,shift:Sq,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:wq,shift:Sq,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:TNt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:cor},{key:"Mod-Alt-g",run:Bsr},{key:"Mod-d",run:Xsr,preventDefault:!0}];class por{constructor(t){this.view=t;let n=this.query=t.state.field(jS).query.spec;this.commit=this.commit.bind(this),this.searchField=fi("input",{value:n.search,placeholder:pp(t,"Find"),"aria-label":pp(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=fi("input",{value:n.replace,placeholder:pp(t,"Replace"),"aria-label":pp(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=fi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=fi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=fi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,o,i){return fi("button",{class:"cm-button",name:s,onclick:o,type:"button"},i)}this.dom=fi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>wq(t),[pp(t,"next")]),r("prev",()=>Sq(t),[pp(t,"previous")]),r("select",()=>lor(t),[pp(t,"all")]),fi("label",null,[this.caseField,pp(t,"match case")]),fi("label",null,[this.reField,pp(t,"regexp")]),fi("label",null,[this.wordField,pp(t,"by word")]),...t.state.readOnly?[]:[fi("br"),this.replaceField,r("replace",()=>bqe(t),[pp(t,"replace")]),r("replaceAll",()=>uor(t),[pp(t,"replace all")])],fi("button",{name:"close",onclick:()=>TNt(t),"aria-label":pp(t,"close"),type:"button"},["×"])])}commit(){let t=new kNt({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:NL.of(t)}))}keydown(t){RKn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?Sq:wq)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),bqe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(NL)&&!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(YA).top}}function pp(e,t){return e.state.phrase(t)}const k9=30,O9=/[\s\.,:;?!]/;function cTe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,o=Math.max(r.from,t-k9),i=Math.min(s,n+k9),l=e.state.sliceDoc(o,i);if(o!=r.from){for(let c=0;c<k9;c++)if(!O9.test(l[c+1])&&O9.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-k9;c--)if(!O9.test(l[c-1])&&O9.test(l[c])){l=l.slice(0,c);break}}return Bt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const hor=Bt.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"}}),mor=[jS,dh.low(aor),hor];class xqe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class _O{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(IL).markerFilter;s&&(t=s(t,r));let o=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Wf,l=[],c=0;for(let d=0;;){let f=d==o.length?null:o[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((y,v)=>Math.min(y,v.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<o.length;){let y=o[d];if(y.from==p&&(y.to>y.from||y.to==p))l.push(y),d++,h=Math.min(y.to,h);else{h=Math.min(y.from,h);break}}let m=Tor(l);if(l.some(y=>y.from==y.to||y.from==y.to-1&&r.doc.lineAt(y.from).to==y.from))i.add(p,p,Ln.widget({widget:new Oor(m),diagnostics:l.slice()}));else{let y=l.reduce((v,b)=>b.markClass?v+" "+b.markClass:v,"");i.add(p,h,Ln.mark({class:"cm-lintRange cm-lintRange-"+m+y,diagnostics:l.slice(),inclusiveEnd:l.some(v=>v.to>h)}))}c=h;for(let y=0;y<l.length;y++)l[y].to<=c&&l.splice(y--,1)}let u=i.finish();return new _O(u,n,gI(u))}}function gI(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,o,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new xqe(s,o,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new xqe(r.from,o,r.diagnostic)}}),r}function gor(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(IL).hideOn(e,n,r);if(s!=null)return s;let o=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(jNt))||e.changes.touchesRange(o.from,Math.max(o.to,r)))}function vor(e,t){return e.field(Mp,!1)?t:t.concat(Sr.appendConfig.of(jor))}const jNt=Sr.define(),uTe=Sr.define(),NNt=Sr.define(),Mp=Vl.define({create(){return new _O(Ln.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 o=t.changes.mapPos(e.selected.from,1);r=gI(n,e.selected.diagnostic,o)||gI(n,null,o)}!n.size&&s&&t.state.facet(IL).autoPanel&&(s=null),e=new _O(n,s,r)}for(let n of t.effects)if(n.is(jNt)){let r=t.state.facet(IL).autoPanel?n.value.length?AL.open:null:e.panel;e=_O.init(n.value,r,t.state)}else n.is(uTe)?e=new _O(e.diagnostics,n.value?AL.open:null,e.selected):n.is(NNt)&&(e=new _O(e.diagnostics,e.panel,n.value));return e},provide:e=>[xL.from(e,t=>t.panel),Bt.decorations.from(e,t=>t.diagnostics)]}),yor=Ln.mark({class:"cm-lintRange cm-lintRange-active"});function bor(e,t,n){let{diagnostics:r}=e.state.field(Mp),s,o=-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,o=c,i=u,!1});let l=e.state.facet(IL).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:o,end:i,above:e.state.doc.lineAt(o).to<i,create(){return{dom:xor(e,s)}}}:null}function xor(e,t){return fi("ul",{class:"cm-tooltip-lint"},t.map(n=>ANt(e,n,!1)))}const wor=e=>{let t=e.state.field(Mp,!1);(!t||!t.panel)&&e.dispatch({effects:vor(e.state,[uTe.of(!0)])});let n=OEe(e,AL.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},wqe=e=>{let t=e.state.field(Mp,!1);return!t||!t.panel?!1:(e.dispatch({effects:uTe.of(!1)}),!0)},Sor=e=>{let t=e.state.field(Mp,!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)},kor=[{key:"Mod-Shift-m",run:wor,preventDefault:!0},{key:"F8",run:Sor}],IL=En.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...vb(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:Sqe,tooltipFilter:Sqe,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,o)=>t(r,s,o)||n(r,s,o):t:n,autoPanel:(t,n)=>t||n})}}});function Sqe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function INt(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(o=>o.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function ANt(e,t,n){var r;let s=n?INt(t.actions):[];return fi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},fi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((o,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=gI(e.state.field(Mp).diagnostics,t);m&&o.apply(e,m.from,m.to)},{name:u}=o,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),fi("u",u.slice(d,d+1)),u.slice(d+1)],p=o.markClass?" "+o.markClass:"";return fi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&fi("div",{class:"cm-diagnosticSource"},t.source))}class Oor extends fh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return fi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class kqe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=ANt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class AL{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)wqe(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:o}=this.items[this.selectedIndex],i=INt(o.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=gI(this.view.state.field(Mp).diagnostics,o);c&&o.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let o=0;o<this.items.length;o++)this.items[o].dom.contains(s.target)&&this.moveSelection(o)};this.list=fi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=fi("div",{class:"cm-panel-lint"},this.list,fi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>wqe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Mp).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(Mp),r=0,s=!1,o=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 kqe(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"),o=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 kqe(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),o?(this.list.setAttribute("aria-activedescendant",o.id),this.view.requestMeasure({key:this,read:()=>({sel:o.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(Mp),r=gI(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:NNt.of(r)})}static open(t){return new AL(t)}}function _or(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 _9(e){return _or(`<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 Cor=Bt.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:_9("#d11")},".cm-lintRange-warning":{backgroundImage:_9("orange")},".cm-lintRange-info":{backgroundImage:_9("#999")},".cm-lintRange-hint":{backgroundImage:_9("#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 Eor(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function Tor(e){let t="hint",n=1;for(let r of e){let s=Eor(r.severity);s>n&&(n=s,t=r.severity)}return t}const jor=[Mp,Bt.decorations.compute([Mp],e=>{let{selected:t,panel:n}=e.field(Mp);return!t||!n||t.from==t.to?Ln.none:Ln.set([yor.range(t.from,t.to)])}),wXn(bor,{hideOn:gor}),Cor];var Oqe=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,o=[];t.closeBracketsKeymap!==!1&&(o=o.concat(ver)),t.defaultKeymap!==!1&&(o=o.concat(Lsr)),t.searchKeymap!==!1&&(o=o.concat(dor)),t.historyKeymap!==!1&&(o=o.concat(Hrr)),t.foldKeymap!==!1&&(o=o.concat(nJn)),t.completionKeymap!==!1&&(o=o.concat(_Tt)),t.lintKeymap!==!1&&(o=o.concat(kor));var i=[];return t.lineNumbers!==!1&&i.push(WEt()),t.highlightActiveLineGutter!==!1&&i.push($Xn()),t.highlightSpecialChars!==!1&&i.push(QKn()),t.history!==!1&&i.push(Mrr()),t.foldGutter!==!1&&i.push(iJn()),t.drawSelection!==!1&&i.push(FKn()),t.dropCursor!==!1&&i.push(qKn()),t.allowMultipleSelections!==!1&&i.push(vs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(GXn()),t.syntaxHighlighting!==!1&&i.push(ZA(uJn,{fallback:!0})),t.bracketMatching!==!1&&i.push(vJn()),t.closeBrackets!==!1&&i.push(per()),t.autocompletion!==!1&&i.push(OTt()),t.rectangularSelection!==!1&&i.push(cXn()),s!==!1&&i.push(fXn()),t.highlightActiveLine!==!1&&i.push(tXn()),t.highlightSelectionMatches!==!1&&i.push(qsr()),t.tabSize&&typeof t.tabSize=="number"&&i.push(WA.of(" ".repeat(t.tabSize))),i.concat([HA.of(o.flat())]).filter(Boolean)};const Nor="#e5c07b",_qe="#e06c75",Ior="#56b6c2",Aor="#ffffff",o7="#abb2bf",Wbe="#7d8799",Ror="#61afef",Por="#98c379",Cqe="#d19a66",$or="#c678dd",Mor="#21252b",Eqe="#2c313a",Tqe="#282c34",wse="#353a42",Dor="#3E4451",jqe="#528bff",Lor=Bt.theme({"&":{color:o7,backgroundColor:Tqe},".cm-content":{caretColor:jqe},".cm-cursor, .cm-dropCursor":{borderLeftColor:jqe},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:Dor},".cm-panels":{backgroundColor:Mor,color:o7},".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:Tqe,color:Wbe,border:"none"},".cm-activeLineGutter":{backgroundColor:Eqe},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:wse},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:wse,borderBottomColor:wse},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Eqe,color:o7}}},{dark:!0}),For=$0.define([{tag:pe.keyword,color:$or},{tag:[pe.name,pe.deleted,pe.character,pe.propertyName,pe.macroName],color:_qe},{tag:[pe.function(pe.variableName),pe.labelName],color:Ror},{tag:[pe.color,pe.constant(pe.name),pe.standard(pe.name)],color:Cqe},{tag:[pe.definition(pe.name),pe.separator],color:o7},{tag:[pe.typeName,pe.className,pe.number,pe.changed,pe.annotation,pe.modifier,pe.self,pe.namespace],color:Nor},{tag:[pe.operator,pe.operatorKeyword,pe.url,pe.escape,pe.regexp,pe.link,pe.special(pe.string)],color:Ior},{tag:[pe.meta,pe.comment],color:Wbe},{tag:pe.strong,fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.link,color:Wbe,textDecoration:"underline"},{tag:pe.heading,fontWeight:"bold",color:_qe},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:Cqe},{tag:[pe.processingInstruction,pe.string,pe.inserted],color:Por},{tag:pe.invalid,color:Aor}]),zor=[Lor,ZA(For)];var Bor=Bt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),Uor=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,o=n.editable,i=o===void 0?!0:o,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,y=[];switch(s&&y.unshift(HA.of([Fsr])),m&&(typeof m=="boolean"?y.unshift(Oqe()):y.unshift(Oqe(m))),p&&y.unshift(oXn(p)),d){case"light":y.push(Bor);break;case"dark":y.push(zor);break;case"none":break;default:y.push(d);break}return i===!1&&y.push(Bt.editable.of(!1)),c&&y.push(vs.readOnly.of(!0)),[...y]},Vor=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 qor{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 Nqe{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 Sse=null,Hor=()=>typeof window>"u"?new Nqe:(Sse||(Sse=new Nqe),Sse),Wor=Bt.theme({"& .cm-scroller":{height:"100% !important"}}),Iqe=null,kse=null;function Zor(e,t,n,r,s,o){if(!e&&!t&&!n&&!r&&!s&&!o)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:o});return i===Iqe||(Iqe=i,kse=Bt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:o}})),kse}var Aqe=gb.define(),Gor=200,Qor=[];function Yor(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,o=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?Qor: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,y=m===void 0?null:m,v=e.maxHeight,b=v===void 0?null:v,x=e.width,w=x===void 0?null:x,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,T=C===void 0?null:C,E=e.placeholder,I=E===void 0?"":E,N=e.editable,A=N===void 0?!0:N,P=e.readOnly,F=P===void 0?!1:P,D=e.indentWithTab,H=D===void 0?!0:D,q=e.basicSetup,V=q===void 0?!0:q,B=e.root,Z=e.initialState,z=g.useState(),Y=z[0],L=z[1],R=g.useState(),M=R[0],U=R[1],Q=g.useState(),te=Q[0],K=Q[1],ee=g.useState(()=>({current:null}))[0],ne=g.useState(()=>({current:null}))[0],le=Zor(h,y,b,w,_,T),J=Bt.updateListener.of(ie=>{if(ie.docChanged&&typeof r=="function"&&!ie.transactions.some(xe=>xe.annotation(Aqe))){ee.current?ee.current.reset():(ee.current=new qor(()=>{if(ne.current){var xe=ne.current;ne.current=null,xe()}ee.current=null},Gor),Hor().add(ee.current));var fe=ie.state.doc,he=fe.toString();r(he,ie)}s&&s(Vor(ie))}),re=Uor({theme:f,editable:A,readOnly:F,placeholder:I,indentWithTab:H,basicSetup:V}),se=[J,...le?[le]:[],Wor,...re];return i&&typeof i=="function"&&se.push(Bt.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(Y&&!te){var ie={doc:t,selection:n,extensions:se},fe=Z?vs.fromJSON(Z.json,ie,Z.fields):vs.create(ie);if(K(fe),!M){var he=new Bt({state:fe,parent:Y,root:B});U(he),o&&o(he,fe)}}return()=>{M&&(K(void 0),U(void 0))}},[Y,te]),g.useEffect(()=>{e.container&&L(e.container)},[e.container]),g.useEffect(()=>()=>{M&&(M.destroy(),U(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[M]),g.useEffect(()=>{u&&M&&M.focus()},[u,M]),g.useEffect(()=>{M&&M.dispatch({effects:Sr.reconfigure.of(se)})},[f,c,h,y,b,w,_,T,I,A,F,H,V,r,i]),g.useEffect(()=>{if(t!==void 0){var ie=M?M.state.doc.toString():"";if(M&&t!==ie){var fe=ee.current&&!ee.current.isDone,he=()=>{M&&t!==M.state.doc.toString()&&M.dispatch({changes:{from:0,to:M.state.doc.toString().length,insert:t||""},annotations:[Aqe.of(!0)]})};fe?ne.current=he:he()}}},[t,M]),{state:te,setState:K,view:M,setView:U,container:Y,setContainer:L}}var Kor=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],d1=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,o=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,y=e.height,v=e.minHeight,b=e.maxHeight,x=e.width,w=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,T=e.indentWithTab,E=e.editable,I=e.readOnly,N=e.root,A=e.initialState,P=zjt(e,Kor),F=g.useRef(null),D=Yor({root:N,value:s,autoFocus:p,theme:m,height:y,minHeight:v,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:T,editable:E,readOnly:I,selection:o,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),H=D.state,q=D.view,V=D.container,B=D.setContainer;g.useImperativeHandle(t,()=>({editor:F.current,state:H,view:q}),[F,V,H,q]);var Z=g.useCallback(Y=>{F.current=Y,B(Y)},[B]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var z=typeof m=="string"?"cm-theme-"+m:"cm-theme";return a.jsx("div",tC({ref:Z,className:""+z+(n?" "+n:"")},P))});d1.displayName="CodeMirror";function Xor(e){return new X_(jEe.define(e))}const Jor=[Ig.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Bo(()=>Promise.resolve().then(()=>w9),[],import.meta.url).then(e=>e.javascript())}}),Ig.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Bo(()=>Promise.resolve().then(()=>jJn),void 0,import.meta.url).then(e=>e.json())}}),Ig.of({name:"JSX",extensions:["jsx"],load(){return Bo(()=>Promise.resolve().then(()=>w9),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),Ig.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Bo(()=>Promise.resolve().then(()=>krr),void 0,import.meta.url).then(e=>e.markdown())}}),Ig.of({name:"TSX",extensions:["tsx"],load(){return Bo(()=>Promise.resolve().then(()=>w9),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 Bo(()=>Promise.resolve().then(()=>w9),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 Bo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>Xor(e.shell))}})];function eir(e,t=5){if(!e?.properties)return[];const n=[];function r(s,o,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:o,label:o,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${o}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${o}[].${c}`,i+1)}for(const[s,o]of Object.entries(e.properties))r(o,s,1);return n}function tir(e){const t=eir(e);return OTt({override:[nir(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function nir(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]??"",o=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 y=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:y},selection:{anchor:f+y.length}})}}));return{from:o,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const rir=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,sir=Ln.mark({class:"cm-variable-highlight"}),Rqe=new DEt({regexp:rir,decoration:()=>sir}),oir=ka.fromClass(class{decorations;constructor(e){this.decorations=Rqe.createDeco(e)}update(e){this.decorations=Rqe.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),iir=oir;function air(){const e=oQ({settings:{fontFamily:"var(--font-mono)",fontSize:"var(--text-body-sm)",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--placeholder)",background:"transparent",foreground:"var(--foreground)",caret:"var(--foreground)"},styles:[{tag:[pe.className,pe.propertyName],color:"var(--foreground)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic",color:"var(--foreground)"},{tag:pe.strong,fontWeight:"bold",color:"var(--foreground)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--foreground)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.quote,fontStyle:"italic",color:"var(--placeholder)"}]}),t=Bt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--foreground)",caretColor:"var(--foreground)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--placeholder)"},".cm-activeLineGutter":{color:"var(--muted-foreground)"},".cm-cursor":{borderLeftColor:"var(--foreground)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--background)",border:"1px solid var(--border)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--foreground)"},".cm-completionDetail":{color:"var(--muted-foreground)",fontSize:"var(--text-caption)",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--background)",border:"1px solid var(--border)",color:"var(--muted-foreground)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--fill-hover)",color:"var(--foreground)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function lir(){const e=Bt.theme({"&":{backgroundColor:"transparent",color:"var(--foreground)",fontSize:"var(--text-body-sm)"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--placeholder)",borderRight:"none"},".cm-content":{color:"var(--foreground)",caretColor:"var(--foreground)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--placeholder)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--muted-foreground)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--foreground)"},"&.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(--background)",border:"1px solid var(--border)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--foreground)"},".cm-completionDetail":{color:"var(--muted-foreground)",fontSize:"var(--text-caption)",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--background)",border:"1px solid var(--border)",color:"var(--muted-foreground)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--fill-hover)",color:"var(--foreground)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=$0.define([{tag:[pe.comment,pe.bracket],color:"var(--placeholder)"},{tag:[pe.string,pe.meta,pe.regexp],color:"var(--accent1)"},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:"var(--accent6)"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"var(--accent2)"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"var(--accent5)"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"var(--accent3)"},{tag:[pe.variableName,pe.number],color:"var(--accent5)"},{tag:[pe.name,pe.quote],color:"var(--accent1)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.emphasis],fontStyle:"italic",color:"var(--foreground)"},{tag:[pe.strong],fontWeight:"bold",color:"var(--foreground)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--foreground)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:[pe.deleted],color:"var(--accent2)"},{tag:pe.invalid,color:"var(--error)"},{tag:[pe.standard(pe.tagName)],color:"var(--accent1)"}]);return[e,ZA(t)]}const n5=()=>{const e=M3().resolvedTheme==="dark";return g.useMemo(()=>e?air():lir(),[e])},cir=rd(W("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","transition-colors duration-normal ease-out-custom"),{variants:{variant:{default:W(nG,"rounded-md p-1",nSt),embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),uir=dh.highest(Bt.editorAttributes.of({style:"outline: none"})),dir=dh.highest(Bt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),fir=[uir,dir],br=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:o="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,id:m,"aria-label":y="Code editor","aria-describedby":v,"aria-invalid":b,...x},w)=>{const k=n5(),_=e?JSON.stringify(e,null,2):t??"",C=g.useMemo(()=>{const T={"aria-label":y};m&&(T.id=m),v&&(T["aria-describedby"]=v),b!==void 0&&(T["aria-invalid"]=String(b));const E=[...fir,Bt.contentAttributes.of(T)];return f&&E.push(Bt.lineWrapping),o==="json"?E.push(qx):o==="markdown"&&E.push(Ljt({base:hI,codeLanguages:Jor})),i&&o==="markdown"&&E.push(iir),c&&o==="markdown"&&E.push(tir(c)),p===!1&&E.push(vs.readOnly.of(!0)),E},[o,i,c,p,f,m,y,v,b]);return a.jsxs("div",{className:W(cir({variant:h}),s),...x,children:[r&&a.jsx(Oo,{content:_,className:"absolute top-2 right-2 z-20"}),a.jsx(d1,{ref:w,value:_,theme:k,extensions:C,onChange:n,editable:p,"aria-label":y,placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),RNt={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 Ose=null;function pir(){return Ose||(Ose=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Bo(()=>import("./core-CGlHLIis.js"),__vite__mapDeps([0,1,2]),import.meta.url),Bo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Bo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Bo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Bo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Bo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Bo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Bo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Bo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Bo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Bo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Bo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Bo(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Bo(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Bo(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Bo(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Bo(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Bo(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Ose}async function hir(e,t){const n=RNt[t?.toLowerCase()];if(!n)return null;const r=await pir(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function mir(e){const t=e?.split(".").pop()?.toLowerCase();return t?RNt[t]:void 0}const gir=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},vir=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=n5(),{settings:r,setSettings:s}=zG(),o=r?.tracingOptions,i=g.useMemo(()=>gir(o),[o]),[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 a.jsxs("div",{className:"space-y-2 px-5 py-2",children:[a.jsx(je,{as:"h3",variant:"body",tone:"muted",children:"Tracing Options"}),a.jsx(d1,{value:l,onChange:d,theme:n,extensions:[qx],className:W("overflow-hidden overflow-y-scroll rounded-lg bg-card p-3",e)}),a.jsx("div",{className:"flex items-center justify-end",children:a.jsx(ae,{icon:a.jsx(Vn,{}),type:"button",onClick:f,children:"Save"})})]})},yir=({resourceId:e,onResourceIdChange:t})=>{const[n,r]=g.useState(!1);return a.jsxs(a.Fragment,{children:[a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx(ae,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>r(!0),children:a.jsx(_t,{children:a.jsx(g_e,{})})})}),a.jsx(kn,{children:"Run Options"})]}),a.jsx(hs,{open:n,onOpenChange:r,children:a.jsxs(rs,{children:[a.jsxs(ss,{children:[a.jsx(Jr,{children:"Run Options"}),a.jsx(Ms,{children:"Configure resource attribution, tracing and debug options for this workflow run"})]}),a.jsxs(ys,{children:[a.jsx("div",{className:"px-5 py-2",children:a.jsx(qi,{name:"workflow-run-resource-id",label:"Resource ID",value:e,onChange:s=>t(s.target.value),placeholder:"e.g. tenant-42",helpText:"Ignored when server auth derives the resource ID from the user."})}),a.jsx(vir,{onSaved:()=>r(!1)})]})]})})]})};function ql(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=ql(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var bir={value:()=>{}};function uQ(){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 i7(n)}function i7(e){this._=e}function xir(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}})}i7.prototype=uQ.prototype={constructor:i7,on:function(e,t){var n=this._,r=xir(e+"",n),s,o=-1,i=r.length;if(arguments.length<2){for(;++o<i;)if((s=(e=r[o]).type)&&(s=wir(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<i;)if(s=(e=r[o]).type)n[s]=Pqe(n[s],e.name,t);else if(t==null)for(s in n)n[s]=Pqe(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 i7(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,o;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],r=0,s=o.length;r<s;++r)o[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,o=r.length;s<o;++s)r[s].value.apply(t,n)}};function wir(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function Pqe(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=bir,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Zbe="http://www.w3.org/1999/xhtml";const $qe={svg:"http://www.w3.org/2000/svg",xhtml:Zbe,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function dQ(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),$qe.hasOwnProperty(t)?{space:$qe[t],local:e}:e}function Sir(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Zbe&&t.documentElement.namespaceURI===Zbe?t.createElement(e):t.createElementNS(n,e)}}function kir(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function PNt(e){var t=dQ(e);return(t.local?kir:Sir)(t)}function Oir(){}function dTe(e){return e==null?Oir:function(){return this.querySelector(e)}}function _ir(e){typeof e!="function"&&(e=dTe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=o[d])&&(u=e.call(c,c.__data__,d,o))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Jp(r,this._parents)}function Cir(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function Eir(){return[]}function $Nt(e){return e==null?Eir:function(){return this.querySelectorAll(e)}}function Tir(e){return function(){return Cir(e.apply(this,arguments))}}function jir(e){typeof e=="function"?e=Tir(e):e=$Nt(e);for(var t=this._groups,n=t.length,r=[],s=[],o=0;o<n;++o)for(var i=t[o],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 Jp(r,s)}function MNt(e){return function(){return this.matches(e)}}function DNt(e){return function(t){return t.matches(e)}}var Nir=Array.prototype.find;function Iir(e){return function(){return Nir.call(this.children,e)}}function Air(){return this.firstElementChild}function Rir(e){return this.select(e==null?Air:Iir(typeof e=="function"?e:DNt(e)))}var Pir=Array.prototype.filter;function $ir(){return Array.from(this.children)}function Mir(e){return function(){return Pir.call(this.children,e)}}function Dir(e){return this.selectAll(e==null?$ir:Mir(typeof e=="function"?e:DNt(e)))}function Lir(e){typeof e!="function"&&(e=MNt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,l=r[s]=[],c,u=0;u<i;++u)(c=o[u])&&e.call(c,c.__data__,u,o)&&l.push(c);return new Jp(r,this._parents)}function LNt(e){return new Array(e.length)}function Fir(){return new Jp(this._enter||this._groups.map(LNt),this._parents)}function kq(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}kq.prototype={constructor:kq,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 zir(e){return function(){return e}}function Bir(e,t,n,r,s,o){for(var i=0,l,c=t.length,u=o.length;i<u;++i)(l=t[i])?(l.__data__=o[i],r[i]=l):n[i]=new kq(e,o[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function Uir(e,t,n,r,s,o,i){var l,c,u=new Map,d=t.length,f=o.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,o[l],l,o)+"",(c=u.get(h))?(r[l]=c,c.__data__=o[l],u.delete(h)):n[l]=new kq(e,o[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function Vir(e){return e.__data__}function qir(e,t){if(!arguments.length)return Array.from(this,Vir);var n=t?Uir:Bir,r=this._parents,s=this._groups;typeof e!="function"&&(e=zir(e));for(var o=s.length,i=new Array(o),l=new Array(o),c=new Array(o),u=0;u<o;++u){var d=r[u],f=s[u],p=f.length,h=Hir(e.call(d,d&&d.__data__,u,r)),m=h.length,y=l[u]=new Array(m),v=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,y,v,b,h,t);for(var x=0,w=0,k,_;x<m;++x)if(k=y[x]){for(x>=w&&(w=x+1);!(_=v[w])&&++w<m;);k._next=_||null}}return i=new Jp(i,r),i._enter=l,i._exit=c,i}function Hir(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Wir(){return new Jp(this._exit||this._groups.map(LNt),this._parents)}function Zir(e,t,n){var r=this.enter(),s=this,o=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?o.remove():n(o),r&&s?r.merge(s).order():s}function Gir(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,o=r.length,i=Math.min(s,o),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 Jp(l,this._parents)}function Qir(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,o=r[s],i;--s>=0;)(i=r[s])&&(o&&i.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(i,o),o=i);return this}function Yir(e){e||(e=Kir);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),o=0;o<r;++o){for(var i=n[o],l=i.length,c=s[o]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Jp(s,this._parents).order()}function Kir(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Xir(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Jir(){return Array.from(this)}function ear(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,o=r.length;s<o;++s){var i=r[s];if(i)return i}return null}function tar(){let e=0;for(const t of this)++e;return e}function nar(){return!this.node()}function rar(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],o=0,i=s.length,l;o<i;++o)(l=s[o])&&e.call(l,l.__data__,o,s);return this}function sar(e){return function(){this.removeAttribute(e)}}function oar(e){return function(){this.removeAttributeNS(e.space,e.local)}}function iar(e,t){return function(){this.setAttribute(e,t)}}function aar(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function lar(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function car(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 uar(e,t){var n=dQ(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?oar:sar:typeof t=="function"?n.local?car:lar:n.local?aar:iar)(n,t))}function FNt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function dar(e){return function(){this.style.removeProperty(e)}}function far(e,t,n){return function(){this.style.setProperty(e,t,n)}}function par(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function har(e,t,n){return arguments.length>1?this.each((t==null?dar:typeof t=="function"?par:far)(e,t,n??"")):vI(this.node(),e)}function vI(e,t){return e.style.getPropertyValue(t)||FNt(e).getComputedStyle(e,null).getPropertyValue(t)}function mar(e){return function(){delete this[e]}}function gar(e,t){return function(){this[e]=t}}function yar(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function bar(e,t){return arguments.length>1?this.each((t==null?mar:typeof t=="function"?yar:gar)(e,t)):this.node()[e]}function zNt(e){return e.trim().split(/^|\s+/)}function fTe(e){return e.classList||new BNt(e)}function BNt(e){this._node=e,this._names=zNt(e.getAttribute("class")||"")}BNt.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 UNt(e,t){for(var n=fTe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function VNt(e,t){for(var n=fTe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function xar(e){return function(){UNt(this,e)}}function war(e){return function(){VNt(this,e)}}function Sar(e,t){return function(){(t.apply(this,arguments)?UNt:VNt)(this,e)}}function kar(e,t){var n=zNt(e+"");if(arguments.length<2){for(var r=fTe(this.node()),s=-1,o=n.length;++s<o;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?Sar:t?xar:war)(n,t))}function Oar(){this.textContent=""}function _ar(e){return function(){this.textContent=e}}function Car(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function Ear(e){return arguments.length?this.each(e==null?Oar:(typeof e=="function"?Car:_ar)(e)):this.node().textContent}function Tar(){this.innerHTML=""}function jar(e){return function(){this.innerHTML=e}}function Nar(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function Iar(e){return arguments.length?this.each(e==null?Tar:(typeof e=="function"?Nar:jar)(e)):this.node().innerHTML}function Aar(){this.nextSibling&&this.parentNode.appendChild(this)}function Rar(){return this.each(Aar)}function Par(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function $ar(){return this.each(Par)}function Mar(e){var t=typeof e=="function"?e:PNt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function Dar(){return null}function Lar(e,t){var n=typeof e=="function"?e:PNt(e),r=t==null?Dar:typeof t=="function"?t:dTe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function Far(){var e=this.parentNode;e&&e.removeChild(this)}function zar(){return this.each(Far)}function Bar(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Uar(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Var(e){return this.select(e?Uar:Bar)}function qar(e){return arguments.length?this.property("__data__",e):this.node().__data__}function Har(e){return function(t){e.call(this,t,this.__data__)}}function War(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 Zar(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,o;n<s;++n)o=t[n],(!e.type||o.type===e.type)&&o.name===e.name?this.removeEventListener(o.type,o.listener,o.options):t[++r]=o;++r?t.length=r:delete this.__on}}}function Gar(e,t,n){return function(){var r=this.__on,s,o=Har(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=o,s.options=n),s.value=t;return}}this.addEventListener(e.type,o,n),s={type:e.type,name:e.name,value:t,listener:o,options:n},r?r.push(s):this.__on=[s]}}function Qar(e,t,n){var r=War(e+""),s,o=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<o;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?Gar:Zar,s=0;s<o;++s)this.each(l(r[s],t,n));return this}function qNt(e,t,n){var r=FNt(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 Yar(e,t){return function(){return qNt(this,e,t)}}function Kar(e,t){return function(){return qNt(this,e,t.apply(this,arguments))}}function Xar(e,t){return this.each((typeof t=="function"?Kar:Yar)(e,t))}function*Jar(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,o=r.length,i;s<o;++s)(i=r[s])&&(yield i)}var HNt=[null];function Jp(e,t){this._groups=e,this._parents=t}function r5(){return new Jp([[document.documentElement]],HNt)}function elr(){return this}Jp.prototype=r5.prototype={constructor:Jp,select:_ir,selectAll:jir,selectChild:Rir,selectChildren:Dir,filter:Lir,data:qir,enter:Fir,exit:Wir,join:Zir,merge:Gir,selection:elr,order:Qir,sort:Yir,call:Xir,nodes:Jir,node:ear,size:tar,empty:nar,each:rar,attr:uar,style:har,property:bar,classed:kar,text:Ear,html:Iar,raise:Rar,lower:$ar,append:Mar,insert:Lar,remove:zar,clone:Var,datum:qar,on:Qar,dispatch:Xar,[Symbol.iterator]:Jar};function Np(e){return typeof e=="string"?new Jp([[document.querySelector(e)]],[document.documentElement]):new Jp([[e]],HNt)}function tlr(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Ag(e,t){if(e=tlr(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 nlr={passive:!1},RL={capture:!0,passive:!1};function _se(e){e.stopImmediatePropagation()}function cN(e){e.preventDefault(),e.stopImmediatePropagation()}function WNt(e){var t=e.document.documentElement,n=Np(e).on("dragstart.drag",cN,RL);"onselectstart"in t?n.on("selectstart.drag",cN,RL):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function ZNt(e,t){var n=e.document.documentElement,r=Np(e).on("dragstart.drag",null);t&&(r.on("click.drag",cN,RL),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 C9=e=>()=>e;function Gbe(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:o,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:o,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}})}Gbe.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function rlr(e){return!e.ctrlKey&&!e.button}function slr(){return this.parentNode}function olr(e,t){return t??{x:e.x,y:e.y}}function ilr(){return navigator.maxTouchPoints||"ontouchstart"in this}function GNt(){var e=rlr,t=slr,n=olr,r=ilr,s={},o=uQ("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",v).on("touchmove.drag",b,nlr).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=w(this,t.call(this,k,_),k,_,"mouse");C&&(Np(k.view).on("mousemove.drag",m,RL).on("mouseup.drag",y,RL),WNt(k.view),_se(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(cN(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function y(k){Np(k.view).on("mousemove.drag mouseup.drag",null),ZNt(k.view,u),cN(k),s.mouse("end",k)}function v(k,_){if(e.call(this,k,_)){var C=k.changedTouches,T=t.call(this,k,_),E=C.length,I,N;for(I=0;I<E;++I)(N=w(this,T,k,_,C[I].identifier,C[I]))&&(_se(k),N("start",k,C[I]))}}function b(k){var _=k.changedTouches,C=_.length,T,E;for(T=0;T<C;++T)(E=s[_[T].identifier])&&(cN(k),E("drag",k,_[T]))}function x(k){var _=k.changedTouches,C=_.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<C;++T)(E=s[_[T].identifier])&&(_se(k),E("end",k,_[T]))}function w(k,_,C,T,E,I){var N=o.copy(),A=Ag(I||C,_),P,F,D;if((D=n.call(k,new Gbe("beforestart",{sourceEvent:C,target:p,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:N}),T))!=null)return P=D.x-A[0]||0,F=D.y-A[1]||0,function H(q,V,B){var Z=A,z;switch(q){case"start":s[E]=H,z=i++;break;case"end":delete s[E],--i;case"drag":A=Ag(B||V,_),z=i;break}N.call(q,k,new Gbe(q,{sourceEvent:V,subject:D,target:p,identifier:E,active:z,x:A[0]+P,y:A[1]+F,dx:A[0]-Z[0],dy:A[1]-Z[1],dispatch:N}),T)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:C9(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:C9(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:C9(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:C9(!!k),p):r},p.on=function(){var k=o.on.apply(o,arguments);return k===o?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function pTe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function QNt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function s5(){}var PL=.7,Oq=1/PL,uN="\\s*([+-]?\\d+)\\s*",$L="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",$y="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",alr=/^#([0-9a-f]{3,8})$/,llr=new RegExp(`^rgb\\(${uN},${uN},${uN}\\)$`),clr=new RegExp(`^rgb\\(${$y},${$y},${$y}\\)$`),ulr=new RegExp(`^rgba\\(${uN},${uN},${uN},${$L}\\)$`),dlr=new RegExp(`^rgba\\(${$y},${$y},${$y},${$L}\\)$`),flr=new RegExp(`^hsl\\(${$L},${$y},${$y}\\)$`),plr=new RegExp(`^hsla\\(${$L},${$y},${$y},${$L}\\)$`),Mqe={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};pTe(s5,nC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Dqe,formatHex:Dqe,formatHex8:hlr,formatHsl:mlr,formatRgb:Lqe,toString:Lqe});function Dqe(){return this.rgb().formatHex()}function hlr(){return this.rgb().formatHex8()}function mlr(){return YNt(this).formatHsl()}function Lqe(){return this.rgb().formatRgb()}function nC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=alr.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Fqe(t):n===3?new Pf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?E9(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?E9(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=llr.exec(e))?new Pf(t[1],t[2],t[3],1):(t=clr.exec(e))?new Pf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=ulr.exec(e))?E9(t[1],t[2],t[3],t[4]):(t=dlr.exec(e))?E9(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=flr.exec(e))?Uqe(t[1],t[2]/100,t[3]/100,1):(t=plr.exec(e))?Uqe(t[1],t[2]/100,t[3]/100,t[4]):Mqe.hasOwnProperty(e)?Fqe(Mqe[e]):e==="transparent"?new Pf(NaN,NaN,NaN,0):null}function Fqe(e){return new Pf(e>>16&255,e>>8&255,e&255,1)}function E9(e,t,n,r){return r<=0&&(e=t=n=NaN),new Pf(e,t,n,r)}function glr(e){return e instanceof s5||(e=nC(e)),e?(e=e.rgb(),new Pf(e.r,e.g,e.b,e.opacity)):new Pf}function Qbe(e,t,n,r){return arguments.length===1?glr(e):new Pf(e,t,n,r??1)}function Pf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}pTe(Pf,Qbe,QNt(s5,{brighter(e){return e=e==null?Oq:Math.pow(Oq,e),new Pf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?PL:Math.pow(PL,e),new Pf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Pf(i_(this.r),i_(this.g),i_(this.b),_q(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:zqe,formatHex:zqe,formatHex8:vlr,formatRgb:Bqe,toString:Bqe}));function zqe(){return`#${LO(this.r)}${LO(this.g)}${LO(this.b)}`}function vlr(){return`#${LO(this.r)}${LO(this.g)}${LO(this.b)}${LO((isNaN(this.opacity)?1:this.opacity)*255)}`}function Bqe(){const e=_q(this.opacity);return`${e===1?"rgb(":"rgba("}${i_(this.r)}, ${i_(this.g)}, ${i_(this.b)}${e===1?")":`, ${e})`}`}function _q(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function i_(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function LO(e){return e=i_(e),(e<16?"0":"")+e.toString(16)}function Uqe(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Lg(e,t,n,r)}function YNt(e){if(e instanceof Lg)return new Lg(e.h,e.s,e.l,e.opacity);if(e instanceof s5||(e=nC(e)),!e)return new Lg;if(e instanceof Lg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),o=Math.max(t,n,r),i=NaN,l=o-s,c=(o+s)/2;return l?(t===o?i=(n-r)/l+(n<r)*6:n===o?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?o+s:2-o-s,i*=60):l=c>0&&c<1?0:i,new Lg(i,l,c,e.opacity)}function ylr(e,t,n,r){return arguments.length===1?YNt(e):new Lg(e,t,n,r??1)}function Lg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}pTe(Lg,ylr,QNt(s5,{brighter(e){return e=e==null?Oq:Math.pow(Oq,e),new Lg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?PL:Math.pow(PL,e),new Lg(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 Pf(Cse(e>=240?e-240:e+120,s,r),Cse(e,s,r),Cse(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Lg(Vqe(this.h),T9(this.s),T9(this.l),_q(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=_q(this.opacity);return`${e===1?"hsl(":"hsla("}${Vqe(this.h)}, ${T9(this.s)*100}%, ${T9(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Vqe(e){return e=(e||0)%360,e<0?e+360:e}function T9(e){return Math.max(0,Math.min(1,e||0))}function Cse(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 hTe=e=>()=>e;function blr(e,t){return function(n){return e+n*t}}function xlr(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 wlr(e){return(e=+e)==1?KNt:function(t,n){return n-t?xlr(t,n,e):hTe(isNaN(t)?n:t)}}function KNt(e,t){var n=t-e;return n?blr(e,n):hTe(isNaN(e)?t:e)}const Cq=(function e(t){var n=wlr(t);function r(s,o){var i=n((s=Qbe(s)).r,(o=Qbe(o)).r),l=n(s.g,o.g),c=n(s.b,o.b),u=KNt(s.opacity,o.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 Slr(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(o){for(s=0;s<n;++s)r[s]=e[s]*(1-o)+t[s]*o;return r}}function klr(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Olr(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),o=new Array(n),i;for(i=0;i<r;++i)s[i]=Hx(e[i],t[i]);for(;i<n;++i)o[i]=t[i];return function(l){for(i=0;i<r;++i)o[i]=s[i](l);return o}}function _lr(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Pg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function Clr(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]=Hx(e[s],t[s]):r[s]=t[s];return function(o){for(s in n)r[s]=n[s](o);return r}}var Ybe=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ese=new RegExp(Ybe.source,"g");function Elr(e){return function(){return e}}function Tlr(e){return function(t){return e(t)+""}}function XNt(e,t){var n=Ybe.lastIndex=Ese.lastIndex=0,r,s,o,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Ybe.exec(e))&&(s=Ese.exec(t));)(o=s.index)>n&&(o=t.slice(n,o),l[i]?l[i]+=o:l[++i]=o),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:Pg(r,s)})),n=Ese.lastIndex;return n<t.length&&(o=t.slice(n),l[i]?l[i]+=o:l[++i]=o),l.length<2?c[0]?Tlr(c[0].x):Elr(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 Hx(e,t){var n=typeof t,r;return t==null||n==="boolean"?hTe(t):(n==="number"?Pg:n==="string"?(r=nC(t))?(t=r,Cq):XNt:t instanceof nC?Cq:t instanceof Date?_lr:klr(t)?Slr:Array.isArray(t)?Olr:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?Clr:Pg)(e,t)}function mTe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var qqe=180/Math.PI,Kbe={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function JNt(e,t,n,r,s,o){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:o,rotate:Math.atan2(t,e)*qqe,skewX:Math.atan(c)*qqe,scaleX:i,scaleY:l}}var j9;function jlr(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Kbe:JNt(t.a,t.b,t.c,t.d,t.e,t.f)}function Nlr(e){return e==null||(j9||(j9=document.createElementNS("http://www.w3.org/2000/svg","g")),j9.setAttribute("transform",e),!(e=j9.transform.baseVal.consolidate()))?Kbe:(e=e.matrix,JNt(e.a,e.b,e.c,e.d,e.e,e.f))}function eIt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function o(u,d,f,p,h,m){if(u!==f||d!==p){var y=h.push("translate(",null,t,null,n);m.push({i:y-4,x:Pg(u,f)},{i:y-2,x:Pg(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:Pg(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:Pg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var y=h.push(s(h)+"scale(",null,",",null,")");m.push({i:y-4,x:Pg(u,f)},{i:y-2,x:Pg(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),o(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,y=p.length,v;++m<y;)f[(v=p[m]).i]=v.x(h);return f.join("")}}}var Ilr=eIt(jlr,"px, ","px)","deg)"),Alr=eIt(Nlr,", ",")",")"),Rlr=1e-12;function Hqe(e){return((e=Math.exp(e))+1/e)/2}function Plr(e){return((e=Math.exp(e))-1/e)/2}function $lr(e){return((e=Math.exp(2*e))-1)/(e+1)}const a7=(function e(t,n,r){function s(o,i){var l=o[0],c=o[1],u=o[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,y=h*h+m*m,v,b;if(y<Rlr)b=Math.log(p/u)/t,v=function(T){return[l+T*h,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(y),w=(p*p-u*u+r*y)/(2*u*n*x),k=(p*p-u*u-r*y)/(2*p*n*x),_=Math.log(Math.sqrt(w*w+1)-w),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,v=function(T){var E=T*b,I=Hqe(_),N=u/(n*x)*(I*$lr(t*E+_)-Plr(_));return[l+N*h,c+N*m,u*I/Hqe(t*E+_)]}}return v.duration=b*1e3*t/Math.SQRT2,v}return s.rho=function(o){var i=Math.max(.001,+o),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function Mlr(e,t){t===void 0&&(t=e,e=Hx);for(var n=0,r=t.length-1,s=t[0],o=new Array(r<0?0:r);n<r;)o[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return o[l](i-l)}}var yI=0,zM=0,u$=0,tIt=1e3,Eq,BM,Tq=0,rC=0,fQ=0,ML=typeof performance=="object"&&performance.now?performance:Date,nIt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function gTe(){return rC||(nIt(Dlr),rC=ML.now()+fQ)}function Dlr(){rC=0}function jq(){this._call=this._time=this._next=null}jq.prototype=rIt.prototype={constructor:jq,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?gTe():+n)+(t==null?0:+t),!this._next&&BM!==this&&(BM?BM._next=this:Eq=this,BM=this),this._call=e,this._time=n,Xbe()},stop:function(){this._call&&(this._call=null,this._time=1/0,Xbe())}};function rIt(e,t,n){var r=new jq;return r.restart(e,t,n),r}function Llr(){gTe(),++yI;for(var e=Eq,t;e;)(t=rC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--yI}function Wqe(){rC=(Tq=ML.now())+fQ,yI=zM=0;try{Llr()}finally{yI=0,zlr(),rC=0}}function Flr(){var e=ML.now(),t=e-Tq;t>tIt&&(fQ-=t,Tq=e)}function zlr(){for(var e,t=Eq,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:Eq=n);BM=e,Xbe(r)}function Xbe(e){if(!yI){zM&&(zM=clearTimeout(zM));var t=e-rC;t>24?(e<1/0&&(zM=setTimeout(Wqe,e-ML.now()-fQ)),u$&&(u$=clearInterval(u$))):(u$||(Tq=ML.now(),u$=setInterval(Flr,tIt)),yI=1,nIt(Wqe))}}function Zqe(e,t,n){var r=new jq;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var Blr=uQ("start","end","cancel","interrupt"),Ulr=[],sIt=0,Gqe=1,Jbe=2,l7=3,Qqe=4,exe=5,c7=6;function pQ(e,t,n,r,s,o){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;Vlr(e,n,{name:t,index:r,group:s,on:Blr,tween:Ulr,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:sIt})}function vTe(e,t){var n=xv(e,t);if(n.state>sIt)throw new Error("too late; already scheduled");return n}function yb(e,t){var n=xv(e,t);if(n.state>l7)throw new Error("too late; already running");return n}function xv(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function Vlr(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=rIt(o,0,n.time);function o(u){n.state=Gqe,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!==Gqe)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===l7)return Zqe(i);h.state===Qqe?(h.state=c7,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=c7,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(Zqe(function(){n.state===l7&&(n.state=Qqe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Jbe,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Jbe){for(n.state=l7,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=exe,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===exe&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=c7,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function u7(e,t){var n=e.__transition,r,s,o=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){o=!1;continue}s=r.state>Jbe&&r.state<exe,r.state=c7,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}o&&delete e.__transition}}function qlr(e){return this.each(function(){u7(this,e)})}function Hlr(e,t){var n,r;return function(){var s=yb(this,e),o=s.tween;if(o!==n){r=n=o;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 Wlr(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var o=yb(this,e),i=o.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)}o.tween=s}}function Zlr(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=xv(this.node(),n).tween,s=0,o=r.length,i;s<o;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?Hlr:Wlr)(n,e,t))}function yTe(e,t,n){var r=e._id;return e.each(function(){var s=yb(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return xv(s,r).value[t]}}function oIt(e,t){var n;return(typeof t=="number"?Pg:t instanceof nC?Cq:(n=nC(t))?(t=n,Cq):XNt)(e,t)}function Glr(e){return function(){this.removeAttribute(e)}}function Qlr(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Ylr(e,t,n){var r,s=n+"",o;return function(){var i=this.getAttribute(e);return i===s?null:i===r?o:o=t(r=i,n)}}function Klr(e,t,n){var r,s=n+"",o;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?o:o=t(r=i,n)}}function Xlr(e,t,n){var r,s,o;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?o:(s=c,o=t(r=i,l)))}}function Jlr(e,t,n){var r,s,o;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?o:(s=c,o=t(r=i,l)))}}function ecr(e,t){var n=dQ(e),r=n==="transform"?Alr:oIt;return this.attrTween(e,typeof t=="function"?(n.local?Jlr:Xlr)(n,r,yTe(this,"attr."+e,t)):t==null?(n.local?Qlr:Glr)(n):(n.local?Klr:Ylr)(n,r,t))}function tcr(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function ncr(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function rcr(e,t){var n,r;function s(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&ncr(e,o)),n}return s._value=t,s}function scr(e,t){var n,r;function s(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&tcr(e,o)),n}return s._value=t,s}function ocr(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=dQ(e);return this.tween(n,(r.local?rcr:scr)(r,t))}function icr(e,t){return function(){vTe(this,e).delay=+t.apply(this,arguments)}}function acr(e,t){return t=+t,function(){vTe(this,e).delay=t}}function lcr(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?icr:acr)(t,e)):xv(this.node(),t).delay}function ccr(e,t){return function(){yb(this,e).duration=+t.apply(this,arguments)}}function ucr(e,t){return t=+t,function(){yb(this,e).duration=t}}function dcr(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?ccr:ucr)(t,e)):xv(this.node(),t).duration}function fcr(e,t){if(typeof t!="function")throw new Error;return function(){yb(this,e).ease=t}}function pcr(e){var t=this._id;return arguments.length?this.each(fcr(t,e)):xv(this.node(),t).ease}function hcr(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;yb(this,e).ease=n}}function mcr(e){if(typeof e!="function")throw new Error;return this.each(hcr(this._id,e))}function gcr(e){typeof e!="function"&&(e=MNt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,l=r[s]=[],c,u=0;u<i;++u)(c=o[u])&&e.call(c,c.__data__,u,o)&&l.push(c);return new u0(r,this._parents,this._name,this._id)}function vcr(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,o=Math.min(r,s),i=new Array(r),l=0;l<o;++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 u0(i,this._parents,this._name,this._id)}function ycr(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 bcr(e,t,n){var r,s,o=ycr(t)?vTe:yb;return function(){var i=o(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function xcr(e,t){var n=this._id;return arguments.length<2?xv(this.node(),n).on.on(e):this.each(bcr(n,e,t))}function wcr(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Scr(){return this.on("end.remove",wcr(this._id))}function kcr(e){var t=this._name,n=this._id;typeof e!="function"&&(e=dTe(e));for(var r=this._groups,s=r.length,o=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=o[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,pQ(u[p],t,n,p,u,xv(d,n)));return new u0(o,this._parents,t,n)}function Ocr(e){var t=this._name,n=this._id;typeof e!="function"&&(e=$Nt(e));for(var r=this._groups,s=r.length,o=[],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=xv(d,n),y=0,v=p.length;y<v;++y)(h=p[y])&&pQ(h,t,n,y,p,m);o.push(p),i.push(d)}return new u0(o,i,t,n)}var _cr=r5.prototype.constructor;function Ccr(){return new _cr(this._groups,this._parents)}function Ecr(e,t){var n,r,s;return function(){var o=vI(this,e),i=(this.style.removeProperty(e),vI(this,e));return o===i?null:o===n&&i===r?s:s=t(n=o,r=i)}}function iIt(e){return function(){this.style.removeProperty(e)}}function Tcr(e,t,n){var r,s=n+"",o;return function(){var i=vI(this,e);return i===s?null:i===r?o:o=t(r=i,n)}}function jcr(e,t,n){var r,s,o;return function(){var i=vI(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),vI(this,e))),i===c?null:i===r&&c===s?o:(s=c,o=t(r=i,l))}}function Ncr(e,t){var n,r,s,o="style."+t,i="end."+o,l;return function(){var c=yb(this,e),u=c.on,d=c.value[o]==null?l||(l=iIt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function Icr(e,t,n){var r=(e+="")=="transform"?Ilr:oIt;return t==null?this.styleTween(e,Ecr(e,r)).on("end.style."+e,iIt(e)):typeof t=="function"?this.styleTween(e,jcr(e,r,yTe(this,"style."+e,t))).each(Ncr(this._id,e)):this.styleTween(e,Tcr(e,r,t),n).on("end.style."+e,null)}function Acr(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function Rcr(e,t,n){var r,s;function o(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&Acr(e,i,n)),r}return o._value=t,o}function Pcr(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,Rcr(e,t,n??""))}function $cr(e){return function(){this.textContent=e}}function Mcr(e){return function(){var t=e(this);this.textContent=t??""}}function Dcr(e){return this.tween("text",typeof e=="function"?Mcr(yTe(this,"text",e)):$cr(e==null?"":e+""))}function Lcr(e){return function(t){this.textContent=e.call(this,t)}}function Fcr(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&Lcr(s)),t}return r._value=e,r}function zcr(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,Fcr(e))}function Bcr(){for(var e=this._name,t=this._id,n=aIt(),r=this._groups,s=r.length,o=0;o<s;++o)for(var i=r[o],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=xv(c,t);pQ(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new u0(r,this._parents,e,n)}function Ucr(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(o,i){var l={value:i},c={value:function(){--s===0&&o()}};n.each(function(){var u=yb(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&&o()})}var Vcr=0;function u0(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function aIt(){return++Vcr}var Gb=r5.prototype;u0.prototype={constructor:u0,select:kcr,selectAll:Ocr,selectChild:Gb.selectChild,selectChildren:Gb.selectChildren,filter:gcr,merge:vcr,selection:Ccr,transition:Bcr,call:Gb.call,nodes:Gb.nodes,node:Gb.node,size:Gb.size,empty:Gb.empty,each:Gb.each,on:xcr,attr:ecr,attrTween:ocr,style:Icr,styleTween:Pcr,text:Dcr,textTween:zcr,remove:Scr,tween:Zlr,delay:lcr,duration:dcr,ease:pcr,easeVarying:mcr,end:Ucr,[Symbol.iterator]:Gb[Symbol.iterator]};function qcr(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Hcr={time:null,delay:0,duration:250,ease:qcr};function Wcr(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 Zcr(e){var t,n;e instanceof u0?(t=e._id,e=e._name):(t=aIt(),(n=Hcr).time=gTe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,o=0;o<s;++o)for(var i=r[o],l=i.length,c,u=0;u<l;++u)(c=i[u])&&pQ(c,e,t,u,i,n||Wcr(c,t));return new u0(r,this._parents,e,t)}r5.prototype.interrupt=qlr;r5.prototype.transition=Zcr;const N9=e=>()=>e;function Gcr(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 Ex(e,t,n){this.k=e,this.x=t,this.y=n}Ex.prototype={constructor:Ex,scale:function(e){return e===1?this:new Ex(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Ex(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 hQ=new Ex(1,0,0);lIt.prototype=Ex.prototype;function lIt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return hQ;return e.__zoom}function Tse(e){e.stopImmediatePropagation()}function d$(e){e.preventDefault(),e.stopImmediatePropagation()}function Qcr(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Ycr(){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 Yqe(){return this.__zoom||hQ}function Kcr(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Xcr(){return navigator.maxTouchPoints||"ontouchstart"in this}function Jcr(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],o=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>o?(o+i)/2:Math.min(0,o)||Math.max(0,i))}function cIt(){var e=Qcr,t=Ycr,n=Jcr,r=Kcr,s=Xcr,o=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=a7,u=uQ("start","zoom","end"),d,f,p,h=500,m=150,y=0,v=10;function b(D){D.property("__zoom",Yqe).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",I).on("dblclick.zoom",N).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,H,q,V){var B=D.selection?D.selection():D;B.property("__zoom",Yqe),D!==B?_(D,H,q,V):B.interrupt().each(function(){C(this,arguments).event(V).start().zoom(null,typeof H=="function"?H.apply(this,arguments):H).end()})},b.scaleBy=function(D,H,q,V){b.scaleTo(D,function(){var B=this.__zoom.k,Z=typeof H=="function"?H.apply(this,arguments):H;return B*Z},q,V)},b.scaleTo=function(D,H,q,V){b.transform(D,function(){var B=t.apply(this,arguments),Z=this.__zoom,z=q==null?k(B):typeof q=="function"?q.apply(this,arguments):q,Y=Z.invert(z),L=typeof H=="function"?H.apply(this,arguments):H;return n(w(x(Z,L),z,Y),B,i)},q,V)},b.translateBy=function(D,H,q,V){b.transform(D,function(){return n(this.__zoom.translate(typeof H=="function"?H.apply(this,arguments):H,typeof q=="function"?q.apply(this,arguments):q),t.apply(this,arguments),i)},null,V)},b.translateTo=function(D,H,q,V,B){b.transform(D,function(){var Z=t.apply(this,arguments),z=this.__zoom,Y=V==null?k(Z):typeof V=="function"?V.apply(this,arguments):V;return n(hQ.translate(Y[0],Y[1]).scale(z.k).translate(typeof H=="function"?-H.apply(this,arguments):-H,typeof q=="function"?-q.apply(this,arguments):-q),Z,i)},V,B)};function x(D,H){return H=Math.max(o[0],Math.min(o[1],H)),H===D.k?D:new Ex(H,D.x,D.y)}function w(D,H,q){var V=H[0]-q[0]*D.k,B=H[1]-q[1]*D.k;return V===D.x&&B===D.y?D:new Ex(D.k,V,B)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,H,q,V){D.on("start.zoom",function(){C(this,arguments).event(V).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(V).end()}).tween("zoom",function(){var B=this,Z=arguments,z=C(B,Z).event(V),Y=t.apply(B,Z),L=q==null?k(Y):typeof q=="function"?q.apply(B,Z):q,R=Math.max(Y[1][0]-Y[0][0],Y[1][1]-Y[0][1]),M=B.__zoom,U=typeof H=="function"?H.apply(B,Z):H,Q=c(M.invert(L).concat(R/M.k),U.invert(L).concat(R/U.k));return function(te){if(te===1)te=U;else{var K=Q(te),ee=R/K[2];te=new Ex(ee,L[0]-K[0]*ee,L[1]-K[1]*ee)}z.zoom(null,te)}})}function C(D,H,q){return!q&&D.__zooming||new T(D,H)}function T(D,H){this.that=D,this.args=H,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,H),this.taps=0}T.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,H){return this.mouse&&D!=="mouse"&&(this.mouse[1]=H.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=H.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=H.invert(this.touch1[0])),this.that.__zoom=H,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var H=Np(this.that).datum();u.call(D,this.that,new Gcr(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),H)}};function E(D,...H){if(!e.apply(this,arguments))return;var q=C(this,H).event(D),V=this.__zoom,B=Math.max(o[0],Math.min(o[1],V.k*Math.pow(2,r.apply(this,arguments)))),Z=Ag(D);if(q.wheel)(q.mouse[0][0]!==Z[0]||q.mouse[0][1]!==Z[1])&&(q.mouse[1]=V.invert(q.mouse[0]=Z)),clearTimeout(q.wheel);else{if(V.k===B)return;q.mouse=[Z,V.invert(Z)],u7(this),q.start()}d$(D),q.wheel=setTimeout(z,m),q.zoom("mouse",n(w(x(V,B),q.mouse[0],q.mouse[1]),q.extent,i));function z(){q.wheel=null,q.end()}}function I(D,...H){if(p||!e.apply(this,arguments))return;var q=D.currentTarget,V=C(this,H,!0).event(D),B=Np(D.view).on("mousemove.zoom",L,!0).on("mouseup.zoom",R,!0),Z=Ag(D,q),z=D.clientX,Y=D.clientY;WNt(D.view),Tse(D),V.mouse=[Z,this.__zoom.invert(Z)],u7(this),V.start();function L(M){if(d$(M),!V.moved){var U=M.clientX-z,Q=M.clientY-Y;V.moved=U*U+Q*Q>y}V.event(M).zoom("mouse",n(w(V.that.__zoom,V.mouse[0]=Ag(M,q),V.mouse[1]),V.extent,i))}function R(M){B.on("mousemove.zoom mouseup.zoom",null),ZNt(M.view,V.moved),d$(M),V.event(M).end()}}function N(D,...H){if(e.apply(this,arguments)){var q=this.__zoom,V=Ag(D.changedTouches?D.changedTouches[0]:D,this),B=q.invert(V),Z=q.k*(D.shiftKey?.5:2),z=n(w(x(q,Z),V,B),t.apply(this,H),i);d$(D),l>0?Np(this).transition().duration(l).call(_,z,V,D):Np(this).call(b.transform,z,V,D)}}function A(D,...H){if(e.apply(this,arguments)){var q=D.touches,V=q.length,B=C(this,H,D.changedTouches.length===V).event(D),Z,z,Y,L;for(Tse(D),z=0;z<V;++z)Y=q[z],L=Ag(Y,this),L=[L,this.__zoom.invert(L),Y.identifier],B.touch0?!B.touch1&&B.touch0[2]!==L[2]&&(B.touch1=L,B.taps=0):(B.touch0=L,Z=!0,B.taps=1+!!d);d&&(d=clearTimeout(d)),Z&&(B.taps<2&&(f=L[0],d=setTimeout(function(){d=null},h)),u7(this),B.start())}}function P(D,...H){if(this.__zooming){var q=C(this,H).event(D),V=D.changedTouches,B=V.length,Z,z,Y,L;for(d$(D),Z=0;Z<B;++Z)z=V[Z],Y=Ag(z,this),q.touch0&&q.touch0[2]===z.identifier?q.touch0[0]=Y:q.touch1&&q.touch1[2]===z.identifier&&(q.touch1[0]=Y);if(z=q.that.__zoom,q.touch1){var R=q.touch0[0],M=q.touch0[1],U=q.touch1[0],Q=q.touch1[1],te=(te=U[0]-R[0])*te+(te=U[1]-R[1])*te,K=(K=Q[0]-M[0])*K+(K=Q[1]-M[1])*K;z=x(z,Math.sqrt(te/K)),Y=[(R[0]+U[0])/2,(R[1]+U[1])/2],L=[(M[0]+Q[0])/2,(M[1]+Q[1])/2]}else if(q.touch0)Y=q.touch0[0],L=q.touch0[1];else return;q.zoom("touch",n(w(z,Y,L),q.extent,i))}}function F(D,...H){if(this.__zooming){var q=C(this,H).event(D),V=D.changedTouches,B=V.length,Z,z;for(Tse(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),Z=0;Z<B;++Z)z=V[Z],q.touch0&&q.touch0[2]===z.identifier?delete q.touch0:q.touch1&&q.touch1[2]===z.identifier&&delete q.touch1;if(q.touch1&&!q.touch0&&(q.touch0=q.touch1,delete q.touch1),q.touch0)q.touch0[1]=this.__zoom.invert(q.touch0[0]);else if(q.end(),q.taps===2&&(z=Ag(z,this),Math.hypot(f[0]-z[0],f[1]-z[1])<v)){var Y=Np(this).on("dblclick.zoom");Y&&Y.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:N9(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:N9(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:N9(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:N9([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(o[0]=+D[0],o[1]=+D[1],b):[o[0],o[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?(y=(D=+D)*D,b):Math.sqrt(y)},b.tapDistance=function(D){return arguments.length?(v=+D,b):v},b}const tb={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."},DL=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],uIt=["Enter"," ","Escape"],dIt={"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 bI;(function(e){e.Strict="strict",e.Loose="loose"})(bI||(bI={}));var a_;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(a_||(a_={}));var LL;(function(e){e.Partial="partial",e.Full="full"})(LL||(LL={}));const fIt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var sS;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(sS||(sS={}));var FL;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(FL||(FL={}));var or;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(or||(or={}));const Kqe={[or.Left]:or.Right,[or.Right]:or.Left,[or.Top]:or.Bottom,[or.Bottom]:or.Top};function pIt(e){return e===null?null:e?"valid":"invalid"}const hIt=e=>"id"in e&&"source"in e&&"target"in e,eur=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),bTe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),o5=(e,t=[0,0])=>{const{width:n,height:r}=M0(e),s=e.origin??t,o=n*s[0],i=r*s[1];return{x:e.position.x-o,y:e.position.y-i}},tur=(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 o=typeof s=="string";let i=!t.nodeLookup&&!o?s:void 0;t.nodeLookup&&(i=o?t.nodeLookup.get(s):bTe(s)?s:t.nodeLookup.get(s.id));const l=i?Nq(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return mQ(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return gQ(n)},i5=(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=mQ(n,Nq(s)),r=!0)}),r?gQ(n):{x:0,y:0,width:0,height:0}},xTe=(e,t,[n,r,s]=[0,0,1],o=!1,i=!1)=>{const l={...l5(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,y=zL(l,wI(u)),v=(h??0)*(m??0),b=o&&y>0;(!u.internals.handleBounds||b||y>=v||u.dragging)&&c.push(u)}return c},nur=(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 rur(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 sur({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:o},i){if(e.size===0)return Promise.resolve(!0);const l=rur(e,i),c=i5(l),u=wTe(c,t,n,i?.minZoom??s,i?.maxZoom??o,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function mIt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:o}){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)o?.("005",tb.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&SI(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=SI(f)?sC(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&o?.("015",tb.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 our({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const o=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=o.has(p.id),m=!h&&p.parentId&&i.find(y=>y.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=nur(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 xI=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),sC=(e={x:0,y:0},t,n)=>({x:xI(e.x,t[0][0],t[1][0]-(n?.width??0)),y:xI(e.y,t[0][1],t[1][1]-(n?.height??0))});function gIt(e,t,n){const{width:r,height:s}=M0(n),{x:o,y:i}=n.internals.positionAbsolute;return sC(e,[[o,i],[o+r,i+s]],t)}const Xqe=(e,t,n)=>e<t?xI(Math.abs(e-t),1,t)/t:e>n?-xI(Math.abs(e-n),1,t)/t:0,vIt=(e,t,n=15,r=40)=>{const s=Xqe(e.x,r,t.width-r)*n,o=Xqe(e.y,r,t.height-r)*n;return[s,o]},mQ=(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)}),txe=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),gQ=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),wI=(e,t=[0,0])=>{const{x:n,y:r}=bTe(e)?e.internals.positionAbsolute:o5(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}},Nq=(e,t=[0,0])=>{const{x:n,y:r}=bTe(e)?e.internals.positionAbsolute:o5(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)}},yIt=(e,t)=>gQ(mQ(txe(e),txe(t))),zL=(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)},Jqe=e=>Ug(e.width)&&Ug(e.height)&&Ug(e.x)&&Ug(e.y),Ug=e=>!isNaN(e)&&isFinite(e),iur=(e,t)=>{},a5=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),l5=({x:e,y:t},[n,r,s],o=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return o?a5(l,i):l},Iq=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function kT(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 aur(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=kT(e,n),s=kT(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=kT(e.top??e.y??0,n),s=kT(e.bottom??e.y??0,n),o=kT(e.left??e.x??0,t),i=kT(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:o,x:o+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function lur(e,t,n,r,s,o){const{x:i,y:l}=Iq(e,[t,n,r]),{x:c,y:u}=Iq({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=o-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const wTe=(e,t,n,r,s,o)=>{const i=aur(o,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=xI(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,y=lur(e,h,m,d,t,n),v={left:Math.min(y.left-i.left,0),top:Math.min(y.top-i.top,0),right:Math.min(y.right-i.right,0),bottom:Math.min(y.bottom-i.bottom,0)};return{x:h-v.left+v.right,y:m-v.top+v.bottom,zoom:d}},BL=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function SI(e){return e!=null&&e!=="parent"}function M0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function STe(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function bIt(e,t={width:0,height:0},n,r,s){const o={...e},i=r.get(n);if(i){const l=i.origin||s;o.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],o.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return o}function eHe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function cur(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function uur(e){return{...dIt,...e||{}}}function A2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:o,y:i}=Vg(e),l=l5({x:o-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?a5(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const kTe=e=>({width:e.offsetWidth,height:e.offsetHeight}),xIt=e=>e?.getRootNode?.()||window?.document,dur=["INPUT","SELECT","TEXTAREA"];function wIt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:dur.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const SIt=e=>"clientX"in e,Vg=(e,t)=>{const n=SIt(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)}},tHe=(e,t,n,r,s)=>{const o=t.querySelectorAll(`.${e}`);return!o||!o.length?null:Array.from(o).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,...kTe(i)}})};function kIt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:o,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+o*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function I9(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function nHe({pos:e,x1:t,y1:n,x2:r,y2:s,c:o}){switch(e){case or.Left:return[t-I9(t-r,o),n];case or.Right:return[t+I9(r-t,o),n];case or.Top:return[t,n-I9(n-s,o)];case or.Bottom:return[t,n+I9(s-n,o)]}}function OTe({sourceX:e,sourceY:t,sourcePosition:n=or.Bottom,targetX:r,targetY:s,targetPosition:o=or.Top,curvature:i=.25}){const[l,c]=nHe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=nHe({pos:o,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=kIt({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 OIt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,o=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[o,l,s,i]}function fur({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:o="basic"}){if(o==="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 pur({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const o=mQ(Nq(e),Nq(t));o.x===o.x2&&(o.x2+=1),o.y===o.y2&&(o.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return zL(i,gQ(o))>0}const hur=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,mur=(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)),gur=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||hur;let s;return hIt(e)?s={...e}:s={...e,id:r(e)},mur(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function _It({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,o,i,l]=OIt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,o,i,l]}const rHe={[or.Left]:{x:-1,y:0},[or.Right]:{x:1,y:0},[or.Top]:{x:0,y:-1},[or.Bottom]:{x:0,y:1}},vur=({source:e,sourcePosition:t=or.Bottom,target:n})=>t===or.Left||t===or.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},sHe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function yur({source:e,sourcePosition:t=or.Bottom,target:n,targetPosition:r=or.Top,center:s,offset:o,stepPosition:i}){const l=rHe[t],c=rHe[r],u={x:e.x+l.x*o,y:e.y+l.y*o},d={x:n.x+c.x*o,y:n.y+c.y*o},f=vur({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],y,v;const b={x:0,y:0},x={x:0,y:0},[,,w,k]=OIt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(y=s.x??u.x+(d.x-u.x)*i,v=s.y??(u.y+d.y)/2):(y=s.x??(u.x+d.x)/2,v=s.y??u.y+(d.y-u.y)*i);const E=[{x:y,y:u.y},{x:y,y:d.y}],I=[{x:u.x,y:v},{x:d.x,y:v}];l[p]===h?m=p==="x"?E:I:m=p==="x"?I:E}else{const E=[{x:u.x,y:d.y}],I=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?I:E:m=l.y===h?E:I,t===r){const D=Math.abs(e[p]-n[p]);if(D<=o){const H=Math.min(o-1,o-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*H:x[p]=(d[p]>n[p]?-1:1)*H}}if(t!==r){const D=p==="x"?"y":"x",H=l[p]===c[D],q=u[D]>d[D],V=u[D]<d[D];(l[p]===1&&(!H&&q||H&&V)||l[p]!==1&&(!H&&V||H&&q))&&(m=p==="x"?E:I)}const N={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},P=Math.max(Math.abs(N.x-m[0].x),Math.abs(A.x-m[0].x)),F=Math.max(Math.abs(N.y-m[0].y),Math.abs(A.y-m[0].y));P>=F?(y=(N.x+A.x)/2,v=m[0].y):(y=m[0].x,v=(N.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],y,v,w,k]}function bur(e,t,n,r){const s=Math.min(sHe(e,t)/2,sHe(t,n)/2,r),{x:o,y:i}=t;if(e.x===o&&o===n.x||e.y===i&&i===n.y)return`L${o} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${o+s*u},${i}Q ${o},${i} ${o},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${o},${i+s*c}Q ${o},${i} ${o+s*l},${i}`}function nxe({sourceX:e,sourceY:t,sourcePosition:n=or.Bottom,targetX:r,targetY:s,targetPosition:o=or.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,y]=yur({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:o,center:{x:l,y:c},offset:u,stepPosition:d});let v=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)v+=bur(f[b-1],f[b],f[b+1],i);return v+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[v,p,h,m,y]}function oHe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function xur(e){const{sourceNode:t,targetNode:n}=e;if(!oHe(t)||!oHe(n))return null;const r=t.internals.handleBounds||iHe(t.handles),s=n.internals.handleBounds||iHe(n.handles),o=aHe(r?.source??[],e.sourceHandle),i=aHe(e.connectionMode===bI.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!o||!i)return e.onError?.("008",tb.error008(o?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=o?.position||or.Bottom,c=i?.position||or.Top,u=oC(t,o,l),d=oC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function iHe(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 oC(e,t,n=or.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,o=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??M0(e);if(r)return{x:s+i/2,y:o+l/2};switch(t?.position??n){case or.Top:return{x:s+i/2,y:o};case or.Right:return{x:s+i,y:o+l/2};case or.Bottom:return{x:s+i/2,y:o+l};case or.Left:return{x:s,y:o+l/2}}}function aHe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function rxe(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function wur(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const o=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=rxe(c,t);o.has(u)||(i.push({id:u,color:c.color||n,...c}),o.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const CIt=1e3,Sur=10,_Te={nodeOrigin:[0,0],nodeExtent:DL,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},kur={..._Te,checkEquality:!0};function CTe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function Our(e,t,n){const r=CTe(_Te,n);for(const s of e.values())if(s.parentId)TTe(s,e,t,r);else{const o=o5(s,r.nodeOrigin),i=SI(s.extent)?s.extent:r.nodeExtent,l=sC(o,i,M0(s));s.internals.positionAbsolute=l}}function _ur(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const o={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(o):s.type==="target"&&r.push(o)}return{source:n,target:r}}function ETe(e){return e==="manual"}function sxe(e,t,n,r={}){const s=CTe(kur,r),o={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!ETe(s.zIndexMode)?CIt: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=o5(d,s.nodeOrigin),h=SI(d.extent)?d.extent:s.nodeExtent,m=sC(p,h,M0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:_ur(d,f),z:EIt(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&&TTe(f,t,n,r,o),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function Cur(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 TTe(e,t,n,r,s){const{elevateNodesOnSelect:o,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=CTe(_Te,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}Cur(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*Sur),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=o&&!ETe(c)?CIt:0,{x:p,y:h,z:m}=Eur(e,d,i,l,f,c),{positionAbsolute:y}=e.internals,v=p!==y.x||h!==y.y;(v||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:v?{x:p,y:h}:y,z:m}})}function EIt(e,t,n){const r=Ug(e.zIndex)?e.zIndex:0;return ETe(n)?r:r+(e.selected?t:0)}function Eur(e,t,n,r,s,o){const{x:i,y:l}=t.internals.positionAbsolute,c=M0(e),u=o5(e,n),d=SI(e.extent)?sC(u,e.extent,c):u;let f=sC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=gIt(f,c,t));const p=EIt(e,s,o),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function jTe(e,t,n,r=[0,0]){const s=[],o=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=o.get(i.parentId)?.expandedRect??wI(l),u=yIt(c,i.rect);o.set(i.parentId,{expandedRect:u,parent:l})}return o.size>0&&o.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=M0(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)),y=Math.max(d.height,Math.round(i.height)),v=(m-d.width)*f[0],b=(y-d.height)*f[1];(p>0||h>0||v||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+v,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(w=>w.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-v:0),height:y+(h?f[1]*h-b:0)}})}),s}function Tur(e,t,n,r,s,o,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 y=kTe(h.nodeElement),v=m.measured.width!==y.width||m.measured.height!==y.height;if(!!(y.width&&y.height&&(v||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),w=SI(m.extent)?m.extent:o;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=gIt(k,y,t.get(m.parentId)):w&&(k=sC(k,w,y));const _={...m,measured:y,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:tHe("source",h.nodeElement,x,f,m.id),target:tHe("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&TTe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,v&&(u.push({id:m.id,type:"dimensions",dimensions:y}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:wI(_,s)}))}}if(p.length>0){const h=jTe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function jur({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:o}){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,o]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function lHe(e,t,n,r,s,o){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)),o){i=`${s}-${e}-${o}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function TIt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:o,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:o,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${o}-${l}`,d=`${o}-${l}--${s}-${i}`;lHe("source",c,d,e,s,i),lHe("target",c,u,e,o,l),t.set(r.id,r)}}function jIt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:jIt(n,t):!1}function cHe(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 Nur(e,t,n,r){const s=new Map;for(const[o,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!jIt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(o);l&&s.set(o,{id:o,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 jse({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 o=n.get(e)?.internals.userNode;return[o?{...o,position:t.get(e)?.position||o.position,dragging:r}:s[0],s]}function Iur({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const o={x:n-s.distance.x,y:r-s.distance.y},i=a5(o,t);return{x:i.x-o.x,y:i.y-o.y}}function Aur({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let o={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,y=null;function v({noDragClassName:x,handleSelector:w,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:T=0}){p=Np(k);function E({x:P,y:F}){const{nodeLookup:D,nodeExtent:H,snapGrid:q,snapToGrid:V,nodeOrigin:B,onNodeDrag:Z,onSelectionDrag:z,onError:Y,updateNodePositions:L}=t();o={x:P,y:F};let R=!1;const M=l.size>1,U=M&&H?txe(i5(l)):null,Q=M&&V?Iur({dragItems:l,snapGrid:q,x:P,y:F}):null;for(const[te,K]of l){if(!D.has(te))continue;let ee={x:P-K.distance.x,y:F-K.distance.y};V&&(ee=Q?{x:Math.round(ee.x+Q.x),y:Math.round(ee.y+Q.y)}:a5(ee,q));let ne=null;if(M&&H&&!K.extent&&U){const{positionAbsolute:re}=K.internals,se=re.x-U.x+H[0][0],ie=re.x+K.measured.width-U.x2+H[1][0],fe=re.y-U.y+H[0][1],he=re.y+K.measured.height-U.y2+H[1][1];ne=[[se,fe],[ie,he]]}const{position:le,positionAbsolute:J}=mIt({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:ne||H,nodeOrigin:B,onError:Y});R=R||K.position.x!==le.x||K.position.y!==le.y,K.position=le,K.internals.positionAbsolute=J}if(m=m||R,!!R&&(L(l,!0),y&&(r||Z||!C&&z))){const[te,K]=jse({nodeId:C,dragItems:l,nodeLookup:D});r?.(y,l,te,K),Z?.(y,te,K),C||z?.(y,K)}}async function I(){if(!d)return;const{transform:P,panBy:F,autoPanSpeed:D,autoPanOnNodeDrag:H}=t();if(!H){c=!1,cancelAnimationFrame(i);return}const[q,V]=vIt(u,d,D);(q!==0||V!==0)&&(o.x=(o.x??0)-q/P[2],o.y=(o.y??0)-V/P[2],await F({x:q,y:V})&&E(o)),i=requestAnimationFrame(I)}function N(P){const{nodeLookup:F,multiSelectionActive:D,nodesDraggable:H,transform:q,snapGrid:V,snapToGrid:B,selectNodesOnDrag:Z,onNodeDragStart:z,onSelectionDragStart:Y,unselectNodesAndEdges:L}=t();f=!0,(!Z||!_)&&!D&&C&&(F.get(C)?.selected||L()),_&&Z&&C&&e?.(C);const R=A2(P.sourceEvent,{transform:q,snapGrid:V,snapToGrid:B,containerBounds:d});if(o=R,l=Nur(F,H,R,C),l.size>0&&(n||z||!C&&Y)){const[M,U]=jse({nodeId:C,dragItems:l,nodeLookup:F});n?.(P.sourceEvent,l,M,U),z?.(P.sourceEvent,M,U),C||Y?.(P.sourceEvent,U)}}const A=GNt().clickDistance(T).on("start",P=>{const{domNode:F,nodeDragThreshold:D,transform:H,snapGrid:q,snapToGrid:V}=t();d=F?.getBoundingClientRect()||null,h=!1,m=!1,y=P.sourceEvent,D===0&&N(P),o=A2(P.sourceEvent,{transform:H,snapGrid:q,snapToGrid:V,containerBounds:d}),u=Vg(P.sourceEvent,d)}).on("drag",P=>{const{autoPanOnNodeDrag:F,transform:D,snapGrid:H,snapToGrid:q,nodeDragThreshold:V,nodeLookup:B}=t(),Z=A2(P.sourceEvent,{transform:D,snapGrid:H,snapToGrid:q,containerBounds:d});if(y=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||C&&!B.has(C))&&(h=!0),!h){if(!c&&F&&f&&(c=!0,I()),!f){const z=Vg(P.sourceEvent,d),Y=z.x-u.x,L=z.y-u.y;Math.sqrt(Y*Y+L*L)>V&&N(P)}(o.x!==Z.xSnapped||o.y!==Z.ySnapped)&&l&&f&&(u=Vg(P.sourceEvent,d),E(Z))}}).on("end",P=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:F,updateNodePositions:D,onNodeDragStop:H,onSelectionDragStop:q}=t();if(m&&(D(l,!1),m=!1),s||H||!C&&q){const[V,B]=jse({nodeId:C,dragItems:l,nodeLookup:F,dragging:!1});s?.(P.sourceEvent,l,V,B),H?.(P.sourceEvent,V,B),C||q?.(P.sourceEvent,B)}}}).filter(P=>{const F=P.target;return!P.button&&(!x||!cHe(F,`.${x}`,k))&&(!w||cHe(F,w,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:v,destroy:b}}function Rur(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const o of t.values())zL(s,wI(o))>0&&r.push(o);return r}const Pur=250;function $ur(e,t,n,r){let s=[],o=1/0;const i=Rur(e,n,t+Pur);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}=oC(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<o?(s=[{...u,x:d,y:f}],o=p):p===o&&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 NIt(e,t,n,r,s,o=!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&&o?{...c,...oC(i,c,c.position,!0)}:c}function IIt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function Mur(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const AIt=()=>!0;function Dur(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:o,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:y,onConnectEnd:v,isValidConnection:b=AIt,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:T=1,handleDomNode:E}){const I=xIt(e.target);let N=0,A;const{x:P,y:F}=Vg(e),D=IIt(o,E),H=l?.getBoundingClientRect();let q=!1;if(!H||!D)return;const V=NIt(s,D,r,c,t);if(!V)return;let B=Vg(e,H),Z=!1,z=null,Y=!1,L=null;function R(){if(!d||!H)return;const[le,J]=vIt(B,H,C);p({x:le,y:J}),N=requestAnimationFrame(R)}const M={...V,nodeId:s,type:D,position:V.position},U=c.get(s);let te={inProgress:!0,isValid:null,from:oC(U,M,or.Left,!0),fromHandle:M,fromPosition:M.position,fromNode:U,to:B,toHandle:null,toPosition:Kqe[M.position],toNode:null,pointer:B};function K(){q=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&K();function ee(le){if(!q){const{x:he,y:xe}=Vg(le),Ne=he-P,Ae=xe-F;if(!(Ne*Ne+Ae*Ae>T*T))return;K()}if(!_()||!M){ne(le);return}const J=k();B=Vg(le,H),A=$ur(l5(B,J,!1,[1,1]),n,c,M),Z||(R(),Z=!0);const re=RIt(le,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:I,lib:u,flowId:f,nodeLookup:c});L=re.handleDomNode,z=re.connection,Y=Mur(!!A,re.isValid);const se=c.get(s),ie=se?oC(se,M,or.Left,!0):te.from,fe={...te,from:ie,isValid:Y,to:re.toHandle&&Y?Iq({x:re.toHandle.x,y:re.toHandle.y},J):B,toHandle:re.toHandle,toPosition:Y&&re.toHandle?re.toHandle.position:Kqe[M.position],toNode:re.toHandle?c.get(re.toHandle.nodeId):null,pointer:B};w(fe),te=fe}function ne(le){if(!("touches"in le&&le.touches.length>0)){if(q){(A||L)&&z&&Y&&y?.(z);const{inProgress:J,...re}=te,se={...re,toPosition:te.toHandle?te.toPosition:null};v?.(le,se),o&&x?.(le,se)}h(),cancelAnimationFrame(N),Z=!1,Y=!1,z=null,L=null,I.removeEventListener("mousemove",ee),I.removeEventListener("mouseup",ne),I.removeEventListener("touchmove",ee),I.removeEventListener("touchend",ne)}}I.addEventListener("mousemove",ee),I.addEventListener("mouseup",ne),I.addEventListener("touchmove",ee),I.addEventListener("touchend",ne)}function RIt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:o,doc:i,lib:l,flowId:c,isValidConnection:u=AIt,nodeLookup:d}){const f=o==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=Vg(e),y=i.elementFromPoint(h,m),v=y?.classList.contains(`${l}-flow__handle`)?y:p,b={handleDomNode:v,isValid:!1,connection:null,toHandle:null};if(v){const x=IIt(void 0,v),w=v.getAttribute("data-nodeid"),k=v.getAttribute("data-handleid"),_=v.classList.contains("connectable"),C=v.classList.contains("connectableend");if(!w||!x)return b;const T={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=T;const I=_&&C&&(n===bI.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=I&&u(T),b.toHandle=NIt(w,x,k,d,n,!0)}return b}const oxe={onPointerDown:Dur,isValid:RIt};function Lur({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Np(e);function o({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=w.sourceEvent.ctrlKey&&BL()?10:1,C=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,C*_);t.scaleTo(T)};let y=[0,0];const v=w=>{(w.sourceEvent.type==="mousedown"||w.sourceEvent.type==="touchstart")&&(y=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY])},b=w=>{const k=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const _=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],C=[_[0]-y[0],_[1]-y[1]];y=_;const T=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),E={x:k[0]-C[0]*T,y:k[1]-C[1]*T},I=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},I,l)},x=cIt().on("start",v).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:o,destroy:i,pointer:Ag}}const vQ=e=>({x:e.x,y:e.y,zoom:e.k}),Nse=({x:e,y:t,zoom:n})=>hQ.translate(e,t).scale(n),Tj=(e,t)=>e.target.closest(`.${t}`),PIt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Fur=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Ise=(e,t=0,n=Fur,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},$It=e=>{const t=e.ctrlKey&&BL()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function zur({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:o,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(Tj(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const v=Ag(d),b=$It(d),x=f*Math.pow(2,b);r.scaleTo(n,x,v,d);return}const p=d.deltaMode===1?20:1;let h=s===a_.Vertical?0:d.deltaX*p,m=s===a_.Horizontal?0:d.deltaY*p;!BL()&&d.shiftKey&&s!==a_.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*o,-(m/f)*o,{internal:!0});const y=vQ(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,y),e.panScrollTimeout=setTimeout(()=>{u?.(d,y),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,y))}}function Bur({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const o=r.type==="wheel",i=!t&&o&&!r.ctrlKey,l=Tj(r,e);if(r.ctrlKey&&o&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function Uur({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=vQ(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 Vur({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return o=>{e.usedRightMouseButton=!!(n&&PIt(t,e.mouseButton??0)),o.sourceEvent?.sync||r([o.transform.x,o.transform.y,o.transform.k]),s&&!o.sourceEvent?.internal&&s?.(o.sourceEvent,vQ(o.transform))}}function qur({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:o}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,o&&PIt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&o(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=vQ(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function Hur({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:o,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"&&(Tj(f,`${u}-flow__node`)||Tj(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!o&&!n||i||d&&!m||Tj(f,l)&&m||Tj(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 y=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&y}}function Wur({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:o,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=cIt().scaleExtent([t,n]).translateExtent(r),p=Np(e).call(f);x({x:s.x,y:s.y,zoom:xI(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta($It);function y(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?Hx:a7).transform(Ise(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function v({noWheelClassName:A,noPanClassName:P,onPaneContextMenu:F,userSelectionActive:D,panOnScroll:H,panOnDrag:q,panOnScrollMode:V,panOnScrollSpeed:B,preventScrolling:Z,zoomOnPinch:z,zoomOnScroll:Y,zoomOnDoubleClick:L,zoomActivationKeyPressed:R,lib:M,onTransformChange:U,connectionInProgress:Q,paneClickDistance:te,selectionOnDrag:K}){D&&!u.isZoomingOrPanning&&b();const ee=H&&!R&&!D;f.clickDistance(K?1/0:!Ug(te)||te<0?0:te);const ne=ee?zur({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:V,panOnScrollSpeed:B,zoomOnPinch:z,onPanZoomStart:i,onPanZoom:o,onPanZoomEnd:l}):Bur({noWheelClassName:A,preventScrolling:Z,d3ZoomHandler:h});if(p.on("wheel.zoom",ne,{passive:!1}),!D){const J=Uur({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",J);const re=Vur({zoomPanValues:u,panOnDrag:q,onPaneContextMenu:!!F,onPanZoom:o,onTransformChange:U});f.on("zoom",re);const se=qur({zoomPanValues:u,panOnDrag:q,panOnScroll:H,onPaneContextMenu:F,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const le=Hur({zoomActivationKeyPressed:R,panOnDrag:q,zoomOnScroll:Y,panOnScroll:H,zoomOnDoubleClick:L,zoomOnPinch:z,userSelectionActive:D,noPanClassName:P,noWheelClassName:A,lib:M,connectionInProgress:Q});f.filter(le),L?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,P,F){const D=Nse(A),H=f?.constrain()(D,P,F);return H&&await y(H),new Promise(q=>q(H))}async function w(A,P){const F=Nse(A);return await y(F,P),new Promise(D=>D(F))}function k(A){if(p){const P=Nse(A),F=p.property("__zoom");(F.k!==A.zoom||F.x!==A.x||F.y!==A.y)&&f?.transform(p,P,null,{sync:!0})}}function _(){const A=p?lIt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?Hx:a7).scaleTo(Ise(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function T(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?Hx:a7).scaleBy(Ise(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function I(A){f?.translateExtent(A)}function N(A){const P=!Ug(A)||A<0?0:A;f?.clickDistance(P)}return{update:v,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:T,setScaleExtent:E,setTranslateExtent:I,syncViewport:k,setClickDistance:N}}var kI;(function(e){e.Line="line",e.Handle="handle"})(kI||(kI={}));function Zur({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:o}){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&&o&&(c[1]=c[1]*-1),c}function uHe(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 jw(e,t){return Math.max(0,t-e)}function Nw(e,t){return Math.max(0,e-t)}function A9(e,t,n){return Math.max(0,t-e,e-n)}function dHe(e,t){return e?!t:t}function Gur(e,t,n,r,s,o,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:y,maxWidth:v,minHeight:b,maxHeight:x}=r,{x:w,y:k,width:_,height:C,aspectRatio:T}=e;let E=Math.floor(d?h-e.pointerX:0),I=Math.floor(f?m-e.pointerY:0);const N=_+(c?-E:E),A=C+(u?-I:I),P=-o[0]*_,F=-o[1]*C;let D=A9(N,y,v),H=A9(A,b,x);if(i){let B=0,Z=0;c&&E<0?B=jw(w+E+P,i[0][0]):!c&&E>0&&(B=Nw(w+N+P,i[1][0])),u&&I<0?Z=jw(k+I+F,i[0][1]):!u&&I>0&&(Z=Nw(k+A+F,i[1][1])),D=Math.max(D,B),H=Math.max(H,Z)}if(l){let B=0,Z=0;c&&E>0?B=Nw(w+E,l[0][0]):!c&&E<0&&(B=jw(w+N,l[1][0])),u&&I>0?Z=Nw(k+I,l[0][1]):!u&&I<0&&(Z=jw(k+A,l[1][1])),D=Math.max(D,B),H=Math.max(H,Z)}if(s){if(d){const B=A9(N/T,b,x)*T;if(D=Math.max(D,B),i){let Z=0;!c&&!u||c&&!u&&p?Z=Nw(k+F+N/T,i[1][1])*T:Z=jw(k+F+(c?E:-E)/T,i[0][1])*T,D=Math.max(D,Z)}if(l){let Z=0;!c&&!u||c&&!u&&p?Z=jw(k+N/T,l[1][1])*T:Z=Nw(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,Z)}}if(f){const B=A9(A*T,y,v)/T;if(H=Math.max(H,B),i){let Z=0;!c&&!u||u&&!c&&p?Z=Nw(w+A*T+P,i[1][0])/T:Z=jw(w+(u?I:-I)*T+P,i[0][0])/T,H=Math.max(H,Z)}if(l){let Z=0;!c&&!u||u&&!c&&p?Z=jw(w+A*T,l[1][0])/T:Z=Nw(w+(u?I:-I)*T,l[0][0])/T,H=Math.max(H,Z)}}}I=I+(I<0?H:-H),E=E+(E<0?D:-D),s&&(p?N>A*T?I=(dHe(c,u)?-E:E)/T:E=(dHe(c,u)?-I:I)*T:d?(I=E/T,u=c):(E=I*T,c=u));const q=c?w+E:w,V=u?k+I:k;return{width:_+(c?-E:E),height:C+(u?-I:I),x:o[0]*E*(c?-1:1)+q,y:o[1]*I*(u?-1:1)+V}}const MIt={width:0,height:0,x:0,y:0},Qur={...MIt,pointerX:0,pointerY:0,aspectRatio:1};function Yur(e){return[[0,0],[e.measured.width,e.measured.height]]}function Kur(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,o=e.measured.width??0,i=e.measured.height??0,l=n[0]*o,c=n[1]*i;return[[r-l,s-c],[r+o-l,s+i-c]]}function Xur({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const o=Np(e);let i={controlDirection:uHe("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:y,shouldResize:v}){let b={...MIt},x={...Qur};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:uHe(u)};let w,k=null,_=[],C,T,E,I=!1;const N=GNt().on("start",A=>{const{nodeLookup:P,transform:F,snapGrid:D,snapToGrid:H,nodeOrigin:q,paneDomNode:V}=n();if(w=P.get(t),!w)return;k=V?.getBoundingClientRect()??null;const{xSnapped:B,ySnapped:Z}=A2(A.sourceEvent,{transform:F,snapGrid:D,snapToGrid:H,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},x={...b,pointerX:B,pointerY:Z,aspectRatio:b.width/b.height},C=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(C=P.get(w.parentId),T=C&&w.extent==="parent"?Yur(C):void 0),_=[],E=void 0;for(const[z,Y]of P)if(Y.parentId===t&&(_.push({id:z,position:{...Y.position},extent:Y.extent}),Y.extent==="parent"||Y.expandParent)){const L=Kur(Y,w,Y.origin??q);E?E=[[Math.min(L[0][0],E[0][0]),Math.min(L[0][1],E[0][1])],[Math.max(L[1][0],E[1][0]),Math.max(L[1][1],E[1][1])]]:E=L}h?.(A,{...b})}).on("drag",A=>{const{transform:P,snapGrid:F,snapToGrid:D,nodeOrigin:H}=n(),q=A2(A.sourceEvent,{transform:P,snapGrid:F,snapToGrid:D,containerBounds:k}),V=[];if(!w)return;const{x:B,y:Z,width:z,height:Y}=b,L={},R=w.origin??H,{width:M,height:U,x:Q,y:te}=Gur(x,i.controlDirection,q,i.boundaries,i.keepAspectRatio,R,T,E),K=M!==z,ee=U!==Y,ne=Q!==B&&K,le=te!==Z&&ee;if(!ne&&!le&&!K&&!ee)return;if((ne||le||R[0]===1||R[1]===1)&&(L.x=ne?Q:b.x,L.y=le?te:b.y,b.x=L.x,b.y=L.y,_.length>0)){const ie=Q-B,fe=te-Z;for(const he of _)he.position={x:he.position.x-ie+R[0]*(M-z),y:he.position.y-fe+R[1]*(U-Y)},V.push(he)}if((K||ee)&&(L.width=K&&(!i.resizeDirection||i.resizeDirection==="horizontal")?M:b.width,L.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?U:b.height,b.width=L.width,b.height=L.height),C&&w.expandParent){const ie=R[0]*(L.width??0);L.x&&L.x<ie&&(b.x=ie,x.x=x.x-(L.x-ie));const fe=R[1]*(L.height??0);L.y&&L.y<fe&&(b.y=fe,x.y=x.y-(L.y-fe))}const J=Zur({width:b.width,prevWidth:z,height:b.height,prevHeight:Y,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),re={...b,direction:J};v?.(A,re)!==!1&&(I=!0,m?.(A,re),r(L,V))}).on("end",A=>{I&&(y?.(A,{...b}),s?.({...b}),I=!1)});o.call(N)}function c(){o.on(".drag",null)}return{update:l,destroy:c}}const Jur={},fHe=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:()=>{(Jur?"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},edr=e=>e?fHe(e):fHe,{useDebugValue:tdr}=$e,{useSyncExternalStoreWithSelector:ndr}=RAn,rdr=e=>e;function DIt(e,t=rdr,n){const r=ndr(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return tdr(r),r}const pHe=(e,t)=>{const n=edr(e),r=(s,o=t)=>DIt(n,s,o);return Object.assign(r,n),r},sdr=(e,t)=>e?pHe(e,t):pHe;function Zi(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 yQ=g.createContext(null),odr=yQ.Provider,LIt=tb.error001();function is(e,t){const n=g.useContext(yQ);if(n===null)throw new Error(LIt);return DIt(n,e,t)}function Ta(){const e=g.useContext(yQ);if(e===null)throw new Error(LIt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const hHe={display:"none"},idr={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},FIt="react-flow__node-desc",zIt="react-flow__edge-desc",adr="react-flow__aria-live",ldr=e=>e.ariaLiveMessage,cdr=e=>e.ariaLabelConfig;function udr({rfId:e}){const t=is(ldr);return a.jsx("div",{id:`${adr}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:idr,children:t})}function ddr({rfId:e,disableKeyboardA11y:t}){const n=is(cdr);return a.jsxs(a.Fragment,{children:[a.jsx("div",{id:`${FIt}-${e}`,style:hHe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),a.jsx("div",{id:`${zIt}-${e}`,style:hHe,children:n["edge.a11yDescription.default"]}),!t&&a.jsx(udr,{rfId:e})]})}const c5=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},o)=>{const i=`${e}`.split("-");return a.jsx("div",{className:ql(["react-flow__panel",n,...i]),style:r,ref:o,...s,children:t})});c5.displayName="Panel";function fdr({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:a.jsx(c5,{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:a.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const pdr=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}},R9=e=>e.id;function hdr(e,t){return Zi(e.selectedNodes.map(R9),t.selectedNodes.map(R9))&&Zi(e.selectedEdges.map(R9),t.selectedEdges.map(R9))}function mdr({onSelectionChange:e}){const t=Ta(),{selectedNodes:n,selectedEdges:r}=is(pdr,hdr);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(o=>o(s))},[n,r,e]),null}const gdr=e=>!!e.onSelectionChangeHandlers;function vdr({onSelectionChange:e}){const t=is(gdr);return e||t?a.jsx(mdr,{onSelectionChange:e}):null}const ixe=typeof window<"u"?g.useLayoutEffect:g.useEffect,BIt=[0,0],ydr={x:0,y:0,zoom:1},bdr=["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"],mHe=[...bdr,"rfId"],xdr=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}),gHe={translateExtent:DL,nodeOrigin:BIt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function wdr(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:o,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=is(xdr,Zi),u=Ta();ixe(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=gHe,l()}),[]);const d=g.useRef(gHe);return ixe(()=>{for(const f of mHe){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"?o(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:uur(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},mHe.map(f=>e[f])),null}function vHe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Sdr(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=vHe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:vHe()?.matches?"dark":"light"}const yHe=typeof document<"u"?document:null;function UL(e=null,t={target:yHe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),o=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("+",`
249
+ `: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 sor(this):new tor(this)}getCursor(t,n=0,r){let s=t.doc?t:vs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?aj(this,s,n,r):ij(this,s,n,r)}}class ONt{constructor(t){this.spec=t}}function Jsr(e,t,n){return(r,s,o,i)=>{if(n&&!n(r,s,o,i))return!1;let l=r>=i&&s<=i+o.length?o.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function ij(e,t,n,r){let s;return e.wholeWord&&(s=eor(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=Jsr(e.test,t,s)),new mI(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:o=>o.toLowerCase(),s)}function eor(e,t){return(n,r,s,o)=>((o>n||o+s.length<r)&&(o=Math.max(0,n-2),s=e.sliceString(o,Math.min(e.length,r+2))),(t(bq(s,n-o))!=ba.Word||t(xq(s,n-o))!=ba.Word)&&(t(xq(s,r-o))!=ba.Word||t(bq(s,r-o))!=ba.Word))}class tor extends ONt{constructor(t){super(t)}nextMatch(t,n,r){let s=ij(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let o=Math.min(t.doc.length,n+this.spec.unquoted.length);s=ij(this.spec,t,0,o).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let o=Math.max(n,s-1e4-this.spec.unquoted.length),i=ij(this.spec,t,o,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(o==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=ij(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 o=ij(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!o.next().done;)s(o.value.from,o.value.to)}}function nor(e,t,n){return(r,s,o)=>(!n||n(r,s,o))&&e(o[0],t,r,s)}function aj(e,t,n,r){let s;return e.wholeWord&&(s=ror(t.charCategorizer(t.selection.main.head))),e.test&&(s=nor(e.test,t,s)),new wNt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function bq(e,t){return e.slice(Tc(e,t,!1),t)}function xq(e,t){return e.slice(t,Tc(e,t))}function ror(e){return(t,n,r)=>!r[0].length||(e(bq(r.input,r.index))!=ba.Word||e(xq(r.input,r.index))!=ba.Word)&&(e(xq(r.input,r.index+r[0].length))!=ba.Word||e(bq(r.input,r.index+r[0].length))!=ba.Word)}class sor extends ONt{nextMatch(t,n,r){let s=aj(this.spec,t,r,t.doc.length).next();return s.done&&(s=aj(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let o=Math.max(n,r-s*1e4),i=aj(this.spec,t,o,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(o==n||l.from>o+10))return l;if(o==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 o=+r.slice(0,s);if(o>0&&o<t.match.length)return t.match[o]+r.slice(s)}return n})}matchAll(t,n){let r=aj(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 o=aj(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!o.next().done;)s(o.value.from,o.value.to)}}const NL=Sr.define(),aTe=Sr.define(),jS=Vl.define({create(e){return new xse(Hbe(e).create(),null)},update(e,t){for(let n of t.effects)n.is(NL)?e=new xse(n.value.create(),e.panel):n.is(aTe)&&(e=new xse(e.query,n.value?lTe:null));return e},provide:e=>xL.from(e,t=>t.panel)});class xse{constructor(t,n){this.query=t,this.panel=n}}const oor=Ln.mark({class:"cm-searchMatch"}),ior=Ln.mark({class:"cm-searchMatch cm-searchMatch-selected"}),aor=ka.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(jS))}update(e){let t=e.state.field(jS);(t!=e.startState.field(jS)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Ln.none;let{view:n}=this,r=new Wf;for(let s=0,o=n.visibleRanges,i=o.length;s<i;s++){let{from:l,to:c}=o[s];for(;s<i-1&&c>o[s+1].from-500;)c=o[++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?ior:oor)})}return r.finish()}},{decorations:e=>e.decorations});function t5(e){return t=>{let n=t.state.field(jS,!1);return n&&n.query.spec.valid?e(t,n):ENt(t)}}const wq=t5((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=St.single(r.from,r.to),o=e.state.facet(YA);return e.dispatch({selection:s,effects:[cTe(e,r),o.scrollToMatch(s.main,e)],userEvent:"select.search"}),CNt(e),!0}),Sq=t5((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let o=St.single(s.from,s.to),i=e.state.facet(YA);return e.dispatch({selection:o,effects:[cTe(e,s),i.scrollToMatch(o.main,e)],userEvent:"select.search"}),CNt(e),!0}),lor=t5((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:St.create(n.map(r=>St.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),cor=({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,o=[],i=0;for(let l=new mI(e.doc,e.sliceDoc(r,s));!l.next().done;){if(o.length>1e3)return!1;l.value.from==r&&(i=o.length),o.push(St.range(l.value.from,l.value.to))}return t(e.update({selection:St.create(o,i),userEvent:"select.search.matches"})),!0},bqe=t5((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let o=t.nextMatch(n,r,r);if(!o)return!1;let i=o,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(Bt.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=St.single(i.from,i.to).map(f),d.push(cTe(e,i)),d.push(n.facet(YA).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),uor=t5((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:o,to:i,precise:l}=s;l&&n.push({from:o,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:Bt.announce.of(r),userEvent:"input.replace.all"}),!0});function lTe(e){return e.state.facet(YA).createPanel(e)}function Hbe(e,t){var n,r,s,o,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(YA);return new kNt({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:(o=t?.regexp)!==null&&o!==void 0?o:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function _Nt(e){let t=OEe(e,lTe);return t&&t.dom.querySelector("[main-field]")}function CNt(e){let t=_Nt(e);t&&t==e.root.activeElement&&t.select()}const ENt=e=>{let t=e.state.field(jS,!1);if(t&&t.panel){let n=_Nt(e);if(n&&n!=e.root.activeElement){let r=Hbe(e.state,t.query.spec);r.valid&&e.dispatch({effects:NL.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[aTe.of(!0),t?NL.of(Hbe(e.state,t.query.spec)):Sr.appendConfig.of(mor)]});return!0},TNt=e=>{let t=e.state.field(jS,!1);if(!t||!t.panel)return!1;let n=OEe(e,lTe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:aTe.of(!1)}),!0},dor=[{key:"Mod-f",run:ENt,scope:"editor search-panel"},{key:"F3",run:wq,shift:Sq,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:wq,shift:Sq,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:TNt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:cor},{key:"Mod-Alt-g",run:Bsr},{key:"Mod-d",run:Xsr,preventDefault:!0}];class por{constructor(t){this.view=t;let n=this.query=t.state.field(jS).query.spec;this.commit=this.commit.bind(this),this.searchField=fi("input",{value:n.search,placeholder:pp(t,"Find"),"aria-label":pp(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=fi("input",{value:n.replace,placeholder:pp(t,"Replace"),"aria-label":pp(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=fi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=fi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=fi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,o,i){return fi("button",{class:"cm-button",name:s,onclick:o,type:"button"},i)}this.dom=fi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>wq(t),[pp(t,"next")]),r("prev",()=>Sq(t),[pp(t,"previous")]),r("select",()=>lor(t),[pp(t,"all")]),fi("label",null,[this.caseField,pp(t,"match case")]),fi("label",null,[this.reField,pp(t,"regexp")]),fi("label",null,[this.wordField,pp(t,"by word")]),...t.state.readOnly?[]:[fi("br"),this.replaceField,r("replace",()=>bqe(t),[pp(t,"replace")]),r("replaceAll",()=>uor(t),[pp(t,"replace all")])],fi("button",{name:"close",onclick:()=>TNt(t),"aria-label":pp(t,"close"),type:"button"},["×"])])}commit(){let t=new kNt({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:NL.of(t)}))}keydown(t){RKn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?Sq:wq)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),bqe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(NL)&&!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(YA).top}}function pp(e,t){return e.state.phrase(t)}const k9=30,O9=/[\s\.,:;?!]/;function cTe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,o=Math.max(r.from,t-k9),i=Math.min(s,n+k9),l=e.state.sliceDoc(o,i);if(o!=r.from){for(let c=0;c<k9;c++)if(!O9.test(l[c+1])&&O9.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-k9;c--)if(!O9.test(l[c-1])&&O9.test(l[c])){l=l.slice(0,c);break}}return Bt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const hor=Bt.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"}}),mor=[jS,dh.low(aor),hor];class xqe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class _O{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(IL).markerFilter;s&&(t=s(t,r));let o=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Wf,l=[],c=0;for(let d=0;;){let f=d==o.length?null:o[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((y,v)=>Math.min(y,v.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<o.length;){let y=o[d];if(y.from==p&&(y.to>y.from||y.to==p))l.push(y),d++,h=Math.min(y.to,h);else{h=Math.min(y.from,h);break}}let m=Tor(l);if(l.some(y=>y.from==y.to||y.from==y.to-1&&r.doc.lineAt(y.from).to==y.from))i.add(p,p,Ln.widget({widget:new Oor(m),diagnostics:l.slice()}));else{let y=l.reduce((v,b)=>b.markClass?v+" "+b.markClass:v,"");i.add(p,h,Ln.mark({class:"cm-lintRange cm-lintRange-"+m+y,diagnostics:l.slice(),inclusiveEnd:l.some(v=>v.to>h)}))}c=h;for(let y=0;y<l.length;y++)l[y].to<=c&&l.splice(y--,1)}let u=i.finish();return new _O(u,n,gI(u))}}function gI(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,o,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new xqe(s,o,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new xqe(r.from,o,r.diagnostic)}}),r}function gor(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(IL).hideOn(e,n,r);if(s!=null)return s;let o=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(jNt))||e.changes.touchesRange(o.from,Math.max(o.to,r)))}function vor(e,t){return e.field(Mp,!1)?t:t.concat(Sr.appendConfig.of(jor))}const jNt=Sr.define(),uTe=Sr.define(),NNt=Sr.define(),Mp=Vl.define({create(){return new _O(Ln.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 o=t.changes.mapPos(e.selected.from,1);r=gI(n,e.selected.diagnostic,o)||gI(n,null,o)}!n.size&&s&&t.state.facet(IL).autoPanel&&(s=null),e=new _O(n,s,r)}for(let n of t.effects)if(n.is(jNt)){let r=t.state.facet(IL).autoPanel?n.value.length?AL.open:null:e.panel;e=_O.init(n.value,r,t.state)}else n.is(uTe)?e=new _O(e.diagnostics,n.value?AL.open:null,e.selected):n.is(NNt)&&(e=new _O(e.diagnostics,e.panel,n.value));return e},provide:e=>[xL.from(e,t=>t.panel),Bt.decorations.from(e,t=>t.diagnostics)]}),yor=Ln.mark({class:"cm-lintRange cm-lintRange-active"});function bor(e,t,n){let{diagnostics:r}=e.state.field(Mp),s,o=-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,o=c,i=u,!1});let l=e.state.facet(IL).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:o,end:i,above:e.state.doc.lineAt(o).to<i,create(){return{dom:xor(e,s)}}}:null}function xor(e,t){return fi("ul",{class:"cm-tooltip-lint"},t.map(n=>ANt(e,n,!1)))}const wor=e=>{let t=e.state.field(Mp,!1);(!t||!t.panel)&&e.dispatch({effects:vor(e.state,[uTe.of(!0)])});let n=OEe(e,AL.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},wqe=e=>{let t=e.state.field(Mp,!1);return!t||!t.panel?!1:(e.dispatch({effects:uTe.of(!1)}),!0)},Sor=e=>{let t=e.state.field(Mp,!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)},kor=[{key:"Mod-Shift-m",run:wor,preventDefault:!0},{key:"F8",run:Sor}],IL=En.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...vb(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:Sqe,tooltipFilter:Sqe,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,o)=>t(r,s,o)||n(r,s,o):t:n,autoPanel:(t,n)=>t||n})}}});function Sqe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function INt(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(o=>o.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function ANt(e,t,n){var r;let s=n?INt(t.actions):[];return fi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},fi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((o,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=gI(e.state.field(Mp).diagnostics,t);m&&o.apply(e,m.from,m.to)},{name:u}=o,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),fi("u",u.slice(d,d+1)),u.slice(d+1)],p=o.markClass?" "+o.markClass:"";return fi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&fi("div",{class:"cm-diagnosticSource"},t.source))}class Oor extends fh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return fi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class kqe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=ANt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class AL{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)wqe(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:o}=this.items[this.selectedIndex],i=INt(o.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=gI(this.view.state.field(Mp).diagnostics,o);c&&o.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let o=0;o<this.items.length;o++)this.items[o].dom.contains(s.target)&&this.moveSelection(o)};this.list=fi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=fi("div",{class:"cm-panel-lint"},this.list,fi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>wqe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Mp).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(Mp),r=0,s=!1,o=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 kqe(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"),o=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 kqe(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),o?(this.list.setAttribute("aria-activedescendant",o.id),this.view.requestMeasure({key:this,read:()=>({sel:o.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(Mp),r=gI(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:NNt.of(r)})}static open(t){return new AL(t)}}function _or(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 _9(e){return _or(`<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 Cor=Bt.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:_9("#d11")},".cm-lintRange-warning":{backgroundImage:_9("orange")},".cm-lintRange-info":{backgroundImage:_9("#999")},".cm-lintRange-hint":{backgroundImage:_9("#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 Eor(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function Tor(e){let t="hint",n=1;for(let r of e){let s=Eor(r.severity);s>n&&(n=s,t=r.severity)}return t}const jor=[Mp,Bt.decorations.compute([Mp],e=>{let{selected:t,panel:n}=e.field(Mp);return!t||!n||t.from==t.to?Ln.none:Ln.set([yor.range(t.from,t.to)])}),wXn(bor,{hideOn:gor}),Cor];var Oqe=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,o=[];t.closeBracketsKeymap!==!1&&(o=o.concat(ver)),t.defaultKeymap!==!1&&(o=o.concat(Lsr)),t.searchKeymap!==!1&&(o=o.concat(dor)),t.historyKeymap!==!1&&(o=o.concat(Hrr)),t.foldKeymap!==!1&&(o=o.concat(nJn)),t.completionKeymap!==!1&&(o=o.concat(_Tt)),t.lintKeymap!==!1&&(o=o.concat(kor));var i=[];return t.lineNumbers!==!1&&i.push(WEt()),t.highlightActiveLineGutter!==!1&&i.push($Xn()),t.highlightSpecialChars!==!1&&i.push(QKn()),t.history!==!1&&i.push(Mrr()),t.foldGutter!==!1&&i.push(iJn()),t.drawSelection!==!1&&i.push(FKn()),t.dropCursor!==!1&&i.push(qKn()),t.allowMultipleSelections!==!1&&i.push(vs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(GXn()),t.syntaxHighlighting!==!1&&i.push(ZA(uJn,{fallback:!0})),t.bracketMatching!==!1&&i.push(vJn()),t.closeBrackets!==!1&&i.push(per()),t.autocompletion!==!1&&i.push(OTt()),t.rectangularSelection!==!1&&i.push(cXn()),s!==!1&&i.push(fXn()),t.highlightActiveLine!==!1&&i.push(tXn()),t.highlightSelectionMatches!==!1&&i.push(qsr()),t.tabSize&&typeof t.tabSize=="number"&&i.push(WA.of(" ".repeat(t.tabSize))),i.concat([HA.of(o.flat())]).filter(Boolean)};const Nor="#e5c07b",_qe="#e06c75",Ior="#56b6c2",Aor="#ffffff",o7="#abb2bf",Wbe="#7d8799",Ror="#61afef",Por="#98c379",Cqe="#d19a66",$or="#c678dd",Mor="#21252b",Eqe="#2c313a",Tqe="#282c34",wse="#353a42",Dor="#3E4451",jqe="#528bff",Lor=Bt.theme({"&":{color:o7,backgroundColor:Tqe},".cm-content":{caretColor:jqe},".cm-cursor, .cm-dropCursor":{borderLeftColor:jqe},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:Dor},".cm-panels":{backgroundColor:Mor,color:o7},".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:Tqe,color:Wbe,border:"none"},".cm-activeLineGutter":{backgroundColor:Eqe},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:wse},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:wse,borderBottomColor:wse},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Eqe,color:o7}}},{dark:!0}),For=$0.define([{tag:pe.keyword,color:$or},{tag:[pe.name,pe.deleted,pe.character,pe.propertyName,pe.macroName],color:_qe},{tag:[pe.function(pe.variableName),pe.labelName],color:Ror},{tag:[pe.color,pe.constant(pe.name),pe.standard(pe.name)],color:Cqe},{tag:[pe.definition(pe.name),pe.separator],color:o7},{tag:[pe.typeName,pe.className,pe.number,pe.changed,pe.annotation,pe.modifier,pe.self,pe.namespace],color:Nor},{tag:[pe.operator,pe.operatorKeyword,pe.url,pe.escape,pe.regexp,pe.link,pe.special(pe.string)],color:Ior},{tag:[pe.meta,pe.comment],color:Wbe},{tag:pe.strong,fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.link,color:Wbe,textDecoration:"underline"},{tag:pe.heading,fontWeight:"bold",color:_qe},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:Cqe},{tag:[pe.processingInstruction,pe.string,pe.inserted],color:Por},{tag:pe.invalid,color:Aor}]),zor=[Lor,ZA(For)];var Bor=Bt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),Uor=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,o=n.editable,i=o===void 0?!0:o,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,y=[];switch(s&&y.unshift(HA.of([Fsr])),m&&(typeof m=="boolean"?y.unshift(Oqe()):y.unshift(Oqe(m))),p&&y.unshift(oXn(p)),d){case"light":y.push(Bor);break;case"dark":y.push(zor);break;case"none":break;default:y.push(d);break}return i===!1&&y.push(Bt.editable.of(!1)),c&&y.push(vs.readOnly.of(!0)),[...y]},Vor=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 qor{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 Nqe{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 Sse=null,Hor=()=>typeof window>"u"?new Nqe:(Sse||(Sse=new Nqe),Sse),Wor=Bt.theme({"& .cm-scroller":{height:"100% !important"}}),Iqe=null,kse=null;function Zor(e,t,n,r,s,o){if(!e&&!t&&!n&&!r&&!s&&!o)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:o});return i===Iqe||(Iqe=i,kse=Bt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:o}})),kse}var Aqe=gb.define(),Gor=200,Qor=[];function Yor(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,o=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?Qor: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,y=m===void 0?null:m,v=e.maxHeight,b=v===void 0?null:v,x=e.width,w=x===void 0?null:x,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,T=C===void 0?null:C,E=e.placeholder,I=E===void 0?"":E,N=e.editable,A=N===void 0?!0:N,P=e.readOnly,F=P===void 0?!1:P,D=e.indentWithTab,H=D===void 0?!0:D,q=e.basicSetup,V=q===void 0?!0:q,B=e.root,Z=e.initialState,z=g.useState(),Y=z[0],L=z[1],R=g.useState(),M=R[0],U=R[1],Q=g.useState(),te=Q[0],K=Q[1],ee=g.useState(()=>({current:null}))[0],ne=g.useState(()=>({current:null}))[0],le=Zor(h,y,b,w,_,T),J=Bt.updateListener.of(ie=>{if(ie.docChanged&&typeof r=="function"&&!ie.transactions.some(xe=>xe.annotation(Aqe))){ee.current?ee.current.reset():(ee.current=new qor(()=>{if(ne.current){var xe=ne.current;ne.current=null,xe()}ee.current=null},Gor),Hor().add(ee.current));var fe=ie.state.doc,he=fe.toString();r(he,ie)}s&&s(Vor(ie))}),re=Uor({theme:f,editable:A,readOnly:F,placeholder:I,indentWithTab:H,basicSetup:V}),se=[J,...le?[le]:[],Wor,...re];return i&&typeof i=="function"&&se.push(Bt.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(Y&&!te){var ie={doc:t,selection:n,extensions:se},fe=Z?vs.fromJSON(Z.json,ie,Z.fields):vs.create(ie);if(K(fe),!M){var he=new Bt({state:fe,parent:Y,root:B});U(he),o&&o(he,fe)}}return()=>{M&&(K(void 0),U(void 0))}},[Y,te]),g.useEffect(()=>{e.container&&L(e.container)},[e.container]),g.useEffect(()=>()=>{M&&(M.destroy(),U(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[M]),g.useEffect(()=>{u&&M&&M.focus()},[u,M]),g.useEffect(()=>{M&&M.dispatch({effects:Sr.reconfigure.of(se)})},[f,c,h,y,b,w,_,T,I,A,F,H,V,r,i]),g.useEffect(()=>{if(t!==void 0){var ie=M?M.state.doc.toString():"";if(M&&t!==ie){var fe=ee.current&&!ee.current.isDone,he=()=>{M&&t!==M.state.doc.toString()&&M.dispatch({changes:{from:0,to:M.state.doc.toString().length,insert:t||""},annotations:[Aqe.of(!0)]})};fe?ne.current=he:he()}}},[t,M]),{state:te,setState:K,view:M,setView:U,container:Y,setContainer:L}}var Kor=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],d1=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,o=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,y=e.height,v=e.minHeight,b=e.maxHeight,x=e.width,w=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,T=e.indentWithTab,E=e.editable,I=e.readOnly,N=e.root,A=e.initialState,P=zjt(e,Kor),F=g.useRef(null),D=Yor({root:N,value:s,autoFocus:p,theme:m,height:y,minHeight:v,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:T,editable:E,readOnly:I,selection:o,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),H=D.state,q=D.view,V=D.container,B=D.setContainer;g.useImperativeHandle(t,()=>({editor:F.current,state:H,view:q}),[F,V,H,q]);var Z=g.useCallback(Y=>{F.current=Y,B(Y)},[B]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var z=typeof m=="string"?"cm-theme-"+m:"cm-theme";return a.jsx("div",tC({ref:Z,className:""+z+(n?" "+n:"")},P))});d1.displayName="CodeMirror";function Xor(e){return new X_(jEe.define(e))}const Jor=[Ig.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Bo(()=>Promise.resolve().then(()=>w9),[],import.meta.url).then(e=>e.javascript())}}),Ig.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Bo(()=>Promise.resolve().then(()=>jJn),void 0,import.meta.url).then(e=>e.json())}}),Ig.of({name:"JSX",extensions:["jsx"],load(){return Bo(()=>Promise.resolve().then(()=>w9),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),Ig.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Bo(()=>Promise.resolve().then(()=>krr),void 0,import.meta.url).then(e=>e.markdown())}}),Ig.of({name:"TSX",extensions:["tsx"],load(){return Bo(()=>Promise.resolve().then(()=>w9),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 Bo(()=>Promise.resolve().then(()=>w9),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 Bo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>Xor(e.shell))}})];function eir(e,t=5){if(!e?.properties)return[];const n=[];function r(s,o,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:o,label:o,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${o}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${o}[].${c}`,i+1)}for(const[s,o]of Object.entries(e.properties))r(o,s,1);return n}function tir(e){const t=eir(e);return OTt({override:[nir(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function nir(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]??"",o=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 y=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:y},selection:{anchor:f+y.length}})}}));return{from:o,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const rir=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,sir=Ln.mark({class:"cm-variable-highlight"}),Rqe=new DEt({regexp:rir,decoration:()=>sir}),oir=ka.fromClass(class{decorations;constructor(e){this.decorations=Rqe.createDeco(e)}update(e){this.decorations=Rqe.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),iir=oir;function air(){const e=oQ({settings:{fontFamily:"var(--font-mono)",fontSize:"var(--text-body-sm)",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--placeholder)",background:"transparent",foreground:"var(--foreground)",caret:"var(--foreground)"},styles:[{tag:[pe.className,pe.propertyName],color:"var(--foreground)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic",color:"var(--foreground)"},{tag:pe.strong,fontWeight:"bold",color:"var(--foreground)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--foreground)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.quote,fontStyle:"italic",color:"var(--placeholder)"}]}),t=Bt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--foreground)",caretColor:"var(--foreground)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--placeholder)"},".cm-activeLineGutter":{color:"var(--muted-foreground)"},".cm-cursor":{borderLeftColor:"var(--foreground)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--background)",border:"1px solid var(--border)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--foreground)"},".cm-completionDetail":{color:"var(--muted-foreground)",fontSize:"var(--text-caption)",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--background)",border:"1px solid var(--border)",color:"var(--muted-foreground)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--fill-hover)",color:"var(--foreground)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function lir(){const e=Bt.theme({"&":{backgroundColor:"transparent",color:"var(--foreground)",fontSize:"var(--text-body-sm)"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--placeholder)",borderRight:"none"},".cm-content":{color:"var(--foreground)",caretColor:"var(--foreground)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--placeholder)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--muted-foreground)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--foreground)"},"&.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(--background)",border:"1px solid var(--border)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--foreground)"},".cm-completionDetail":{color:"var(--muted-foreground)",fontSize:"var(--text-caption)",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--background)",border:"1px solid var(--border)",color:"var(--muted-foreground)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--fill-hover)",color:"var(--foreground)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=$0.define([{tag:[pe.comment,pe.bracket],color:"var(--placeholder)"},{tag:[pe.string,pe.meta,pe.regexp],color:"var(--accent1)"},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:"var(--accent6)"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"var(--accent2)"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"var(--accent5)"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"var(--accent3)"},{tag:[pe.variableName,pe.number],color:"var(--accent5)"},{tag:[pe.name,pe.quote],color:"var(--accent1)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.emphasis],fontStyle:"italic",color:"var(--foreground)"},{tag:[pe.strong],fontWeight:"bold",color:"var(--foreground)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--foreground)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:[pe.deleted],color:"var(--accent2)"},{tag:pe.invalid,color:"var(--error)"},{tag:[pe.standard(pe.tagName)],color:"var(--accent1)"}]);return[e,ZA(t)]}const n5=()=>{const e=M3().resolvedTheme==="dark";return g.useMemo(()=>e?air():lir(),[e])},cir=rd(W("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","transition-colors duration-normal ease-out-custom"),{variants:{variant:{default:W(nG,"rounded-md p-1",nSt),embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),uir=dh.highest(Bt.editorAttributes.of({style:"outline: none"})),dir=dh.highest(Bt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),fir=[uir,dir],br=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:o="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,id:m,"aria-label":y="Code editor","aria-describedby":v,"aria-invalid":b,...x},w)=>{const k=n5(),_=e?JSON.stringify(e,null,2):t??"",C=g.useMemo(()=>{const T={"aria-label":y};m&&(T.id=m),v&&(T["aria-describedby"]=v),b!==void 0&&(T["aria-invalid"]=String(b));const E=[...fir,Bt.contentAttributes.of(T)];return f&&E.push(Bt.lineWrapping),o==="json"?E.push(qx):o==="markdown"&&E.push(Ljt({base:hI,codeLanguages:Jor})),i&&o==="markdown"&&E.push(iir),c&&o==="markdown"&&E.push(tir(c)),p===!1&&E.push(vs.readOnly.of(!0)),E},[o,i,c,p,f,m,y,v,b]);return a.jsxs("div",{className:W(cir({variant:h}),s),...x,children:[r&&a.jsx(Oo,{content:_,className:"absolute top-2 right-2 z-20"}),a.jsx(d1,{ref:w,value:_,theme:k,extensions:C,onChange:n,editable:p,"aria-label":y,placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),RNt={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 Ose=null;function pir(){return Ose||(Ose=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Bo(()=>import("./core-CaKkm_q3.js"),__vite__mapDeps([0,1,2]),import.meta.url),Bo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Bo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Bo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Bo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Bo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Bo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Bo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Bo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Bo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Bo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Bo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Bo(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Bo(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Bo(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Bo(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Bo(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Bo(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Ose}async function hir(e,t){const n=RNt[t?.toLowerCase()];if(!n)return null;const r=await pir(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function mir(e){const t=e?.split(".").pop()?.toLowerCase();return t?RNt[t]:void 0}const gir=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},vir=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=n5(),{settings:r,setSettings:s}=zG(),o=r?.tracingOptions,i=g.useMemo(()=>gir(o),[o]),[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 a.jsxs("div",{className:"space-y-2 px-5 py-2",children:[a.jsx(je,{as:"h3",variant:"body",tone:"muted",children:"Tracing Options"}),a.jsx(d1,{value:l,onChange:d,theme:n,extensions:[qx],className:W("overflow-hidden overflow-y-scroll rounded-lg bg-card p-3",e)}),a.jsx("div",{className:"flex items-center justify-end",children:a.jsx(ae,{icon:a.jsx(Vn,{}),type:"button",onClick:f,children:"Save"})})]})},yir=({resourceId:e,onResourceIdChange:t})=>{const[n,r]=g.useState(!1);return a.jsxs(a.Fragment,{children:[a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx(ae,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>r(!0),children:a.jsx(_t,{children:a.jsx(g_e,{})})})}),a.jsx(kn,{children:"Run Options"})]}),a.jsx(hs,{open:n,onOpenChange:r,children:a.jsxs(rs,{children:[a.jsxs(ss,{children:[a.jsx(Jr,{children:"Run Options"}),a.jsx(Ms,{children:"Configure resource attribution, tracing and debug options for this workflow run"})]}),a.jsxs(ys,{children:[a.jsx("div",{className:"px-5 py-2",children:a.jsx(qi,{name:"workflow-run-resource-id",label:"Resource ID",value:e,onChange:s=>t(s.target.value),placeholder:"e.g. tenant-42",helpText:"Ignored when server auth derives the resource ID from the user."})}),a.jsx(vir,{onSaved:()=>r(!1)})]})]})})]})};function ql(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=ql(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var bir={value:()=>{}};function uQ(){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 i7(n)}function i7(e){this._=e}function xir(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}})}i7.prototype=uQ.prototype={constructor:i7,on:function(e,t){var n=this._,r=xir(e+"",n),s,o=-1,i=r.length;if(arguments.length<2){for(;++o<i;)if((s=(e=r[o]).type)&&(s=wir(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<i;)if(s=(e=r[o]).type)n[s]=Pqe(n[s],e.name,t);else if(t==null)for(s in n)n[s]=Pqe(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 i7(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,o;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],r=0,s=o.length;r<s;++r)o[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,o=r.length;s<o;++s)r[s].value.apply(t,n)}};function wir(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function Pqe(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=bir,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Zbe="http://www.w3.org/1999/xhtml";const $qe={svg:"http://www.w3.org/2000/svg",xhtml:Zbe,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function dQ(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),$qe.hasOwnProperty(t)?{space:$qe[t],local:e}:e}function Sir(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Zbe&&t.documentElement.namespaceURI===Zbe?t.createElement(e):t.createElementNS(n,e)}}function kir(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function PNt(e){var t=dQ(e);return(t.local?kir:Sir)(t)}function Oir(){}function dTe(e){return e==null?Oir:function(){return this.querySelector(e)}}function _ir(e){typeof e!="function"&&(e=dTe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=o[d])&&(u=e.call(c,c.__data__,d,o))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Jp(r,this._parents)}function Cir(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function Eir(){return[]}function $Nt(e){return e==null?Eir:function(){return this.querySelectorAll(e)}}function Tir(e){return function(){return Cir(e.apply(this,arguments))}}function jir(e){typeof e=="function"?e=Tir(e):e=$Nt(e);for(var t=this._groups,n=t.length,r=[],s=[],o=0;o<n;++o)for(var i=t[o],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 Jp(r,s)}function MNt(e){return function(){return this.matches(e)}}function DNt(e){return function(t){return t.matches(e)}}var Nir=Array.prototype.find;function Iir(e){return function(){return Nir.call(this.children,e)}}function Air(){return this.firstElementChild}function Rir(e){return this.select(e==null?Air:Iir(typeof e=="function"?e:DNt(e)))}var Pir=Array.prototype.filter;function $ir(){return Array.from(this.children)}function Mir(e){return function(){return Pir.call(this.children,e)}}function Dir(e){return this.selectAll(e==null?$ir:Mir(typeof e=="function"?e:DNt(e)))}function Lir(e){typeof e!="function"&&(e=MNt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,l=r[s]=[],c,u=0;u<i;++u)(c=o[u])&&e.call(c,c.__data__,u,o)&&l.push(c);return new Jp(r,this._parents)}function LNt(e){return new Array(e.length)}function Fir(){return new Jp(this._enter||this._groups.map(LNt),this._parents)}function kq(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}kq.prototype={constructor:kq,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 zir(e){return function(){return e}}function Bir(e,t,n,r,s,o){for(var i=0,l,c=t.length,u=o.length;i<u;++i)(l=t[i])?(l.__data__=o[i],r[i]=l):n[i]=new kq(e,o[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function Uir(e,t,n,r,s,o,i){var l,c,u=new Map,d=t.length,f=o.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,o[l],l,o)+"",(c=u.get(h))?(r[l]=c,c.__data__=o[l],u.delete(h)):n[l]=new kq(e,o[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function Vir(e){return e.__data__}function qir(e,t){if(!arguments.length)return Array.from(this,Vir);var n=t?Uir:Bir,r=this._parents,s=this._groups;typeof e!="function"&&(e=zir(e));for(var o=s.length,i=new Array(o),l=new Array(o),c=new Array(o),u=0;u<o;++u){var d=r[u],f=s[u],p=f.length,h=Hir(e.call(d,d&&d.__data__,u,r)),m=h.length,y=l[u]=new Array(m),v=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,y,v,b,h,t);for(var x=0,w=0,k,_;x<m;++x)if(k=y[x]){for(x>=w&&(w=x+1);!(_=v[w])&&++w<m;);k._next=_||null}}return i=new Jp(i,r),i._enter=l,i._exit=c,i}function Hir(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Wir(){return new Jp(this._exit||this._groups.map(LNt),this._parents)}function Zir(e,t,n){var r=this.enter(),s=this,o=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?o.remove():n(o),r&&s?r.merge(s).order():s}function Gir(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,o=r.length,i=Math.min(s,o),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 Jp(l,this._parents)}function Qir(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,o=r[s],i;--s>=0;)(i=r[s])&&(o&&i.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(i,o),o=i);return this}function Yir(e){e||(e=Kir);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),o=0;o<r;++o){for(var i=n[o],l=i.length,c=s[o]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Jp(s,this._parents).order()}function Kir(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Xir(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Jir(){return Array.from(this)}function ear(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,o=r.length;s<o;++s){var i=r[s];if(i)return i}return null}function tar(){let e=0;for(const t of this)++e;return e}function nar(){return!this.node()}function rar(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],o=0,i=s.length,l;o<i;++o)(l=s[o])&&e.call(l,l.__data__,o,s);return this}function sar(e){return function(){this.removeAttribute(e)}}function oar(e){return function(){this.removeAttributeNS(e.space,e.local)}}function iar(e,t){return function(){this.setAttribute(e,t)}}function aar(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function lar(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function car(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 uar(e,t){var n=dQ(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?oar:sar:typeof t=="function"?n.local?car:lar:n.local?aar:iar)(n,t))}function FNt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function dar(e){return function(){this.style.removeProperty(e)}}function far(e,t,n){return function(){this.style.setProperty(e,t,n)}}function par(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function har(e,t,n){return arguments.length>1?this.each((t==null?dar:typeof t=="function"?par:far)(e,t,n??"")):vI(this.node(),e)}function vI(e,t){return e.style.getPropertyValue(t)||FNt(e).getComputedStyle(e,null).getPropertyValue(t)}function mar(e){return function(){delete this[e]}}function gar(e,t){return function(){this[e]=t}}function yar(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function bar(e,t){return arguments.length>1?this.each((t==null?mar:typeof t=="function"?yar:gar)(e,t)):this.node()[e]}function zNt(e){return e.trim().split(/^|\s+/)}function fTe(e){return e.classList||new BNt(e)}function BNt(e){this._node=e,this._names=zNt(e.getAttribute("class")||"")}BNt.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 UNt(e,t){for(var n=fTe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function VNt(e,t){for(var n=fTe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function xar(e){return function(){UNt(this,e)}}function war(e){return function(){VNt(this,e)}}function Sar(e,t){return function(){(t.apply(this,arguments)?UNt:VNt)(this,e)}}function kar(e,t){var n=zNt(e+"");if(arguments.length<2){for(var r=fTe(this.node()),s=-1,o=n.length;++s<o;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?Sar:t?xar:war)(n,t))}function Oar(){this.textContent=""}function _ar(e){return function(){this.textContent=e}}function Car(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function Ear(e){return arguments.length?this.each(e==null?Oar:(typeof e=="function"?Car:_ar)(e)):this.node().textContent}function Tar(){this.innerHTML=""}function jar(e){return function(){this.innerHTML=e}}function Nar(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function Iar(e){return arguments.length?this.each(e==null?Tar:(typeof e=="function"?Nar:jar)(e)):this.node().innerHTML}function Aar(){this.nextSibling&&this.parentNode.appendChild(this)}function Rar(){return this.each(Aar)}function Par(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function $ar(){return this.each(Par)}function Mar(e){var t=typeof e=="function"?e:PNt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function Dar(){return null}function Lar(e,t){var n=typeof e=="function"?e:PNt(e),r=t==null?Dar:typeof t=="function"?t:dTe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function Far(){var e=this.parentNode;e&&e.removeChild(this)}function zar(){return this.each(Far)}function Bar(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Uar(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function Var(e){return this.select(e?Uar:Bar)}function qar(e){return arguments.length?this.property("__data__",e):this.node().__data__}function Har(e){return function(t){e.call(this,t,this.__data__)}}function War(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 Zar(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,o;n<s;++n)o=t[n],(!e.type||o.type===e.type)&&o.name===e.name?this.removeEventListener(o.type,o.listener,o.options):t[++r]=o;++r?t.length=r:delete this.__on}}}function Gar(e,t,n){return function(){var r=this.__on,s,o=Har(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=o,s.options=n),s.value=t;return}}this.addEventListener(e.type,o,n),s={type:e.type,name:e.name,value:t,listener:o,options:n},r?r.push(s):this.__on=[s]}}function Qar(e,t,n){var r=War(e+""),s,o=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<o;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?Gar:Zar,s=0;s<o;++s)this.each(l(r[s],t,n));return this}function qNt(e,t,n){var r=FNt(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 Yar(e,t){return function(){return qNt(this,e,t)}}function Kar(e,t){return function(){return qNt(this,e,t.apply(this,arguments))}}function Xar(e,t){return this.each((typeof t=="function"?Kar:Yar)(e,t))}function*Jar(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,o=r.length,i;s<o;++s)(i=r[s])&&(yield i)}var HNt=[null];function Jp(e,t){this._groups=e,this._parents=t}function r5(){return new Jp([[document.documentElement]],HNt)}function elr(){return this}Jp.prototype=r5.prototype={constructor:Jp,select:_ir,selectAll:jir,selectChild:Rir,selectChildren:Dir,filter:Lir,data:qir,enter:Fir,exit:Wir,join:Zir,merge:Gir,selection:elr,order:Qir,sort:Yir,call:Xir,nodes:Jir,node:ear,size:tar,empty:nar,each:rar,attr:uar,style:har,property:bar,classed:kar,text:Ear,html:Iar,raise:Rar,lower:$ar,append:Mar,insert:Lar,remove:zar,clone:Var,datum:qar,on:Qar,dispatch:Xar,[Symbol.iterator]:Jar};function Np(e){return typeof e=="string"?new Jp([[document.querySelector(e)]],[document.documentElement]):new Jp([[e]],HNt)}function tlr(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Ag(e,t){if(e=tlr(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 nlr={passive:!1},RL={capture:!0,passive:!1};function _se(e){e.stopImmediatePropagation()}function cN(e){e.preventDefault(),e.stopImmediatePropagation()}function WNt(e){var t=e.document.documentElement,n=Np(e).on("dragstart.drag",cN,RL);"onselectstart"in t?n.on("selectstart.drag",cN,RL):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function ZNt(e,t){var n=e.document.documentElement,r=Np(e).on("dragstart.drag",null);t&&(r.on("click.drag",cN,RL),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 C9=e=>()=>e;function Gbe(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:o,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:o,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}})}Gbe.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function rlr(e){return!e.ctrlKey&&!e.button}function slr(){return this.parentNode}function olr(e,t){return t??{x:e.x,y:e.y}}function ilr(){return navigator.maxTouchPoints||"ontouchstart"in this}function GNt(){var e=rlr,t=slr,n=olr,r=ilr,s={},o=uQ("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",v).on("touchmove.drag",b,nlr).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=w(this,t.call(this,k,_),k,_,"mouse");C&&(Np(k.view).on("mousemove.drag",m,RL).on("mouseup.drag",y,RL),WNt(k.view),_se(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(cN(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function y(k){Np(k.view).on("mousemove.drag mouseup.drag",null),ZNt(k.view,u),cN(k),s.mouse("end",k)}function v(k,_){if(e.call(this,k,_)){var C=k.changedTouches,T=t.call(this,k,_),E=C.length,I,N;for(I=0;I<E;++I)(N=w(this,T,k,_,C[I].identifier,C[I]))&&(_se(k),N("start",k,C[I]))}}function b(k){var _=k.changedTouches,C=_.length,T,E;for(T=0;T<C;++T)(E=s[_[T].identifier])&&(cN(k),E("drag",k,_[T]))}function x(k){var _=k.changedTouches,C=_.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<C;++T)(E=s[_[T].identifier])&&(_se(k),E("end",k,_[T]))}function w(k,_,C,T,E,I){var N=o.copy(),A=Ag(I||C,_),P,F,D;if((D=n.call(k,new Gbe("beforestart",{sourceEvent:C,target:p,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:N}),T))!=null)return P=D.x-A[0]||0,F=D.y-A[1]||0,function H(q,V,B){var Z=A,z;switch(q){case"start":s[E]=H,z=i++;break;case"end":delete s[E],--i;case"drag":A=Ag(B||V,_),z=i;break}N.call(q,k,new Gbe(q,{sourceEvent:V,subject:D,target:p,identifier:E,active:z,x:A[0]+P,y:A[1]+F,dx:A[0]-Z[0],dy:A[1]-Z[1],dispatch:N}),T)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:C9(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:C9(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:C9(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:C9(!!k),p):r},p.on=function(){var k=o.on.apply(o,arguments);return k===o?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function pTe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function QNt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function s5(){}var PL=.7,Oq=1/PL,uN="\\s*([+-]?\\d+)\\s*",$L="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",$y="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",alr=/^#([0-9a-f]{3,8})$/,llr=new RegExp(`^rgb\\(${uN},${uN},${uN}\\)$`),clr=new RegExp(`^rgb\\(${$y},${$y},${$y}\\)$`),ulr=new RegExp(`^rgba\\(${uN},${uN},${uN},${$L}\\)$`),dlr=new RegExp(`^rgba\\(${$y},${$y},${$y},${$L}\\)$`),flr=new RegExp(`^hsl\\(${$L},${$y},${$y}\\)$`),plr=new RegExp(`^hsla\\(${$L},${$y},${$y},${$L}\\)$`),Mqe={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};pTe(s5,nC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Dqe,formatHex:Dqe,formatHex8:hlr,formatHsl:mlr,formatRgb:Lqe,toString:Lqe});function Dqe(){return this.rgb().formatHex()}function hlr(){return this.rgb().formatHex8()}function mlr(){return YNt(this).formatHsl()}function Lqe(){return this.rgb().formatRgb()}function nC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=alr.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Fqe(t):n===3?new Pf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?E9(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?E9(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=llr.exec(e))?new Pf(t[1],t[2],t[3],1):(t=clr.exec(e))?new Pf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=ulr.exec(e))?E9(t[1],t[2],t[3],t[4]):(t=dlr.exec(e))?E9(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=flr.exec(e))?Uqe(t[1],t[2]/100,t[3]/100,1):(t=plr.exec(e))?Uqe(t[1],t[2]/100,t[3]/100,t[4]):Mqe.hasOwnProperty(e)?Fqe(Mqe[e]):e==="transparent"?new Pf(NaN,NaN,NaN,0):null}function Fqe(e){return new Pf(e>>16&255,e>>8&255,e&255,1)}function E9(e,t,n,r){return r<=0&&(e=t=n=NaN),new Pf(e,t,n,r)}function glr(e){return e instanceof s5||(e=nC(e)),e?(e=e.rgb(),new Pf(e.r,e.g,e.b,e.opacity)):new Pf}function Qbe(e,t,n,r){return arguments.length===1?glr(e):new Pf(e,t,n,r??1)}function Pf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}pTe(Pf,Qbe,QNt(s5,{brighter(e){return e=e==null?Oq:Math.pow(Oq,e),new Pf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?PL:Math.pow(PL,e),new Pf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Pf(i_(this.r),i_(this.g),i_(this.b),_q(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:zqe,formatHex:zqe,formatHex8:vlr,formatRgb:Bqe,toString:Bqe}));function zqe(){return`#${LO(this.r)}${LO(this.g)}${LO(this.b)}`}function vlr(){return`#${LO(this.r)}${LO(this.g)}${LO(this.b)}${LO((isNaN(this.opacity)?1:this.opacity)*255)}`}function Bqe(){const e=_q(this.opacity);return`${e===1?"rgb(":"rgba("}${i_(this.r)}, ${i_(this.g)}, ${i_(this.b)}${e===1?")":`, ${e})`}`}function _q(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function i_(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function LO(e){return e=i_(e),(e<16?"0":"")+e.toString(16)}function Uqe(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Lg(e,t,n,r)}function YNt(e){if(e instanceof Lg)return new Lg(e.h,e.s,e.l,e.opacity);if(e instanceof s5||(e=nC(e)),!e)return new Lg;if(e instanceof Lg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),o=Math.max(t,n,r),i=NaN,l=o-s,c=(o+s)/2;return l?(t===o?i=(n-r)/l+(n<r)*6:n===o?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?o+s:2-o-s,i*=60):l=c>0&&c<1?0:i,new Lg(i,l,c,e.opacity)}function ylr(e,t,n,r){return arguments.length===1?YNt(e):new Lg(e,t,n,r??1)}function Lg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}pTe(Lg,ylr,QNt(s5,{brighter(e){return e=e==null?Oq:Math.pow(Oq,e),new Lg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?PL:Math.pow(PL,e),new Lg(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 Pf(Cse(e>=240?e-240:e+120,s,r),Cse(e,s,r),Cse(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Lg(Vqe(this.h),T9(this.s),T9(this.l),_q(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=_q(this.opacity);return`${e===1?"hsl(":"hsla("}${Vqe(this.h)}, ${T9(this.s)*100}%, ${T9(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Vqe(e){return e=(e||0)%360,e<0?e+360:e}function T9(e){return Math.max(0,Math.min(1,e||0))}function Cse(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 hTe=e=>()=>e;function blr(e,t){return function(n){return e+n*t}}function xlr(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 wlr(e){return(e=+e)==1?KNt:function(t,n){return n-t?xlr(t,n,e):hTe(isNaN(t)?n:t)}}function KNt(e,t){var n=t-e;return n?blr(e,n):hTe(isNaN(e)?t:e)}const Cq=(function e(t){var n=wlr(t);function r(s,o){var i=n((s=Qbe(s)).r,(o=Qbe(o)).r),l=n(s.g,o.g),c=n(s.b,o.b),u=KNt(s.opacity,o.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 Slr(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(o){for(s=0;s<n;++s)r[s]=e[s]*(1-o)+t[s]*o;return r}}function klr(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Olr(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),o=new Array(n),i;for(i=0;i<r;++i)s[i]=Hx(e[i],t[i]);for(;i<n;++i)o[i]=t[i];return function(l){for(i=0;i<r;++i)o[i]=s[i](l);return o}}function _lr(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Pg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function Clr(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]=Hx(e[s],t[s]):r[s]=t[s];return function(o){for(s in n)r[s]=n[s](o);return r}}var Ybe=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ese=new RegExp(Ybe.source,"g");function Elr(e){return function(){return e}}function Tlr(e){return function(t){return e(t)+""}}function XNt(e,t){var n=Ybe.lastIndex=Ese.lastIndex=0,r,s,o,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Ybe.exec(e))&&(s=Ese.exec(t));)(o=s.index)>n&&(o=t.slice(n,o),l[i]?l[i]+=o:l[++i]=o),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:Pg(r,s)})),n=Ese.lastIndex;return n<t.length&&(o=t.slice(n),l[i]?l[i]+=o:l[++i]=o),l.length<2?c[0]?Tlr(c[0].x):Elr(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 Hx(e,t){var n=typeof t,r;return t==null||n==="boolean"?hTe(t):(n==="number"?Pg:n==="string"?(r=nC(t))?(t=r,Cq):XNt:t instanceof nC?Cq:t instanceof Date?_lr:klr(t)?Slr:Array.isArray(t)?Olr:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?Clr:Pg)(e,t)}function mTe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var qqe=180/Math.PI,Kbe={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function JNt(e,t,n,r,s,o){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:o,rotate:Math.atan2(t,e)*qqe,skewX:Math.atan(c)*qqe,scaleX:i,scaleY:l}}var j9;function jlr(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Kbe:JNt(t.a,t.b,t.c,t.d,t.e,t.f)}function Nlr(e){return e==null||(j9||(j9=document.createElementNS("http://www.w3.org/2000/svg","g")),j9.setAttribute("transform",e),!(e=j9.transform.baseVal.consolidate()))?Kbe:(e=e.matrix,JNt(e.a,e.b,e.c,e.d,e.e,e.f))}function eIt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function o(u,d,f,p,h,m){if(u!==f||d!==p){var y=h.push("translate(",null,t,null,n);m.push({i:y-4,x:Pg(u,f)},{i:y-2,x:Pg(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:Pg(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:Pg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var y=h.push(s(h)+"scale(",null,",",null,")");m.push({i:y-4,x:Pg(u,f)},{i:y-2,x:Pg(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),o(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,y=p.length,v;++m<y;)f[(v=p[m]).i]=v.x(h);return f.join("")}}}var Ilr=eIt(jlr,"px, ","px)","deg)"),Alr=eIt(Nlr,", ",")",")"),Rlr=1e-12;function Hqe(e){return((e=Math.exp(e))+1/e)/2}function Plr(e){return((e=Math.exp(e))-1/e)/2}function $lr(e){return((e=Math.exp(2*e))-1)/(e+1)}const a7=(function e(t,n,r){function s(o,i){var l=o[0],c=o[1],u=o[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,y=h*h+m*m,v,b;if(y<Rlr)b=Math.log(p/u)/t,v=function(T){return[l+T*h,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(y),w=(p*p-u*u+r*y)/(2*u*n*x),k=(p*p-u*u-r*y)/(2*p*n*x),_=Math.log(Math.sqrt(w*w+1)-w),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,v=function(T){var E=T*b,I=Hqe(_),N=u/(n*x)*(I*$lr(t*E+_)-Plr(_));return[l+N*h,c+N*m,u*I/Hqe(t*E+_)]}}return v.duration=b*1e3*t/Math.SQRT2,v}return s.rho=function(o){var i=Math.max(.001,+o),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function Mlr(e,t){t===void 0&&(t=e,e=Hx);for(var n=0,r=t.length-1,s=t[0],o=new Array(r<0?0:r);n<r;)o[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return o[l](i-l)}}var yI=0,zM=0,u$=0,tIt=1e3,Eq,BM,Tq=0,rC=0,fQ=0,ML=typeof performance=="object"&&performance.now?performance:Date,nIt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function gTe(){return rC||(nIt(Dlr),rC=ML.now()+fQ)}function Dlr(){rC=0}function jq(){this._call=this._time=this._next=null}jq.prototype=rIt.prototype={constructor:jq,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?gTe():+n)+(t==null?0:+t),!this._next&&BM!==this&&(BM?BM._next=this:Eq=this,BM=this),this._call=e,this._time=n,Xbe()},stop:function(){this._call&&(this._call=null,this._time=1/0,Xbe())}};function rIt(e,t,n){var r=new jq;return r.restart(e,t,n),r}function Llr(){gTe(),++yI;for(var e=Eq,t;e;)(t=rC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--yI}function Wqe(){rC=(Tq=ML.now())+fQ,yI=zM=0;try{Llr()}finally{yI=0,zlr(),rC=0}}function Flr(){var e=ML.now(),t=e-Tq;t>tIt&&(fQ-=t,Tq=e)}function zlr(){for(var e,t=Eq,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:Eq=n);BM=e,Xbe(r)}function Xbe(e){if(!yI){zM&&(zM=clearTimeout(zM));var t=e-rC;t>24?(e<1/0&&(zM=setTimeout(Wqe,e-ML.now()-fQ)),u$&&(u$=clearInterval(u$))):(u$||(Tq=ML.now(),u$=setInterval(Flr,tIt)),yI=1,nIt(Wqe))}}function Zqe(e,t,n){var r=new jq;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var Blr=uQ("start","end","cancel","interrupt"),Ulr=[],sIt=0,Gqe=1,Jbe=2,l7=3,Qqe=4,exe=5,c7=6;function pQ(e,t,n,r,s,o){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;Vlr(e,n,{name:t,index:r,group:s,on:Blr,tween:Ulr,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:sIt})}function vTe(e,t){var n=xv(e,t);if(n.state>sIt)throw new Error("too late; already scheduled");return n}function yb(e,t){var n=xv(e,t);if(n.state>l7)throw new Error("too late; already running");return n}function xv(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function Vlr(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=rIt(o,0,n.time);function o(u){n.state=Gqe,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!==Gqe)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===l7)return Zqe(i);h.state===Qqe?(h.state=c7,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=c7,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(Zqe(function(){n.state===l7&&(n.state=Qqe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Jbe,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Jbe){for(n.state=l7,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=exe,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===exe&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=c7,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function u7(e,t){var n=e.__transition,r,s,o=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){o=!1;continue}s=r.state>Jbe&&r.state<exe,r.state=c7,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}o&&delete e.__transition}}function qlr(e){return this.each(function(){u7(this,e)})}function Hlr(e,t){var n,r;return function(){var s=yb(this,e),o=s.tween;if(o!==n){r=n=o;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 Wlr(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var o=yb(this,e),i=o.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)}o.tween=s}}function Zlr(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=xv(this.node(),n).tween,s=0,o=r.length,i;s<o;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?Hlr:Wlr)(n,e,t))}function yTe(e,t,n){var r=e._id;return e.each(function(){var s=yb(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return xv(s,r).value[t]}}function oIt(e,t){var n;return(typeof t=="number"?Pg:t instanceof nC?Cq:(n=nC(t))?(t=n,Cq):XNt)(e,t)}function Glr(e){return function(){this.removeAttribute(e)}}function Qlr(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Ylr(e,t,n){var r,s=n+"",o;return function(){var i=this.getAttribute(e);return i===s?null:i===r?o:o=t(r=i,n)}}function Klr(e,t,n){var r,s=n+"",o;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?o:o=t(r=i,n)}}function Xlr(e,t,n){var r,s,o;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?o:(s=c,o=t(r=i,l)))}}function Jlr(e,t,n){var r,s,o;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?o:(s=c,o=t(r=i,l)))}}function ecr(e,t){var n=dQ(e),r=n==="transform"?Alr:oIt;return this.attrTween(e,typeof t=="function"?(n.local?Jlr:Xlr)(n,r,yTe(this,"attr."+e,t)):t==null?(n.local?Qlr:Glr)(n):(n.local?Klr:Ylr)(n,r,t))}function tcr(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function ncr(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function rcr(e,t){var n,r;function s(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&ncr(e,o)),n}return s._value=t,s}function scr(e,t){var n,r;function s(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&tcr(e,o)),n}return s._value=t,s}function ocr(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=dQ(e);return this.tween(n,(r.local?rcr:scr)(r,t))}function icr(e,t){return function(){vTe(this,e).delay=+t.apply(this,arguments)}}function acr(e,t){return t=+t,function(){vTe(this,e).delay=t}}function lcr(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?icr:acr)(t,e)):xv(this.node(),t).delay}function ccr(e,t){return function(){yb(this,e).duration=+t.apply(this,arguments)}}function ucr(e,t){return t=+t,function(){yb(this,e).duration=t}}function dcr(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?ccr:ucr)(t,e)):xv(this.node(),t).duration}function fcr(e,t){if(typeof t!="function")throw new Error;return function(){yb(this,e).ease=t}}function pcr(e){var t=this._id;return arguments.length?this.each(fcr(t,e)):xv(this.node(),t).ease}function hcr(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;yb(this,e).ease=n}}function mcr(e){if(typeof e!="function")throw new Error;return this.each(hcr(this._id,e))}function gcr(e){typeof e!="function"&&(e=MNt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var o=t[s],i=o.length,l=r[s]=[],c,u=0;u<i;++u)(c=o[u])&&e.call(c,c.__data__,u,o)&&l.push(c);return new u0(r,this._parents,this._name,this._id)}function vcr(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,o=Math.min(r,s),i=new Array(r),l=0;l<o;++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 u0(i,this._parents,this._name,this._id)}function ycr(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 bcr(e,t,n){var r,s,o=ycr(t)?vTe:yb;return function(){var i=o(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function xcr(e,t){var n=this._id;return arguments.length<2?xv(this.node(),n).on.on(e):this.each(bcr(n,e,t))}function wcr(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Scr(){return this.on("end.remove",wcr(this._id))}function kcr(e){var t=this._name,n=this._id;typeof e!="function"&&(e=dTe(e));for(var r=this._groups,s=r.length,o=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=o[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,pQ(u[p],t,n,p,u,xv(d,n)));return new u0(o,this._parents,t,n)}function Ocr(e){var t=this._name,n=this._id;typeof e!="function"&&(e=$Nt(e));for(var r=this._groups,s=r.length,o=[],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=xv(d,n),y=0,v=p.length;y<v;++y)(h=p[y])&&pQ(h,t,n,y,p,m);o.push(p),i.push(d)}return new u0(o,i,t,n)}var _cr=r5.prototype.constructor;function Ccr(){return new _cr(this._groups,this._parents)}function Ecr(e,t){var n,r,s;return function(){var o=vI(this,e),i=(this.style.removeProperty(e),vI(this,e));return o===i?null:o===n&&i===r?s:s=t(n=o,r=i)}}function iIt(e){return function(){this.style.removeProperty(e)}}function Tcr(e,t,n){var r,s=n+"",o;return function(){var i=vI(this,e);return i===s?null:i===r?o:o=t(r=i,n)}}function jcr(e,t,n){var r,s,o;return function(){var i=vI(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),vI(this,e))),i===c?null:i===r&&c===s?o:(s=c,o=t(r=i,l))}}function Ncr(e,t){var n,r,s,o="style."+t,i="end."+o,l;return function(){var c=yb(this,e),u=c.on,d=c.value[o]==null?l||(l=iIt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function Icr(e,t,n){var r=(e+="")=="transform"?Ilr:oIt;return t==null?this.styleTween(e,Ecr(e,r)).on("end.style."+e,iIt(e)):typeof t=="function"?this.styleTween(e,jcr(e,r,yTe(this,"style."+e,t))).each(Ncr(this._id,e)):this.styleTween(e,Tcr(e,r,t),n).on("end.style."+e,null)}function Acr(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function Rcr(e,t,n){var r,s;function o(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&Acr(e,i,n)),r}return o._value=t,o}function Pcr(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,Rcr(e,t,n??""))}function $cr(e){return function(){this.textContent=e}}function Mcr(e){return function(){var t=e(this);this.textContent=t??""}}function Dcr(e){return this.tween("text",typeof e=="function"?Mcr(yTe(this,"text",e)):$cr(e==null?"":e+""))}function Lcr(e){return function(t){this.textContent=e.call(this,t)}}function Fcr(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&Lcr(s)),t}return r._value=e,r}function zcr(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,Fcr(e))}function Bcr(){for(var e=this._name,t=this._id,n=aIt(),r=this._groups,s=r.length,o=0;o<s;++o)for(var i=r[o],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=xv(c,t);pQ(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new u0(r,this._parents,e,n)}function Ucr(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(o,i){var l={value:i},c={value:function(){--s===0&&o()}};n.each(function(){var u=yb(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&&o()})}var Vcr=0;function u0(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function aIt(){return++Vcr}var Gb=r5.prototype;u0.prototype={constructor:u0,select:kcr,selectAll:Ocr,selectChild:Gb.selectChild,selectChildren:Gb.selectChildren,filter:gcr,merge:vcr,selection:Ccr,transition:Bcr,call:Gb.call,nodes:Gb.nodes,node:Gb.node,size:Gb.size,empty:Gb.empty,each:Gb.each,on:xcr,attr:ecr,attrTween:ocr,style:Icr,styleTween:Pcr,text:Dcr,textTween:zcr,remove:Scr,tween:Zlr,delay:lcr,duration:dcr,ease:pcr,easeVarying:mcr,end:Ucr,[Symbol.iterator]:Gb[Symbol.iterator]};function qcr(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Hcr={time:null,delay:0,duration:250,ease:qcr};function Wcr(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 Zcr(e){var t,n;e instanceof u0?(t=e._id,e=e._name):(t=aIt(),(n=Hcr).time=gTe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,o=0;o<s;++o)for(var i=r[o],l=i.length,c,u=0;u<l;++u)(c=i[u])&&pQ(c,e,t,u,i,n||Wcr(c,t));return new u0(r,this._parents,e,t)}r5.prototype.interrupt=qlr;r5.prototype.transition=Zcr;const N9=e=>()=>e;function Gcr(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 Ex(e,t,n){this.k=e,this.x=t,this.y=n}Ex.prototype={constructor:Ex,scale:function(e){return e===1?this:new Ex(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Ex(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 hQ=new Ex(1,0,0);lIt.prototype=Ex.prototype;function lIt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return hQ;return e.__zoom}function Tse(e){e.stopImmediatePropagation()}function d$(e){e.preventDefault(),e.stopImmediatePropagation()}function Qcr(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Ycr(){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 Yqe(){return this.__zoom||hQ}function Kcr(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Xcr(){return navigator.maxTouchPoints||"ontouchstart"in this}function Jcr(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],o=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>o?(o+i)/2:Math.min(0,o)||Math.max(0,i))}function cIt(){var e=Qcr,t=Ycr,n=Jcr,r=Kcr,s=Xcr,o=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=a7,u=uQ("start","zoom","end"),d,f,p,h=500,m=150,y=0,v=10;function b(D){D.property("__zoom",Yqe).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",I).on("dblclick.zoom",N).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,H,q,V){var B=D.selection?D.selection():D;B.property("__zoom",Yqe),D!==B?_(D,H,q,V):B.interrupt().each(function(){C(this,arguments).event(V).start().zoom(null,typeof H=="function"?H.apply(this,arguments):H).end()})},b.scaleBy=function(D,H,q,V){b.scaleTo(D,function(){var B=this.__zoom.k,Z=typeof H=="function"?H.apply(this,arguments):H;return B*Z},q,V)},b.scaleTo=function(D,H,q,V){b.transform(D,function(){var B=t.apply(this,arguments),Z=this.__zoom,z=q==null?k(B):typeof q=="function"?q.apply(this,arguments):q,Y=Z.invert(z),L=typeof H=="function"?H.apply(this,arguments):H;return n(w(x(Z,L),z,Y),B,i)},q,V)},b.translateBy=function(D,H,q,V){b.transform(D,function(){return n(this.__zoom.translate(typeof H=="function"?H.apply(this,arguments):H,typeof q=="function"?q.apply(this,arguments):q),t.apply(this,arguments),i)},null,V)},b.translateTo=function(D,H,q,V,B){b.transform(D,function(){var Z=t.apply(this,arguments),z=this.__zoom,Y=V==null?k(Z):typeof V=="function"?V.apply(this,arguments):V;return n(hQ.translate(Y[0],Y[1]).scale(z.k).translate(typeof H=="function"?-H.apply(this,arguments):-H,typeof q=="function"?-q.apply(this,arguments):-q),Z,i)},V,B)};function x(D,H){return H=Math.max(o[0],Math.min(o[1],H)),H===D.k?D:new Ex(H,D.x,D.y)}function w(D,H,q){var V=H[0]-q[0]*D.k,B=H[1]-q[1]*D.k;return V===D.x&&B===D.y?D:new Ex(D.k,V,B)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,H,q,V){D.on("start.zoom",function(){C(this,arguments).event(V).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(V).end()}).tween("zoom",function(){var B=this,Z=arguments,z=C(B,Z).event(V),Y=t.apply(B,Z),L=q==null?k(Y):typeof q=="function"?q.apply(B,Z):q,R=Math.max(Y[1][0]-Y[0][0],Y[1][1]-Y[0][1]),M=B.__zoom,U=typeof H=="function"?H.apply(B,Z):H,Q=c(M.invert(L).concat(R/M.k),U.invert(L).concat(R/U.k));return function(te){if(te===1)te=U;else{var K=Q(te),ee=R/K[2];te=new Ex(ee,L[0]-K[0]*ee,L[1]-K[1]*ee)}z.zoom(null,te)}})}function C(D,H,q){return!q&&D.__zooming||new T(D,H)}function T(D,H){this.that=D,this.args=H,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,H),this.taps=0}T.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,H){return this.mouse&&D!=="mouse"&&(this.mouse[1]=H.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=H.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=H.invert(this.touch1[0])),this.that.__zoom=H,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var H=Np(this.that).datum();u.call(D,this.that,new Gcr(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),H)}};function E(D,...H){if(!e.apply(this,arguments))return;var q=C(this,H).event(D),V=this.__zoom,B=Math.max(o[0],Math.min(o[1],V.k*Math.pow(2,r.apply(this,arguments)))),Z=Ag(D);if(q.wheel)(q.mouse[0][0]!==Z[0]||q.mouse[0][1]!==Z[1])&&(q.mouse[1]=V.invert(q.mouse[0]=Z)),clearTimeout(q.wheel);else{if(V.k===B)return;q.mouse=[Z,V.invert(Z)],u7(this),q.start()}d$(D),q.wheel=setTimeout(z,m),q.zoom("mouse",n(w(x(V,B),q.mouse[0],q.mouse[1]),q.extent,i));function z(){q.wheel=null,q.end()}}function I(D,...H){if(p||!e.apply(this,arguments))return;var q=D.currentTarget,V=C(this,H,!0).event(D),B=Np(D.view).on("mousemove.zoom",L,!0).on("mouseup.zoom",R,!0),Z=Ag(D,q),z=D.clientX,Y=D.clientY;WNt(D.view),Tse(D),V.mouse=[Z,this.__zoom.invert(Z)],u7(this),V.start();function L(M){if(d$(M),!V.moved){var U=M.clientX-z,Q=M.clientY-Y;V.moved=U*U+Q*Q>y}V.event(M).zoom("mouse",n(w(V.that.__zoom,V.mouse[0]=Ag(M,q),V.mouse[1]),V.extent,i))}function R(M){B.on("mousemove.zoom mouseup.zoom",null),ZNt(M.view,V.moved),d$(M),V.event(M).end()}}function N(D,...H){if(e.apply(this,arguments)){var q=this.__zoom,V=Ag(D.changedTouches?D.changedTouches[0]:D,this),B=q.invert(V),Z=q.k*(D.shiftKey?.5:2),z=n(w(x(q,Z),V,B),t.apply(this,H),i);d$(D),l>0?Np(this).transition().duration(l).call(_,z,V,D):Np(this).call(b.transform,z,V,D)}}function A(D,...H){if(e.apply(this,arguments)){var q=D.touches,V=q.length,B=C(this,H,D.changedTouches.length===V).event(D),Z,z,Y,L;for(Tse(D),z=0;z<V;++z)Y=q[z],L=Ag(Y,this),L=[L,this.__zoom.invert(L),Y.identifier],B.touch0?!B.touch1&&B.touch0[2]!==L[2]&&(B.touch1=L,B.taps=0):(B.touch0=L,Z=!0,B.taps=1+!!d);d&&(d=clearTimeout(d)),Z&&(B.taps<2&&(f=L[0],d=setTimeout(function(){d=null},h)),u7(this),B.start())}}function P(D,...H){if(this.__zooming){var q=C(this,H).event(D),V=D.changedTouches,B=V.length,Z,z,Y,L;for(d$(D),Z=0;Z<B;++Z)z=V[Z],Y=Ag(z,this),q.touch0&&q.touch0[2]===z.identifier?q.touch0[0]=Y:q.touch1&&q.touch1[2]===z.identifier&&(q.touch1[0]=Y);if(z=q.that.__zoom,q.touch1){var R=q.touch0[0],M=q.touch0[1],U=q.touch1[0],Q=q.touch1[1],te=(te=U[0]-R[0])*te+(te=U[1]-R[1])*te,K=(K=Q[0]-M[0])*K+(K=Q[1]-M[1])*K;z=x(z,Math.sqrt(te/K)),Y=[(R[0]+U[0])/2,(R[1]+U[1])/2],L=[(M[0]+Q[0])/2,(M[1]+Q[1])/2]}else if(q.touch0)Y=q.touch0[0],L=q.touch0[1];else return;q.zoom("touch",n(w(z,Y,L),q.extent,i))}}function F(D,...H){if(this.__zooming){var q=C(this,H).event(D),V=D.changedTouches,B=V.length,Z,z;for(Tse(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),Z=0;Z<B;++Z)z=V[Z],q.touch0&&q.touch0[2]===z.identifier?delete q.touch0:q.touch1&&q.touch1[2]===z.identifier&&delete q.touch1;if(q.touch1&&!q.touch0&&(q.touch0=q.touch1,delete q.touch1),q.touch0)q.touch0[1]=this.__zoom.invert(q.touch0[0]);else if(q.end(),q.taps===2&&(z=Ag(z,this),Math.hypot(f[0]-z[0],f[1]-z[1])<v)){var Y=Np(this).on("dblclick.zoom");Y&&Y.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:N9(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:N9(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:N9(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:N9([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(o[0]=+D[0],o[1]=+D[1],b):[o[0],o[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?(y=(D=+D)*D,b):Math.sqrt(y)},b.tapDistance=function(D){return arguments.length?(v=+D,b):v},b}const tb={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."},DL=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],uIt=["Enter"," ","Escape"],dIt={"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 bI;(function(e){e.Strict="strict",e.Loose="loose"})(bI||(bI={}));var a_;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(a_||(a_={}));var LL;(function(e){e.Partial="partial",e.Full="full"})(LL||(LL={}));const fIt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var sS;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(sS||(sS={}));var FL;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(FL||(FL={}));var or;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(or||(or={}));const Kqe={[or.Left]:or.Right,[or.Right]:or.Left,[or.Top]:or.Bottom,[or.Bottom]:or.Top};function pIt(e){return e===null?null:e?"valid":"invalid"}const hIt=e=>"id"in e&&"source"in e&&"target"in e,eur=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),bTe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),o5=(e,t=[0,0])=>{const{width:n,height:r}=M0(e),s=e.origin??t,o=n*s[0],i=r*s[1];return{x:e.position.x-o,y:e.position.y-i}},tur=(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 o=typeof s=="string";let i=!t.nodeLookup&&!o?s:void 0;t.nodeLookup&&(i=o?t.nodeLookup.get(s):bTe(s)?s:t.nodeLookup.get(s.id));const l=i?Nq(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return mQ(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return gQ(n)},i5=(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=mQ(n,Nq(s)),r=!0)}),r?gQ(n):{x:0,y:0,width:0,height:0}},xTe=(e,t,[n,r,s]=[0,0,1],o=!1,i=!1)=>{const l={...l5(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,y=zL(l,wI(u)),v=(h??0)*(m??0),b=o&&y>0;(!u.internals.handleBounds||b||y>=v||u.dragging)&&c.push(u)}return c},nur=(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 rur(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 sur({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:o},i){if(e.size===0)return Promise.resolve(!0);const l=rur(e,i),c=i5(l),u=wTe(c,t,n,i?.minZoom??s,i?.maxZoom??o,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function mIt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:o}){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)o?.("005",tb.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&SI(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=SI(f)?sC(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&o?.("015",tb.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 our({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const o=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=o.has(p.id),m=!h&&p.parentId&&i.find(y=>y.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=nur(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 xI=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),sC=(e={x:0,y:0},t,n)=>({x:xI(e.x,t[0][0],t[1][0]-(n?.width??0)),y:xI(e.y,t[0][1],t[1][1]-(n?.height??0))});function gIt(e,t,n){const{width:r,height:s}=M0(n),{x:o,y:i}=n.internals.positionAbsolute;return sC(e,[[o,i],[o+r,i+s]],t)}const Xqe=(e,t,n)=>e<t?xI(Math.abs(e-t),1,t)/t:e>n?-xI(Math.abs(e-n),1,t)/t:0,vIt=(e,t,n=15,r=40)=>{const s=Xqe(e.x,r,t.width-r)*n,o=Xqe(e.y,r,t.height-r)*n;return[s,o]},mQ=(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)}),txe=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),gQ=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),wI=(e,t=[0,0])=>{const{x:n,y:r}=bTe(e)?e.internals.positionAbsolute:o5(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}},Nq=(e,t=[0,0])=>{const{x:n,y:r}=bTe(e)?e.internals.positionAbsolute:o5(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)}},yIt=(e,t)=>gQ(mQ(txe(e),txe(t))),zL=(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)},Jqe=e=>Ug(e.width)&&Ug(e.height)&&Ug(e.x)&&Ug(e.y),Ug=e=>!isNaN(e)&&isFinite(e),iur=(e,t)=>{},a5=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),l5=({x:e,y:t},[n,r,s],o=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return o?a5(l,i):l},Iq=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function kT(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 aur(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=kT(e,n),s=kT(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=kT(e.top??e.y??0,n),s=kT(e.bottom??e.y??0,n),o=kT(e.left??e.x??0,t),i=kT(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:o,x:o+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function lur(e,t,n,r,s,o){const{x:i,y:l}=Iq(e,[t,n,r]),{x:c,y:u}=Iq({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=o-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const wTe=(e,t,n,r,s,o)=>{const i=aur(o,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=xI(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,y=lur(e,h,m,d,t,n),v={left:Math.min(y.left-i.left,0),top:Math.min(y.top-i.top,0),right:Math.min(y.right-i.right,0),bottom:Math.min(y.bottom-i.bottom,0)};return{x:h-v.left+v.right,y:m-v.top+v.bottom,zoom:d}},BL=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function SI(e){return e!=null&&e!=="parent"}function M0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function STe(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function bIt(e,t={width:0,height:0},n,r,s){const o={...e},i=r.get(n);if(i){const l=i.origin||s;o.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],o.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return o}function eHe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function cur(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function uur(e){return{...dIt,...e||{}}}function A2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:o,y:i}=Vg(e),l=l5({x:o-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?a5(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const kTe=e=>({width:e.offsetWidth,height:e.offsetHeight}),xIt=e=>e?.getRootNode?.()||window?.document,dur=["INPUT","SELECT","TEXTAREA"];function wIt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:dur.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const SIt=e=>"clientX"in e,Vg=(e,t)=>{const n=SIt(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)}},tHe=(e,t,n,r,s)=>{const o=t.querySelectorAll(`.${e}`);return!o||!o.length?null:Array.from(o).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,...kTe(i)}})};function kIt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:o,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+o*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function I9(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function nHe({pos:e,x1:t,y1:n,x2:r,y2:s,c:o}){switch(e){case or.Left:return[t-I9(t-r,o),n];case or.Right:return[t+I9(r-t,o),n];case or.Top:return[t,n-I9(n-s,o)];case or.Bottom:return[t,n+I9(s-n,o)]}}function OTe({sourceX:e,sourceY:t,sourcePosition:n=or.Bottom,targetX:r,targetY:s,targetPosition:o=or.Top,curvature:i=.25}){const[l,c]=nHe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=nHe({pos:o,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=kIt({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 OIt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,o=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[o,l,s,i]}function fur({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:o="basic"}){if(o==="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 pur({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const o=mQ(Nq(e),Nq(t));o.x===o.x2&&(o.x2+=1),o.y===o.y2&&(o.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return zL(i,gQ(o))>0}const hur=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,mur=(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)),gur=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||hur;let s;return hIt(e)?s={...e}:s={...e,id:r(e)},mur(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function _It({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,o,i,l]=OIt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,o,i,l]}const rHe={[or.Left]:{x:-1,y:0},[or.Right]:{x:1,y:0},[or.Top]:{x:0,y:-1},[or.Bottom]:{x:0,y:1}},vur=({source:e,sourcePosition:t=or.Bottom,target:n})=>t===or.Left||t===or.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},sHe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function yur({source:e,sourcePosition:t=or.Bottom,target:n,targetPosition:r=or.Top,center:s,offset:o,stepPosition:i}){const l=rHe[t],c=rHe[r],u={x:e.x+l.x*o,y:e.y+l.y*o},d={x:n.x+c.x*o,y:n.y+c.y*o},f=vur({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],y,v;const b={x:0,y:0},x={x:0,y:0},[,,w,k]=OIt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(y=s.x??u.x+(d.x-u.x)*i,v=s.y??(u.y+d.y)/2):(y=s.x??(u.x+d.x)/2,v=s.y??u.y+(d.y-u.y)*i);const E=[{x:y,y:u.y},{x:y,y:d.y}],I=[{x:u.x,y:v},{x:d.x,y:v}];l[p]===h?m=p==="x"?E:I:m=p==="x"?I:E}else{const E=[{x:u.x,y:d.y}],I=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?I:E:m=l.y===h?E:I,t===r){const D=Math.abs(e[p]-n[p]);if(D<=o){const H=Math.min(o-1,o-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*H:x[p]=(d[p]>n[p]?-1:1)*H}}if(t!==r){const D=p==="x"?"y":"x",H=l[p]===c[D],q=u[D]>d[D],V=u[D]<d[D];(l[p]===1&&(!H&&q||H&&V)||l[p]!==1&&(!H&&V||H&&q))&&(m=p==="x"?E:I)}const N={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},P=Math.max(Math.abs(N.x-m[0].x),Math.abs(A.x-m[0].x)),F=Math.max(Math.abs(N.y-m[0].y),Math.abs(A.y-m[0].y));P>=F?(y=(N.x+A.x)/2,v=m[0].y):(y=m[0].x,v=(N.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],y,v,w,k]}function bur(e,t,n,r){const s=Math.min(sHe(e,t)/2,sHe(t,n)/2,r),{x:o,y:i}=t;if(e.x===o&&o===n.x||e.y===i&&i===n.y)return`L${o} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${o+s*u},${i}Q ${o},${i} ${o},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${o},${i+s*c}Q ${o},${i} ${o+s*l},${i}`}function nxe({sourceX:e,sourceY:t,sourcePosition:n=or.Bottom,targetX:r,targetY:s,targetPosition:o=or.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,y]=yur({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:o,center:{x:l,y:c},offset:u,stepPosition:d});let v=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)v+=bur(f[b-1],f[b],f[b+1],i);return v+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[v,p,h,m,y]}function oHe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function xur(e){const{sourceNode:t,targetNode:n}=e;if(!oHe(t)||!oHe(n))return null;const r=t.internals.handleBounds||iHe(t.handles),s=n.internals.handleBounds||iHe(n.handles),o=aHe(r?.source??[],e.sourceHandle),i=aHe(e.connectionMode===bI.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!o||!i)return e.onError?.("008",tb.error008(o?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=o?.position||or.Bottom,c=i?.position||or.Top,u=oC(t,o,l),d=oC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function iHe(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 oC(e,t,n=or.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,o=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??M0(e);if(r)return{x:s+i/2,y:o+l/2};switch(t?.position??n){case or.Top:return{x:s+i/2,y:o};case or.Right:return{x:s+i,y:o+l/2};case or.Bottom:return{x:s+i/2,y:o+l};case or.Left:return{x:s,y:o+l/2}}}function aHe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function rxe(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function wur(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const o=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=rxe(c,t);o.has(u)||(i.push({id:u,color:c.color||n,...c}),o.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const CIt=1e3,Sur=10,_Te={nodeOrigin:[0,0],nodeExtent:DL,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},kur={..._Te,checkEquality:!0};function CTe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function Our(e,t,n){const r=CTe(_Te,n);for(const s of e.values())if(s.parentId)TTe(s,e,t,r);else{const o=o5(s,r.nodeOrigin),i=SI(s.extent)?s.extent:r.nodeExtent,l=sC(o,i,M0(s));s.internals.positionAbsolute=l}}function _ur(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const o={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(o):s.type==="target"&&r.push(o)}return{source:n,target:r}}function ETe(e){return e==="manual"}function sxe(e,t,n,r={}){const s=CTe(kur,r),o={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!ETe(s.zIndexMode)?CIt: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=o5(d,s.nodeOrigin),h=SI(d.extent)?d.extent:s.nodeExtent,m=sC(p,h,M0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:_ur(d,f),z:EIt(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&&TTe(f,t,n,r,o),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function Cur(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 TTe(e,t,n,r,s){const{elevateNodesOnSelect:o,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=CTe(_Te,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}Cur(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*Sur),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=o&&!ETe(c)?CIt:0,{x:p,y:h,z:m}=Eur(e,d,i,l,f,c),{positionAbsolute:y}=e.internals,v=p!==y.x||h!==y.y;(v||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:v?{x:p,y:h}:y,z:m}})}function EIt(e,t,n){const r=Ug(e.zIndex)?e.zIndex:0;return ETe(n)?r:r+(e.selected?t:0)}function Eur(e,t,n,r,s,o){const{x:i,y:l}=t.internals.positionAbsolute,c=M0(e),u=o5(e,n),d=SI(e.extent)?sC(u,e.extent,c):u;let f=sC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=gIt(f,c,t));const p=EIt(e,s,o),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function jTe(e,t,n,r=[0,0]){const s=[],o=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=o.get(i.parentId)?.expandedRect??wI(l),u=yIt(c,i.rect);o.set(i.parentId,{expandedRect:u,parent:l})}return o.size>0&&o.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=M0(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)),y=Math.max(d.height,Math.round(i.height)),v=(m-d.width)*f[0],b=(y-d.height)*f[1];(p>0||h>0||v||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+v,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(w=>w.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-v:0),height:y+(h?f[1]*h-b:0)}})}),s}function Tur(e,t,n,r,s,o,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 y=kTe(h.nodeElement),v=m.measured.width!==y.width||m.measured.height!==y.height;if(!!(y.width&&y.height&&(v||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),w=SI(m.extent)?m.extent:o;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=gIt(k,y,t.get(m.parentId)):w&&(k=sC(k,w,y));const _={...m,measured:y,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:tHe("source",h.nodeElement,x,f,m.id),target:tHe("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&TTe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,v&&(u.push({id:m.id,type:"dimensions",dimensions:y}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:wI(_,s)}))}}if(p.length>0){const h=jTe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function jur({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:o}){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,o]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function lHe(e,t,n,r,s,o){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)),o){i=`${s}-${e}-${o}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function TIt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:o,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:o,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${o}-${l}`,d=`${o}-${l}--${s}-${i}`;lHe("source",c,d,e,s,i),lHe("target",c,u,e,o,l),t.set(r.id,r)}}function jIt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:jIt(n,t):!1}function cHe(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 Nur(e,t,n,r){const s=new Map;for(const[o,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!jIt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(o);l&&s.set(o,{id:o,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 jse({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 o=n.get(e)?.internals.userNode;return[o?{...o,position:t.get(e)?.position||o.position,dragging:r}:s[0],s]}function Iur({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const o={x:n-s.distance.x,y:r-s.distance.y},i=a5(o,t);return{x:i.x-o.x,y:i.y-o.y}}function Aur({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let o={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,y=null;function v({noDragClassName:x,handleSelector:w,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:T=0}){p=Np(k);function E({x:P,y:F}){const{nodeLookup:D,nodeExtent:H,snapGrid:q,snapToGrid:V,nodeOrigin:B,onNodeDrag:Z,onSelectionDrag:z,onError:Y,updateNodePositions:L}=t();o={x:P,y:F};let R=!1;const M=l.size>1,U=M&&H?txe(i5(l)):null,Q=M&&V?Iur({dragItems:l,snapGrid:q,x:P,y:F}):null;for(const[te,K]of l){if(!D.has(te))continue;let ee={x:P-K.distance.x,y:F-K.distance.y};V&&(ee=Q?{x:Math.round(ee.x+Q.x),y:Math.round(ee.y+Q.y)}:a5(ee,q));let ne=null;if(M&&H&&!K.extent&&U){const{positionAbsolute:re}=K.internals,se=re.x-U.x+H[0][0],ie=re.x+K.measured.width-U.x2+H[1][0],fe=re.y-U.y+H[0][1],he=re.y+K.measured.height-U.y2+H[1][1];ne=[[se,fe],[ie,he]]}const{position:le,positionAbsolute:J}=mIt({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:ne||H,nodeOrigin:B,onError:Y});R=R||K.position.x!==le.x||K.position.y!==le.y,K.position=le,K.internals.positionAbsolute=J}if(m=m||R,!!R&&(L(l,!0),y&&(r||Z||!C&&z))){const[te,K]=jse({nodeId:C,dragItems:l,nodeLookup:D});r?.(y,l,te,K),Z?.(y,te,K),C||z?.(y,K)}}async function I(){if(!d)return;const{transform:P,panBy:F,autoPanSpeed:D,autoPanOnNodeDrag:H}=t();if(!H){c=!1,cancelAnimationFrame(i);return}const[q,V]=vIt(u,d,D);(q!==0||V!==0)&&(o.x=(o.x??0)-q/P[2],o.y=(o.y??0)-V/P[2],await F({x:q,y:V})&&E(o)),i=requestAnimationFrame(I)}function N(P){const{nodeLookup:F,multiSelectionActive:D,nodesDraggable:H,transform:q,snapGrid:V,snapToGrid:B,selectNodesOnDrag:Z,onNodeDragStart:z,onSelectionDragStart:Y,unselectNodesAndEdges:L}=t();f=!0,(!Z||!_)&&!D&&C&&(F.get(C)?.selected||L()),_&&Z&&C&&e?.(C);const R=A2(P.sourceEvent,{transform:q,snapGrid:V,snapToGrid:B,containerBounds:d});if(o=R,l=Nur(F,H,R,C),l.size>0&&(n||z||!C&&Y)){const[M,U]=jse({nodeId:C,dragItems:l,nodeLookup:F});n?.(P.sourceEvent,l,M,U),z?.(P.sourceEvent,M,U),C||Y?.(P.sourceEvent,U)}}const A=GNt().clickDistance(T).on("start",P=>{const{domNode:F,nodeDragThreshold:D,transform:H,snapGrid:q,snapToGrid:V}=t();d=F?.getBoundingClientRect()||null,h=!1,m=!1,y=P.sourceEvent,D===0&&N(P),o=A2(P.sourceEvent,{transform:H,snapGrid:q,snapToGrid:V,containerBounds:d}),u=Vg(P.sourceEvent,d)}).on("drag",P=>{const{autoPanOnNodeDrag:F,transform:D,snapGrid:H,snapToGrid:q,nodeDragThreshold:V,nodeLookup:B}=t(),Z=A2(P.sourceEvent,{transform:D,snapGrid:H,snapToGrid:q,containerBounds:d});if(y=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||C&&!B.has(C))&&(h=!0),!h){if(!c&&F&&f&&(c=!0,I()),!f){const z=Vg(P.sourceEvent,d),Y=z.x-u.x,L=z.y-u.y;Math.sqrt(Y*Y+L*L)>V&&N(P)}(o.x!==Z.xSnapped||o.y!==Z.ySnapped)&&l&&f&&(u=Vg(P.sourceEvent,d),E(Z))}}).on("end",P=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:F,updateNodePositions:D,onNodeDragStop:H,onSelectionDragStop:q}=t();if(m&&(D(l,!1),m=!1),s||H||!C&&q){const[V,B]=jse({nodeId:C,dragItems:l,nodeLookup:F,dragging:!1});s?.(P.sourceEvent,l,V,B),H?.(P.sourceEvent,V,B),C||q?.(P.sourceEvent,B)}}}).filter(P=>{const F=P.target;return!P.button&&(!x||!cHe(F,`.${x}`,k))&&(!w||cHe(F,w,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:v,destroy:b}}function Rur(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const o of t.values())zL(s,wI(o))>0&&r.push(o);return r}const Pur=250;function $ur(e,t,n,r){let s=[],o=1/0;const i=Rur(e,n,t+Pur);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}=oC(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<o?(s=[{...u,x:d,y:f}],o=p):p===o&&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 NIt(e,t,n,r,s,o=!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&&o?{...c,...oC(i,c,c.position,!0)}:c}function IIt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function Mur(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const AIt=()=>!0;function Dur(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:o,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:y,onConnectEnd:v,isValidConnection:b=AIt,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:T=1,handleDomNode:E}){const I=xIt(e.target);let N=0,A;const{x:P,y:F}=Vg(e),D=IIt(o,E),H=l?.getBoundingClientRect();let q=!1;if(!H||!D)return;const V=NIt(s,D,r,c,t);if(!V)return;let B=Vg(e,H),Z=!1,z=null,Y=!1,L=null;function R(){if(!d||!H)return;const[le,J]=vIt(B,H,C);p({x:le,y:J}),N=requestAnimationFrame(R)}const M={...V,nodeId:s,type:D,position:V.position},U=c.get(s);let te={inProgress:!0,isValid:null,from:oC(U,M,or.Left,!0),fromHandle:M,fromPosition:M.position,fromNode:U,to:B,toHandle:null,toPosition:Kqe[M.position],toNode:null,pointer:B};function K(){q=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&K();function ee(le){if(!q){const{x:he,y:xe}=Vg(le),Ne=he-P,Ae=xe-F;if(!(Ne*Ne+Ae*Ae>T*T))return;K()}if(!_()||!M){ne(le);return}const J=k();B=Vg(le,H),A=$ur(l5(B,J,!1,[1,1]),n,c,M),Z||(R(),Z=!0);const re=RIt(le,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:I,lib:u,flowId:f,nodeLookup:c});L=re.handleDomNode,z=re.connection,Y=Mur(!!A,re.isValid);const se=c.get(s),ie=se?oC(se,M,or.Left,!0):te.from,fe={...te,from:ie,isValid:Y,to:re.toHandle&&Y?Iq({x:re.toHandle.x,y:re.toHandle.y},J):B,toHandle:re.toHandle,toPosition:Y&&re.toHandle?re.toHandle.position:Kqe[M.position],toNode:re.toHandle?c.get(re.toHandle.nodeId):null,pointer:B};w(fe),te=fe}function ne(le){if(!("touches"in le&&le.touches.length>0)){if(q){(A||L)&&z&&Y&&y?.(z);const{inProgress:J,...re}=te,se={...re,toPosition:te.toHandle?te.toPosition:null};v?.(le,se),o&&x?.(le,se)}h(),cancelAnimationFrame(N),Z=!1,Y=!1,z=null,L=null,I.removeEventListener("mousemove",ee),I.removeEventListener("mouseup",ne),I.removeEventListener("touchmove",ee),I.removeEventListener("touchend",ne)}}I.addEventListener("mousemove",ee),I.addEventListener("mouseup",ne),I.addEventListener("touchmove",ee),I.addEventListener("touchend",ne)}function RIt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:o,doc:i,lib:l,flowId:c,isValidConnection:u=AIt,nodeLookup:d}){const f=o==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=Vg(e),y=i.elementFromPoint(h,m),v=y?.classList.contains(`${l}-flow__handle`)?y:p,b={handleDomNode:v,isValid:!1,connection:null,toHandle:null};if(v){const x=IIt(void 0,v),w=v.getAttribute("data-nodeid"),k=v.getAttribute("data-handleid"),_=v.classList.contains("connectable"),C=v.classList.contains("connectableend");if(!w||!x)return b;const T={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=T;const I=_&&C&&(n===bI.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=I&&u(T),b.toHandle=NIt(w,x,k,d,n,!0)}return b}const oxe={onPointerDown:Dur,isValid:RIt};function Lur({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Np(e);function o({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=w.sourceEvent.ctrlKey&&BL()?10:1,C=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,C*_);t.scaleTo(T)};let y=[0,0];const v=w=>{(w.sourceEvent.type==="mousedown"||w.sourceEvent.type==="touchstart")&&(y=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY])},b=w=>{const k=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const _=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],C=[_[0]-y[0],_[1]-y[1]];y=_;const T=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),E={x:k[0]-C[0]*T,y:k[1]-C[1]*T},I=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},I,l)},x=cIt().on("start",v).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:o,destroy:i,pointer:Ag}}const vQ=e=>({x:e.x,y:e.y,zoom:e.k}),Nse=({x:e,y:t,zoom:n})=>hQ.translate(e,t).scale(n),Tj=(e,t)=>e.target.closest(`.${t}`),PIt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Fur=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Ise=(e,t=0,n=Fur,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},$It=e=>{const t=e.ctrlKey&&BL()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function zur({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:o,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(Tj(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const v=Ag(d),b=$It(d),x=f*Math.pow(2,b);r.scaleTo(n,x,v,d);return}const p=d.deltaMode===1?20:1;let h=s===a_.Vertical?0:d.deltaX*p,m=s===a_.Horizontal?0:d.deltaY*p;!BL()&&d.shiftKey&&s!==a_.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*o,-(m/f)*o,{internal:!0});const y=vQ(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,y),e.panScrollTimeout=setTimeout(()=>{u?.(d,y),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,y))}}function Bur({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const o=r.type==="wheel",i=!t&&o&&!r.ctrlKey,l=Tj(r,e);if(r.ctrlKey&&o&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function Uur({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=vQ(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 Vur({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return o=>{e.usedRightMouseButton=!!(n&&PIt(t,e.mouseButton??0)),o.sourceEvent?.sync||r([o.transform.x,o.transform.y,o.transform.k]),s&&!o.sourceEvent?.internal&&s?.(o.sourceEvent,vQ(o.transform))}}function qur({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:o}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,o&&PIt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&o(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=vQ(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function Hur({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:o,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"&&(Tj(f,`${u}-flow__node`)||Tj(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!o&&!n||i||d&&!m||Tj(f,l)&&m||Tj(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 y=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&y}}function Wur({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:o,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=cIt().scaleExtent([t,n]).translateExtent(r),p=Np(e).call(f);x({x:s.x,y:s.y,zoom:xI(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta($It);function y(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?Hx:a7).transform(Ise(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function v({noWheelClassName:A,noPanClassName:P,onPaneContextMenu:F,userSelectionActive:D,panOnScroll:H,panOnDrag:q,panOnScrollMode:V,panOnScrollSpeed:B,preventScrolling:Z,zoomOnPinch:z,zoomOnScroll:Y,zoomOnDoubleClick:L,zoomActivationKeyPressed:R,lib:M,onTransformChange:U,connectionInProgress:Q,paneClickDistance:te,selectionOnDrag:K}){D&&!u.isZoomingOrPanning&&b();const ee=H&&!R&&!D;f.clickDistance(K?1/0:!Ug(te)||te<0?0:te);const ne=ee?zur({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:V,panOnScrollSpeed:B,zoomOnPinch:z,onPanZoomStart:i,onPanZoom:o,onPanZoomEnd:l}):Bur({noWheelClassName:A,preventScrolling:Z,d3ZoomHandler:h});if(p.on("wheel.zoom",ne,{passive:!1}),!D){const J=Uur({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",J);const re=Vur({zoomPanValues:u,panOnDrag:q,onPaneContextMenu:!!F,onPanZoom:o,onTransformChange:U});f.on("zoom",re);const se=qur({zoomPanValues:u,panOnDrag:q,panOnScroll:H,onPaneContextMenu:F,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const le=Hur({zoomActivationKeyPressed:R,panOnDrag:q,zoomOnScroll:Y,panOnScroll:H,zoomOnDoubleClick:L,zoomOnPinch:z,userSelectionActive:D,noPanClassName:P,noWheelClassName:A,lib:M,connectionInProgress:Q});f.filter(le),L?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,P,F){const D=Nse(A),H=f?.constrain()(D,P,F);return H&&await y(H),new Promise(q=>q(H))}async function w(A,P){const F=Nse(A);return await y(F,P),new Promise(D=>D(F))}function k(A){if(p){const P=Nse(A),F=p.property("__zoom");(F.k!==A.zoom||F.x!==A.x||F.y!==A.y)&&f?.transform(p,P,null,{sync:!0})}}function _(){const A=p?lIt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?Hx:a7).scaleTo(Ise(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function T(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?Hx:a7).scaleBy(Ise(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function I(A){f?.translateExtent(A)}function N(A){const P=!Ug(A)||A<0?0:A;f?.clickDistance(P)}return{update:v,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:T,setScaleExtent:E,setTranslateExtent:I,syncViewport:k,setClickDistance:N}}var kI;(function(e){e.Line="line",e.Handle="handle"})(kI||(kI={}));function Zur({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:o}){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&&o&&(c[1]=c[1]*-1),c}function uHe(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 jw(e,t){return Math.max(0,t-e)}function Nw(e,t){return Math.max(0,e-t)}function A9(e,t,n){return Math.max(0,t-e,e-n)}function dHe(e,t){return e?!t:t}function Gur(e,t,n,r,s,o,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:y,maxWidth:v,minHeight:b,maxHeight:x}=r,{x:w,y:k,width:_,height:C,aspectRatio:T}=e;let E=Math.floor(d?h-e.pointerX:0),I=Math.floor(f?m-e.pointerY:0);const N=_+(c?-E:E),A=C+(u?-I:I),P=-o[0]*_,F=-o[1]*C;let D=A9(N,y,v),H=A9(A,b,x);if(i){let B=0,Z=0;c&&E<0?B=jw(w+E+P,i[0][0]):!c&&E>0&&(B=Nw(w+N+P,i[1][0])),u&&I<0?Z=jw(k+I+F,i[0][1]):!u&&I>0&&(Z=Nw(k+A+F,i[1][1])),D=Math.max(D,B),H=Math.max(H,Z)}if(l){let B=0,Z=0;c&&E>0?B=Nw(w+E,l[0][0]):!c&&E<0&&(B=jw(w+N,l[1][0])),u&&I>0?Z=Nw(k+I,l[0][1]):!u&&I<0&&(Z=jw(k+A,l[1][1])),D=Math.max(D,B),H=Math.max(H,Z)}if(s){if(d){const B=A9(N/T,b,x)*T;if(D=Math.max(D,B),i){let Z=0;!c&&!u||c&&!u&&p?Z=Nw(k+F+N/T,i[1][1])*T:Z=jw(k+F+(c?E:-E)/T,i[0][1])*T,D=Math.max(D,Z)}if(l){let Z=0;!c&&!u||c&&!u&&p?Z=jw(k+N/T,l[1][1])*T:Z=Nw(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,Z)}}if(f){const B=A9(A*T,y,v)/T;if(H=Math.max(H,B),i){let Z=0;!c&&!u||u&&!c&&p?Z=Nw(w+A*T+P,i[1][0])/T:Z=jw(w+(u?I:-I)*T+P,i[0][0])/T,H=Math.max(H,Z)}if(l){let Z=0;!c&&!u||u&&!c&&p?Z=jw(w+A*T,l[1][0])/T:Z=Nw(w+(u?I:-I)*T,l[0][0])/T,H=Math.max(H,Z)}}}I=I+(I<0?H:-H),E=E+(E<0?D:-D),s&&(p?N>A*T?I=(dHe(c,u)?-E:E)/T:E=(dHe(c,u)?-I:I)*T:d?(I=E/T,u=c):(E=I*T,c=u));const q=c?w+E:w,V=u?k+I:k;return{width:_+(c?-E:E),height:C+(u?-I:I),x:o[0]*E*(c?-1:1)+q,y:o[1]*I*(u?-1:1)+V}}const MIt={width:0,height:0,x:0,y:0},Qur={...MIt,pointerX:0,pointerY:0,aspectRatio:1};function Yur(e){return[[0,0],[e.measured.width,e.measured.height]]}function Kur(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,o=e.measured.width??0,i=e.measured.height??0,l=n[0]*o,c=n[1]*i;return[[r-l,s-c],[r+o-l,s+i-c]]}function Xur({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const o=Np(e);let i={controlDirection:uHe("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:y,shouldResize:v}){let b={...MIt},x={...Qur};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:uHe(u)};let w,k=null,_=[],C,T,E,I=!1;const N=GNt().on("start",A=>{const{nodeLookup:P,transform:F,snapGrid:D,snapToGrid:H,nodeOrigin:q,paneDomNode:V}=n();if(w=P.get(t),!w)return;k=V?.getBoundingClientRect()??null;const{xSnapped:B,ySnapped:Z}=A2(A.sourceEvent,{transform:F,snapGrid:D,snapToGrid:H,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},x={...b,pointerX:B,pointerY:Z,aspectRatio:b.width/b.height},C=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(C=P.get(w.parentId),T=C&&w.extent==="parent"?Yur(C):void 0),_=[],E=void 0;for(const[z,Y]of P)if(Y.parentId===t&&(_.push({id:z,position:{...Y.position},extent:Y.extent}),Y.extent==="parent"||Y.expandParent)){const L=Kur(Y,w,Y.origin??q);E?E=[[Math.min(L[0][0],E[0][0]),Math.min(L[0][1],E[0][1])],[Math.max(L[1][0],E[1][0]),Math.max(L[1][1],E[1][1])]]:E=L}h?.(A,{...b})}).on("drag",A=>{const{transform:P,snapGrid:F,snapToGrid:D,nodeOrigin:H}=n(),q=A2(A.sourceEvent,{transform:P,snapGrid:F,snapToGrid:D,containerBounds:k}),V=[];if(!w)return;const{x:B,y:Z,width:z,height:Y}=b,L={},R=w.origin??H,{width:M,height:U,x:Q,y:te}=Gur(x,i.controlDirection,q,i.boundaries,i.keepAspectRatio,R,T,E),K=M!==z,ee=U!==Y,ne=Q!==B&&K,le=te!==Z&&ee;if(!ne&&!le&&!K&&!ee)return;if((ne||le||R[0]===1||R[1]===1)&&(L.x=ne?Q:b.x,L.y=le?te:b.y,b.x=L.x,b.y=L.y,_.length>0)){const ie=Q-B,fe=te-Z;for(const he of _)he.position={x:he.position.x-ie+R[0]*(M-z),y:he.position.y-fe+R[1]*(U-Y)},V.push(he)}if((K||ee)&&(L.width=K&&(!i.resizeDirection||i.resizeDirection==="horizontal")?M:b.width,L.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?U:b.height,b.width=L.width,b.height=L.height),C&&w.expandParent){const ie=R[0]*(L.width??0);L.x&&L.x<ie&&(b.x=ie,x.x=x.x-(L.x-ie));const fe=R[1]*(L.height??0);L.y&&L.y<fe&&(b.y=fe,x.y=x.y-(L.y-fe))}const J=Zur({width:b.width,prevWidth:z,height:b.height,prevHeight:Y,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),re={...b,direction:J};v?.(A,re)!==!1&&(I=!0,m?.(A,re),r(L,V))}).on("end",A=>{I&&(y?.(A,{...b}),s?.({...b}),I=!1)});o.call(N)}function c(){o.on(".drag",null)}return{update:l,destroy:c}}const Jur={},fHe=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:()=>{(Jur?"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},edr=e=>e?fHe(e):fHe,{useDebugValue:tdr}=$e,{useSyncExternalStoreWithSelector:ndr}=RAn,rdr=e=>e;function DIt(e,t=rdr,n){const r=ndr(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return tdr(r),r}const pHe=(e,t)=>{const n=edr(e),r=(s,o=t)=>DIt(n,s,o);return Object.assign(r,n),r},sdr=(e,t)=>e?pHe(e,t):pHe;function Zi(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 yQ=g.createContext(null),odr=yQ.Provider,LIt=tb.error001();function is(e,t){const n=g.useContext(yQ);if(n===null)throw new Error(LIt);return DIt(n,e,t)}function Ta(){const e=g.useContext(yQ);if(e===null)throw new Error(LIt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const hHe={display:"none"},idr={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},FIt="react-flow__node-desc",zIt="react-flow__edge-desc",adr="react-flow__aria-live",ldr=e=>e.ariaLiveMessage,cdr=e=>e.ariaLabelConfig;function udr({rfId:e}){const t=is(ldr);return a.jsx("div",{id:`${adr}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:idr,children:t})}function ddr({rfId:e,disableKeyboardA11y:t}){const n=is(cdr);return a.jsxs(a.Fragment,{children:[a.jsx("div",{id:`${FIt}-${e}`,style:hHe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),a.jsx("div",{id:`${zIt}-${e}`,style:hHe,children:n["edge.a11yDescription.default"]}),!t&&a.jsx(udr,{rfId:e})]})}const c5=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},o)=>{const i=`${e}`.split("-");return a.jsx("div",{className:ql(["react-flow__panel",n,...i]),style:r,ref:o,...s,children:t})});c5.displayName="Panel";function fdr({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:a.jsx(c5,{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:a.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const pdr=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}},R9=e=>e.id;function hdr(e,t){return Zi(e.selectedNodes.map(R9),t.selectedNodes.map(R9))&&Zi(e.selectedEdges.map(R9),t.selectedEdges.map(R9))}function mdr({onSelectionChange:e}){const t=Ta(),{selectedNodes:n,selectedEdges:r}=is(pdr,hdr);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(o=>o(s))},[n,r,e]),null}const gdr=e=>!!e.onSelectionChangeHandlers;function vdr({onSelectionChange:e}){const t=is(gdr);return e||t?a.jsx(mdr,{onSelectionChange:e}):null}const ixe=typeof window<"u"?g.useLayoutEffect:g.useEffect,BIt=[0,0],ydr={x:0,y:0,zoom:1},bdr=["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"],mHe=[...bdr,"rfId"],xdr=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}),gHe={translateExtent:DL,nodeOrigin:BIt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function wdr(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:o,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=is(xdr,Zi),u=Ta();ixe(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=gHe,l()}),[]);const d=g.useRef(gHe);return ixe(()=>{for(const f of mHe){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"?o(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:uur(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},mHe.map(f=>e[f])),null}function vHe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Sdr(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=vHe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:vHe()?.matches?"dark":"light"}const yHe=typeof document<"u"?document:null;function UL(e=null,t={target:yHe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),o=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("+",`
250
250
  `).replace(`
251
251
 
252
252
  `,`
@@ -683,7 +683,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
683
683
  }
684
684
  ]`,mjs=[{name:"input",description:"What the agent receives. A string or any JSON value.",required:!0},{name:"groundTruth",description:"Expected answer used by scorers.",required:!1},{name:"metadata",description:"Any object, useful for filtering and grouping.",required:!1}];function gjs(){const{isCopied:e,handleCopy:t}=Ud({text:Bot,showToast:!1});return a.jsxs("div",{className:"flex flex-col gap-4",children:[a.jsx("p",{className:"flex h-8 items-center text-column text-foreground",children:"Each item looks like this"}),a.jsx("dl",{className:"divide-y divide-border rounded-lg border border-border",children:mjs.map(n=>a.jsxs("div",{className:"grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5",children:[a.jsx("dt",{className:"text-meta text-foreground",children:a.jsx(w1,{children:n.name})}),a.jsxs("dd",{className:"flex flex-col items-start gap-1.5 text-meta text-muted-foreground",children:[a.jsx("span",{children:n.description}),n.required?a.jsx(Mt,{variant:"green",size:"xs",children:"required"}):a.jsx(Mt,{variant:"neutral",emphasis:"muted",size:"xs",children:"optional"})]})]},n.name))}),a.jsxs("div",{className:"overflow-hidden rounded-lg border border-border",children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-border bg-card py-1.5 pr-1.5 pl-3",children:[a.jsx(je,{as:"span",variant:"meta",tone:"muted",font:"mono",children:"example.json"}),a.jsx(ae,{icon:e?a.jsx(Vn,{}):a.jsx(Ju,{}),variant:"ghost",size:"sm",onClick:t,children:e?"Copied":"Copy"})]}),a.jsx(br,{variant:"embedded",language:"json",editable:!1,lineNumbers:!1,showCopyButton:!1,value:Bot,className:"p-3"})]}),a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:hjs,target:"_blank",rel:"noopener noreferrer"}),className:"self-start",icon:a.jsx(Ts,{}),children:"Datasets documentation"})]})}const rce=10,vjs=`[
685
685
  { "input": "…", "groundTruth": "…" }
686
- ]`,Uot="flex min-h-0 flex-1 flex-col py-0";function yjs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:o,onPastedTextChange:i,validation:l,isImporting:c}){return a.jsxs(ll,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[a.jsxs(al,{variant:"pill",children:[a.jsx(Lr,{value:"upload",children:"Upload file"}),a.jsx(Lr,{value:"paste",children:"Paste JSON"})]}),a.jsx(Ss,{value:"upload",className:Uot,children:n?a.jsx(Sjs,{file:n,validation:l,onReplace:s,isImporting:c}):a.jsx(bjs,{onFileSelect:r,disabled:c})}),a.jsx(Ss,{value:"paste",className:Uot,children:a.jsx(br,{"aria-label":"JSON items",language:"json",lineNumbers:!1,showCopyButton:!1,placeholder:vjs,value:o,onChange:i,editable:!c,className:"min-h-50 flex-1"})})]})}function bjs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),o=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return a.jsxs("div",{"data-testid":"json-dropzone",onDragOver:o,onDragLeave:i,onDrop:l,className:W("relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-card px-4 py-6 text-center","hover:border-accent1/50 hover:bg-accent1/5",n&&"border-accent1/50 bg-accent1/5",t&&"cursor-wait opacity-60"),children:[a.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),a.jsx("div",{className:"flex size-9 items-center justify-center rounded-md border border-border bg-background text-muted-foreground",children:a.jsx(PA,{className:"size-4"})}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("p",{className:"text-body text-foreground",children:"Drop a JSON file here"}),a.jsxs("p",{className:"text-caption text-muted-foreground",children:["or ",a.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),a.jsxs("p",{className:"text-meta text-muted-foreground",children:[".json · an array of items · up to ",l2e]})]})}function xjs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function wjs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function Sjs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],o="total"in t?t.total:0,i=s.slice(0,rce);return a.jsxs("div",{"data-testid":"json-file-card",className:"rounded-lg border border-border",children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[a.jsx(jA,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(je,{as:"span",variant:"caption",tone:"ink",font:"mono",className:"min-w-0 flex-1 truncate",children:e.name}),a.jsx("span",{className:"shrink-0 text-meta text-muted-foreground",children:xjs(e.size)}),a.jsx(ae,{icon:a.jsx(n0,{}),variant:"ghost",size:"sm",onClick:n,disabled:r,children:"Replace"})]}),i.map(l=>a.jsxs("div",{className:"grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t border-border px-3 py-1.5",children:[a.jsx("span",{className:"text-meta text-muted-foreground",children:l.index}),a.jsx(je,{as:"span",variant:"caption",tone:"ink",font:"mono",className:"truncate",children:wjs(l.input)}),l.hasInput?l.hasGroundTruth?null:a.jsx(Mt,{variant:"yellow",size:"xs",children:"no groundTruth"}):a.jsx(Mt,{variant:"red",size:"xs",children:"no input"})]},l.index)),o>rce&&a.jsxs("div",{className:"border-t border-border px-3 py-1.5 text-meta text-muted-foreground",children:["+ ",o-rce," more"]})]})}const kjs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function Ojs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[o,i]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,p]=g.useState(null),[h,m]=g.useState(""),[y,v]=g.useState(!1),b=g.useRef(0),{batchInsertItems:x}=cl(),w=o==="upload"?u:h,k=g.useMemo(()=>o==="upload"&&f?{status:"error",kind:"parse",message:f}:fTs(w),[o,f,w]),_=g.useCallback(async N=>{const A=++b.current;if(!N.name.toLowerCase().endsWith(".json")){p("Only .json files are supported");return}if(N.size>TXt){p(`File is larger than ${l2e}`);return}try{const P=await kjs(N);if(A!==b.current)return;c({name:N.name,size:N.size}),d(P),p(null)}catch{if(A!==b.current)return;p("Could not read the file")}},[]),C=g.useCallback(()=>{b.current++,c(null),d(""),p(null)},[]),T=g.useCallback(()=>{b.current++,i("upload"),c(null),d(""),p(null),m("")},[]),E=g.useCallback(()=>{y||(r(!1),setTimeout(T,150))},[y,r,T]),I=g.useCallback(async()=>{if(k.status==="ready"){v(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Qe.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(N){Qe.error(N instanceof Error?N.message:"Failed to import items")}finally{v(!1)}}},[k,x,e,s,r,T]);return a.jsx(hs,{open:n,onOpenChange:E,children:a.jsxs(rs,{className:"flex max-h-[90vh] w-[960px] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0",children:[a.jsxs(ss,{className:"border-b border-border px-4 py-4",children:[a.jsx(Jr,{children:"Import into dataset"}),a.jsxs(Ms,{className:"not-sr-only text-caption text-muted-foreground",children:["Add items to ",t?a.jsx("span",{className:"text-foreground",children:t}):"this dataset"," from a JSON file or paste them directly."]})]}),a.jsx(ys,{className:"max-h-none min-h-0 flex-1 overflow-y-auto p-0",children:a.jsxs("div",{className:"grid divide-y divide-border md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[a.jsx("div",{className:"flex min-h-[360px] flex-col p-4",children:a.jsx(yjs,{tab:o,onTabChange:i,file:l,onFileSelect:_,onReplace:C,pastedText:h,onPastedTextChange:m,validation:k,isImporting:y})}),a.jsx("div",{className:"p-4",children:a.jsx(gjs,{})})]})}),a.jsxs(rc,{className:"items-center border-t border-border px-4 py-3 sm:justify-between",children:[a.jsx(_js,{validation:k}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:E,disabled:y,children:"Cancel"}),a.jsxs(ae,{variant:"primary",onClick:I,disabled:k.status!=="ready"||y,children:[y&&a.jsx(Cn,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function _js({validation:e}){const t=W("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-muted-foreground",e.status==="ready"&&"bg-accent1",e.status==="error"&&"bg-accent2");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=a.jsxs(a.Fragment,{children:[a.jsx("b",{className:"font-medium text-foreground",children:e.total})," item",e.total!==1?"s":""," ","ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${l2e}`;break;case"missing-input":n=a.jsxs(a.Fragment,{children:[a.jsx("b",{className:"font-medium text-foreground",children:e.missingInputCount})," of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",a.jsx(w1,{children:"input"})]});break}break}return a.jsxs("div",{role:"status",className:"flex min-w-0 items-center gap-2 text-caption text-muted-foreground",children:[a.jsx("span",{className:t}),a.jsx("span",{className:"truncate",children:n})]})}function Cjs(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function LXt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=o=>{o.defaultPrevented||Cjs(o.target)||(o.key==="PageUp"?(o.preventDefault(),t?.()):o.key==="PageDown"?(o.preventDefault(),n?.()):o.key==="Escape"&&(o.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const FXt=g.createContext(null);function Ejs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=zr(),i=sOe("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(h=>{s(`/datasets/${e}/items/${encodeURIComponent(h)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(h=>h.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const h=t[u-1].id;return()=>l(h)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const h=t[u+1].id;return()=>l(h)},[u,t,l]);LXt({active:!!i,onPrevious:d,onNext:f,onClose:c});const p=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return a.jsx(FXt.Provider,{value:p,children:r})}function zXt(){const e=g.useContext(FXt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}const Tjs=["createdAt"];function jjs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:o}){const[i,l]=so(),{activeVersion:c}=u2e(i,l),{sort:u,onSortChange:d}=fk({searchParams:i,setSearchParams:l,allowedKeys:Tjs}),f=g.useMemo(()=>u?{field:u.key,direction:u.direction==="asc"?"ASC":"DESC"}:void 0,[u]),[p,h]=g.useState(!1),[m,y]=g.useState(!1),[v,b]=g.useState(!1),[x,w]=g.useState([]),[k,_]=g.useState(!1),[C,T]=g.useState([]),[E,I]=g.useState(!1),[N,A]=g.useState([]),[P,F]=g.useState(0),[D,H]=g.useState(""),[q]=kCe(D,300),{data:V}=vv(e),{data:B=[],isLoading:Z,setEndOfListElement:z,isFetchingNextPage:Y,hasNextPage:L}=oA(e,q||void 0,c,f),{deleteItems:R}=cl(),{currentItemId:M,openItem:U,close:Q}=zXt(),te=ie=>{M===ie?Q():U(ie)},K=ie=>{w(ie),b(!0)},ee=ie=>{T(ie),_(!0)},ne=ie=>{_(ie),ie||(T([]),F(fe=>fe+1))},le=ie=>{A(ie),I(!0)},J=async()=>{await R.mutateAsync({datasetId:e,itemIds:N}),Qe.success(`Deleted ${N.length} items`),I(!1),A([]),F(ie=>ie+1)},re=ie=>{b(!1),w([]),F(fe=>fe+1),n?.(ie)},se=ie=>{b(ie),ie||(w([]),F(fe=>fe+1))};return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid h-full overflow-auto",children:a.jsx(pjs,{items:B,leftSlot:r,rightSlot:s,belowToolbarSlot:o,isLoading:Z,onItemClick:te,featuredItemId:M,onAddClick:t??(()=>{}),onImportClick:()=>h(!0),onImportJsonClick:()=>y(!0),onBulkDeleteClick:le,onCreateDatasetClick:K,onAddToDatasetClick:ee,datasetName:V?.name,clearSelectionTrigger:P,setEndOfListElement:z,isFetchingNextPage:Y,hasNextPage:L,searchQuery:D,activeSearchQuery:q,onSearchChange:H,sort:u,onSortChange:d,currentDatasetVersion:V?.version})}),a.jsx(ijs,{datasetId:e,open:p,onOpenChange:h}),a.jsx(Ojs,{datasetId:e,datasetName:V?.name,open:m,onOpenChange:y}),a.jsx(BTs,{open:v,onOpenChange:se,items:x,onSuccess:re}),a.jsx(UTs,{open:k,onOpenChange:ne,items:C,currentDatasetId:e}),a.jsx($t,{open:E,onOpenChange:I,children:a.jsxs($t.Content,{children:[a.jsxs($t.Header,{children:[a.jsx($t.Title,{children:"Delete Items"}),a.jsxs($t.Description,{children:["Are you sure you want to delete ",N.length," item",N.length!==1?"s":"","? This action cannot be undone."]})]}),a.jsxs($t.Footer,{children:[a.jsx($t.Cancel,{children:"Cancel"}),a.jsx($t.Action,{onClick:J,children:R.isPending?"Deleting...":"Delete"})]})]})})]})}const Vot="__create_tag__";function Njs({datasetId:e}){const{data:t}=vv(e),{data:n}=W1(),{updateDataset:r}=cl(),[s,o]=g.useState(""),i=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>IXt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const p=l.map(y=>({label:y,value:y,end:i.includes(y)?a.jsx(Vn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=s.trim();return h.length>0&&!l.includes(h)&&!i.includes(h)?[{label:`Create "${h}"`,value:Vot},...p]:p},[l,i,s]),u=p=>{r.mutate({datasetId:e,tags:p},{onError:()=>Qe.error("Failed to update tags")})},d=p=>{const h=p===Vot?s.trim():p;!h||i.includes(h)||u([...i,h])},f=p=>{u(i.filter(h=>h!==p))};return a.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2",children:[i.map(p=>a.jsxs(qX,{value:p,size:"md",className:"gap-1 pr-1",children:[p,a.jsx("button",{type:"button","aria-label":`Remove tag ${p}`,disabled:r.isPending,onClick:()=>f(p),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:a.jsx(Gt,{className:"size-3"})})]},p)),a.jsx(za,{options:c,value:void 0,onValueChange:d,onInputValueChange:o,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(V1,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"sm",className:"w-auto min-w-0",disabled:r.isPending})]})}function BXt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return a.jsxs("div",{className:"grid gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(oc,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),a.jsx(Mn,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),a.jsx("p",{className:"text-caption text-muted-foreground",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?a.jsx(WX,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function TN({name:e,field:t,errors:n}){return n.length===0?null:a.jsx(Ht.ErrorMsg,{name:e,children:a.jsx("span",{className:"space-y-1",children:n.map(r=>a.jsxs("span",{className:"block",children:[a.jsxs("code",{className:"rounded bg-destructive/10 px-1",children:[t,r.path!=="/"?r.path:""]}),": ",r.message]},`${r.path}:${r.message}`))})})}function Ijs(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 Ajs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,o]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(!1),[m,y]=g.useState([]),[v,b]=g.useState(""),[x,w]=g.useState(null),{addItem:k}=cl(),_=()=>{o("{}"),l(""),u(""),f(""),h(!1),y([]),b(""),w(null)},C=P=>{_(),n(P)},T=async P=>{P.preventDefault();let F;try{F=JSON.parse(s)}catch{Qe.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Qe.error("Ground Truth must be valid JSON");return}let H;if(c.trim())try{H=JSON.parse(c)}catch{Qe.error("Expected Trajectory must be valid JSON");return}let q;if(d.trim())try{const B=JSON.parse(d);if(!Array.isArray(B)){Qe.error("Tool Mocks must be a JSON array");return}q=B}catch{Qe.error("Tool Mocks must be valid JSON");return}let V;if(v.trim())try{V=JSON.parse(v)}catch{Qe.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:F,groundTruth:D,expectedTrajectory:H,toolMocks:q,scorerIds:p?m:void 0,requestContext:V}),Qe.success("Item added successfully"),C(!1),r?.()}catch(B){const Z=Ijs(B);Z?w(Z):Qe.error(`Failed to add item: ${B instanceof Error?B.message:"Unknown error"}`)}},E=P=>{o(P),x?.field==="input"&&w(null)},I=P=>{l(P),x?.field==="groundTruth"&&w(null)},N=P=>{f(P),x?.field==="toolMocks"&&w(null)},A=()=>{C(!1)};return a.jsxs(ki,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[a.jsx(ki.Top,{children:"Add Item"}),a.jsxs(ki.Content,{children:[a.jsx(ki.Header,{children:a.jsx(ki.Heading,{children:"Add Item"})}),a.jsxs("form",{onSubmit:T,className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-input",required:!0,children:"Input (JSON)"}),a.jsx(br,{id:"input-item-input","aria-invalid":x?.field==="input"?!0:void 0,"aria-describedby":x?.field==="input"?Ui("item-input"):void 0,value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&a.jsx(TN,{name:"item-input",field:"input",errors:x.errors})]}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),a.jsx(br,{id:"input-item-ground-truth","aria-invalid":x?.field==="groundTruth"?!0:void 0,"aria-describedby":x?.field==="groundTruth"?Ui("item-ground-truth"):void 0,value:i,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&a.jsx(TN,{name:"item-ground-truth",field:"groundTruth",errors:x.errors})]}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),a.jsx(br,{id:"input-item-trajectory",value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),a.jsx(br,{id:"input-item-tool-mocks","aria-invalid":x?.field==="toolMocks"?!0:void 0,"aria-describedby":x?.field==="toolMocks"?Ui("item-tool-mocks"):void 0,value:d,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&a.jsx(TN,{name:"item-tool-mocks",field:"toolMocks",errors:x.errors})]}),a.jsx(BXt,{overrideEnabled:p,onOverrideEnabledChange:h,selectedScorerIds:m,onSelectedScorerIdsChange:y,disabled:k.isPending}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-request-context",children:"Request Context (JSON, optional)"}),a.jsx(br,{id:"input-item-request-context",value:v,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),type:"button",onClick:A,children:"Cancel"}),a.jsx(ae,{icon:a.jsx(Yr,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const oO=e=>JSON.stringify(e??null,null,2),Rjs=[{key:"input",title:"Input",icon:a.jsx(qD,{}),value:e=>oO(e.input)},{key:"groundTruth",title:"Ground Truth",icon:a.jsx(CS,{}),value:e=>oO(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:a.jsx(m_e,{}),value:e=>e.expectedTrajectory!=null?oO(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:a.jsx(xu,{}),value:e=>oO(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:a.jsx(CSt,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":oO(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:a.jsx(bl,{}),value:e=>e.requestContext!=null?oO(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:a.jsx(V1,{}),value:e=>oO(e.metadata)}];function JSe({item:e,diff:t}){return a.jsxs(a.Fragment,{children:[a.jsxs(Ft,{children:[a.jsx(Ft.Key,{children:"Dataset Id"}),a.jsx(Ft.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),a.jsx(Ft.Key,{children:"Version"}),a.jsxs(Ft.Value,{children:["v",e.datasetVersion]}),a.jsx(Ft.Key,{children:"Created"}),a.jsx(Ft.Value,{children:Fr(e.createdAt,"date-time")}),a.jsx(Ft.Key,{children:"Updated"}),a.jsx(Ft.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?Fr(e.updatedAt,"date-time"):"n/a"})]}),a.jsx("div",{className:"mt-3 grid gap-3",children:Rjs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:a.jsx(Rt.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function Pjs({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:o,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:p,setSelectedScorerIds:h,requestContextValue:m,setRequestContextValue:y,validationErrors:v,onSave:b,onCancel:x,isSaving:w}){return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mb-4",children:a.jsxs("h3",{className:"flex items-center gap-2 text-heading",children:[a.jsx(Bd,{className:"h-5 w-5"})," Edit Item"]})}),a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-input",required:!0,children:"Input (JSON)"}),a.jsx(br,{id:"input-item-input","aria-invalid":v?.field==="input"?!0:void 0,"aria-describedby":v?.field==="input"?Ui("item-input"):void 0,value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),v?.field==="input"&&a.jsx(TN,{name:"item-input",field:"input",errors:v.errors})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),a.jsx(br,{id:"input-item-ground-truth","aria-invalid":v?.field==="groundTruth"?!0:void 0,"aria-describedby":v?.field==="groundTruth"?Ui("item-ground-truth"):void 0,value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),v?.field==="groundTruth"&&a.jsx(TN,{name:"item-ground-truth",field:"groundTruth",errors:v.errors})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),a.jsx(br,{id:"input-item-trajectory",value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),a.jsxs("p",{className:"text-caption text-muted-foreground",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",a.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),a.jsx(br,{id:"input-item-tool-mocks","aria-invalid":v?.field==="toolMocks"?!0:void 0,"aria-describedby":v?.field==="toolMocks"?Ui("item-tool-mocks"):void 0,value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),v?.field==="toolMocks"&&a.jsx(TN,{name:"item-tool-mocks",field:"toolMocks",errors:v.errors})]}),a.jsx(BXt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:p,onSelectedScorerIdsChange:h,disabled:w}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-request-context",children:"Request Context (JSON, optional)"}),a.jsx(br,{id:"input-item-request-context",value:m,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-metadata",children:"Metadata (JSON, optional)"}),a.jsx(br,{id:"input-item-metadata",value:s,onChange:o,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[a.jsx(ae,{icon:a.jsx(Vn,{}),variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:x,disabled:w,children:"Cancel"})]})]})]})}const $js=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Mjs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:o,isLoading:i}=ef(),{data:l,isLoading:c}=ih(),{data:u,isLoading:d}=lh(),f=e==="agent"?Object.entries(o??{}).map(([y,v])=>({value:y,label:v.name??y})):e==="workflow"?Object.entries(l??{}).map(([y,v])=>({value:y,label:v.name??y})):e==="scorer"?Object.entries(u??{}).map(([y,v])=>({value:y,label:v.scorer?.config?.name??y})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=y=>{t(y),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{children:"Target Type"}),a.jsx(za,{options:$js,value:e,onValueChange:h,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{children:m}),a.jsx(za,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}const Djs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function Ljs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return Am(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mn,{children:"Request Context"}),a.jsx(W3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):a.jsx("div",{role:"alert",children:a.jsx(Jt,{variant:"destructive",children:"Failed to parse request context schema"})})}function sce({index:e,done:t,isLast:n,children:r}){return a.jsxs("li",{className:"flex gap-4",children:[a.jsxs("div",{className:"flex flex-col items-center",children:[a.jsx("span",{"aria-hidden":"true",className:W("flex size-6 shrink-0 items-center justify-center rounded-full border text-meta",t?"border-accent1 bg-accent1 text-white":"border-border text-muted-foreground"),children:e}),!n&&a.jsx("span",{"aria-hidden":"true",className:"mt-2 w-px flex-1 bg-border"})]}),a.jsx("div",{className:W("min-w-0 flex-1 space-y-3",!n&&"pb-4"),children:r})]})}function ZX({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:o,initialDescription:i,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,p]=g.useState(o??""),[h,m]=g.useState(i??""),[y,v]=g.useState(e??""),[b,x]=g.useState(t??null),[w,k]=g.useState(r??""),[_,C]=g.useState(s??""),[T,E]=g.useState(n??null),[I,N]=g.useState({}),[A,P]=g.useState(""),{triggerExperiment:F}=cl(),{data:D}=vv(y),{total:H}=oA(y,void 0,b),q=D?.requestContextSchema,V=D?.scorerIds??[],B=T===null&&V.length>0,Z=T??V,z=!!(q&&Object.keys(q).length>0),Y=!!(y&&w&&_&&f.trim()),L=F.isPending,R=[!f.trim()&&"name",!y&&"dataset",!_&&"target"].filter(Boolean),M=z?Object.values(I).some(le=>le!==void 0&&le!==""):A.trim().length>0,U=le=>{v(le),x(null),E(n??null),N({})},Q=()=>{p(o??""),m(i??""),v(e??""),x(t??null),k(r??""),C(s??""),E(n??null),N({}),P("")},te=()=>{if(z){const le=Object.entries(I).filter(([,J])=>J!==void 0&&J!=="");return le.length>0?Object.fromEntries(le):void 0}if(A.trim()){let le;try{le=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!le||typeof le!="object"||Array.isArray(le))throw new Error("Request Context must be a JSON object");return le}},K=async()=>{if(!y||!w||!_||!f.trim())return;let le;try{le=te()}catch(J){const re=J instanceof Error?J.message:"Request Context must be valid JSON";uu.error(re);return}try{const J=await F.mutateAsync({datasetId:y,name:f.trim(),description:h.trim()||void 0,targetType:w,targetId:_,scorerIds:Z.length>0?Z:void 0,version:b??void 0,requestContext:le});uu.success("Experiment triggered successfully"),c(!1),u?.(J.experimentId),Q()}catch(J){const re=J instanceof Error?J.message:"Failed to trigger experiment";uu.error(re)}},ee=()=>{L||(c(!1),Q())},ne=le=>{(le.metaKey||le.ctrlKey)&&le.key==="Enter"&&Y&&!L&&(le.preventDefault(),K())};return a.jsx(hs,{open:l,onOpenChange:ee,children:a.jsxs(rs,{ref:d,className:"w-[640px] max-w-[calc(100vw-2rem)] gap-0 p-0",onKeyDown:ne,children:[a.jsxs(ss,{className:"border-b border-border px-4 py-4",children:[a.jsx(Jr,{children:"Run experiment"}),a.jsx(Ms,{className:"not-sr-only text-caption text-muted-foreground",children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),a.jsxs(ys,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-4 py-5",children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{htmlFor:"experiment-name",children:"Name *"}),a.jsx(gr,{id:"experiment-name",value:f,onChange:le=>p(le.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:L})]}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{htmlFor:"experiment-description",children:"Description"}),a.jsx(Im,{id:"experiment-description",value:h,onChange:le=>m(le.target.value),placeholder:"Enter experiment description (optional)",disabled:L,rows:2})]})]}),a.jsxs("ol",{className:"list-none",children:[a.jsxs(sce,{index:1,done:!!y,children:[a.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{children:"Dataset"}),a.jsx(xkt,{value:y,onValueChange:U,container:d})]}),y&&a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{children:"Version"}),a.jsx(DXt,{datasetId:y,value:b,onValueChange:x,container:d})]})]}),y&&H!==void 0&&a.jsxs("p",{className:"text-meta text-muted-foreground",children:[H," ",H===1?"item":"items"]})]}),a.jsxs(sce,{index:2,done:!!_,children:[a.jsx(Mjs,{targetType:w,setTargetType:k,targetId:_,setTargetId:C,container:d}),w&&!_&&a.jsxs("p",{className:"text-meta text-muted-foreground",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),a.jsx(sce,{index:3,done:Z.length>0,isLast:!0,children:a.jsx(WX,{selectedScorers:Z,setSelectedScorers:E,disabled:L,container:d,helperText:B?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),a.jsxs(il,{children:[a.jsxs(Va,{className:"flex items-center gap-2 text-caption",children:[a.jsx(wr,{className:"size-4"}),"Request Context (JSON, optional)",M&&a.jsx(Mt,{size:"xs",variant:"blue",children:"set"})]}),a.jsx(qa,{className:"pt-3",children:z?a.jsx(Ljs,{requestContextSchema:q,onChange:N}):a.jsx(br,{value:A,onChange:P,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),a.jsxs(rc,{className:"items-center border-t border-border px-4 py-4 sm:justify-between",children:[a.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:R.length===0?a.jsxs(a.Fragment,{children:[a.jsx(Mt,{variant:"green",indicator:"dot",children:"Ready"}),a.jsxs("span",{className:"text-meta text-muted-foreground",children:[H??0," items · ",w," · ",Z.length," scorers"]})]}):a.jsxs(Mt,{variant:"neutral",indicator:"dot",children:["Missing ",R.join(", ")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:ee,disabled:L,children:"Cancel"}),a.jsx(ae,{variant:"primary",onClick:K,disabled:!Y||L,children:L?a.jsxs(a.Fragment,{children:[a.jsx(Cn,{className:"h-4 w-4"}),"Running..."]}):a.jsxs(a.Fragment,{children:["Run",a.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[a.jsx(Id,{size:"xs",children:Djs?"⌘":"Ctrl"}),a.jsx(Id,{size:"xs",children:"↵"})]})]})})]})]})]})})}const UXt=g.createContext(null);function Fjs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:o,children:i}){const l=zr(),u=sOe("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(v=>{l(`/experiments/${e}/items/${encodeURIComponent(v)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),p=g.useMemo(()=>u?r.findIndex(v=>v.itemId===u):-1,[r,u]),h=g.useMemo(()=>{if(p<=0)return;const v=r[p-1].itemId;return()=>d(v)},[p,r,d]),m=g.useMemo(()=>{if(p<0||p>=r.length-1)return;const v=r[p+1].itemId;return()=>d(v)},[p,r,d]);LXt({active:!!u,onPrevious:h,onNext:m,onClose:f});const y=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:o,currentItemId:u,openItem:d,close:f,goToPreviousItem:h,goToNextItem:m}),[e,t,n,r,s,o,u,d,f,h,m]);return a.jsx(UXt.Provider,{value:y,children:i})}function VXt(){const e=g.useContext(UXt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}const zjs=new Set(["itemId","id","status","input","tags","scores","startedAt"]);function qXt({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:o,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,emptyMessage:d="No results yet",selectedIds:f,onToggleSelect:p,onToggleSelectAll:h,sort:m,onSortChange:y}){const{Link:v,paths:b}=dn(),x=!!(f&&p),w=s.filter(V=>zjs.has(V.name)||i?.includes(V.name)),k=[x?"2rem":"",...w.map(V=>V.size)].filter(Boolean).join(" "),_=V=>w.some(B=>B.name===V),C=_("itemId")||_("id"),T=_("status"),E=_("input"),I=_("tags"),N=_("scores"),A=_("startedAt"),P=f?e.filter(V=>f.has(V.id)).length:0,F=e.length>0&&P===e.length,{containerRef:D,getRowProps:H}=Bc({count:e.length}),q=V=>i?.includes(V.name)?a.jsx(Oe.TopCell,{children:a.jsxs(v,{href:b.scorerLink(V.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[a.jsx(hb,{}),a.jsx("span",{className:"min-w-0 truncate",children:V.label})]})},V.name):V.name==="startedAt"&&y?a.jsx(Oe.SortableTopCell,{sortKey:"startedAt",sort:m?.key==="startedAt"?m.direction:void 0,onSortChange:y,children:V.label},V.name):a.jsx(Oe.TopCell,{children:V.label},V.name);return t?a.jsx(dc,{columns:k}):a.jsxs(Oe,{columns:k,className:"min-w-0",scrollRef:D,fit:"container",children:[a.jsxs(Oe.Top,{hasLeadingCell:x,children:[x&&(h?a.jsx(Oe.TopSelectCell,{checked:F?!0:P>0?"indeterminate":!1,onToggle:h,"aria-label":"Select all"}):a.jsx(Oe.TopCell,{children:" "})),x?a.jsx(Oe.TopCells,{colStart:2,children:w.map(q)}):w.map(q)]}),e.length===0?a.jsx(Oe.NoMatch,{message:d}):a.jsxs(a.Fragment,{children:[e.map((V,B)=>{const Z=!!V.error,z=V.id===n,Y=a.jsxs(a.Fragment,{children:[C&&a.jsxs(Oe.Cell,{className:"flex items-center gap-1.5 text-body-sm tracking-wide text-muted-foreground",children:[a.jsx("span",{children:V.itemId?.slice(0,8)??""}),Z&&a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx(KN,{role:"img","aria-label":"Error",className:"size-3.5 text-error"})}),a.jsx(kn,{children:Ujs(V.error)})]})]}),T&&a.jsx(Oe.Cell,{className:"flex items-center","data-testid":`result-status-${V.id}`,children:V.status?a.jsx(KMe,{status:V.status}):a.jsx("span",{className:"text-placeholder",children:"—"})}),E&&a.jsx(Oe.TextCell,{font:"mono",children:qjs(Vjs(V.input),200)}),I&&a.jsx(Oe.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${V.id}`,children:V.tags?.map(L=>a.jsx(qX,{value:L,className:"shrink-0"},L))}),N&&a.jsx(Oe.Cell,{children:a.jsx(Bjs,{scores:V.scores})}),A&&(V.startedAt?a.jsx(Oe.CreatedCell,{timestamp:V.startedAt}):a.jsx(Oe.Cell,{className:"text-placeholder",children:"—"})),i?.map(L=>{const M=o?.[V.itemId]?.find(U=>U.scorerId===L);return a.jsx(Oe.Cell,{className:"text-body-sm text-muted-foreground tabular-nums",children:M!=null?M.score.toFixed(3):"-"},L)})]});return x?a.jsxs(Oe.RowWrapper,{children:[a.jsx(Oe.SelectCell,{checked:f.has(V.id),onToggle:()=>p(V.id),"aria-label":`Select result ${V.itemId}`}),a.jsx(Oe.RowButton,{colStart:2,featured:z,"data-selected":z||void 0,onClick:()=>r(V.id),...H(B),children:Y})]},V.id):a.jsx(Oe.RowButton,{featured:z,"data-selected":z||void 0,onClick:()=>r(V.id),...H(B),children:Y},V.id)}),a.jsx(Oe.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Bjs({scores:e}){const t=Array.isArray(e)?e.map(n=>n.score).filter(n=>n!=null):Object.values(e??{});return t.length===0?a.jsx(je,{variant:"meta",tone:"faint",children:"—"}):a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(_t,{size:"xs",className:"text-muted-foreground",children:a.jsx(mv,{})}),a.jsx(je,{variant:"meta",tone:"muted",font:"mono",children:t[0].toFixed(2)}),t.length>1&&a.jsxs(Mt,{children:["+",t.length-1]})]})}function Ujs(e){return e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?e.message||"Error":typeof e=="string"&&e?e:"Error"}function Vjs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function qjs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Hjs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:o,hasNextPage:i,selectedIds:l,onToggleSelect:c,sort:u,onSortChange:d}){const{currentItemId:f,openItem:p,close:h}=VXt(),m=g.useMemo(()=>f?n.find(w=>w.itemId===f)?.id??null:null,[n,f]),{data:y}=A1(e,t),v=g.useMemo(()=>{if(!y)return[];const w=new Set;for(const k of Object.values(y))for(const _ of k)w.add(_.scorerId);return[...w].sort()},[y]),b=g.useCallback(w=>{const k=n.find(_=>_.id===w);k&&(k.itemId===f?h():p(k.itemId))},[n,f,h,p]),x=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"1fr"},{name:"tags",label:"Tags",size:"auto"},{name:"startedAt",label:"Created",size:"auto"},...v.map(w=>({name:w,label:w,size:"auto"}))],[v]);return a.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:a.jsx(qXt,{results:n,isLoading:r,featuredResultId:m,onResultClick:b,columns:x,scoresByItemId:y,scorerIds:v,setEndOfListElement:s,isFetchingNextPage:o,hasNextPage:i,selectedIds:l,onToggleSelect:c,sort:u,onSortChange:d})})}const qot={pending:{icon:a.jsx(R_,{className:"size-4 text-warning1"}),label:"Pending"},running:{icon:a.jsx(Cn,{size:"sm"}),label:"Running"},completed:{icon:a.jsx(gSt,{className:"size-4 text-muted-foreground"}),label:"Completed"},failed:{icon:a.jsx(VD,{className:"size-4 text-error"}),label:"Failed"}};function Wjs({status:e,className:t}){const n=qot[e]??qot.pending;return a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx("span",{tabIndex:0,className:W("flex shrink-0 items-center",t),children:n.icon})}),a.jsx(kn,{children:n.label})]})}function Zjs({children:e,className:t}){return a.jsx("div",{className:W("grid content-start gap-4 overflow-y-auto",t),children:e})}function Gjs({children:e,className:t}){return a.jsx("div",{className:"flex w-full overflow-y-auto",children:a.jsx("div",{className:W("grid w-full content-start gap-4 overflow-y-auto",t),children:e})})}function Qjs({children:e,className:t}){return a.jsx("div",{className:W("flex w-full flex-wrap items-center justify-between gap-3 gap-x-4",t),children:e})}const HXt=Object.assign(Gjs,{Content:Zjs,Toolbar:Qjs});function Yjs({children:e,className:t}){return a.jsx("div",{className:W("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const Kjs=e=>{const t=Xe();return wt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:$Kt,enabled:!!e})};function Xjs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${Fr(n,"date-time")}`}return`v${e}`}function Jjs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=CXt(e),o=(s??[]).map(i=>({value:String(i.version),label:`${Xjs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return a.jsxs(HXt.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[a.jsx("div",{}),a.jsx(wu,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:o,value:t??"",onValueChange:i=>r?.(i,n??"")}),a.jsx(wu,{label:"Version B",labelIsHidden:!0,name:"version-b",options:o,value:n??"",onValueChange:i=>r?.(t??"",i)}),a.jsx("div",{})]})}function WXt({children:e,className:t}){return a.jsx("div",{className:W("",t),children:e})}function eNs({date:e,className:t,preset:n="date"}){return a.jsx("div",{className:W("truncate text-body text-placeholder",t),children:Fr(e,n)})}function d2e(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function tNs({columns:e,isSelectionActive:t,children:n}){return a.jsx("div",{className:W("sticky top-0 z-10 mb-2 rounded-lg bg-card px-3"),children:a.jsx("div",{className:W("grid items-center gap-3 text-left text-meta tracking-widest text-muted-foreground uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:d2e(e)},children:n})})}function nNs({children:e,className:t}){return a.jsx("span",{className:W("py-3",t),children:e})}function rNs({id:e,className:t,isShortened:n=!0}){const r=n?e.slice(0,8):e;return a.jsx("div",{className:W("truncate py-[0.6rem] text-body text-placeholder",t),children:r})}function sNs({children:e}){return a.jsx("ul",{className:"grid content-start",children:e})}function oNs({children:e}){const t=g.useRef(null);return a.jsx("div",{ref:t,className:W("overflow-y-auto"),children:e})}function iNs({children:e,className:t}){return a.jsx("label",{className:W("flex h-full w-14 items-center justify-center rounded-lg text-caption hover:bg-fill-subtle",t),children:e})}function aNs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const o=a.jsx(r,{href:t,className:W("flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left","hover:bg-fill-subtle",vo.colors,hv.visible,n),children:e});return s==null?o:a.jsxs(On,{children:[a.jsx(Sn,{render:o}),a.jsx(kn,{children:s})]})}function lNs({children:e,message:t,className:n,type:r}){return!e&&!t?null:a.jsx("div",{className:W("grid border-t border-border",n),children:t?a.jsxs("p",{className:W("grid justify-center justify-items-center gap-2 p-5 text-center text-body text-muted-foreground","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?a.jsx(cu,{}):a.jsx(Hf,{})," ",t]}):e})}function cNs({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?a.jsxs("div",{ref:n,className:"mt-4 flex justify-center text-body text-muted-foreground opacity-50",children:[e&&r,!t&&!e&&s]}):null}function uNs({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return a.jsxs("div",{className:W("flex items-center justify-center gap-4 pt-4 text-body text-muted-foreground"),children:[a.jsxs("span",{children:["Page ",a.jsx("b",{children:e?e+1:"1"})]}),s&&a.jsxs("div",{className:W("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border [&>button]:p-1 [&>button]:px-2 [&>button]:text-muted-foreground [&>button]:transition-colors [&>button:hover]:text-foreground","[&_svg]:size-[1em] [&_svg]:text-muted-foreground"),children:[typeof e=="number"&&e>0&&a.jsxs("button",{onClick:r,children:[a.jsx(Cu,{}),"Previous"]}),t&&a.jsxs("button",{onClick:n,children:["Next",a.jsx(qf,{})]})]})]})}function dNs({children:e,className:t}){return a.jsx("div",{className:W("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function fNs({isSelected:e,children:t,columns:n}){return a.jsx("li",{className:W("flex overflow-hidden rounded-lg border border-transparent border-t-border py-[3px] pb-[2px] text-body text-foreground first:border-t-transparent","[&:last-child>button]:rounded-b-lg","[&.selected-row]:border [&.selected-row]:border-dashed [&.selected-row]:border-white/50 [&.selected-row]:pr-[3px] [&.selected-row]:first:border-t","[&:has(+.selected-row)]:rounded-b-none [&:has(+.selected-row)]:border-b-transparent","[.selected-row+&]:rounded-t-none",vo.colors,{"selected-row":e,"grid gap-3 px-3":n}),style:{gridTemplateColumns:d2e(n)},children:t})}function pNs({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:o,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=a.jsx("button",{...c,onClick:u,className:W("grid w-full items-center gap-3 rounded-lg px-3 text-left",vo.colors,hv.visible,{"bg-fill-hover":t,"hover:bg-fill-subtle":e&&!t&&!i},o),style:{gridTemplateColumns:d2e(s)},disabled:i,children:r});return l==null?d:a.jsxs(On,{children:[a.jsx(Sn,{render:d}),a.jsx(kn,{children:l})]})}function hNs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function mNs({status:e}){return e?a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("div",{className:W("relative flex h-full w-10 items-center justify-center bg-transparent"),children:a.jsx("div",{className:W("size-2 rounded-full",{"bg-green-600":["success","completed"].includes(e),"bg-red-700":["error","failed"].includes(e),"bg-yellow-500":["pending","running"].includes(e)})})})}),a.jsx(kn,{children:hNs(e)})]}):null}function gNs({children:e,isLoading:t,className:n}){return a.jsx("div",{className:W("truncate py-[0.6rem] text-body text-muted-foreground",n),children:t?a.jsx("div",{className:"h-4 animate-pulse rounded-md bg-muted text-transparent select-none"}):e})}const Hot={latest:"Latest version",deleted:"Deleted in this version"};function vNs({version:e,date:t,isLatest:n,isDeleted:r}){return a.jsxs(WXt,{className:W("grid grid-cols-[1fr_auto] pl-1"),children:[a.jsxs("div",{className:W("grid gap-1 leading-none text-muted-foreground",{"text-muted-foreground":n}),children:[a.jsxs("strong",{className:"text-body-sm",children:["v. ",e]}),a.jsx("em",{className:"text-caption text-placeholder",children:Fr(t,"date-time")})]}),(n||r)&&a.jsxs("div",{className:"flex items-center gap-1",children:[n&&a.jsx("span",{className:"inline-flex",role:"img","aria-label":Hot.latest,children:a.jsx(Mt,{variant:"blue",size:"sm",icon:a.jsx(R_,{})})}),r&&a.jsx("span",{className:"inline-flex",role:"img","aria-label":Hot.deleted,children:a.jsx(Mt,{variant:"red",size:"sm",icon:a.jsx(n_e,{})})})]})]})}const Mh=Object.assign(dNs,{Header:tNs,HeaderCol:nNs,Items:sNs,Scroller:oNs,Row:fNs,RowButton:pNs,Message:lNs,NextPageLoading:cNs,Pagination:uNs,Cell:WXt,TextCell:gNs,StatusCell:mNs,VersionCell:vNs,IdCell:rNs,DateCell:eNs,LinkCell:aNs,LabelCell:iNs}),yNs=[{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"}],V7={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:a.jsx(Yr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:a.jsx(Y2n,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:a.jsx(bSt,{}),tooltip:"Same in both versions"}};function oce({red:e=!1,tooltip:t}){return a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:"rounded focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-border-focus focus-visible:outline-solid",children:a.jsx(n_e,{className:W("h-5 w-5 text-muted-foreground/40",{"text-red-900":e})})}),a.jsx(kn,{children:t})]})}function ice({variant:e,version:t}){if(!e)return a.jsxs("span",{className:"text-body text-muted-foreground",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=V7[e];return a.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&a.jsxs("span",{className:"flex min-w-16 justify-end pr-3 text-body text-muted-foreground",children:["v. ",t]}),a.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:a.jsx(Mt,{variant:n,size:"xs",icon:r})})]})}function bNs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Wot({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function xNs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:o}){const{Link:i}=dn(),l=t>n;return a.jsx(Mh,{children:a.jsx(Mh.Scroller,{children:a.jsx(Mh.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=o.get(c),f=bNs(u,d),p=Wot({otherVersionExists:d!==void 0,status:f,isNewer:l}),h=Wot({otherVersionExists:u!==void 0,status:f,isNewer:!l});return a.jsxs(Mh.Row,{columns:yNs,children:[a.jsx(Mh.IdCell,{id:c,isShortened:!1}),f!=="same"?a.jsxs(a.Fragment,{children:[u?.datasetVersion?a.jsx(Mh.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?V7[p].tooltip:void 0,children:a.jsx(ice,{variant:p,version:u.datasetVersion})}):a.jsx(Mh.Cell,{className:"flex items-center justify-center",children:a.jsx(oce,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?a.jsx(Mh.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?V7[h].tooltip:void 0,children:a.jsx(ice,{variant:h,version:d.datasetVersion})}):a.jsx(Mh.Cell,{className:"flex items-center justify-center",children:a.jsx(oce,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):a.jsx(Mh.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:V7.same.tooltip,children:a.jsx(ice,{variant:"same",version:d?.datasetVersion})}),f==="changed"?a.jsx(Mh.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):a.jsx(Mh.Cell,{children:a.jsx(oce,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}const b_="targetType",vS="targetId";function ZXt({resetParams:e=[]}={}){const[t,n]=so(),r=e.join(","),s=t.get(b_),o=HX(s)?s:"",i=o?t.get(vS)??"":"",l=g.useCallback(d=>{n(f=>{const p=new URLSearchParams(f);d?p.set(b_,d):p.delete(b_),p.delete(vS);for(const h of r.split(","))h&&p.delete(h);return p},{replace:!0})},[n,r]),c=g.useCallback(d=>{n(f=>{const p=new URLSearchParams(f);d?p.set(vS,d):p.delete(vS);for(const h of r.split(","))h&&p.delete(h);return p},{replace:!0})},[n,r]),u=g.useCallback(()=>l(""),[l]);return{targetType:o,targetId:i,setTargetType:l,setTargetId:c,clear:u}}const rM=[Wr("/datasets")],wNs=["name","updatedAt"];function SNs(){const[e,t]=so(),{sort:n,onSortChange:r}=fk({searchParams:e,setSearchParams:t,allowedKeys:wNs}),s=g.useMemo(()=>n?{field:n.key,direction:n.direction==="asc"?"ASC":"DESC"}:void 0,[n]),[o,i]=g.useState(""),[l,c]=g.useState("all"),[u,d]=g.useState("all"),{targetType:f,targetId:p,setTargetType:h,setTargetId:m,clear:y}=ZXt(),{data:v=[],isLoading:b,error:x,isFetchingNextPage:w,hasNextPage:k,setEndOfListElement:_}=_6n({targetType:f,targetId:p},s),{data:C,isLoading:T,error:E}=a2e(),I=g.useMemo(()=>C?.experiments??[],[C?.experiments]),N=g.useMemo(()=>wTs(v),[v]),A=b||T,P=x||E,F=zr(),D=()=>{F("/datasets/new")},H=a.jsx(mK,{href:"/datasets/new",tooltip:"Create a dataset",children:"New dataset"});if(P&&_s(P))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(Qs,{variant:"fill"})]});if(P&&js(P))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(Fs,{variant:"fill",resource:"datasets"})]});if(P)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load datasets",descriptionSlot:P.message})]});if(v.length===0&&!A&&!f)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),headerActions:H,children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(STs,{onCreateClick:D})]});const q=l!=="all"||u!=="all"||o!==""||f!=="",V=()=>{i(""),c("all"),d("all"),y()};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),headerActions:H,actionRow:a.jsx(CTs,{search:o,onSearchChange:i,experimentFilter:l,onExperimentFilterChange:c,tagFilter:u,onTagFilterChange:d,tagOptions:N,targetType:f,onTargetTypeChange:h,targetId:p,onTargetIdChange:m,onReset:V,hasActiveFilters:q}),children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(bTs,{datasets:v,experiments:I,isLoading:A,search:o,experimentFilter:l,tagFilter:u,isFetchingNextPage:w,hasNextPage:k,setEndOfListElement:_,sort:n,onSortChange:r})]})}function kNs(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 ONs({item:e,itemId:t,fallback:n,onClose:r,...s}){const o=e?.id??t;return a.jsx(Rt,{open:!!o,onClose:r,title:`Dataset item ${o??""}`,children:e?a.jsx(_Ns,{item:e,onClose:r,...s},e.id):t?a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:r,tooltip:"Close detail panel"}),a.jsxs(Rt.Heading,{children:["Item",a.jsx(Rt.CopyId,{id:t})]})]}),n]}):null})}function _Ns({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:o}=dn(),{updateItem:i,deleteItem:l}=cl(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[p,h]=g.useState(""),[m,y]=g.useState(""),[v,b]=g.useState(""),[x,w]=g.useState(""),[k,_]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[E,I]=g.useState(""),[N,A]=g.useState(null),[P,F]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),y(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),I(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),F(!1),A(null))},[t?.id]);const D=n.findIndex(L=>L.id===t.id),H=D>0?()=>r(n[D-1].id):void 0,q=D>=0&&D<n.length-1?()=>r(n[D+1].id):void 0,V=async()=>{let L;try{L=JSON.parse(d)}catch{Qe.error("Input must be valid JSON");return}let R;if(p.trim())try{R=JSON.parse(p)}catch{Qe.error("Ground Truth must be valid JSON");return}let M;if(m.trim())try{M=JSON.parse(m)}catch{Qe.error("Metadata must be valid JSON");return}let U=null;if(v.trim())try{U=JSON.parse(v)}catch{Qe.error("Expected Trajectory must be valid JSON");return}let Q;if(x.trim())try{const ee=JSON.parse(x);if(!Array.isArray(ee)){Qe.error("Tool Mocks must be a JSON array");return}Q=ee}catch{Qe.error("Tool Mocks must be valid JSON");return}else Q=[];let te;if(E.trim())try{te=JSON.parse(E)}catch{Qe.error("Request Context must be valid JSON");return}let K;k?K=C:t.scorerIds!==void 0&&(K=null);try{const ee=await i.mutateAsync({datasetId:e,itemId:t.id,input:L,groundTruth:R,metadata:M,expectedTrajectory:U,toolMocks:Q,scorerIds:K,requestContext:te});Qe.success("Item updated successfully"),_(ee.scorerIds!==void 0),T(ee.scorerIds??[]),u(!1),A(null)}catch(ee){const ne=kNs(ee);ne?A(ne):Qe.error(`Failed to update item: ${ee instanceof Error?ee.message:"Unknown error"}`)}},B=()=>{f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),y(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),I(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},Z=L=>{f(L),N?.field==="input"&&A(null)},z=L=>{h(L),N?.field==="groundTruth"&&A(null)},Y=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Qe.success("Item deleted successfully"),F(!1),s()}catch(L){Qe.error(`Failed to delete item: ${L instanceof Error?L.message:"Unknown error"}`)}};return a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:s,tooltip:"Close detail panel"}),a.jsxs(Rt.Heading,{children:["Item",a.jsx(Rt.CopyId,{id:t.id})]}),a.jsxs(Rt.HeaderActions,{children:[!c&&a.jsxs(a.Fragment,{children:[a.jsx(ae,{render:a.jsx(o,{href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`}),size:"sm",variant:"ghost",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:a.jsx(h_e,{})}),a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{size:"sm",variant:"ghost",tooltip:"Open actions menu","aria-label":"Open actions menu",children:a.jsx(U1,{})})}),a.jsxs(pt.Content,{align:"end",className:"w-48",children:[a.jsxs(pt.Item,{onSelect:()=>u(!0),children:[a.jsx(Bd,{}),"Edit"]}),a.jsxs(pt.Item,{onSelect:()=>F(!0),className:"text-red-500 focus:text-red-400",children:[a.jsx(Ni,{}),"Delete Item"]})]})]})]}),a.jsx(Rt.NextPrevNav,{onPrevious:H,onNext:q,previousLabel:"Go to previous item",nextLabel:"Go to next item"})]})]}),a.jsx(Rt.Content,{children:c?a.jsx(Pjs,{inputValue:d,setInputValue:Z,groundTruthValue:p,setGroundTruthValue:z,metadataValue:m,setMetadataValue:y,trajectoryValue:v,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:_,selectedScorerIds:C,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:I,validationErrors:N,onSave:V,onCancel:B,isSaving:i.isPending}):a.jsx(JSe,{item:t})}),a.jsx($t,{open:P,onOpenChange:F,children:a.jsxs($t.Content,{children:[a.jsxs($t.Header,{children:[a.jsx($t.Title,{children:"Delete Item"}),a.jsx($t.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),a.jsxs($t.Footer,{children:[a.jsx($t.Cancel,{children:"Cancel"}),a.jsx($t.Action,{onClick:Y,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function CNs(){const{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:s,close:o}=zXt(),i=g.useMemo(()=>r?t.find(d=>d.id===r):void 0,[t,r]),{data:l,isLoading:c}=zKt(i?"":e,!i&&r?r:""),u=i??l??void 0;return a.jsx(ONs,{datasetId:e,item:u,itemId:r,fallback:n||c?a.jsx(Rt.LoadingData,{}):a.jsxs(Rt.NoData,{children:['No loaded item "',r,'".']}),items:t,onItemChange:s,onClose:o})}function nB({crumbs:e,children:t}){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:e}),children:[a.jsx("h1",{className:"sr-only",children:"Dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:t})]})}function ENs(){const{datasetId:e,itemId:t}=fr(),n=[Wr("/datasets"),{...FG,to:`/datasets/${encodeURIComponent(e)}`},...t?[{id:"dataset-items",label:"Items"},{id:"dataset-item",label:FCe(t)}]:[]],r=zr(),[s,o]=so(),{activeVersion:i,handleVersionChange:l}=u2e(s,o),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[p,h]=g.useState(!1),[m,y]=g.useState(!1),{data:v,error:b,isLoading:x}=vv(e),{data:w=[],isLoading:k}=oA(e,void 0,i),_=!k&&w.length===0;if(x)return null;if(b&&_s(b))return a.jsx(nB,{crumbs:n,children:a.jsx(Qs,{})});if(b&&js(b))return a.jsx(nB,{crumbs:n,children:a.jsx(Fs,{resource:"datasets"})});if(b&&zA(b)||!x&&!b&&!v)return a.jsx(nB,{crumbs:n,children:a.jsx(un,{titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:a.jsx(ae,{render:a.jsx(ml,{to:"/datasets"}),icon:a.jsx(Cu,{}),children:"Back to Datasets"})})});if(b)return a.jsx(nB,{crumbs:n,children:a.jsx(un,{tone:"error",titleSlot:"Failed to load dataset",descriptionSlot:b instanceof Error?b.message:"An unexpected error occurred. Please try again."})});const C=E=>{r(`/experiments/${E}`)},T=()=>{r("/datasets")};return a.jsxs(Ejs,{datasetId:e,items:w,isLoadingItems:k,children:[a.jsxs("div",{className:"h-full",children:[a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{children:a.jsx(jjs,{datasetId:e,onAddItemClick:()=>f(!0),belowToolbarSlot:a.jsx(Njs,{datasetId:e}),leftSlot:a.jsx("span",{className:"mr-3 text-caption whitespace-nowrap text-muted-foreground",children:v?.createdAt?`Created ${Fr(v.createdAt,"date-time")}`:""}),rightSlot:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ae,{render:a.jsx(ml,{to:`/experiments?dataset=${e}`}),icon:a.jsx(lG,{}),children:"View experiments"}),a.jsx(DXt,{datasetId:e,value:i,onValueChange:l,currentVersion:v?.version,className:"w-36"}),_?a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("span",{className:"cursor-not-allowed",children:a.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:a.jsx(ae,{variant:"primary",icon:a.jsx(bu,{}),children:"Run Experiment"})})})}),a.jsx(kn,{children:"Add items to the dataset before running an experiment"})]}):a.jsx(ae,{variant:"primary",onClick:()=>u(!0),icon:a.jsx(bu,{}),children:"Run Experiment"}),a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{size:"lg","aria-label":"Dataset actions menu",children:a.jsx(U1,{})})}),a.jsxs(pt.Content,{align:"end",className:"w-48",children:[a.jsxs(pt.Item,{onSelect:()=>{r(`/datasets/${e}/edit`)},children:[a.jsx(Bd,{})," Edit Dataset"]}),a.jsxs(pt.Item,{onSelect:()=>y(!0),children:[a.jsx(Ju,{})," Duplicate Dataset"]}),a.jsxs(pt.Item,{onSelect:()=>h(!0),className:"text-red-500 focus:text-red-400",children:[a.jsx(Ni,{})," Delete Dataset"]})]})]})]})})})]}),a.jsx(CNs,{})]}),a.jsx(ZX,{initialDatasetId:e,initialDatasetVersion:i??void 0,open:c,onOpenChange:u,onSuccess:C},`${e}:${i??"latest"}`),a.jsx(Ajs,{datasetId:e,open:d,onOpenChange:f}),v&&a.jsx(VTs,{open:m,onOpenChange:y,sourceDatasetId:v.id,sourceDatasetName:v.name,sourceDatasetDescription:v.description,sourceDatasetTargetType:v.targetType}),v&&a.jsx(ZTs,{open:p,onOpenChange:h,datasetId:v.id,datasetName:v.name,onSuccess:T})]})}const GXt=[Wr("/datasets"),FG,{id:"dataset-edit",label:"Edit dataset"}];function ace({children:e}){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:GXt}),children:[a.jsx("h1",{className:"sr-only",children:"Edit dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:e})]})}function TNs(){const{datasetId:e}=fr(),t=zr(),{data:n,error:r,isLoading:s}=vv(e),o=()=>{t(`/datasets/${e}`)};return s?null:r&&_s(r)?a.jsx(ace,{children:a.jsx(Qs,{})}):r&&js(r)?a.jsx(ace,{children:a.jsx(Fs,{resource:"datasets"})}):r||!n?a.jsx(ace,{children:a.jsx(un,{tone:"error",titleSlot:"Failed to load dataset",descriptionSlot:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:GXt}),children:[a.jsx("h1",{className:"sr-only",children:"Edit dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[a.jsx(Ap,{className:"mb-6 p-0",children:a.jsxs(Ap.Column,{children:[a.jsxs(Ap.Title,{children:[a.jsx(nv,{})," Edit dataset"]}),a.jsx(Ap.Description,{children:n.name})]})}),a.jsx(ku,{className:"p-4",children:a.jsx(WTs,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema,scorerIds:n.scorerIds},onSuccess:o,onCancel:o})})]})})]})}function Zot(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function Got(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:a.jsxs("span",{className:"flex w-full items-center gap-2",children:[a.jsxs("span",{children:[a.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",Fr(r,"date-time")]}),n.isLatest?a.jsx(Mt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function Qot(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function jNs(){const{datasetId:e,itemId:t}=fr(),[n,r]=so(),s=[Wr("/datasets"),FG,{id:"dataset-item",label:FCe(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:"dataset-item-versions",label:"Item Version History"}],o=Qot(n.get("version")),i=Qot(n.get("compare")),l=n.get("view")==="diff",{data:c,error:u}=vv(e??""),{data:d,isLoading:f}=eTs(e??"",t??""),p=(o!=null?d?.find(T=>T.datasetVersion===o):void 0)??d?.[0],h=p?.datasetVersion??null,m=i!=null&&i!==h?i:null,{data:y,isLoading:v}=tTs(e??"",t??"",m??0,c?.version),b=(T,E)=>r(I=>{const N=new URLSearchParams(I);return E==null?N.delete(T):N.set(T,String(E)),N},{replace:!0});if(u&&_s(u))return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(Qs,{variant:"fill"})]});if(u&&js(u))return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(Fs,{variant:"fill",resource:"datasets"})]});if(!e||!t)return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsx("div",{className:"py-5 text-center text-muted-foreground",children:a.jsx("p",{children:"Item not found."})})})]});const x=!!(p&&y),w=l&&x,k=p?Zot(p,e):null,_=y?Zot(y,e):null,C=(p?.datasetVersion??0)<(y?.datasetVersion??0);return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:s}),headerActions:x&&a.jsx(ae,{variant:"ghost",size:"sm",onClick:()=>b("view",l?null:"diff"),children:l?a.jsxs(a.Fragment,{children:[a.jsx(s_e,{})," Default View"]}):a.jsxs(a.Fragment,{children:[a.jsx(kMn,{})," Diff View"]})}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2",children:[a.jsxs(ku,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx($q,{children:a.jsx(Yot,{name:"version",value:h!=null?String(h):"",options:Got(d??[],m!=null?new Set([m]):void 0),onValueChange:T=>b("version",Number(T))})}),a.jsx(lv,{className:"grid content-start gap-5 overflow-y-auto",children:f?a.jsx("div",{className:"text-body text-muted-foreground",children:"Loading..."}):k?a.jsx(JSe,{item:k,diff:w&&_?{against:_,side:C?"a":"b"}:void 0}):a.jsx("div",{className:"text-body text-muted-foreground",children:"Item data not available"})})]}),a.jsxs(ku,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx($q,{children:a.jsx(Yot,{name:"compare",value:m!=null?String(m):"",placeholder:"Select a version to compare",options:Got(d??[],h!=null?new Set([h]):void 0),onValueChange:T=>b("compare",Number(T))})}),a.jsx(lv,{className:"grid content-start gap-5 overflow-y-auto",children:m==null?a.jsx(un,{className:"h-full",titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):v?a.jsx("div",{className:"text-body text-muted-foreground",children:"Loading..."}):_?a.jsx(JSe,{item:_,diff:w&&k?{against:k,side:C?"b":"a"}:void 0}):a.jsxs("div",{className:"text-body text-muted-foreground",children:["Version ",m," not found"]})})]})]})]})}function Yot({name:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return a.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[a.jsx(h_e,{className:"size-4 opacity-50"}),a.jsxs(Po,{name:e,value:t,onValueChange:s,children:[a.jsx(Mo,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:a.jsx($o,{placeholder:r,className:"flex-1"})}),a.jsx(Do,{children:n.map(o=>a.jsx(Vr,{value:o.value,disabled:o.disabled,children:o.label},o.value))})]})]})}const rB=[Wr("/datasets"),FG,{id:"dataset-versions",label:"Versions"}];function NNs(){const{datasetId:e}=fr(),[t]=so(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=zr(),{data:s,error:o}=vv(e??""),i=oA(e??"",void 0,n[0]??null),l=oA(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const y of[...c,...u])m.has(y.id)||m.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...m.values()].sort((y,v)=>v.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),p=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(o&&_s(o))return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:rB}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(Qs,{variant:"fill"})]});if(o&&js(o))return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:rB}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(Fs,{variant:"fill",resource:"datasets"})]});if(!e||n.length<2)return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:rB}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsx("div",{className:"py-5 text-center text-muted-foreground",children:a.jsx("p",{children:"Select at least two versions to compare."})})})]});const h=(m,y)=>{r(`/datasets/${e}/versions?ids=${m},${y}`,{replace:!0})};return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:rB}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:a.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-4",children:[a.jsxs(Ap,{children:[a.jsxs(Ap.Column,{children:[a.jsxs(Ap.Title,{children:[a.jsx(CDn,{})," Compare Dataset Versions"]}),a.jsx(Ap.Description,{children:a.jsxs(Pd,{children:[a.jsx(h_e,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),a.jsx(Ap.Column,{children:a.jsx(ae,{render:a.jsx(ml,{to:`/datasets/${e}`}),icon:a.jsx(Cu,{}),children:"Back to Dataset"})})]}),a.jsx(Yjs,{children:a.jsxs(HXt,{children:[a.jsx(Jjs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:h}),a.jsx(xNs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p})]})})]})})]})}const INs=[Wr("/datasets"),{id:"dataset-new",label:"Create new dataset"}];function ANs(){const e=zr(),[t]=so(),n=t.get("targetType"),r=HX(n)?n:void 0,s=t.get("targetIds"),o=r&&s?s.split(",").map(l=>l.trim()).filter(Boolean):void 0,i=l=>{e(`/datasets/${l}`)};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:INs}),children:[a.jsx("h1",{className:"sr-only",children:"Create new dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[a.jsx(Ap,{className:"mb-6 p-0",children:a.jsxs(Ap.Column,{children:[a.jsxs(Ap.Title,{children:[a.jsx(nv,{})," Create new dataset"]}),a.jsx(Ap.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),a.jsx(ku,{className:"p-4",children:a.jsx(LTs,{targetType:r,targetIds:o,onSuccess:i,onCancel:()=>{e(-1)}})})]})})]})}function QXt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:o}=cl(),i=async()=>{try{await o.mutateAsync(n),Qe.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Qe.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return a.jsx($t,{open:e,onOpenChange:t,children:a.jsxs($t.Content,{children:[a.jsxs($t.Header,{children:[a.jsx($t.Title,{children:"Delete Experiment"}),a.jsxs($t.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),a.jsxs($t.Footer,{children:[a.jsx(ae,{icon:a.jsx(Ni,{}),variant:"primary",size:"lg",onClick:i,disabled:o.isPending,children:o.isPending?"Deleting...":"Delete"}),a.jsx($t.Cancel,{children:"Cancel"})]})]})})}const RNs="minmax(9rem,1fr)",PNs="minmax(8rem,16rem)",$Ns="1fr",MNs="auto auto auto auto auto auto auto",Hv={experiment:"Experiment",description:"Description",dataset:"Dataset",target:"Target",status:"Status",items:"Items",succeeded:"Processed",failed:"Errored",review:"Review",date:"Date"},DNs={completed:"neutral",running:"yellow",failed:"red",pending:"neutral"},LNs={completed:"Run completed",running:"Run in progress",failed:"Run failed",pending:"Run queued"};function YXt(e){const t=g0(e.id)??e.id;return e.name||`Experiment #${t}`}const FNs=60;function zNs({experiment:e}){return a.jsx("span",{className:"block min-w-0 truncate text-left text-muted-foreground",children:YXt(e)})}function BNs({experiment:e}){const t=e.description;if(!t)return a.jsx("span",{className:"text-placeholder",children:"—"});const n=a.jsx("span",{className:"block min-w-0 truncate text-left text-muted-foreground",children:t});return t.length<=FNs?n:a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:n}),a.jsx(kn,{children:t})]})}function KXt(){const{data:e}=ef(),{data:t}=ih(),{data:n}=lh(),{data:r}=nE();return{agents:e,workflows:t,scorers:n,processors:r}}const XXt={agent:Pi,workflow:yl,scorer:hb,processor:kO},JXt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},UNs="External (caller-run)";function eJt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:o,targetId:i}=e;if(!i)return UNs;switch(o){case"agent":return t?.[i]?.name??i;case"workflow":return n?.[i]?.name??i;case"scorer":return r?.[i]?.scorer?.config?.name??i;case"processor":return s?.[i]?.name??i;default:return i}}function VNs({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,o=e.failedCount??0,i=e.totalItems??0;return a.jsxs(a.Fragment,{children:[a.jsx(Oe.Cell,{children:a.jsx(zNs,{experiment:e})}),a.jsx(Oe.Cell,{children:a.jsx(BNs,{experiment:e})}),t!==void 0&&a.jsx(Oe.TextCell,{children:t}),a.jsx(Oe.Cell,{children:a.jsx(qNs,{experiment:e})}),a.jsx(Oe.Cell,{children:a.jsx(Mt,{variant:DNs[r]??"neutral",indicator:"dot",children:LNs[r]??r})}),a.jsx(Oe.TextCell,{className:"text-center",children:i}),a.jsx(Oe.TextCell,{className:"text-center",children:s}),a.jsx(Oe.TextCell,{className:"text-center",children:a.jsx("span",{className:o>0?"text-accent2":"",children:o})}),a.jsx(Oe.Cell,{className:"text-center",children:a.jsx(HNs,{review:n})}),a.jsx(Oe.TextCell,{children:Fr(e.createdAt,"date")??"—"})]})}function qNs({experiment:e}){const t=KXt(),n=eJt(e,t),r=e.targetId?e.targetType:null,s=r?XXt[r]:null;return a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&a.jsx("span",{className:"flex text-muted-foreground",role:"img","aria-label":JXt[r],children:a.jsx(s,{})}),a.jsx("span",{className:r?"truncate":"truncate text-placeholder",children:n})]})}function HNs({review:e}){if(!e)return a.jsx("span",{className:"text-placeholder",children:"—"});const t=e.needsReview+e.complete;return t===0?a.jsx("span",{className:"text-placeholder",children:"—"}):e.needsReview>0?a.jsxs(Mt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):a.jsxs(Mt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const tJt=`${RNs} ${PNs} ${$Ns} ${MNs}`,Kot=`${tJt} auto`,WNs=[{label:Hv.experiment},{label:Hv.description},{label:Hv.dataset},{label:Hv.target},{label:Hv.status,sortKey:"status"},{label:Hv.items,className:"text-center"},{label:Hv.succeeded,className:"text-center"},{label:Hv.failed,className:"text-center"},{label:Hv.review,className:"text-center"},{label:Hv.date,sortKey:"createdAt"}],nJt=e=>e.stopPropagation();function ZNs({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:s,children:o}){const{paths:i,Link:l}=dn(),c=g.useRef(null);return a.jsxs(Oe.RowWrapper,{...t,onSelectRow:n??(()=>c.current?.click()),children:[n?a.jsx(Oe.RowButton,{colEnd:-2,featured:r,tabIndex:-1,onClick:u=>{u.stopPropagation(),n()},children:o}):a.jsx(Oe.RowLink,{ref:c,colEnd:-2,to:i.experimentLink(e.id),LinkComponent:l,tabIndex:-1,onClick:nJt,children:o}),a.jsx(Oe.ActionsCell,{className:"pl-2",children:a.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:u=>{u.stopPropagation(),s()},children:a.jsx(Ni,{className:"size-4"})})})]})}function GNs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:o="all",datasetFilter:i="all",selection:l,onSelectExperiment:c,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:p,setEndOfListElement:h,sort:m,onSortChange:y}){const v=l!==void 0,b=g.useMemo(()=>{const N=new Map;return t?.forEach(A=>N.set(A.id,A.name)),N},[t]),x=g.useMemo(()=>m?e:[...e].sort((N,A)=>{const P=N.createdAt?new Date(N.createdAt).getTime():0;return(A.createdAt?new Date(A.createdAt).getTime():0)-P}),[e,m]),w=g.useMemo(()=>{const N=s.toLowerCase();return x.filter(A=>{const P=A.datasetId?b.get(A.datasetId)??"":"",F=!N||A.id.toLowerCase().includes(N)||(A.name??"").toLowerCase().includes(N)||P.toLowerCase().includes(N)||(A.targetId??"").toLowerCase().includes(N),D=o==="all"||A.status===o,H=i==="all"||A.datasetId===i;return F&&D&&H})},[x,s,b,o,i]),{containerRef:k,getRowProps:_}=Bc({count:w.length,global:d}),[C,T]=g.useState(null);if(r)return a.jsx(dc,{columns:Kot});const E=v?`auto ${tJt}`:Kot,I=WNs.map(N=>N.sortKey&&y?a.jsx(Oe.SortableTopCell,{className:N.className,sortKey:N.sortKey,sort:m?.key===N.sortKey?m.direction:void 0,onSortChange:y,children:N.label},N.label):a.jsx(Oe.TopCell,{className:N.className,children:N.label},N.label));return a.jsxs(Oe,{columns:E,scrollRef:k,children:[a.jsx(Oe.Top,{hasLeadingCell:v,children:v?a.jsxs(a.Fragment,{children:[a.jsx(Oe.TopCell,{children:" "}),a.jsx(Oe.TopCells,{colStart:2,children:I})]}):a.jsxs(a.Fragment,{children:[I,a.jsx(Oe.TopCell,{"aria-hidden":!0,children:null})]})}),w.map((N,A)=>{const P=N.datasetId?b.get(N.datasetId)??g0(N.datasetId)??N.datasetId:"—",F=a.jsx(VNs,{experiment:N,datasetName:P,review:n?.get(N.id)});if(!l)return a.jsx(ZNs,{experiment:N,rowProps:_(A),onSelect:c?()=>c(N):void 0,featured:u===N.id,onDelete:()=>T(N),children:F},N.id);const D=l.selectedExperimentIds.includes(N.id),H=()=>l.onToggleSelection(N.id);return a.jsxs(Oe.RowWrapper,{..._(A),onSelectRow:H,children:[a.jsx(Oe.SelectCell,{checked:D,onToggle:H,"aria-label":`Select experiment ${N.id}`}),a.jsx(Oe.RowButton,{colStart:2,featured:D,tabIndex:-1,onClick:nJt,children:F})]},N.id)}),a.jsx(Oe.NextPageLoading,{isLoading:f,hasMore:p,setEndOfListElement:h}),C&&a.jsx(QXt,{open:!0,onOpenChange:N=>{N||T(null)},experimentId:C.id,experimentName:C.name??void 0})]})}const QNs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function YNs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const KNs=({onRunExperiment:e})=>a.jsx(un,{titleSlot:"No Experiments yet",descriptionSlot:a.jsxs(a.Fragment,{children:["Run an experiment from a dataset to evaluate ",a.jsx("br",{}),"your agents and workflows."]}),actionSlot:a.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&a.jsx(ae,{variant:"primary",onClick:e,icon:a.jsx(bu,{}),children:"Run Experiment"}),a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Ts,{}),children:"Experiments Documentation"})]}),variant:"fill"});function XNs({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:o,datasetOptions:i,targetType:l,onTargetTypeChange:c,targetId:u,onTargetIdChange:d,onReset:f,hasActiveFilters:p,onRunClick:h,runTooltip:m="Run an experiment",onCompareClick:y,selection:v}){const b=v?.selectedCount===2&&!v.compareDisabledReason;return a.jsxs(Gn,{children:[a.jsxs(Gn.Start,{children:[a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),a.jsx(wu,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...QNs],value:n,onValueChange:r,className:"whitespace-nowrap"}),a.jsx(wu,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:o,className:"whitespace-nowrap"}),a.jsx(AXt,{targetType:l,targetId:u,onTargetTypeChange:c,onTargetIdChange:d}),f&&p&&a.jsx(ae,{onClick:f,size:"sm",variant:"default",icon:a.jsx(Gt,{}),children:"Reset"})]}),v?a.jsx(Gn.End,{children:a.jsxs(zl,{className:"whitespace-nowrap",children:[a.jsxs(Fp,{className:"gap-2",children:[a.jsxs(Mt,{size:"sm",variant:v.selectedCount<2?"red":"green",children:[v.selectedCount," / 2"]}),"selected",v.compareDisabledReason&&a.jsxs("span",{className:"text-accent2",children:["· ",v.compareDisabledReason]})]}),a.jsx(ae,{variant:"primary",disabled:!b,onClick:v.onExecuteCompare,icon:a.jsx(z8e,{}),children:"Compare Experiments"}),a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:v.onCancelSelection,children:"Cancel"})]})}):a.jsxs(Gn.End,{children:[y&&a.jsx(ae,{onClick:y,tooltip:"Select two experiments of the same dataset to compare",icon:a.jsx(z8e,{}),children:"Compare"}),h&&a.jsx(ae,{onClick:h,tooltip:m,variant:"primary",icon:a.jsx(bu,{}),children:"Run Experiment"})]})]})}const JNs={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Xot=e=>e?e instanceof Date?e.toISOString():e:null,Jot=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},eit=(e,t,n)=>{if(!e)return JNs;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:Xot(t?.startedAt),completedAt:Xot(t?.completedAt),scores:Object.entries(e.scores).map(([s,o])=>({scorerId:s,value:o,reason:r.get(s)??null})).sort((s,o)=>s.scorerId.localeCompare(o.scorerId))}},eIs=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:o,contenderScores:i})=>{if(!e)return[];const l=Jot(r),c=Jot(s);return e.items.map(u=>{const d=eit(u.results[t],l.get(u.itemId),o?.[u.itemId]),f=eit(u.results[n],c.get(u.itemId),i?.[u.itemId]),p={};for(const h of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(v=>v.scorerId===h)?.value??null,y=f.scores.find(v=>v.scorerId===h)?.value??null;p[h]=m!=null&&y!=null?y-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:p}})};function TO({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return a.jsxs(il,{defaultOpen:r,className:"grid gap-2",children:[a.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[a.jsxs(Va,{className:W("flex items-center gap-1.5 text-subheading [&>svg]:size-4",n==="negative"?"text-negative1":"text-foreground"),children:[a.jsx(wr,{}),e]}),t]}),a.jsx(qa,{role:"region","aria-label":e,children:s})]})}function tit({label:e,value:t}){return t==null?null:a.jsx(TO,{title:e,defaultOpen:!1,children:a.jsx("pre",{className:"max-h-40 overflow-auto rounded-md bg-card p-3 text-caption whitespace-pre-wrap text-muted-foreground",children:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function rJt({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-muted-foreground";return a.jsxs("span",{className:W("inline-flex min-w-20 items-center gap-1 text-body tabular-nums",t),children:[a.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?a.jsx(t_e,{className:"size-3.5"}):e<0?a.jsx(lSt,{className:"size-3.5"}):null]})}function sJt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:o}=dn();return a.jsxs("div",{className:"grid gap-1 rounded-lg bg-background px-3 py-2",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsxs(s,{href:o.scorerLink(e),"aria-label":`Open ${e}`,className:"flex min-w-0 items-center gap-1.5 text-subheading text-foreground hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[a.jsx(hb,{}),a.jsx("span",{className:"min-w-0 truncate",children:e})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-body text-muted-foreground tabular-nums",children:t!=null?t.toFixed(2):"-"}),n!=null&&a.jsx(rJt,{delta:n})]})]}),r&&a.jsx("p",{className:"text-body text-muted-foreground",children:r})]})}function nit(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function tIs(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Zd(t)??null}const nIs=W(ir,"max-h-[30vh] overflow-y-auto rounded-xl p-4 text-body break-all whitespace-pre-wrap text-muted-foreground");function rit({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],o=tIs(s);if(r)return a.jsx("div",{className:"flex h-32 items-center justify-center",children:a.jsx(Cn,{})});if(!s.present)return a.jsx("p",{className:"py-5 text-center text-body text-muted-foreground",children:"Not present in this experiment"});const i=nit(s.output);return a.jsxs("div",{className:"grid content-start gap-5",children:[o&&a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsxs("p",{className:"flex items-center justify-end gap-1.5 text-body text-muted-foreground [&>svg]:size-3.5",children:[a.jsx(R_,{}),a.jsx(je,{as:"span",variant:"body",font:"mono",children:o})]})}),a.jsx(kn,{children:"Run duration"})]}),s.error?a.jsx(TO,{title:"Error",tone:"negative",actions:a.jsx(Oo,{content:s.error.message}),children:a.jsx("p",{className:"rounded-xl border border-negative1/40 bg-negative1/5 p-4 text-body break-words text-muted-foreground",children:s.error.message})}):a.jsx(TO,{title:"Output",actions:a.jsx(Oo,{content:i}),children:a.jsx("pre",{className:nIs,children:i})}),s.scores.length>0&&a.jsx(TO,{title:"Scores",children:a.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>a.jsx(sJt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&a.jsx(TO,{title:"Comment",defaultOpen:!1,children:a.jsx("p",{className:"text-body text-muted-foreground",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&a.jsx(TO,{title:"Metadata",defaultOpen:!1,children:a.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>a.jsxs("div",{className:"flex items-start justify-between gap-4 text-body",children:[a.jsx("dt",{className:"text-muted-foreground",children:l}),a.jsx("dd",{className:"break-all text-foreground",children:a.jsx(je,{as:"span",variant:"body",font:"mono",children:nit(c)})})]},l))})})]})}const rIs={baseline:"Baseline",contender:"Contender"},sIs={baseline:"purple",contender:"blue"},oIs="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function sit({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:o,paths:i}=dn(),l=rIs[e],c=t?g0(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return a.jsxs("div",{className:"grid content-start gap-3",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(Mt,{variant:sIs[e],size:"xs",children:l}),t&&a.jsx(ae,{render:a.jsx(o,{href:`/experiments/${t.id}`}),size:"sm","aria-label":`Open experiment ${t.name||c}`,children:a.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&a.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-caption text-muted-foreground",children:[t.name&&a.jsxs(Pd,{children:[a.jsx(AA,{})," ",c]}),t.targetType==="agent"&&t.targetId?a.jsxs(o,{href:i.agentLink(t.targetId),className:oIs,children:[a.jsx(Pi,{}),a.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):a.jsxs(Pd,{children:[a.jsx(ZSt,{})," ",t.targetId]}),a.jsx("span",{className:W(s&&"text-accent6"),children:a.jsxs(Pd,{children:[a.jsx(C3,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&a.jsxs(Pd,{children:[a.jsx(iV,{})," ",Fr(u,"date-time")]})]}),d.length>0&&a.jsx(TO,{title:"Overall score",children:a.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:p,delta:h})=>a.jsx(sJt,{scorerId:f,value:p,delta:r?h:null},f))})})]})}const WT="min-w-0 px-4 py-3";function iIs({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=dn(),{data:o,isLoading:i,error:l}=nTs(e,t,n),{data:c}=L4(e,t),{data:u}=L4(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=o?.baselineId??t,p=t===f?n:t,h=c?.id===f?c:u,m=c?.id===p?c:u,{data:y,isLoading:v}=YSe({datasetId:e,experimentId:f,experimentStatus:h?.status}),{data:b,isLoading:x}=YSe({datasetId:e,experimentId:p,experimentStatus:m?.status}),{data:w}=A1(f,h?.status),{data:k}=A1(p,m?.status),_=g.useMemo(()=>eIs({comparison:o,baselineId:f,contenderId:p,baselineResults:y,contenderResults:b,baselineScores:w,contenderScores:k}),[o,f,p,y,b,w,k]),C=g.useMemo(()=>[...new Set(_.flatMap(E=>Object.keys(E.deltas)))].sort(),[_]),T=g.useMemo(()=>{const E=(A,P)=>{const F=_.map(D=>D[A].scores.find(H=>H.scorerId===P)?.value).filter(D=>D!=null);return F.length>0?F.reduce((D,H)=>D+H,0)/F.length:null},I=C.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),N=C.map(A=>{const P=E("baseline",A),F=E("contender",A);return{scorerId:A,average:F,delta:P!=null&&F!=null?F-P:null}});return{baseline:I,contender:N}},[_,C]);return i?a.jsx("div",{className:"flex h-64 items-center justify-center",children:a.jsx(Cn,{})}):l?a.jsx(Jt,{variant:"warning",title:"Error loading comparison",children:a.jsx(Jt.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!o||o.items.length===0?a.jsx("div",{className:"py-5 text-center text-body text-muted-foreground",children:"No comparison data"}):a.jsx("div",{className:"grid gap-4",children:a.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[a.jsxs("div",{role:"row",className:"grid border-y border-border xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border)]",children:[a.jsx("div",{role:"columnheader","aria-label":"Items",className:`${WT} text-caption text-muted-foreground uppercase`,children:"Items"}),a.jsx("div",{role:"columnheader","aria-label":"Baseline",className:WT,children:a.jsx(sit,{side:"baseline",experiment:h??void 0,summary:T.baseline,versionMismatch:d??void 0})}),a.jsx("div",{role:"columnheader","aria-label":"Contender",className:WT,children:a.jsx(sit,{side:"contender",experiment:m??void 0,summary:T.contender,versionMismatch:d??void 0,showDeltas:!0})})]}),_.map(E=>{const I=Object.entries(E.deltas).flatMap(([N,A])=>A==null||A===0?[]:[{scorerId:N,delta:A}]);return a.jsxs("div",{role:"row","aria-label":E.itemId,className:"grid border-b border-border xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border)]",children:[a.jsxs("div",{role:"cell",className:`${WT} grid content-start gap-1`,children:[a.jsx(r,{href:s.datasetItemLink(e,E.itemId),"aria-label":`Open item ${E.itemId}`,className:W("flex items-start gap-1.5 text-caption break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0",E.baseline.present&&E.contender.present?"text-muted-foreground":"text-placeholder"),children:a.jsx(je,{as:"span",variant:"caption",font:"mono",className:"min-w-0",children:E.itemId})}),I.length>0&&a.jsx("span",{className:"flex flex-wrap items-center gap-2",children:I.map(({scorerId:N,delta:A})=>a.jsx(rJt,{delta:A},N))}),a.jsxs("div",{className:"grid pt-3",children:[a.jsx(tit,{label:"Input",value:E.input}),a.jsx(tit,{label:"Ground truth",value:E.groundTruth})]})]}),a.jsx("div",{role:"cell","aria-label":"Baseline",className:WT,children:a.jsx(rit,{side:"baseline",row:E,isLoading:v})}),a.jsx("div",{role:"cell","aria-label":"Contender",className:WT,children:a.jsx(rit,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const aIs=100;function lIs(e,t,n){const r=Xe(),{inView:s,setRef:o}=A0(),i=t?.targetType||void 0,l=t?.targetId||void 0,c=Tm({queryKey:e?["dataset-experiments",e,"infinite",{targetType:i,targetId:l,orderBy:n}]:["experiments","infinite",{targetType:i,targetId:l,orderBy:n}],queryFn:({pageParam:u})=>{const d={page:u,perPage:aIs};return i&&(d.targetType=i),l&&(d.targetId=l),n&&(d.orderBy=n),e?r.listDatasetExperiments(e,d):r.listExperiments(d)},initialPageParam:0,getNextPageParam:(u,d,f)=>{if(!(!u?.experiments?.length||!u.pagination?.hasMore))return f+1},select:u=>u.pages.flatMap(d=>d?.experiments??[])});return g.useEffect(()=>{s&&c.hasNextPage&&!c.isFetchingNextPage&&c.fetchNextPage()},[s,c]),{...c,setEndOfListElement:o}}function cIs({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s,size:o="sm"}){const[i,l]=g.useState(!1),[c,u]=g.useState(""),d=t.filter(p=>p.toLowerCase().includes(c.toLowerCase())),f=c.trim()&&!t.includes(c.trim());return a.jsxs(ah,{open:i,onOpenChange:l,children:[a.jsx(Vd,{asChild:!0,children:a.jsxs(ae,{size:o,icon:a.jsx(V1,{}),children:["Tag ",e," items"]})}),a.jsxs(Zf,{className:"w-56 p-2",align:"end",children:[a.jsx(gr,{value:c,onChange:p=>u(p.target.value),onKeyDown:p=>{p.key==="Enter"&&c.trim()&&(p.preventDefault(),f?s(c.trim()):n(c.trim()),u(""))},placeholder:"Search or create tag...",className:"mb-1 h-7 text-caption",autoFocus:!0}),a.jsxs("div",{className:"max-h-40 space-y-0.5 overflow-y-auto",children:[d.map(p=>a.jsxs("div",{className:"flex items-center justify-between rounded px-2 py-1 text-caption hover:bg-fill-subtle",children:[a.jsx("button",{type:"button",onClick:()=>n(p),className:"flex-1 text-left text-muted-foreground",children:p}),a.jsx("button",{type:"button",onClick:()=>r(p),className:"ml-2 text-placeholder hover:text-negative1",children:a.jsx(Gt,{className:"h-3 w-3"})})]},p)),f&&a.jsxs("button",{type:"button",onClick:()=>{s(c.trim()),u("")},className:"w-full rounded px-2 py-1 text-left text-caption text-accent1 hover:bg-fill-subtle",children:['Create & apply "',c.trim(),'"']})]})]})]})}function uIs({tag:e,onRename:t,onRemove:n}){const[r,s]=g.useState(!1),[o,i]=g.useState(e),l=g.useRef(null);g.useEffect(()=>{r&&(l.current?.focus(),l.current?.select())},[r]);const c=()=>{const u=o.trim();u&&u!==e&&t(u),s(!1)};return r?a.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1",children:[a.jsx("input",{ref:l,value:o,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),c()),u.key==="Escape"&&(i(e),s(!1))},onBlur:c,className:"w-20 bg-transparent py-0.5 text-caption text-muted-foreground outline-hidden"}),a.jsx("button",{type:"button",onMouseDown:u=>{u.preventDefault(),c()},className:"hover:text-positive2 p-0.5 text-positive1",children:a.jsx(Vn,{className:"h-3 w-3"})})]}):a.jsxs("span",{className:"group inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1.5 py-0.5 text-caption text-muted-foreground",children:[e,a.jsx("button",{type:"button",onClick:()=>{i(e),s(!0)},className:W(Pn,"p-0.5 opacity-0 transition-opacity group-hover:opacity-100"),title:"Edit tag",children:a.jsx(Bd,{className:"h-3 w-3"})}),a.jsx("button",{type:"button",onClick:n,className:"p-0.5 text-placeholder opacity-0 transition-opacity group-hover:opacity-100 hover:text-negative1",title:"Remove tag",children:a.jsx(Gt,{className:"h-3 w-3"})})]})}const dIs=100;function oJt(e,t,{enabled:n=!0}={}){const r=Xe(),s={perPage:dIs};return t?.targetType&&(s.targetType=t.targetType),t?.targetId&&(s.targetId=t.targetId),wt({enabled:n,queryKey:["experiments",s],queryFn:()=>r.listExperiments(s)})}const iJt=(e,{experimentId:t,targetType:n,targetId:r,experiments:s,isLoadingExperiments:o=!1})=>{const i=Xe(),l=s!==void 0,{data:c,isLoading:u}=oJt(void 0,{targetType:n,targetId:r},{enabled:!l}),d=l?s:c?.experiments,f=l?o:u,p=t?d?.filter(m=>m.id===t):d,h=wt({queryKey:["review-items",e,t??"all",l?"supplied":"discovered",l?void 0:n||"all",l?void 0:r||"all",p?.map(m=>[m.datasetId,m.id])],queryFn:async()=>!p||p.length===0?[]:(await Promise.all(p.map(async y=>{if(!y.datasetId)return[];try{const{results:v}=await i.listDatasetExperimentResults(y.datasetId,y.id);return v.filter(b=>b.status===e).map(b=>({id:b.id,input:b.input,output:b.output,error:b.error,itemId:b.itemId,experimentId:b.experimentId,datasetId:y.datasetId??void 0,traceId:b.traceId??void 0,scores:b.scores?Object.fromEntries(b.scores.map(x=>[x.scorerId,x.score??0])):{},tags:b.tags??[],createdAt:b.createdAt,status:b.status,groundTruth:b.groundTruth,toolMockReport:b.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!d,refetchOnWindowFocus:!1});return{...h,isLoading:h.isLoading||f}},fIs=(e={})=>iJt("needs-review",e),pIs=(e={})=>iJt("complete",e);function hIs(e){const{data:t}=RE(e),r=t?.spans.find(i=>!i.parentSpanId)?.entityType==="agent",{supportsMetrics:s}=F6(),o=VSe({traceIds:e?[e]:[],enabled:r&&s,autoRefetch:!1});return e?o.data?.get(e):void 0}const oit="__create_tag__";function aJt({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,appearance:s="toolbar"}){const[o,i]=g.useState(""),l=g.useMemo(()=>[...t].sort(),[t]),c=g.useMemo(()=>{if(e.length===0)return new Set;const[f,...p]=e;return new Set((f.tags??[]).filter(h=>p.every(m=>(m.tags??[]).includes(h))))},[e]),u=g.useMemo(()=>{const f=l.map(m=>({label:m,value:m,end:c.has(m)?a.jsx(Vn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=o.trim();return p.length>0&&!l.includes(p)?[{label:`Create "${p}"`,value:oit},...f]:f},[l,c,o]),d=f=>{const p=f===oit?o.trim():f;!p||c.has(p)||n(p)};return a.jsx(za,{"data-testid":"experiment-results-tag-picker",options:u,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(V1,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s==="inline"?"ghost":"default",size:s==="inline"?"sm":"md",className:"w-auto min-w-0",disabled:r})}function lce(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function mIs({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,o=[...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 a.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[a.jsx(Rt.SectionHeading,{icon:a.jsx(xu,{}),children:"Tool Mocks"}),s&&a.jsx(Jt,{variant:"destructive",title:"Mock mismatch",children:a.jsxs(Jt.Message,{children:[a.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),a.jsxs("span",{className:"mt-1 block text-caption",children:["Called with: ",a.jsx(w1,{children:lce(s.args)})]}),n.length>0&&a.jsxs("span",{className:"mt-1 block text-caption",children:["Unconsumed mocks: ",a.jsx(w1,{children:n.map(i=>lce(i.args)).join(", ")})]})]})}),a.jsx("div",{className:"divide-y divide-border rounded border border-border text-body",children:o.map((i,l)=>a.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[a.jsxs("span",{className:"min-w-0 truncate",children:[a.jsx(je,{as:"span",variant:"body-sm",tone:"muted",font:"mono",children:i.toolName}),a.jsx(je,{as:"span",variant:"caption",tone:"muted",font:"mono",className:"ml-2",children:lce(i.args)})]}),a.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-caption ${gIs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function gIs(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-muted-foreground/10 text-muted-foreground"}}function vIs({result:e,itemId:t,fallback:n,title:r,onClose:s,...o}){const i=r??(t?`Experiment item ${t}`:`Result ${e?.id??""}`);return a.jsx(Rt,{open:!!(e??t),onClose:s,title:i,depth:1,size:"half",children:e?a.jsx(yIs,{result:e,onClose:s,...o}):t?a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:s,tooltip:"Close result panel"}),a.jsxs(Rt.Heading,{children:["Experiment item",a.jsx(Rt.CopyId,{id:t})]})]}),n]}):null})}function yIs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:o,onScoreClick:i,featuredScoreId:l,onFlagForReview:c,onTagsChange:u,tagVocabulary:d=[],isUpdatingTags:f=!1,experimentLink:p,onComplete:h,feedbackTabSlot:m}){const y=!!e?.error,v=sB(e?.input),b=sB(e?.output),x=sB(e?.groundTruth),w=c&&e.status!=="needs-review"&&e.status!=="complete",k=Array.isArray(e.tags)?e.tags:[],_=g.useMemo(()=>[e],[e]),C=!!u||k.length>0,{Link:T}=dn(),E=m&&e.traceId?e.traceId:void 0,{data:I}=z6({traceId:E}),N=hIs(e.traceId),A=a.jsxs(Rt.Content,{children:[a.jsxs("div",{className:"mb-6 grid gap-4",children:[a.jsxs(Ft,{children:[a.jsx(Ft.Key,{children:"Item Id"}),a.jsx(Ft.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),e.createdAt&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Created"}),a.jsx(Ft.Value,{children:Fr(e.createdAt,"date-time")})]}),e.status&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Status"}),a.jsx(Ft.Value,{children:a.jsx(KMe,{status:e.status})})]}),C&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Tags"}),a.jsx(Ft.Value,{children:a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[k.map(P=>a.jsxs(qX,{value:P,className:u?"gap-1 pr-1":void 0,children:[P,u&&a.jsx("button",{type:"button","aria-label":`Remove tag ${P}`,disabled:f,onClick:()=>u(k.filter(F=>F!==P)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:a.jsx(Gt,{className:"size-3"})})]},P)),u&&a.jsx(aJt,{appearance:"inline",selectedResults:_,vocabulary:d,onAddTag:P=>u([...k,P]),disabled:f})]})})]}),N&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Input tokens"}),a.jsx(Ft.Value,{children:N.inputTokens!==void 0?$l(N.inputTokens):"—"}),a.jsx(Ft.Key,{children:"Output tokens"}),a.jsx(Ft.Value,{children:N.outputTokens!==void 0?$l(N.outputTokens):"—"}),a.jsx(Ft.Key,{children:"Cost"}),a.jsx(Ft.Value,{children:N.estimatedCost!==void 0?bm(N.estimatedCost,N.costUnit):"—"})]})]}),y&&a.jsx(Jt,{variant:"destructive",title:"Error",children:a.jsx(Jt.Message,{children:sB(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&a.jsxs(Oe,{columns:"1fr 1fr",children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{children:"Scorer"}),a.jsx(Oe.TopCell,{children:"Score"})]}),t.map(P=>i?a.jsxs(Oe.RowButton,{featured:l===P.id,onClick:()=>i(P.id),children:[a.jsx(Oe.Cell,{children:P.scorerId}),a.jsx(Oe.TextCell,{font:"mono",children:P.score.toFixed(3)})]},P.id):a.jsxs(Oe.RowStatic,{children:[a.jsx(Oe.Cell,{children:P.scorerId}),a.jsx(Oe.TextCell,{font:"mono",children:P.score.toFixed(3)})]},P.id))]}),e.toolMockReport&&a.jsx(mIs,{report:e.toolMockReport})]}),a.jsxs("div",{className:"grid gap-3",children:[a.jsx(Rt.CodeSection,{title:"Input",icon:a.jsx(i_e,{}),codeStr:v}),a.jsx(Rt.CodeSection,{title:"Output",icon:a.jsx(CS,{}),codeStr:b}),e.groundTruth!==void 0&&a.jsx(Rt.CodeSection,{title:"Ground Truth",icon:a.jsx(ZSt,{}),codeStr:x})]})]});return a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:s,tooltip:"Close result panel"}),a.jsxs(Rt.Heading,{children:["Result",a.jsx(Rt.CopyId,{id:e.id})]}),a.jsxs(Rt.HeaderActions,{children:[w&&a.jsx(ae,{size:"sm",variant:"primary",onClick:()=>c(e.id),icon:a.jsx(O3,{}),children:"Flag for Review"}),h&&e.status==="needs-review"&&a.jsx(ae,{size:"sm",variant:"primary",onClick:h,icon:a.jsx(k3,{}),children:"Mark as reviewed"}),p&&a.jsx(ae,{size:"sm",variant:"ghost",render:a.jsx(T,{href:p}),tooltip:"See experiment","aria-label":"See experiment",children:a.jsx(lG,{})}),e.traceId&&o&&a.jsx(ae,{size:"sm",variant:"ghost",onClick:o,tooltip:"See trace","aria-label":"See trace",children:a.jsx(a0,{})}),a.jsx(Rt.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Go to previous result",nextLabel:"Go to next result"})]})]}),E?a.jsxs(ll,{defaultTab:"details",className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[a.jsx(Rt.Header,{children:a.jsxs(al,{variant:"pill-ghost",size:"sm",children:[a.jsx(Lr,{value:"details",children:"Details"}),a.jsxs(Lr,{value:"feedback",children:["Feedback",I?.pagination?.total!=null&&a.jsxs(a.Fragment,{children:[" (",I.pagination.total,")"]})]})]})}),a.jsx(Ss,{value:"details",flush:!0,children:A}),a.jsx(Ss,{value:"feedback",flush:!0,children:a.jsx(Rt.Content,{children:m({traceId:E})})})]}):A]})}function sB(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function bIs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function xIs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){return a.jsx(Rt,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:"Score",depth:2,children:e&&a.jsx(wIs,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s})})}function wIs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){const o=bIs(e),i=o?"N/A — code-based scorer":"N/A — step not configured";return a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:r,tooltip:"Close score panel"}),a.jsxs(Rt.Heading,{children:["Score",a.jsx(Rt.CopyId,{id:e.scorerId})]}),a.jsxs(Rt.HeaderActions,{children:[s&&e.traceId&&a.jsx(ae,{size:"sm",variant:"ghost",onClick:s,tooltip:"See trace","aria-label":"See trace",children:a.jsx(a0,{})}),(n||t)&&a.jsx(Rt.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Go to previous score",nextLabel:"Go to next score"})]})]}),a.jsx(Rt.Content,{children:a.jsxs("div",{className:"grid gap-3",children:[a.jsx(Rt.CodeSection,{title:`Score: ${e.score}`,icon:a.jsx(mv,{}),codeStr:e.reason||i,simplified:!0}),!o&&a.jsxs(a.Fragment,{children:[a.jsx(Rt.CodeSection,{title:"Preprocess Prompt",icon:a.jsx(Uh,{}),codeStr:e.preprocessPrompt||i,simplified:!0}),a.jsx(Rt.CodeSection,{title:"Analyze Prompt",icon:a.jsx(Uh,{}),codeStr:e.analyzePrompt||i,simplified:!0}),a.jsx(Rt.CodeSection,{title:"Generate Score Prompt",icon:a.jsx(Uh,{}),codeStr:e.generateScorePrompt||i,simplified:!0}),a.jsx(Rt.CodeSection,{title:"Generate Reason Prompt",icon:a.jsx(Uh,{}),codeStr:e.generateReasonPrompt||i,simplified:!0})]})]})})]})}function lJt(e,t){const[n,r]=g.useState(null),[s,o]=g.useState(void 0),[i,l]=g.useState(null),[c,u]=g.useState(t);t!==c&&(u(t),r(null),o(void 0),l(null));const d=e?.find(f=>f.id===i)??null;return{featuredTraceId:n,setFeaturedTraceId:r,featuredSpanId:s,setFeaturedSpanId:o,featuredScoreId:i,setFeaturedScoreId:l,featuredScore:d}}function cJt({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:s,...o}){const i=lJt(t,e?.id),{featuredTraceId:l,setFeaturedTraceId:c,featuredSpanId:u,setFeaturedSpanId:d,featuredScoreId:f,setFeaturedScoreId:p,featuredScore:h}=n??i,m=I=>{p(N=>I===N?null:I),c(null),d(void 0)},y=I=>{I&&(c(I),d(void 0),p(null))},v=()=>{if(!f||!t)return;const I=t.findIndex(N=>N.id===f);if(I>=0&&I<t.length-1)return()=>p(t[I+1].id)},b=()=>{if(!f||!t)return;const I=t.findIndex(N=>N.id===f);if(I>0)return()=>p(t[I-1].id)},{data:x,isLoading:w}=Kjs(l),k=x?.spans,_=k?.find(I=>!I.parentSpanId),{data:C}=z6({traceId:l??void 0,enabled:s}),{data:T}=YMe({traceId:l??void 0,spanId:u,enabled:s}),{data:E}=TX({traceId:l??void 0,spanId:_?.spanId,page:0});return a.jsxs(a.Fragment,{children:[a.jsx(vIs,{...o,result:e,scores:t,onScoreClick:m,featuredScoreId:f,onShowTrace:e?.traceId?()=>y(e.traceId):void 0,feedbackTabSlot:s?({traceId:I})=>a.jsx(UW,{traceId:I},I):void 0}),a.jsx(xIs,{score:h??void 0,onNext:v(),onPrevious:b(),onClose:()=>p(null),onShowTrace:h?()=>y(h.traceId):void 0}),a.jsx(s2e,{size:"wide",depth:2,traceId:l??void 0,spans:k,isLoadingSpans:w,selectedSpanId:u??null,onClose:()=>{c(null),d(void 0)},onSpanSelect:d,showUnavailableFeaturesMsg:!1,traceHref:l?`/traces?traceId=${encodeURIComponent(l)}`:void 0,anchorSpanId:_?.spanId,withQueryTrace:r,withFeedback:s,feedbackTabBadge:s?C?.pagination?.total??void 0:void 0,feedbackTabSlot:s?({traceId:I})=>a.jsx(UW,{traceId:I}):void 0,scoresTabBadge:E?.pagination?.total??void 0,scoresTabSlot:({traceId:I,rootSpanId:N})=>N?a.jsx(XMe,{traceId:I,spanId:N,onScoreSelect:A=>{t?.some(P=>P.id===A)&&(c(null),d(void 0),p(A))}}):null,spanFeedbackTabBadge:s?T?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:s?({traceId:I,spanId:N})=>I&&N?a.jsx(tXt,{traceId:I,spanId:N},`${I}:${N}`):null:void 0})]})}const SIs=[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"},{name:"scores",label:"Scores",size:"6rem"}],cce="__untagged__",oB="all",kIs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function OIs({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:s,targetId:o,featuredItemId:i,toolbarStart:l,renderFilters:c,toolbarEnd:u,onCreateScorer:d,breadcrumbs:f,withQueryTrace:p,withFeedback:h}){const m=Xe(),{paths:y}=dn(),{data:v}=vv(e??""),{data:b,isLoading:x}=fIs({experimentId:t,targetType:s,targetId:o,experiments:n,isLoadingExperiments:r}),{data:w,isLoading:k}=pIs({experimentId:t,targetType:s,targetId:o,experiments:n,isLoadingExperiments:r}),{updateExperimentResult:_}=cl(),[C,T]=g.useState(i??null);g.useEffect(()=>{i!==void 0&&T(i)},[i]);const[E,I]=g.useState(null),[N,A]=g.useState(new Set),[P,F]=g.useState(!1),[D,H]=g.useState(!1),[q,V]=g.useState(!1),[B,Z]=g.useState(""),[z,Y]=g.useState(""),[L,R]=g.useState(""),[M,U]=g.useState([]),[Q,te]=g.useState(!1),K=g.useMemo(()=>b??[],[b]),ee=g.useMemo(()=>{const ge=new Set;if(v?.tags)for(const De of v.tags)ge.add(De);for(const De of K)for(const et of De.tags)ge.add(et);return[...ge].sort()},[v,K]),ne=g.useCallback(ge=>{!v||!e||(v.tags??[]).includes(ge)},[v,e]),le=g.useMemo(()=>E?E===cce?K.filter(ge=>ge.tags.length===0):K.filter(ge=>ge.tags.includes(E)):K,[K,E]),J=g.useMemo(()=>{const ge=new Map;let De=0;for(const Et of K){Et.tags.length===0&&De++;for(const Ut of Et.tags)ge.set(Ut,(ge.get(Ut)??0)+1)}const et=[...ge.entries()].sort((Et,Ut)=>Ut[1]-Et[1]).map(([Et])=>({value:Et,label:Et}));return[{value:oB,label:"All tags"},...De>0?[{value:cce,label:"Untagged"}]:[],...et]},[K]),re=!!E||P,se=g.useCallback(()=>{I(null),F(!1),T(null)},[]),ie=g.useCallback((ge,De)=>{const et=K.find(Et=>Et.id===ge);et?.experimentId&&et?.datasetId&&_.mutate({datasetId:et.datasetId,experimentId:et.experimentId,resultId:et.id,tags:De})},[K,_]),fe=g.useCallback(ge=>{const De=K.find(et=>et.id===ge);A(et=>{const Et=new Set(et);return Et.delete(ge),Et}),C===ge&&T(null),De?.experimentId&&De?.datasetId&&_.mutate({datasetId:De.datasetId,experimentId:De.experimentId,resultId:De.id,status:null})},[K,_,C]),he=g.useCallback(ge=>{const De=K.find(et=>et.id===ge);A(et=>{const Et=new Set(et);return Et.delete(ge),Et}),C===ge&&T(null),De?.experimentId&&De?.datasetId&&_.mutate({datasetId:De.datasetId,experimentId:De.experimentId,resultId:De.id,status:"complete"})},[K,_,C]),xe=g.useMemo(()=>{const ge=P?w??[]:le;return!P||!E?ge:E===cce?ge.filter(De=>De.tags.length===0):ge.filter(De=>De.tags.includes(E))},[P,w,le,E]),Ne=P?k:!1,Ae=g.useMemo(()=>new Set(xe.map(ge=>ge.id)),[xe]),Ge=g.useMemo(()=>[...N].filter(ge=>Ae.has(ge)).length,[N,Ae]),Ue=xe.length>0&&Ge===xe.length,Le=g.useCallback(ge=>{A(De=>{const et=new Set(De);return et.has(ge)?et.delete(ge):et.add(ge),et})},[]),be=g.useCallback(()=>{A(Ue?new Set:new Set(xe.map(ge=>ge.id)))},[Ue,xe]),_e=g.useCallback(ge=>{for(const De of N){const et=K.find(Et=>Et.id===De);et&&!et.tags.includes(ge)&&ie(De,[...et.tags,ge])}},[K,N,ie]),ye=g.useCallback(ge=>{for(const De of N){const et=K.find(Et=>Et.id===De);et&&et.tags.includes(ge)&&ie(De,et.tags.filter(Et=>Et!==ge))}},[K,N,ie]),ve=g.useCallback(()=>{for(const ge of N)he(ge);A(new Set)},[N,he]),me=g.useCallback(()=>{for(const ge of N)fe(ge);A(new Set)},[N,fe]),de=g.useCallback(()=>{Z(""),V(!0)},[]),Ce=g.useCallback(async()=>{if(!(!z||!L)){H(!0),V(!1);try{const ge=K.filter(et=>N.has(et.id));if(ge.length===0){H(!1);return}const De=await m.clusterFailures({modelId:`${z}/${L}`,items:ge.map(et=>({id:et.id,input:et.input,output:et.output??void 0,error:typeof et.error=="string"?et.error:et.error?String(et.error):void 0,scores:et.scores,existingTags:et.tags.length>0?et.tags:void 0})),availableTags:ee.length>0?ee:void 0,prompt:B||void 0});De.proposedTags&&De.proposedTags.length>0&&(U(De.proposedTags.map(et=>({...et,accepted:!0}))),te(!0))}catch(ge){console.error("Analysis failed:",ge)}finally{H(!1)}}},[z,L,K,N,m,ee,B]),Ve=g.useCallback(()=>{for(const ge of M){if(!ge.accepted)continue;const De=K.find(et=>et.id===ge.itemId);if(De){const et=[...new Set([...De.tags,...ge.tags])];ie(De.id,et)}}te(!1)},[M,K,ie]),Fe=g.useCallback(ge=>{T(De=>De===ge?null:ge)},[]),ce=g.useMemo(()=>C?xe.find(ge=>ge.id===C)??null:null,[C,xe]),{data:we}=A1(ce?.experimentId??""),Ee=C?xe.findIndex(ge=>ge.id===C):-1,Be=Ee>0?()=>T(xe[Ee-1].id):void 0,qe=Ee>=0&&Ee<xe.length-1?()=>T(xe[Ee+1].id):void 0,Ie=!P&&N.size>0,Re=!!d&&!P&&le.length>0,He=P?"completed":"review",ze=ge=>{F(ge==="completed"),T(null)},nt=a.jsxs(Gn,{children:[a.jsx(Gn.Start,{children:c?a.jsxs(a.Fragment,{children:[l,c({status:He,onStatusChange:ze,tag:E,onTagChange:I,tagOptions:J.filter(ge=>ge.value!==oB)})]}):a.jsxs(a.Fragment,{children:[l,a.jsx(wu,{label:"Status",labelIsHidden:!0,name:"filter-status",options:kIs,value:He,onValueChange:ge=>ze(ge==="completed"?"completed":"review"),className:"whitespace-nowrap"}),J.length>1&&a.jsx(wu,{label:"Tags",labelIsHidden:!0,name:"filter-tags",options:J,value:E??oB,onValueChange:ge=>I(ge===oB?null:ge),className:"whitespace-nowrap"}),re&&a.jsx(ae,{onClick:se,size:"sm",variant:"default",icon:a.jsx(Gt,{}),children:"Reset"})]})}),(Ie||u||Re)&&a.jsxs(Gn.End,{children:[u,Re&&a.jsxs(ae,{size:"md",onClick:()=>d?.(le.map(ge=>({input:ge.input,output:ge.output}))),children:[a.jsx(_t,{size:"xs",children:a.jsx(mv,{})}),"Create Scorer"]}),Ie&&a.jsxs(a.Fragment,{children:[a.jsx(cIs,{size:"md",selectedCount:N.size,vocabulary:ee,onApplyTag:_e,onRemoveTag:ye,onNewTag:ge=>_e(ge)}),a.jsx(ae,{variant:"primary",onClick:ve,icon:a.jsx(k3,{}),children:"Mark as reviewed"}),a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{disabled:D,"aria-label":"More actions",children:D?a.jsx(Cn,{className:"h-4 w-4"}):a.jsx(P_,{})})}),a.jsxs(pt.Content,{align:"end",children:[a.jsxs(pt.Item,{onSelect:de,children:[a.jsx(_t,{size:"xs",children:a.jsx(j3,{})}),"Analyze"]}),a.jsx(pt.Separator,{}),a.jsxs(pt.Item,{onSelect:me,children:[a.jsx(_t,{size:"xs",children:a.jsx(Ni,{})}),"Remove from queue"]})]})]})]})]})]});if(x)return a.jsxs(gt,{breadcrumbs:f,actionRow:nt,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Cn,{fill:!0})]});const jt=a.jsx(cJt,{withQueryTrace:p,withFeedback:h,result:ce??void 0,title:`Review item ${ce?.id??""}`,scores:ce?we?.[ce.itemId]:void 0,experimentLink:ce?.experimentId?y.experimentItemLink(ce.experimentId,ce.itemId):void 0,tagVocabulary:ee,onTagsChange:P||!ce?void 0:ge=>{ie(ce.id,ge);for(const De of ge)ee.includes(De)||ne(De)},onComplete:P||!ce?void 0:()=>he(ce.id),onPrevious:Be,onNext:qe,onClose:()=>T(null)});return a.jsxs(gt,{breadcrumbs:f,actionRow:nt,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(hs,{open:q,onOpenChange:V,children:a.jsxs(rs,{children:[a.jsxs(ss,{children:[a.jsx(Jr,{children:"Analyze Items"}),a.jsx(Ms,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),a.jsxs("div",{className:"space-y-4 py-2",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{children:[a.jsx(Mn,{className:"mb-1 block",children:"Provider"}),a.jsx(rk,{value:z,onValueChange:Y})]}),a.jsxs("div",{children:[a.jsx(Mn,{className:"mb-1 block",children:"Model"}),a.jsx(sk,{llmId:z,value:L,onValueChange:R})]})]}),a.jsxs(je,{variant:"meta",tone:"muted",children:[N.size," item",N.size!==1?"s":""," will be analyzed"]}),a.jsxs("div",{children:[a.jsx(Mn,{children:"Instructions (optional)"}),a.jsx(Im,{value:B,onChange:ge=>Z(ge.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-caption"})]})]}),a.jsxs(rc,{children:[a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:()=>V(!1),children:"Cancel"}),a.jsxs(ae,{onClick:Ce,disabled:!z||!L||D,children:[D?a.jsx(Cn,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),a.jsx(hs,{open:Q,onOpenChange:te,children:a.jsxs(rs,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[a.jsxs(ss,{children:[a.jsx(Jr,{children:"Review Proposed Tags"}),a.jsxs(Ms,{children:[M.filter(ge=>ge.accepted).length," of ",M.length," proposals selected"]})]}),a.jsx("div",{className:"space-y-3 py-2",children:M.map((ge,De)=>{const et=K.find(Et=>Et.id===ge.itemId);return a.jsx("div",{className:W("rounded-lg border p-3",!ge.accepted&&"opacity-50"),children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Eu,{checked:ge.accepted,onCheckedChange:Et=>U(Ut=>Ut.map((Zt,ft)=>ft===De?{...Zt,accepted:!!Et}:Zt))}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx(je,{variant:"meta",tone:"muted",className:"block truncate",children:et?typeof et.input=="string"?et.input.slice(0,100):JSON.stringify(et.input).slice(0,100):ge.itemId}),a.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:ge.tags.map((Et,Ut)=>a.jsx(uIs,{tag:Et,onRename:Zt=>U(ft=>ft.map((hn,mn)=>mn===De?{...hn,tags:hn.tags.map((ke,Pe)=>Pe===Ut?Zt:ke)}:hn)),onRemove:()=>U(Zt=>Zt.map((ft,hn)=>hn===De?{...ft,tags:ft.tags.filter((mn,ke)=>ke!==Ut)}:ft))},`${Et}-${Ut}`))}),ge.reason&&a.jsx(je,{variant:"meta",tone:"muted",className:"mt-1 block italic",children:ge.reason})]})]})},ge.itemId)})}),a.jsxs(rc,{children:[a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:()=>te(!1),children:"Cancel"}),a.jsxs(ae,{icon:a.jsx(Vn,{}),onClick:Ve,disabled:M.filter(ge=>ge.accepted).length===0,children:["Accept ",M.filter(ge=>ge.accepted).length," proposals"]})]})]})}),a.jsxs("div",{className:"grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden",children:[a.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:Ne?a.jsx(Cn,{fill:!0}):xe.length===0?a.jsx(un,{titleSlot:P?"No completed reviews yet":"No items to review",descriptionSlot:P?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here.",variant:"fill"}):a.jsx(qXt,{results:xe,isLoading:!1,featuredResultId:C,onResultClick:Fe,columns:SIs,selectedIds:P?void 0:N,onToggleSelect:P?void 0:Le,onToggleSelectAll:P?void 0:be})}),jt]})]})}function _Is(){const e=Xe();return wt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function CIs(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}const ZT=[Wr("/experiments")],EIs=["createdAt","status"];function TIs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,o]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState([]),d=zr(),[f,p]=so(),{sort:h,onSortChange:m}=fk({searchParams:f,setSearchParams:p,allowedKeys:EIs}),y=g.useMemo(()=>h?{field:h.key,direction:h.direction==="asc"?"ASC":"DESC"}:void 0,[h]),v=f.get("dataset")??"all",b=g.useCallback(le=>{p(J=>{const re=new URLSearchParams(J);return le==="all"?re.delete("dataset"):re.set("dataset",le),re},{replace:!0})},[p]),{targetType:x,targetId:w,setTargetType:k,setTargetId:_}=ZXt(),{data:C,isLoading:T,error:E}=W1(),{data:I,isLoading:N,error:A,isFetchingNextPage:P,hasNextPage:F,setEndOfListElement:D}=lIs(v==="all"?void 0:v,{targetType:x,targetId:w},y),{data:H}=_Is(),q=g.useMemo(()=>C?.datasets??[],[C?.datasets]),V=g.useMemo(()=>I??[],[I]),B=g.useMemo(()=>YNs(q),[q]),Z=g.useMemo(()=>CIs(H),[H]),z=T||N,Y=A||E,L=le=>{u(J=>J.includes(le)?J.filter(re=>re!==le):J.length>=2?[J[0],le]:[...J,le])},R=()=>{u([]),l(!1)},{selectedIds:M,selectedDatasetIds:U}=g.useMemo(()=>{const le=new Map(V.map(re=>[re.id,re.datasetId])),J=c.filter(re=>le.has(re));return{selectedIds:J,selectedDatasetIds:new Set(J.map(re=>le.get(re)))}},[V,c]),Q=M.length===2&&U.size!==1?"not the same dataset":void 0,te=()=>{if(M.length!==2||Q)return;const[le,J]=M,[re]=U;if(!re)return;const se=new URLSearchParams({dataset:re,baseline:le,contender:J});d(`/experiments/compare?${se.toString()}`)};if(Y&&_s(Y))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Qs,{variant:"fill"})]});if(A&&js(A))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Fs,{variant:"fill",resource:"experiments"})]});if(E&&js(E))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Fs,{variant:"fill",resource:"datasets"})]});if(Y)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:Y.message})]});const K=a.jsx(ZX,{open:s,onOpenChange:o,onSuccess:le=>{d(`/experiments/${le}`)}});if(V.length===0&&!z&&v==="all"&&!x)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(KNs,{onRunExperiment:()=>o(!0)}),K]});const ee=n!=="all"||v!=="all"||e!==""||x!=="",ne=()=>{t(""),r("all"),p(le=>{const J=new URLSearchParams(le);return J.delete("dataset"),J.delete(b_),J.delete(vS),J},{replace:!0})};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),actionRow:a.jsx(XNs,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:v,onDatasetFilterChange:b,datasetOptions:B,targetType:x,onTargetTypeChange:k,targetId:w,onTargetIdChange:_,onReset:ne,hasActiveFilters:ee,onRunClick:()=>o(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:M.length,onExecuteCompare:te,onCancelSelection:R,compareDisabledReason:Q}:void 0}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(GNs,{experiments:V,datasets:q,reviewByExperiment:Z,isLoading:z,search:e,statusFilter:n,datasetFilter:v,isFetchingNextPage:P,hasNextPage:F,setEndOfListElement:D,sort:h,onSortChange:m,selection:i?{selectedExperimentIds:M,onToggleSelection:L}:void 0}),K]})}const GT=[Wr("/experiments"),{id:"experiments-compare",label:"Compare"}];function iB({experimentId:e}){const{Link:t,paths:n}=dn();return a.jsx(ae,{render:a.jsx(t,{href:n.experimentLink(e)}),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function jIs(){const[e,t]=so(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",o=L4(n,r),i=L4(n,s),l=o.isLoading||i.isLoading,c=o.error??i.error;return c&&_s(c)?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx(Qs,{variant:"fill"})]}):c&&js(c)?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx(Fs,{variant:"fill",resource:"experiments"})]}):!n||!r||!s?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"py-5 text-center text-muted-foreground",children:[a.jsx("p",{children:"Select two experiments to compare."}),a.jsxs("p",{className:"mt-2 text-body",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})]}):l?null:c&&!zA(c)?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:c.message})]}):c||!o.data||!i.data?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"py-5 text-center text-muted-foreground",children:[a.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),a.jsxs("p",{className:"mt-2 flex items-center justify-center gap-2 text-body",children:["One of",a.jsx(iB,{experimentId:r}),"and",a.jsx(iB,{experimentId:s}),"was not found in it."]})]})})]}):a.jsx(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"grid w-full content-start",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[a.jsx(je,{as:"h1",variant:"heading",tone:"ink",children:"Experiments comparison"}),a.jsxs("p",{className:"flex items-center gap-2 text-caption text-muted-foreground",children:[a.jsx(iB,{experimentId:r}),"and",a.jsx(iB,{experimentId:s})]})]}),a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx(ae,{onClick:()=>t({dataset:n,baseline:s,contender:r}),icon:a.jsx(cSt,{}),children:"Swap sides"})}),a.jsx(kn,{children:"Switch baseline and contender"})]})]}),a.jsx(iIs,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}function uJt(e,t){const{data:n}=vv(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function NIs({withQueryTrace:e,withFeedback:t}){const{currentItemId:n,experimentId:r,datasetId:s,experimentStatus:o,results:i,isLoadingResults:l,hasNextPage:c,close:u,goToPreviousItem:d,goToNextItem:f}=VXt(),p=g.useMemo(()=>n?i.find(_=>_.itemId===n):void 0,[i,n]),{data:h}=A1(r,o),{updateExperimentResult:m}=cl(),y=g.useCallback(async _=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:_,status:"needs-review"}),Qe("Result flagged for review")}catch{Qe.error("Failed to flag result for review")}},[s,r,m]),v=uJt(s,i),b=g.useCallback(async(_,C)=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:_,tags:C})}catch{Qe.error("Failed to update tags")}},[s,r,m]),x=g.useCallback(async _=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:_,status:"complete"}),Qe("Result marked as reviewed")}catch{Qe.error("Failed to complete result")}},[s,r,m]),w=p?h?.[p.itemId]:void 0,k=lJt(w,p?.id);return a.jsx(cJt,{result:p,itemId:n,fallback:l||c?a.jsx(Rt.LoadingData,{}):a.jsxs(Rt.NoData,{children:['No loaded result for item "',n,'".']}),scores:w,state:k,withQueryTrace:e,withFeedback:t,onPrevious:d,onNext:f,onClose:u,onComplete:p?()=>x(p.id):void 0,onFlagForReview:p?()=>{y(p.id)}:void 0,onTagsChange:p?_=>{b(p.id,_)}:void 0,tagVocabulary:v,isUpdatingTags:m.isPending})}function IIs({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:o}=e;if(t.size===0)return null;const i=s||o;return a.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap",children:[a.jsxs(ae,{disabled:i,onClick:e.flagSelectedForReview,icon:a.jsx(O3,{}),children:["Flag ",t.size," to review"]}),a.jsx(aJt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:i}),a.jsx(ae,{icon:a.jsx(Gt,{}),variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}function dJt(e){const{data:t}=A1(e.id,e.status);return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}function uce({icon:e,typeLabel:t,subject:n,description:r,isLast:s=!1}){return a.jsxs("li",{className:"relative grid grid-cols-[auto_1fr] gap-x-2.5 pb-4 last:pb-0",children:[a.jsxs("div",{className:"flex flex-col items-center",children:[a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-3.5",role:"img","aria-label":t}),children:e}),a.jsx(kn,{children:t})]}),!s&&a.jsx("span",{"aria-hidden":!0,className:"mt-1 w-px flex-1 bg-border"})]}),a.jsxs("div",{className:"grid min-w-0 gap-0.5",children:[a.jsx("div",{className:"flex min-h-5 items-center text-caption text-foreground",children:n}),a.jsx("p",{className:"text-meta text-placeholder",children:r})]})]})}const dce="text-foreground inline-flex min-w-0 items-center gap-1.5 hover:underline";function AIs({experiment:e,className:t}){const{Link:n,paths:r}=dn(),s=KXt(),{scorers:o}=s,{data:i,isLoading:l}=vv(e.datasetId??""),c=dJt(e),u=e.targetType,d=e.targetId,f=eJt(e,s),p=(()=>{if(!d)return null;switch(u){case"agent":return r.agentLink(d);case"workflow":return r.workflowLink(d);case"scorer":return r.scorerLink(d);default:return null}})(),h=u&&XXt[u]||Pi,m=u&&JXt[u]||"Evaluation target";return a.jsxs("ol",{className:W("grid",t),children:[a.jsx(uce,{icon:a.jsx(DG,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?a.jsxs(n,{href:r.datasetLink(e.datasetId),className:dce,children:[a.jsx("span",{className:"truncate",children:l?a.jsx(at,{className:"h-4 w-28"}):i?.name??e.datasetId}),e.datasetVersion!=null&&a.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["(v",e.datasetVersion,")"]})]}):a.jsx("span",{className:"text-muted-foreground",children:"No dataset"})}),a.jsx(uce,{icon:a.jsx(h,{}),typeLabel:m,description:"Its output is then scored",subject:p?a.jsx(n,{href:p,className:dce,children:a.jsx("span",{className:"truncate",children:f})}):a.jsx("span",{className:"truncate text-muted-foreground",children:f})}),a.jsx(uce,{icon:a.jsx(hb,{}),typeLabel:"Scorers",description:"It gives a score by comparing ground truth",isLast:!0,subject:c.length===0?a.jsx("span",{className:"text-muted-foreground",children:"No scorer has produced a score yet"}):a.jsx("ul",{className:"grid min-w-0 gap-0.5",children:c.map(y=>{const v=o?.[y]?.scorer?.config?.name??y;return a.jsx("li",{className:"min-w-0",children:a.jsx(n,{href:r.scorerLink(y),className:dce,children:a.jsx("span",{className:"truncate",children:v})})},y)})})})]})}function QT({label:e,children:t}){return a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:e}),a.jsx(Ft.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function RIs({experiment:e,metrics:t}){const{data:n}=A1(e.id,e.status),r=e.status==="running"||e.status==="pending",s=g.useMemo(()=>{if(!n)return;const c=Object.values(n).flat();if(c.length!==0)return c.reduce((u,d)=>u+d.score,0)/c.length},[n]),o=e.startedAt??e.createdAt,i=o?new Date(o):null,l=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const c=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Zd(c)??"—"})();return a.jsxs(Ft,{children:[a.jsx(QT,{label:"Avg score",children:s===void 0?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsxs(a.Fragment,{children:[a.jsx("span",{children:s.toFixed(3)}),r&&a.jsx("span",{className:"text-muted-foreground",children:"· so far"})]})}),a.jsx(QT,{label:"Items",children:r?a.jsxs("span",{className:"text-muted-foreground",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&a.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),a.jsx(QT,{label:"Started",children:i?a.jsx("span",{title:LTe(i),children:Fr(i,"date-time")}):a.jsx("span",{children:"—"})}),a.jsx(QT,{label:"Duration",children:a.jsx("span",{children:l})}),t?.isEnabled&&a.jsxs(a.Fragment,{children:[a.jsx(QT,{label:"Tokens",children:t.data?.totalTokens==null?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsxs(a.Fragment,{children:[a.jsx("span",{children:$l(t.data.totalTokens)}),t.data.estimatedCost!=null&&a.jsxs("span",{className:"text-muted-foreground",children:["· ",bm(t.data.estimatedCost,t.data.costUnit)]}),r&&a.jsx("span",{className:"text-muted-foreground",children:"· so far"})]})}),a.jsx(QT,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsx(je,{as:"span",variant:"body-sm",font:"mono",children:Zd(Math.round(t.data.avgAgentDurationMs))})})]})]})}function PIs({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=dn(),{data:s}=lh(),o=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(o.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),a.jsxs("div",{className:"flex items-center gap-2 text-caption text-muted-foreground",children:[a.jsx(mv,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx("span",{className:"text-muted-foreground",children:c}),a.jsx("span",{className:"truncate",children:u})]})}return a.jsx("div",{className:"flex flex-col gap-2",children:o.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return a.jsxs(xf,{className:"min-w-0 p-3",children:[a.jsxs(n,{href:r.scorerLink(i),className:"flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground hover:underline [&>svg]:size-3 [&>svg]:shrink-0 [&>svg]:text-muted-foreground",children:[a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx(hb,{role:"img","aria-label":"Scorer"})}),a.jsx(kn,{children:"Scorer"})]}),a.jsx("span",{className:"truncate",children:c})]}),a.jsxs("strong",{className:"text-subheading text-muted-foreground",children:[l.toFixed(3),a.jsx("span",{className:"ml-1.5 text-caption text-muted-foreground",children:"avg score"})]})]},i)})})}function fce({title:e,children:t}){return a.jsxs("section",{className:"grid gap-3",children:[a.jsx("h2",{className:"text-body tracking-widest text-placeholder uppercase",children:e}),t]})}function $Is({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=dn(),{data:o}=A1(e.id,e.status),i=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${s.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return a.jsxs(ku,{as:"aside","aria-label":"Experiment details",className:W("grid content-start gap-5 p-5",n),children:[a.jsxs(fce,{title:"Pipeline",children:[a.jsx(AIs,{experiment:e}),e.agentVersion&&a.jsxs(Ft,{children:[a.jsx(Ft.Key,{children:"Version"}),i?a.jsx(Ft.ValueLink,{href:i,as:r,children:e.agentVersion}):a.jsx(Ft.Value,{children:e.agentVersion})]})]}),a.jsx(fce,{title:"Run",children:a.jsx(RIs,{experiment:e,metrics:t})}),a.jsx(fce,{title:"Scorers",children:a.jsx(PIs,{scoresByItemId:o,experimentStatus:e.status})})]})}function MIs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[o,i]=g.useState(e.description??""),{updateExperiment:l}=cl(),c=!!r.trim()&&!l.isPending,u=async d=>{if(d.preventDefault(),!(!c||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:o.trim()}),Qe.success("Experiment renamed"),n(!1)}catch(f){Qe.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return a.jsx(hs,{open:t,onOpenChange:n,children:a.jsxs(rs,{className:"max-w-md",children:[a.jsx(ss,{children:a.jsx(Jr,{children:"Rename Experiment"})}),a.jsx(ys,{children:a.jsxs("form",{onSubmit:u,className:"space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mn,{htmlFor:"rename-experiment-name",children:"Name *"}),a.jsx(gr,{id:"rename-experiment-name",value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mn,{htmlFor:"rename-experiment-description",children:"Description"}),a.jsx(gr,{id:"rename-experiment-description",value:o,onChange:d=>i(d.target.value),placeholder:"Enter experiment description (optional)"})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),a.jsx(ae,{icon:a.jsx(Vn,{}),type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}const DIs=["agent","workflow","scorer"];function LIs({experiment:e}){const[t,n]=g.useState(!1),r=zr(),{paths:s}=dn(),o=dJt(e),i=DIs.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:a.jsxs(a.Fragment,{children:[a.jsx(ae,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",icon:a.jsx(bu,{}),children:"Rerun"}),t&&a.jsx(ZX,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:i,initialTargetId:e.targetId,initialScorerIds:o,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},o.join(","))]})}function FIs({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=dn(),[s,o]=g.useState(!1),i=!!e.datasetId,l=i||!!t;return a.jsxs(a.Fragment,{children:[a.jsxs(Gn,{children:[a.jsxs(Gn.Start,{className:"whitespace-nowrap",children:[a.jsx(LIs,{experiment:e}),a.jsx(ae,{render:a.jsx(r,{href:NBr(e.id)}),icon:a.jsx(O3,{}),children:"Review queue"}),l&&a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{size:"lg","aria-label":"Experiment actions menu",children:a.jsx(U1,{})})}),a.jsxs(pt.Content,{align:"start",className:"w-48",children:[i&&a.jsxs(pt.Item,{onSelect:()=>o(!0),children:[a.jsx(Bd,{})," Rename Experiment"]}),t&&a.jsxs(pt.Item,{onSelect:t,className:"text-red-500 focus:text-red-400",children:[a.jsx(Ni,{})," Delete Experiment"]})]})]})]}),n&&a.jsx(Gn.End,{children:n})]}),s&&a.jsx(MIs,{experiment:e,open:!0,onOpenChange:o})]})}const fJt=()=>{const{experimentId:e}=fr(),{data:t}=a2e();return{experimentId:e,experiment:t?.experiments?.find(n=>n.id===e)}};function zIs(){const{experimentId:e,experiment:t}=fJt();if(!e)return null;const n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function BIs(){const{experiment:e}=fJt();return e?a.jsx(Wjs,{status:e.status}):null}const UIs=({experimentId:e,experimentStatus:t})=>{const n=Xe(),{supportsMetrics:r}=F6(),s=!!e&&r,i=wt({queryKey:["experiment-metrics",e],enabled:s,refetchInterval:t==="running"||t==="pending"?2e3:!1,queryFn:async()=>{if(!e)throw new Error("experimentId is required");const l={experimentId:e},[c,u,d]=await Promise.all([n.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"avg",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:l})]);return{totalTokens:c.value??null,estimatedCost:c.estimatedCost??null,costUnit:c.costUnit??null,avgAgentDurationMs:u.value??null,agentRuns:d.value??null}}});return{data:i.data,isLoading:i.isLoading,isEnabled:s}};function VIs({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=cl();return{addTag:g.useCallback(async(i,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(i));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],i]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Qe(`Tag "${i}" added to ${u} result${u>1?"s":""}`):Qe.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function qIs({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[o,i]=g.useState(!1),{updateExperimentResult:l}=cl(),{addTag:c,isPending:u}=VIs({datasetId:e,experimentId:t}),d=uJt(e,n),f=g.useMemo(()=>n.filter(v=>r.has(v.id)),[n,r]),p=g.useCallback(v=>{s(b=>{const x=new Set(b);return x.has(v)?x.delete(v):x.add(v),x})},[]),h=g.useCallback(()=>s(new Set),[]),m=g.useCallback(async()=>{if(o||r.size===0)return;i(!0);const v=new Set;try{for(const b of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:b,status:"needs-review"}),v.add(b)}catch{}}finally{i(!1)}v.size>0&&(s(b=>{const x=new Set(b);for(const w of v)x.delete(w);return x}),Qe(`${v.size} result${v.size>1?"s":""} flagged for review`))},[e,t,o,r,l]),y=g.useCallback(v=>c(v,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:p,clearSelection:h,flagSelectedForReview:m,isFlagging:o,addTagToSelected:y,isTagging:u,tagVocabulary:d}}const HIs=[],WIs=["startedAt"];function aB({crumbs:e,children:t}){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:e}),children:[a.jsx("h1",{className:"sr-only",children:"Experiment"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:t})]})}function ZIs(){const{experimentId:e,itemId:t}=fr(),n=[Wr("/experiments"),{id:"experiment",Component:zIs,icon:BIs,to:e?`/experiments/${encodeURIComponent(e)}`:void 0},...t?[{id:"experiment-items",label:"Items"},{id:"experiment-item",label:FCe(t)}]:[]],r=zr(),[s,o]=g.useState(!1),i=FX(),[l,c]=so(),{sort:u,onSortChange:d}=fk({searchParams:l,setSearchParams:c,allowedKeys:WIs}),f=g.useMemo(()=>u?{field:u.key,direction:u.direction==="asc"?"ASC":"DESC"}:void 0,[u]),{data:p,isLoading:h}=a2e(),y=p?.experiments?.find(A=>A.id===e)?.datasetId??"",{data:v,isLoading:b,error:x}=L4(y,e??""),{data:w,isLoading:k,setEndOfListElement:_,isFetchingNextPage:C,hasNextPage:T}=YSe({datasetId:y,experimentId:e??"",experimentStatus:v?.status,orderBy:f}),E=UIs({experimentId:e,experimentStatus:v?.status}),I=qIs({datasetId:y,experimentId:e??"",results:w??HIs});if(!e||h||b)return null;if(x&&_s(x))return a.jsx(aB,{crumbs:n,children:a.jsx(Qs,{})});if(x&&js(x))return a.jsx(aB,{crumbs:n,children:a.jsx(Fs,{resource:"datasets"})});const N=a.jsx(aB,{crumbs:n,children:a.jsx(un,{titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:a.jsx(ae,{render:a.jsx(ml,{to:"/experiments"}),icon:a.jsx(Cu,{}),children:"Back to Experiments"})})});return x&&zA(x)?N:x?a.jsx(aB,{crumbs:n,children:a.jsx(un,{tone:"error",titleSlot:"Failed to load experiment",descriptionSlot:x instanceof Error?x.message:"An unexpected error occurred. Please try again."})}):!y||!v?N:a.jsx(Fjs,{experimentId:e,datasetId:y,experimentStatus:v.status,results:w??[],isLoadingResults:k,hasNextPage:T,children:a.jsxs("div",{className:"h-full",children:[a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:n}),actionRow:a.jsx(FIs,{experiment:v,onDeleteClick:()=>o(!0),children:a.jsx(IIs,{selection:I})}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-4 overflow-visible",children:[a.jsx(Hjs,{experimentId:e,experimentStatus:v.status,results:w??[],isLoading:k,setEndOfListElement:_,isFetchingNextPage:C,hasNextPage:T,selectedIds:I.selectedIds,onToggleSelect:I.toggleSelect,sort:u,onSortChange:d}),a.jsx($Is,{experiment:v,metrics:E,className:"w-80 overflow-y-auto"})]})]}),a.jsx(NIs,{withQueryTrace:i.enabled,withFeedback:i.enabled}),a.jsx(QXt,{open:s,onOpenChange:o,experimentId:e,experimentName:v.name??void 0,onSuccess:()=>r("/experiments")})]})})}const GX="targetType",QX="targetId",YX="experiment",KX="status",XX="tag",iit={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},GIs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}],ait={[GX]:{icon:fSt,hue:265},[QX]:{icon:xSt,hue:315},[YX]:{icon:lG,hue:160},[KX]:{icon:k3,hue:0},[XX]:{icon:V1,hue:340}},sM=(e,t)=>({id:e,label:t,icon:ait[e].icon,color:sAe(ait[e].hue),strict:!0}),QIs=[{id:"is",label:"is"}],oM=(e,t)=>({id:e,fieldId:e,operatorId:"is",value:t}),YIs=({targetType:e,targetId:t,experimentId:n,status:r,tag:s})=>{const o=[];return e&&o.push(oM(GX,e)),t&&o.push(oM(QX,t)),n&&o.push(oM(YX,n)),r!=="review"&&o.push(oM(KX,r)),s&&o.push(oM(XX,s)),o},KIs=e=>{const t=s=>{const o=e.find(i=>i.fieldId===s);return typeof o?.value=="string"?o.value:""},n=t(GX),r=HX(n)?n:"";return{targetType:r,targetId:r?t(QX):"",experimentId:t(YX),status:t(KX)==="completed"?"completed":"review",tag:t(XX)||null}};function XIs({targetType:e,targetId:t,experimentId:n,status:r,tag:s,experiments:o,tagOptions:i,onChange:l}){const{data:c}=ef({enabled:e==="agent"}),{data:u}=ih({enabled:e==="workflow"}),{data:d}=lh({enabled:e==="scorer"}),{data:f}=nE({enabled:e==="processor"}),p=g.useMemo(()=>{const m=e==="agent"?Object.entries(c??{}).map(([y,v])=>({value:y,label:v.name??y})):e==="workflow"?Object.entries(u??{}).map(([y,v])=>({value:y,label:v.name??y})):e==="scorer"?Object.entries(d??{}).map(([y,v])=>({value:y,label:v.scorer?.config?.name??y})):e==="processor"?Object.entries(f??{}).map(([y,v])=>({value:y,label:v.name??y})):[];return[{...sM(GX,"Target type"),suggestions:c2e.map(y=>({value:y,label:iit[y]}))},{...sM(QX,e?iit[e]:"Target"),hidden:!e,suggestions:m},{...sM(YX,"Experiment"),suggestions:o.map(y=>({value:y.id,label:YXt(y)}))},{...sM(KX,"Status"),suggestions:GIs},{...sM(XX,"Tag"),hidden:i.length===0,suggestions:i}]},[e,c,u,d,f,o,i]),h=g.useMemo(()=>YIs({targetType:e,targetId:t,experimentId:n,status:r,tag:s}),[e,t,n,r,s]);return a.jsxs(Wg,{fields:p,operators:QIs,value:h,onValueChange:m=>l(KIs(m)),createItemId:m=>m,"aria-label":"Review queue filters",className:"min-w-64 flex-1",children:[a.jsx(Wg.Chips,{}),a.jsx(Wg.Input,{placeholder:"Filter review queue…"})]})}const lB=[Wr("/experiments"),Wr("/experiments/review-queue")],pce="experiment",lit="review";function JIs(){const[e,t]=so(),n=e.get(b_),r=HX(n)?n:"",s=r?e.get(vS)??"":"",o=e.get(pce),i=e.get(lit),{Link:l,paths:c}=dn(),u=FX(),{data:d,error:f}=oJt(void 0,{targetType:r,targetId:s}),p=d?.experiments.find(m=>m.id===o),h=(m,y)=>{m.status!==y.status&&y.onStatusChange(m.status),m.tag!==y.tag&&y.onTagChange(m.tag),t(v=>{const b=new URLSearchParams(v),x=m.targetType!==r,k=x||m.targetId!==s?"":m.experimentId,_=x?"":m.targetId;return m.targetType?b.set(b_,m.targetType):b.delete(b_),_?b.set(vS,_):b.delete(vS),k?b.set(pce,k):b.delete(pce),b.delete(lit),b},{replace:!0})};return f&&_s(f)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lB}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Qs,{variant:"fill"})]}):f&&js(f)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lB}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Fs,{variant:"fill",resource:"experiments"})]}):f?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lB}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:f.message})]}):a.jsx(OIs,{withQueryTrace:u.enabled,withFeedback:u.enabled,breadcrumbs:a.jsx(kt,{crumbs:lB}),datasetId:p?.datasetId??void 0,experimentId:o??void 0,targetType:r,targetId:s,featuredItemId:i,renderFilters:m=>a.jsx(XIs,{targetType:r,targetId:s,experimentId:o??"",status:m.status,tag:m.tag,experiments:d?.experiments??[],tagOptions:m.tagOptions,onChange:y=>h(y,m)}),toolbarEnd:o?a.jsx(ae,{render:a.jsx(l,{href:c.experimentLink(o)}),icon:a.jsx(t_e,{}),children:"See experiment"}):void 0})}function eAs({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[a.jsxs("div",{children:[a.jsx(je,{as:"div",variant:"caption",font:"mono",children:e.connectionId}),a.jsxs("div",{className:"text-caption text-muted-foreground",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),a.jsx("button",{type:"button",className:"text-destructive underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function pJt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsx("ul",{className:"space-y-1",children:e.map(s=>a.jsx(eAs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function tAs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsx("div",{className:"space-y-4",children:e.map(([s,o])=>a.jsxs("div",{children:[a.jsx("h3",{className:"text-subheading text-foreground","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),a.jsx(pJt,{connections:o,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function nAs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:o,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return a.jsxs("div",{className:"space-y-2 rounded border p-4",children:[a.jsx("h2",{className:"text-heading",children:"Existing connections"}),!e||!t?a.jsx("p",{className:"text-muted-foreground",children:"Pick a provider and toolkit to list connections."}):o?a.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):i?a.jsx("p",{className:"text-destructive",children:String(i)}):n.length===0?a.jsx("p",{className:"text-muted-foreground",children:"No connections."}):r?a.jsx(tAs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):a.jsx(pJt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?a.jsx("p",{className:"text-destructive",children:String(c)}):null]})}function rAs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:o,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:y}){return a.jsxs("div",{className:"space-y-4 rounded border p-4",children:[a.jsx(wu,{name:"provider",label:"Provider",value:n,onValueChange:p,disabled:o,placeholder:o?"Loading providers…":"Select provider",options:e.map(v=>({value:v.id,label:`${v.displayName??v.name} (${v.id})`})),errorMsg:i?String(i):void 0}),a.jsx(wu,{name:"toolkit",label:"Toolkit",value:r,onValueChange:h,disabled:!n||l,placeholder:l?"Loading toolkits…":"Select toolkit",options:t.map(v=>({value:v.slug,label:`${v.name} (${v.slug})`})),errorMsg:c?String(c):void 0}),a.jsx(qi,{name:"connection-label",label:"Label (optional)",placeholder:"My personal Gmail",value:s,onChange:v=>m(v.target.value),disabled:!n||!r}),a.jsx(ae,{type:"button",variant:"primary",onClick:y,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?a.jsx("div",{role:"alert",children:a.jsx(Jt,{variant:"destructive",children:String(d)})}):null,f?a.jsxs(Jt,{variant:"success",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]}):null]})}const cit=e=>e.authorId?.trim()||"shared",sAs=(e,t)=>{if(!t||new Set(e.map(cit)).size<=1)return null;const r=new Map;for(const o of e){const i=cit(o);r.set(i,[...r.get(i)??[],o])}const s=Array.from(r.entries());return s.sort(([o],[i])=>o==="shared"?1:i==="shared"?-1:o.localeCompare(i)),s},oAs=["*","tool-providers:*","tool-providers:admin"];function iAs(){const{data:e}=Ym();return e?.permissions?.some(t=>oAs.includes(t))??!1}const aAs=[{id:"integrations",label:"Integrations"}];function lAs(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,o]=g.useState(""),i=OR(),l=dK(e||null),c=l8t(e||null,n||null),u=a8t(),d=o8t(),f=iAs(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),y=g.useMemo(()=>sAs(m,f),[m,f]),v=w=>{t(w),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{o(""),c.refetch()}})},x=w=>{d.mutate({providerId:e,connectionId:w})};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aAs}),children:[a.jsx("h1",{className:"sr-only",children:"Integrations"}),a.jsxs("div",{className:"max-w-3xl space-y-6 text-body",children:[a.jsx("p",{className:"text-muted-foreground",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),a.jsx(rAs,{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:v,onToolkitChange:r,onLabelChange:o,onConnect:b}),a.jsx(nAs,{providerId:e,toolkit:n,connections:m,groupedByAuthor:y,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})]})}function cAs({title:e,description:t,errorBanner:n,children:r}){return a.jsxs("div",{"data-testid":"login-page",className:"w-full max-w-sm space-y-6 p-6",children:[a.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[a.jsx(zy,{className:"h-10 w-10"}),a.jsx("h1",{className:"text-heading text-foreground",children:e})]}),t,n,r]})}function hJt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:o}=Ul(),{mutate:i,isPending:l,error:c}=jUr(),{mutate:u,isPending:d,error:f}=IUr(),{mutate:p,isPending:h}=NFt(),[m,y]=g.useState(n),[v,b]=g.useState(""),[x,w]=g.useState(""),[k,_]=g.useState("");if(o)return a.jsx("div",{className:"text-muted-foreground",children:"Loading..."});if(!s?.enabled||!s?.login)return a.jsx("div",{className:"text-muted-foreground",children:"Authentication is not configured"});const{login:C}=s,T=C.type==="sso"||C.type==="both",E=C.type==="credentials"||C.type==="both",I=C.sso,N=C.signUpEnabled!==!1,A=m==="signin"||!N,P=A?l:d,F=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=gK("/")},H=z=>{z.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:v||void 0},{onSuccess:D})},q=()=>{p({redirectUri:e},{onSuccess:z=>{window.location.href=z.url}})},V=()=>{y(A?"signup":"signin")},B=C.description?a.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border bg-sidebar p-3",children:[a.jsx(ed,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx("p",{className:"text-body text-muted-foreground",children:C.description})]}):null,Z=r?a.jsx("div",{role:"alert",children:a.jsx(Jt,{variant:"destructive",children:r})}):null;return a.jsxs(cAs,{title:A?"Sign in to Mastra Studio":"Create your account",description:B,errorBanner:Z,children:[E&&a.jsxs("form",{onSubmit:H,className:"space-y-4",children:[!A&&a.jsx(qi,{name:"name",label:"Name",type:"text",value:v,onChange:z=>b(z.target.value),placeholder:"Your name",variant:"default",size:"lg"}),a.jsx(qi,{name:"email",label:"Email",type:"email",value:x,onChange:z=>w(z.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"}),a.jsx(qi,{name:"password",label:"Password",type:"password",value:k,onChange:z=>_(z.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"}),F?a.jsx("div",{role:"alert",children:a.jsx(Jt,{variant:"destructive",children:F.message})}):null,a.jsx(ae,{icon:a.jsx(d_e,{}),type:"submit",disabled:P,className:"w-full",size:"lg",children:P?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),N&&a.jsxs("div",{className:"text-center text-body",children:[a.jsx("span",{className:"text-muted-foreground",children:A?"Don't have an account? ":"Already have an account? "}),a.jsx("button",{type:"button",onClick:V,className:"text-foreground hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"absolute inset-0 flex items-center",children:a.jsx("div",{className:"w-full border-t border-border"})}),a.jsx("div",{className:"relative flex justify-center text-body",children:a.jsx("span",{className:"bg-sidebar px-2 text-muted-foreground",children:"or continue with"})})]}),T&&I&&a.jsxs(ae,{onClick:q,disabled:h,className:"w-full",size:"lg",children:[I.icon&&a.jsx("span",{className:"mr-2",children:I.icon}),h?"Redirecting...":I.text||"Sign in"]})]})}function uAs(){const[e]=so(),t=zr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",o=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(hJt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:o})}function mJt({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const o=!!(n||r||s);return!t&&!o?null:a.jsxs("div",{className:"flex items-center gap-2",children:[t&&a.jsx(ae,{disabled:e,size:"md",onClick:t,icon:a.jsx(Gt,{}),children:"Clear"}),o&&a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{disabled:e,size:"md","aria-label":"More filter actions",children:a.jsx(U1,{})})}),a.jsxs(pt.Content,{align:"end",children:[n&&a.jsxs(pt.Item,{onSelect:()=>n(),children:[a.jsx(Gt,{}),"Remove all filters"]}),n&&(r||s)&&a.jsx(pt.Separator,{}),r&&a.jsxs(pt.Item,{onSelect:()=>r(),children:[a.jsx(Df,{}),"Save filters for next time"]}),s&&a.jsxs(pt.Item,{onSelect:()=>s(),children:[a.jsx(Ni,{}),"Remove saved filters"]})]})]})]})}const dAs=W(H1,"min-w-0 focus:text-foreground");function hce({role:e,checked:t,label:n,onClick:r}){return a.jsxs("button",{ref:oh(),type:"button",role:e,"aria-checked":t,"data-selected":t||void 0,"data-pick-multi-item":"",title:n,className:dAs,onClick:r,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:n}),t&&a.jsx("span",{className:P3,children:a.jsx(Vn,{})})]})}function gJt({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),o=I0(),i={className:W("max-h-[80dvh] overflow-auto p-1",o.containerClassName),...o.getContainerProps({})},l=g.useMemo(()=>{const f=r.trim().toLowerCase();return f?e.options.filter(p=>p.label.toLowerCase().includes(f)):e.options},[e.options,r]),c=g.useMemo(()=>t.find(f=>f.fieldId===e.id),[t,e.id]),u=typeof c?.value=="string"?c.value:e.multi?void 0:e.defaultValue,d=g.useMemo(()=>{const f=c?.value;return Array.isArray(f)?f:typeof f=="string"?[f]:[]},[c]);return a.jsxs(a.Fragment,{children:[e.searchable!==!1&&a.jsxs("div",{className:Xj.container,children:[a.jsx(Ro,{className:Xj.icon}),a.jsx("input",{type:"text",value:r,onChange:f=>s(f.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:Xj.input,onKeyDown:f=>{if(f.key!=="ArrowDown")return;const h=f.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");h&&(f.preventDefault(),f.stopPropagation(),h.focus())}})]}),e.isLoading?a.jsxs("div",{className:W(hV,"m-1"),children:[a.jsx(Cn,{size:"sm",className:"size-3 text-muted-foreground"}),"Loading options…"]}):l.length===0?a.jsx("div",{className:W(hV,"m-1"),children:e.emptyText??"No option found."}):e.multi?a.jsx("div",{...i,children:a.jsx(Xy,{menu:o,children:l.map(f=>{const p=d.includes(f.value);return a.jsx(hce,{role:"checkbox",checked:p,label:f.label,onClick:()=>n(e.id,p?d.filter(h=>h!==f.value):[...d,f.value])},f.value)})})}):a.jsx("div",{role:"radiogroup",...i,children:a.jsxs(Xy,{menu:o,children:[l.map(f=>a.jsx(hce,{role:"radio",checked:u===f.value,label:f.label,onClick:()=>n(e.id,f.value)},f.value)),!e.omitAnyOption&&a.jsx(hce,{role:"radio",checked:u==="Any",label:"Any",onClick:()=>n(e.id,"Any")})]})})]})}function f2e(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const fAs="This filter is set by the current context and cannot be removed here.";function pAs(e,t){return e.kind==="pick-multi"&&e.options?Array.isArray(t)?t.length===0?"Any":t.map(n=>e.options.find(r=>r.value===n)?.label??n).join(", "):e.options.find(n=>n.value===t)?.label??t:f2e(t)}function hAs({field:e,value:t,tooltipContent:n}){const r=pAs(e,t),s=`${e.label} filter is locked by context`;return a.jsx(Bl,{delayDuration:150,children:a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsxs(zl,{"data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[a.jsx(Fp,{children:e.label}),a.jsx(Fp,{children:"is"}),a.jsx(Fp,{children:r}),a.jsx(Fp,{children:a.jsx(ed,{})})]})}),a.jsx(kn,{children:n})]})})}function mAs({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:o}){const[i,l]=g.useState(t),c=g.useRef(null);return g.useEffect(()=>{i.trim()!==t&&l(t)},[t]),g.useEffect(()=>{o&&c.current?.focus()},[o]),a.jsxs(zl,{children:[a.jsx(Fp,{children:e.label}),a.jsx(Fp,{children:"is"}),a.jsx(gr,{ref:c,disabled:s,value:i,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=i.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.currentTarget.blur())}}),a.jsx(ae,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,onMouseDown:u=>u.preventDefault(),onClick:r,children:a.jsx(Gt,{})})]})}function gAs({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:o}){const[i,l]=g.useState(!1);return a.jsxs(zl,{children:[a.jsx(Fp,{children:e.label}),a.jsx(Fp,{children:"is"}),a.jsxs(ah,{open:i,onOpenChange:l,children:[a.jsx(Vd,{asChild:!0,children:a.jsx(ae,{type:"button",disabled:o,children:f2e(t.value)})}),a.jsx(Zf,{align:"start",sideOffset:eE,className:"w-64 p-0","data-pick-multi-panel":!0,children:a.jsx(gJt,{field:e,tokens:n,onChange:r})})]}),a.jsx(ae,{type:"button",disabled:o,"aria-label":`Remove ${e.label} filter`,onClick:s,children:a.jsx(Gt,{})})]})}function vJt({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:o,lockedTooltipContent:i=fAs}){if(t.length===0)return null;const l=new Set(o??[]),c=(d,f)=>{const p=[...t];p[d]=f,n(p)},u=d=>{n(t.filter((f,p)=>p!==d))};return a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const p=e.find(h=>h.id===d.fieldId);return p?l.has(d.fieldId)?a.jsx(hAs,{field:p,value:d.value,tooltipContent:i},`${d.fieldId}-${f}`):p.kind==="text"&&!Array.isArray(d.value)?a.jsx(mAs,{field:p,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:h=>c(f,{fieldId:d.fieldId,value:h}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):p.kind==="pick-multi"?a.jsx(gAs,{field:p,token:d,tokens:t,disabled:r,onChange:(h,m)=>c(f,{fieldId:h,value:m}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):a.jsxs(zl,{children:[a.jsx(Fp,{children:p.label}),a.jsx(Fp,{children:"is"}),a.jsx(Fp,{children:f2e(d.value)}),a.jsx(ae,{type:"button",disabled:r,"aria-label":`Remove ${p.label} filter`,onClick:()=>u(f),children:a.jsx(Gt,{})})]},`${d.fieldId}-${f}`):null})})}const yJt=W(H1,"focus:text-foreground"),p2e=g.forwardRef((e,t)=>a.jsx("button",{type:"button",role:"menuitem","data-filter-item":"",ref:oh(t),...e}));p2e.displayName="FilterMenuButton";function bJt({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:o,onStartTextFilter:i,hiddenFieldIds:l}){const c=g.useMemo(()=>{if(!l||l.length===0)return e;const P=new Set(l);return e.filter(F=>!P.has(F.id))},[e,l]),[u,d]=g.useState(!1),f=I0(),[p,h]=g.useState(),[m,y]=g.useState([]),[v,b]=g.useState(),[x,w]=g.useState(),k=g.useRef(!1),_=g.useCallback(P=>{w(F=>F===P?void 0:P)},[]),C=g.useCallback(()=>w(void 0),[]);g.useEffect(()=>{u||w(void 0)},[u]);const T=g.useMemo(()=>c.find(P=>P.id===p),[c,p]),E=g.useMemo(()=>{const P=new Set;for(const F of t){const D=e.find(H=>H.id===F.fieldId);D&&D.kind!=="pick-multi"&&P.add(F.fieldId)}return P},[t,e]),I=g.useCallback(()=>{h(void 0),y([]),b(void 0)},[]);g.useEffect(()=>{u||I()},[u,I]);const N=g.useCallback((P,F)=>{const D=t.findIndex(q=>q.fieldId===P);if(Array.isArray(F)&&F.length===0){if(D===-1)return;n(t.filter((q,V)=>V!==D));return}if(D===-1){n([...t,{fieldId:P,value:F}]);return}const H=[...t];H[D]={fieldId:P,value:F},n(H)},[n,t]),A=g.useCallback(()=>{if(!T){b("Choose a property first.");return}if(E.has(T.id)){b(`Remove the existing ${T.label} filter before adding another.`);return}if(m.length===0){b(`Choose at least one ${T.label.toLowerCase()} value.`);return}n([...t,{fieldId:T.id,value:m}]),d(!1)},[m,n,T,E,t]);return a.jsxs(ah,{open:u,onOpenChange:d,children:[a.jsx(Vd,{asChild:!0,children:a.jsx(ae,{size:o,disabled:s,icon:a.jsx(B8e,{}),children:r})}),a.jsx(Zf,{align:"end",sideOffset:eE,className:W("w-64",T?"p-3":"p-1"),initialFocus:!1,finalFocus:()=>k.current?(k.current=!1,!1):!0,children:a.jsxs("div",{className:W("grid",T&&"gap-3"),children:[T&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button","aria-label":"Back to properties",className:W(Pn,vn),onClick:I,children:a.jsx(Cu,{className:"size-4"})}),a.jsx(bMn,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx("span",{className:"text-caption text-muted-foreground",children:`${T.label} · is`})]}),!T&&a.jsx("div",{role:"menu",className:W("max-h-[80dvh] overflow-auto",f.containerClassName),...f.getContainerProps({}),onKeyDown:P=>{if(P.key!=="ArrowDown"&&P.key!=="ArrowUp"&&P.key!=="Home"&&P.key!=="End")return;const F=Array.from(P.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(F.length===0)return;P.preventDefault();const D=document.activeElement,H=F.findIndex(V=>V===D);let q;P.key==="Home"?q=0:P.key==="End"?q=F.length-1:P.key==="ArrowDown"?q=H<0?0:(H+1)%F.length:q=H<=0?F.length-1:H-1,F[q]?.focus()},children:a.jsx(Xy,{menu:f,children:c.length>0?c.map(P=>{const F=E.has(P.id);return P.kind==="pick-multi"?a.jsx(vAs,{field:P,tokens:t,onChange:N,open:x===P.id,onToggle:_,onClose:C},P.id):a.jsxs(p2e,{className:W(yJt,"group"),disabled:F,onClick:()=>{if(b(void 0),P.kind==="text"){n([...t,{fieldId:P.id,value:""}]),i?.(P.id),k.current=!0,d(!1);return}h(P.id)},children:[a.jsx("span",{className:"truncate",children:P.label}),F?a.jsx("span",{className:"ml-auto text-muted-foreground",children:"In use"}):a.jsx("span",{className:W(kG,"text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"),children:a.jsx(Yr,{})})]},P.id)}):a.jsx("div",{className:hV,children:"No matching property."})})}),T&&a.jsx(za,{multiple:!0,options:T.options??[],value:m,onValueChange:P=>{y(P),b(void 0)},placeholder:T.placeholder??`Choose ${T.label}`,searchPlaceholder:`Search ${T.label.toLowerCase()}...`,emptyText:T.emptyText??"No option found.",size:"md",name:`property-filter-${T.id}`,"aria-label":T.label,error:v}),T&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),a.jsx(ae,{icon:a.jsx(B8e,{}),size:"md",onClick:A,children:"Add filter"})]})]})})]})}function vAs({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:o}){const i=g.useRef(null);return a.jsxs(ah,{open:r,onOpenChange:l=>{l?s(e.id):o()},children:[a.jsx(Vd,{asChild:!0,children:a.jsxs(p2e,{className:yJt,onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{i.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&a.jsx(wr,{className:"text-muted-foreground"}),a.jsx("span",{className:"truncate",children:e.label}),!r&&a.jsx("span",{className:W(kG,"text-muted-foreground"),children:a.jsx(wr,{})})]})}),a.jsx(Zf,{ref:i,side:"right",align:"start",sideOffset:eE,className:"w-64 p-0",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(p=>p===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:a.jsx(gJt,{field:e,tokens:t,onChange:n})})]})}function yAs({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:o,depth:i}){const l=e?aC(e.timestamp)??"":"";return a.jsx(Rt,{open:!!e,onClose:t,title:e?`Log ${l}`:"Log",depth:i,children:e&&a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:t}),a.jsxs(Rt.Heading,{children:["Log · ",l]}),a.jsx(Rt.HeaderActions,{children:a.jsx(Rt.NextPrevNav,{onPrevious:s,onNext:o,previousLabel:"Go to previous log",nextLabel:"Go to next log"})})]}),a.jsx(Rt.Content,{children:a.jsxs("div",{className:"grid gap-6 p-2",children:[a.jsxs(Ft,{children:[e.entityType&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Entity Type"}),a.jsx(Ft.Value,{children:e.entityType})]}),e.entityName&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Entity Name"}),a.jsx(Ft.Value,{children:e.entityName})]}),e.serviceName&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Service"}),a.jsx(Ft.Value,{children:e.serviceName})]}),e.environment&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Environment"}),a.jsx(Ft.Value,{children:e.environment})]}),e.source&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Source"}),a.jsx(Ft.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([c,u])=>a.jsxs(g.Fragment,{children:[a.jsx(Ft.Key,{children:c}),a.jsx(Ft.Value,{children:String(u)})]},c))]}),a.jsx(Rt.CodeSection,{title:"Message",codeStr:e.message,simplified:!0}),(e.traceId||e.spanId)&&a.jsxs("div",{className:"grid gap-2",children:[e.traceId&&a.jsxs(zl,{className:"w-full min-w-0",children:[a.jsxs(ae,{className:"min-w-0 flex-1 justify-between overflow-hidden",icon:a.jsx(qf,{}),onClick:()=>e.traceId&&n?.(e.traceId),children:[a.jsx("span",{children:"Trace"}),a.jsxs("span",{className:"ml-auto min-w-0 truncate text-caption text-placeholder",children:["# ",e.traceId]})]}),a.jsx(Oo,{content:e.traceId,tooltip:"Copy Trace ID to clipboard"})]}),e.spanId&&a.jsxs(zl,{className:"w-full min-w-0",children:[a.jsxs(ae,{className:"min-w-0 flex-1 justify-between overflow-hidden",disabled:!e.traceId||!r,onClick:()=>e.traceId&&e.spanId&&r?.(e.traceId,e.spanId),icon:a.jsx(qf,{}),children:[a.jsx("span",{children:"Span"}),a.jsxs("span",{className:"ml-auto min-w-0 truncate text-caption text-placeholder",children:["# ",e.spanId]})]}),a.jsx(Oo,{content:e.spanId,tooltip:"Copy Span ID to clipboard"})]})]}),e.data&&Object.keys(e.data).length>0&&a.jsx(Rt.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function bAs({error:e,resource:t,errorTitle:n}){if(_s(e))return a.jsx(Qs,{});if(js(e))return a.jsx(Fs,{resource:t});if(L3(e))return a.jsx(un,{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(D3(e,"logs"))return a.jsx(un,{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 a.jsx(un,{tone:"error",titleSlot:n,descriptionSlot:r??"Unknown error"})}const xAs={debug:"neutral",info:"blue",warn:"yellow",error:"red",fatal:"red"};function wAs({level:e}){return a.jsx(da,{children:a.jsx(Mt,{variant:xAs[e],children:e})})}function SAs({entityType:e,className:t}){const n=W("size-3.5 shrink-0 text-placeholder",t);switch(e.toLowerCase()){case"agent":return a.jsx(Pi,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return a.jsx(yl,{className:n,"aria-hidden":!0});case"tool":return a.jsx(Hd,{className:n,"aria-hidden":!0});default:return null}}function kAs({entityType:e,entityName:t}){const n=e??"";return a.jsxs(da,{className:"flex min-w-0 items-center gap-2",children:[a.jsx(SAs,{entityType:n}),t?a.jsx("span",{className:"min-w-0 truncate text-body-sm",children:t}):"-"]})}function OAs({message:e}){return a.jsx(da,{className:"min-w-0 truncate font-mono text-body-sm text-muted-foreground",children:e})}function _As({data:e}){if(!e||Object.keys(e).length===0)return a.jsx(da,{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 a.jsx(jIe,{font:"mono",children:t})}const El=Object.assign(B5,{Top:U5,TopCell:B0,SortableTopCell:GY,TopCellWithTooltip:HY,TopCellSmart:X3t,RowWrapper:AIe,RowButton:V5,RowLink:IIe,Spacer:RIe,NoMatch:ZY,DateCell:Q3t,TimeCell:K3t,LevelCell:wAs,EntityCell:kAs,MessageCell:OAs,DataCell:_As,NextPageLoading:WY}),uit="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",CAs=36,EAs=8;function TAs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:o,featuredLogId:i,onLogClick:l,timestampSort:c,onSortChange:u}){const d=g.useRef(null),f=NKt({count:e.length,getScrollElement:()=>d.current,estimateSize:()=>CAs,overscan:EAs}),{getRowProps:p}=Bc({count:e.length,containerRef:d,onNavigate:x=>f.scrollToIndex(x),global:!0}),h=g.useRef(t);if(g.useEffect(()=>{h.current&&!t&&d.current?.dispatchEvent(new Event("scroll")),h.current=t},[t]),t)return a.jsx(dc,{columns:uit,fit:"container"});const m=f.getVirtualItems(),y=f.getTotalSize(),v=m[0]?.start??0,b=m.length>0?Math.max(0,y-(m[m.length-1]?.end??0)):0;return a.jsxs(El,{columns:uit,scrollRef:d,className:"min-w-0",fit:"container",children:[a.jsxs(El.Top,{children:[u?a.jsx(El.SortableTopCell,{sortKey:"timestamp",sort:c,onSortChange:u,children:"Date"}):a.jsx(El.TopCell,{children:"Date"}),a.jsx(El.TopCell,{children:"Time"}),a.jsx(El.TopCell,{children:"Level"}),a.jsx(El.TopCell,{children:"Entity"}),a.jsx(El.TopCell,{children:"Message"}),a.jsx(El.TopCell,{children:"Data"})]}),e.length===0?a.jsx(El.NoMatch,{message:"No logs match your search"}):a.jsxs(a.Fragment,{children:[a.jsx(El.Spacer,{height:v}),m.map(x=>{const w=e[x.index];if(!w)return null;const k=o.get(w);if(!k)return null;const _=k===i;return a.jsxs(El.RowButton,{ref:f.measureElement,"data-index":x.index,...p(x.index),onClick:()=>l(w),featured:_,variant:w.level==="error"||w.level==="fatal"?"error":"default",children:[a.jsx(El.DateCell,{timestamp:w.timestamp}),a.jsx(El.TimeCell,{timestamp:w.timestamp}),a.jsx(El.LevelCell,{level:w.level}),a.jsx(El.EntityCell,{entityType:w.entityType,entityName:w.entityName}),a.jsx(El.MessageCell,{message:w.message}),a.jsx(El.DataCell,{data:w.data})]},k)}),a.jsx(El.Spacer,{height:b})]}),a.jsx(El.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function jAs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:o,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>NAs(f,o));return u?a.jsxs("div",{className:W("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx(vJt,{fields:o,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(mJt,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function NAs(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 IAs={"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"},mce="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function AAs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${IAs[e]}`,description:mce}:t&&n?{title:`No logs between ${Fr(t,"date-time")} and ${Fr(n,"date-time")}`,description:mce}:t?{title:`No logs since ${Fr(t,"date-time")}`,description:mce}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const RAs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=AAs({datePreset:e,dateFrom:t,dateTo:n});return a.jsx(un,{titleSlot:r,descriptionSlot:s,actionSlot:a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Ts,{}),children:"Logging Documentation"}),variant:"fill"})},PAs=20,$As=1e4,MAs={field:"timestamp",direction:"DESC"};function DAs(e,t,n){if(e?.pagination?.hasMore)return n+1}function LAs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const o=s.logId??JSON.stringify(s);t.has(o)||(t.add(o),n.push(s))}return n}function FAs(e){return D3(e.state.error,"logs")||L3(e.state.error)?!1:$As}const zAs=({filters:e,orderBy:t=MAs}={})=>{const n=Xe(),{inView:r,setRef:s}=A0(),o=Tm({queryKey:["logs",e,t],queryFn:({pageParam:h})=>n.listLogsVNext({pagination:{page:h,perPage:PAs},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:DAs,select:LAs,retry:!1,refetchInterval:FAs}),{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c,data:u,isLoading:d,isError:f,error:p}=o;return g.useEffect(()=>{r&&i&&!l&&c()},[r,i,l,c]),{data:u,hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c,isLoading:d,isError:f,error:p,setEndOfListElement:s}},cB={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},xJt=[{label:"Agent",entityType:cB.AGENT},{label:"Workflow",entityType:cB.WORKFLOW},{label:"Scorer",entityType:cB.SCORER},{label:"Ingest",entityType:cB.INGEST}],BAs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],x0="rootEntityType",kx="datePreset",Ox="dateFrom",_x="dateTo",UAs=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"},U6=Object.keys(Nl),h2e=new Set(["tags"]),m2e="mastra:logs:saved-filters";function VAs(e,t=m2e){const n=GAs(e),r=e.get(kx);r&&n.set(kx,r);const s=e.get(Ox);s&&n.set(Ox,s);const o=e.get(_x);o&&n.set(_x,o);try{localStorage.setItem(t,n.toString())}catch{}}function qAs(e=m2e){try{localStorage.removeItem(e)}catch{}}function dit(e=m2e){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function HAs(e){if(e.has(kx)||e.has(Ox)||e.has(_x)||e.has(x0))return!0;for(const t of U6)if(e.has(Nl[t]))return!0;return!1}function WAs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const o=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:xJt.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:BAs.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=o.filter(u=>u.kind==="pick-multi").sort(i),c=o.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function ZAs(e){const t=[],n=new Map([[x0,"rootEntityType"]]);for(const s of U6)n.set(Nl[s],s);const r=new Set;for(const[s]of e.entries()){const o=n.get(s);if(!o||r.has(o))continue;if(r.add(o),h2e.has(o)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:o,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:o,value:i})}return t}function GAs(e){const t=new URLSearchParams,n=e.get(x0);n&&t.set(x0,n);for(const r of U6){const s=Nl[r];if(h2e.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const o=e.get(s);o&&t.set(s,o)}return t}function QAs(e,t){e.delete(x0);for(const n of U6)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(x0,n.value);continue}const r=Nl[n.fieldId];if(r){if(h2e.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 YAs({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 o of r){if(o.fieldId==="tags"){Array.isArray(o.value)&&o.value.length>0?s.tags=o.value:typeof o.value=="string"&&o.value.trim()&&(s.tags=[o.value.trim()]);continue}if(o.fieldId==="level"){typeof o.value=="string"&&o.value.trim()&&o.value!=="Any"&&(s.level=o.value);continue}if(typeof o.value=="string"&&o.value.trim()&&o.value!=="Any")switch(o.fieldId){case"entityName":s.rootEntityName=o.value;break;case"traceId":s.traceId=o.value;break;case"spanId":s.spanId=o.value;break;case"runId":s.runId=o.value;break;case"threadId":s.threadId=o.value;break;case"sessionId":s.sessionId=o.value;break;case"requestId":s.requestId=o.value;break;case"resourceId":s.resourceId=o.value;break;case"userId":s.userId=o.value;break;case"organizationId":s.organizationId=o.value;break;case"serviceName":s.serviceName=o.value;break;case"environment":s.environment=o.value;break;case"experimentId":s.experimentId=o.value;break}}return s}function KAs(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 XAs="Filters setting for Logs saved",JAs="Filters setting for Logs cleared up";function eRs(e,t,n){const{storageKey:r,messages:s,skipHydration:o}={},[i,l]=g.useState(()=>dit(r)!==null),c=g.useCallback(()=>{VAs(e,r),l(!0);const f=s?.saved??XAs;f!==!1&&Qe.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{qAs(r),l(!1);const f=s?.cleared??JAs;f!==!1&&Qe.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(o||d.current||(d.current=!0,HAs(e)))return;const f=dit(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,y]of f)h.append(m,y);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function tRs(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 nRs(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,tRs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function rRs(e,t,n,r){const s=g.useMemo(()=>nRs(e),[e]),o=g.useMemo(()=>{const h=new Map;for(const[m,y]of e.entries()){const v=s.get(y);v&&h.set(v,{log:y,idx:m})}return h},[e,s]),l=(t?o.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 e1e="logId",t1e="traceId",n1e="spanId",iM=1440*60*1e3,sRs={"last-24h":iM,"last-3d":3*iM,"last-7d":7*iM,"last-14d":14*iM,"last-30d":30*iM};function uB(e){e.delete(e1e),e.delete(t1e),e.delete(n1e)}function oRs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(kx);return _&&UAs.has(_)?_:"last-24h"},[e]),o=e.get(Ox),i=e.get(_x),l=g.useMemo(()=>{if(s==="custom"){if(!o)return;const C=new Date(o);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=sRs[s];return _?new Date(Date.now()-_):void 0},[s,o]),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(e1e),f=e.get(t1e),p=e.get(n1e),h=g.useMemo(()=>xJt.find(_=>_.entityType===e.get(x0)),[e]),m=g.useMemo(()=>ZAs(e),[e]),y=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);for(const[E,I]of Object.entries(_)){const N=E==="logId"?e1e:E==="traceId"?t1e:n1e;I?T.set(N,I):T.delete(N)}return T},{replace:!0})},[t]),v=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);return QAs(T,_),uB(T),T},{replace:!0})},[t]),b=v,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const T=C==="from"?Ox:_x;t(E=>{const I=new URLSearchParams(E);return _?I.set(T,_.toISOString()):I.delete(T),uB(I),I},{replace:!0})},[t]),w=g.useCallback(_=>{u.current=_,t(C=>{const T=new URLSearchParams(C);return _==="last-24h"?(T.delete(kx),T.delete(Ox),T.delete(_x)):_==="custom"?T.set(kx,"custom"):(T.set(kx,_),T.delete(Ox),T.delete(_x)),uB(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(x0);for(const T of U6)C.delete(Nl[T]);return C.delete(kx),C.delete(Ox),C.delete(_x),uB(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:y,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:v}),[e,t,s,l,c,u,d,f,p,h,m,y,b,x,w,k,v])}const wJt=()=>{const e=Xe();return wt({queryKey:["observability-service-names"],queryFn:async()=>{try{return await e.getServiceNames()}catch{return{serviceNames:[]}}},select:t=>t?.serviceNames??[],retry:!1,staleTime:L6})},SJt=()=>{const e=Xe();return wt({queryKey:["observability-tags"],queryFn:async()=>{try{return await e.getTags()}catch{return{tags:[]}}},select:t=>t?.tags??[],retry:!1,staleTime:L6})},gce=[Wr("/logs")],iRs=["timestamp"],aRs={key:"timestamp",direction:"desc"};function lRs(){const[e,t]=so(),n=oRs(e,t),r=FX(),{sort:s,onSortChange:o}=fk({searchParams:e,setSearchParams:t,allowedKeys:iRs,defaultSort:aRs}),i=g.useMemo(()=>({field:"timestamp",direction:s?.direction==="asc"?"ASC":"DESC"}),[s?.direction]),l=eRs(e,t),[c,u]=g.useState(),{data:d=[],isPending:f}=SJt(),{data:p=[],isPending:h}=WMe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:m=[],isPending:y}=ZMe(),{data:v=[],isPending:b}=wJt(),x=g.useMemo(()=>WAs({availableTags:d,availableRootEntityNames:p,availableServiceNames:v,availableEnvironments:m,loading:{tags:f,entityNames:h,serviceNames:b,environments:y}}),[d,p,v,m,f,h,b,y]),w=g.useMemo(()=>YAs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:k=[],isLoading:_,error:C,isFetchingNextPage:T,hasNextPage:E,setEndOfListElement:I}=zAs({filters:w,orderBy:i}),{logIdMap:N,featuredLog:A,handleLogClick:P,handlePreviousLog:F,handleNextLog:D}=rRs(k,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:H,isLoading:q}=RE(n.featuredTraceId??null),V=g.useCallback(()=>n.applyFilterTokens(KAs(x,n.filterTokens)),[x,n]),B=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),Z=g.useCallback(U=>n.handleFeaturedChange({traceId:U,spanId:null}),[n]),z=g.useCallback((U,Q)=>n.handleFeaturedChange({traceId:U,spanId:Q}),[n]),Y=g.useCallback(()=>n.handleFeaturedChange({traceId:null,spanId:null}),[n]),L=g.useCallback(U=>n.handleFeaturedChange({spanId:U??null}),[n]),R=a.jsxs(a.Fragment,{children:[a.jsx(Gn,{children:a.jsxs(Gn.Start,{children:[a.jsx(QY,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:_,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),a.jsx(bJt,{fields:x,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:_,onStartTextFilter:u})]})}),a.jsx(jAs,{isLoading:_,filterFields:x,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:V,onRemoveAll:n.handleRemoveAll,onSave:l.handleSave,onRemoveSaved:l.hasSavedFilters?l.handleRemoveSaved:void 0,autoFocusFilterFieldId:c})]});if(C)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:gce}),actionRow:R,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(bAs,{error:C,resource:"logs",errorTitle:"Failed to load logs"})})]});const M=!!n.selectedEntityOption||n.filterTokens.length>0;return k.length===0&&!_&&!M?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:gce}),actionRow:R,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(RAs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:gce}),actionRow:R,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(TAs,{logs:k,isLoading:_,isFetchingNextPage:T,hasNextPage:E,setEndOfListElement:I,logIdMap:N,featuredLogId:n.featuredLogId,onLogClick:P,timestampSort:s?.direction,onSortChange:o}),a.jsx(yAs,{log:A??void 0,onClose:B,onTraceClick:Z,onSpanClick:z,onPrevious:F,onNext:D}),a.jsx(s2e,{depth:2,traceId:A?n.featuredTraceId??void 0:void 0,spans:H?.spans,isLoadingSpans:q,selectedSpanId:n.featuredSpanId??null,onSpanSelect:L,onClose:Y,withQueryTrace:r.enabled,withFeedback:r.enabled})]})}const cRs={name:e=>e.name||e.id};function uRs({server:e,rowProps:t}){const{paths:n,Link:r}=dn(),o=Xe().options.baseUrl,l=e.transports?.includes("sse")??!0?"sse":"mcp",c=o?`${o}/api/mcp/${e.id}/${l}`:"",{data:u}=dGt(e),d=Object.values(u||{}),f=d.length,p=d.filter(y=>y.toolType==="agent").length,h=d.filter(y=>y.toolType==="workflow").length,m=Xd(e.name,50);return a.jsxs(Oe.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[a.jsx(Oe.NameCell,{children:m}),a.jsx(Oe.DescriptionCell,{children:c}),a.jsx(Oe.TextCell,{className:"text-center",children:p||""}),a.jsx(Oe.TextCell,{className:"text-center",children:f||""}),a.jsx(Oe.TextCell,{className:"text-center",children:h||""})]})}function dRs({mcpServers:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const o=g.useMemo(()=>{const c=n.toLowerCase();return G0(e.filter(u=>u.name?.toLowerCase().includes(c)||u.id?.toLowerCase().includes(c)),r,cRs)},[e,n,r]),{containerRef:i,getRowProps:l}=Bc({count:o.length,global:!0});return t?a.jsx(dc,{columns:"auto 1fr auto auto auto"}):a.jsxs(Oe,{columns:"auto 1fr auto auto auto",scrollRef:i,children:[a.jsxs(Oe.Top,{children:[s?a.jsx(Oe.SortableTopCell,{sortKey:"name",sort:r?.key==="name"?r.direction:void 0,onSortChange:s,children:"Name"}):a.jsx(Oe.TopCell,{children:"Name"}),a.jsx(Oe.TopCell,{children:"URL"}),a.jsx(Oe.TopCellSmart,{long:"Agents",short:a.jsx(Pi,{}),tooltip:"Agent Tools",className:"text-center"}),a.jsx(Oe.TopCellSmart,{long:"Tools",short:a.jsx(Hd,{}),tooltip:"Tools",className:"text-center"}),a.jsx(Oe.TopCellSmart,{long:"Workflows",short:a.jsx(yl,{}),tooltip:"Workflow Tools",className:"text-center"})]}),o.length===0&&n?a.jsx(Oe.NoMatch,{message:"No MCP Servers match your search"}):null,o.map((c,u)=>a.jsx(uRs,{server:c,rowProps:l(u)},c.id))]})}const fRs=()=>a.jsx(un,{titleSlot:"No MCP Servers yet",descriptionSlot:a.jsxs(a.Fragment,{children:["MCP servers are not configured yet. ",a.jsx("br",{}),"More information in the documentation."]}),actionSlot:a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Ts,{}),children:"MCP Documentation"}),variant:"fill"}),aM=[Wr("/mcps")],pRs=()=>{const{data:e=[],isLoading:t,error:n}=FA(),[r,s]=g.useState(""),[o,i]=g.useState();return n&&_s(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Qs,{variant:"fill"})]}):n&&js(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Fs,{variant:"fill",resource:"MCP servers"})]}):n?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load MCP servers",descriptionSlot:n.message})]}):e.length===0&&!t?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(fRs,{})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),actionRow:a.jsx(Gn,{children:a.jsx(Gn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(dRs,{mcpServers:e,isLoading:t,search:r,sort:o,onSortChange:(l,c)=>i({key:c,direction:l})})]})},fit="auto 1fr auto",hRs={tool:"Tool",agent:"Agent",workflow:"Workflow"};function mRs(e){return e in sMe}function gRs({type:e}){const t=mRs(e)?e:"tool",n=sMe[t],r=hRs[t];return a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("span",{"aria-label":t,className:"text-neutral3 inline-flex [&>svg]:size-4",children:a.jsx(n,{})})}),a.jsx(kn,{children:r})]})}const vRs=mr({ui:mr({resourceUri:jn().optional()}).optional(),"ui/resourceUri":jn().optional()});function yRs(e){const t=vRs.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith("ui://")||t.data["ui/resourceUri"]?.startsWith("ui://")):!1}function bRs({server:e}){const[t,n]=g.useState(""),{data:r={},isLoading:s}=dGt(e),{Link:o,paths:i}=dn(),l=g.useMemo(()=>{const d=t.toLowerCase();return Object.values(r).filter(f=>f.name.toLowerCase().includes(d)||f.description?.toLowerCase().includes(d))},[r,t]),{containerRef:c,getRowProps:u}=Bc({count:l.length});return a.jsxs("section",{className:"flex flex-col gap-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[a.jsx(je,{as:"h2",variant:"heading",children:"Available tools"}),a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{onSearch:n,label:"Filter tools",placeholder:"Filter by name",shortcutDisabled:!0})})]}),s?a.jsx(dc,{columns:fit}):a.jsxs(Oe,{columns:fit,scrollRef:c,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{children:"Name"}),a.jsx(Oe.TopCell,{children:"Description"}),a.jsx(Oe.TopCell,{className:"justify-center text-center",children:"Type"})]}),l.length===0&&t?a.jsx(Oe.NoMatch,{message:"No tools match your search"}):null,l.map((d,f)=>a.jsxs(Oe.RowLink,{to:i.mcpServerToolLink(e.id,d.name),LinkComponent:o,...u(f),children:[a.jsx(Oe.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-2",children:[d.name,yRs(d._meta)&&a.jsx(Mt,{size:"xs",children:"App"})]})}),a.jsx(Oe.DescriptionCell,{children:d.description}),a.jsx(Oe.TextCell,{className:"justify-center text-center",children:a.jsx(gRs,{type:d.toolType??"tool"})})]},d.name))]})]})}const xRs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const c=window.MASTRA_SERVER_HOST,u=window.MASTRA_SERVER_PORT;let d=null;c&&u&&(d=`http://${c}:${u}`);const f=d||"http://localhost:4111",p=`${f}/api/mcp/${t.id}/sse`,h=`${f}/api/mcp/${t.id}/mcp`;s({sseUrl:p,httpStreamUrl:h})},[t]),e)return null;if(!t)return a.jsx(je,{as:"h1",variant:"heading",tone:"muted",className:"py-20 text-center",children:"Server not found"});const o=t.transports?.includes("sse")??!0,i=`npx -y mcp-remote ${o?n:r}`,l=[{value:"http",label:"HTTP",description:"Use for stateless HTTP transport with streamable responses.",content:r,tooltip:"Copy HTTP Stream URL"},...o?[{value:"sse",label:"SSE",description:"Use for real-time communication via SSE.",content:n,tooltip:"Copy SSE URL"}]:[],{value:"cli",label:"CLI",description:"Use for local command-line access via npx and mcp-remote.",content:i,tooltip:"Copy Command Line Config"}];return a.jsxs("div",{className:"flex flex-col gap-6 pt-4",children:[a.jsx(ku,{children:a.jsxs(ll,{defaultTab:"http",children:[a.jsxs($q,{className:"border-border1 flex-row items-center justify-between gap-3 space-y-0 border-b",children:[a.jsx(J1,{className:"shrink-0",children:"Connect"}),a.jsx("div",{className:"min-w-0",children:a.jsx(al,{variant:"pill-ghost",size:"sm",children:l.map(c=>a.jsx(Lr,{value:c.value,children:c.label},c.value))})})]}),l.map(c=>a.jsx(Ss,{value:c.value,flush:!0,children:a.jsxs(lv,{className:"flex flex-col gap-3",children:[a.jsx(je,{tone:"muted",children:c.description}),a.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3",children:[a.jsx(je,{as:"span",font:"mono",className:"min-w-0 break-all",children:c.content}),a.jsx(Oo,{tooltip:c.tooltip,content:c.content})]})]})},c.value))]})}),a.jsx(bRs,{server:t})]})},wRs=()=>{const{serverId:e}=fr(),t=[Wr("/mcps"),b_t],{data:n=[],isLoading:r}=FA(),s=n.find(l=>l.id===e),o=s?.transports?.includes("sse")??!0,i=r||s?a.jsxs(jc,{children:[a.jsx(jc.Title,{isLoading:r,children:s?.name}),s&&a.jsx(jc.Meta,{beside:!0,children:a.jsxs(Mt,{size:"sm",children:["v",s.version_detail.version]})}),s&&a.jsx(jc.Description,{children:o?"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case.":"This MCP server speaks Streamable HTTP only (protocol 2026-07-28)."})]}):void 0;return a.jsx(gt,{variant:"narrow",breadcrumbs:a.jsx(kt,{crumbs:t}),header:i,children:a.jsx(xRs,{isLoading:r,server:s})})};function SRs(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}function kRs(e){return typeof e=="object"&&e!==null&&e.status==="suspended"}function ORs(e){return JSON.stringify({error:e instanceof Error?e.message:String(e)},null,2)}const _Rs=({toolId:e,serverId:t})=>{const{canExecute:n}=_a(),r=n("tools"),s=Xe(),{data:o,isLoading:i,error:l}=H_e(t,e),{mutateAsync:c,isPending:u,data:d,error:f}=T6n(t,e),p=o?SRs(o._meta):void 0,{data:h}=wt({queryKey:["mcp-app-resource",t,p],queryFn:async()=>p?(await s.readMcpServerResource(t,p)).contents[0]?.text??null:null,enabled:!!p}),m=g.useCallback(async(b,x)=>await c(x),[c]);g.useEffect(()=>{if(l){const b=l instanceof Error?l.message:"Failed to load tool";Qe.error(`Error loading tool: ${b}`)}},[l]);const y=async b=>{if(o)return await c(b).catch(()=>{})};if(i)return a.jsxs("div",{className:"p-4",children:[a.jsx(at,{className:"mb-4 h-8 w-48"}),a.jsx(at,{className:"h-32 w-full"})]});if(l)return null;if(!o)return a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(je,{variant:"heading",tone:"muted",children:"Tool not found"})});if(!r)return a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(je,{variant:"caption",tone:"muted",children:"You don't have permission to execute tools."})});let v;try{v=Am(o.inputSchema)}catch(b){console.error("Error processing input schema:",b),Qe.error("Failed to process tool input schema."),v=mr({})}return a.jsxs("div",{className:"flex flex-col gap-4",children:[h&&a.jsx("div",{className:"border-b border-border p-4",children:a.jsx(uGt,{html:h,toolName:o.name,onToolCall:m})}),kRs(d)&&a.jsx("div",{className:"px-4 pt-4",children:a.jsxs(Jt,{variant:"warning",children:["This tool asked for more input, which Studio cannot provide. The suspend payload below shows what it needs. Call it from an MCP client with an ",a.jsx("code",{children:"inputRequests"})," handler to finish the request."]})}),a.jsx(oMe,{executionResult:d,errorString:f?ORs(f):void 0,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:y,toolDescription:o.description||"",toolId:o.name})]})},CRs=()=>{const{serverId:e,toolId:t}=fr(),n=[Wr("/mcps"),{...b_t,to:e?`/mcps/${encodeURIComponent(e)}`:void 0},{id:"mcp-server-tool",Component:I6n}],{data:r,isLoading:s}=H_e(e,t);return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:t}),!s&&r&&a.jsx("div",{className:"h-full w-full overflow-y-auto",children:a.jsx(_Rs,{toolId:t,serverId:e})})]})},ERs={default:YOe,inset:W(ir,"*:bg-background! *:shadow-rim!")};function TRs({children:e,variant:t="default",className:n}){return a.jsx("div",{className:W("grid grid-cols-1 gap-1 rounded-xl p-1 *:min-w-0! md:grid-cols-2 lg:flex lg:*:flex-1",ERs[t],n),children:e})}function jRs({children:e,className:t}){return a.jsx("div",{className:W("flex flex-wrap gap-4",t),children:e})}const kJt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],iA="rootEntityType",aA={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"},JX=Object.keys(aA),g2e="mastra:metrics:saved-filters";function NRs(e){const t=PRs(e);try{localStorage.setItem(g2e,t.toString())}catch{}}function IRs(){try{localStorage.removeItem(g2e)}catch{}}function OJt(){try{const e=localStorage.getItem(g2e);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function ARs(e){if(e.has(iA))return!0;for(const t of JX)if(e.has(aA[t]))return!0;return!1}function _Jt({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const o=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:kJt.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=o.filter(u=>u.kind==="pick-multi").sort(i),c=o.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function RRs(e){const t=[],n=new Map([[iA,"rootEntityType"]]);for(const s of JX)n.set(aA[s],s);const r=new Set;for(const[s]of e.entries()){const o=n.get(s);if(!o||r.has(o))continue;if(r.add(o),o==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:o,value:l.filter(Boolean)});continue}if(o==="rootEntityType"||o==="entityName"||o==="serviceName"||o==="environment"||o==="provider"||o==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:o,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:o,value:i})}return t}function PRs(e){const t=new URLSearchParams,n=e.getAll(iA);for(const r of n)t.append(iA,r);for(const r of JX){const s=aA[r],o=e.getAll(s);for(const i of o)t.append(s,i)}return t}function $Rs(e,t){e.delete(iA);for(const n of JX)e.delete(aA[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?iA:aA[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(o=>typeof o=="string"&&o!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const o of s)e.append(r,o)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const MRs="Any";function pit(e){const t=e.trim();return t===""||t===MRs}const DRs=new Set(kJt.map(e=>e.entityType));function hit(e){const t=e.trim();return DRs.has(t)?t:void 0}function LRs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>!pit(o));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const o=s[0],i=o!==void 0?hit(o):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(pit(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const o=hit(s);o&&(t.rootEntityType=o)}else t[r]=s}}return t}const CJt=[{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"}],FRs=new Set(CJt.map(e=>e.value));function zRs(e){return typeof e=="string"&&(FRs.has(e)||e==="custom")}const EJt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function eJ(){return g.useContext(EJt)}function BRs(e,t){return e!=="custom"?CJt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${l_(t.from)} – ${l_(t.to)}`:l_(t.from)??"":"Custom range"}function URs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:o,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>LRs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=BRs(t,o),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:o,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,o,i,h,d,s,f,p,l,c]);return a.jsx(EJt.Provider,{value:m,children:e})}const r1e=1440*60*1e3,VRs={"24h":r1e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function qRs(e,t,n){if(e!=="custom"){const r=VRs[e]??r1e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-r1e),end:t?.to??new Date(n)}}function sg(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=eJ(),s=g.useRef(null),o=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==o)&&(s.current={key:o,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>qRs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${o}|${r}`,[o,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function TJt(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function V6({href:e,LinkComponent:t="a"}){return a.jsx(ae,{render:a.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:a.jsx(La,{})})}function HRs({href:e,LinkComponent:t="a"}){return a.jsx(ae,{render:a.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:a.jsx(c2n,{})})}function WRs({children:e,className:t}){return a.jsx("div",{className:W("flex shrink-0 items-center gap-1",t),children:e})}function ZRs({children:e,className:t}){return a.jsx("div",{className:W("overflow-x-auto",t),children:e})}function jJt({children:e,className:t}){return a.jsx("p",{className:W("mt-0.5 text-body text-placeholder",t),children:e})}function GRs({message:e="Failed to load data",className:t}){return a.jsx("div",{className:W("flex flex-col items-center justify-center gap-3",t),children:a.jsx("p",{className:"text-caption text-accent2",children:e})})}function QRs({className:e}){return a.jsx("div",{className:W("flex items-center justify-center",e),children:a.jsx(Cn,{size:"md",variant:"pulse",className:"text-placeholder"})})}function YRs({message:e="No data yet",className:t}){return a.jsx("div",{className:W("flex h-full items-center justify-center",t),children:a.jsx("p",{className:"text-body text-placeholder",children:e})})}function mit({children:e,className:t}){return a.jsx(ku,{className:W("grid min-h-72 min-w-80 flex-1 grid-rows-[auto_1fr] gap-4 px-4 py-3 2xl:min-w-120 md:min-w-88 lg:min-w-sm xl:min-w-104",t),children:e})}function KRs({value:e,label:t,className:n}){return a.jsxs("div",{className:W("text-right",n),children:[a.jsx("p",{className:"text-body text-muted-foreground tabular-nums",children:e}),t&&a.jsx("p",{className:"mt-0.5 text-body text-placeholder",children:t})]})}function NJt({children:e,className:t,as:n="h2"}){return a.jsx(n,{className:W("text-body text-foreground",t),children:e})}function XRs(e){if("children"in e)return a.jsx("div",{className:e.className,children:e.children});const{title:t,description:n,titleAs:r}=e;return a.jsxs("div",{className:e.className,children:[a.jsx(NJt,{as:r,children:t}),n&&a.jsx(jJt,{children:n})]})}function JRs({children:e,className:t}){return a.jsx("div",{className:W("flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1",t),children:e})}const tr=Object.assign(mit,{Root:mit,Kpi:xf,TopBar:JRs,Actions:WRs,TitleAndDescription:XRs,Title:NJt,Description:jJt,Summary:KRs,Loading:QRs,Error:GRs,Content:ZRs,NoData:YRs});function WW({data:e,series:t,className:n}){return a.jsx("div",{className:W("flex flex-wrap items-center gap-4 gap-y-1",n),children:t.map(r=>{const s=r.aggregate?.(e);return a.jsxs("div",{className:"inline-flex items-center gap-2",children:[a.jsx("div",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:r.color}}),a.jsx("span",{className:"max-w-24 truncate text-caption text-muted-foreground",children:r.label}),s&&a.jsxs("span",{className:"text-caption text-muted-foreground",children:[s.value,s.suffix&&a.jsxs("span",{className:"text-caption text-placeholder",children:[" ",s.suffix]})]})]},r.dataKey)})})}function ePs({active:e,payload:t,label:n,suffix:r}){return!e||!t?.length?null:a.jsxs(yIe,{children:[a.jsx("p",{className:"mb-1 text-column text-foreground",children:n}),t.map(s=>a.jsxs("p",{className:"text-foreground",children:[a.jsx("span",{className:"mr-2 inline-block size-2 rounded-full",style:{backgroundColor:s.color}}),s.name,":"," ",a.jsxs("span",{className:"font-mono",children:[typeof s.value=="number"?s.value.toLocaleString("en-US"):s.value,r]})]},s.name))]})}const tPs=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1});function nPs({points:e}){const[t,n]=e??[];return!t||!n?null:a.jsx("line",{x1:0,x2:0,y1:t.y,y2:n.y,stroke:"currentColor",strokeOpacity:.2,strokeWidth:1,className:"pointer-events-none text-black transition-transform duration-150 ease-out dark:text-white",style:{transform:`translateX(${t.x}px)`}})}function s1e({data:e,series:t,height:n=210,yDomain:r,onPointClick:s,xAxisInterval:o="preserveStartEnd",xAxisMinTickGap:i=28,showDots:l=!1,showLegend:c=!0}){const u=typeof s=="function";return a.jsxs("div",{children:[c&&a.jsx(WW,{data:e,series:t,className:"mb-4"}),a.jsx("div",{style:{height:n},children:a.jsx(C5,{width:"100%",height:"100%",children:a.jsxs(A3r,{data:e,margin:{top:5,right:5,bottom:5,left:0},children:[a.jsx(k4t,{stroke:"currentColor",strokeOpacity:.08,strokeDasharray:"4 4",vertical:!1,className:"text-black dark:text-white"}),a.jsx(L5,{dataKey:"time",tick:{fontSize:Rve,fill:M9e,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,interval:o,minTickGap:i}),a.jsx(F5,{tick:{fontSize:Rve,fill:M9e,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,width:"auto",tickFormatter:d=>tPs.format(d),domain:r,tickCount:3}),a.jsx(OY,{content:a.jsx(ePs,{}),cursor:a.jsx(nPs,{})}),t.map(d=>a.jsx(A4t,{type:"linear",dataKey:d.dataKey,stroke:d.color,strokeWidth:2,dot:l?{r:3,fill:d.color,strokeWidth:0}:!1,activeDot:u?{r:4,stroke:d.color,strokeOpacity:.3,strokeWidth:4,style:{cursor:"pointer"},onClick:(f,p)=>{const h=p?.payload;h&&s(h,d.dataKey)}}:{r:4,stroke:d.color,strokeOpacity:.3,strokeWidth:4},name:d.label},d.dataKey))]})})})]})}function rPs(e){return e==="agents"||e==="workflows"||e==="tools"}function git(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const o=s[t];return r+(typeof o=="number"&&Number.isFinite(o)?o:0)},0);return`${Math.round(n/e.length)}`}function sPs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const o1e={className:"max-h-80",mask:{left:!1}},By={pink:"var(--chart-pink)",purple:"var(--chart-purple)",blue:"var(--chart-blue)",blueDark:"var(--chart-blue-deep)",yellow:"var(--chart-yellow)"},IJt=[{dataKey:"p50",label:"p50",color:By.blue,aggregate:e=>({value:git(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:By.yellow,aggregate:e=>({value:git(e,"p95"),suffix:"avg ms"})}];function vce({data:e,onPointClick:t}){return e.length===0?a.jsx(tr.NoData,{message:"No latency data yet"}):a.jsx(s1e,{data:e,series:IJt,showLegend:!1,onPointClick:t?n=>sPs(n)?t(n):void 0:void 0})}function oPs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const o=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:o,workflows:i,tools:l},u=o?"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?.interval??"1h",y=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?{agents:e.agentData,workflows:e.workflowData,tools:e.toolData}[p]:[];return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Latency",description:m==="1h"?"Hourly p50 and p95 latency.":"Daily p50 and p95 latency."}),h?a.jsx(tr.Actions,{children:h}):null]}),t?a.jsx(tr.Loading,{}):n?a.jsx(tr.Error,{message:"Failed to load latency data"}):a.jsx(tr.Content,{children:y?a.jsxs(ll,{value:p,onValueChange:b=>{rPs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 [&>:first-child]:w-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"agents",disabled:!o,disabledTooltip:"No agent latency data for this period",children:"Agents"}),a.jsx(Lr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),a.jsx(Lr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),v.length>0&&a.jsx(WW,{data:v,series:IJt})]}),a.jsx(Ss,{value:"agents",className:"pt-3",children:a.jsx(vce,{data:e.agentData,onPointClick:r?b=>r("agents",b,m):void 0})}),a.jsx(Ss,{value:"workflows",className:"pt-3",children:a.jsx(vce,{data:e.workflowData,onPointClick:r?b=>r("workflows",b,m):void 0})}),a.jsx(Ss,{value:"tools",className:"pt-3",children:a.jsx(vce,{data:e.toolData,onPointClick:r?b=>r("tools",b,m):void 0})})]}):a.jsx(tr.NoData,{message:"No latency data yet"})})]})}function iPs(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 aPs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const o=new Date(s.getTime()+3600*1e3);return{from:s,to:o}}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 AJt(e,t,n,r,s,o,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"),o?.from&&e.set(n,o.from.toISOString()),o?.to&&e.set(r,o.to.toISOString());return}const l=iPs(s);l&&e.set(t,l)}function Ra(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function RJt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function vit({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const o=new URLSearchParams;o.set(mS,"branches"),AJt(o,gS,Yw,Kw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&o.set(N1,i),r.status&&o.set(I1,r.status),Ra(o,Kl.entityName,r.entityName??n.entityName),Ra(o,Kl.threadId,r.threadId??n.threadId),Ra(o,Kl.resourceId,r.resourceId??n.resourceId),Ra(o,Kl.entityId,n.entityId),Ra(o,Kl.runId,n.runId),Ra(o,Kl.sessionId,n.sessionId),Ra(o,Kl.requestId,n.requestId),Ra(o,Kl.userId,n.userId),Ra(o,Kl.organizationId,n.organizationId),Ra(o,Kl.experimentId,n.experimentId),Ra(o,Kl.serviceName,n.serviceName),Ra(o,Kl.environment,n.environment),RJt(o,Kl.tags,n.tags);const l=o.toString();return l?`${s}?${l}`:s}function lPs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const o=new URLSearchParams;AJt(o,kx,Ox,_x,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&o.set(x0,i),Ra(o,Nl.entityName,r.entityName??n.entityName),Ra(o,Nl.threadId,r.threadId??n.threadId),Ra(o,Nl.resourceId,r.resourceId??n.resourceId),Ra(o,Nl.runId,n.runId),Ra(o,Nl.sessionId,n.sessionId),Ra(o,Nl.requestId,n.requestId),Ra(o,Nl.userId,n.userId),Ra(o,Nl.organizationId,n.organizationId),Ra(o,Nl.experimentId,n.experimentId),Ra(o,Nl.serviceName,n.serviceName),Ra(o,Nl.environment,n.environment),RJt(o,Nl.tags,n.tags),r.status==="error"&&o.append(Nl.level,"error");const l=o.toString();return l?`${s}?${l}`:s}function BR(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=eJ(),o=g.useCallback((c={})=>vit({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>lPs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=aPs(u,d);return vit({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:o,getLogsHref:i,getBucketTracesHref:l}}const cPs=2880*60*1e3;function PJt({start:e,end:t}){return t.getTime()-e.getTime()<=cPs?"1h":"1d"}function $Jt(e,t){return t==="1h"?Fr(e,"time")??"":l_(e)??""}async function yce(e,t,n,r){const s=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:r,filters:n}),o=s.series.find(c=>c.percentile===.5),i=s.series.find(c=>c.percentile===.95);if(!o||!i)return[];const l=new Map(i.points.map(c=>[new Date(c.timestamp).getTime(),c.value]));return o.points.map(c=>{const u=new Date(c.timestamp),d=u.getTime();return{time:$Jt(u,r),tsMs:d,p50:Math.round(c.value),p95:Math.round(l.get(d)??0)}})}function uPs(){const e=Xe(),{timestamp:t,filters:n,filterKey:r}=sg(),s=PJt(t);return wt({queryKey:["metrics","latency",r,s],queryFn:async()=>{const[o,i,l]=await Promise.all([yce(e,"mastra_agent_duration_ms",n,s),yce(e,"mastra_workflow_duration_ms",n,s),yce(e,"mastra_tool_duration_ms",n,s)]);return{agentData:o,workflowData:i,toolData:l,interval:s}}})}const yit={agents:lu.AGENT,workflows:lu.WORKFLOW_RUN,tools:lu.TOOL};function dPs(){const{data:e,isLoading:t,isError:n}=uPs(),{getTracesHref:r,getBucketTracesHref:s}=BR(),{Link:o}=dn(),i=zr();return a.jsx(oPs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:yit[l]},c.tsMs,"1h"))},actions:l=>a.jsx(V6,{href:r({rootEntityType:yit[l]}),LinkComponent:o})})}function fPs(e){return e==="threads"||e==="resources"}function bce(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function pPs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:o}){const[i,l]=g.useState("threads"),c=e.data?.map(v=>({...v,key:v.threadId}))??[],u=t.data?.map(v=>({...v,key:v.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((v,b)=>v+b.runs,0)??0,h=t.data?.reduce((v,b)=>v+b.threadCount,0)??0,m=i==="threads"?e:t,y=typeof s=="function"?s(i):s;return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&a.jsx(tr.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&a.jsx(tr.Summary,{value:h.toLocaleString(),label:"Total threads"}),y?a.jsx(tr.Actions,{children:y}):null]}),m.isLoading?a.jsx(tr.Loading,{}):m.isError?a.jsx(tr.Error,{message:"Failed to load memory data"}):a.jsx(tr.Content,{children:a.jsxs(ll,{defaultTab:"threads",value:i,onValueChange:v=>{fPs(v)&&l(v)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"threads",children:"Threads"}),a.jsx(Lr,{value:"resources",children:"Resources"})]}),a.jsx(Ss,{value:"threads",className:"pt-3",children:d?a.jsxs(Oe,{columns:"auto auto auto auto auto",...o1e,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{sticky:"start",children:"Thread ID"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Resource ID"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Runs"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Tokens"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(v=>{const b=n?.(v),x=a.jsxs(a.Fragment,{children:[a.jsx(Oe.RowHeaderCell,{className:"text-caption",children:bce(v.threadId)}),a.jsx(Oe.NumberCell,{children:v.resourceId?bce(v.resourceId):"—"}),a.jsx(Oe.NumberCell,{highlight:!0,children:v.runs.toLocaleString()}),a.jsx(Oe.NumberCell,{children:v.tokens>0?$l(v.tokens):"—"}),a.jsx(Oe.NumberCell,{children:v.cost!=null?bm(v.cost,v.costUnit):"—"})]});return b?a.jsx(Oe.RowLink,{to:b,LinkComponent:o,children:x},v.key):a.jsx(Oe.RowStatic,{children:x},v.key)})]}):a.jsx(tr.NoData,{message:"No thread activity yet"})}),a.jsx(Ss,{value:"resources",className:"pt-3",children:f?a.jsxs(Oe,{columns:"auto auto auto auto",...o1e,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{sticky:"start",children:"Resource ID"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Threads"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Tokens"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(v=>{const b=r?.(v),x=a.jsxs(a.Fragment,{children:[a.jsx(Oe.RowHeaderCell,{className:"text-caption",children:bce(v.resourceId)}),a.jsx(Oe.NumberCell,{highlight:!0,children:v.threadCount.toLocaleString()}),a.jsx(Oe.NumberCell,{children:v.tokens>0?$l(v.tokens):"—"}),a.jsx(Oe.NumberCell,{children:v.cost!=null?bm(v.cost,v.costUnit):"—"})]});return b?a.jsx(Oe.RowLink,{to:b,LinkComponent:o,children:x},v.key):a.jsx(Oe.RowStatic,{children:x},v.key)})]}):a.jsx(tr.NoData,{message:"No resource activity yet"})})]})})]})}const xce=20;function hPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,o,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:xce}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:xce}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:xce})]),l=new Map,c=d=>FR(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(o.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 wce=20;function mPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,o,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:wce}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:wce}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:wce})]),l=new Map,c=d=>FR(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(o.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 gPs(){const e=hPs(),t=mPs(),{getTracesHref:n}=BR(),{Link:r}=dn();return a.jsx(pPs,{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 q6({value:e,currency:t,className:n}){const r=$l(e,{currency:t}),s=AE(e,{currency:t});return r===s?a.jsx("span",{className:W("tabular-nums",n),children:r}):a.jsxs(On,{children:[a.jsxs(Sn,{render:a.jsx("span",{tabIndex:0,className:W("tabular-nums",n)}),children:[a.jsx("span",{"aria-hidden":"true",children:r}),a.jsx("span",{className:"sr-only",children:s})]}),a.jsx(kn,{side:"right",children:s})]})}function H6({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:o,lowerIsBetter:i}){const l=t!=null;return a.jsxs(xf,{children:[a.jsx(xf.Label,{children:e}),a.jsxs(xf.ValueRow,{children:[l?a.jsx(xf.Value,{children:t}):null,o?a.jsx(xf.Error,{}):s?a.jsx(xf.Loading,{}):l?r!=null&&r!==0?a.jsx(xf.Change,{changePct:r,prevValue:n,lowerIsBetter:i}):a.jsx(xf.NoChange,{}):a.jsx(xf.NoData,{})]})]})}function vPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({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 yPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({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 bPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({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 xPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({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"})]),o=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:o?l:null,previousValue:i?c:null,changePercent:u}}})}function wPs(){const{data:e,isLoading:t,isError:n}=TJt();return a.jsx(H6,{label:"Total Agent Runs",value:e?.value!=null?a.jsx(q6,{value:e.value}):null,prevValue:e?.previousValue!=null?AE(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function SPs(){const{data:e,isLoading:t,isError:n}=bPs(),r=e?.costUnit??void 0;return a.jsx(H6,{label:"Total Model Cost",value:e?.cost!=null?a.jsx(q6,{value:e.cost,currency:r}):null,prevValue:e?.previousCost!=null?AE(e.previousCost,{currency:r}):void 0,changePct:e?.costChangePercent??null,lowerIsBetter:!0,isLoading:t,isError:n})}function kPs(){const{data:e,isLoading:t,isError:n}=xPs();return a.jsx(H6,{label:"Total Tokens",value:e?.value!=null?a.jsx(q6,{value:e.value}):null,prevValue:e?.previousValue!=null?AE(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function OPs(){const{data:e,isLoading:t,isError:n}=yPs();return a.jsx(H6,{label:"Total Threads",value:e?.value!=null?a.jsx(q6,{value:e.value}):null,prevValue:e?.previousValue!=null?AE(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function _Ps(){const{data:e,isLoading:t,isError:n}=vPs();return a.jsx(H6,{label:"Total Resources",value:e?.value!=null?a.jsx(q6,{value:e.value}):null,prevValue:e?.previousValue!=null?AE(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}const CPs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function EPs(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 TPs(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 jPs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=eJ(),s=g.useRef(e);s.current=e;const o=g.useRef(n);return o.current=n,a.jsx(QY,{preset:EPs(e),onPresetChange:i=>{const l=TPs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...o.current,[l]:i};o.current=c,r(c)},presets:CPs})}const rD=[Wr("/metrics")];function NPs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:o,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>IPs(f,o));return u?a.jsxs("div",{className:W("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx(vJt,{fields:o,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(mJt,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function IPs(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 i1e({children:e,filterFields:t,isLoading:n=!1}){const[r]=so(),{filterTokens:s,setFilterTokens:o}=eJ(),[i,l]=g.useState(),[c,u]=g.useState(()=>!!OJt()),d=()=>{NRs(r),u(!0),Qe.success("Filters setting for Metrics saved")},f=()=>{IRs(),u(!1),Qe.success("Filters setting for Metrics cleared up")},p=()=>{const h=s.map(m=>{const y=t.find(v=>v.id===m.fieldId);return y?y.kind==="text"?{fieldId:m.fieldId,value:""}:y.kind==="pick-multi"?y.multi?{fieldId:m.fieldId,value:[]}:{fieldId:m.fieldId,value:"Any"}:y.kind==="multi-select"?{fieldId:m.fieldId,value:[]}:m:m});o(h)};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),actionRow:a.jsxs(a.Fragment,{children:[a.jsx(Gn,{children:a.jsxs(Gn.Start,{children:[a.jsx(jPs,{}),a.jsx(bJt,{fields:t,tokens:s,onTokensChange:o,disabled:n,onStartTextFilter:l})]})}),a.jsx(NPs,{isLoading:n,filterFields:t,filterTokens:s,onFilterTokensChange:o,onClear:p,onRemoveAll:()=>o([]),onSave:d,onRemoveSaved:c?f:void 0,autoFocusFilterFieldId:i})]}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),e]})}function APs({error:e}){return _s(e)?a.jsx(Qs,{}):js(e)?a.jsx(Fs,{resource:"metrics"}):a.jsx(un,{tone:"error",titleSlot:"Failed to load storage capabilities",descriptionSlot:e.message})}const bit=_Jt({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function RPs({children:e}){const{supportsMetrics:t,isLoading:n,error:r}=F6();return n?a.jsx(i1e,{filterFields:bit,isLoading:!0,children:a.jsxs("div",{className:"flex h-full items-center justify-center gap-2",children:[a.jsx(Cn,{"aria-label":"Loading storage capabilities"}),a.jsx("span",{className:"text-caption text-muted-foreground",children:"Loading storage capabilities"})]})}):r?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(APs,{error:r})})]}):t?e:a.jsx(i1e,{filterFields:bit,children:a.jsx(un,{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:a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Ts,{}),children:"Metrics Documentation"}),variant:"fill"})})}function PPs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:o}){const i=!!e&&e.length>0;return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.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?bm(l):"—":c.size===1?u=l>0?bm(l,[...c][0]):"—":u="Mixed",a.jsx(tr.Summary,{value:u,label:"Total cost"})})(),s?a.jsx(tr.Actions,{children:s}):null]}),t?a.jsx(tr.Loading,{}):n?a.jsx(tr.Error,{message:"Failed to load model usage data"}):a.jsx(tr.Content,{children:i?a.jsxs(Oe,{columns:"auto auto auto auto auto auto",...o1e,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{sticky:"start",children:"Model"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Input"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Output"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cache Read"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cache Write"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=a.jsxs(a.Fragment,{children:[a.jsx(Oe.RowHeaderCell,{className:"text-caption",children:l.model}),a.jsx(Oe.NumberCell,{children:l.input}),a.jsx(Oe.NumberCell,{children:l.output}),a.jsx(Oe.NumberCell,{children:l.cacheRead}),a.jsx(Oe.NumberCell,{children:l.cacheWrite}),a.jsx(Oe.NumberCell,{highlight:!0,children:l.cost!=null?bm(l.cost,l.costUnit):"—"})]});return c?a.jsx(Oe.RowLink,{to:c,LinkComponent:o,children:u},l.model):a.jsx(Oe.RowStatic,{children:u},l.model)})]}):a.jsx(tr.NoData,{message:"No model usage data yet"})})]})}function $Ps(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,o,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||!o||!i)return[];const l=new Map,c=d=>FR(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 o.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:$l(f.input),output:$l(f.output),cacheRead:$l(f.cacheRead),cacheWrite:$l(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function MPs(){const{data:e,isLoading:t,isError:n}=$Ps(),{getTracesHref:r}=BR(),{Link:s}=dn();return a.jsx(PPs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:lu.AGENT}),actions:a.jsx(V6,{href:r({rootEntityType:lu.AGENT}),LinkComponent:s})})}function DPs(e){const t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim())?.[1];if(!t)return;const n=t.length===3?[...t].map(s=>s+s).join(""):t,r=s=>{const o=parseInt(n.slice(s,s+2),16)/255;return o<=.03928?o/12.92:((o+.055)/1.055)**2.4};return .2126*r(0)+.7152*r(2)+.0722*r(4)}function LPs(e){const t=e?DPs(e):void 0;return t!==void 0&&t>.25}function a1e({data:e,segments:t,maxVal:n,fmt:r,className:s,LinkComponent:o="a"}){const i=[...e].sort((c,u)=>{const d=u.values.reduce((p,h)=>p+h,0),f=c.values.reduce((p,h)=>p+h,0);return d-f}),l=t.length>1;return a.jsxs(Hr,{className:W("size-full",s),children:[a.jsxs("div",{className:"mt-2 mb-4 flex items-center gap-3",children:[a.jsx("div",{className:"flex flex-1 items-center gap-4",children:t.map(c=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"size-2 rounded-full",style:{backgroundColor:c.color}}),a.jsx("span",{className:"text-caption text-muted-foreground",children:c.label})]},c.label))}),a.jsx("span",{className:"shrink-0 pr-2 text-caption text-placeholder",children:"Total"})]}),a.jsx("div",{className:"grid gap-3.5",children:i.map(c=>{const u=c.values.reduce((h,m)=>h+m,0),d=`${n>0?u/n*100:0}%`,f=LPs(t[c.values.findIndex(h=>h>0)]?.color),p=a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"relative h-full min-w-0 flex-1",style:{"--bar-width":d},children:[a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("div",{className:W("absolute inset-y-0 left-0",c.href?"cursor-pointer":"cursor-default"),style:{width:d},children:t.map((h,m)=>{const y=c.values[m]??0,v=u>0?y/u*100:0,b=c.values.slice(0,m).reduce((_,C)=>_+(u>0?C/u*100:0),0),x=c.values.slice(m+1).every(_=>!_),w=c.href?void 0:c.hrefs?.[m],k=a.jsx("div",{className:W("absolute inset-y-0 opacity-40 dark:opacity-100",l&&m===0&&"rounded-l",l&&x&&"rounded-r",!l&&"rounded",w&&"cursor-pointer transition-opacity hover:opacity-70"),style:{left:l?`${b}%`:0,width:l?`${v}%`:`${v}%`,backgroundColor:h.color}});return w?a.jsx(o,{href:w,"aria-label":`${c.name} — ${h.label}`,className:"contents",children:k},h.label):a.jsx(FPs,{children:k},h.label)})})}),a.jsx(kn,{side:"top",className:"font-mono",children:a.jsx("div",{className:"grid gap-1",children:t.map((h,m)=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:h.label}),a.jsx("span",{className:"ml-auto pl-3",children:r(c.values[m]??0)})]},h.label))})})]}),a.jsx("div",{className:W("pointer-events-none absolute inset-0 z-10",f&&"dark:[clip-path:inset(0_0_0_var(--bar-width))]"),children:a.jsx("span",{className:"absolute inset-y-0 left-2.5 flex items-center truncate text-caption text-muted-foreground",children:c.name})}),f&&a.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-y-0 left-0 z-10 hidden w-(--bar-width) overflow-hidden dark:block",children:a.jsx("span",{className:"absolute inset-y-0 left-2.5 flex items-center text-caption whitespace-nowrap text-placeholder",children:c.name})})]}),a.jsx("span",{className:"shrink-0 pr-3 text-body text-muted-foreground tabular-nums",children:r(u)})]});return c.href?a.jsx(o,{href:c.href,className:"flex h-6 cursor-pointer items-center gap-14 rounded transition-colors outline-none hover:bg-fill-subtle focus-visible:bg-fill-subtle",children:p},c.name):a.jsx("div",{className:"flex h-6 items-center gap-14",children:p},c.name)})})]})}function FPs({children:e}){return a.jsx(a.Fragment,{children:e})}function zPs(e){return e==="tokens"||e==="cost"}function BPs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:o}){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,y=h?f.reduce((b,x)=>b+(x.cost??0),0):0,v=h&&y>0;return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&v?a.jsx(tr.Summary,{value:bm(y,m),label:"Total cost"}):a.jsx(tr.Summary,{value:$l(d),label:"Total tokens"})),u&&s?a.jsx(tr.Actions,{children:s}):null]}),t?a.jsx(tr.Loading,{}):n?a.jsx(tr.Error,{message:"Failed to load token usage data"}):a.jsx(tr.Content,{children:u?a.jsxs(ll,{defaultTab:"tokens",value:i,onValueChange:b=>{zPs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"tokens",children:"Tokens"}),a.jsx(Lr,{value:"cost",children:"Cost"})]}),a.jsx(Ss,{value:"tokens",className:"pt-3",children:a.jsx(a1e,{LinkComponent:o,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:By.blueDark},{label:"Output",color:By.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:$l})}),a.jsx(Ss,{value:"cost",className:"pt-3",children:v?a.jsx(a1e,{LinkComponent:o,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:By.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>bm(b,m)}):a.jsx(tr.NoData,{message:"No cost data yet"})})]}):a.jsx(tr.NoData,{message:"No token usage data yet"})})]})}function UPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,o]=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=>FR(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 o.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 VPs(){const{data:e,isLoading:t,isError:n}=UPs(),{getTracesHref:r}=BR(),{Link:s}=dn();return a.jsx(BPs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:o=>r({rootEntityType:lu.AGENT,entityName:o.name}),actions:a.jsx(V6,{href:r({rootEntityType:lu.AGENT}),LinkComponent:s})})}function l1e(e,t=$l){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const xit=[{dataKey:"input",label:"Input tokens",color:By.blue,aggregate:l1e("input")},{dataKey:"output",label:"Output tokens",color:By.yellow,aggregate:l1e("output")}];function qPs(e){return e==="tokens"||e==="cost"}function HPs({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[o,i]=g.useState("tokens"),l=e??[],c=l.map(w=>({...w})),u=l.length>0,d=l.filter(w=>w.cost!=null&&w.cost>0),f=d.map(w=>({...w})),p=new Set(d.map(w=>w.costUnit).filter(w=>!!w)),h=p.size===1&&d.every(w=>w.costUnit!=null),m=h?[...p][0]??null:null,y=h?d.reduce((w,k)=>w+(k.cost??0),0):0,v=h&&y>0,b=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",x=[{dataKey:"cost",label:"Cost",color:By.purple,aggregate:l1e("cost",w=>bm(w,m))}];return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Token usage over time",description:b}),u&&s?a.jsx(tr.Actions,{children:s}):null]}),n?a.jsx(tr.Loading,{}):r?a.jsx(tr.Error,{message:"Failed to load token usage timeline"}):a.jsx(tr.Content,{children:u?a.jsxs(ll,{defaultTab:"tokens",value:o,onValueChange:w=>{qPs(w)&&i(w)},className:"overflow-visible",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 [&>:first-child]:w-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"tokens",children:"Tokens"}),a.jsx(Lr,{value:"cost",children:"Cost"})]}),o==="tokens"?a.jsx(WW,{data:c,series:xit}):v?a.jsx(WW,{data:f,series:x}):null]}),a.jsx(Ss,{value:"tokens",className:"pt-3",children:a.jsx(s1e,{data:c,series:xit,showLegend:!1})}),a.jsx(Ss,{value:"cost",className:"pt-3",children:v?a.jsx(s1e,{data:f,series:x,showLegend:!1}):a.jsx(tr.NoData,{message:"No cost data yet"})})]}):a.jsx(tr.NoData,{message:"No token usage data yet"})})]})}function wit(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const o=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};o[n]+=r.value,r.estimatedCost!=null&&(o.cost=(o.cost??0)+r.estimatedCost,t?.costUnit?o.costUnits.add(t.costUnit):o.hasUnknownCostUnit=!0),e.set(s,o)}}function WPs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function ZPs(){const e=Xe(),{timestamp:t,filters:n,filterKey:r}=sg(),s=PJt(t);return wt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[o,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 wit(l,o.series[0],"input"),wit(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:$Jt(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:WPs(u)}}),interval:s}}})}function GPs(){const{data:e,isLoading:t,isError:n}=ZPs(),{getTracesHref:r}=BR(),{Link:s}=dn();return a.jsx(HPs,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:a.jsx(V6,{href:r(),LinkComponent:s})})}function Sce({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return a.jsx(a1e,{LinkComponent:r,data:e.map(s=>{const o=n?.(s),i=t?.(s);return o?{name:s.name,values:[s.completed,s.errors],hrefs:[i,o]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:By.blueDark},{label:"Errors",color:By.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:$l})}function QPs({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:o,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof o=="function"?o(l):o,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,y)=>m+y.completed+y.errors,0):0,p=m=>r?y=>r(m,y):void 0,h=m=>s?y=>s(m,y):void 0;return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&a.jsx(tr.Summary,{value:$l(f),label:"Total runs"}),u?a.jsx(tr.Actions,{children:u}):null]}),t?a.jsx(tr.Loading,{}):n?a.jsx(tr.Error,{message:"Failed to load trace volume data"}):a.jsx(tr.Content,{children:d?a.jsxs(ll,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"agents",children:"Agents"}),a.jsx(Lr,{value:"workflows",children:"Workflows"}),a.jsx(Lr,{value:"tools",children:"Tools"})]}),a.jsx(Ss,{value:"agents",className:"pt-3",children:e.agentData.length>0?a.jsx(Sce,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):a.jsx(tr.NoData,{message:"No agent data yet"})}),a.jsx(Ss,{value:"workflows",className:"pt-3",children:e.workflowData.length>0?a.jsx(Sce,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):a.jsx(tr.NoData,{message:"No workflow data yet"})}),a.jsx(Ss,{value:"tools",className:"pt-3",children:e.toolData.length>0?a.jsx(Sce,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):a.jsx(tr.NoData,{message:"No tool data yet"})})]}):a.jsx(tr.NoData,{message:"No trace volume data yet"})})]})}async function kce(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const o of r.groups){const i=o.dimensions.entityName??"unknown",l=o.dimensions.status??"ok",c=FR(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=o.value:c.completed+=o.value}return Array.from(s.entries()).map(([o,i])=>({name:o,...i})).sort((o,i)=>i.completed+i.errors-(o.completed+o.errors))}function YPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,o]=await Promise.all([kce(e,"mastra_agent_duration_ms",t),kce(e,"mastra_workflow_duration_ms",t),kce(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:o}}})}const dB={agents:lu.AGENT,workflows:lu.WORKFLOW_RUN,tools:lu.TOOL};function KPs(){const{data:e,isLoading:t,isError:n}=YPs(),{getTracesHref:r,getLogsHref:s}=BR(),{Link:o}=dn();return a.jsx(QPs,{data:e,isLoading:t,isError:n,LinkComponent:o,getRowHref:(i,l)=>r({rootEntityType:dB[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:dB[i],entityName:l.name,status:"error"}):void 0,actions:i=>a.jsxs(a.Fragment,{children:[a.jsx(V6,{href:r({rootEntityType:dB[i]}),LinkComponent:o}),a.jsx(HRs,{href:s({rootEntityType:dB[i],status:"error"}),LinkComponent:o})]})})}const Oce="period",fB="dateFrom",pB="dateTo";function XPs(){const[e,t]=so(),n=e.get(Oce),r=zRs(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(fB)),p=d(e.get(pB));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),o=g.useMemo(()=>RRs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Oce):p.set(Oce,d),d!=="custom"&&(p.delete(fB),p.delete(pB)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(fB,d.from.toISOString()):p.delete(fB),d?.to?p.set(pB,d.to.toISOString()):p.delete(pB),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return $Rs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,ARs(e)))return;const d=OJt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),a.jsx(URs,{preset:r,filterTokens:o,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:a.jsx(RPs,{children:a.jsx(JPs,{})})})}function JPs(){const{error:e,isLoading:t}=TJt(),{isInMemory:n}=F6(),{data:r,isLoading:s}=SJt(),{data:o,isLoading:i}=WMe(),{data:l,isLoading:c}=wJt(),{data:u,isLoading:d}=ZMe(),f=g.useMemo(()=>_Jt({availableTags:r??[],availableEntityNames:o??[],availableServiceNames:l??[],availableEnvironments:u??[],loading:{tags:s,entityNames:i,serviceNames:c,environments:d}}),[r,o,l,u,s,i,c,d]);return e&&_s(e)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Qs,{variant:"fill"})]}):e&&js(e)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Fs,{variant:"fill",resource:"metrics"})]}):e?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load metrics",descriptionSlot:e.message})]}):a.jsx(i1e,{filterFields:f,isLoading:t,children:a.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[n&&a.jsx(Jt,{variant:"info",title:"Metrics are not persisted",children:a.jsx(Jt.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."})}),a.jsxs(TRs,{children:[a.jsx(wPs,{}),a.jsx(SPs,{}),a.jsx(kPs,{}),a.jsx(OPs,{}),a.jsx(_Ps,{})]}),a.jsxs(jRs,{children:[a.jsx(MPs,{}),a.jsx(VPs,{}),a.jsx(GPs,{}),a.jsx(gPs,{}),a.jsx(KPs,{}),a.jsx(dPs,{})]})]})})}function e$s(){const{isCmsAvailable:e}=kb(),{paths:t}=dn();return e?a.jsx(mK,{href:t.cmsPromptBlockCreateLink(),tooltip:"Create a prompt",children:"New prompt"}):null}const lM=[Wr("/prompts")],t$s=50,n$s=["updatedAt"];function r$s(){const[e,t]=g.useState(""),[n,r]=g.useState(0),[s,o]=so(),{sort:i,onSortChange:l}=fk({searchParams:s,setSearchParams:o,allowedKeys:n$s}),c=g.useMemo(()=>i?{field:i.key,direction:i.direction==="asc"?"ASC":"DESC"}:void 0,[i]),{data:u,isLoading:d,error:f,isPlaceholderData:p}=wQt({page:n,perPage:t$s,orderBy:c}),h=u?.promptBlocks??[],m=u?.hasMore??!1,y=g.useCallback(()=>{p||r(w=>w+1)},[p]),v=g.useCallback(()=>{p||r(w=>Math.max(0,w-1))},[p]),b=g.useCallback(w=>{t(w),r(0)},[]),x=g.useCallback((w,k)=>{l(w,k),r(0)},[l]);return f&&_s(f)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Qs,{variant:"fill"})]}):f&&js(f)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Fs,{variant:"fill",resource:"prompt blocks"})]}):f?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load prompt blocks",descriptionSlot:f.message})]}):h.length===0&&!d&&n===0?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(rxs,{})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),headerActions:a.jsx(e$s,{}),actionRow:a.jsx(Gn,{children:a.jsx(Gn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{onSearch:b,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(nxs,{promptBlocks:h,isLoading:d,search:e,currentPage:n,hasMore:m,onNextPage:y,onPrevPage:v,updatedSort:i?.direction,onSortChange:x})]})}const s$s=[Wr("/request-context")];function o$s(){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:s$s}),children:[a.jsx("h1",{className:"sr-only",children:"Request Context"}),a.jsx("div",{children:a.jsx(fms,{children:a.jsx(pSe,{})})})]})}const i$s=[Wr("/resources")],a$s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:A$n,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:dSt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Ts,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:E3,href:"https://discord.gg/mastra-ai",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:ySt,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:r_e,href:"https://mastra.ai/contact?ref=studio",external:!0}];function l$s(){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:i$s}),children:[a.jsx("h1",{className:"sr-only",children:"Resources"}),a.jsx("div",{children:a.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:a$s.map(e=>a.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group state-layer flex flex-col gap-3 rounded-lg border border-border bg-background p-5 hover:border-accent1",children:[a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx(e.icon,{className:W("h-5 w-5 text-muted-foreground group-hover:text-accent1",vn)}),a.jsx("span",{className:"text-subheading text-foreground",children:e.title}),e.external&&a.jsx(Ts,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]}),a.jsx("p",{className:"text-text3 text-caption",children:e.description})]},e.href))})})]})}function Sit(){const{isCmsAvailable:e}=kb(),{paths:t}=dn();return e?a.jsx(mK,{href:t.cmsScorersCreateLink(),tooltip:"Create a scorer",children:"New scorer"}):null}const cM=[Wr("/scorers")];function c$s(){const{data:e={},isLoading:t,error:n}=lh(),[r,s]=g.useState(""),[o,i]=g.useState("all"),[l,c]=g.useState();if(n&&_s(n))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Qs,{variant:"fill"})]});if(n&&js(n))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Fs,{variant:"fill",resource:"scorers"})]});if(n)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load scorers",descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),headerActions:a.jsx(Sit,{}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Fgs,{})]});const u=o!=="all"||r!=="",d=()=>{s(""),i("all")};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),headerActions:a.jsx(Sit,{}),actionRow:a.jsx(Bgs,{search:r,onSearchChange:s,sourceFilter:o,onSourceFilterChange:i,onReset:d,hasActiveFilters:u}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Lgs,{scorers:e,isLoading:t,search:r,sourceFilter:o,sort:l,onSortChange:(f,p)=>c({key:p,direction:f})})]})}const MJt=["input","entity"],u$s={input:"Input",entity:"Entity"};function d$s(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function f$s(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(MJt.filter(o=>!e.has(o))),[e]),r=g.useMemo(()=>d$s(n),[n]),s=g.useCallback(o=>{t(i=>{const l=new Set(i);return l.has(o)?l.delete(o):l.add(o),l})},[]);return{visibleColumns:n,columns:r,toggleColumn:s}}function p$s({visibleColumns:e,toggleColumn:t}){return a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{icon:a.jsx(Vve,{}),children:"Columns"})}),a.jsxs(pt.Content,{align:"end",children:[a.jsx(pt.Label,{children:"Toggle columns"}),MJt.map(n=>a.jsx(pt.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:u$s[n]},n))]})]})}const kit=[Wr("/scorers"),xqn],h$s=["date","score"];function m$s(){const{scorerId:e}=fr(),[t,n]=so(),r=t.get("scoreId")??void 0,[s,o]=g.useState(r),[i,l]=g.useState(!1),c=zr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:p}=eqn(e),h=f$s(),{data:m={},isLoading:y,error:v}=ef(),{isLoading:b,error:x}=ih(),{sort:w,onSortChange:k}=fk({searchParams:t,setSearchParams:n,allowedKeys:h$s}),{data:_=[],isLoading:C,error:T,isFetchingNextPage:E,hasNextPage:I,setEndOfListElement:N}=JVn({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),A=g.useMemo(()=>G0(_,w,{date:K=>K.createdAt,score:K=>typeof K.score=="number"?K.score:void 0}),[_,w]),P=g.useMemo(()=>f?.agentIds?.filter(K=>m[K]).map(K=>({value:K,label:m[K].name,type:"AGENT"}))||[],[f?.agentIds,m]),F=g.useMemo(()=>f?.workflowIds?.map(K=>({value:K,label:K,type:"WORKFLOW"}))||[],[f?.workflowIds]),D=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...P,...F],[P,F]),H=t.get("entity")??"all",q=D.find(K=>K.value===H);q&&q.value!==u?.value&&d(q),g.useEffect(()=>{if(p){const K=p instanceof Error?p.message:"Failed to load scorer";Qe.error(`Error loading scorer: ${K}`)}},[p]),g.useEffect(()=>{if(v){const K=v instanceof Error?v.message:"Failed to load agents";Qe.error(`Error loading agents: ${K}`)}},[v]),g.useEffect(()=>{if(x){const K=x instanceof Error?x.message:"Failed to load workflows";Qe.error(`Error loading workflows: ${K}`)}},[x]);const V=K=>{K?.value&&n(ee=>{const ne=new URLSearchParams(ee);return ne.set("entity",K.value),ne})};g.useEffect(()=>{const K=t.get("scoreId")??void 0;if(K===s)return;if(!K){o(void 0);return}A.find(ne=>ne.id===K)&&o(K)},[t,A]);const B=g.useCallback(K=>{o(K||void 0),n(ee=>{const ne=new URLSearchParams(ee);return K?ne.set("scoreId",K):ne.delete("scoreId"),ne})},[n]);if(!f)return null;const Z=_s(p)||_s(v)||_s(x),z=p&&js(p),Y=!Z&&!z&&(p||v||x),L=!C&&A.length===0,R=u?.value!=="all",M=f?.source==="stored",U=e?a.jsx(ZX,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:K=>{c(`/experiments/${K}`)}}):null,Q=M?a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{size:"lg","aria-label":"Scorer actions menu",children:a.jsx(U1,{})})}),a.jsx(pt.Content,{align:"end",className:"w-48",children:a.jsxs(pt.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[a.jsx(Bd,{})," Edit Scorer"]})})]}):null;if(Z||z||Y||L&&!R){const K=(p instanceof Error?p.message:void 0)??(v instanceof Error?v.message:void 0)??(x instanceof Error?x.message:void 0)??"An unexpected error occurred",ee=Z||z||Y;return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:kit}),actionRow:!ee&&Q?a.jsx(Gn,{children:a.jsx(Gn.End,{children:Q})}):void 0,children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"flex h-full items-center justify-center",children:Z?a.jsx(Qs,{}):z?a.jsx(Fs,{resource:"scorers"}):Y?a.jsx(un,{tone:"error",titleSlot:"Failed to load scorer",descriptionSlot:K}):a.jsx($gs,{onRunExperiment:()=>l(!0)})}),U]})}return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:kit}),actionRow:a.jsxs(Gn,{children:[a.jsx(Gn.Start,{children:a.jsx(Mgs,{selectedEntity:u,entityOptions:D,onEntityChange:V,onReset:()=>{n(K=>{const ee=new URLSearchParams(K);return ee.set("entity","all"),ee})},isLoading:C||y||b})}),a.jsxs(Gn.End,{children:[a.jsx(p$s,{visibleColumns:h.visibleColumns,toggleColumn:h.toggleColumn}),a.jsx(ae,{variant:"primary",onClick:()=>l(!0),icon:a.jsx(bu,{}),children:"Run Experiment"}),Q]})]}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Pgs,{scores:A,isLoading:C,selectedScoreId:s,isFetchingNextPage:E,hasNextPage:I,setEndOfListElement:N,onScoreClick:B,errorMsg:T?.message,columnsState:h,sort:w,onSortChange:k}),U]})}const g$s=[{value:"system",label:"System",icon:a.jsx(MSt,{})},{value:"light",label:"Light",icon:a.jsx(KDn,{})},{value:"dark",label:"Dark",icon:a.jsx(E2n,{})}],v$s={md:{itemGap:2,itemWidth:28,root:"gap-0.5 p-0.5",indicator:"inset-y-0.5 left-0.5",item:"h-6 [&_svg]:size-3.5"},xs:{itemGap:1,itemWidth:20,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-4 [&_svg]:size-icon-xs"},sm:{itemGap:1,itemWidth:24,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-5 [&_svg]:size-icon-xs"}},y$s=({value:e,onChange:t,options:n=g$s,size:r="md",className:s,"aria-label":o="Theme",...i})=>{const{theme:l,setTheme:c}=M3(),u=e??l,d=t??c,f=n.some(v=>v.value===u)?u:n[0]?.value??"system",p=v=>{const b=n.find(x=>x.value===v);b&&d(b.value)},h=Math.max(0,n.findIndex(v=>v.value===f)),m=v$s[r],y=h*(m.itemWidth+m.itemGap);return a.jsxs(g7t,{...i,value:f,onValueChange:p,"aria-label":o,className:W(ir,"relative inline-flex w-fit items-center rounded-full",m.root,s),children:[a.jsx("span",{"aria-hidden":"true",className:W("pointer-events-none absolute rounded-full bg-fill-hover motion-reduce:transition-none",vo.transform,m.indicator),style:{width:m.itemWidth,transform:`translateX(${y}px)`}}),n.map(v=>a.jsx(m7t,{value:v.value,"aria-label":v.label,style:{width:m.itemWidth},className:W("relative inline-flex cursor-pointer items-center justify-center rounded-full","text-muted-foreground hover:text-foreground data-[checked]:text-foreground",m.item,"focus-visible:outline-hidden","active:scale-90 motion-reduce:transition-none",vo.colors,vo.transform),children:a.jsx("span",{"aria-hidden":"true",className:"pointer-events-none inline-flex items-center justify-center",children:v.icon})},v.value))]})},b$s=[Wr("/settings")],x$s=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=N3();return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:b$s}),children:[a.jsx("h1",{className:"sr-only",children:"Settings"}),a.jsx(cvs,{children:a.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[a.jsxs(nrt,{children:[a.jsxs(rrt,{children:[a.jsx(srt,{children:"General"}),a.jsx(ort,{children:"Stored in this browser."})]}),a.jsx(IGt,{children:a.jsx(ySe,{label:"Theme",description:"Customize the appearance of the studio.",children:a.jsx(y$s,{})})})]}),a.jsxs(nrt,{children:[a.jsxs(rrt,{children:[a.jsx(srt,{children:"Mastra Connection"}),a.jsx(ort,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),a.jsx(VGt,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})]})};function w$s(){const[e]=so(),t=zr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(hJt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function S$s(e){return e.replace(/\/$/,"").split("/").pop()}function k$s({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?a.jsx("div",{className:W("grid gap-y-4",n),children:Array.from({length:5}).map((o,i)=>a.jsx("div",{className:"h-16 animate-pulse rounded-lg bg-card"},i))}):a.jsx("div",{className:W("grid gap-y-4",n),children:e.map(o=>{const i=o?.agents||o?.tools||o?.networks||o?.workflows||o?.mcp;return a.jsxs("article",{className:W(ir,"state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg"),children:[a.jsxs(s,{to:`/templates/${o.slug}`,className:W("group grid",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":o.imageURL}),children:[o.imageURL&&a.jsx("div",{className:W("overflow-hidden"),children:a.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${o.imageURL})`}})}),a.jsxs("div",{className:W("grid w-full gap-0.5 px-4 py-3","[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground"),children:[a.jsx("h2",{className:"text-body text-foreground",children:o.title}),a.jsx("p",{className:W("text-body",Ky,vn),children:o.description}),a.jsxs("div",{className:"mt-3 hidden flex-wrap items-center gap-4 text-body text-muted-foreground 2xl:flex",children:[i&&a.jsxs("ul",{className:W("m-0 flex list-none gap-4 p-0 text-body text-muted-foreground","text-muted-foreground [&>li]:flex [&>li]:items-center [&>li]:gap-0.5"),children:[o?.agents&&o.agents.length>0&&a.jsxs("li",{children:[a.jsx(Pi,{})," ",o.agents.length]}),o?.tools&&o.tools.length>0&&a.jsxs("li",{children:[a.jsx(Hd,{})," ",o.tools.length]}),o?.networks&&o.networks.length>0&&a.jsxs("li",{children:[a.jsx(DSt,{})," ",o.networks.length]}),o?.workflows&&o.workflows.length>0&&a.jsxs("li",{children:[a.jsx(q1,{})," ",o.workflows.length]}),o?.mcp&&o.mcp.length>0&&a.jsxs("li",{children:[a.jsx(sE,{})," ",o.mcp.length]})]}),i&&o.supportedProviders&&a.jsx("small",{children:"|"}),a.jsx("div",{className:"flex items-center gap-4 text-muted-foreground",children:o.supportedProviders.map(l=>a.jsx("span",{className:"",children:l},l))})]})]})]}),a.jsx("a",{href:o.githubUrl,className:W("group ml-auto hidden items-center gap-2 pr-4 text-body","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:a.jsxs("span",{className:W("flex items-center gap-2 rounded bg-sidebar px-2 py-1",Xwt,Ky,vn),children:[a.jsx(hK,{})," ",S$s(o.githubUrl)]})})]},o.slug)})})}function O$s({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:o,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?a.jsxs("div",{className:W("flex h-[6.5rem] items-center gap-5","[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card",u),children:[a.jsx("div",{})," ",a.jsx("div",{})," ",a.jsx("div",{})]}):a.jsxs("div",{className:W("sticky top-0 mx-auto flex flex-wrap gap-4 bg-background py-5",u),children:[a.jsx(nL,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),a.jsx(wu,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),a.jsx(wu,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:o,options:n}),c&&a.jsx(ae,{onClick:c,icon:a.jsx(Gt,{}),children:"Reset"})]})}const _$s=[{id:"templates",label:"Templates"}];function C$s(){const{data:e,isLoading:t}=Evr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[o,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,w)=>{w==="tag"?i(x):w==="provider"&&c(x)},m=x=>{d(x)},y=()=>{i("all"),c("all"),d("")},v=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||o!=="all"&&!x.tags.includes(o)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||o!=="all"||l!=="all";return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:_$s}),children:[a.jsx("h1",{className:"sr-only",children:"Templates"}),a.jsx(I3,{children:a.jsxs(b1t,{children:[a.jsx(_t,{children:a.jsx(zx,{})}),"Templates"]})}),a.jsxs("div",{className:W("z-10 h-full w-full overflow-y-auto px-5 pb-12"),children:[a.jsx(O$s,{selectedTag:o,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?y:void 0,className:"max-w-[80rem]",isLoading:t}),a.jsx(k$s,{templates:v,linkComponent:ml,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const E$s="1.71.0-alpha.1";function tJ({children:e,className:t}){return a.jsx("div",{className:W("transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12",t),children:e})}function T$s({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,o=()=>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:a.jsx(cu,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:a.jsx(H$n,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return a.jsxs(tJ,{className:"mb-5 content-center space-y-4 text-muted-foreground",children:[a.jsxs("div",{className:W("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[l,a.jsxs("div",{className:"space-y-2 text-center",children:[a.jsx("p",{className:"text-subheading text-foreground",children:c}),a.jsx("p",{className:"text-body text-muted-foreground",children:o()})]})]}),t&&t.length>0&&a.jsxs("details",{className:"text-caption",children:[a.jsxs("summary",{className:W(Pn,"cursor-pointer text-center select-none"),children:["Show Validation Issues (",t.length,")"]}),a.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left text-caption",children:t.map((u,d)=>a.jsxs("div",{className:"border-l-2 border-destructive pl-2",children:[a.jsx("div",{className:"font-medium text-destructive",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),a.jsx("pre",{className:"mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground",children:u.message})]},d))})]}),n&&!s&&a.jsxs("details",{className:"text-caption",children:[a.jsx("summary",{className:W(Pn,"cursor-pointer text-center select-none"),children:"Show Details"}),a.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left text-caption",children:a.jsx("pre",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}const j$s=g.createContext(null);function N$s(){const e=g.useContext(j$s);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const DJt=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{const[s]=g.useState(e),[o]=g.useState(t),[i,l]=g.useState(t),[c,u]=g.useState(e||""),[d,f]=g.useState(!1),[p,h]=g.useState(!1),[m,y]=g.useState(!1),{data:v,isLoading:b}=q5(),x=T0(),{models:w}=U0(),k=g.useMemo(()=>v?.providers||[],[v]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const _=si(c),T=bN(k,_)?.id||_,E=async D=>{if(l(D),D&&T){f(!0);try{const H=await n({provider:T,modelId:D});console.info("Model updated:",H)}catch(H){console.error("Failed to update model:",H)}finally{f(!1)}}},I=D=>{const H=si(D);u(H),H!==_&&(l(""),y(!0))},{registerResetFn:N}=N$s();if(g.useEffect(()=>(N(()=>{if(p||m)return;if(_&&_!==s&&(!i||i==="")){u(si(s)),l(o);const B=bN(k,s)?.id||s;B&&o&&n({provider:B,modelId:o}).catch(Z=>{console.error("Failed to reset model:",Z)})}}),()=>{N(null)}),[N,_,i,s,o,n,p,m,k]),b)return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Cn,{}),a.jsx("span",{className:"text-body text-muted-foreground",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(D){console.error("Failed to reset model:",D)}finally{f(!1)}},P=bN(k,_);if(x.active&&x.pickerVisible===!1){const D=x.default&&x.default.provider&&x.default.modelId?`${x.default.provider}/${x.default.modelId}`:c&&i?`${c}/${i}`:"Locked by admin";return a.jsxs("div",{className:W(ir,"flex items-center gap-2 rounded-md px-3 py-2"),"data-testid":"agent-metadata-model-locked",children:[a.jsx(ed,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx("span",{className:"truncate text-caption text-foreground",children:D}),a.jsx("span",{className:"ml-auto shrink-0 text-meta text-muted-foreground",children:"Set by admin"})]})}const F=!!(_&&i)&&x.active&&x.allowed!==void 0&&!w.some(D=>si(D.provider)===_&&D.model===i);return a.jsxs("div",{className:"@container",children:[a.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[a.jsx("div",{className:"w-full @xs:w-2/5",children:a.jsx(rk,{value:_,onValueChange:I,open:p,onOpenChange:h})}),a.jsx("div",{className:"w-full @xs:w-3/5",children:a.jsx(sk,{llmId:_,value:i,onValueChange:E,open:m,onOpenChange:y})}),a.jsx(ae,{variant:"default",size:"md",onClick:A,disabled:d,className:"flex items-center gap-1.5 border-0! text-caption whitespace-nowrap",title:"Reset to original model",children:a.jsx(QC,{className:"h-3.5 w-3.5"})})]}),F&&a.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:a.jsx(Jt,{variant:"warning",title:"Model not allowed",children:a.jsxs(Jt.Message,{children:[a.jsxs("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:[c,"/",i]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),P&&!P.connected&&a.jsx("div",{className:"p-2 pt-2",children:a.jsx(Jt,{variant:"warning",title:"Provider not connected",children:a.jsxs(Jt.Message,{children:["Set the"," ",a.jsx("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:Array.isArray(P.envVar)?P.envVar.join(", "):P.envVar})," ","environment"," ",Array.isArray(P.envVar)&&P.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function I$s({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:o,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return a.jsx(tJ,{children:a.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5",children:[a.jsxs("h2",{className:W("flex items-center gap-2 text-heading text-muted-foreground","[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]"),children:["Install Template ",a.jsx(LSt,{})]}),a.jsx(wu,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-body text-muted-foreground",children:"Set required Environmental Variables"}),a.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?a.jsxs("div",{className:W("col-span-2 flex items-center justify-center gap-4 text-caption text-muted-foreground","[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50","animate-in duration-300 fade-in"),children:[a.jsx(Cn,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>a.jsxs(g.Fragment,{children:[a.jsx(qi,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),a.jsx(qi,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),a.jsxs("div",{className:"relative mt-3.5 border-t border-border pt-12",children:[a.jsx("div",{className:"absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background text-caption text-muted-foreground",children:"And"}),a.jsx("h3",{className:"text-body text-muted-foreground",children:"Set AI Model for Template Installation"}),a.jsx("p",{className:"mt-2 mb-5 text-body text-muted-foreground",children:"This model will be used by the workflow to process and install the template"}),a.jsx(DJt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&a.jsx(ae,{className:W("state-layer mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card text-body text-foreground","[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]"),onClick:o,disabled:!t||!u||!d||s.length>0||c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(Cn,{className:"h-4 w-4"})," Installing..."]}):a.jsxs(a.Fragment,{children:["Install ",a.jsx(qf,{})]})})]})})}function A$s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:o}){const i=o?`feat/install-template-${o}`:"feat/install-template-[slug]";return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:W("mt-5 grid items-center"),children:a.jsxs("div",{className:W("flex items-center gap-3 text-title","[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[a.jsx(zx,{}),a.jsx("h2",{className:W({"flex min-w-[50%] rounded-lg bg-muted":r}),children:r?a.jsx(a.Fragment,{children:" "}):e})]})}),a.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[a.jsxs("div",{className:"grid",children:[a.jsx("p",{className:W("mt-2 mb-4 text-body text-muted-foreground",{"rounded-lg bg-muted":r}),children:r?a.jsx(a.Fragment,{children:" "}):t}),!r&&o&&a.jsxs("div",{className:W("mb-4 rounded-lg border border-border bg-background p-4","flex items-start gap-3"),children:[a.jsx("div",{className:"mt-0.5 shrink-0",children:a.jsx(Hf,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(XN,{className:"h-[1em] w-[1em] text-muted-foreground"}),a.jsx("span",{className:"text-subheading text-foreground",children:"A new Git branch will be created"})]}),a.jsxs("div",{className:"space-y-1 text-caption text-muted-foreground",children:[a.jsxs("div",{children:[a.jsx("span",{className:"font-medium",children:"Branch name:"})," ",a.jsx(w1,{children:i})]}),a.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&a.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:W(Pn,"mt-auto flex items-center gap-2 text-body"),children:[a.jsx(hK,{}),n?.split("/")?.pop()]})]}),s&&a.jsx(Q$e,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Oit(e){switch(e){case"running":return a.jsx(Cn,{size:"sm","aria-hidden":!0});case"success":return a.jsx(Vn,{"aria-hidden":!0});case"failed":return a.jsx(Gt,{"aria-hidden":!0});default:return null}}function R$s(){return a.jsx("svg",{viewBox:"0 0 24 24",className:"text-placeholder","aria-hidden":!0,children:a.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function P$s({status:e,variant:t}){return t==="plain"?a.jsx("span",{className:W("flex size-4 items-center justify-center self-center [&>svg]:size-4",vo.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?a.jsx(R$s,{}):Oit(e)}):a.jsx("span",{className:W("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",vo.colors,vo.transform,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-placeholder":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark":e==="success","bg-accent2Dark":e==="failed","scale-110":e==="success"||e==="failed"}),children:Oit(e)})}function $$s({step:e,isActive:t,position:n,variant:r="default"}){return a.jsxs("div",{className:W("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",vo.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[a.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[a.jsxs("span",{className:W("flex min-w-6 justify-end text-body",vo.colors,{"text-foreground":t||e.status==="success","text-muted-foreground":!t&&e.status!=="success"}),children:[n,"."]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h4",{className:W("text-body",vo.colors,{"text-foreground":t||e.status==="success","text-muted-foreground":!t&&e.status!=="success"}),children:e.title}),e.description&&a.jsx("p",{className:W("-mt-0.5 text-body text-placeholder",{truncate:r==="plain"}),children:e.description})]})]}),a.jsx(P$s,{status:e.status,variant:r})]})}function M$s({currentStep:e,steps:t=[],className:n}){return a.jsx("div",{className:W(n),children:t.map((r,s)=>a.jsx($$s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function D$s({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return a.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[a.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>a.jsx("div",{className:W("relative flex h-8 items-center justify-end",vo.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:a.jsx("div",{className:W("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none",vo.colors,vo.transform,{"border border-dashed border-placeholder":r.status==="pending","scale-110 bg-accent1Dark text-notice-success-fg":r.status==="success","scale-110 bg-accent2Dark text-notice-destructive-fg":r.status==="failed"}),children:r.status==="running"?a.jsx(Cn,{}):s+1})},r.id))}),a.jsxs("div",{className:W("text-center text-caption text-muted-foreground",vo.colors),children:[n," of ",t," steps completed"]})]})}function L$s({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",o=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=o?.steps||{},u=Object.keys(c).length>0,d=y=>y==="input"||y.endsWith(".input")||y.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(y)||/[0-9a-f]{8,}/.test(y)?!1:r?.allSteps?y in r.allSteps:!0,f=Object.entries(c).filter(([y,v])=>d(y)),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(([y,v])=>({id:y,status:v?.status,description:v?.description,title:y.charAt(0).toUpperCase()+y.slice(1).replace(/-/g," "),isActive:i?.id===y}));return a.jsxs(tJ,{className:"mb-5 content-center space-y-6 text-muted-foreground",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("h3",{className:"text-heading text-foreground",children:h()}),(t?.runId||n)&&a.jsxs("div",{className:"mt-2 text-caption text-muted-foreground",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&a.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-4",children:a.jsx(D$s,{steps:m})}),l&&s==="error"&&a.jsxs("div",{className:W("flex items-center gap-3 rounded-lg bg-red-500/10 p-4 text-body text-foreground","[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-red-500 [&>svg]:opacity-70"),children:[a.jsx(z2n,{}),l||"Something went wrong"]}),u&&a.jsx(M$s,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&a.jsxs("div",{className:"grid justify-items-center gap-4 text-center text-body text-muted-foreground",children:[a.jsx(Cn,{}),a.jsx("p",{children:"This may take some time..."})]})]})}function F$s({name:e,installedEntities:t}){return a.jsxs(tJ,{className:W("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[a.jsx(LSt,{}),a.jsx("h2",{className:"text-heading",children:"Done!"}),a.jsxs("p",{className:"text-center text-body text-muted-foreground",children:["The ",a.jsx("b",{className:"text-muted-foreground",children:e})," template has been successfully installed.",t&&t.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&a.jsx(Q$e,{data:t})]})}function z$s(){const{templateSlug:e}=fr(),t=[{id:"templates",label:"Templates",to:"/templates"},{id:"template",label:LG(e)}],[n,r]=so(),[s,o]=g.useState(""),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState({}),[p,h]=g.useState([]),[m,y]=g.useState(null),[v,b]=g.useState(!1),[x,w]=g.useState(""),[k,_]=g.useState(!1),[C,T]=g.useState(!1),[E,I]=g.useState([]),{data:N,isLoading:A}=Tvr({repoOrSlug:e,owner:"mastra-ai"}),F=E$s?.includes("beta")??!1?"beta":"main",{data:D,isLoading:H}=jvr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:F}),{data:q,isLoading:V}=Nvr(),{mutateAsync:B,isPending:Z}=Ivr(),{mutateAsync:z}=Avr(),{streamInstall:Y,streamResult:L,isStreaming:R}=Pvr(q),{observeInstall:M,streamResult:U,isStreaming:Q}=$vr(q);g.useEffect(()=>{const se=n.get("runId");se&&!v&&!m&&!R&&!Q&&(console.info("🔄 Checking completed run after hot reload:",{runId:se}),w(se),z({runId:se}).then(ie=>{const fe=ie.snapshot;if(fe?.status==="success"&&fe?.result?.success)b(!0);else if(fe?.result?.success===!1)if(fe?.result?.validationResults&&!fe?.result?.validationResults?.valid&&fe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:xe,errors:Ne}=fe.result.validationResults,Ae=`Template installation completed but ${xe} validation issue${xe>1?"s":""} remain unresolved.`;y(Ae),I(Ne||[])}else{const xe=fe?.result?.message||fe?.result?.error||"Template installation failed";y(typeof xe=="string"?xe:String(xe))}}).catch(ie=>{console.error("❌ Failed to fetch run details:",ie),y("Failed to retrieve installation status after reload")}))},[n,v,m,R,Q,z]),g.useEffect(()=>{const se=n.get("runId"),ie=n.get("resume"),fe=n.get("provider");if(se&&ie==="true"&&fe&&!R&&!Q&&!k&&!C&&q){w(se),_(!0);try{z({runId:se}).then(he=>{if(he.snapshot?.status==="running")return M.mutateAsync({runId:se})}).then(()=>{r(he=>{const xe=new URLSearchParams(he);return xe.delete("resume"),xe})}).catch(he=>{console.error("❌ Failed to resume template installation:",he),he.message?.includes("404")||he.message?.includes("not found")?y("Template installation run not found. It may have expired or been completed."):y("Failed to resume template installation. Please try again.")})}catch(he){console.error("❌ Auto-resume failed with error:",he),y("Failed to resume template installation. Please refresh and try again.")}}},[n,e,R,Q,k,C,q,z,M,r]);const te=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],K=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(se=>se).join(", "):"n/a",icon:a.jsx(Hd,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(se=>se).join(", "):"n/a",icon:a.jsx(Pi,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(se=>se).join(", "):"n/a",icon:a.jsx(q1,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:a.jsx(yy,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:a.jsx(V1,{})}],ee=[{...K[0]},{...K[1]},{...K[2]}].filter(se=>se.value!=="n/a");g.useEffect(()=>{D&&f(D)},[D]),g.useEffect(()=>{const se=L||U;se?.phase==="error"&&se?.error&&y(typeof se.error=="string"?se.error:String(se.error))},[L?.phase,L?.error,U?.phase,U?.error]);const ne=se=>{o(se)},le=async se=>(l(se.provider),u(se.modelId),{message:"Model updated successfully"}),J=async()=>{const se=Object.entries(d).reduce((ie,[fe,he])=>(he===""&&ie.push(fe),ie),[]);if(se.length>0){h(se);return}if(N){y(null),b(!1),w(""),T(!0);try{const fe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:F,slug:N.slug,variables:d},{runId:he}=await B({});w(he),r(xe=>{const Ne=new URLSearchParams(xe);return Ne.set("runId",he),Ne.set("resume","true"),Ne.set("provider",s||"openai"),Ne}),await Y.mutateAsync({inputData:fe,selectedModel:{provider:i,modelId:c},runId:he})}catch(ie){T(!1),y(ie?.message||"Template installation failed"),console.error("Template installation failed",ie)}}},re=se=>{const{name:ie,value:fe}=se.target;fe.trim()===""?h(he=>[...he,ie]):h(he=>he.filter(xe=>xe!==ie)),f(he=>({...he,[ie]:fe}))};return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:W("h-full w-full overflow-y-scroll lg:px-12"),children:a.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-4",children:[a.jsx(A$s,{isLoading:A,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:K,templateSlug:e}),N&&a.jsxs(a.Fragment,{children:[(R||Q)&&a.jsx(L$s,{name:N.title,streamResult:Q?U:L,runId:x,workflowInfo:q}),v&&a.jsx(F$s,{name:N.title,installedEntities:ee,linkComponent:ml}),m&&a.jsx(T$s,{errorMsg:m,validationErrors:E.length>0?E:L?.validationResults?.errors||U?.validationResults?.errors}),!R&&!Q&&!v&&!m&&a.jsx(I$s,{providerOptions:te,selectedProvider:s,onProviderChange:ne,variables:d,setVariables:f,errors:p,setErrors:h,handleInstallTemplate:J,handleVariableChange:re,isLoadingEnvVars:H||V,isInstalling:Z,defaultModelProvider:i,defaultModelId:c,onModelUpdate:le})]})]})})]})}const B$s=()=>{const{toolId:e,agentId:t}=fr(),n=[Wr("/agents"),{...zCe,to:t?`/agents/${encodeURIComponent(t)}`:void 0},{id:"agent-tool",Component:S6n}];return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"h-full w-full overflow-y-auto",children:a.jsx(Cys,{toolId:e,agentId:t})})]})},U$s=()=>{const e=Xe();return wn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new IC;Object.entries(r??{}).forEach(([o,i])=>{s.set(o,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(o){throw Qe.error("Error executing dev tool"),console.error("Error executing dev tool:",o),o}}})},V$s=({toolId:e})=>{const{canExecute:t}=_a(),n=t("tools"),{data:r={}}=ef(),s=g.useMemo(()=>{for(const y of Object.values(r))if(y.tools){const v=Object.values(y.tools).find(b=>b.id===e);if(v)return v}return null},[r,e]),{data:o,isLoading:i,error:l}=oqn(e,{enabled:!s}),c=s||o,{mutateAsync:u,isPending:d,data:f}=U$s(),{requestContext:p}=bs();g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Qe.error(`Error loading tool: ${y}`)}},[l]);const h=async(y,v)=>{if(!c)return;const b={...p??{},...v??{}};return u({toolId:c.id,input:y,requestContext:b})},m=c?.inputSchema?Am(r0(c?.inputSchema)):mr({});return i?a.jsxs("div",{className:"p-4",children:[a.jsx(at,{className:"mb-4 h-8 w-48"}),a.jsx(at,{className:"h-32 w-full"})]}):l?null:c?n?a.jsx(oMe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(je,{variant:"caption",tone:"muted",children:"You don't have permission to execute tools."})}):a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(je,{variant:"heading",tone:"muted",children:"Tool not found"})})},q$s=()=>{const{toolId:e}=fr(),t=[Wr("/tools"),wqn];return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"h-full w-full overflow-y-hidden",children:a.jsx(V$s,{toolId:e})})]})},uM=[Wr("/workflows")];function H$s(){const{data:e,isLoading:t,error:n}=ih(),[r,s]=g.useState(""),[o,i]=g.useState();return n&&_s(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Qs,{variant:"fill"})]}):n&&js(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Fs,{variant:"fill",resource:"workflows"})]}):n?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load workflows",descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(sls,{})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),actionRow:a.jsxs(Gn,{children:[a.jsx(Gn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})})}),a.jsx(Gn.End,{children:a.jsx(ae,{render:a.jsx(ml,{to:"/workflows/schedules"}),variant:"primary",icon:a.jsx(t0,{}),children:"Schedules"})})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(rls,{workflows:e||{},isLoading:t,search:r,sort:o,onSortChange:(l,c)=>i({key:c,direction:l})})]})}const W$s={active:"bg-accent1",paused:"bg-accent3"},Z$s={active:"text-accent1",paused:"text-accent3"},LJt=({status:e})=>a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${W$s[e]}`,"aria-hidden":!0}),a.jsx("span",{className:`text-caption ${Z$s[e]}`,children:e})]});function FJt({status:e}){const{icon:t,color:n}=G$s(e);return a.jsxs("span",{className:`inline-flex items-center gap-1.5 text-caption whitespace-nowrap ${n}`,children:[a.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),a.jsx("span",{children:e})]})}function G$s(e){switch(e){case"success":return{icon:a.jsx(Vn,{size:14}),color:"text-accent1"};case"failed":return{icon:a.jsx(Gt,{size:14}),color:"text-accent2"};case"running":return{icon:a.jsx(Cn,{}),color:"text-muted-foreground"};case"suspended":return{icon:a.jsx(iG,{size:14}),color:"text-accent3"};case"canceled":return{icon:a.jsx(EA,{size:14}),color:"text-muted-foreground"};case"pending":case"waiting":return{icon:a.jsx(R_,{size:14}),color:"text-muted-foreground"};default:return{icon:null,color:"text-muted-foreground"}}}const _it="auto auto auto auto 1fr",Q$s=3e4,Y$s=5*6e4;function K$s({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:o}){const{Link:i,paths:l}=dn(),c=h=>!!(n&&h.runId&&h.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Bc({count:u});let p=-1;return t?a.jsx(dc,{columns:_it}):e.length===0?a.jsx(je,{variant:"body",tone:"muted",className:"p-4",children:"No trigger history yet."}):a.jsxs(Oe,{columns:_it,className:"min-w-0",scrollRef:d,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{children:"Run"}),a.jsx(Oe.TopCell,{children:"Status"}),a.jsx(Oe.TopCell,{children:"Started"}),a.jsx(Oe.TopCell,{children:"Duration"}),a.jsx(Oe.TopCell,{children:" "})]}),e.map(h=>{const m=h.actualFireAt-h.scheduledFireAt,y=Zd(m,{signed:!0}),v=h.outcome==="failed",b=v?h.error:h.run?.error,x=Math.abs(m),w=!v&&x>Q$s&&x<=Y$s,k=`${h.scheduleId}-${h.runId}-${h.actualFireAt}`,_=c(h);_&&(p+=1);const C=a.jsx(je,{as:"span",variant:"caption",font:"mono",tone:_?void 0:"muted",className:_?"whitespace-nowrap text-accent1":"whitespace-nowrap",children:h.runId}),T=a.jsxs(a.Fragment,{children:[a.jsx(Oe.Cell,{children:C}),a.jsx(Oe.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2",children:[v?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-caption whitespace-nowrap text-accent2",children:[a.jsx(cu,{size:14}),"publish failed"]}):h.run?a.jsx(FJt,{status:h.run.status}):a.jsx("span",{className:"inline-flex items-center gap-1.5 text-caption whitespace-nowrap text-muted-foreground",children:"pending"}),b?a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-accent2",children:a.jsx(cu,{size:14})})}),a.jsx(kn,{children:b})]}):null]})}),a.jsx(Oe.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[h.actualFireAt?a.jsx(pN,{value:h.actualFireAt}):"—",w?a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-accent3",children:a.jsx(cu,{size:14})})}),a.jsxs(kn,{children:["Published ",y," after the scheduled fire time"]})]}):null]})}),a.jsx(Oe.Cell,{children:h.run?a.jsx(je,{as:"span",variant:"body-sm",font:"mono",children:Zd(h.run.durationMs)||"—"}):a.jsx("span",{className:"text-muted-foreground",children:"—"})}),a.jsx(Oe.Cell,{children:" "})]});return _?a.jsx(Oe.RowLink,{to:l.workflowRunLink(n,h.runId),LinkComponent:i,...f(p),children:T},k):a.jsx(Oe.RowStatic,{children:T},k)}),a.jsx(Oe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:o})]})}const X$s=e=>{const t=Xe();return wt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Cit=25,J$s=e=>{const t=Xe(),{inView:n,setRef:r}=A0(),s=Tm({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Cit,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Cit))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}),o=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:o,setEndOfListElement:r}},eMs=e=>{const t=Xe(),n=Tr();return wn({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"]}),Qe.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Qe.error(r.message)}})},zJt={id:"workflow-schedules",label:"Schedules",icon:t0,to:"/workflows/schedules"};function hB({label:e,children:t}){return a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(je,{variant:"meta",tone:"muted",className:"tracking-wide uppercase",children:e}),a.jsx("div",{className:"text-body",children:t})]})}function tMs(){const{scheduleId:e}=fr(),t=[Wr("/workflows"),zJt,{id:"schedule",label:LG(e),icon:t0}],{paths:n}=dn(),{data:r,error:s}=X$s(e),{data:o,isLoading:i,error:l,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d}=J$s(e),f=eMs(e);if(s&&_s(s))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Qs,{variant:"fill"})]});if(s&&js(s))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Fs,{variant:"fill",resource:"schedules"})]});if(s)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load schedule",descriptionSlot:s.message})]});const p=r?.workflowId,h=r?.agentId;return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:t}),actionRow:a.jsx(Gn,{children:a.jsxs(Gn.End,{children:[a.jsx(ae,{render:a.jsx(ml,{to:n.schedulesLink()}),variant:"ghost",icon:a.jsx(Cu,{}),children:"Back to schedules"}),p?a.jsx(ae,{icon:a.jsx(yl,{}),render:a.jsx(ml,{to:n.workflowLink(p)}),variant:"ghost",children:"Open workflow"}):null,r?a.jsx(ae,{onClick:()=>f.mutate(r.status==="active"?"pause":"resume"),disabled:f.isPending,"data-testid":"schedule-toggle-button",children:r.status==="active"?a.jsxs(a.Fragment,{children:[a.jsx(JS,{}),"Pause"]}):a.jsxs(a.Fragment,{children:[a.jsx(bu,{}),"Resume"]})}):null]})}),children:[a.jsx("h1",{className:"sr-only",children:e}),r?a.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden",children:[a.jsxs("div",{className:"flex h-fit flex-col gap-4 rounded-md border border-border p-4",children:[a.jsx(hB,{label:h?"Agent":"Workflow",children:p?a.jsx(ml,{to:n.workflowLink(p),className:"text-accent1 hover:underline",children:p}):h?a.jsx(ml,{to:n.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),a.jsxs(hB,{label:"Cron",children:[a.jsx(je,{as:"span",variant:"body",font:"mono",children:r.cron}),r.timezone?a.jsx("span",{className:"ml-2 text-caption text-muted-foreground",children:r.timezone}):null]}),a.jsx(hB,{label:"Status",children:a.jsx(LJt,{status:r.status})}),a.jsx(hB,{label:"Next fire",children:r.nextFireAt?a.jsx(pN,{value:r.nextFireAt}):"—"})]}),a.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[a.jsx(je,{variant:"body",className:"mb-3",children:"Trigger history"}),l?a.jsx(un,{tone:"error",titleSlot:"Failed to load trigger history",descriptionSlot:l.message}):a.jsx(K$s,{triggers:o??[],isLoading:i,workflowId:p,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d})]})]}):null]})}const nMs={target:e=>e.workflowId??e.agentId??"",status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},Eit="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function rMs({schedules:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const{paths:o,Link:i}=dn(),l=g.useMemo(()=>{const f=n.toLowerCase(),p=f?e.filter(h=>h.id.toLowerCase().includes(f)||(h.workflowId??h.agentId??"").toLowerCase().includes(f)):e;return G0(p,r,nMs)},[e,n,r]),{containerRef:c,getRowProps:u}=Bc({count:l.length,global:!0});if(t)return a.jsx(dc,{columns:Eit});const d=(f,p)=>s?a.jsx(Oe.SortableTopCell,{sortKey:f,sort:r?.key===f?r.direction:void 0,onSortChange:s,children:p}):a.jsx(Oe.TopCell,{children:p});return a.jsxs(Oe,{columns:Eit,className:"min-w-0",scrollRef:c,children:[a.jsxs(Oe.Top,{children:[d("target","Target"),a.jsx(Oe.TopCell,{children:"Schedule ID"}),a.jsx(Oe.TopCell,{children:"Cron"}),d("status","Status"),d("nextFireAt","Next fire"),d("lastFireAt","Last run")]}),l.length===0&&n?a.jsx(Oe.NoMatch,{message:"No schedules match your search"}):null,l.length===0&&!n?a.jsx(Oe.NoMatch,{message:"No schedules configured"}):null,l.map((f,p)=>a.jsxs(Oe.RowLink,{to:o.scheduleLink(f.id),LinkComponent:i,...u(p),children:[a.jsx(Oe.NameCell,{children:f.workflowId??f.agentId}),a.jsx(Oe.Cell,{className:"min-w-0",children:a.jsx(je,{as:"span",variant:"body-sm",tone:"muted",font:"mono",className:"block truncate",title:f.id,children:f.id})}),a.jsx(Oe.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(je,{as:"span",variant:"caption",font:"mono",children:f.cron}),f.timezone?a.jsx("span",{className:"text-meta text-muted-foreground",children:f.timezone}):null]})}),a.jsx(Oe.Cell,{children:a.jsx(LJt,{status:f.status})}),a.jsx(Oe.Cell,{children:f.nextFireAt?a.jsx(pN,{value:f.nextFireAt}):"—"}),a.jsx(Oe.Cell,{children:f.lastRun?a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(FJt,{status:f.lastRun.status}),f.lastFireAt?a.jsx(je,{as:"span",variant:"caption",tone:"muted",children:a.jsx(pN,{value:f.lastFireAt})}):null]}):f.lastFireAt?a.jsx(pN,{value:f.lastFireAt}):a.jsx("span",{className:"text-muted-foreground",children:"Never"})})]},f.id))]})}function BJt({workflowId:e}={}){const{data:t,isLoading:n,error:r}=CQ(e?{workflowId:e}:{}),[s,o]=g.useState(""),[i,l]=g.useState();return r?a.jsx(un,{tone:"error",titleSlot:"Failed to load schedules",descriptionSlot:r.message}):a.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[a.jsx("div",{className:"max-w-120",children:a.jsx(ju,{onSearch:o,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),a.jsx("div",{className:"overflow-y-auto",children:a.jsx(rMs,{schedules:t??[],isLoading:n,search:s,sort:i,onSortChange:(c,u)=>l({key:u,direction:c})})})]})}const _ce=[Wr("/workflows"),zJt];function sMs(){const[e]=so(),t=e.get("workflowId")??void 0,{error:n}=CQ(t?{workflowId:t}:{});return n&&_s(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:_ce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Qs,{variant:"fill"})]}):n&&js(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:_ce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Fs,{variant:"fill",resource:"schedules"})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:_ce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx("div",{className:"h-full",children:a.jsx(BJt,{workflowId:t})})]})}const oMs={"--belt-hue":"var(--warning1)"};function iMs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function aMs(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 lMs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:a.jsxs("section",{className:W(HTe,"pointer-events-auto relative isolate"),"data-testid":"workflow-suspended-steps","aria-label":"Step suspended",children:[a.jsxs("div",{className:"max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/50 bg-background px-5 py-4",children:[a.jsxs(je,{as:"h2",variant:"column",tone:"ink",className:"flex items-center gap-2",children:[a.jsx(_t,{children:a.jsx(iG,{})}),"Step suspended"]}),a.jsx(Mt,{variant:"orange",emphasis:"muted",children:"Needs input"})]}),e.map(s=>{const o=t.allSteps[s.stepId];if(!o||o.isWorkflow)return null;const i=o?.resumeSchema?Am(r0(o.resumeSchema)):bf(jn(),Nf());return a.jsx(cMs,{step:s,stepSchema:i,description:o.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),a.jsx(SAt,{status:"ready",label:"Needs input",className:"before:hidden",style:oMs})]})}function cMs({step:e,stepSchema:t,description:n,onResume:r}){const[s,o]=g.useState(!1),[i,l]=g.useState(!1),c=async u=>{l(!0);try{await r({stepId:e.stepId.split("."),runId:e.runId,resumeData:u})}catch(d){Qe.error(d instanceof Error?d.message:"Error resuming workflow")}finally{l(!1)}};return a.jsxs("div",{className:"space-y-5 p-5 [&+&]:border-t [&+&]:border-border/50",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(je,{as:"p",variant:"subheading",tone:"ink",className:"break-words",children:e.stepId}),n&&a.jsx(je,{as:"p",variant:"caption",tone:"muted",children:n})]}),e.suspendPayload!==void 0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs(je,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(_t,{children:a.jsx(j2n,{})}),"The step is asking"]}),a.jsxs(il,{open:s,onOpenChange:o,children:[a.jsxs(Va,{className:W(ir,"flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5"),children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(_t,{children:a.jsx(wr,{className:W("text-muted-foreground transition-transform",{"rotate-90 transform":s})})}),a.jsx(je,{as:"span",variant:"body",tone:"ink",className:"truncate",children:aMs(e.suspendPayload,e.stepId)})]}),a.jsx(je,{as:"span",variant:"caption",tone:"muted",className:"shrink-0",children:iMs(e.suspendPayload)})]}),a.jsx(qa,{children:a.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:a.jsx(br,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs(je,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(_t,{children:a.jsx(R2n,{})}),"Your response"]}),a.jsx("div",{className:"-mx-5",children:a.jsx(BTe,{schema:t,isSubmitLoading:i,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:a.jsx(bu,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function uMs({hidden:e}){const{result:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(ac),{canExecute:o,isLoading:i}=_a(),l=kRt(t,r),c=Zmr(),u=t?.status==="suspended"&&l.length>0&&!s,d=!i&&o("workflows");return!n||!u||!d?null:a.jsx("div",{hidden:e,"data-testid":"workflow-suspended-overlay",className:"pointer-events-none absolute top-12 right-2 z-30 w-[380px] max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none",children:a.jsx(lMs,{suspendedSteps:l,workflow:n,isStreaming:s,onResume:c})},r)}const Tit={success:{label:"Completed",icon:Vn,color:"text-positive1",bar:"bg-muted-foreground/60"},failed:{label:"Failed",icon:VD,color:"text-negative1",bar:"bg-negative1/60"},suspended:{label:"Needs input",icon:JS,color:"text-accent3",bar:"bg-accent3/60"},waiting:{label:"Waiting",icon:t1,color:"text-muted-foreground",bar:"bg-muted-foreground/40"},paused:{label:"Paused",icon:JS,color:"text-muted-foreground",bar:"bg-muted-foreground/40"},skipped:{label:"Skipped",icon:FDn,color:"text-muted-foreground",bar:"bg-muted-foreground/25"},running:{label:"Running",icon:ko,color:"text-accent6",bar:"bg-accent6/60"},canceled:{label:"Canceled",icon:EA,color:"text-muted-foreground",bar:"bg-muted-foreground/40"}},dMs={label:"Status unavailable",icon:l$n,color:"text-muted-foreground",bar:"bg-muted-foreground/25"};function fMs({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:o,onOpenOutput:i}){const l=Object.hasOwn(Tit,e.status)?Tit[e.status]:dMs,c=l.icon,u=e.stepId.slice(0,e.stepId.lastIndexOf(".")),d=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(".")+1):e.stepId;return a.jsxs("div",{"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&s(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&s(null),className:W("grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1","@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2",(t||n)&&"bg-fill-subtle"),children:[a.jsxs("button",{type:"button",className:"flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left text-meta text-foreground focus-visible:rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-border-focus aria-disabled:cursor-default","aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,children:[a.jsx("span",{"aria-label":l.label,className:W("grid size-6 flex-none place-items-center rounded-md border border-border bg-background",l.color),children:a.jsx(c,{"aria-hidden":!0,className:W("size-3.5",e.status==="running"&&"motion-safe:animate-spin")})}),a.jsxs("span",{className:"min-w-0",children:[a.jsx("span",{className:"block truncate",children:d}),e.isNestedEntry&&a.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-meta text-muted-foreground",children:[a.jsx(o_e,{"aria-hidden":!0,className:"size-3 shrink-0"}),a.jsx("span",{className:"truncate",children:u})]})]})]}),a.jsx("div",{className:"relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]","aria-hidden":!0,children:e.timing&&a.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:W("absolute top-0 h-full min-w-0.5 rounded-sm",l.bar),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),a.jsx("span",{className:"text-right text-meta whitespace-nowrap text-muted-foreground",title:e.timing&&e.spansSuspension?"Includes time spent suspended waiting for input":void 0,children:e.timing?a.jsx(je,{as:"span",variant:"meta",font:"mono",children:Zd(e.timing.durationMs)}):a.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),a.jsxs("div",{className:"flex items-center",children:[a.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:e.step.input===void 0,onClick:f=>o(e,f.currentTarget),children:a.jsx(rG,{})}),a.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:e.step.output===void 0,onClick:f=>i(e,f.currentTarget),children:a.jsx(oG,{})})]})]})}const pMs=e=>e.includes("."),hMs=e=>e==="input"||e.endsWith(".input"),jit=1;function mMs(e,t){const n=FTe(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function gMs(e,t){const n=Object.entries(e).filter(([l])=>!hMs(l)).map(([l,c])=>({stepId:l,step:c,...mMs(c,t)})).sort((l,c)=>(l.span?.start??1/0)-(c.span?.start??1/0)||l.stepId.localeCompare(c.stepId)),r=n.flatMap(l=>l.span?[l.span]:[]),s=Math.min(...r.map(l=>l.start)),o=Math.max(s,...r.map(l=>l.end)),i=Math.max(o-s,1);return n.map(({stepId:l,step:c,span:u,isLive:d,spansSuspension:f})=>{let p;if(u){const h=u.end-u.start,m=Math.min((u.start-s)/i*100,100-jit),y=Math.min(Math.max(h/i*100,jit),100-m);p={durationMs:h,offsetPct:m,widthPct:y}}return{stepId:l,step:c,status:_Q(c)?"suspended":c.status,timing:p,spansSuspension:f,isRunning:d,isNestedEntry:pMs(l)}})}function vMs(){const{steps:e}=AR(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=BG(),[o,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=X1(),p=g.useRef(null),h=gMs(e,o),m=h.some(y=>y.isRunning);return ckt(p,{enabled:m&&!l}),g.useEffect(()=>{if(!m||l)return;const y=setInterval(()=>i(Date.now()),100);return()=>clearInterval(y)},[m,l]),h.length===0?null:a.jsx("div",{"data-testid":"workflow-timeline",className:"relative z-20 shrink-0 px-2 pb-2",children:a.jsxs(il,{open:!l,onOpenChange:y=>c(!y),className:W(ir,"@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl"),children:[a.jsxs("div",{className:"flex items-center",children:[a.jsxs(Va,{className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle","aria-label":l?"Expand timeline":"Collapse timeline",children:[a.jsx("span",{children:a.jsx(pSt,{"aria-hidden":!0,className:"size-4 text-muted-foreground"})}),a.jsx("span",{children:"Timeline"}),a.jsxs("span",{className:"text-meta text-muted-foreground",children:[h.length," events"]}),a.jsx("span",{className:"ml-auto",children:a.jsx(po,{"aria-hidden":!0,className:W("size-4 transition-transform motion-reduce:transition-none",l&&"-rotate-90")})})]}),!l&&a.jsx(ae,{variant:"ghost",size:"icon-sm",tooltip:u?"Restore timeline height":"Enlarge timeline","aria-pressed":u,onClick:()=>d(!u),className:"mr-2 shrink-0",children:u?a.jsx(WPn,{}):a.jsx(mSt,{})})]}),a.jsx(qa,{children:a.jsx("div",{ref:p,"data-testid":"workflow-timeline-list",className:W("overflow-auto overscroll-contain px-1.5 pb-1.5",u?"max-h-[min(720px,calc(100dvh-112px))]":"max-h-[min(320px,40dvh)]"),children:h.map(y=>a.jsx(fMs,{row:y,isSelected:t===y.stepId,isHovered:n===y.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:(v,b)=>f({type:"step-input",stepId:v.stepId},b),onOpenOutput:(v,b)=>f({type:"step-output",stepId:v.stepId},b)},y.stepId))})})]})})}const yMs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=X1(),s=KA(),o=r?.type==="data",i=a.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[a.jsx(T7t,{workflowId:e,workflow:t,isLoading:n}),a.jsx(uMs,{hidden:o}),o&&a.jsx("div",{className:"pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col",children:a.jsx(P7,{})}),a.jsx("div",{className:"pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20",children:a.jsx(vMs,{})})]});return s&&r&&!o?a.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:a.jsx(P7,{})}):a.jsxs("div",{className:"relative h-full min-h-0",children:[i,a.jsxs(vMe,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[a.jsx(EC,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),r&&!o&&a.jsxs(a.Fragment,{children:[a.jsx($W,{className:"pointer-events-auto"}),a.jsx(EC,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:a.jsx("div",{className:"pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background",children:a.jsx(P7,{})})})]})]})]})},Nit=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=v5(e);return r&&_s(r)?a.jsx(Qs,{variant:"fill"}):r&&js(r)?a.jsx(Fs,{variant:"fill",resource:"workflows"}):a.jsx(yMs,{workflowId:e,workflow:t??void 0,isLoading:n})};function bMs(){const{workflowId:e}=fr(),{error:t}=CQ(e?{workflowId:e}:{});if(!e)return null;let n;return t&&_s(t)?n=a.jsx(Qs,{variant:"fill"}):t&&js(t)?n=a.jsx(Fs,{variant:"fill",resource:"schedules"}):n=a.jsx("div",{className:"h-full",children:a.jsx(BJt,{workflowId:e})}),a.jsxs(gt,{children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),n]})}function xMs(){const{workflowId:e}=fr();return e?a.jsx(o2e,{scopedEntityId:e,scopedEntityType:lu.WORKFLOW_RUN}):null}function wMs(e,t){if(e==null)return{};var n,r,s=zjt(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function c1e(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 SMs(e){if(Array.isArray(e))return c1e(e)}function kMs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function OMs(e,t){if(e){if(typeof e=="string")return c1e(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)?c1e(e,t):void 0}}function _Ms(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
686
+ ]`,Uot="flex min-h-0 flex-1 flex-col py-0";function yjs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:o,onPastedTextChange:i,validation:l,isImporting:c}){return a.jsxs(ll,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[a.jsxs(al,{variant:"pill",children:[a.jsx(Lr,{value:"upload",children:"Upload file"}),a.jsx(Lr,{value:"paste",children:"Paste JSON"})]}),a.jsx(Ss,{value:"upload",className:Uot,children:n?a.jsx(Sjs,{file:n,validation:l,onReplace:s,isImporting:c}):a.jsx(bjs,{onFileSelect:r,disabled:c})}),a.jsx(Ss,{value:"paste",className:Uot,children:a.jsx(br,{"aria-label":"JSON items",language:"json",lineNumbers:!1,showCopyButton:!1,placeholder:vjs,value:o,onChange:i,editable:!c,className:"min-h-50 flex-1"})})]})}function bjs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),o=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return a.jsxs("div",{"data-testid":"json-dropzone",onDragOver:o,onDragLeave:i,onDrop:l,className:W("relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-card px-4 py-6 text-center","hover:border-accent1/50 hover:bg-accent1/5",n&&"border-accent1/50 bg-accent1/5",t&&"cursor-wait opacity-60"),children:[a.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),a.jsx("div",{className:"flex size-9 items-center justify-center rounded-md border border-border bg-background text-muted-foreground",children:a.jsx(PA,{className:"size-4"})}),a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx("p",{className:"text-body text-foreground",children:"Drop a JSON file here"}),a.jsxs("p",{className:"text-caption text-muted-foreground",children:["or ",a.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),a.jsxs("p",{className:"text-meta text-muted-foreground",children:[".json · an array of items · up to ",l2e]})]})}function xjs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function wjs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function Sjs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],o="total"in t?t.total:0,i=s.slice(0,rce);return a.jsxs("div",{"data-testid":"json-file-card",className:"rounded-lg border border-border",children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[a.jsx(jA,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx(je,{as:"span",variant:"caption",tone:"ink",font:"mono",className:"min-w-0 flex-1 truncate",children:e.name}),a.jsx("span",{className:"shrink-0 text-meta text-muted-foreground",children:xjs(e.size)}),a.jsx(ae,{icon:a.jsx(n0,{}),variant:"ghost",size:"sm",onClick:n,disabled:r,children:"Replace"})]}),i.map(l=>a.jsxs("div",{className:"grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t border-border px-3 py-1.5",children:[a.jsx("span",{className:"text-meta text-muted-foreground",children:l.index}),a.jsx(je,{as:"span",variant:"caption",tone:"ink",font:"mono",className:"truncate",children:wjs(l.input)}),l.hasInput?l.hasGroundTruth?null:a.jsx(Mt,{variant:"yellow",size:"xs",children:"no groundTruth"}):a.jsx(Mt,{variant:"red",size:"xs",children:"no input"})]},l.index)),o>rce&&a.jsxs("div",{className:"border-t border-border px-3 py-1.5 text-meta text-muted-foreground",children:["+ ",o-rce," more"]})]})}const kjs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function Ojs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[o,i]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,p]=g.useState(null),[h,m]=g.useState(""),[y,v]=g.useState(!1),b=g.useRef(0),{batchInsertItems:x}=cl(),w=o==="upload"?u:h,k=g.useMemo(()=>o==="upload"&&f?{status:"error",kind:"parse",message:f}:fTs(w),[o,f,w]),_=g.useCallback(async N=>{const A=++b.current;if(!N.name.toLowerCase().endsWith(".json")){p("Only .json files are supported");return}if(N.size>TXt){p(`File is larger than ${l2e}`);return}try{const P=await kjs(N);if(A!==b.current)return;c({name:N.name,size:N.size}),d(P),p(null)}catch{if(A!==b.current)return;p("Could not read the file")}},[]),C=g.useCallback(()=>{b.current++,c(null),d(""),p(null)},[]),T=g.useCallback(()=>{b.current++,i("upload"),c(null),d(""),p(null),m("")},[]),E=g.useCallback(()=>{y||(r(!1),setTimeout(T,150))},[y,r,T]),I=g.useCallback(async()=>{if(k.status==="ready"){v(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Qe.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(N){Qe.error(N instanceof Error?N.message:"Failed to import items")}finally{v(!1)}}},[k,x,e,s,r,T]);return a.jsx(hs,{open:n,onOpenChange:E,children:a.jsxs(rs,{className:"flex max-h-[90vh] w-[960px] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0",children:[a.jsxs(ss,{className:"border-b border-border px-4 py-4",children:[a.jsx(Jr,{children:"Import into dataset"}),a.jsxs(Ms,{className:"not-sr-only text-caption text-muted-foreground",children:["Add items to ",t?a.jsx("span",{className:"text-foreground",children:t}):"this dataset"," from a JSON file or paste them directly."]})]}),a.jsx(ys,{className:"max-h-none min-h-0 flex-1 overflow-y-auto p-0",children:a.jsxs("div",{className:"grid divide-y divide-border md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[a.jsx("div",{className:"flex min-h-[360px] flex-col p-4",children:a.jsx(yjs,{tab:o,onTabChange:i,file:l,onFileSelect:_,onReplace:C,pastedText:h,onPastedTextChange:m,validation:k,isImporting:y})}),a.jsx("div",{className:"p-4",children:a.jsx(gjs,{})})]})}),a.jsxs(rc,{className:"items-center border-t border-border px-4 py-3 sm:justify-between",children:[a.jsx(_js,{validation:k}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:E,disabled:y,children:"Cancel"}),a.jsxs(ae,{variant:"primary",onClick:I,disabled:k.status!=="ready"||y,children:[y&&a.jsx(Cn,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function _js({validation:e}){const t=W("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-muted-foreground",e.status==="ready"&&"bg-accent1",e.status==="error"&&"bg-accent2");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=a.jsxs(a.Fragment,{children:[a.jsx("b",{className:"font-medium text-foreground",children:e.total})," item",e.total!==1?"s":""," ","ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${l2e}`;break;case"missing-input":n=a.jsxs(a.Fragment,{children:[a.jsx("b",{className:"font-medium text-foreground",children:e.missingInputCount})," of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",a.jsx(w1,{children:"input"})]});break}break}return a.jsxs("div",{role:"status",className:"flex min-w-0 items-center gap-2 text-caption text-muted-foreground",children:[a.jsx("span",{className:t}),a.jsx("span",{className:"truncate",children:n})]})}function Cjs(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function LXt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=o=>{o.defaultPrevented||Cjs(o.target)||(o.key==="PageUp"?(o.preventDefault(),t?.()):o.key==="PageDown"?(o.preventDefault(),n?.()):o.key==="Escape"&&(o.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const FXt=g.createContext(null);function Ejs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=zr(),i=sOe("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(h=>{s(`/datasets/${e}/items/${encodeURIComponent(h)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(h=>h.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const h=t[u-1].id;return()=>l(h)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const h=t[u+1].id;return()=>l(h)},[u,t,l]);LXt({active:!!i,onPrevious:d,onNext:f,onClose:c});const p=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return a.jsx(FXt.Provider,{value:p,children:r})}function zXt(){const e=g.useContext(FXt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}const Tjs=["createdAt"];function jjs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:o}){const[i,l]=so(),{activeVersion:c}=u2e(i,l),{sort:u,onSortChange:d}=fk({searchParams:i,setSearchParams:l,allowedKeys:Tjs}),f=g.useMemo(()=>u?{field:u.key,direction:u.direction==="asc"?"ASC":"DESC"}:void 0,[u]),[p,h]=g.useState(!1),[m,y]=g.useState(!1),[v,b]=g.useState(!1),[x,w]=g.useState([]),[k,_]=g.useState(!1),[C,T]=g.useState([]),[E,I]=g.useState(!1),[N,A]=g.useState([]),[P,F]=g.useState(0),[D,H]=g.useState(""),[q]=kCe(D,300),{data:V}=vv(e),{data:B=[],isLoading:Z,setEndOfListElement:z,isFetchingNextPage:Y,hasNextPage:L}=oA(e,q||void 0,c,f),{deleteItems:R}=cl(),{currentItemId:M,openItem:U,close:Q}=zXt(),te=ie=>{M===ie?Q():U(ie)},K=ie=>{w(ie),b(!0)},ee=ie=>{T(ie),_(!0)},ne=ie=>{_(ie),ie||(T([]),F(fe=>fe+1))},le=ie=>{A(ie),I(!0)},J=async()=>{await R.mutateAsync({datasetId:e,itemIds:N}),Qe.success(`Deleted ${N.length} items`),I(!1),A([]),F(ie=>ie+1)},re=ie=>{b(!1),w([]),F(fe=>fe+1),n?.(ie)},se=ie=>{b(ie),ie||(w([]),F(fe=>fe+1))};return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"grid h-full overflow-auto",children:a.jsx(pjs,{items:B,leftSlot:r,rightSlot:s,belowToolbarSlot:o,isLoading:Z,onItemClick:te,featuredItemId:M,onAddClick:t??(()=>{}),onImportClick:()=>h(!0),onImportJsonClick:()=>y(!0),onBulkDeleteClick:le,onCreateDatasetClick:K,onAddToDatasetClick:ee,datasetName:V?.name,clearSelectionTrigger:P,setEndOfListElement:z,isFetchingNextPage:Y,hasNextPage:L,searchQuery:D,activeSearchQuery:q,onSearchChange:H,sort:u,onSortChange:d,currentDatasetVersion:V?.version})}),a.jsx(ijs,{datasetId:e,open:p,onOpenChange:h}),a.jsx(Ojs,{datasetId:e,datasetName:V?.name,open:m,onOpenChange:y}),a.jsx(BTs,{open:v,onOpenChange:se,items:x,onSuccess:re}),a.jsx(UTs,{open:k,onOpenChange:ne,items:C,currentDatasetId:e}),a.jsx($t,{open:E,onOpenChange:I,children:a.jsxs($t.Content,{children:[a.jsxs($t.Header,{children:[a.jsx($t.Title,{children:"Delete Items"}),a.jsxs($t.Description,{children:["Are you sure you want to delete ",N.length," item",N.length!==1?"s":"","? This action cannot be undone."]})]}),a.jsxs($t.Footer,{children:[a.jsx($t.Cancel,{children:"Cancel"}),a.jsx($t.Action,{onClick:J,children:R.isPending?"Deleting...":"Delete"})]})]})})]})}const Vot="__create_tag__";function Njs({datasetId:e}){const{data:t}=vv(e),{data:n}=W1(),{updateDataset:r}=cl(),[s,o]=g.useState(""),i=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>IXt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const p=l.map(y=>({label:y,value:y,end:i.includes(y)?a.jsx(Vn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=s.trim();return h.length>0&&!l.includes(h)&&!i.includes(h)?[{label:`Create "${h}"`,value:Vot},...p]:p},[l,i,s]),u=p=>{r.mutate({datasetId:e,tags:p},{onError:()=>Qe.error("Failed to update tags")})},d=p=>{const h=p===Vot?s.trim():p;!h||i.includes(h)||u([...i,h])},f=p=>{u(i.filter(h=>h!==p))};return a.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2",children:[i.map(p=>a.jsxs(qX,{value:p,size:"md",className:"gap-1 pr-1",children:[p,a.jsx("button",{type:"button","aria-label":`Remove tag ${p}`,disabled:r.isPending,onClick:()=>f(p),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:a.jsx(Gt,{className:"size-3"})})]},p)),a.jsx(za,{options:c,value:void 0,onValueChange:d,onInputValueChange:o,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(V1,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"sm",className:"w-auto min-w-0",disabled:r.isPending})]})}function BXt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return a.jsxs("div",{className:"grid gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(oc,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),a.jsx(Mn,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),a.jsx("p",{className:"text-caption text-muted-foreground",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?a.jsx(WX,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function TN({name:e,field:t,errors:n}){return n.length===0?null:a.jsx(Ht.ErrorMsg,{name:e,children:a.jsx("span",{className:"space-y-1",children:n.map(r=>a.jsxs("span",{className:"block",children:[a.jsxs("code",{className:"rounded bg-destructive/10 px-1",children:[t,r.path!=="/"?r.path:""]}),": ",r.message]},`${r.path}:${r.message}`))})})}function Ijs(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 Ajs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,o]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(!1),[m,y]=g.useState([]),[v,b]=g.useState(""),[x,w]=g.useState(null),{addItem:k}=cl(),_=()=>{o("{}"),l(""),u(""),f(""),h(!1),y([]),b(""),w(null)},C=P=>{_(),n(P)},T=async P=>{P.preventDefault();let F;try{F=JSON.parse(s)}catch{Qe.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Qe.error("Ground Truth must be valid JSON");return}let H;if(c.trim())try{H=JSON.parse(c)}catch{Qe.error("Expected Trajectory must be valid JSON");return}let q;if(d.trim())try{const B=JSON.parse(d);if(!Array.isArray(B)){Qe.error("Tool Mocks must be a JSON array");return}q=B}catch{Qe.error("Tool Mocks must be valid JSON");return}let V;if(v.trim())try{V=JSON.parse(v)}catch{Qe.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:F,groundTruth:D,expectedTrajectory:H,toolMocks:q,scorerIds:p?m:void 0,requestContext:V}),Qe.success("Item added successfully"),C(!1),r?.()}catch(B){const Z=Ijs(B);Z?w(Z):Qe.error(`Failed to add item: ${B instanceof Error?B.message:"Unknown error"}`)}},E=P=>{o(P),x?.field==="input"&&w(null)},I=P=>{l(P),x?.field==="groundTruth"&&w(null)},N=P=>{f(P),x?.field==="toolMocks"&&w(null)},A=()=>{C(!1)};return a.jsxs(ki,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[a.jsx(ki.Top,{children:"Add Item"}),a.jsxs(ki.Content,{children:[a.jsx(ki.Header,{children:a.jsx(ki.Heading,{children:"Add Item"})}),a.jsxs("form",{onSubmit:T,className:"grid gap-4",children:[a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-input",required:!0,children:"Input (JSON)"}),a.jsx(br,{id:"input-item-input","aria-invalid":x?.field==="input"?!0:void 0,"aria-describedby":x?.field==="input"?Ui("item-input"):void 0,value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&a.jsx(TN,{name:"item-input",field:"input",errors:x.errors})]}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),a.jsx(br,{id:"input-item-ground-truth","aria-invalid":x?.field==="groundTruth"?!0:void 0,"aria-describedby":x?.field==="groundTruth"?Ui("item-ground-truth"):void 0,value:i,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&a.jsx(TN,{name:"item-ground-truth",field:"groundTruth",errors:x.errors})]}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),a.jsx(br,{id:"input-item-trajectory",value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),a.jsx(br,{id:"input-item-tool-mocks","aria-invalid":x?.field==="toolMocks"?!0:void 0,"aria-describedby":x?.field==="toolMocks"?Ui("item-tool-mocks"):void 0,value:d,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&a.jsx(TN,{name:"item-tool-mocks",field:"toolMocks",errors:x.errors})]}),a.jsx(BXt,{overrideEnabled:p,onOverrideEnabledChange:h,selectedScorerIds:m,onSelectedScorerIdsChange:y,disabled:k.isPending}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Ht.Label,{name:"item-request-context",children:"Request Context (JSON, optional)"}),a.jsx(br,{id:"input-item-request-context",value:v,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),type:"button",onClick:A,children:"Cancel"}),a.jsx(ae,{icon:a.jsx(Yr,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const oO=e=>JSON.stringify(e??null,null,2),Rjs=[{key:"input",title:"Input",icon:a.jsx(qD,{}),value:e=>oO(e.input)},{key:"groundTruth",title:"Ground Truth",icon:a.jsx(CS,{}),value:e=>oO(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:a.jsx(m_e,{}),value:e=>e.expectedTrajectory!=null?oO(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:a.jsx(xu,{}),value:e=>oO(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:a.jsx(CSt,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":oO(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:a.jsx(bl,{}),value:e=>e.requestContext!=null?oO(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:a.jsx(V1,{}),value:e=>oO(e.metadata)}];function JSe({item:e,diff:t}){return a.jsxs(a.Fragment,{children:[a.jsxs(Ft,{children:[a.jsx(Ft.Key,{children:"Dataset Id"}),a.jsx(Ft.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),a.jsx(Ft.Key,{children:"Version"}),a.jsxs(Ft.Value,{children:["v",e.datasetVersion]}),a.jsx(Ft.Key,{children:"Created"}),a.jsx(Ft.Value,{children:Fr(e.createdAt,"date-time")}),a.jsx(Ft.Key,{children:"Updated"}),a.jsx(Ft.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?Fr(e.updatedAt,"date-time"):"n/a"})]}),a.jsx("div",{className:"mt-3 grid gap-3",children:Rjs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:a.jsx(Rt.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function Pjs({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:o,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:p,setSelectedScorerIds:h,requestContextValue:m,setRequestContextValue:y,validationErrors:v,onSave:b,onCancel:x,isSaving:w}){return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mb-4",children:a.jsxs("h3",{className:"flex items-center gap-2 text-heading",children:[a.jsx(Bd,{className:"h-5 w-5"})," Edit Item"]})}),a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-input",required:!0,children:"Input (JSON)"}),a.jsx(br,{id:"input-item-input","aria-invalid":v?.field==="input"?!0:void 0,"aria-describedby":v?.field==="input"?Ui("item-input"):void 0,value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),v?.field==="input"&&a.jsx(TN,{name:"item-input",field:"input",errors:v.errors})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),a.jsx(br,{id:"input-item-ground-truth","aria-invalid":v?.field==="groundTruth"?!0:void 0,"aria-describedby":v?.field==="groundTruth"?Ui("item-ground-truth"):void 0,value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),v?.field==="groundTruth"&&a.jsx(TN,{name:"item-ground-truth",field:"groundTruth",errors:v.errors})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),a.jsx(br,{id:"input-item-trajectory",value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),a.jsxs("p",{className:"text-caption text-muted-foreground",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",a.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),a.jsx(br,{id:"input-item-tool-mocks","aria-invalid":v?.field==="toolMocks"?!0:void 0,"aria-describedby":v?.field==="toolMocks"?Ui("item-tool-mocks"):void 0,value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),v?.field==="toolMocks"&&a.jsx(TN,{name:"item-tool-mocks",field:"toolMocks",errors:v.errors})]}),a.jsx(BXt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:p,onSelectedScorerIdsChange:h,disabled:w}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-request-context",children:"Request Context (JSON, optional)"}),a.jsx(br,{id:"input-item-request-context",value:m,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Ht.Label,{name:"item-metadata",children:"Metadata (JSON, optional)"}),a.jsx(br,{id:"input-item-metadata",value:s,onChange:o,showCopyButton:!1,className:"min-h-[80px]"})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[a.jsx(ae,{icon:a.jsx(Vn,{}),variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:x,disabled:w,children:"Cancel"})]})]})]})}const $js=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Mjs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:o,isLoading:i}=ef(),{data:l,isLoading:c}=ih(),{data:u,isLoading:d}=lh(),f=e==="agent"?Object.entries(o??{}).map(([y,v])=>({value:y,label:v.name??y})):e==="workflow"?Object.entries(l??{}).map(([y,v])=>({value:y,label:v.name??y})):e==="scorer"?Object.entries(u??{}).map(([y,v])=>({value:y,label:v.scorer?.config?.name??y})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=y=>{t(y),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{children:"Target Type"}),a.jsx(za,{options:$js,value:e,onValueChange:h,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{children:m}),a.jsx(za,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}const Djs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function Ljs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return Am(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mn,{children:"Request Context"}),a.jsx(W3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):a.jsx("div",{role:"alert",children:a.jsx(Jt,{variant:"destructive",children:"Failed to parse request context schema"})})}function sce({index:e,done:t,isLast:n,children:r}){return a.jsxs("li",{className:"flex gap-4",children:[a.jsxs("div",{className:"flex flex-col items-center",children:[a.jsx("span",{"aria-hidden":"true",className:W("flex size-6 shrink-0 items-center justify-center rounded-full border text-meta",t?"border-accent1 bg-accent1 text-white":"border-border text-muted-foreground"),children:e}),!n&&a.jsx("span",{"aria-hidden":"true",className:"mt-2 w-px flex-1 bg-border"})]}),a.jsx("div",{className:W("min-w-0 flex-1 space-y-3",!n&&"pb-4"),children:r})]})}function ZX({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:o,initialDescription:i,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,p]=g.useState(o??""),[h,m]=g.useState(i??""),[y,v]=g.useState(e??""),[b,x]=g.useState(t??null),[w,k]=g.useState(r??""),[_,C]=g.useState(s??""),[T,E]=g.useState(n??null),[I,N]=g.useState({}),[A,P]=g.useState(""),{triggerExperiment:F}=cl(),{data:D}=vv(y),{total:H}=oA(y,void 0,b),q=D?.requestContextSchema,V=D?.scorerIds??[],B=T===null&&V.length>0,Z=T??V,z=!!(q&&Object.keys(q).length>0),Y=!!(y&&w&&_&&f.trim()),L=F.isPending,R=[!f.trim()&&"name",!y&&"dataset",!_&&"target"].filter(Boolean),M=z?Object.values(I).some(le=>le!==void 0&&le!==""):A.trim().length>0,U=le=>{v(le),x(null),E(n??null),N({})},Q=()=>{p(o??""),m(i??""),v(e??""),x(t??null),k(r??""),C(s??""),E(n??null),N({}),P("")},te=()=>{if(z){const le=Object.entries(I).filter(([,J])=>J!==void 0&&J!=="");return le.length>0?Object.fromEntries(le):void 0}if(A.trim()){let le;try{le=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!le||typeof le!="object"||Array.isArray(le))throw new Error("Request Context must be a JSON object");return le}},K=async()=>{if(!y||!w||!_||!f.trim())return;let le;try{le=te()}catch(J){const re=J instanceof Error?J.message:"Request Context must be valid JSON";uu.error(re);return}try{const J=await F.mutateAsync({datasetId:y,name:f.trim(),description:h.trim()||void 0,targetType:w,targetId:_,scorerIds:Z.length>0?Z:void 0,version:b??void 0,requestContext:le});uu.success("Experiment triggered successfully"),c(!1),u?.(J.experimentId),Q()}catch(J){const re=J instanceof Error?J.message:"Failed to trigger experiment";uu.error(re)}},ee=()=>{L||(c(!1),Q())},ne=le=>{(le.metaKey||le.ctrlKey)&&le.key==="Enter"&&Y&&!L&&(le.preventDefault(),K())};return a.jsx(hs,{open:l,onOpenChange:ee,children:a.jsxs(rs,{ref:d,className:"w-[640px] max-w-[calc(100vw-2rem)] gap-0 p-0",onKeyDown:ne,children:[a.jsxs(ss,{className:"border-b border-border px-4 py-4",children:[a.jsx(Jr,{children:"Run experiment"}),a.jsx(Ms,{className:"not-sr-only text-caption text-muted-foreground",children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),a.jsxs(ys,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-4 py-5",children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{htmlFor:"experiment-name",children:"Name *"}),a.jsx(gr,{id:"experiment-name",value:f,onChange:le=>p(le.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:L})]}),a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{htmlFor:"experiment-description",children:"Description"}),a.jsx(Im,{id:"experiment-description",value:h,onChange:le=>m(le.target.value),placeholder:"Enter experiment description (optional)",disabled:L,rows:2})]})]}),a.jsxs("ol",{className:"list-none",children:[a.jsxs(sce,{index:1,done:!!y,children:[a.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{children:"Dataset"}),a.jsx(xkt,{value:y,onValueChange:U,container:d})]}),y&&a.jsxs("div",{className:"grid gap-2",children:[a.jsx(Mn,{children:"Version"}),a.jsx(DXt,{datasetId:y,value:b,onValueChange:x,container:d})]})]}),y&&H!==void 0&&a.jsxs("p",{className:"text-meta text-muted-foreground",children:[H," ",H===1?"item":"items"]})]}),a.jsxs(sce,{index:2,done:!!_,children:[a.jsx(Mjs,{targetType:w,setTargetType:k,targetId:_,setTargetId:C,container:d}),w&&!_&&a.jsxs("p",{className:"text-meta text-muted-foreground",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),a.jsx(sce,{index:3,done:Z.length>0,isLast:!0,children:a.jsx(WX,{selectedScorers:Z,setSelectedScorers:E,disabled:L,container:d,helperText:B?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),a.jsxs(il,{children:[a.jsxs(Va,{className:"flex items-center gap-2 text-caption",children:[a.jsx(wr,{className:"size-4"}),"Request Context (JSON, optional)",M&&a.jsx(Mt,{size:"xs",variant:"blue",children:"set"})]}),a.jsx(qa,{className:"pt-3",children:z?a.jsx(Ljs,{requestContextSchema:q,onChange:N}):a.jsx(br,{value:A,onChange:P,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),a.jsxs(rc,{className:"items-center border-t border-border px-4 py-4 sm:justify-between",children:[a.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:R.length===0?a.jsxs(a.Fragment,{children:[a.jsx(Mt,{variant:"green",indicator:"dot",children:"Ready"}),a.jsxs("span",{className:"text-meta text-muted-foreground",children:[H??0," items · ",w," · ",Z.length," scorers"]})]}):a.jsxs(Mt,{variant:"neutral",indicator:"dot",children:["Missing ",R.join(", ")]})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:ee,disabled:L,children:"Cancel"}),a.jsx(ae,{variant:"primary",onClick:K,disabled:!Y||L,children:L?a.jsxs(a.Fragment,{children:[a.jsx(Cn,{className:"h-4 w-4"}),"Running..."]}):a.jsxs(a.Fragment,{children:["Run",a.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[a.jsx(Id,{size:"xs",children:Djs?"⌘":"Ctrl"}),a.jsx(Id,{size:"xs",children:"↵"})]})]})})]})]})]})})}const UXt=g.createContext(null);function Fjs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:o,children:i}){const l=zr(),u=sOe("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(v=>{l(`/experiments/${e}/items/${encodeURIComponent(v)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),p=g.useMemo(()=>u?r.findIndex(v=>v.itemId===u):-1,[r,u]),h=g.useMemo(()=>{if(p<=0)return;const v=r[p-1].itemId;return()=>d(v)},[p,r,d]),m=g.useMemo(()=>{if(p<0||p>=r.length-1)return;const v=r[p+1].itemId;return()=>d(v)},[p,r,d]);LXt({active:!!u,onPrevious:h,onNext:m,onClose:f});const y=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:o,currentItemId:u,openItem:d,close:f,goToPreviousItem:h,goToNextItem:m}),[e,t,n,r,s,o,u,d,f,h,m]);return a.jsx(UXt.Provider,{value:y,children:i})}function VXt(){const e=g.useContext(UXt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}const zjs=new Set(["itemId","id","status","input","tags","scores","startedAt"]);function qXt({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:o,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,emptyMessage:d="No results yet",selectedIds:f,onToggleSelect:p,onToggleSelectAll:h,sort:m,onSortChange:y}){const{Link:v,paths:b}=dn(),x=!!(f&&p),w=s.filter(V=>zjs.has(V.name)||i?.includes(V.name)),k=[x?"2rem":"",...w.map(V=>V.size)].filter(Boolean).join(" "),_=V=>w.some(B=>B.name===V),C=_("itemId")||_("id"),T=_("status"),E=_("input"),I=_("tags"),N=_("scores"),A=_("startedAt"),P=f?e.filter(V=>f.has(V.id)).length:0,F=e.length>0&&P===e.length,{containerRef:D,getRowProps:H}=Bc({count:e.length}),q=V=>i?.includes(V.name)?a.jsx(Oe.TopCell,{children:a.jsxs(v,{href:b.scorerLink(V.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[a.jsx(hb,{}),a.jsx("span",{className:"min-w-0 truncate",children:V.label})]})},V.name):V.name==="startedAt"&&y?a.jsx(Oe.SortableTopCell,{sortKey:"startedAt",sort:m?.key==="startedAt"?m.direction:void 0,onSortChange:y,children:V.label},V.name):a.jsx(Oe.TopCell,{children:V.label},V.name);return t?a.jsx(dc,{columns:k}):a.jsxs(Oe,{columns:k,className:"min-w-0",scrollRef:D,fit:"container",children:[a.jsxs(Oe.Top,{hasLeadingCell:x,children:[x&&(h?a.jsx(Oe.TopSelectCell,{checked:F?!0:P>0?"indeterminate":!1,onToggle:h,"aria-label":"Select all"}):a.jsx(Oe.TopCell,{children:" "})),x?a.jsx(Oe.TopCells,{colStart:2,children:w.map(q)}):w.map(q)]}),e.length===0?a.jsx(Oe.NoMatch,{message:d}):a.jsxs(a.Fragment,{children:[e.map((V,B)=>{const Z=!!V.error,z=V.id===n,Y=a.jsxs(a.Fragment,{children:[C&&a.jsxs(Oe.Cell,{className:"flex items-center gap-1.5 text-body-sm tracking-wide text-muted-foreground",children:[a.jsx("span",{children:V.itemId?.slice(0,8)??""}),Z&&a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx(KN,{role:"img","aria-label":"Error",className:"size-3.5 text-error"})}),a.jsx(kn,{children:Ujs(V.error)})]})]}),T&&a.jsx(Oe.Cell,{className:"flex items-center","data-testid":`result-status-${V.id}`,children:V.status?a.jsx(KMe,{status:V.status}):a.jsx("span",{className:"text-placeholder",children:"—"})}),E&&a.jsx(Oe.TextCell,{font:"mono",children:qjs(Vjs(V.input),200)}),I&&a.jsx(Oe.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${V.id}`,children:V.tags?.map(L=>a.jsx(qX,{value:L,className:"shrink-0"},L))}),N&&a.jsx(Oe.Cell,{children:a.jsx(Bjs,{scores:V.scores})}),A&&(V.startedAt?a.jsx(Oe.CreatedCell,{timestamp:V.startedAt}):a.jsx(Oe.Cell,{className:"text-placeholder",children:"—"})),i?.map(L=>{const M=o?.[V.itemId]?.find(U=>U.scorerId===L);return a.jsx(Oe.Cell,{className:"text-body-sm text-muted-foreground tabular-nums",children:M!=null?M.score.toFixed(3):"-"},L)})]});return x?a.jsxs(Oe.RowWrapper,{children:[a.jsx(Oe.SelectCell,{checked:f.has(V.id),onToggle:()=>p(V.id),"aria-label":`Select result ${V.itemId}`}),a.jsx(Oe.RowButton,{colStart:2,featured:z,"data-selected":z||void 0,onClick:()=>r(V.id),...H(B),children:Y})]},V.id):a.jsx(Oe.RowButton,{featured:z,"data-selected":z||void 0,onClick:()=>r(V.id),...H(B),children:Y},V.id)}),a.jsx(Oe.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Bjs({scores:e}){const t=Array.isArray(e)?e.map(n=>n.score).filter(n=>n!=null):Object.values(e??{});return t.length===0?a.jsx(je,{variant:"meta",tone:"faint",children:"—"}):a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(_t,{size:"xs",className:"text-muted-foreground",children:a.jsx(mv,{})}),a.jsx(je,{variant:"meta",tone:"muted",font:"mono",children:t[0].toFixed(2)}),t.length>1&&a.jsxs(Mt,{children:["+",t.length-1]})]})}function Ujs(e){return e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?e.message||"Error":typeof e=="string"&&e?e:"Error"}function Vjs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function qjs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Hjs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:o,hasNextPage:i,selectedIds:l,onToggleSelect:c,sort:u,onSortChange:d}){const{currentItemId:f,openItem:p,close:h}=VXt(),m=g.useMemo(()=>f?n.find(w=>w.itemId===f)?.id??null:null,[n,f]),{data:y}=A1(e,t),v=g.useMemo(()=>{if(!y)return[];const w=new Set;for(const k of Object.values(y))for(const _ of k)w.add(_.scorerId);return[...w].sort()},[y]),b=g.useCallback(w=>{const k=n.find(_=>_.id===w);k&&(k.itemId===f?h():p(k.itemId))},[n,f,h,p]),x=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"1fr"},{name:"tags",label:"Tags",size:"auto"},{name:"startedAt",label:"Created",size:"auto"},...v.map(w=>({name:w,label:w,size:"auto"}))],[v]);return a.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:a.jsx(qXt,{results:n,isLoading:r,featuredResultId:m,onResultClick:b,columns:x,scoresByItemId:y,scorerIds:v,setEndOfListElement:s,isFetchingNextPage:o,hasNextPage:i,selectedIds:l,onToggleSelect:c,sort:u,onSortChange:d})})}const qot={pending:{icon:a.jsx(R_,{className:"size-4 text-warning1"}),label:"Pending"},running:{icon:a.jsx(Cn,{size:"sm"}),label:"Running"},completed:{icon:a.jsx(gSt,{className:"size-4 text-muted-foreground"}),label:"Completed"},failed:{icon:a.jsx(VD,{className:"size-4 text-error"}),label:"Failed"}};function Wjs({status:e,className:t}){const n=qot[e]??qot.pending;return a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx("span",{tabIndex:0,className:W("flex shrink-0 items-center",t),children:n.icon})}),a.jsx(kn,{children:n.label})]})}function Zjs({children:e,className:t}){return a.jsx("div",{className:W("grid content-start gap-4 overflow-y-auto",t),children:e})}function Gjs({children:e,className:t}){return a.jsx("div",{className:"flex w-full overflow-y-auto",children:a.jsx("div",{className:W("grid w-full content-start gap-4 overflow-y-auto",t),children:e})})}function Qjs({children:e,className:t}){return a.jsx("div",{className:W("flex w-full flex-wrap items-center justify-between gap-3 gap-x-4",t),children:e})}const HXt=Object.assign(Gjs,{Content:Zjs,Toolbar:Qjs});function Yjs({children:e,className:t}){return a.jsx("div",{className:W("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const Kjs=e=>{const t=Xe();return wt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:$Kt,enabled:!!e})};function Xjs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${Fr(n,"date-time")}`}return`v${e}`}function Jjs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=CXt(e),o=(s??[]).map(i=>({value:String(i.version),label:`${Xjs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return a.jsxs(HXt.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[a.jsx("div",{}),a.jsx(wu,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:o,value:t??"",onValueChange:i=>r?.(i,n??"")}),a.jsx(wu,{label:"Version B",labelIsHidden:!0,name:"version-b",options:o,value:n??"",onValueChange:i=>r?.(t??"",i)}),a.jsx("div",{})]})}function WXt({children:e,className:t}){return a.jsx("div",{className:W("",t),children:e})}function eNs({date:e,className:t,preset:n="date"}){return a.jsx("div",{className:W("truncate text-body text-placeholder",t),children:Fr(e,n)})}function d2e(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function tNs({columns:e,isSelectionActive:t,children:n}){return a.jsx("div",{className:W("sticky top-0 z-10 mb-2 rounded-lg bg-card px-3"),children:a.jsx("div",{className:W("grid items-center gap-3 text-left text-meta tracking-widest text-muted-foreground uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:d2e(e)},children:n})})}function nNs({children:e,className:t}){return a.jsx("span",{className:W("py-3",t),children:e})}function rNs({id:e,className:t,isShortened:n=!0}){const r=n?e.slice(0,8):e;return a.jsx("div",{className:W("truncate py-[0.6rem] text-body text-placeholder",t),children:r})}function sNs({children:e}){return a.jsx("ul",{className:"grid content-start",children:e})}function oNs({children:e}){const t=g.useRef(null);return a.jsx("div",{ref:t,className:W("overflow-y-auto"),children:e})}function iNs({children:e,className:t}){return a.jsx("label",{className:W("flex h-full w-14 items-center justify-center rounded-lg text-caption hover:bg-fill-subtle",t),children:e})}function aNs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const o=a.jsx(r,{href:t,className:W("flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left","hover:bg-fill-subtle",vo.colors,hv.visible,n),children:e});return s==null?o:a.jsxs(On,{children:[a.jsx(Sn,{render:o}),a.jsx(kn,{children:s})]})}function lNs({children:e,message:t,className:n,type:r}){return!e&&!t?null:a.jsx("div",{className:W("grid border-t border-border",n),children:t?a.jsxs("p",{className:W("grid justify-center justify-items-center gap-2 p-5 text-center text-body text-muted-foreground","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?a.jsx(cu,{}):a.jsx(Hf,{})," ",t]}):e})}function cNs({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?a.jsxs("div",{ref:n,className:"mt-4 flex justify-center text-body text-muted-foreground opacity-50",children:[e&&r,!t&&!e&&s]}):null}function uNs({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return a.jsxs("div",{className:W("flex items-center justify-center gap-4 pt-4 text-body text-muted-foreground"),children:[a.jsxs("span",{children:["Page ",a.jsx("b",{children:e?e+1:"1"})]}),s&&a.jsxs("div",{className:W("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border [&>button]:p-1 [&>button]:px-2 [&>button]:text-muted-foreground [&>button]:transition-colors [&>button:hover]:text-foreground","[&_svg]:size-[1em] [&_svg]:text-muted-foreground"),children:[typeof e=="number"&&e>0&&a.jsxs("button",{onClick:r,children:[a.jsx(Cu,{}),"Previous"]}),t&&a.jsxs("button",{onClick:n,children:["Next",a.jsx(qf,{})]})]})]})}function dNs({children:e,className:t}){return a.jsx("div",{className:W("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function fNs({isSelected:e,children:t,columns:n}){return a.jsx("li",{className:W("flex overflow-hidden rounded-lg border border-transparent border-t-border py-[3px] pb-[2px] text-body text-foreground first:border-t-transparent","[&:last-child>button]:rounded-b-lg","[&.selected-row]:border [&.selected-row]:border-dashed [&.selected-row]:border-white/50 [&.selected-row]:pr-[3px] [&.selected-row]:first:border-t","[&:has(+.selected-row)]:rounded-b-none [&:has(+.selected-row)]:border-b-transparent","[.selected-row+&]:rounded-t-none",vo.colors,{"selected-row":e,"grid gap-3 px-3":n}),style:{gridTemplateColumns:d2e(n)},children:t})}function pNs({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:o,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=a.jsx("button",{...c,onClick:u,className:W("grid w-full items-center gap-3 rounded-lg px-3 text-left",vo.colors,hv.visible,{"bg-fill-hover":t,"hover:bg-fill-subtle":e&&!t&&!i},o),style:{gridTemplateColumns:d2e(s)},disabled:i,children:r});return l==null?d:a.jsxs(On,{children:[a.jsx(Sn,{render:d}),a.jsx(kn,{children:l})]})}function hNs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function mNs({status:e}){return e?a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("div",{className:W("relative flex h-full w-10 items-center justify-center bg-transparent"),children:a.jsx("div",{className:W("size-2 rounded-full",{"bg-green-600":["success","completed"].includes(e),"bg-red-700":["error","failed"].includes(e),"bg-yellow-500":["pending","running"].includes(e)})})})}),a.jsx(kn,{children:hNs(e)})]}):null}function gNs({children:e,isLoading:t,className:n}){return a.jsx("div",{className:W("truncate py-[0.6rem] text-body text-muted-foreground",n),children:t?a.jsx("div",{className:"h-4 animate-pulse rounded-md bg-muted text-transparent select-none"}):e})}const Hot={latest:"Latest version",deleted:"Deleted in this version"};function vNs({version:e,date:t,isLatest:n,isDeleted:r}){return a.jsxs(WXt,{className:W("grid grid-cols-[1fr_auto] pl-1"),children:[a.jsxs("div",{className:W("grid gap-1 leading-none text-muted-foreground",{"text-muted-foreground":n}),children:[a.jsxs("strong",{className:"text-body-sm",children:["v. ",e]}),a.jsx("em",{className:"text-caption text-placeholder",children:Fr(t,"date-time")})]}),(n||r)&&a.jsxs("div",{className:"flex items-center gap-1",children:[n&&a.jsx("span",{className:"inline-flex",role:"img","aria-label":Hot.latest,children:a.jsx(Mt,{variant:"blue",size:"sm",icon:a.jsx(R_,{})})}),r&&a.jsx("span",{className:"inline-flex",role:"img","aria-label":Hot.deleted,children:a.jsx(Mt,{variant:"red",size:"sm",icon:a.jsx(n_e,{})})})]})]})}const Mh=Object.assign(dNs,{Header:tNs,HeaderCol:nNs,Items:sNs,Scroller:oNs,Row:fNs,RowButton:pNs,Message:lNs,NextPageLoading:cNs,Pagination:uNs,Cell:WXt,TextCell:gNs,StatusCell:mNs,VersionCell:vNs,IdCell:rNs,DateCell:eNs,LinkCell:aNs,LabelCell:iNs}),yNs=[{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"}],V7={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:a.jsx(Yr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:a.jsx(Y2n,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:a.jsx(bSt,{}),tooltip:"Same in both versions"}};function oce({red:e=!1,tooltip:t}){return a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:"rounded focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-border-focus focus-visible:outline-solid",children:a.jsx(n_e,{className:W("h-5 w-5 text-muted-foreground/40",{"text-red-900":e})})}),a.jsx(kn,{children:t})]})}function ice({variant:e,version:t}){if(!e)return a.jsxs("span",{className:"text-body text-muted-foreground",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=V7[e];return a.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&a.jsxs("span",{className:"flex min-w-16 justify-end pr-3 text-body text-muted-foreground",children:["v. ",t]}),a.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:a.jsx(Mt,{variant:n,size:"xs",icon:r})})]})}function bNs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Wot({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function xNs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:o}){const{Link:i}=dn(),l=t>n;return a.jsx(Mh,{children:a.jsx(Mh.Scroller,{children:a.jsx(Mh.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=o.get(c),f=bNs(u,d),p=Wot({otherVersionExists:d!==void 0,status:f,isNewer:l}),h=Wot({otherVersionExists:u!==void 0,status:f,isNewer:!l});return a.jsxs(Mh.Row,{columns:yNs,children:[a.jsx(Mh.IdCell,{id:c,isShortened:!1}),f!=="same"?a.jsxs(a.Fragment,{children:[u?.datasetVersion?a.jsx(Mh.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?V7[p].tooltip:void 0,children:a.jsx(ice,{variant:p,version:u.datasetVersion})}):a.jsx(Mh.Cell,{className:"flex items-center justify-center",children:a.jsx(oce,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?a.jsx(Mh.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?V7[h].tooltip:void 0,children:a.jsx(ice,{variant:h,version:d.datasetVersion})}):a.jsx(Mh.Cell,{className:"flex items-center justify-center",children:a.jsx(oce,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):a.jsx(Mh.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:V7.same.tooltip,children:a.jsx(ice,{variant:"same",version:d?.datasetVersion})}),f==="changed"?a.jsx(Mh.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):a.jsx(Mh.Cell,{children:a.jsx(oce,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}const b_="targetType",vS="targetId";function ZXt({resetParams:e=[]}={}){const[t,n]=so(),r=e.join(","),s=t.get(b_),o=HX(s)?s:"",i=o?t.get(vS)??"":"",l=g.useCallback(d=>{n(f=>{const p=new URLSearchParams(f);d?p.set(b_,d):p.delete(b_),p.delete(vS);for(const h of r.split(","))h&&p.delete(h);return p},{replace:!0})},[n,r]),c=g.useCallback(d=>{n(f=>{const p=new URLSearchParams(f);d?p.set(vS,d):p.delete(vS);for(const h of r.split(","))h&&p.delete(h);return p},{replace:!0})},[n,r]),u=g.useCallback(()=>l(""),[l]);return{targetType:o,targetId:i,setTargetType:l,setTargetId:c,clear:u}}const rM=[Wr("/datasets")],wNs=["name","updatedAt"];function SNs(){const[e,t]=so(),{sort:n,onSortChange:r}=fk({searchParams:e,setSearchParams:t,allowedKeys:wNs}),s=g.useMemo(()=>n?{field:n.key,direction:n.direction==="asc"?"ASC":"DESC"}:void 0,[n]),[o,i]=g.useState(""),[l,c]=g.useState("all"),[u,d]=g.useState("all"),{targetType:f,targetId:p,setTargetType:h,setTargetId:m,clear:y}=ZXt(),{data:v=[],isLoading:b,error:x,isFetchingNextPage:w,hasNextPage:k,setEndOfListElement:_}=_6n({targetType:f,targetId:p},s),{data:C,isLoading:T,error:E}=a2e(),I=g.useMemo(()=>C?.experiments??[],[C?.experiments]),N=g.useMemo(()=>wTs(v),[v]),A=b||T,P=x||E,F=zr(),D=()=>{F("/datasets/new")},H=a.jsx(mK,{href:"/datasets/new",tooltip:"Create a dataset",children:"New dataset"});if(P&&_s(P))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(Qs,{variant:"fill"})]});if(P&&js(P))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(Fs,{variant:"fill",resource:"datasets"})]});if(P)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load datasets",descriptionSlot:P.message})]});if(v.length===0&&!A&&!f)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),headerActions:H,children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(STs,{onCreateClick:D})]});const q=l!=="all"||u!=="all"||o!==""||f!=="",V=()=>{i(""),c("all"),d("all"),y()};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rM}),headerActions:H,actionRow:a.jsx(CTs,{search:o,onSearchChange:i,experimentFilter:l,onExperimentFilterChange:c,tagFilter:u,onTagFilterChange:d,tagOptions:N,targetType:f,onTargetTypeChange:h,targetId:p,onTargetIdChange:m,onReset:V,hasActiveFilters:q}),children:[a.jsx("h1",{className:"sr-only",children:"Datasets"}),a.jsx(bTs,{datasets:v,experiments:I,isLoading:A,search:o,experimentFilter:l,tagFilter:u,isFetchingNextPage:w,hasNextPage:k,setEndOfListElement:_,sort:n,onSortChange:r})]})}function kNs(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 ONs({item:e,itemId:t,fallback:n,onClose:r,...s}){const o=e?.id??t;return a.jsx(Rt,{open:!!o,onClose:r,title:`Dataset item ${o??""}`,children:e?a.jsx(_Ns,{item:e,onClose:r,...s},e.id):t?a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:r,tooltip:"Close detail panel"}),a.jsxs(Rt.Heading,{children:["Item",a.jsx(Rt.CopyId,{id:t})]})]}),n]}):null})}function _Ns({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:o}=dn(),{updateItem:i,deleteItem:l}=cl(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[p,h]=g.useState(""),[m,y]=g.useState(""),[v,b]=g.useState(""),[x,w]=g.useState(""),[k,_]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[E,I]=g.useState(""),[N,A]=g.useState(null),[P,F]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),y(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),I(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),F(!1),A(null))},[t?.id]);const D=n.findIndex(L=>L.id===t.id),H=D>0?()=>r(n[D-1].id):void 0,q=D>=0&&D<n.length-1?()=>r(n[D+1].id):void 0,V=async()=>{let L;try{L=JSON.parse(d)}catch{Qe.error("Input must be valid JSON");return}let R;if(p.trim())try{R=JSON.parse(p)}catch{Qe.error("Ground Truth must be valid JSON");return}let M;if(m.trim())try{M=JSON.parse(m)}catch{Qe.error("Metadata must be valid JSON");return}let U=null;if(v.trim())try{U=JSON.parse(v)}catch{Qe.error("Expected Trajectory must be valid JSON");return}let Q;if(x.trim())try{const ee=JSON.parse(x);if(!Array.isArray(ee)){Qe.error("Tool Mocks must be a JSON array");return}Q=ee}catch{Qe.error("Tool Mocks must be valid JSON");return}else Q=[];let te;if(E.trim())try{te=JSON.parse(E)}catch{Qe.error("Request Context must be valid JSON");return}let K;k?K=C:t.scorerIds!==void 0&&(K=null);try{const ee=await i.mutateAsync({datasetId:e,itemId:t.id,input:L,groundTruth:R,metadata:M,expectedTrajectory:U,toolMocks:Q,scorerIds:K,requestContext:te});Qe.success("Item updated successfully"),_(ee.scorerIds!==void 0),T(ee.scorerIds??[]),u(!1),A(null)}catch(ee){const ne=kNs(ee);ne?A(ne):Qe.error(`Failed to update item: ${ee instanceof Error?ee.message:"Unknown error"}`)}},B=()=>{f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),y(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),I(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},Z=L=>{f(L),N?.field==="input"&&A(null)},z=L=>{h(L),N?.field==="groundTruth"&&A(null)},Y=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Qe.success("Item deleted successfully"),F(!1),s()}catch(L){Qe.error(`Failed to delete item: ${L instanceof Error?L.message:"Unknown error"}`)}};return a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:s,tooltip:"Close detail panel"}),a.jsxs(Rt.Heading,{children:["Item",a.jsx(Rt.CopyId,{id:t.id})]}),a.jsxs(Rt.HeaderActions,{children:[!c&&a.jsxs(a.Fragment,{children:[a.jsx(ae,{render:a.jsx(o,{href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`}),size:"sm",variant:"ghost",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:a.jsx(h_e,{})}),a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{size:"sm",variant:"ghost",tooltip:"Open actions menu","aria-label":"Open actions menu",children:a.jsx(U1,{})})}),a.jsxs(pt.Content,{align:"end",className:"w-48",children:[a.jsxs(pt.Item,{onSelect:()=>u(!0),children:[a.jsx(Bd,{}),"Edit"]}),a.jsxs(pt.Item,{onSelect:()=>F(!0),className:"text-red-500 focus:text-red-400",children:[a.jsx(Ni,{}),"Delete Item"]})]})]})]}),a.jsx(Rt.NextPrevNav,{onPrevious:H,onNext:q,previousLabel:"Go to previous item",nextLabel:"Go to next item"})]})]}),a.jsx(Rt.Content,{children:c?a.jsx(Pjs,{inputValue:d,setInputValue:Z,groundTruthValue:p,setGroundTruthValue:z,metadataValue:m,setMetadataValue:y,trajectoryValue:v,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:_,selectedScorerIds:C,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:I,validationErrors:N,onSave:V,onCancel:B,isSaving:i.isPending}):a.jsx(JSe,{item:t})}),a.jsx($t,{open:P,onOpenChange:F,children:a.jsxs($t.Content,{children:[a.jsxs($t.Header,{children:[a.jsx($t.Title,{children:"Delete Item"}),a.jsx($t.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),a.jsxs($t.Footer,{children:[a.jsx($t.Cancel,{children:"Cancel"}),a.jsx($t.Action,{onClick:Y,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function CNs(){const{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:s,close:o}=zXt(),i=g.useMemo(()=>r?t.find(d=>d.id===r):void 0,[t,r]),{data:l,isLoading:c}=zKt(i?"":e,!i&&r?r:""),u=i??l??void 0;return a.jsx(ONs,{datasetId:e,item:u,itemId:r,fallback:n||c?a.jsx(Rt.LoadingData,{}):a.jsxs(Rt.NoData,{children:['No loaded item "',r,'".']}),items:t,onItemChange:s,onClose:o})}function nB({crumbs:e,children:t}){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:e}),children:[a.jsx("h1",{className:"sr-only",children:"Dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:t})]})}function ENs(){const{datasetId:e,itemId:t}=fr(),n=[Wr("/datasets"),{...FG,to:`/datasets/${encodeURIComponent(e)}`},...t?[{id:"dataset-items",label:"Items"},{id:"dataset-item",label:FCe(t)}]:[]],r=zr(),[s,o]=so(),{activeVersion:i,handleVersionChange:l}=u2e(s,o),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[p,h]=g.useState(!1),[m,y]=g.useState(!1),{data:v,error:b,isLoading:x}=vv(e),{data:w=[],isLoading:k}=oA(e,void 0,i),_=!k&&w.length===0;if(x)return null;if(b&&_s(b))return a.jsx(nB,{crumbs:n,children:a.jsx(Qs,{})});if(b&&js(b))return a.jsx(nB,{crumbs:n,children:a.jsx(Fs,{resource:"datasets"})});if(b&&zA(b)||!x&&!b&&!v)return a.jsx(nB,{crumbs:n,children:a.jsx(un,{titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:a.jsx(ae,{render:a.jsx(ml,{to:"/datasets"}),icon:a.jsx(Cu,{}),children:"Back to Datasets"})})});if(b)return a.jsx(nB,{crumbs:n,children:a.jsx(un,{tone:"error",titleSlot:"Failed to load dataset",descriptionSlot:b instanceof Error?b.message:"An unexpected error occurred. Please try again."})});const C=E=>{r(`/experiments/${E}`)},T=()=>{r("/datasets")};return a.jsxs(Ejs,{datasetId:e,items:w,isLoadingItems:k,children:[a.jsxs("div",{className:"h-full",children:[a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{children:a.jsx(jjs,{datasetId:e,onAddItemClick:()=>f(!0),belowToolbarSlot:a.jsx(Njs,{datasetId:e}),leftSlot:a.jsx("span",{className:"mr-3 text-caption whitespace-nowrap text-muted-foreground",children:v?.createdAt?`Created ${Fr(v.createdAt,"date-time")}`:""}),rightSlot:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ae,{render:a.jsx(ml,{to:`/experiments?dataset=${e}`}),icon:a.jsx(lG,{}),children:"View experiments"}),a.jsx(DXt,{datasetId:e,value:i,onValueChange:l,currentVersion:v?.version,className:"w-36"}),_?a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("span",{className:"cursor-not-allowed",children:a.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:a.jsx(ae,{variant:"primary",icon:a.jsx(bu,{}),children:"Run Experiment"})})})}),a.jsx(kn,{children:"Add items to the dataset before running an experiment"})]}):a.jsx(ae,{variant:"primary",onClick:()=>u(!0),icon:a.jsx(bu,{}),children:"Run Experiment"}),a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{size:"lg","aria-label":"Dataset actions menu",children:a.jsx(U1,{})})}),a.jsxs(pt.Content,{align:"end",className:"w-48",children:[a.jsxs(pt.Item,{onSelect:()=>{r(`/datasets/${e}/edit`)},children:[a.jsx(Bd,{})," Edit Dataset"]}),a.jsxs(pt.Item,{onSelect:()=>y(!0),children:[a.jsx(Ju,{})," Duplicate Dataset"]}),a.jsxs(pt.Item,{onSelect:()=>h(!0),className:"text-red-500 focus:text-red-400",children:[a.jsx(Ni,{})," Delete Dataset"]})]})]})]})})})]}),a.jsx(CNs,{})]}),a.jsx(ZX,{initialDatasetId:e,initialDatasetVersion:i??void 0,open:c,onOpenChange:u,onSuccess:C},`${e}:${i??"latest"}`),a.jsx(Ajs,{datasetId:e,open:d,onOpenChange:f}),v&&a.jsx(VTs,{open:m,onOpenChange:y,sourceDatasetId:v.id,sourceDatasetName:v.name,sourceDatasetDescription:v.description,sourceDatasetTargetType:v.targetType}),v&&a.jsx(ZTs,{open:p,onOpenChange:h,datasetId:v.id,datasetName:v.name,onSuccess:T})]})}const GXt=[Wr("/datasets"),FG,{id:"dataset-edit",label:"Edit dataset"}];function ace({children:e}){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:GXt}),children:[a.jsx("h1",{className:"sr-only",children:"Edit dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:e})]})}function TNs(){const{datasetId:e}=fr(),t=zr(),{data:n,error:r,isLoading:s}=vv(e),o=()=>{t(`/datasets/${e}`)};return s?null:r&&_s(r)?a.jsx(ace,{children:a.jsx(Qs,{})}):r&&js(r)?a.jsx(ace,{children:a.jsx(Fs,{resource:"datasets"})}):r||!n?a.jsx(ace,{children:a.jsx(un,{tone:"error",titleSlot:"Failed to load dataset",descriptionSlot:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:GXt}),children:[a.jsx("h1",{className:"sr-only",children:"Edit dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[a.jsx(Ap,{className:"mb-6 p-0",children:a.jsxs(Ap.Column,{children:[a.jsxs(Ap.Title,{children:[a.jsx(nv,{})," Edit dataset"]}),a.jsx(Ap.Description,{children:n.name})]})}),a.jsx(ku,{className:"p-4",children:a.jsx(WTs,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema,scorerIds:n.scorerIds},onSuccess:o,onCancel:o})})]})})]})}function Zot(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function Got(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:a.jsxs("span",{className:"flex w-full items-center gap-2",children:[a.jsxs("span",{children:[a.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",Fr(r,"date-time")]}),n.isLatest?a.jsx(Mt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function Qot(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function jNs(){const{datasetId:e,itemId:t}=fr(),[n,r]=so(),s=[Wr("/datasets"),FG,{id:"dataset-item",label:FCe(t),to:e&&t?`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`:void 0},{id:"dataset-item-versions",label:"Item Version History"}],o=Qot(n.get("version")),i=Qot(n.get("compare")),l=n.get("view")==="diff",{data:c,error:u}=vv(e??""),{data:d,isLoading:f}=eTs(e??"",t??""),p=(o!=null?d?.find(T=>T.datasetVersion===o):void 0)??d?.[0],h=p?.datasetVersion??null,m=i!=null&&i!==h?i:null,{data:y,isLoading:v}=tTs(e??"",t??"",m??0,c?.version),b=(T,E)=>r(I=>{const N=new URLSearchParams(I);return E==null?N.delete(T):N.set(T,String(E)),N},{replace:!0});if(u&&_s(u))return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(Qs,{variant:"fill"})]});if(u&&js(u))return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx(Fs,{variant:"fill",resource:"datasets"})]});if(!e||!t)return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:s}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsx("div",{className:"py-5 text-center text-muted-foreground",children:a.jsx("p",{children:"Item not found."})})})]});const x=!!(p&&y),w=l&&x,k=p?Zot(p,e):null,_=y?Zot(y,e):null,C=(p?.datasetVersion??0)<(y?.datasetVersion??0);return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:s}),headerActions:x&&a.jsx(ae,{variant:"ghost",size:"sm",onClick:()=>b("view",l?null:"diff"),children:l?a.jsxs(a.Fragment,{children:[a.jsx(s_e,{})," Default View"]}):a.jsxs(a.Fragment,{children:[a.jsx(kMn,{})," Diff View"]})}),children:[a.jsx("h1",{className:"sr-only",children:"Item Version History"}),a.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2",children:[a.jsxs(ku,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx($q,{children:a.jsx(Yot,{name:"version",value:h!=null?String(h):"",options:Got(d??[],m!=null?new Set([m]):void 0),onValueChange:T=>b("version",Number(T))})}),a.jsx(lv,{className:"grid content-start gap-5 overflow-y-auto",children:f?a.jsx("div",{className:"text-body text-muted-foreground",children:"Loading..."}):k?a.jsx(JSe,{item:k,diff:w&&_?{against:_,side:C?"a":"b"}:void 0}):a.jsx("div",{className:"text-body text-muted-foreground",children:"Item data not available"})})]}),a.jsxs(ku,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[a.jsx($q,{children:a.jsx(Yot,{name:"compare",value:m!=null?String(m):"",placeholder:"Select a version to compare",options:Got(d??[],h!=null?new Set([h]):void 0),onValueChange:T=>b("compare",Number(T))})}),a.jsx(lv,{className:"grid content-start gap-5 overflow-y-auto",children:m==null?a.jsx(un,{className:"h-full",titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):v?a.jsx("div",{className:"text-body text-muted-foreground",children:"Loading..."}):_?a.jsx(JSe,{item:_,diff:w&&k?{against:k,side:C?"b":"a"}:void 0}):a.jsxs("div",{className:"text-body text-muted-foreground",children:["Version ",m," not found"]})})]})]})]})}function Yot({name:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return a.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[a.jsx(h_e,{className:"size-4 opacity-50"}),a.jsxs(Po,{name:e,value:t,onValueChange:s,children:[a.jsx(Mo,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:a.jsx($o,{placeholder:r,className:"flex-1"})}),a.jsx(Do,{children:n.map(o=>a.jsx(Vr,{value:o.value,disabled:o.disabled,children:o.label},o.value))})]})]})}const rB=[Wr("/datasets"),FG,{id:"dataset-versions",label:"Versions"}];function NNs(){const{datasetId:e}=fr(),[t]=so(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=zr(),{data:s,error:o}=vv(e??""),i=oA(e??"",void 0,n[0]??null),l=oA(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const y of[...c,...u])m.has(y.id)||m.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...m.values()].sort((y,v)=>v.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),p=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(o&&_s(o))return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:rB}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(Qs,{variant:"fill"})]});if(o&&js(o))return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:rB}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx(Fs,{variant:"fill",resource:"datasets"})]});if(!e||n.length<2)return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:rB}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsx("div",{className:"py-5 text-center text-muted-foreground",children:a.jsx("p",{children:"Select at least two versions to compare."})})})]});const h=(m,y)=>{r(`/datasets/${e}/versions?ids=${m},${y}`,{replace:!0})};return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:rB}),children:[a.jsx("h1",{className:"sr-only",children:"Versions"}),a.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:a.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-4",children:[a.jsxs(Ap,{children:[a.jsxs(Ap.Column,{children:[a.jsxs(Ap.Title,{children:[a.jsx(CDn,{})," Compare Dataset Versions"]}),a.jsx(Ap.Description,{children:a.jsxs(Pd,{children:[a.jsx(h_e,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),a.jsx(Ap.Column,{children:a.jsx(ae,{render:a.jsx(ml,{to:`/datasets/${e}`}),icon:a.jsx(Cu,{}),children:"Back to Dataset"})})]}),a.jsx(Yjs,{children:a.jsxs(HXt,{children:[a.jsx(Jjs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:h}),a.jsx(xNs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p})]})})]})})]})}const INs=[Wr("/datasets"),{id:"dataset-new",label:"Create new dataset"}];function ANs(){const e=zr(),[t]=so(),n=t.get("targetType"),r=HX(n)?n:void 0,s=t.get("targetIds"),o=r&&s?s.split(",").map(l=>l.trim()).filter(Boolean):void 0,i=l=>{e(`/datasets/${l}`)};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:INs}),children:[a.jsx("h1",{className:"sr-only",children:"Create new dataset"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[a.jsx(Ap,{className:"mb-6 p-0",children:a.jsxs(Ap.Column,{children:[a.jsxs(Ap.Title,{children:[a.jsx(nv,{})," Create new dataset"]}),a.jsx(Ap.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),a.jsx(ku,{className:"p-4",children:a.jsx(LTs,{targetType:r,targetIds:o,onSuccess:i,onCancel:()=>{e(-1)}})})]})})]})}function QXt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:o}=cl(),i=async()=>{try{await o.mutateAsync(n),Qe.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Qe.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return a.jsx($t,{open:e,onOpenChange:t,children:a.jsxs($t.Content,{children:[a.jsxs($t.Header,{children:[a.jsx($t.Title,{children:"Delete Experiment"}),a.jsxs($t.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),a.jsxs($t.Footer,{children:[a.jsx(ae,{icon:a.jsx(Ni,{}),variant:"primary",size:"lg",onClick:i,disabled:o.isPending,children:o.isPending?"Deleting...":"Delete"}),a.jsx($t.Cancel,{children:"Cancel"})]})]})})}const RNs="minmax(9rem,1fr)",PNs="minmax(8rem,16rem)",$Ns="1fr",MNs="auto auto auto auto auto auto auto",Hv={experiment:"Experiment",description:"Description",dataset:"Dataset",target:"Target",status:"Status",items:"Items",succeeded:"Processed",failed:"Errored",review:"Review",date:"Date"},DNs={completed:"neutral",running:"yellow",failed:"red",pending:"neutral"},LNs={completed:"Run completed",running:"Run in progress",failed:"Run failed",pending:"Run queued"};function YXt(e){const t=g0(e.id)??e.id;return e.name||`Experiment #${t}`}const FNs=60;function zNs({experiment:e}){return a.jsx("span",{className:"block min-w-0 truncate text-left text-muted-foreground",children:YXt(e)})}function BNs({experiment:e}){const t=e.description;if(!t)return a.jsx("span",{className:"text-placeholder",children:"—"});const n=a.jsx("span",{className:"block min-w-0 truncate text-left text-muted-foreground",children:t});return t.length<=FNs?n:a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:n}),a.jsx(kn,{children:t})]})}function KXt(){const{data:e}=ef(),{data:t}=ih(),{data:n}=lh(),{data:r}=nE();return{agents:e,workflows:t,scorers:n,processors:r}}const XXt={agent:Pi,workflow:yl,scorer:hb,processor:kO},JXt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},UNs="External (caller-run)";function eJt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:o,targetId:i}=e;if(!i)return UNs;switch(o){case"agent":return t?.[i]?.name??i;case"workflow":return n?.[i]?.name??i;case"scorer":return r?.[i]?.scorer?.config?.name??i;case"processor":return s?.[i]?.name??i;default:return i}}function VNs({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,o=e.failedCount??0,i=e.totalItems??0;return a.jsxs(a.Fragment,{children:[a.jsx(Oe.Cell,{children:a.jsx(zNs,{experiment:e})}),a.jsx(Oe.Cell,{children:a.jsx(BNs,{experiment:e})}),t!==void 0&&a.jsx(Oe.TextCell,{children:t}),a.jsx(Oe.Cell,{children:a.jsx(qNs,{experiment:e})}),a.jsx(Oe.Cell,{children:a.jsx(Mt,{variant:DNs[r]??"neutral",indicator:"dot",children:LNs[r]??r})}),a.jsx(Oe.TextCell,{className:"text-center",children:i}),a.jsx(Oe.TextCell,{className:"text-center",children:s}),a.jsx(Oe.TextCell,{className:"text-center",children:a.jsx("span",{className:o>0?"text-accent2":"",children:o})}),a.jsx(Oe.Cell,{className:"text-center",children:a.jsx(HNs,{review:n})}),a.jsx(Oe.TextCell,{children:Fr(e.createdAt,"date")??"—"})]})}function qNs({experiment:e}){const t=KXt(),n=eJt(e,t),r=e.targetId?e.targetType:null,s=r?XXt[r]:null;return a.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&a.jsx("span",{className:"flex text-muted-foreground",role:"img","aria-label":JXt[r],children:a.jsx(s,{})}),a.jsx("span",{className:r?"truncate":"truncate text-placeholder",children:n})]})}function HNs({review:e}){if(!e)return a.jsx("span",{className:"text-placeholder",children:"—"});const t=e.needsReview+e.complete;return t===0?a.jsx("span",{className:"text-placeholder",children:"—"}):e.needsReview>0?a.jsxs(Mt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):a.jsxs(Mt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const tJt=`${RNs} ${PNs} ${$Ns} ${MNs}`,Kot=`${tJt} auto`,WNs=[{label:Hv.experiment},{label:Hv.description},{label:Hv.dataset},{label:Hv.target},{label:Hv.status,sortKey:"status"},{label:Hv.items,className:"text-center"},{label:Hv.succeeded,className:"text-center"},{label:Hv.failed,className:"text-center"},{label:Hv.review,className:"text-center"},{label:Hv.date,sortKey:"createdAt"}],nJt=e=>e.stopPropagation();function ZNs({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:s,children:o}){const{paths:i,Link:l}=dn(),c=g.useRef(null);return a.jsxs(Oe.RowWrapper,{...t,onSelectRow:n??(()=>c.current?.click()),children:[n?a.jsx(Oe.RowButton,{colEnd:-2,featured:r,tabIndex:-1,onClick:u=>{u.stopPropagation(),n()},children:o}):a.jsx(Oe.RowLink,{ref:c,colEnd:-2,to:i.experimentLink(e.id),LinkComponent:l,tabIndex:-1,onClick:nJt,children:o}),a.jsx(Oe.ActionsCell,{className:"pl-2",children:a.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:u=>{u.stopPropagation(),s()},children:a.jsx(Ni,{className:"size-4"})})})]})}function GNs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:o="all",datasetFilter:i="all",selection:l,onSelectExperiment:c,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:p,setEndOfListElement:h,sort:m,onSortChange:y}){const v=l!==void 0,b=g.useMemo(()=>{const N=new Map;return t?.forEach(A=>N.set(A.id,A.name)),N},[t]),x=g.useMemo(()=>m?e:[...e].sort((N,A)=>{const P=N.createdAt?new Date(N.createdAt).getTime():0;return(A.createdAt?new Date(A.createdAt).getTime():0)-P}),[e,m]),w=g.useMemo(()=>{const N=s.toLowerCase();return x.filter(A=>{const P=A.datasetId?b.get(A.datasetId)??"":"",F=!N||A.id.toLowerCase().includes(N)||(A.name??"").toLowerCase().includes(N)||P.toLowerCase().includes(N)||(A.targetId??"").toLowerCase().includes(N),D=o==="all"||A.status===o,H=i==="all"||A.datasetId===i;return F&&D&&H})},[x,s,b,o,i]),{containerRef:k,getRowProps:_}=Bc({count:w.length,global:d}),[C,T]=g.useState(null);if(r)return a.jsx(dc,{columns:Kot});const E=v?`auto ${tJt}`:Kot,I=WNs.map(N=>N.sortKey&&y?a.jsx(Oe.SortableTopCell,{className:N.className,sortKey:N.sortKey,sort:m?.key===N.sortKey?m.direction:void 0,onSortChange:y,children:N.label},N.label):a.jsx(Oe.TopCell,{className:N.className,children:N.label},N.label));return a.jsxs(Oe,{columns:E,scrollRef:k,children:[a.jsx(Oe.Top,{hasLeadingCell:v,children:v?a.jsxs(a.Fragment,{children:[a.jsx(Oe.TopCell,{children:" "}),a.jsx(Oe.TopCells,{colStart:2,children:I})]}):a.jsxs(a.Fragment,{children:[I,a.jsx(Oe.TopCell,{"aria-hidden":!0,children:null})]})}),w.map((N,A)=>{const P=N.datasetId?b.get(N.datasetId)??g0(N.datasetId)??N.datasetId:"—",F=a.jsx(VNs,{experiment:N,datasetName:P,review:n?.get(N.id)});if(!l)return a.jsx(ZNs,{experiment:N,rowProps:_(A),onSelect:c?()=>c(N):void 0,featured:u===N.id,onDelete:()=>T(N),children:F},N.id);const D=l.selectedExperimentIds.includes(N.id),H=()=>l.onToggleSelection(N.id);return a.jsxs(Oe.RowWrapper,{..._(A),onSelectRow:H,children:[a.jsx(Oe.SelectCell,{checked:D,onToggle:H,"aria-label":`Select experiment ${N.id}`}),a.jsx(Oe.RowButton,{colStart:2,featured:D,tabIndex:-1,onClick:nJt,children:F})]},N.id)}),a.jsx(Oe.NextPageLoading,{isLoading:f,hasMore:p,setEndOfListElement:h}),C&&a.jsx(QXt,{open:!0,onOpenChange:N=>{N||T(null)},experimentId:C.id,experimentName:C.name??void 0})]})}const QNs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function YNs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const KNs=({onRunExperiment:e})=>a.jsx(un,{titleSlot:"No Experiments yet",descriptionSlot:a.jsxs(a.Fragment,{children:["Run an experiment from a dataset to evaluate ",a.jsx("br",{}),"your agents and workflows."]}),actionSlot:a.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&a.jsx(ae,{variant:"primary",onClick:e,icon:a.jsx(bu,{}),children:"Run Experiment"}),a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Ts,{}),children:"Experiments Documentation"})]}),variant:"fill"});function XNs({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:o,datasetOptions:i,targetType:l,onTargetTypeChange:c,targetId:u,onTargetIdChange:d,onReset:f,hasActiveFilters:p,onRunClick:h,runTooltip:m="Run an experiment",onCompareClick:y,selection:v}){const b=v?.selectedCount===2&&!v.compareDisabledReason;return a.jsxs(Gn,{children:[a.jsxs(Gn.Start,{children:[a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),a.jsx(wu,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...QNs],value:n,onValueChange:r,className:"whitespace-nowrap"}),a.jsx(wu,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:o,className:"whitespace-nowrap"}),a.jsx(AXt,{targetType:l,targetId:u,onTargetTypeChange:c,onTargetIdChange:d}),f&&p&&a.jsx(ae,{onClick:f,size:"sm",variant:"default",icon:a.jsx(Gt,{}),children:"Reset"})]}),v?a.jsx(Gn.End,{children:a.jsxs(zl,{className:"whitespace-nowrap",children:[a.jsxs(Fp,{className:"gap-2",children:[a.jsxs(Mt,{size:"sm",variant:v.selectedCount<2?"red":"green",children:[v.selectedCount," / 2"]}),"selected",v.compareDisabledReason&&a.jsxs("span",{className:"text-accent2",children:["· ",v.compareDisabledReason]})]}),a.jsx(ae,{variant:"primary",disabled:!b,onClick:v.onExecuteCompare,icon:a.jsx(z8e,{}),children:"Compare Experiments"}),a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:v.onCancelSelection,children:"Cancel"})]})}):a.jsxs(Gn.End,{children:[y&&a.jsx(ae,{onClick:y,tooltip:"Select two experiments of the same dataset to compare",icon:a.jsx(z8e,{}),children:"Compare"}),h&&a.jsx(ae,{onClick:h,tooltip:m,variant:"primary",icon:a.jsx(bu,{}),children:"Run Experiment"})]})]})}const JNs={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Xot=e=>e?e instanceof Date?e.toISOString():e:null,Jot=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},eit=(e,t,n)=>{if(!e)return JNs;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:Xot(t?.startedAt),completedAt:Xot(t?.completedAt),scores:Object.entries(e.scores).map(([s,o])=>({scorerId:s,value:o,reason:r.get(s)??null})).sort((s,o)=>s.scorerId.localeCompare(o.scorerId))}},eIs=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:o,contenderScores:i})=>{if(!e)return[];const l=Jot(r),c=Jot(s);return e.items.map(u=>{const d=eit(u.results[t],l.get(u.itemId),o?.[u.itemId]),f=eit(u.results[n],c.get(u.itemId),i?.[u.itemId]),p={};for(const h of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(v=>v.scorerId===h)?.value??null,y=f.scores.find(v=>v.scorerId===h)?.value??null;p[h]=m!=null&&y!=null?y-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:p}})};function TO({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return a.jsxs(il,{defaultOpen:r,className:"grid gap-2",children:[a.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[a.jsxs(Va,{className:W("flex items-center gap-1.5 text-subheading [&>svg]:size-4",n==="negative"?"text-negative1":"text-foreground"),children:[a.jsx(wr,{}),e]}),t]}),a.jsx(qa,{role:"region","aria-label":e,children:s})]})}function tit({label:e,value:t}){return t==null?null:a.jsx(TO,{title:e,defaultOpen:!1,children:a.jsx("pre",{className:"max-h-40 overflow-auto rounded-md bg-card p-3 text-caption whitespace-pre-wrap text-muted-foreground",children:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function rJt({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-muted-foreground";return a.jsxs("span",{className:W("inline-flex min-w-20 items-center gap-1 text-body tabular-nums",t),children:[a.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?a.jsx(t_e,{className:"size-3.5"}):e<0?a.jsx(lSt,{className:"size-3.5"}):null]})}function sJt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:o}=dn();return a.jsxs("div",{className:"grid gap-1 rounded-lg bg-background px-3 py-2",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsxs(s,{href:o.scorerLink(e),"aria-label":`Open ${e}`,className:"flex min-w-0 items-center gap-1.5 text-subheading text-foreground hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[a.jsx(hb,{}),a.jsx("span",{className:"min-w-0 truncate",children:e})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("span",{className:"text-body text-muted-foreground tabular-nums",children:t!=null?t.toFixed(2):"-"}),n!=null&&a.jsx(rJt,{delta:n})]})]}),r&&a.jsx("p",{className:"text-body text-muted-foreground",children:r})]})}function nit(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function tIs(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Zd(t)??null}const nIs=W(ir,"max-h-[30vh] overflow-y-auto rounded-xl p-4 text-body break-all whitespace-pre-wrap text-muted-foreground");function rit({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],o=tIs(s);if(r)return a.jsx("div",{className:"flex h-32 items-center justify-center",children:a.jsx(Cn,{})});if(!s.present)return a.jsx("p",{className:"py-5 text-center text-body text-muted-foreground",children:"Not present in this experiment"});const i=nit(s.output);return a.jsxs("div",{className:"grid content-start gap-5",children:[o&&a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsxs("p",{className:"flex items-center justify-end gap-1.5 text-body text-muted-foreground [&>svg]:size-3.5",children:[a.jsx(R_,{}),a.jsx(je,{as:"span",variant:"body",font:"mono",children:o})]})}),a.jsx(kn,{children:"Run duration"})]}),s.error?a.jsx(TO,{title:"Error",tone:"negative",actions:a.jsx(Oo,{content:s.error.message}),children:a.jsx("p",{className:"rounded-xl border border-negative1/40 bg-negative1/5 p-4 text-body break-words text-muted-foreground",children:s.error.message})}):a.jsx(TO,{title:"Output",actions:a.jsx(Oo,{content:i}),children:a.jsx("pre",{className:nIs,children:i})}),s.scores.length>0&&a.jsx(TO,{title:"Scores",children:a.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>a.jsx(sJt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&a.jsx(TO,{title:"Comment",defaultOpen:!1,children:a.jsx("p",{className:"text-body text-muted-foreground",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&a.jsx(TO,{title:"Metadata",defaultOpen:!1,children:a.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>a.jsxs("div",{className:"flex items-start justify-between gap-4 text-body",children:[a.jsx("dt",{className:"text-muted-foreground",children:l}),a.jsx("dd",{className:"break-all text-foreground",children:a.jsx(je,{as:"span",variant:"body",font:"mono",children:nit(c)})})]},l))})})]})}const rIs={baseline:"Baseline",contender:"Contender"},sIs={baseline:"purple",contender:"blue"},oIs="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function sit({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:o,paths:i}=dn(),l=rIs[e],c=t?g0(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return a.jsxs("div",{className:"grid content-start gap-3",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(Mt,{variant:sIs[e],size:"xs",children:l}),t&&a.jsx(ae,{render:a.jsx(o,{href:`/experiments/${t.id}`}),size:"sm","aria-label":`Open experiment ${t.name||c}`,children:a.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&a.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-caption text-muted-foreground",children:[t.name&&a.jsxs(Pd,{children:[a.jsx(AA,{})," ",c]}),t.targetType==="agent"&&t.targetId?a.jsxs(o,{href:i.agentLink(t.targetId),className:oIs,children:[a.jsx(Pi,{}),a.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):a.jsxs(Pd,{children:[a.jsx(ZSt,{})," ",t.targetId]}),a.jsx("span",{className:W(s&&"text-accent6"),children:a.jsxs(Pd,{children:[a.jsx(C3,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&a.jsxs(Pd,{children:[a.jsx(iV,{})," ",Fr(u,"date-time")]})]}),d.length>0&&a.jsx(TO,{title:"Overall score",children:a.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:p,delta:h})=>a.jsx(sJt,{scorerId:f,value:p,delta:r?h:null},f))})})]})}const WT="min-w-0 px-4 py-3";function iIs({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=dn(),{data:o,isLoading:i,error:l}=nTs(e,t,n),{data:c}=L4(e,t),{data:u}=L4(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=o?.baselineId??t,p=t===f?n:t,h=c?.id===f?c:u,m=c?.id===p?c:u,{data:y,isLoading:v}=YSe({datasetId:e,experimentId:f,experimentStatus:h?.status}),{data:b,isLoading:x}=YSe({datasetId:e,experimentId:p,experimentStatus:m?.status}),{data:w}=A1(f,h?.status),{data:k}=A1(p,m?.status),_=g.useMemo(()=>eIs({comparison:o,baselineId:f,contenderId:p,baselineResults:y,contenderResults:b,baselineScores:w,contenderScores:k}),[o,f,p,y,b,w,k]),C=g.useMemo(()=>[...new Set(_.flatMap(E=>Object.keys(E.deltas)))].sort(),[_]),T=g.useMemo(()=>{const E=(A,P)=>{const F=_.map(D=>D[A].scores.find(H=>H.scorerId===P)?.value).filter(D=>D!=null);return F.length>0?F.reduce((D,H)=>D+H,0)/F.length:null},I=C.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),N=C.map(A=>{const P=E("baseline",A),F=E("contender",A);return{scorerId:A,average:F,delta:P!=null&&F!=null?F-P:null}});return{baseline:I,contender:N}},[_,C]);return i?a.jsx("div",{className:"flex h-64 items-center justify-center",children:a.jsx(Cn,{})}):l?a.jsx(Jt,{variant:"warning",title:"Error loading comparison",children:a.jsx(Jt.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!o||o.items.length===0?a.jsx("div",{className:"py-5 text-center text-body text-muted-foreground",children:"No comparison data"}):a.jsx("div",{className:"grid gap-4",children:a.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[a.jsxs("div",{role:"row",className:"grid border-y border-border xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border)]",children:[a.jsx("div",{role:"columnheader","aria-label":"Items",className:`${WT} text-caption text-muted-foreground uppercase`,children:"Items"}),a.jsx("div",{role:"columnheader","aria-label":"Baseline",className:WT,children:a.jsx(sit,{side:"baseline",experiment:h??void 0,summary:T.baseline,versionMismatch:d??void 0})}),a.jsx("div",{role:"columnheader","aria-label":"Contender",className:WT,children:a.jsx(sit,{side:"contender",experiment:m??void 0,summary:T.contender,versionMismatch:d??void 0,showDeltas:!0})})]}),_.map(E=>{const I=Object.entries(E.deltas).flatMap(([N,A])=>A==null||A===0?[]:[{scorerId:N,delta:A}]);return a.jsxs("div",{role:"row","aria-label":E.itemId,className:"grid border-b border-border xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border)]",children:[a.jsxs("div",{role:"cell",className:`${WT} grid content-start gap-1`,children:[a.jsx(r,{href:s.datasetItemLink(e,E.itemId),"aria-label":`Open item ${E.itemId}`,className:W("flex items-start gap-1.5 text-caption break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0",E.baseline.present&&E.contender.present?"text-muted-foreground":"text-placeholder"),children:a.jsx(je,{as:"span",variant:"caption",font:"mono",className:"min-w-0",children:E.itemId})}),I.length>0&&a.jsx("span",{className:"flex flex-wrap items-center gap-2",children:I.map(({scorerId:N,delta:A})=>a.jsx(rJt,{delta:A},N))}),a.jsxs("div",{className:"grid pt-3",children:[a.jsx(tit,{label:"Input",value:E.input}),a.jsx(tit,{label:"Ground truth",value:E.groundTruth})]})]}),a.jsx("div",{role:"cell","aria-label":"Baseline",className:WT,children:a.jsx(rit,{side:"baseline",row:E,isLoading:v})}),a.jsx("div",{role:"cell","aria-label":"Contender",className:WT,children:a.jsx(rit,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const aIs=100;function lIs(e,t,n){const r=Xe(),{inView:s,setRef:o}=A0(),i=t?.targetType||void 0,l=t?.targetId||void 0,c=Tm({queryKey:e?["dataset-experiments",e,"infinite",{targetType:i,targetId:l,orderBy:n}]:["experiments","infinite",{targetType:i,targetId:l,orderBy:n}],queryFn:({pageParam:u})=>{const d={page:u,perPage:aIs};return i&&(d.targetType=i),l&&(d.targetId=l),n&&(d.orderBy=n),e?r.listDatasetExperiments(e,d):r.listExperiments(d)},initialPageParam:0,getNextPageParam:(u,d,f)=>{if(!(!u?.experiments?.length||!u.pagination?.hasMore))return f+1},select:u=>u.pages.flatMap(d=>d?.experiments??[])});return g.useEffect(()=>{s&&c.hasNextPage&&!c.isFetchingNextPage&&c.fetchNextPage()},[s,c]),{...c,setEndOfListElement:o}}function cIs({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s,size:o="sm"}){const[i,l]=g.useState(!1),[c,u]=g.useState(""),d=t.filter(p=>p.toLowerCase().includes(c.toLowerCase())),f=c.trim()&&!t.includes(c.trim());return a.jsxs(ah,{open:i,onOpenChange:l,children:[a.jsx(Vd,{asChild:!0,children:a.jsxs(ae,{size:o,icon:a.jsx(V1,{}),children:["Tag ",e," items"]})}),a.jsxs(Zf,{className:"w-56 p-2",align:"end",children:[a.jsx(gr,{value:c,onChange:p=>u(p.target.value),onKeyDown:p=>{p.key==="Enter"&&c.trim()&&(p.preventDefault(),f?s(c.trim()):n(c.trim()),u(""))},placeholder:"Search or create tag...",className:"mb-1 h-7 text-caption",autoFocus:!0}),a.jsxs("div",{className:"max-h-40 space-y-0.5 overflow-y-auto",children:[d.map(p=>a.jsxs("div",{className:"flex items-center justify-between rounded px-2 py-1 text-caption hover:bg-fill-subtle",children:[a.jsx("button",{type:"button",onClick:()=>n(p),className:"flex-1 text-left text-muted-foreground",children:p}),a.jsx("button",{type:"button",onClick:()=>r(p),className:"ml-2 text-placeholder hover:text-negative1",children:a.jsx(Gt,{className:"h-3 w-3"})})]},p)),f&&a.jsxs("button",{type:"button",onClick:()=>{s(c.trim()),u("")},className:"w-full rounded px-2 py-1 text-left text-caption text-accent1 hover:bg-fill-subtle",children:['Create & apply "',c.trim(),'"']})]})]})]})}function uIs({tag:e,onRename:t,onRemove:n}){const[r,s]=g.useState(!1),[o,i]=g.useState(e),l=g.useRef(null);g.useEffect(()=>{r&&(l.current?.focus(),l.current?.select())},[r]);const c=()=>{const u=o.trim();u&&u!==e&&t(u),s(!1)};return r?a.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1",children:[a.jsx("input",{ref:l,value:o,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),c()),u.key==="Escape"&&(i(e),s(!1))},onBlur:c,className:"w-20 bg-transparent py-0.5 text-caption text-muted-foreground outline-hidden"}),a.jsx("button",{type:"button",onMouseDown:u=>{u.preventDefault(),c()},className:"hover:text-positive2 p-0.5 text-positive1",children:a.jsx(Vn,{className:"h-3 w-3"})})]}):a.jsxs("span",{className:"group inline-flex items-center gap-0.5 rounded-md border border-border bg-card px-1.5 py-0.5 text-caption text-muted-foreground",children:[e,a.jsx("button",{type:"button",onClick:()=>{i(e),s(!0)},className:W(Pn,"p-0.5 opacity-0 transition-opacity group-hover:opacity-100"),title:"Edit tag",children:a.jsx(Bd,{className:"h-3 w-3"})}),a.jsx("button",{type:"button",onClick:n,className:"p-0.5 text-placeholder opacity-0 transition-opacity group-hover:opacity-100 hover:text-negative1",title:"Remove tag",children:a.jsx(Gt,{className:"h-3 w-3"})})]})}const dIs=100;function oJt(e,t,{enabled:n=!0}={}){const r=Xe(),s={perPage:dIs};return t?.targetType&&(s.targetType=t.targetType),t?.targetId&&(s.targetId=t.targetId),wt({enabled:n,queryKey:["experiments",s],queryFn:()=>r.listExperiments(s)})}const iJt=(e,{experimentId:t,targetType:n,targetId:r,experiments:s,isLoadingExperiments:o=!1})=>{const i=Xe(),l=s!==void 0,{data:c,isLoading:u}=oJt(void 0,{targetType:n,targetId:r},{enabled:!l}),d=l?s:c?.experiments,f=l?o:u,p=t?d?.filter(m=>m.id===t):d,h=wt({queryKey:["review-items",e,t??"all",l?"supplied":"discovered",l?void 0:n||"all",l?void 0:r||"all",p?.map(m=>[m.datasetId,m.id])],queryFn:async()=>!p||p.length===0?[]:(await Promise.all(p.map(async y=>{if(!y.datasetId)return[];try{const{results:v}=await i.listDatasetExperimentResults(y.datasetId,y.id);return v.filter(b=>b.status===e).map(b=>({id:b.id,input:b.input,output:b.output,error:b.error,itemId:b.itemId,experimentId:b.experimentId,datasetId:y.datasetId??void 0,traceId:b.traceId??void 0,scores:b.scores?Object.fromEntries(b.scores.map(x=>[x.scorerId,x.score??0])):{},tags:b.tags??[],createdAt:b.createdAt,status:b.status,groundTruth:b.groundTruth,toolMockReport:b.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!d,refetchOnWindowFocus:!1});return{...h,isLoading:h.isLoading||f}},fIs=(e={})=>iJt("needs-review",e),pIs=(e={})=>iJt("complete",e);function hIs(e){const{data:t}=RE(e),r=t?.spans.find(i=>!i.parentSpanId)?.entityType==="agent",{supportsMetrics:s}=F6(),o=VSe({traceIds:e?[e]:[],enabled:r&&s,autoRefetch:!1});return e?o.data?.get(e):void 0}const oit="__create_tag__";function aJt({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,appearance:s="toolbar"}){const[o,i]=g.useState(""),l=g.useMemo(()=>[...t].sort(),[t]),c=g.useMemo(()=>{if(e.length===0)return new Set;const[f,...p]=e;return new Set((f.tags??[]).filter(h=>p.every(m=>(m.tags??[]).includes(h))))},[e]),u=g.useMemo(()=>{const f=l.map(m=>({label:m,value:m,end:c.has(m)?a.jsx(Vn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=o.trim();return p.length>0&&!l.includes(p)?[{label:`Create "${p}"`,value:oit},...f]:f},[l,c,o]),d=f=>{const p=f===oit?o.trim():f;!p||c.has(p)||n(p)};return a.jsx(za,{"data-testid":"experiment-results-tag-picker",options:u,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(V1,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s==="inline"?"ghost":"default",size:s==="inline"?"sm":"md",className:"w-auto min-w-0",disabled:r})}function lce(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function mIs({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,o=[...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 a.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[a.jsx(Rt.SectionHeading,{icon:a.jsx(xu,{}),children:"Tool Mocks"}),s&&a.jsx(Jt,{variant:"destructive",title:"Mock mismatch",children:a.jsxs(Jt.Message,{children:[a.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),a.jsxs("span",{className:"mt-1 block text-caption",children:["Called with: ",a.jsx(w1,{children:lce(s.args)})]}),n.length>0&&a.jsxs("span",{className:"mt-1 block text-caption",children:["Unconsumed mocks: ",a.jsx(w1,{children:n.map(i=>lce(i.args)).join(", ")})]})]})}),a.jsx("div",{className:"divide-y divide-border rounded border border-border text-body",children:o.map((i,l)=>a.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[a.jsxs("span",{className:"min-w-0 truncate",children:[a.jsx(je,{as:"span",variant:"body-sm",tone:"muted",font:"mono",children:i.toolName}),a.jsx(je,{as:"span",variant:"caption",tone:"muted",font:"mono",className:"ml-2",children:lce(i.args)})]}),a.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-caption ${gIs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function gIs(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-muted-foreground/10 text-muted-foreground"}}function vIs({result:e,itemId:t,fallback:n,title:r,onClose:s,...o}){const i=r??(t?`Experiment item ${t}`:`Result ${e?.id??""}`);return a.jsx(Rt,{open:!!(e??t),onClose:s,title:i,depth:1,size:"half",children:e?a.jsx(yIs,{result:e,onClose:s,...o}):t?a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:s,tooltip:"Close result panel"}),a.jsxs(Rt.Heading,{children:["Experiment item",a.jsx(Rt.CopyId,{id:t})]})]}),n]}):null})}function yIs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:o,onScoreClick:i,featuredScoreId:l,onFlagForReview:c,onTagsChange:u,tagVocabulary:d=[],isUpdatingTags:f=!1,experimentLink:p,onComplete:h,feedbackTabSlot:m}){const y=!!e?.error,v=sB(e?.input),b=sB(e?.output),x=sB(e?.groundTruth),w=c&&e.status!=="needs-review"&&e.status!=="complete",k=Array.isArray(e.tags)?e.tags:[],_=g.useMemo(()=>[e],[e]),C=!!u||k.length>0,{Link:T}=dn(),E=m&&e.traceId?e.traceId:void 0,{data:I}=z6({traceId:E}),N=hIs(e.traceId),A=a.jsxs(Rt.Content,{children:[a.jsxs("div",{className:"mb-6 grid gap-4",children:[a.jsxs(Ft,{children:[a.jsx(Ft.Key,{children:"Item Id"}),a.jsx(Ft.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),e.createdAt&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Created"}),a.jsx(Ft.Value,{children:Fr(e.createdAt,"date-time")})]}),e.status&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Status"}),a.jsx(Ft.Value,{children:a.jsx(KMe,{status:e.status})})]}),C&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Tags"}),a.jsx(Ft.Value,{children:a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[k.map(P=>a.jsxs(qX,{value:P,className:u?"gap-1 pr-1":void 0,children:[P,u&&a.jsx("button",{type:"button","aria-label":`Remove tag ${P}`,disabled:f,onClick:()=>u(k.filter(F=>F!==P)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:a.jsx(Gt,{className:"size-3"})})]},P)),u&&a.jsx(aJt,{appearance:"inline",selectedResults:_,vocabulary:d,onAddTag:P=>u([...k,P]),disabled:f})]})})]}),N&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Input tokens"}),a.jsx(Ft.Value,{children:N.inputTokens!==void 0?$l(N.inputTokens):"—"}),a.jsx(Ft.Key,{children:"Output tokens"}),a.jsx(Ft.Value,{children:N.outputTokens!==void 0?$l(N.outputTokens):"—"}),a.jsx(Ft.Key,{children:"Cost"}),a.jsx(Ft.Value,{children:N.estimatedCost!==void 0?bm(N.estimatedCost,N.costUnit):"—"})]})]}),y&&a.jsx(Jt,{variant:"destructive",title:"Error",children:a.jsx(Jt.Message,{children:sB(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&a.jsxs(Oe,{columns:"1fr 1fr",children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{children:"Scorer"}),a.jsx(Oe.TopCell,{children:"Score"})]}),t.map(P=>i?a.jsxs(Oe.RowButton,{featured:l===P.id,onClick:()=>i(P.id),children:[a.jsx(Oe.Cell,{children:P.scorerId}),a.jsx(Oe.TextCell,{font:"mono",children:P.score.toFixed(3)})]},P.id):a.jsxs(Oe.RowStatic,{children:[a.jsx(Oe.Cell,{children:P.scorerId}),a.jsx(Oe.TextCell,{font:"mono",children:P.score.toFixed(3)})]},P.id))]}),e.toolMockReport&&a.jsx(mIs,{report:e.toolMockReport})]}),a.jsxs("div",{className:"grid gap-3",children:[a.jsx(Rt.CodeSection,{title:"Input",icon:a.jsx(i_e,{}),codeStr:v}),a.jsx(Rt.CodeSection,{title:"Output",icon:a.jsx(CS,{}),codeStr:b}),e.groundTruth!==void 0&&a.jsx(Rt.CodeSection,{title:"Ground Truth",icon:a.jsx(ZSt,{}),codeStr:x})]})]});return a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:s,tooltip:"Close result panel"}),a.jsxs(Rt.Heading,{children:["Result",a.jsx(Rt.CopyId,{id:e.id})]}),a.jsxs(Rt.HeaderActions,{children:[w&&a.jsx(ae,{size:"sm",variant:"primary",onClick:()=>c(e.id),icon:a.jsx(O3,{}),children:"Flag for Review"}),h&&e.status==="needs-review"&&a.jsx(ae,{size:"sm",variant:"primary",onClick:h,icon:a.jsx(k3,{}),children:"Mark as reviewed"}),p&&a.jsx(ae,{size:"sm",variant:"ghost",render:a.jsx(T,{href:p}),tooltip:"See experiment","aria-label":"See experiment",children:a.jsx(lG,{})}),e.traceId&&o&&a.jsx(ae,{size:"sm",variant:"ghost",onClick:o,tooltip:"See trace","aria-label":"See trace",children:a.jsx(a0,{})}),a.jsx(Rt.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Go to previous result",nextLabel:"Go to next result"})]})]}),E?a.jsxs(ll,{defaultTab:"details",className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[a.jsx(Rt.Header,{children:a.jsxs(al,{variant:"pill-ghost",size:"sm",children:[a.jsx(Lr,{value:"details",children:"Details"}),a.jsxs(Lr,{value:"feedback",children:["Feedback",I?.pagination?.total!=null&&a.jsxs(a.Fragment,{children:[" (",I.pagination.total,")"]})]})]})}),a.jsx(Ss,{value:"details",flush:!0,children:A}),a.jsx(Ss,{value:"feedback",flush:!0,children:a.jsx(Rt.Content,{children:m({traceId:E})})})]}):A]})}function sB(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function bIs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function xIs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){return a.jsx(Rt,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:"Score",depth:2,children:e&&a.jsx(wIs,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s})})}function wIs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){const o=bIs(e),i=o?"N/A — code-based scorer":"N/A — step not configured";return a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:r,tooltip:"Close score panel"}),a.jsxs(Rt.Heading,{children:["Score",a.jsx(Rt.CopyId,{id:e.scorerId})]}),a.jsxs(Rt.HeaderActions,{children:[s&&e.traceId&&a.jsx(ae,{size:"sm",variant:"ghost",onClick:s,tooltip:"See trace","aria-label":"See trace",children:a.jsx(a0,{})}),(n||t)&&a.jsx(Rt.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Go to previous score",nextLabel:"Go to next score"})]})]}),a.jsx(Rt.Content,{children:a.jsxs("div",{className:"grid gap-3",children:[a.jsx(Rt.CodeSection,{title:`Score: ${e.score}`,icon:a.jsx(mv,{}),codeStr:e.reason||i,simplified:!0}),!o&&a.jsxs(a.Fragment,{children:[a.jsx(Rt.CodeSection,{title:"Preprocess Prompt",icon:a.jsx(Uh,{}),codeStr:e.preprocessPrompt||i,simplified:!0}),a.jsx(Rt.CodeSection,{title:"Analyze Prompt",icon:a.jsx(Uh,{}),codeStr:e.analyzePrompt||i,simplified:!0}),a.jsx(Rt.CodeSection,{title:"Generate Score Prompt",icon:a.jsx(Uh,{}),codeStr:e.generateScorePrompt||i,simplified:!0}),a.jsx(Rt.CodeSection,{title:"Generate Reason Prompt",icon:a.jsx(Uh,{}),codeStr:e.generateReasonPrompt||i,simplified:!0})]})]})})]})}function lJt(e,t){const[n,r]=g.useState(null),[s,o]=g.useState(void 0),[i,l]=g.useState(null),[c,u]=g.useState(t);t!==c&&(u(t),r(null),o(void 0),l(null));const d=e?.find(f=>f.id===i)??null;return{featuredTraceId:n,setFeaturedTraceId:r,featuredSpanId:s,setFeaturedSpanId:o,featuredScoreId:i,setFeaturedScoreId:l,featuredScore:d}}function cJt({result:e,scores:t,state:n,withQueryTrace:r,withFeedback:s,...o}){const i=lJt(t,e?.id),{featuredTraceId:l,setFeaturedTraceId:c,featuredSpanId:u,setFeaturedSpanId:d,featuredScoreId:f,setFeaturedScoreId:p,featuredScore:h}=n??i,m=I=>{p(N=>I===N?null:I),c(null),d(void 0)},y=I=>{I&&(c(I),d(void 0),p(null))},v=()=>{if(!f||!t)return;const I=t.findIndex(N=>N.id===f);if(I>=0&&I<t.length-1)return()=>p(t[I+1].id)},b=()=>{if(!f||!t)return;const I=t.findIndex(N=>N.id===f);if(I>0)return()=>p(t[I-1].id)},{data:x,isLoading:w}=Kjs(l),k=x?.spans,_=k?.find(I=>!I.parentSpanId),{data:C}=z6({traceId:l??void 0,enabled:s}),{data:T}=YMe({traceId:l??void 0,spanId:u,enabled:s}),{data:E}=TX({traceId:l??void 0,spanId:_?.spanId,page:0});return a.jsxs(a.Fragment,{children:[a.jsx(vIs,{...o,result:e,scores:t,onScoreClick:m,featuredScoreId:f,onShowTrace:e?.traceId?()=>y(e.traceId):void 0,feedbackTabSlot:s?({traceId:I})=>a.jsx(UW,{traceId:I},I):void 0}),a.jsx(xIs,{score:h??void 0,onNext:v(),onPrevious:b(),onClose:()=>p(null),onShowTrace:h?()=>y(h.traceId):void 0}),a.jsx(s2e,{size:"wide",depth:2,traceId:l??void 0,spans:k,isLoadingSpans:w,selectedSpanId:u??null,onClose:()=>{c(null),d(void 0)},onSpanSelect:d,showUnavailableFeaturesMsg:!1,traceHref:l?`/traces?traceId=${encodeURIComponent(l)}`:void 0,anchorSpanId:_?.spanId,withQueryTrace:r,withFeedback:s,feedbackTabBadge:s?C?.pagination?.total??void 0:void 0,feedbackTabSlot:s?({traceId:I})=>a.jsx(UW,{traceId:I}):void 0,scoresTabBadge:E?.pagination?.total??void 0,scoresTabSlot:({traceId:I,rootSpanId:N})=>N?a.jsx(XMe,{traceId:I,spanId:N,onScoreSelect:A=>{t?.some(P=>P.id===A)&&(c(null),d(void 0),p(A))}}):null,spanFeedbackTabBadge:s?T?.pagination?.total??void 0:void 0,spanFeedbackTabSlot:s?({traceId:I,spanId:N})=>I&&N?a.jsx(tXt,{traceId:I,spanId:N},`${I}:${N}`):null:void 0})]})}const SIs=[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"},{name:"scores",label:"Scores",size:"6rem"}],cce="__untagged__",oB="all",kIs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function OIs({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:s,targetId:o,featuredItemId:i,toolbarStart:l,renderFilters:c,toolbarEnd:u,onCreateScorer:d,breadcrumbs:f,withQueryTrace:p,withFeedback:h}){const m=Xe(),{paths:y}=dn(),{data:v}=vv(e??""),{data:b,isLoading:x}=fIs({experimentId:t,targetType:s,targetId:o,experiments:n,isLoadingExperiments:r}),{data:w,isLoading:k}=pIs({experimentId:t,targetType:s,targetId:o,experiments:n,isLoadingExperiments:r}),{updateExperimentResult:_}=cl(),[C,T]=g.useState(i??null);g.useEffect(()=>{i!==void 0&&T(i)},[i]);const[E,I]=g.useState(null),[N,A]=g.useState(new Set),[P,F]=g.useState(!1),[D,H]=g.useState(!1),[q,V]=g.useState(!1),[B,Z]=g.useState(""),[z,Y]=g.useState(""),[L,R]=g.useState(""),[M,U]=g.useState([]),[Q,te]=g.useState(!1),K=g.useMemo(()=>b??[],[b]),ee=g.useMemo(()=>{const ge=new Set;if(v?.tags)for(const De of v.tags)ge.add(De);for(const De of K)for(const et of De.tags)ge.add(et);return[...ge].sort()},[v,K]),ne=g.useCallback(ge=>{!v||!e||(v.tags??[]).includes(ge)},[v,e]),le=g.useMemo(()=>E?E===cce?K.filter(ge=>ge.tags.length===0):K.filter(ge=>ge.tags.includes(E)):K,[K,E]),J=g.useMemo(()=>{const ge=new Map;let De=0;for(const Et of K){Et.tags.length===0&&De++;for(const Ut of Et.tags)ge.set(Ut,(ge.get(Ut)??0)+1)}const et=[...ge.entries()].sort((Et,Ut)=>Ut[1]-Et[1]).map(([Et])=>({value:Et,label:Et}));return[{value:oB,label:"All tags"},...De>0?[{value:cce,label:"Untagged"}]:[],...et]},[K]),re=!!E||P,se=g.useCallback(()=>{I(null),F(!1),T(null)},[]),ie=g.useCallback((ge,De)=>{const et=K.find(Et=>Et.id===ge);et?.experimentId&&et?.datasetId&&_.mutate({datasetId:et.datasetId,experimentId:et.experimentId,resultId:et.id,tags:De})},[K,_]),fe=g.useCallback(ge=>{const De=K.find(et=>et.id===ge);A(et=>{const Et=new Set(et);return Et.delete(ge),Et}),C===ge&&T(null),De?.experimentId&&De?.datasetId&&_.mutate({datasetId:De.datasetId,experimentId:De.experimentId,resultId:De.id,status:null})},[K,_,C]),he=g.useCallback(ge=>{const De=K.find(et=>et.id===ge);A(et=>{const Et=new Set(et);return Et.delete(ge),Et}),C===ge&&T(null),De?.experimentId&&De?.datasetId&&_.mutate({datasetId:De.datasetId,experimentId:De.experimentId,resultId:De.id,status:"complete"})},[K,_,C]),xe=g.useMemo(()=>{const ge=P?w??[]:le;return!P||!E?ge:E===cce?ge.filter(De=>De.tags.length===0):ge.filter(De=>De.tags.includes(E))},[P,w,le,E]),Ne=P?k:!1,Ae=g.useMemo(()=>new Set(xe.map(ge=>ge.id)),[xe]),Ge=g.useMemo(()=>[...N].filter(ge=>Ae.has(ge)).length,[N,Ae]),Ue=xe.length>0&&Ge===xe.length,Le=g.useCallback(ge=>{A(De=>{const et=new Set(De);return et.has(ge)?et.delete(ge):et.add(ge),et})},[]),be=g.useCallback(()=>{A(Ue?new Set:new Set(xe.map(ge=>ge.id)))},[Ue,xe]),_e=g.useCallback(ge=>{for(const De of N){const et=K.find(Et=>Et.id===De);et&&!et.tags.includes(ge)&&ie(De,[...et.tags,ge])}},[K,N,ie]),ye=g.useCallback(ge=>{for(const De of N){const et=K.find(Et=>Et.id===De);et&&et.tags.includes(ge)&&ie(De,et.tags.filter(Et=>Et!==ge))}},[K,N,ie]),ve=g.useCallback(()=>{for(const ge of N)he(ge);A(new Set)},[N,he]),me=g.useCallback(()=>{for(const ge of N)fe(ge);A(new Set)},[N,fe]),de=g.useCallback(()=>{Z(""),V(!0)},[]),Ce=g.useCallback(async()=>{if(!(!z||!L)){H(!0),V(!1);try{const ge=K.filter(et=>N.has(et.id));if(ge.length===0){H(!1);return}const De=await m.clusterFailures({modelId:`${z}/${L}`,items:ge.map(et=>({id:et.id,input:et.input,output:et.output??void 0,error:typeof et.error=="string"?et.error:et.error?String(et.error):void 0,scores:et.scores,existingTags:et.tags.length>0?et.tags:void 0})),availableTags:ee.length>0?ee:void 0,prompt:B||void 0});De.proposedTags&&De.proposedTags.length>0&&(U(De.proposedTags.map(et=>({...et,accepted:!0}))),te(!0))}catch(ge){console.error("Analysis failed:",ge)}finally{H(!1)}}},[z,L,K,N,m,ee,B]),Ve=g.useCallback(()=>{for(const ge of M){if(!ge.accepted)continue;const De=K.find(et=>et.id===ge.itemId);if(De){const et=[...new Set([...De.tags,...ge.tags])];ie(De.id,et)}}te(!1)},[M,K,ie]),Fe=g.useCallback(ge=>{T(De=>De===ge?null:ge)},[]),ce=g.useMemo(()=>C?xe.find(ge=>ge.id===C)??null:null,[C,xe]),{data:we}=A1(ce?.experimentId??""),Ee=C?xe.findIndex(ge=>ge.id===C):-1,Be=Ee>0?()=>T(xe[Ee-1].id):void 0,qe=Ee>=0&&Ee<xe.length-1?()=>T(xe[Ee+1].id):void 0,Ie=!P&&N.size>0,Re=!!d&&!P&&le.length>0,He=P?"completed":"review",ze=ge=>{F(ge==="completed"),T(null)},nt=a.jsxs(Gn,{children:[a.jsx(Gn.Start,{children:c?a.jsxs(a.Fragment,{children:[l,c({status:He,onStatusChange:ze,tag:E,onTagChange:I,tagOptions:J.filter(ge=>ge.value!==oB)})]}):a.jsxs(a.Fragment,{children:[l,a.jsx(wu,{label:"Status",labelIsHidden:!0,name:"filter-status",options:kIs,value:He,onValueChange:ge=>ze(ge==="completed"?"completed":"review"),className:"whitespace-nowrap"}),J.length>1&&a.jsx(wu,{label:"Tags",labelIsHidden:!0,name:"filter-tags",options:J,value:E??oB,onValueChange:ge=>I(ge===oB?null:ge),className:"whitespace-nowrap"}),re&&a.jsx(ae,{onClick:se,size:"sm",variant:"default",icon:a.jsx(Gt,{}),children:"Reset"})]})}),(Ie||u||Re)&&a.jsxs(Gn.End,{children:[u,Re&&a.jsxs(ae,{size:"md",onClick:()=>d?.(le.map(ge=>({input:ge.input,output:ge.output}))),children:[a.jsx(_t,{size:"xs",children:a.jsx(mv,{})}),"Create Scorer"]}),Ie&&a.jsxs(a.Fragment,{children:[a.jsx(cIs,{size:"md",selectedCount:N.size,vocabulary:ee,onApplyTag:_e,onRemoveTag:ye,onNewTag:ge=>_e(ge)}),a.jsx(ae,{variant:"primary",onClick:ve,icon:a.jsx(k3,{}),children:"Mark as reviewed"}),a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{disabled:D,"aria-label":"More actions",children:D?a.jsx(Cn,{className:"h-4 w-4"}):a.jsx(P_,{})})}),a.jsxs(pt.Content,{align:"end",children:[a.jsxs(pt.Item,{onSelect:de,children:[a.jsx(_t,{size:"xs",children:a.jsx(j3,{})}),"Analyze"]}),a.jsx(pt.Separator,{}),a.jsxs(pt.Item,{onSelect:me,children:[a.jsx(_t,{size:"xs",children:a.jsx(Ni,{})}),"Remove from queue"]})]})]})]})]})]});if(x)return a.jsxs(gt,{breadcrumbs:f,actionRow:nt,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Cn,{fill:!0})]});const jt=a.jsx(cJt,{withQueryTrace:p,withFeedback:h,result:ce??void 0,title:`Review item ${ce?.id??""}`,scores:ce?we?.[ce.itemId]:void 0,experimentLink:ce?.experimentId?y.experimentItemLink(ce.experimentId,ce.itemId):void 0,tagVocabulary:ee,onTagsChange:P||!ce?void 0:ge=>{ie(ce.id,ge);for(const De of ge)ee.includes(De)||ne(De)},onComplete:P||!ce?void 0:()=>he(ce.id),onPrevious:Be,onNext:qe,onClose:()=>T(null)});return a.jsxs(gt,{breadcrumbs:f,actionRow:nt,children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(hs,{open:q,onOpenChange:V,children:a.jsxs(rs,{children:[a.jsxs(ss,{children:[a.jsx(Jr,{children:"Analyze Items"}),a.jsx(Ms,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),a.jsxs("div",{className:"space-y-4 py-2",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{children:[a.jsx(Mn,{className:"mb-1 block",children:"Provider"}),a.jsx(rk,{value:z,onValueChange:Y})]}),a.jsxs("div",{children:[a.jsx(Mn,{className:"mb-1 block",children:"Model"}),a.jsx(sk,{llmId:z,value:L,onValueChange:R})]})]}),a.jsxs(je,{variant:"meta",tone:"muted",children:[N.size," item",N.size!==1?"s":""," will be analyzed"]}),a.jsxs("div",{children:[a.jsx(Mn,{children:"Instructions (optional)"}),a.jsx(Im,{value:B,onChange:ge=>Z(ge.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-caption"})]})]}),a.jsxs(rc,{children:[a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:()=>V(!1),children:"Cancel"}),a.jsxs(ae,{onClick:Ce,disabled:!z||!L||D,children:[D?a.jsx(Cn,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),a.jsx(hs,{open:Q,onOpenChange:te,children:a.jsxs(rs,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[a.jsxs(ss,{children:[a.jsx(Jr,{children:"Review Proposed Tags"}),a.jsxs(Ms,{children:[M.filter(ge=>ge.accepted).length," of ",M.length," proposals selected"]})]}),a.jsx("div",{className:"space-y-3 py-2",children:M.map((ge,De)=>{const et=K.find(Et=>Et.id===ge.itemId);return a.jsx("div",{className:W("rounded-lg border p-3",!ge.accepted&&"opacity-50"),children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Eu,{checked:ge.accepted,onCheckedChange:Et=>U(Ut=>Ut.map((Zt,ft)=>ft===De?{...Zt,accepted:!!Et}:Zt))}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx(je,{variant:"meta",tone:"muted",className:"block truncate",children:et?typeof et.input=="string"?et.input.slice(0,100):JSON.stringify(et.input).slice(0,100):ge.itemId}),a.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:ge.tags.map((Et,Ut)=>a.jsx(uIs,{tag:Et,onRename:Zt=>U(ft=>ft.map((hn,mn)=>mn===De?{...hn,tags:hn.tags.map((ke,Pe)=>Pe===Ut?Zt:ke)}:hn)),onRemove:()=>U(Zt=>Zt.map((ft,hn)=>hn===De?{...ft,tags:ft.tags.filter((mn,ke)=>ke!==Ut)}:ft))},`${Et}-${Ut}`))}),ge.reason&&a.jsx(je,{variant:"meta",tone:"muted",className:"mt-1 block italic",children:ge.reason})]})]})},ge.itemId)})}),a.jsxs(rc,{children:[a.jsx(ae,{icon:a.jsx(Gt,{}),onClick:()=>te(!1),children:"Cancel"}),a.jsxs(ae,{icon:a.jsx(Vn,{}),onClick:Ve,disabled:M.filter(ge=>ge.accepted).length===0,children:["Accept ",M.filter(ge=>ge.accepted).length," proposals"]})]})]})}),a.jsxs("div",{className:"grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden",children:[a.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:Ne?a.jsx(Cn,{fill:!0}):xe.length===0?a.jsx(un,{titleSlot:P?"No completed reviews yet":"No items to review",descriptionSlot:P?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here.",variant:"fill"}):a.jsx(qXt,{results:xe,isLoading:!1,featuredResultId:C,onResultClick:Fe,columns:SIs,selectedIds:P?void 0:N,onToggleSelect:P?void 0:Le,onToggleSelectAll:P?void 0:be})}),jt]})]})}function _Is(){const e=Xe();return wt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function CIs(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}const ZT=[Wr("/experiments")],EIs=["createdAt","status"];function TIs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,o]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState([]),d=zr(),[f,p]=so(),{sort:h,onSortChange:m}=fk({searchParams:f,setSearchParams:p,allowedKeys:EIs}),y=g.useMemo(()=>h?{field:h.key,direction:h.direction==="asc"?"ASC":"DESC"}:void 0,[h]),v=f.get("dataset")??"all",b=g.useCallback(le=>{p(J=>{const re=new URLSearchParams(J);return le==="all"?re.delete("dataset"):re.set("dataset",le),re},{replace:!0})},[p]),{targetType:x,targetId:w,setTargetType:k,setTargetId:_}=ZXt(),{data:C,isLoading:T,error:E}=W1(),{data:I,isLoading:N,error:A,isFetchingNextPage:P,hasNextPage:F,setEndOfListElement:D}=lIs(v==="all"?void 0:v,{targetType:x,targetId:w},y),{data:H}=_Is(),q=g.useMemo(()=>C?.datasets??[],[C?.datasets]),V=g.useMemo(()=>I??[],[I]),B=g.useMemo(()=>YNs(q),[q]),Z=g.useMemo(()=>CIs(H),[H]),z=T||N,Y=A||E,L=le=>{u(J=>J.includes(le)?J.filter(re=>re!==le):J.length>=2?[J[0],le]:[...J,le])},R=()=>{u([]),l(!1)},{selectedIds:M,selectedDatasetIds:U}=g.useMemo(()=>{const le=new Map(V.map(re=>[re.id,re.datasetId])),J=c.filter(re=>le.has(re));return{selectedIds:J,selectedDatasetIds:new Set(J.map(re=>le.get(re)))}},[V,c]),Q=M.length===2&&U.size!==1?"not the same dataset":void 0,te=()=>{if(M.length!==2||Q)return;const[le,J]=M,[re]=U;if(!re)return;const se=new URLSearchParams({dataset:re,baseline:le,contender:J});d(`/experiments/compare?${se.toString()}`)};if(Y&&_s(Y))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Qs,{variant:"fill"})]});if(A&&js(A))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Fs,{variant:"fill",resource:"experiments"})]});if(E&&js(E))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(Fs,{variant:"fill",resource:"datasets"})]});if(Y)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:Y.message})]});const K=a.jsx(ZX,{open:s,onOpenChange:o,onSuccess:le=>{d(`/experiments/${le}`)}});if(V.length===0&&!z&&v==="all"&&!x)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(KNs,{onRunExperiment:()=>o(!0)}),K]});const ee=n!=="all"||v!=="all"||e!==""||x!=="",ne=()=>{t(""),r("all"),p(le=>{const J=new URLSearchParams(le);return J.delete("dataset"),J.delete(b_),J.delete(vS),J},{replace:!0})};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:ZT}),actionRow:a.jsx(XNs,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:v,onDatasetFilterChange:b,datasetOptions:B,targetType:x,onTargetTypeChange:k,targetId:w,onTargetIdChange:_,onReset:ne,hasActiveFilters:ee,onRunClick:()=>o(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:M.length,onExecuteCompare:te,onCancelSelection:R,compareDisabledReason:Q}:void 0}),children:[a.jsx("h1",{className:"sr-only",children:"Experiments"}),a.jsx(GNs,{experiments:V,datasets:q,reviewByExperiment:Z,isLoading:z,search:e,statusFilter:n,datasetFilter:v,isFetchingNextPage:P,hasNextPage:F,setEndOfListElement:D,sort:h,onSortChange:m,selection:i?{selectedExperimentIds:M,onToggleSelection:L}:void 0}),K]})}const GT=[Wr("/experiments"),{id:"experiments-compare",label:"Compare"}];function iB({experimentId:e}){const{Link:t,paths:n}=dn();return a.jsx(ae,{render:a.jsx(t,{href:n.experimentLink(e)}),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function jIs(){const[e,t]=so(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",o=L4(n,r),i=L4(n,s),l=o.isLoading||i.isLoading,c=o.error??i.error;return c&&_s(c)?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx(Qs,{variant:"fill"})]}):c&&js(c)?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx(Fs,{variant:"fill",resource:"experiments"})]}):!n||!r||!s?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"py-5 text-center text-muted-foreground",children:[a.jsx("p",{children:"Select two experiments to compare."}),a.jsxs("p",{className:"mt-2 text-body",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})]}):l?null:c&&!zA(c)?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:c.message})]}):c||!o.data||!i.data?a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:[a.jsx("h1",{className:"sr-only",children:"Compare"}),a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"py-5 text-center text-muted-foreground",children:[a.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),a.jsxs("p",{className:"mt-2 flex items-center justify-center gap-2 text-body",children:["One of",a.jsx(iB,{experimentId:r}),"and",a.jsx(iB,{experimentId:s}),"was not found in it."]})]})})]}):a.jsx(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:GT}),children:a.jsx("div",{className:"grid h-full min-w-min content-start items-start overflow-x-auto overflow-y-auto",children:a.jsxs("div",{className:"grid w-full content-start",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[a.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[a.jsx(je,{as:"h1",variant:"heading",tone:"ink",children:"Experiments comparison"}),a.jsxs("p",{className:"flex items-center gap-2 text-caption text-muted-foreground",children:[a.jsx(iB,{experimentId:r}),"and",a.jsx(iB,{experimentId:s})]})]}),a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx(ae,{onClick:()=>t({dataset:n,baseline:s,contender:r}),icon:a.jsx(cSt,{}),children:"Swap sides"})}),a.jsx(kn,{children:"Switch baseline and contender"})]})]}),a.jsx(iIs,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}function uJt(e,t){const{data:n}=vv(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function NIs({withQueryTrace:e,withFeedback:t}){const{currentItemId:n,experimentId:r,datasetId:s,experimentStatus:o,results:i,isLoadingResults:l,hasNextPage:c,close:u,goToPreviousItem:d,goToNextItem:f}=VXt(),p=g.useMemo(()=>n?i.find(_=>_.itemId===n):void 0,[i,n]),{data:h}=A1(r,o),{updateExperimentResult:m}=cl(),y=g.useCallback(async _=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:_,status:"needs-review"}),Qe("Result flagged for review")}catch{Qe.error("Failed to flag result for review")}},[s,r,m]),v=uJt(s,i),b=g.useCallback(async(_,C)=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:_,tags:C})}catch{Qe.error("Failed to update tags")}},[s,r,m]),x=g.useCallback(async _=>{try{await m.mutateAsync({datasetId:s,experimentId:r,resultId:_,status:"complete"}),Qe("Result marked as reviewed")}catch{Qe.error("Failed to complete result")}},[s,r,m]),w=p?h?.[p.itemId]:void 0,k=lJt(w,p?.id);return a.jsx(cJt,{result:p,itemId:n,fallback:l||c?a.jsx(Rt.LoadingData,{}):a.jsxs(Rt.NoData,{children:['No loaded result for item "',n,'".']}),scores:w,state:k,withQueryTrace:e,withFeedback:t,onPrevious:d,onNext:f,onClose:u,onComplete:p?()=>x(p.id):void 0,onFlagForReview:p?()=>{y(p.id)}:void 0,onTagsChange:p?_=>{b(p.id,_)}:void 0,tagVocabulary:v,isUpdatingTags:m.isPending})}function IIs({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:o}=e;if(t.size===0)return null;const i=s||o;return a.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap",children:[a.jsxs(ae,{disabled:i,onClick:e.flagSelectedForReview,icon:a.jsx(O3,{}),children:["Flag ",t.size," to review"]}),a.jsx(aJt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:i}),a.jsx(ae,{icon:a.jsx(Gt,{}),variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}function dJt(e){const{data:t}=A1(e.id,e.status);return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}function uce({icon:e,typeLabel:t,subject:n,description:r,isLast:s=!1}){return a.jsxs("li",{className:"relative grid grid-cols-[auto_1fr] gap-x-2.5 pb-4 last:pb-0",children:[a.jsxs("div",{className:"flex flex-col items-center",children:[a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-3.5",role:"img","aria-label":t}),children:e}),a.jsx(kn,{children:t})]}),!s&&a.jsx("span",{"aria-hidden":!0,className:"mt-1 w-px flex-1 bg-border"})]}),a.jsxs("div",{className:"grid min-w-0 gap-0.5",children:[a.jsx("div",{className:"flex min-h-5 items-center text-caption text-foreground",children:n}),a.jsx("p",{className:"text-meta text-placeholder",children:r})]})]})}const dce="text-foreground inline-flex min-w-0 items-center gap-1.5 hover:underline";function AIs({experiment:e,className:t}){const{Link:n,paths:r}=dn(),s=KXt(),{scorers:o}=s,{data:i,isLoading:l}=vv(e.datasetId??""),c=dJt(e),u=e.targetType,d=e.targetId,f=eJt(e,s),p=(()=>{if(!d)return null;switch(u){case"agent":return r.agentLink(d);case"workflow":return r.workflowLink(d);case"scorer":return r.scorerLink(d);default:return null}})(),h=u&&XXt[u]||Pi,m=u&&JXt[u]||"Evaluation target";return a.jsxs("ol",{className:W("grid",t),children:[a.jsx(uce,{icon:a.jsx(DG,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?a.jsxs(n,{href:r.datasetLink(e.datasetId),className:dce,children:[a.jsx("span",{className:"truncate",children:l?a.jsx(at,{className:"h-4 w-28"}):i?.name??e.datasetId}),e.datasetVersion!=null&&a.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["(v",e.datasetVersion,")"]})]}):a.jsx("span",{className:"text-muted-foreground",children:"No dataset"})}),a.jsx(uce,{icon:a.jsx(h,{}),typeLabel:m,description:"Its output is then scored",subject:p?a.jsx(n,{href:p,className:dce,children:a.jsx("span",{className:"truncate",children:f})}):a.jsx("span",{className:"truncate text-muted-foreground",children:f})}),a.jsx(uce,{icon:a.jsx(hb,{}),typeLabel:"Scorers",description:"It gives a score by comparing ground truth",isLast:!0,subject:c.length===0?a.jsx("span",{className:"text-muted-foreground",children:"No scorer has produced a score yet"}):a.jsx("ul",{className:"grid min-w-0 gap-0.5",children:c.map(y=>{const v=o?.[y]?.scorer?.config?.name??y;return a.jsx("li",{className:"min-w-0",children:a.jsx(n,{href:r.scorerLink(y),className:dce,children:a.jsx("span",{className:"truncate",children:v})})},y)})})})]})}function QT({label:e,children:t}){return a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:e}),a.jsx(Ft.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function RIs({experiment:e,metrics:t}){const{data:n}=A1(e.id,e.status),r=e.status==="running"||e.status==="pending",s=g.useMemo(()=>{if(!n)return;const c=Object.values(n).flat();if(c.length!==0)return c.reduce((u,d)=>u+d.score,0)/c.length},[n]),o=e.startedAt??e.createdAt,i=o?new Date(o):null,l=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const c=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Zd(c)??"—"})();return a.jsxs(Ft,{children:[a.jsx(QT,{label:"Avg score",children:s===void 0?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsxs(a.Fragment,{children:[a.jsx("span",{children:s.toFixed(3)}),r&&a.jsx("span",{className:"text-muted-foreground",children:"· so far"})]})}),a.jsx(QT,{label:"Items",children:r?a.jsxs("span",{className:"text-muted-foreground",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&a.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),a.jsx(QT,{label:"Started",children:i?a.jsx("span",{title:LTe(i),children:Fr(i,"date-time")}):a.jsx("span",{children:"—"})}),a.jsx(QT,{label:"Duration",children:a.jsx("span",{children:l})}),t?.isEnabled&&a.jsxs(a.Fragment,{children:[a.jsx(QT,{label:"Tokens",children:t.data?.totalTokens==null?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsxs(a.Fragment,{children:[a.jsx("span",{children:$l(t.data.totalTokens)}),t.data.estimatedCost!=null&&a.jsxs("span",{className:"text-muted-foreground",children:["· ",bm(t.data.estimatedCost,t.data.costUnit)]}),r&&a.jsx("span",{className:"text-muted-foreground",children:"· so far"})]})}),a.jsx(QT,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?a.jsx("span",{className:"text-muted-foreground",children:"—"}):a.jsx(je,{as:"span",variant:"body-sm",font:"mono",children:Zd(Math.round(t.data.avgAgentDurationMs))})})]})]})}function PIs({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=dn(),{data:s}=lh(),o=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(o.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),a.jsxs("div",{className:"flex items-center gap-2 text-caption text-muted-foreground",children:[a.jsx(mv,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx("span",{className:"text-muted-foreground",children:c}),a.jsx("span",{className:"truncate",children:u})]})}return a.jsx("div",{className:"flex flex-col gap-2",children:o.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return a.jsxs(xf,{className:"min-w-0 p-3",children:[a.jsxs(n,{href:r.scorerLink(i),className:"flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground hover:underline [&>svg]:size-3 [&>svg]:shrink-0 [&>svg]:text-muted-foreground",children:[a.jsxs(On,{children:[a.jsx(Sn,{render:a.jsx(hb,{role:"img","aria-label":"Scorer"})}),a.jsx(kn,{children:"Scorer"})]}),a.jsx("span",{className:"truncate",children:c})]}),a.jsxs("strong",{className:"text-subheading text-muted-foreground",children:[l.toFixed(3),a.jsx("span",{className:"ml-1.5 text-caption text-muted-foreground",children:"avg score"})]})]},i)})})}function fce({title:e,children:t}){return a.jsxs("section",{className:"grid gap-3",children:[a.jsx("h2",{className:"text-body tracking-widest text-placeholder uppercase",children:e}),t]})}function $Is({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=dn(),{data:o}=A1(e.id,e.status),i=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${s.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return a.jsxs(ku,{as:"aside","aria-label":"Experiment details",className:W("grid content-start gap-5 p-5",n),children:[a.jsxs(fce,{title:"Pipeline",children:[a.jsx(AIs,{experiment:e}),e.agentVersion&&a.jsxs(Ft,{children:[a.jsx(Ft.Key,{children:"Version"}),i?a.jsx(Ft.ValueLink,{href:i,as:r,children:e.agentVersion}):a.jsx(Ft.Value,{children:e.agentVersion})]})]}),a.jsx(fce,{title:"Run",children:a.jsx(RIs,{experiment:e,metrics:t})}),a.jsx(fce,{title:"Scorers",children:a.jsx(PIs,{scoresByItemId:o,experimentStatus:e.status})})]})}function MIs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[o,i]=g.useState(e.description??""),{updateExperiment:l}=cl(),c=!!r.trim()&&!l.isPending,u=async d=>{if(d.preventDefault(),!(!c||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:o.trim()}),Qe.success("Experiment renamed"),n(!1)}catch(f){Qe.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return a.jsx(hs,{open:t,onOpenChange:n,children:a.jsxs(rs,{className:"max-w-md",children:[a.jsx(ss,{children:a.jsx(Jr,{children:"Rename Experiment"})}),a.jsx(ys,{children:a.jsxs("form",{onSubmit:u,className:"space-y-4",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mn,{htmlFor:"rename-experiment-name",children:"Name *"}),a.jsx(gr,{id:"rename-experiment-name",value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx(Mn,{htmlFor:"rename-experiment-description",children:"Description"}),a.jsx(gr,{id:"rename-experiment-description",value:o,onChange:d=>i(d.target.value),placeholder:"Enter experiment description (optional)"})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),a.jsx(ae,{icon:a.jsx(Vn,{}),type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}const DIs=["agent","workflow","scorer"];function LIs({experiment:e}){const[t,n]=g.useState(!1),r=zr(),{paths:s}=dn(),o=dJt(e),i=DIs.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:a.jsxs(a.Fragment,{children:[a.jsx(ae,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",icon:a.jsx(bu,{}),children:"Rerun"}),t&&a.jsx(ZX,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:i,initialTargetId:e.targetId,initialScorerIds:o,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},o.join(","))]})}function FIs({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=dn(),[s,o]=g.useState(!1),i=!!e.datasetId,l=i||!!t;return a.jsxs(a.Fragment,{children:[a.jsxs(Gn,{children:[a.jsxs(Gn.Start,{className:"whitespace-nowrap",children:[a.jsx(LIs,{experiment:e}),a.jsx(ae,{render:a.jsx(r,{href:NBr(e.id)}),icon:a.jsx(O3,{}),children:"Review queue"}),l&&a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{size:"lg","aria-label":"Experiment actions menu",children:a.jsx(U1,{})})}),a.jsxs(pt.Content,{align:"start",className:"w-48",children:[i&&a.jsxs(pt.Item,{onSelect:()=>o(!0),children:[a.jsx(Bd,{})," Rename Experiment"]}),t&&a.jsxs(pt.Item,{onSelect:t,className:"text-red-500 focus:text-red-400",children:[a.jsx(Ni,{})," Delete Experiment"]})]})]})]}),n&&a.jsx(Gn.End,{children:n})]}),s&&a.jsx(MIs,{experiment:e,open:!0,onOpenChange:o})]})}const fJt=()=>{const{experimentId:e}=fr(),{data:t}=a2e();return{experimentId:e,experiment:t?.experiments?.find(n=>n.id===e)}};function zIs(){const{experimentId:e,experiment:t}=fJt();if(!e)return null;const n=e.length>8?`${e.slice(0,8)}...`:e;return t?.name||n}function BIs(){const{experiment:e}=fJt();return e?a.jsx(Wjs,{status:e.status}):null}const UIs=({experimentId:e,experimentStatus:t})=>{const n=Xe(),{supportsMetrics:r}=F6(),s=!!e&&r,i=wt({queryKey:["experiment-metrics",e],enabled:s,refetchInterval:t==="running"||t==="pending"?2e3:!1,queryFn:async()=>{if(!e)throw new Error("experimentId is required");const l={experimentId:e},[c,u,d]=await Promise.all([n.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"avg",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:l})]);return{totalTokens:c.value??null,estimatedCost:c.estimatedCost??null,costUnit:c.costUnit??null,avgAgentDurationMs:u.value??null,agentRuns:d.value??null}}});return{data:i.data,isLoading:i.isLoading,isEnabled:s}};function VIs({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=cl();return{addTag:g.useCallback(async(i,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(i));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],i]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Qe(`Tag "${i}" added to ${u} result${u>1?"s":""}`):Qe.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function qIs({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[o,i]=g.useState(!1),{updateExperimentResult:l}=cl(),{addTag:c,isPending:u}=VIs({datasetId:e,experimentId:t}),d=uJt(e,n),f=g.useMemo(()=>n.filter(v=>r.has(v.id)),[n,r]),p=g.useCallback(v=>{s(b=>{const x=new Set(b);return x.has(v)?x.delete(v):x.add(v),x})},[]),h=g.useCallback(()=>s(new Set),[]),m=g.useCallback(async()=>{if(o||r.size===0)return;i(!0);const v=new Set;try{for(const b of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:b,status:"needs-review"}),v.add(b)}catch{}}finally{i(!1)}v.size>0&&(s(b=>{const x=new Set(b);for(const w of v)x.delete(w);return x}),Qe(`${v.size} result${v.size>1?"s":""} flagged for review`))},[e,t,o,r,l]),y=g.useCallback(v=>c(v,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:p,clearSelection:h,flagSelectedForReview:m,isFlagging:o,addTagToSelected:y,isTagging:u,tagVocabulary:d}}const HIs=[],WIs=["startedAt"];function aB({crumbs:e,children:t}){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:e}),children:[a.jsx("h1",{className:"sr-only",children:"Experiment"}),a.jsx("div",{}),a.jsx("div",{className:"flex h-full items-center justify-center",children:t})]})}function ZIs(){const{experimentId:e,itemId:t}=fr(),n=[Wr("/experiments"),{id:"experiment",Component:zIs,icon:BIs,to:e?`/experiments/${encodeURIComponent(e)}`:void 0},...t?[{id:"experiment-items",label:"Items"},{id:"experiment-item",label:FCe(t)}]:[]],r=zr(),[s,o]=g.useState(!1),i=FX(),[l,c]=so(),{sort:u,onSortChange:d}=fk({searchParams:l,setSearchParams:c,allowedKeys:WIs}),f=g.useMemo(()=>u?{field:u.key,direction:u.direction==="asc"?"ASC":"DESC"}:void 0,[u]),{data:p,isLoading:h}=a2e(),y=p?.experiments?.find(A=>A.id===e)?.datasetId??"",{data:v,isLoading:b,error:x}=L4(y,e??""),{data:w,isLoading:k,setEndOfListElement:_,isFetchingNextPage:C,hasNextPage:T}=YSe({datasetId:y,experimentId:e??"",experimentStatus:v?.status,orderBy:f}),E=UIs({experimentId:e,experimentStatus:v?.status}),I=qIs({datasetId:y,experimentId:e??"",results:w??HIs});if(!e||h||b)return null;if(x&&_s(x))return a.jsx(aB,{crumbs:n,children:a.jsx(Qs,{})});if(x&&js(x))return a.jsx(aB,{crumbs:n,children:a.jsx(Fs,{resource:"datasets"})});const N=a.jsx(aB,{crumbs:n,children:a.jsx(un,{titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:a.jsx(ae,{render:a.jsx(ml,{to:"/experiments"}),icon:a.jsx(Cu,{}),children:"Back to Experiments"})})});return x&&zA(x)?N:x?a.jsx(aB,{crumbs:n,children:a.jsx(un,{tone:"error",titleSlot:"Failed to load experiment",descriptionSlot:x instanceof Error?x.message:"An unexpected error occurred. Please try again."})}):!y||!v?N:a.jsx(Fjs,{experimentId:e,datasetId:y,experimentStatus:v.status,results:w??[],isLoadingResults:k,hasNextPage:T,children:a.jsxs("div",{className:"h-full",children:[a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:n}),actionRow:a.jsx(FIs,{experiment:v,onDeleteClick:()=>o(!0),children:a.jsx(IIs,{selection:I})}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsxs("div",{className:"grid grid-cols-[1fr_auto] gap-4 overflow-visible",children:[a.jsx(Hjs,{experimentId:e,experimentStatus:v.status,results:w??[],isLoading:k,setEndOfListElement:_,isFetchingNextPage:C,hasNextPage:T,selectedIds:I.selectedIds,onToggleSelect:I.toggleSelect,sort:u,onSortChange:d}),a.jsx($Is,{experiment:v,metrics:E,className:"w-80 overflow-y-auto"})]})]}),a.jsx(NIs,{withQueryTrace:i.enabled,withFeedback:i.enabled}),a.jsx(QXt,{open:s,onOpenChange:o,experimentId:e,experimentName:v.name??void 0,onSuccess:()=>r("/experiments")})]})})}const GX="targetType",QX="targetId",YX="experiment",KX="status",XX="tag",iit={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},GIs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}],ait={[GX]:{icon:fSt,hue:265},[QX]:{icon:xSt,hue:315},[YX]:{icon:lG,hue:160},[KX]:{icon:k3,hue:0},[XX]:{icon:V1,hue:340}},sM=(e,t)=>({id:e,label:t,icon:ait[e].icon,color:sAe(ait[e].hue),strict:!0}),QIs=[{id:"is",label:"is"}],oM=(e,t)=>({id:e,fieldId:e,operatorId:"is",value:t}),YIs=({targetType:e,targetId:t,experimentId:n,status:r,tag:s})=>{const o=[];return e&&o.push(oM(GX,e)),t&&o.push(oM(QX,t)),n&&o.push(oM(YX,n)),r!=="review"&&o.push(oM(KX,r)),s&&o.push(oM(XX,s)),o},KIs=e=>{const t=s=>{const o=e.find(i=>i.fieldId===s);return typeof o?.value=="string"?o.value:""},n=t(GX),r=HX(n)?n:"";return{targetType:r,targetId:r?t(QX):"",experimentId:t(YX),status:t(KX)==="completed"?"completed":"review",tag:t(XX)||null}};function XIs({targetType:e,targetId:t,experimentId:n,status:r,tag:s,experiments:o,tagOptions:i,onChange:l}){const{data:c}=ef({enabled:e==="agent"}),{data:u}=ih({enabled:e==="workflow"}),{data:d}=lh({enabled:e==="scorer"}),{data:f}=nE({enabled:e==="processor"}),p=g.useMemo(()=>{const m=e==="agent"?Object.entries(c??{}).map(([y,v])=>({value:y,label:v.name??y})):e==="workflow"?Object.entries(u??{}).map(([y,v])=>({value:y,label:v.name??y})):e==="scorer"?Object.entries(d??{}).map(([y,v])=>({value:y,label:v.scorer?.config?.name??y})):e==="processor"?Object.entries(f??{}).map(([y,v])=>({value:y,label:v.name??y})):[];return[{...sM(GX,"Target type"),suggestions:c2e.map(y=>({value:y,label:iit[y]}))},{...sM(QX,e?iit[e]:"Target"),hidden:!e,suggestions:m},{...sM(YX,"Experiment"),suggestions:o.map(y=>({value:y.id,label:YXt(y)}))},{...sM(KX,"Status"),suggestions:GIs},{...sM(XX,"Tag"),hidden:i.length===0,suggestions:i}]},[e,c,u,d,f,o,i]),h=g.useMemo(()=>YIs({targetType:e,targetId:t,experimentId:n,status:r,tag:s}),[e,t,n,r,s]);return a.jsxs(Wg,{fields:p,operators:QIs,value:h,onValueChange:m=>l(KIs(m)),createItemId:m=>m,"aria-label":"Review queue filters",className:"min-w-64 flex-1",children:[a.jsx(Wg.Chips,{}),a.jsx(Wg.Input,{placeholder:"Filter review queue…"})]})}const lB=[Wr("/experiments"),Wr("/experiments/review-queue")],pce="experiment",lit="review";function JIs(){const[e,t]=so(),n=e.get(b_),r=HX(n)?n:"",s=r?e.get(vS)??"":"",o=e.get(pce),i=e.get(lit),{Link:l,paths:c}=dn(),u=FX(),{data:d,error:f}=oJt(void 0,{targetType:r,targetId:s}),p=d?.experiments.find(m=>m.id===o),h=(m,y)=>{m.status!==y.status&&y.onStatusChange(m.status),m.tag!==y.tag&&y.onTagChange(m.tag),t(v=>{const b=new URLSearchParams(v),x=m.targetType!==r,k=x||m.targetId!==s?"":m.experimentId,_=x?"":m.targetId;return m.targetType?b.set(b_,m.targetType):b.delete(b_),_?b.set(vS,_):b.delete(vS),k?b.set(pce,k):b.delete(pce),b.delete(lit),b},{replace:!0})};return f&&_s(f)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lB}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Qs,{variant:"fill"})]}):f&&js(f)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lB}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(Fs,{variant:"fill",resource:"experiments"})]}):f?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lB}),children:[a.jsx("h1",{className:"sr-only",children:"Review Queue"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load experiments",descriptionSlot:f.message})]}):a.jsx(OIs,{withQueryTrace:u.enabled,withFeedback:u.enabled,breadcrumbs:a.jsx(kt,{crumbs:lB}),datasetId:p?.datasetId??void 0,experimentId:o??void 0,targetType:r,targetId:s,featuredItemId:i,renderFilters:m=>a.jsx(XIs,{targetType:r,targetId:s,experimentId:o??"",status:m.status,tag:m.tag,experiments:d?.experiments??[],tagOptions:m.tagOptions,onChange:y=>h(y,m)}),toolbarEnd:o?a.jsx(ae,{render:a.jsx(l,{href:c.experimentLink(o)}),icon:a.jsx(t_e,{}),children:"See experiment"}):void 0})}function eAs({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[a.jsxs("div",{children:[a.jsx(je,{as:"div",variant:"caption",font:"mono",children:e.connectionId}),a.jsxs("div",{className:"text-caption text-muted-foreground",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),a.jsx("button",{type:"button",className:"text-destructive underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function pJt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsx("ul",{className:"space-y-1",children:e.map(s=>a.jsx(eAs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function tAs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return a.jsx("div",{className:"space-y-4",children:e.map(([s,o])=>a.jsxs("div",{children:[a.jsx("h3",{className:"text-subheading text-foreground","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),a.jsx(pJt,{connections:o,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function nAs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:o,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return a.jsxs("div",{className:"space-y-2 rounded border p-4",children:[a.jsx("h2",{className:"text-heading",children:"Existing connections"}),!e||!t?a.jsx("p",{className:"text-muted-foreground",children:"Pick a provider and toolkit to list connections."}):o?a.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):i?a.jsx("p",{className:"text-destructive",children:String(i)}):n.length===0?a.jsx("p",{className:"text-muted-foreground",children:"No connections."}):r?a.jsx(tAs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):a.jsx(pJt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?a.jsx("p",{className:"text-destructive",children:String(c)}):null]})}function rAs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:o,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:y}){return a.jsxs("div",{className:"space-y-4 rounded border p-4",children:[a.jsx(wu,{name:"provider",label:"Provider",value:n,onValueChange:p,disabled:o,placeholder:o?"Loading providers…":"Select provider",options:e.map(v=>({value:v.id,label:`${v.displayName??v.name} (${v.id})`})),errorMsg:i?String(i):void 0}),a.jsx(wu,{name:"toolkit",label:"Toolkit",value:r,onValueChange:h,disabled:!n||l,placeholder:l?"Loading toolkits…":"Select toolkit",options:t.map(v=>({value:v.slug,label:`${v.name} (${v.slug})`})),errorMsg:c?String(c):void 0}),a.jsx(qi,{name:"connection-label",label:"Label (optional)",placeholder:"My personal Gmail",value:s,onChange:v=>m(v.target.value),disabled:!n||!r}),a.jsx(ae,{type:"button",variant:"primary",onClick:y,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?a.jsx("div",{role:"alert",children:a.jsx(Jt,{variant:"destructive",children:String(d)})}):null,f?a.jsxs(Jt,{variant:"success",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]}):null]})}const cit=e=>e.authorId?.trim()||"shared",sAs=(e,t)=>{if(!t||new Set(e.map(cit)).size<=1)return null;const r=new Map;for(const o of e){const i=cit(o);r.set(i,[...r.get(i)??[],o])}const s=Array.from(r.entries());return s.sort(([o],[i])=>o==="shared"?1:i==="shared"?-1:o.localeCompare(i)),s},oAs=["*","tool-providers:*","tool-providers:admin"];function iAs(){const{data:e}=Ym();return e?.permissions?.some(t=>oAs.includes(t))??!1}const aAs=[{id:"integrations",label:"Integrations"}];function lAs(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,o]=g.useState(""),i=OR(),l=dK(e||null),c=l8t(e||null,n||null),u=a8t(),d=o8t(),f=iAs(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),y=g.useMemo(()=>sAs(m,f),[m,f]),v=w=>{t(w),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{o(""),c.refetch()}})},x=w=>{d.mutate({providerId:e,connectionId:w})};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aAs}),children:[a.jsx("h1",{className:"sr-only",children:"Integrations"}),a.jsxs("div",{className:"max-w-3xl space-y-6 text-body",children:[a.jsx("p",{className:"text-muted-foreground",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),a.jsx(rAs,{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:v,onToolkitChange:r,onLabelChange:o,onConnect:b}),a.jsx(nAs,{providerId:e,toolkit:n,connections:m,groupedByAuthor:y,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})]})}function cAs({title:e,description:t,errorBanner:n,children:r}){return a.jsxs("div",{"data-testid":"login-page",className:"w-full max-w-sm space-y-6 p-6",children:[a.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[a.jsx(zy,{className:"h-10 w-10"}),a.jsx("h1",{className:"text-heading text-foreground",children:e})]}),t,n,r]})}function hJt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:o}=Ul(),{mutate:i,isPending:l,error:c}=jUr(),{mutate:u,isPending:d,error:f}=IUr(),{mutate:p,isPending:h}=NFt(),[m,y]=g.useState(n),[v,b]=g.useState(""),[x,w]=g.useState(""),[k,_]=g.useState("");if(o)return a.jsx("div",{className:"text-muted-foreground",children:"Loading..."});if(!s?.enabled||!s?.login)return a.jsx("div",{className:"text-muted-foreground",children:"Authentication is not configured"});const{login:C}=s,T=C.type==="sso"||C.type==="both",E=C.type==="credentials"||C.type==="both",I=C.sso,N=C.signUpEnabled!==!1,A=m==="signin"||!N,P=A?l:d,F=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=gK("/")},H=z=>{z.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:v||void 0},{onSuccess:D})},q=()=>{p({redirectUri:e},{onSuccess:z=>{window.location.href=z.url}})},V=()=>{y(A?"signup":"signin")},B=C.description?a.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border bg-sidebar p-3",children:[a.jsx(ed,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx("p",{className:"text-body text-muted-foreground",children:C.description})]}):null,Z=r?a.jsx("div",{role:"alert",children:a.jsx(Jt,{variant:"destructive",children:r})}):null;return a.jsxs(cAs,{title:A?"Sign in to Mastra Studio":"Create your account",description:B,errorBanner:Z,children:[E&&a.jsxs("form",{onSubmit:H,className:"space-y-4",children:[!A&&a.jsx(qi,{name:"name",label:"Name",type:"text",value:v,onChange:z=>b(z.target.value),placeholder:"Your name",variant:"default",size:"lg"}),a.jsx(qi,{name:"email",label:"Email",type:"email",value:x,onChange:z=>w(z.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"}),a.jsx(qi,{name:"password",label:"Password",type:"password",value:k,onChange:z=>_(z.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"}),F?a.jsx("div",{role:"alert",children:a.jsx(Jt,{variant:"destructive",children:F.message})}):null,a.jsx(ae,{icon:a.jsx(d_e,{}),type:"submit",disabled:P,className:"w-full",size:"lg",children:P?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),N&&a.jsxs("div",{className:"text-center text-body",children:[a.jsx("span",{className:"text-muted-foreground",children:A?"Don't have an account? ":"Already have an account? "}),a.jsx("button",{type:"button",onClick:V,className:"text-foreground hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"absolute inset-0 flex items-center",children:a.jsx("div",{className:"w-full border-t border-border"})}),a.jsx("div",{className:"relative flex justify-center text-body",children:a.jsx("span",{className:"bg-sidebar px-2 text-muted-foreground",children:"or continue with"})})]}),T&&I&&a.jsxs(ae,{onClick:q,disabled:h,className:"w-full",size:"lg",children:[I.icon&&a.jsx("span",{className:"mr-2",children:I.icon}),h?"Redirecting...":I.text||"Sign in"]})]})}function uAs(){const[e]=so(),t=zr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",o=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(hJt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:o})}function mJt({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const o=!!(n||r||s);return!t&&!o?null:a.jsxs("div",{className:"flex items-center gap-2",children:[t&&a.jsx(ae,{disabled:e,size:"md",onClick:t,icon:a.jsx(Gt,{}),children:"Clear"}),o&&a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{disabled:e,size:"md","aria-label":"More filter actions",children:a.jsx(U1,{})})}),a.jsxs(pt.Content,{align:"end",children:[n&&a.jsxs(pt.Item,{onSelect:()=>n(),children:[a.jsx(Gt,{}),"Remove all filters"]}),n&&(r||s)&&a.jsx(pt.Separator,{}),r&&a.jsxs(pt.Item,{onSelect:()=>r(),children:[a.jsx(Df,{}),"Save filters for next time"]}),s&&a.jsxs(pt.Item,{onSelect:()=>s(),children:[a.jsx(Ni,{}),"Remove saved filters"]})]})]})]})}const dAs=W(H1,"min-w-0 focus:text-foreground");function hce({role:e,checked:t,label:n,onClick:r}){return a.jsxs("button",{ref:oh(),type:"button",role:e,"aria-checked":t,"data-selected":t||void 0,"data-pick-multi-item":"",title:n,className:dAs,onClick:r,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:n}),t&&a.jsx("span",{className:P3,children:a.jsx(Vn,{})})]})}function gJt({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),o=I0(),i={className:W("max-h-[80dvh] overflow-auto p-1",o.containerClassName),...o.getContainerProps({})},l=g.useMemo(()=>{const f=r.trim().toLowerCase();return f?e.options.filter(p=>p.label.toLowerCase().includes(f)):e.options},[e.options,r]),c=g.useMemo(()=>t.find(f=>f.fieldId===e.id),[t,e.id]),u=typeof c?.value=="string"?c.value:e.multi?void 0:e.defaultValue,d=g.useMemo(()=>{const f=c?.value;return Array.isArray(f)?f:typeof f=="string"?[f]:[]},[c]);return a.jsxs(a.Fragment,{children:[e.searchable!==!1&&a.jsxs("div",{className:Xj.container,children:[a.jsx(Ro,{className:Xj.icon}),a.jsx("input",{type:"text",value:r,onChange:f=>s(f.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:Xj.input,onKeyDown:f=>{if(f.key!=="ArrowDown")return;const h=f.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");h&&(f.preventDefault(),f.stopPropagation(),h.focus())}})]}),e.isLoading?a.jsxs("div",{className:W(hV,"m-1"),children:[a.jsx(Cn,{size:"sm",className:"size-3 text-muted-foreground"}),"Loading options…"]}):l.length===0?a.jsx("div",{className:W(hV,"m-1"),children:e.emptyText??"No option found."}):e.multi?a.jsx("div",{...i,children:a.jsx(Xy,{menu:o,children:l.map(f=>{const p=d.includes(f.value);return a.jsx(hce,{role:"checkbox",checked:p,label:f.label,onClick:()=>n(e.id,p?d.filter(h=>h!==f.value):[...d,f.value])},f.value)})})}):a.jsx("div",{role:"radiogroup",...i,children:a.jsxs(Xy,{menu:o,children:[l.map(f=>a.jsx(hce,{role:"radio",checked:u===f.value,label:f.label,onClick:()=>n(e.id,f.value)},f.value)),!e.omitAnyOption&&a.jsx(hce,{role:"radio",checked:u==="Any",label:"Any",onClick:()=>n(e.id,"Any")})]})})]})}function f2e(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const fAs="This filter is set by the current context and cannot be removed here.";function pAs(e,t){return e.kind==="pick-multi"&&e.options?Array.isArray(t)?t.length===0?"Any":t.map(n=>e.options.find(r=>r.value===n)?.label??n).join(", "):e.options.find(n=>n.value===t)?.label??t:f2e(t)}function hAs({field:e,value:t,tooltipContent:n}){const r=pAs(e,t),s=`${e.label} filter is locked by context`;return a.jsx(Bl,{delayDuration:150,children:a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsxs(zl,{"data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[a.jsx(Fp,{children:e.label}),a.jsx(Fp,{children:"is"}),a.jsx(Fp,{children:r}),a.jsx(Fp,{children:a.jsx(ed,{})})]})}),a.jsx(kn,{children:n})]})})}function mAs({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:o}){const[i,l]=g.useState(t),c=g.useRef(null);return g.useEffect(()=>{i.trim()!==t&&l(t)},[t]),g.useEffect(()=>{o&&c.current?.focus()},[o]),a.jsxs(zl,{children:[a.jsx(Fp,{children:e.label}),a.jsx(Fp,{children:"is"}),a.jsx(gr,{ref:c,disabled:s,value:i,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=i.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.currentTarget.blur())}}),a.jsx(ae,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,onMouseDown:u=>u.preventDefault(),onClick:r,children:a.jsx(Gt,{})})]})}function gAs({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:o}){const[i,l]=g.useState(!1);return a.jsxs(zl,{children:[a.jsx(Fp,{children:e.label}),a.jsx(Fp,{children:"is"}),a.jsxs(ah,{open:i,onOpenChange:l,children:[a.jsx(Vd,{asChild:!0,children:a.jsx(ae,{type:"button",disabled:o,children:f2e(t.value)})}),a.jsx(Zf,{align:"start",sideOffset:eE,className:"w-64 p-0","data-pick-multi-panel":!0,children:a.jsx(gJt,{field:e,tokens:n,onChange:r})})]}),a.jsx(ae,{type:"button",disabled:o,"aria-label":`Remove ${e.label} filter`,onClick:s,children:a.jsx(Gt,{})})]})}function vJt({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:o,lockedTooltipContent:i=fAs}){if(t.length===0)return null;const l=new Set(o??[]),c=(d,f)=>{const p=[...t];p[d]=f,n(p)},u=d=>{n(t.filter((f,p)=>p!==d))};return a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const p=e.find(h=>h.id===d.fieldId);return p?l.has(d.fieldId)?a.jsx(hAs,{field:p,value:d.value,tooltipContent:i},`${d.fieldId}-${f}`):p.kind==="text"&&!Array.isArray(d.value)?a.jsx(mAs,{field:p,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:h=>c(f,{fieldId:d.fieldId,value:h}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):p.kind==="pick-multi"?a.jsx(gAs,{field:p,token:d,tokens:t,disabled:r,onChange:(h,m)=>c(f,{fieldId:h,value:m}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):a.jsxs(zl,{children:[a.jsx(Fp,{children:p.label}),a.jsx(Fp,{children:"is"}),a.jsx(Fp,{children:f2e(d.value)}),a.jsx(ae,{type:"button",disabled:r,"aria-label":`Remove ${p.label} filter`,onClick:()=>u(f),children:a.jsx(Gt,{})})]},`${d.fieldId}-${f}`):null})})}const yJt=W(H1,"focus:text-foreground"),p2e=g.forwardRef((e,t)=>a.jsx("button",{type:"button",role:"menuitem","data-filter-item":"",ref:oh(t),...e}));p2e.displayName="FilterMenuButton";function bJt({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:o,onStartTextFilter:i,hiddenFieldIds:l}){const c=g.useMemo(()=>{if(!l||l.length===0)return e;const P=new Set(l);return e.filter(F=>!P.has(F.id))},[e,l]),[u,d]=g.useState(!1),f=I0(),[p,h]=g.useState(),[m,y]=g.useState([]),[v,b]=g.useState(),[x,w]=g.useState(),k=g.useRef(!1),_=g.useCallback(P=>{w(F=>F===P?void 0:P)},[]),C=g.useCallback(()=>w(void 0),[]);g.useEffect(()=>{u||w(void 0)},[u]);const T=g.useMemo(()=>c.find(P=>P.id===p),[c,p]),E=g.useMemo(()=>{const P=new Set;for(const F of t){const D=e.find(H=>H.id===F.fieldId);D&&D.kind!=="pick-multi"&&P.add(F.fieldId)}return P},[t,e]),I=g.useCallback(()=>{h(void 0),y([]),b(void 0)},[]);g.useEffect(()=>{u||I()},[u,I]);const N=g.useCallback((P,F)=>{const D=t.findIndex(q=>q.fieldId===P);if(Array.isArray(F)&&F.length===0){if(D===-1)return;n(t.filter((q,V)=>V!==D));return}if(D===-1){n([...t,{fieldId:P,value:F}]);return}const H=[...t];H[D]={fieldId:P,value:F},n(H)},[n,t]),A=g.useCallback(()=>{if(!T){b("Choose a property first.");return}if(E.has(T.id)){b(`Remove the existing ${T.label} filter before adding another.`);return}if(m.length===0){b(`Choose at least one ${T.label.toLowerCase()} value.`);return}n([...t,{fieldId:T.id,value:m}]),d(!1)},[m,n,T,E,t]);return a.jsxs(ah,{open:u,onOpenChange:d,children:[a.jsx(Vd,{asChild:!0,children:a.jsx(ae,{size:o,disabled:s,icon:a.jsx(B8e,{}),children:r})}),a.jsx(Zf,{align:"end",sideOffset:eE,className:W("w-64",T?"p-3":"p-1"),initialFocus:!1,finalFocus:()=>k.current?(k.current=!1,!1):!0,children:a.jsxs("div",{className:W("grid",T&&"gap-3"),children:[T&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button","aria-label":"Back to properties",className:W(Pn,vn),onClick:I,children:a.jsx(Cu,{className:"size-4"})}),a.jsx(bMn,{className:"size-4 shrink-0 text-muted-foreground"}),a.jsx("span",{className:"text-caption text-muted-foreground",children:`${T.label} · is`})]}),!T&&a.jsx("div",{role:"menu",className:W("max-h-[80dvh] overflow-auto",f.containerClassName),...f.getContainerProps({}),onKeyDown:P=>{if(P.key!=="ArrowDown"&&P.key!=="ArrowUp"&&P.key!=="Home"&&P.key!=="End")return;const F=Array.from(P.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(F.length===0)return;P.preventDefault();const D=document.activeElement,H=F.findIndex(V=>V===D);let q;P.key==="Home"?q=0:P.key==="End"?q=F.length-1:P.key==="ArrowDown"?q=H<0?0:(H+1)%F.length:q=H<=0?F.length-1:H-1,F[q]?.focus()},children:a.jsx(Xy,{menu:f,children:c.length>0?c.map(P=>{const F=E.has(P.id);return P.kind==="pick-multi"?a.jsx(vAs,{field:P,tokens:t,onChange:N,open:x===P.id,onToggle:_,onClose:C},P.id):a.jsxs(p2e,{className:W(yJt,"group"),disabled:F,onClick:()=>{if(b(void 0),P.kind==="text"){n([...t,{fieldId:P.id,value:""}]),i?.(P.id),k.current=!0,d(!1);return}h(P.id)},children:[a.jsx("span",{className:"truncate",children:P.label}),F?a.jsx("span",{className:"ml-auto text-muted-foreground",children:"In use"}):a.jsx("span",{className:W(kG,"text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"),children:a.jsx(Yr,{})})]},P.id)}):a.jsx("div",{className:hV,children:"No matching property."})})}),T&&a.jsx(za,{multiple:!0,options:T.options??[],value:m,onValueChange:P=>{y(P),b(void 0)},placeholder:T.placeholder??`Choose ${T.label}`,searchPlaceholder:`Search ${T.label.toLowerCase()}...`,emptyText:T.emptyText??"No option found.",size:"md",name:`property-filter-${T.id}`,"aria-label":T.label,error:v}),T&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsx(ae,{icon:a.jsx(Gt,{}),variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),a.jsx(ae,{icon:a.jsx(B8e,{}),size:"md",onClick:A,children:"Add filter"})]})]})})]})}function vAs({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:o}){const i=g.useRef(null);return a.jsxs(ah,{open:r,onOpenChange:l=>{l?s(e.id):o()},children:[a.jsx(Vd,{asChild:!0,children:a.jsxs(p2e,{className:yJt,onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{i.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&a.jsx(wr,{className:"text-muted-foreground"}),a.jsx("span",{className:"truncate",children:e.label}),!r&&a.jsx("span",{className:W(kG,"text-muted-foreground"),children:a.jsx(wr,{})})]})}),a.jsx(Zf,{ref:i,side:"right",align:"start",sideOffset:eE,className:"w-64 p-0",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(p=>p===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:a.jsx(gJt,{field:e,tokens:t,onChange:n})})]})}function yAs({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:o,depth:i}){const l=e?aC(e.timestamp)??"":"";return a.jsx(Rt,{open:!!e,onClose:t,title:e?`Log ${l}`:"Log",depth:i,children:e&&a.jsxs(a.Fragment,{children:[a.jsxs(Rt.Header,{children:[a.jsx(Rt.CloseButton,{onClick:t}),a.jsxs(Rt.Heading,{children:["Log · ",l]}),a.jsx(Rt.HeaderActions,{children:a.jsx(Rt.NextPrevNav,{onPrevious:s,onNext:o,previousLabel:"Go to previous log",nextLabel:"Go to next log"})})]}),a.jsx(Rt.Content,{children:a.jsxs("div",{className:"grid gap-6 p-2",children:[a.jsxs(Ft,{children:[e.entityType&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Entity Type"}),a.jsx(Ft.Value,{children:e.entityType})]}),e.entityName&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Entity Name"}),a.jsx(Ft.Value,{children:e.entityName})]}),e.serviceName&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Service"}),a.jsx(Ft.Value,{children:e.serviceName})]}),e.environment&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Environment"}),a.jsx(Ft.Value,{children:e.environment})]}),e.source&&a.jsxs(a.Fragment,{children:[a.jsx(Ft.Key,{children:"Source"}),a.jsx(Ft.Value,{children:e.source})]}),e.metadata&&Object.entries(e.metadata).map(([c,u])=>a.jsxs(g.Fragment,{children:[a.jsx(Ft.Key,{children:c}),a.jsx(Ft.Value,{children:String(u)})]},c))]}),a.jsx(Rt.CodeSection,{title:"Message",codeStr:e.message,simplified:!0}),(e.traceId||e.spanId)&&a.jsxs("div",{className:"grid gap-2",children:[e.traceId&&a.jsxs(zl,{className:"w-full min-w-0",children:[a.jsxs(ae,{className:"min-w-0 flex-1 justify-between overflow-hidden",icon:a.jsx(qf,{}),onClick:()=>e.traceId&&n?.(e.traceId),children:[a.jsx("span",{children:"Trace"}),a.jsxs("span",{className:"ml-auto min-w-0 truncate text-caption text-placeholder",children:["# ",e.traceId]})]}),a.jsx(Oo,{content:e.traceId,tooltip:"Copy Trace ID to clipboard"})]}),e.spanId&&a.jsxs(zl,{className:"w-full min-w-0",children:[a.jsxs(ae,{className:"min-w-0 flex-1 justify-between overflow-hidden",disabled:!e.traceId||!r,onClick:()=>e.traceId&&e.spanId&&r?.(e.traceId,e.spanId),icon:a.jsx(qf,{}),children:[a.jsx("span",{children:"Span"}),a.jsxs("span",{className:"ml-auto min-w-0 truncate text-caption text-placeholder",children:["# ",e.spanId]})]}),a.jsx(Oo,{content:e.spanId,tooltip:"Copy Span ID to clipboard"})]})]}),e.data&&Object.keys(e.data).length>0&&a.jsx(Rt.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2)})]})})]})})}function bAs({error:e,resource:t,errorTitle:n}){if(_s(e))return a.jsx(Qs,{});if(js(e))return a.jsx(Fs,{resource:t});if(L3(e))return a.jsx(un,{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(D3(e,"logs"))return a.jsx(un,{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 a.jsx(un,{tone:"error",titleSlot:n,descriptionSlot:r??"Unknown error"})}const xAs={debug:"neutral",info:"blue",warn:"yellow",error:"red",fatal:"red"};function wAs({level:e}){return a.jsx(da,{children:a.jsx(Mt,{variant:xAs[e],children:e})})}function SAs({entityType:e,className:t}){const n=W("size-3.5 shrink-0 text-placeholder",t);switch(e.toLowerCase()){case"agent":return a.jsx(Pi,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return a.jsx(yl,{className:n,"aria-hidden":!0});case"tool":return a.jsx(Hd,{className:n,"aria-hidden":!0});default:return null}}function kAs({entityType:e,entityName:t}){const n=e??"";return a.jsxs(da,{className:"flex min-w-0 items-center gap-2",children:[a.jsx(SAs,{entityType:n}),t?a.jsx("span",{className:"min-w-0 truncate text-body-sm",children:t}):"-"]})}function OAs({message:e}){return a.jsx(da,{className:"min-w-0 truncate font-mono text-body-sm text-muted-foreground",children:e})}function _As({data:e}){if(!e||Object.keys(e).length===0)return a.jsx(da,{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 a.jsx(jIe,{font:"mono",children:t})}const El=Object.assign(B5,{Top:U5,TopCell:B0,SortableTopCell:GY,TopCellWithTooltip:HY,TopCellSmart:X3t,RowWrapper:AIe,RowButton:V5,RowLink:IIe,Spacer:RIe,NoMatch:ZY,DateCell:Q3t,TimeCell:K3t,LevelCell:wAs,EntityCell:kAs,MessageCell:OAs,DataCell:_As,NextPageLoading:WY}),uit="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",CAs=36,EAs=8;function TAs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:o,featuredLogId:i,onLogClick:l,timestampSort:c,onSortChange:u}){const d=g.useRef(null),f=NKt({count:e.length,getScrollElement:()=>d.current,estimateSize:()=>CAs,overscan:EAs}),{getRowProps:p}=Bc({count:e.length,containerRef:d,onNavigate:x=>f.scrollToIndex(x),global:!0}),h=g.useRef(t);if(g.useEffect(()=>{h.current&&!t&&d.current?.dispatchEvent(new Event("scroll")),h.current=t},[t]),t)return a.jsx(dc,{columns:uit,fit:"container"});const m=f.getVirtualItems(),y=f.getTotalSize(),v=m[0]?.start??0,b=m.length>0?Math.max(0,y-(m[m.length-1]?.end??0)):0;return a.jsxs(El,{columns:uit,scrollRef:d,className:"min-w-0",fit:"container",children:[a.jsxs(El.Top,{children:[u?a.jsx(El.SortableTopCell,{sortKey:"timestamp",sort:c,onSortChange:u,children:"Date"}):a.jsx(El.TopCell,{children:"Date"}),a.jsx(El.TopCell,{children:"Time"}),a.jsx(El.TopCell,{children:"Level"}),a.jsx(El.TopCell,{children:"Entity"}),a.jsx(El.TopCell,{children:"Message"}),a.jsx(El.TopCell,{children:"Data"})]}),e.length===0?a.jsx(El.NoMatch,{message:"No logs match your search"}):a.jsxs(a.Fragment,{children:[a.jsx(El.Spacer,{height:v}),m.map(x=>{const w=e[x.index];if(!w)return null;const k=o.get(w);if(!k)return null;const _=k===i;return a.jsxs(El.RowButton,{ref:f.measureElement,"data-index":x.index,...p(x.index),onClick:()=>l(w),featured:_,variant:w.level==="error"||w.level==="fatal"?"error":"default",children:[a.jsx(El.DateCell,{timestamp:w.timestamp}),a.jsx(El.TimeCell,{timestamp:w.timestamp}),a.jsx(El.LevelCell,{level:w.level}),a.jsx(El.EntityCell,{entityType:w.entityType,entityName:w.entityName}),a.jsx(El.MessageCell,{message:w.message}),a.jsx(El.DataCell,{data:w.data})]},k)}),a.jsx(El.Spacer,{height:b})]}),a.jsx(El.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function jAs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:o,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>NAs(f,o));return u?a.jsxs("div",{className:W("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx(vJt,{fields:o,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(mJt,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function NAs(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 IAs={"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"},mce="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function AAs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${IAs[e]}`,description:mce}:t&&n?{title:`No logs between ${Fr(t,"date-time")} and ${Fr(n,"date-time")}`,description:mce}:t?{title:`No logs since ${Fr(t,"date-time")}`,description:mce}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const RAs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=AAs({datePreset:e,dateFrom:t,dateTo:n});return a.jsx(un,{titleSlot:r,descriptionSlot:s,actionSlot:a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Ts,{}),children:"Logging Documentation"}),variant:"fill"})},PAs=20,$As=1e4,MAs={field:"timestamp",direction:"DESC"};function DAs(e,t,n){if(e?.pagination?.hasMore)return n+1}function LAs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const o=s.logId??JSON.stringify(s);t.has(o)||(t.add(o),n.push(s))}return n}function FAs(e){return D3(e.state.error,"logs")||L3(e.state.error)?!1:$As}const zAs=({filters:e,orderBy:t=MAs}={})=>{const n=Xe(),{inView:r,setRef:s}=A0(),o=Tm({queryKey:["logs",e,t],queryFn:({pageParam:h})=>n.listLogsVNext({pagination:{page:h,perPage:PAs},filters:e,orderBy:t}),initialPageParam:0,getNextPageParam:DAs,select:LAs,retry:!1,refetchInterval:FAs}),{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c,data:u,isLoading:d,isError:f,error:p}=o;return g.useEffect(()=>{r&&i&&!l&&c()},[r,i,l,c]),{data:u,hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c,isLoading:d,isError:f,error:p,setEndOfListElement:s}},cB={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},xJt=[{label:"Agent",entityType:cB.AGENT},{label:"Workflow",entityType:cB.WORKFLOW},{label:"Scorer",entityType:cB.SCORER},{label:"Ingest",entityType:cB.INGEST}],BAs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],x0="rootEntityType",kx="datePreset",Ox="dateFrom",_x="dateTo",UAs=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"},U6=Object.keys(Nl),h2e=new Set(["tags"]),m2e="mastra:logs:saved-filters";function VAs(e,t=m2e){const n=GAs(e),r=e.get(kx);r&&n.set(kx,r);const s=e.get(Ox);s&&n.set(Ox,s);const o=e.get(_x);o&&n.set(_x,o);try{localStorage.setItem(t,n.toString())}catch{}}function qAs(e=m2e){try{localStorage.removeItem(e)}catch{}}function dit(e=m2e){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function HAs(e){if(e.has(kx)||e.has(Ox)||e.has(_x)||e.has(x0))return!0;for(const t of U6)if(e.has(Nl[t]))return!0;return!1}function WAs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const o=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:xJt.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:BAs.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=o.filter(u=>u.kind==="pick-multi").sort(i),c=o.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function ZAs(e){const t=[],n=new Map([[x0,"rootEntityType"]]);for(const s of U6)n.set(Nl[s],s);const r=new Set;for(const[s]of e.entries()){const o=n.get(s);if(!o||r.has(o))continue;if(r.add(o),h2e.has(o)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:o,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:o,value:i})}return t}function GAs(e){const t=new URLSearchParams,n=e.get(x0);n&&t.set(x0,n);for(const r of U6){const s=Nl[r];if(h2e.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const o=e.get(s);o&&t.set(s,o)}return t}function QAs(e,t){e.delete(x0);for(const n of U6)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(x0,n.value);continue}const r=Nl[n.fieldId];if(r){if(h2e.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 YAs({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 o of r){if(o.fieldId==="tags"){Array.isArray(o.value)&&o.value.length>0?s.tags=o.value:typeof o.value=="string"&&o.value.trim()&&(s.tags=[o.value.trim()]);continue}if(o.fieldId==="level"){typeof o.value=="string"&&o.value.trim()&&o.value!=="Any"&&(s.level=o.value);continue}if(typeof o.value=="string"&&o.value.trim()&&o.value!=="Any")switch(o.fieldId){case"entityName":s.rootEntityName=o.value;break;case"traceId":s.traceId=o.value;break;case"spanId":s.spanId=o.value;break;case"runId":s.runId=o.value;break;case"threadId":s.threadId=o.value;break;case"sessionId":s.sessionId=o.value;break;case"requestId":s.requestId=o.value;break;case"resourceId":s.resourceId=o.value;break;case"userId":s.userId=o.value;break;case"organizationId":s.organizationId=o.value;break;case"serviceName":s.serviceName=o.value;break;case"environment":s.environment=o.value;break;case"experimentId":s.experimentId=o.value;break}}return s}function KAs(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 XAs="Filters setting for Logs saved",JAs="Filters setting for Logs cleared up";function eRs(e,t,n){const{storageKey:r,messages:s,skipHydration:o}={},[i,l]=g.useState(()=>dit(r)!==null),c=g.useCallback(()=>{VAs(e,r),l(!0);const f=s?.saved??XAs;f!==!1&&Qe.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{qAs(r),l(!1);const f=s?.cleared??JAs;f!==!1&&Qe.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(o||d.current||(d.current=!0,HAs(e)))return;const f=dit(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,y]of f)h.append(m,y);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function tRs(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 nRs(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,tRs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function rRs(e,t,n,r){const s=g.useMemo(()=>nRs(e),[e]),o=g.useMemo(()=>{const h=new Map;for(const[m,y]of e.entries()){const v=s.get(y);v&&h.set(v,{log:y,idx:m})}return h},[e,s]),l=(t?o.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 e1e="logId",t1e="traceId",n1e="spanId",iM=1440*60*1e3,sRs={"last-24h":iM,"last-3d":3*iM,"last-7d":7*iM,"last-14d":14*iM,"last-30d":30*iM};function uB(e){e.delete(e1e),e.delete(t1e),e.delete(n1e)}function oRs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(kx);return _&&UAs.has(_)?_:"last-24h"},[e]),o=e.get(Ox),i=e.get(_x),l=g.useMemo(()=>{if(s==="custom"){if(!o)return;const C=new Date(o);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=sRs[s];return _?new Date(Date.now()-_):void 0},[s,o]),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(e1e),f=e.get(t1e),p=e.get(n1e),h=g.useMemo(()=>xJt.find(_=>_.entityType===e.get(x0)),[e]),m=g.useMemo(()=>ZAs(e),[e]),y=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);for(const[E,I]of Object.entries(_)){const N=E==="logId"?e1e:E==="traceId"?t1e:n1e;I?T.set(N,I):T.delete(N)}return T},{replace:!0})},[t]),v=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);return QAs(T,_),uB(T),T},{replace:!0})},[t]),b=v,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const T=C==="from"?Ox:_x;t(E=>{const I=new URLSearchParams(E);return _?I.set(T,_.toISOString()):I.delete(T),uB(I),I},{replace:!0})},[t]),w=g.useCallback(_=>{u.current=_,t(C=>{const T=new URLSearchParams(C);return _==="last-24h"?(T.delete(kx),T.delete(Ox),T.delete(_x)):_==="custom"?T.set(kx,"custom"):(T.set(kx,_),T.delete(Ox),T.delete(_x)),uB(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(x0);for(const T of U6)C.delete(Nl[T]);return C.delete(kx),C.delete(Ox),C.delete(_x),uB(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:y,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:v}),[e,t,s,l,c,u,d,f,p,h,m,y,b,x,w,k,v])}const wJt=()=>{const e=Xe();return wt({queryKey:["observability-service-names"],queryFn:async()=>{try{return await e.getServiceNames()}catch{return{serviceNames:[]}}},select:t=>t?.serviceNames??[],retry:!1,staleTime:L6})},SJt=()=>{const e=Xe();return wt({queryKey:["observability-tags"],queryFn:async()=>{try{return await e.getTags()}catch{return{tags:[]}}},select:t=>t?.tags??[],retry:!1,staleTime:L6})},gce=[Wr("/logs")],iRs=["timestamp"],aRs={key:"timestamp",direction:"desc"};function lRs(){const[e,t]=so(),n=oRs(e,t),r=FX(),{sort:s,onSortChange:o}=fk({searchParams:e,setSearchParams:t,allowedKeys:iRs,defaultSort:aRs}),i=g.useMemo(()=>({field:"timestamp",direction:s?.direction==="asc"?"ASC":"DESC"}),[s?.direction]),l=eRs(e,t),[c,u]=g.useState(),{data:d=[],isPending:f}=SJt(),{data:p=[],isPending:h}=WMe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:m=[],isPending:y}=ZMe(),{data:v=[],isPending:b}=wJt(),x=g.useMemo(()=>WAs({availableTags:d,availableRootEntityNames:p,availableServiceNames:v,availableEnvironments:m,loading:{tags:f,entityNames:h,serviceNames:b,environments:y}}),[d,p,v,m,f,h,b,y]),w=g.useMemo(()=>YAs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:k=[],isLoading:_,error:C,isFetchingNextPage:T,hasNextPage:E,setEndOfListElement:I}=zAs({filters:w,orderBy:i}),{logIdMap:N,featuredLog:A,handleLogClick:P,handlePreviousLog:F,handleNextLog:D}=rRs(k,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:H,isLoading:q}=RE(n.featuredTraceId??null),V=g.useCallback(()=>n.applyFilterTokens(KAs(x,n.filterTokens)),[x,n]),B=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),Z=g.useCallback(U=>n.handleFeaturedChange({traceId:U,spanId:null}),[n]),z=g.useCallback((U,Q)=>n.handleFeaturedChange({traceId:U,spanId:Q}),[n]),Y=g.useCallback(()=>n.handleFeaturedChange({traceId:null,spanId:null}),[n]),L=g.useCallback(U=>n.handleFeaturedChange({spanId:U??null}),[n]),R=a.jsxs(a.Fragment,{children:[a.jsx(Gn,{children:a.jsxs(Gn.Start,{children:[a.jsx(QY,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:_,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),a.jsx(bJt,{fields:x,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:_,onStartTextFilter:u})]})}),a.jsx(jAs,{isLoading:_,filterFields:x,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:V,onRemoveAll:n.handleRemoveAll,onSave:l.handleSave,onRemoveSaved:l.hasSavedFilters?l.handleRemoveSaved:void 0,autoFocusFilterFieldId:c})]});if(C)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:gce}),actionRow:R,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(bAs,{error:C,resource:"logs",errorTitle:"Failed to load logs"})})]});const M=!!n.selectedEntityOption||n.filterTokens.length>0;return k.length===0&&!_&&!M?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:gce}),actionRow:R,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(RAs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:gce}),actionRow:R,children:[a.jsx("h1",{className:"sr-only",children:"Logs"}),a.jsx(TAs,{logs:k,isLoading:_,isFetchingNextPage:T,hasNextPage:E,setEndOfListElement:I,logIdMap:N,featuredLogId:n.featuredLogId,onLogClick:P,timestampSort:s?.direction,onSortChange:o}),a.jsx(yAs,{log:A??void 0,onClose:B,onTraceClick:Z,onSpanClick:z,onPrevious:F,onNext:D}),a.jsx(s2e,{depth:2,traceId:A?n.featuredTraceId??void 0:void 0,spans:H?.spans,isLoadingSpans:q,selectedSpanId:n.featuredSpanId??null,onSpanSelect:L,onClose:Y,withQueryTrace:r.enabled,withFeedback:r.enabled})]})}const cRs={name:e=>e.name||e.id};function uRs({server:e,rowProps:t}){const{paths:n,Link:r}=dn(),o=Xe().options.baseUrl,l=e.transports?.includes("sse")??!0?"sse":"mcp",c=o?`${o}/api/mcp/${e.id}/${l}`:"",{data:u}=dGt(e),d=Object.values(u||{}),f=d.length,p=d.filter(y=>y.toolType==="agent").length,h=d.filter(y=>y.toolType==="workflow").length,m=Xd(e.name,50);return a.jsxs(Oe.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[a.jsx(Oe.NameCell,{children:m}),a.jsx(Oe.DescriptionCell,{children:c}),a.jsx(Oe.TextCell,{className:"text-center",children:p||""}),a.jsx(Oe.TextCell,{className:"text-center",children:f||""}),a.jsx(Oe.TextCell,{className:"text-center",children:h||""})]})}function dRs({mcpServers:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const o=g.useMemo(()=>{const c=n.toLowerCase();return G0(e.filter(u=>u.name?.toLowerCase().includes(c)||u.id?.toLowerCase().includes(c)),r,cRs)},[e,n,r]),{containerRef:i,getRowProps:l}=Bc({count:o.length,global:!0});return t?a.jsx(dc,{columns:"auto 1fr auto auto auto"}):a.jsxs(Oe,{columns:"auto 1fr auto auto auto",scrollRef:i,children:[a.jsxs(Oe.Top,{children:[s?a.jsx(Oe.SortableTopCell,{sortKey:"name",sort:r?.key==="name"?r.direction:void 0,onSortChange:s,children:"Name"}):a.jsx(Oe.TopCell,{children:"Name"}),a.jsx(Oe.TopCell,{children:"URL"}),a.jsx(Oe.TopCellSmart,{long:"Agents",short:a.jsx(Pi,{}),tooltip:"Agent Tools",className:"text-center"}),a.jsx(Oe.TopCellSmart,{long:"Tools",short:a.jsx(Hd,{}),tooltip:"Tools",className:"text-center"}),a.jsx(Oe.TopCellSmart,{long:"Workflows",short:a.jsx(yl,{}),tooltip:"Workflow Tools",className:"text-center"})]}),o.length===0&&n?a.jsx(Oe.NoMatch,{message:"No MCP Servers match your search"}):null,o.map((c,u)=>a.jsx(uRs,{server:c,rowProps:l(u)},c.id))]})}const fRs=()=>a.jsx(un,{titleSlot:"No MCP Servers yet",descriptionSlot:a.jsxs(a.Fragment,{children:["MCP servers are not configured yet. ",a.jsx("br",{}),"More information in the documentation."]}),actionSlot:a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Ts,{}),children:"MCP Documentation"}),variant:"fill"}),aM=[Wr("/mcps")],pRs=()=>{const{data:e=[],isLoading:t,error:n}=FA(),[r,s]=g.useState(""),[o,i]=g.useState();return n&&_s(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Qs,{variant:"fill"})]}):n&&js(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(Fs,{variant:"fill",resource:"MCP servers"})]}):n?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load MCP servers",descriptionSlot:n.message})]}):e.length===0&&!t?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(fRs,{})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:aM}),actionRow:a.jsx(Gn,{children:a.jsx(Gn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"MCP Servers"}),a.jsx(dRs,{mcpServers:e,isLoading:t,search:r,sort:o,onSortChange:(l,c)=>i({key:c,direction:l})})]})},fit="auto 1fr auto",hRs={tool:"Tool",agent:"Agent",workflow:"Workflow"};function mRs(e){return e in sMe}function gRs({type:e}){const t=mRs(e)?e:"tool",n=sMe[t],r=hRs[t];return a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("span",{"aria-label":t,className:"text-neutral3 inline-flex [&>svg]:size-4",children:a.jsx(n,{})})}),a.jsx(kn,{children:r})]})}const vRs=mr({ui:mr({resourceUri:jn().optional()}).optional(),"ui/resourceUri":jn().optional()});function yRs(e){const t=vRs.safeParse(e);return t.success?!!(t.data.ui?.resourceUri?.startsWith("ui://")||t.data["ui/resourceUri"]?.startsWith("ui://")):!1}function bRs({server:e}){const[t,n]=g.useState(""),{data:r={},isLoading:s}=dGt(e),{Link:o,paths:i}=dn(),l=g.useMemo(()=>{const d=t.toLowerCase();return Object.values(r).filter(f=>f.name.toLowerCase().includes(d)||f.description?.toLowerCase().includes(d))},[r,t]),{containerRef:c,getRowProps:u}=Bc({count:l.length});return a.jsxs("section",{className:"flex flex-col gap-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[a.jsx(je,{as:"h2",variant:"heading",children:"Available tools"}),a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{onSearch:n,label:"Filter tools",placeholder:"Filter by name",shortcutDisabled:!0})})]}),s?a.jsx(dc,{columns:fit}):a.jsxs(Oe,{columns:fit,scrollRef:c,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{children:"Name"}),a.jsx(Oe.TopCell,{children:"Description"}),a.jsx(Oe.TopCell,{className:"justify-center text-center",children:"Type"})]}),l.length===0&&t?a.jsx(Oe.NoMatch,{message:"No tools match your search"}):null,l.map((d,f)=>a.jsxs(Oe.RowLink,{to:i.mcpServerToolLink(e.id,d.name),LinkComponent:o,...u(f),children:[a.jsx(Oe.NameCell,{children:a.jsxs("span",{className:"flex items-center gap-2",children:[d.name,yRs(d._meta)&&a.jsx(Mt,{size:"xs",children:"App"})]})}),a.jsx(Oe.DescriptionCell,{children:d.description}),a.jsx(Oe.TextCell,{className:"justify-center text-center",children:a.jsx(gRs,{type:d.toolType??"tool"})})]},d.name))]})]})}const xRs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const c=window.MASTRA_SERVER_HOST,u=window.MASTRA_SERVER_PORT;let d=null;c&&u&&(d=`http://${c}:${u}`);const f=d||"http://localhost:4111",p=`${f}/api/mcp/${t.id}/sse`,h=`${f}/api/mcp/${t.id}/mcp`;s({sseUrl:p,httpStreamUrl:h})},[t]),e)return null;if(!t)return a.jsx(je,{as:"h1",variant:"heading",tone:"muted",className:"py-20 text-center",children:"Server not found"});const o=t.transports?.includes("sse")??!0,i=`npx -y mcp-remote ${o?n:r}`,l=[{value:"http",label:"HTTP",description:"Use for stateless HTTP transport with streamable responses.",content:r,tooltip:"Copy HTTP Stream URL"},...o?[{value:"sse",label:"SSE",description:"Use for real-time communication via SSE.",content:n,tooltip:"Copy SSE URL"}]:[],{value:"cli",label:"CLI",description:"Use for local command-line access via npx and mcp-remote.",content:i,tooltip:"Copy Command Line Config"}];return a.jsxs("div",{className:"flex flex-col gap-6 pt-4",children:[a.jsx(ku,{children:a.jsxs(ll,{defaultTab:"http",children:[a.jsxs($q,{className:"border-border1 flex-row items-center justify-between gap-3 space-y-0 border-b",children:[a.jsx(J1,{className:"shrink-0",children:"Connect"}),a.jsx("div",{className:"min-w-0",children:a.jsx(al,{variant:"pill-ghost",size:"sm",children:l.map(c=>a.jsx(Lr,{value:c.value,children:c.label},c.value))})})]}),l.map(c=>a.jsx(Ss,{value:c.value,flush:!0,children:a.jsxs(lv,{className:"flex flex-col gap-3",children:[a.jsx(je,{tone:"muted",children:c.description}),a.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg bg-muted py-2 pr-2 pl-3",children:[a.jsx(je,{as:"span",font:"mono",className:"min-w-0 break-all",children:c.content}),a.jsx(Oo,{tooltip:c.tooltip,content:c.content})]})]})},c.value))]})}),a.jsx(bRs,{server:t})]})},wRs=()=>{const{serverId:e}=fr(),t=[Wr("/mcps"),b_t],{data:n=[],isLoading:r}=FA(),s=n.find(l=>l.id===e),o=s?.transports?.includes("sse")??!0,i=r||s?a.jsxs(jc,{children:[a.jsx(jc.Title,{isLoading:r,children:s?.name}),s&&a.jsx(jc.Meta,{beside:!0,children:a.jsxs(Mt,{size:"sm",children:["v",s.version_detail.version]})}),s&&a.jsx(jc.Description,{children:o?"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case.":"This MCP server speaks Streamable HTTP only (protocol 2026-07-28)."})]}):void 0;return a.jsx(gt,{variant:"narrow",breadcrumbs:a.jsx(kt,{crumbs:t}),header:i,children:a.jsx(xRs,{isLoading:r,server:s})})};function SRs(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}function kRs(e){return typeof e=="object"&&e!==null&&e.status==="suspended"}function ORs(e){return JSON.stringify({error:e instanceof Error?e.message:String(e)},null,2)}const _Rs=({toolId:e,serverId:t})=>{const{canExecute:n}=_a(),r=n("tools"),s=Xe(),{data:o,isLoading:i,error:l}=H_e(t,e),{mutateAsync:c,isPending:u,data:d,error:f}=T6n(t,e),p=o?SRs(o._meta):void 0,{data:h}=wt({queryKey:["mcp-app-resource",t,p],queryFn:async()=>p?(await s.readMcpServerResource(t,p)).contents[0]?.text??null:null,enabled:!!p}),m=g.useCallback(async(b,x)=>await c(x),[c]);g.useEffect(()=>{if(l){const b=l instanceof Error?l.message:"Failed to load tool";Qe.error(`Error loading tool: ${b}`)}},[l]);const y=async b=>{if(o)return await c(b).catch(()=>{})};if(i)return a.jsxs("div",{className:"p-4",children:[a.jsx(at,{className:"mb-4 h-8 w-48"}),a.jsx(at,{className:"h-32 w-full"})]});if(l)return null;if(!o)return a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(je,{variant:"heading",tone:"muted",children:"Tool not found"})});if(!r)return a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(je,{variant:"caption",tone:"muted",children:"You don't have permission to execute tools."})});let v;try{v=Am(o.inputSchema)}catch(b){console.error("Error processing input schema:",b),Qe.error("Failed to process tool input schema."),v=mr({})}return a.jsxs("div",{className:"flex flex-col gap-4",children:[h&&a.jsx("div",{className:"border-b border-border p-4",children:a.jsx(uGt,{html:h,toolName:o.name,onToolCall:m})}),kRs(d)&&a.jsx("div",{className:"px-4 pt-4",children:a.jsxs(Jt,{variant:"warning",children:["This tool asked for more input, which Studio cannot provide. The suspend payload below shows what it needs. Call it from an MCP client with an ",a.jsx("code",{children:"inputRequests"})," handler to finish the request."]})}),a.jsx(oMe,{executionResult:d,errorString:f?ORs(f):void 0,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:y,toolDescription:o.description||"",toolId:o.name})]})},CRs=()=>{const{serverId:e,toolId:t}=fr(),n=[Wr("/mcps"),{...b_t,to:e?`/mcps/${encodeURIComponent(e)}`:void 0},{id:"mcp-server-tool",Component:I6n}],{data:r,isLoading:s}=H_e(e,t);return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:t}),!s&&r&&a.jsx("div",{className:"h-full w-full overflow-y-auto",children:a.jsx(_Rs,{toolId:t,serverId:e})})]})},ERs={default:YOe,inset:W(ir,"*:bg-background! *:shadow-rim!")};function TRs({children:e,variant:t="default",className:n}){return a.jsx("div",{className:W("grid grid-cols-1 gap-1 rounded-xl p-1 *:min-w-0! md:grid-cols-2 lg:flex lg:*:flex-1",ERs[t],n),children:e})}function jRs({children:e,className:t}){return a.jsx("div",{className:W("flex flex-wrap gap-4",t),children:e})}const kJt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],iA="rootEntityType",aA={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"},JX=Object.keys(aA),g2e="mastra:metrics:saved-filters";function NRs(e){const t=PRs(e);try{localStorage.setItem(g2e,t.toString())}catch{}}function IRs(){try{localStorage.removeItem(g2e)}catch{}}function OJt(){try{const e=localStorage.getItem(g2e);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function ARs(e){if(e.has(iA))return!0;for(const t of JX)if(e.has(aA[t]))return!0;return!1}function _Jt({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const o=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:kJt.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=o.filter(u=>u.kind==="pick-multi").sort(i),c=o.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function RRs(e){const t=[],n=new Map([[iA,"rootEntityType"]]);for(const s of JX)n.set(aA[s],s);const r=new Set;for(const[s]of e.entries()){const o=n.get(s);if(!o||r.has(o))continue;if(r.add(o),o==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:o,value:l.filter(Boolean)});continue}if(o==="rootEntityType"||o==="entityName"||o==="serviceName"||o==="environment"||o==="provider"||o==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:o,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:o,value:i})}return t}function PRs(e){const t=new URLSearchParams,n=e.getAll(iA);for(const r of n)t.append(iA,r);for(const r of JX){const s=aA[r],o=e.getAll(s);for(const i of o)t.append(s,i)}return t}function $Rs(e,t){e.delete(iA);for(const n of JX)e.delete(aA[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?iA:aA[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(o=>typeof o=="string"&&o!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const o of s)e.append(r,o)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const MRs="Any";function pit(e){const t=e.trim();return t===""||t===MRs}const DRs=new Set(kJt.map(e=>e.entityType));function hit(e){const t=e.trim();return DRs.has(t)?t:void 0}function LRs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>!pit(o));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const o=s[0],i=o!==void 0?hit(o):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(pit(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const o=hit(s);o&&(t.rootEntityType=o)}else t[r]=s}}return t}const CJt=[{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"}],FRs=new Set(CJt.map(e=>e.value));function zRs(e){return typeof e=="string"&&(FRs.has(e)||e==="custom")}const EJt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function eJ(){return g.useContext(EJt)}function BRs(e,t){return e!=="custom"?CJt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${l_(t.from)} – ${l_(t.to)}`:l_(t.from)??"":"Custom range"}function URs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:o,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>LRs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=BRs(t,o),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:o,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,o,i,h,d,s,f,p,l,c]);return a.jsx(EJt.Provider,{value:m,children:e})}const r1e=1440*60*1e3,VRs={"24h":r1e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function qRs(e,t,n){if(e!=="custom"){const r=VRs[e]??r1e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-r1e),end:t?.to??new Date(n)}}function sg(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=eJ(),s=g.useRef(null),o=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==o)&&(s.current={key:o,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>qRs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${o}|${r}`,[o,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function TJt(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function V6({href:e,LinkComponent:t="a"}){return a.jsx(ae,{render:a.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:a.jsx(La,{})})}function HRs({href:e,LinkComponent:t="a"}){return a.jsx(ae,{render:a.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:a.jsx(c2n,{})})}function WRs({children:e,className:t}){return a.jsx("div",{className:W("flex shrink-0 items-center gap-1",t),children:e})}function ZRs({children:e,className:t}){return a.jsx("div",{className:W("overflow-x-auto",t),children:e})}function jJt({children:e,className:t}){return a.jsx("p",{className:W("mt-0.5 text-body text-placeholder",t),children:e})}function GRs({message:e="Failed to load data",className:t}){return a.jsx("div",{className:W("flex flex-col items-center justify-center gap-3",t),children:a.jsx("p",{className:"text-caption text-accent2",children:e})})}function QRs({className:e}){return a.jsx("div",{className:W("flex items-center justify-center",e),children:a.jsx(Cn,{size:"md",variant:"pulse",className:"text-placeholder"})})}function YRs({message:e="No data yet",className:t}){return a.jsx("div",{className:W("flex h-full items-center justify-center",t),children:a.jsx("p",{className:"text-body text-placeholder",children:e})})}function mit({children:e,className:t}){return a.jsx(ku,{className:W("grid min-h-72 min-w-80 flex-1 grid-rows-[auto_1fr] gap-4 px-4 py-3 2xl:min-w-120 md:min-w-88 lg:min-w-sm xl:min-w-104",t),children:e})}function KRs({value:e,label:t,className:n}){return a.jsxs("div",{className:W("text-right",n),children:[a.jsx("p",{className:"text-body text-muted-foreground tabular-nums",children:e}),t&&a.jsx("p",{className:"mt-0.5 text-body text-placeholder",children:t})]})}function NJt({children:e,className:t,as:n="h2"}){return a.jsx(n,{className:W("text-body text-foreground",t),children:e})}function XRs(e){if("children"in e)return a.jsx("div",{className:e.className,children:e.children});const{title:t,description:n,titleAs:r}=e;return a.jsxs("div",{className:e.className,children:[a.jsx(NJt,{as:r,children:t}),n&&a.jsx(jJt,{children:n})]})}function JRs({children:e,className:t}){return a.jsx("div",{className:W("flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1",t),children:e})}const tr=Object.assign(mit,{Root:mit,Kpi:xf,TopBar:JRs,Actions:WRs,TitleAndDescription:XRs,Title:NJt,Description:jJt,Summary:KRs,Loading:QRs,Error:GRs,Content:ZRs,NoData:YRs});function WW({data:e,series:t,className:n}){return a.jsx("div",{className:W("flex flex-wrap items-center gap-4 gap-y-1",n),children:t.map(r=>{const s=r.aggregate?.(e);return a.jsxs("div",{className:"inline-flex items-center gap-2",children:[a.jsx("div",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:r.color}}),a.jsx("span",{className:"max-w-24 truncate text-caption text-muted-foreground",children:r.label}),s&&a.jsxs("span",{className:"text-caption text-muted-foreground",children:[s.value,s.suffix&&a.jsxs("span",{className:"text-caption text-placeholder",children:[" ",s.suffix]})]})]},r.dataKey)})})}function ePs({active:e,payload:t,label:n,suffix:r}){return!e||!t?.length?null:a.jsxs(yIe,{children:[a.jsx("p",{className:"mb-1 text-column text-foreground",children:n}),t.map(s=>a.jsxs("p",{className:"text-foreground",children:[a.jsx("span",{className:"mr-2 inline-block size-2 rounded-full",style:{backgroundColor:s.color}}),s.name,":"," ",a.jsxs("span",{className:"font-mono",children:[typeof s.value=="number"?s.value.toLocaleString("en-US"):s.value,r]})]},s.name))]})}const tPs=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1});function nPs({points:e}){const[t,n]=e??[];return!t||!n?null:a.jsx("line",{x1:0,x2:0,y1:t.y,y2:n.y,stroke:"currentColor",strokeOpacity:.2,strokeWidth:1,className:"pointer-events-none text-black transition-transform duration-150 ease-out dark:text-white",style:{transform:`translateX(${t.x}px)`}})}function s1e({data:e,series:t,height:n=210,yDomain:r,onPointClick:s,xAxisInterval:o="preserveStartEnd",xAxisMinTickGap:i=28,showDots:l=!1,showLegend:c=!0}){const u=typeof s=="function";return a.jsxs("div",{children:[c&&a.jsx(WW,{data:e,series:t,className:"mb-4"}),a.jsx("div",{style:{height:n},children:a.jsx(C5,{width:"100%",height:"100%",children:a.jsxs(A3r,{data:e,margin:{top:5,right:5,bottom:5,left:0},children:[a.jsx(k4t,{stroke:"currentColor",strokeOpacity:.08,strokeDasharray:"4 4",vertical:!1,className:"text-black dark:text-white"}),a.jsx(L5,{dataKey:"time",tick:{fontSize:Rve,fill:M9e,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,interval:o,minTickGap:i}),a.jsx(F5,{tick:{fontSize:Rve,fill:M9e,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,width:"auto",tickFormatter:d=>tPs.format(d),domain:r,tickCount:3}),a.jsx(OY,{content:a.jsx(ePs,{}),cursor:a.jsx(nPs,{})}),t.map(d=>a.jsx(A4t,{type:"linear",dataKey:d.dataKey,stroke:d.color,strokeWidth:2,dot:l?{r:3,fill:d.color,strokeWidth:0}:!1,activeDot:u?{r:4,stroke:d.color,strokeOpacity:.3,strokeWidth:4,style:{cursor:"pointer"},onClick:(f,p)=>{const h=p?.payload;h&&s(h,d.dataKey)}}:{r:4,stroke:d.color,strokeOpacity:.3,strokeWidth:4},name:d.label},d.dataKey))]})})})]})}function rPs(e){return e==="agents"||e==="workflows"||e==="tools"}function git(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const o=s[t];return r+(typeof o=="number"&&Number.isFinite(o)?o:0)},0);return`${Math.round(n/e.length)}`}function sPs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const o1e={className:"max-h-80",mask:{left:!1}},By={pink:"var(--chart-pink)",purple:"var(--chart-purple)",blue:"var(--chart-blue)",blueDark:"var(--chart-blue-deep)",yellow:"var(--chart-yellow)"},IJt=[{dataKey:"p50",label:"p50",color:By.blue,aggregate:e=>({value:git(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:By.yellow,aggregate:e=>({value:git(e,"p95"),suffix:"avg ms"})}];function vce({data:e,onPointClick:t}){return e.length===0?a.jsx(tr.NoData,{message:"No latency data yet"}):a.jsx(s1e,{data:e,series:IJt,showLegend:!1,onPointClick:t?n=>sPs(n)?t(n):void 0:void 0})}function oPs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const o=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:o,workflows:i,tools:l},u=o?"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?.interval??"1h",y=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?{agents:e.agentData,workflows:e.workflowData,tools:e.toolData}[p]:[];return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Latency",description:m==="1h"?"Hourly p50 and p95 latency.":"Daily p50 and p95 latency."}),h?a.jsx(tr.Actions,{children:h}):null]}),t?a.jsx(tr.Loading,{}):n?a.jsx(tr.Error,{message:"Failed to load latency data"}):a.jsx(tr.Content,{children:y?a.jsxs(ll,{value:p,onValueChange:b=>{rPs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 [&>:first-child]:w-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"agents",disabled:!o,disabledTooltip:"No agent latency data for this period",children:"Agents"}),a.jsx(Lr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),a.jsx(Lr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),v.length>0&&a.jsx(WW,{data:v,series:IJt})]}),a.jsx(Ss,{value:"agents",className:"pt-3",children:a.jsx(vce,{data:e.agentData,onPointClick:r?b=>r("agents",b,m):void 0})}),a.jsx(Ss,{value:"workflows",className:"pt-3",children:a.jsx(vce,{data:e.workflowData,onPointClick:r?b=>r("workflows",b,m):void 0})}),a.jsx(Ss,{value:"tools",className:"pt-3",children:a.jsx(vce,{data:e.toolData,onPointClick:r?b=>r("tools",b,m):void 0})})]}):a.jsx(tr.NoData,{message:"No latency data yet"})})]})}function iPs(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 aPs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const o=new Date(s.getTime()+3600*1e3);return{from:s,to:o}}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 AJt(e,t,n,r,s,o,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"),o?.from&&e.set(n,o.from.toISOString()),o?.to&&e.set(r,o.to.toISOString());return}const l=iPs(s);l&&e.set(t,l)}function Ra(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function RJt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function vit({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const o=new URLSearchParams;o.set(mS,"branches"),AJt(o,gS,Yw,Kw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&o.set(N1,i),r.status&&o.set(I1,r.status),Ra(o,Kl.entityName,r.entityName??n.entityName),Ra(o,Kl.threadId,r.threadId??n.threadId),Ra(o,Kl.resourceId,r.resourceId??n.resourceId),Ra(o,Kl.entityId,n.entityId),Ra(o,Kl.runId,n.runId),Ra(o,Kl.sessionId,n.sessionId),Ra(o,Kl.requestId,n.requestId),Ra(o,Kl.userId,n.userId),Ra(o,Kl.organizationId,n.organizationId),Ra(o,Kl.experimentId,n.experimentId),Ra(o,Kl.serviceName,n.serviceName),Ra(o,Kl.environment,n.environment),RJt(o,Kl.tags,n.tags);const l=o.toString();return l?`${s}?${l}`:s}function lPs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const o=new URLSearchParams;AJt(o,kx,Ox,_x,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&o.set(x0,i),Ra(o,Nl.entityName,r.entityName??n.entityName),Ra(o,Nl.threadId,r.threadId??n.threadId),Ra(o,Nl.resourceId,r.resourceId??n.resourceId),Ra(o,Nl.runId,n.runId),Ra(o,Nl.sessionId,n.sessionId),Ra(o,Nl.requestId,n.requestId),Ra(o,Nl.userId,n.userId),Ra(o,Nl.organizationId,n.organizationId),Ra(o,Nl.experimentId,n.experimentId),Ra(o,Nl.serviceName,n.serviceName),Ra(o,Nl.environment,n.environment),RJt(o,Nl.tags,n.tags),r.status==="error"&&o.append(Nl.level,"error");const l=o.toString();return l?`${s}?${l}`:s}function BR(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=eJ(),o=g.useCallback((c={})=>vit({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>lPs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=aPs(u,d);return vit({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:o,getLogsHref:i,getBucketTracesHref:l}}const cPs=2880*60*1e3;function PJt({start:e,end:t}){return t.getTime()-e.getTime()<=cPs?"1h":"1d"}function $Jt(e,t){return t==="1h"?Fr(e,"time")??"":l_(e)??""}async function yce(e,t,n,r){const s=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:r,filters:n}),o=s.series.find(c=>c.percentile===.5),i=s.series.find(c=>c.percentile===.95);if(!o||!i)return[];const l=new Map(i.points.map(c=>[new Date(c.timestamp).getTime(),c.value]));return o.points.map(c=>{const u=new Date(c.timestamp),d=u.getTime();return{time:$Jt(u,r),tsMs:d,p50:Math.round(c.value),p95:Math.round(l.get(d)??0)}})}function uPs(){const e=Xe(),{timestamp:t,filters:n,filterKey:r}=sg(),s=PJt(t);return wt({queryKey:["metrics","latency",r,s],queryFn:async()=>{const[o,i,l]=await Promise.all([yce(e,"mastra_agent_duration_ms",n,s),yce(e,"mastra_workflow_duration_ms",n,s),yce(e,"mastra_tool_duration_ms",n,s)]);return{agentData:o,workflowData:i,toolData:l,interval:s}}})}const yit={agents:lu.AGENT,workflows:lu.WORKFLOW_RUN,tools:lu.TOOL};function dPs(){const{data:e,isLoading:t,isError:n}=uPs(),{getTracesHref:r,getBucketTracesHref:s}=BR(),{Link:o}=dn(),i=zr();return a.jsx(oPs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:yit[l]},c.tsMs,"1h"))},actions:l=>a.jsx(V6,{href:r({rootEntityType:yit[l]}),LinkComponent:o})})}function fPs(e){return e==="threads"||e==="resources"}function bce(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function pPs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:o}){const[i,l]=g.useState("threads"),c=e.data?.map(v=>({...v,key:v.threadId}))??[],u=t.data?.map(v=>({...v,key:v.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((v,b)=>v+b.runs,0)??0,h=t.data?.reduce((v,b)=>v+b.threadCount,0)??0,m=i==="threads"?e:t,y=typeof s=="function"?s(i):s;return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&a.jsx(tr.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&a.jsx(tr.Summary,{value:h.toLocaleString(),label:"Total threads"}),y?a.jsx(tr.Actions,{children:y}):null]}),m.isLoading?a.jsx(tr.Loading,{}):m.isError?a.jsx(tr.Error,{message:"Failed to load memory data"}):a.jsx(tr.Content,{children:a.jsxs(ll,{defaultTab:"threads",value:i,onValueChange:v=>{fPs(v)&&l(v)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"threads",children:"Threads"}),a.jsx(Lr,{value:"resources",children:"Resources"})]}),a.jsx(Ss,{value:"threads",className:"pt-3",children:d?a.jsxs(Oe,{columns:"auto auto auto auto auto",...o1e,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{sticky:"start",children:"Thread ID"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Resource ID"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Runs"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Tokens"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(v=>{const b=n?.(v),x=a.jsxs(a.Fragment,{children:[a.jsx(Oe.RowHeaderCell,{className:"text-caption",children:bce(v.threadId)}),a.jsx(Oe.NumberCell,{children:v.resourceId?bce(v.resourceId):"—"}),a.jsx(Oe.NumberCell,{highlight:!0,children:v.runs.toLocaleString()}),a.jsx(Oe.NumberCell,{children:v.tokens>0?$l(v.tokens):"—"}),a.jsx(Oe.NumberCell,{children:v.cost!=null?bm(v.cost,v.costUnit):"—"})]});return b?a.jsx(Oe.RowLink,{to:b,LinkComponent:o,children:x},v.key):a.jsx(Oe.RowStatic,{children:x},v.key)})]}):a.jsx(tr.NoData,{message:"No thread activity yet"})}),a.jsx(Ss,{value:"resources",className:"pt-3",children:f?a.jsxs(Oe,{columns:"auto auto auto auto",...o1e,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{sticky:"start",children:"Resource ID"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Threads"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Tokens"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(v=>{const b=r?.(v),x=a.jsxs(a.Fragment,{children:[a.jsx(Oe.RowHeaderCell,{className:"text-caption",children:bce(v.resourceId)}),a.jsx(Oe.NumberCell,{highlight:!0,children:v.threadCount.toLocaleString()}),a.jsx(Oe.NumberCell,{children:v.tokens>0?$l(v.tokens):"—"}),a.jsx(Oe.NumberCell,{children:v.cost!=null?bm(v.cost,v.costUnit):"—"})]});return b?a.jsx(Oe.RowLink,{to:b,LinkComponent:o,children:x},v.key):a.jsx(Oe.RowStatic,{children:x},v.key)})]}):a.jsx(tr.NoData,{message:"No resource activity yet"})})]})})]})}const xce=20;function hPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,o,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:xce}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:xce}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:xce})]),l=new Map,c=d=>FR(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(o.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 wce=20;function mPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,o,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:wce}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:wce}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:wce})]),l=new Map,c=d=>FR(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(o.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 gPs(){const e=hPs(),t=mPs(),{getTracesHref:n}=BR(),{Link:r}=dn();return a.jsx(pPs,{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 q6({value:e,currency:t,className:n}){const r=$l(e,{currency:t}),s=AE(e,{currency:t});return r===s?a.jsx("span",{className:W("tabular-nums",n),children:r}):a.jsxs(On,{children:[a.jsxs(Sn,{render:a.jsx("span",{tabIndex:0,className:W("tabular-nums",n)}),children:[a.jsx("span",{"aria-hidden":"true",children:r}),a.jsx("span",{className:"sr-only",children:s})]}),a.jsx(kn,{side:"right",children:s})]})}function H6({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:o,lowerIsBetter:i}){const l=t!=null;return a.jsxs(xf,{children:[a.jsx(xf.Label,{children:e}),a.jsxs(xf.ValueRow,{children:[l?a.jsx(xf.Value,{children:t}):null,o?a.jsx(xf.Error,{}):s?a.jsx(xf.Loading,{}):l?r!=null&&r!==0?a.jsx(xf.Change,{changePct:r,prevValue:n,lowerIsBetter:i}):a.jsx(xf.NoChange,{}):a.jsx(xf.NoData,{})]})]})}function vPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({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 yPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({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 bPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({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 xPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({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"})]),o=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:o?l:null,previousValue:i?c:null,changePercent:u}}})}function wPs(){const{data:e,isLoading:t,isError:n}=TJt();return a.jsx(H6,{label:"Total Agent Runs",value:e?.value!=null?a.jsx(q6,{value:e.value}):null,prevValue:e?.previousValue!=null?AE(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function SPs(){const{data:e,isLoading:t,isError:n}=bPs(),r=e?.costUnit??void 0;return a.jsx(H6,{label:"Total Model Cost",value:e?.cost!=null?a.jsx(q6,{value:e.cost,currency:r}):null,prevValue:e?.previousCost!=null?AE(e.previousCost,{currency:r}):void 0,changePct:e?.costChangePercent??null,lowerIsBetter:!0,isLoading:t,isError:n})}function kPs(){const{data:e,isLoading:t,isError:n}=xPs();return a.jsx(H6,{label:"Total Tokens",value:e?.value!=null?a.jsx(q6,{value:e.value}):null,prevValue:e?.previousValue!=null?AE(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function OPs(){const{data:e,isLoading:t,isError:n}=yPs();return a.jsx(H6,{label:"Total Threads",value:e?.value!=null?a.jsx(q6,{value:e.value}):null,prevValue:e?.previousValue!=null?AE(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function _Ps(){const{data:e,isLoading:t,isError:n}=vPs();return a.jsx(H6,{label:"Total Resources",value:e?.value!=null?a.jsx(q6,{value:e.value}):null,prevValue:e?.previousValue!=null?AE(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}const CPs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function EPs(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 TPs(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 jPs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=eJ(),s=g.useRef(e);s.current=e;const o=g.useRef(n);return o.current=n,a.jsx(QY,{preset:EPs(e),onPresetChange:i=>{const l=TPs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...o.current,[l]:i};o.current=c,r(c)},presets:CPs})}const rD=[Wr("/metrics")];function NPs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:o,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>IPs(f,o));return u?a.jsxs("div",{className:W("grid grid-cols-[1fr_auto] items-start gap-3"),children:[a.jsx(vJt,{fields:o,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&a.jsx(mJt,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function IPs(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 i1e({children:e,filterFields:t,isLoading:n=!1}){const[r]=so(),{filterTokens:s,setFilterTokens:o}=eJ(),[i,l]=g.useState(),[c,u]=g.useState(()=>!!OJt()),d=()=>{NRs(r),u(!0),Qe.success("Filters setting for Metrics saved")},f=()=>{IRs(),u(!1),Qe.success("Filters setting for Metrics cleared up")},p=()=>{const h=s.map(m=>{const y=t.find(v=>v.id===m.fieldId);return y?y.kind==="text"?{fieldId:m.fieldId,value:""}:y.kind==="pick-multi"?y.multi?{fieldId:m.fieldId,value:[]}:{fieldId:m.fieldId,value:"Any"}:y.kind==="multi-select"?{fieldId:m.fieldId,value:[]}:m:m});o(h)};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),actionRow:a.jsxs(a.Fragment,{children:[a.jsx(Gn,{children:a.jsxs(Gn.Start,{children:[a.jsx(jPs,{}),a.jsx(bJt,{fields:t,tokens:s,onTokensChange:o,disabled:n,onStartTextFilter:l})]})}),a.jsx(NPs,{isLoading:n,filterFields:t,filterTokens:s,onFilterTokensChange:o,onClear:p,onRemoveAll:()=>o([]),onSave:d,onRemoveSaved:c?f:void 0,autoFocusFilterFieldId:i})]}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),e]})}function APs({error:e}){return _s(e)?a.jsx(Qs,{}):js(e)?a.jsx(Fs,{resource:"metrics"}):a.jsx(un,{tone:"error",titleSlot:"Failed to load storage capabilities",descriptionSlot:e.message})}const bit=_Jt({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function RPs({children:e}){const{supportsMetrics:t,isLoading:n,error:r}=F6();return n?a.jsx(i1e,{filterFields:bit,isLoading:!0,children:a.jsxs("div",{className:"flex h-full items-center justify-center gap-2",children:[a.jsx(Cn,{"aria-label":"Loading storage capabilities"}),a.jsx("span",{className:"text-caption text-muted-foreground",children:"Loading storage capabilities"})]})}):r?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx("div",{className:"flex h-full items-center justify-center",children:a.jsx(APs,{error:r})})]}):t?e:a.jsx(i1e,{filterFields:bit,children:a.jsx(un,{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:a.jsx(ae,{variant:"ghost",render:a.jsx("a",{href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer"}),icon:a.jsx(Ts,{}),children:"Metrics Documentation"}),variant:"fill"})})}function PPs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:o}){const i=!!e&&e.length>0;return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.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?bm(l):"—":c.size===1?u=l>0?bm(l,[...c][0]):"—":u="Mixed",a.jsx(tr.Summary,{value:u,label:"Total cost"})})(),s?a.jsx(tr.Actions,{children:s}):null]}),t?a.jsx(tr.Loading,{}):n?a.jsx(tr.Error,{message:"Failed to load model usage data"}):a.jsx(tr.Content,{children:i?a.jsxs(Oe,{columns:"auto auto auto auto auto auto",...o1e,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{sticky:"start",children:"Model"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Input"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Output"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cache Read"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cache Write"}),a.jsx(Oe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=a.jsxs(a.Fragment,{children:[a.jsx(Oe.RowHeaderCell,{className:"text-caption",children:l.model}),a.jsx(Oe.NumberCell,{children:l.input}),a.jsx(Oe.NumberCell,{children:l.output}),a.jsx(Oe.NumberCell,{children:l.cacheRead}),a.jsx(Oe.NumberCell,{children:l.cacheWrite}),a.jsx(Oe.NumberCell,{highlight:!0,children:l.cost!=null?bm(l.cost,l.costUnit):"—"})]});return c?a.jsx(Oe.RowLink,{to:c,LinkComponent:o,children:u},l.model):a.jsx(Oe.RowStatic,{children:u},l.model)})]}):a.jsx(tr.NoData,{message:"No model usage data yet"})})]})}function $Ps(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,o,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||!o||!i)return[];const l=new Map,c=d=>FR(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 o.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:$l(f.input),output:$l(f.output),cacheRead:$l(f.cacheRead),cacheWrite:$l(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function MPs(){const{data:e,isLoading:t,isError:n}=$Ps(),{getTracesHref:r}=BR(),{Link:s}=dn();return a.jsx(PPs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:lu.AGENT}),actions:a.jsx(V6,{href:r({rootEntityType:lu.AGENT}),LinkComponent:s})})}function DPs(e){const t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim())?.[1];if(!t)return;const n=t.length===3?[...t].map(s=>s+s).join(""):t,r=s=>{const o=parseInt(n.slice(s,s+2),16)/255;return o<=.03928?o/12.92:((o+.055)/1.055)**2.4};return .2126*r(0)+.7152*r(2)+.0722*r(4)}function LPs(e){const t=e?DPs(e):void 0;return t!==void 0&&t>.25}function a1e({data:e,segments:t,maxVal:n,fmt:r,className:s,LinkComponent:o="a"}){const i=[...e].sort((c,u)=>{const d=u.values.reduce((p,h)=>p+h,0),f=c.values.reduce((p,h)=>p+h,0);return d-f}),l=t.length>1;return a.jsxs(Hr,{className:W("size-full",s),children:[a.jsxs("div",{className:"mt-2 mb-4 flex items-center gap-3",children:[a.jsx("div",{className:"flex flex-1 items-center gap-4",children:t.map(c=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"size-2 rounded-full",style:{backgroundColor:c.color}}),a.jsx("span",{className:"text-caption text-muted-foreground",children:c.label})]},c.label))}),a.jsx("span",{className:"shrink-0 pr-2 text-caption text-placeholder",children:"Total"})]}),a.jsx("div",{className:"grid gap-3.5",children:i.map(c=>{const u=c.values.reduce((h,m)=>h+m,0),d=`${n>0?u/n*100:0}%`,f=LPs(t[c.values.findIndex(h=>h>0)]?.color),p=a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"relative h-full min-w-0 flex-1",style:{"--bar-width":d},children:[a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("div",{className:W("absolute inset-y-0 left-0",c.href?"cursor-pointer":"cursor-default"),style:{width:d},children:t.map((h,m)=>{const y=c.values[m]??0,v=u>0?y/u*100:0,b=c.values.slice(0,m).reduce((_,C)=>_+(u>0?C/u*100:0),0),x=c.values.slice(m+1).every(_=>!_),w=c.href?void 0:c.hrefs?.[m],k=a.jsx("div",{className:W("absolute inset-y-0 opacity-40 dark:opacity-100",l&&m===0&&"rounded-l",l&&x&&"rounded-r",!l&&"rounded",w&&"cursor-pointer transition-opacity hover:opacity-70"),style:{left:l?`${b}%`:0,width:l?`${v}%`:`${v}%`,backgroundColor:h.color}});return w?a.jsx(o,{href:w,"aria-label":`${c.name} — ${h.label}`,className:"contents",children:k},h.label):a.jsx(FPs,{children:k},h.label)})})}),a.jsx(kn,{side:"top",className:"font-mono",children:a.jsx("div",{className:"grid gap-1",children:t.map((h,m)=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:h.label}),a.jsx("span",{className:"ml-auto pl-3",children:r(c.values[m]??0)})]},h.label))})})]}),a.jsx("div",{className:W("pointer-events-none absolute inset-0 z-10",f&&"dark:[clip-path:inset(0_0_0_var(--bar-width))]"),children:a.jsx("span",{className:"absolute inset-y-0 left-2.5 flex items-center truncate text-caption text-muted-foreground",children:c.name})}),f&&a.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-y-0 left-0 z-10 hidden w-(--bar-width) overflow-hidden dark:block",children:a.jsx("span",{className:"absolute inset-y-0 left-2.5 flex items-center text-caption whitespace-nowrap text-placeholder",children:c.name})})]}),a.jsx("span",{className:"shrink-0 pr-3 text-body text-muted-foreground tabular-nums",children:r(u)})]});return c.href?a.jsx(o,{href:c.href,className:"flex h-6 cursor-pointer items-center gap-14 rounded transition-colors outline-none hover:bg-fill-subtle focus-visible:bg-fill-subtle",children:p},c.name):a.jsx("div",{className:"flex h-6 items-center gap-14",children:p},c.name)})})]})}function FPs({children:e}){return a.jsx(a.Fragment,{children:e})}function zPs(e){return e==="tokens"||e==="cost"}function BPs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:o}){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,y=h?f.reduce((b,x)=>b+(x.cost??0),0):0,v=h&&y>0;return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&v?a.jsx(tr.Summary,{value:bm(y,m),label:"Total cost"}):a.jsx(tr.Summary,{value:$l(d),label:"Total tokens"})),u&&s?a.jsx(tr.Actions,{children:s}):null]}),t?a.jsx(tr.Loading,{}):n?a.jsx(tr.Error,{message:"Failed to load token usage data"}):a.jsx(tr.Content,{children:u?a.jsxs(ll,{defaultTab:"tokens",value:i,onValueChange:b=>{zPs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"tokens",children:"Tokens"}),a.jsx(Lr,{value:"cost",children:"Cost"})]}),a.jsx(Ss,{value:"tokens",className:"pt-3",children:a.jsx(a1e,{LinkComponent:o,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:By.blueDark},{label:"Output",color:By.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:$l})}),a.jsx(Ss,{value:"cost",className:"pt-3",children:v?a.jsx(a1e,{LinkComponent:o,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:By.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>bm(b,m)}):a.jsx(tr.NoData,{message:"No cost data yet"})})]}):a.jsx(tr.NoData,{message:"No token usage data yet"})})]})}function UPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,o]=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=>FR(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 o.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 VPs(){const{data:e,isLoading:t,isError:n}=UPs(),{getTracesHref:r}=BR(),{Link:s}=dn();return a.jsx(BPs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:o=>r({rootEntityType:lu.AGENT,entityName:o.name}),actions:a.jsx(V6,{href:r({rootEntityType:lu.AGENT}),LinkComponent:s})})}function l1e(e,t=$l){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const xit=[{dataKey:"input",label:"Input tokens",color:By.blue,aggregate:l1e("input")},{dataKey:"output",label:"Output tokens",color:By.yellow,aggregate:l1e("output")}];function qPs(e){return e==="tokens"||e==="cost"}function HPs({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[o,i]=g.useState("tokens"),l=e??[],c=l.map(w=>({...w})),u=l.length>0,d=l.filter(w=>w.cost!=null&&w.cost>0),f=d.map(w=>({...w})),p=new Set(d.map(w=>w.costUnit).filter(w=>!!w)),h=p.size===1&&d.every(w=>w.costUnit!=null),m=h?[...p][0]??null:null,y=h?d.reduce((w,k)=>w+(k.cost??0),0):0,v=h&&y>0,b=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",x=[{dataKey:"cost",label:"Cost",color:By.purple,aggregate:l1e("cost",w=>bm(w,m))}];return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Token usage over time",description:b}),u&&s?a.jsx(tr.Actions,{children:s}):null]}),n?a.jsx(tr.Loading,{}):r?a.jsx(tr.Error,{message:"Failed to load token usage timeline"}):a.jsx(tr.Content,{children:u?a.jsxs(ll,{defaultTab:"tokens",value:o,onValueChange:w=>{qPs(w)&&i(w)},className:"overflow-visible",children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 [&>:first-child]:w-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"tokens",children:"Tokens"}),a.jsx(Lr,{value:"cost",children:"Cost"})]}),o==="tokens"?a.jsx(WW,{data:c,series:xit}):v?a.jsx(WW,{data:f,series:x}):null]}),a.jsx(Ss,{value:"tokens",className:"pt-3",children:a.jsx(s1e,{data:c,series:xit,showLegend:!1})}),a.jsx(Ss,{value:"cost",className:"pt-3",children:v?a.jsx(s1e,{data:f,series:x,showLegend:!1}):a.jsx(tr.NoData,{message:"No cost data yet"})})]}):a.jsx(tr.NoData,{message:"No token usage data yet"})})]})}function wit(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const o=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};o[n]+=r.value,r.estimatedCost!=null&&(o.cost=(o.cost??0)+r.estimatedCost,t?.costUnit?o.costUnits.add(t.costUnit):o.hasUnknownCostUnit=!0),e.set(s,o)}}function WPs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function ZPs(){const e=Xe(),{timestamp:t,filters:n,filterKey:r}=sg(),s=PJt(t);return wt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[o,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 wit(l,o.series[0],"input"),wit(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:$Jt(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:WPs(u)}}),interval:s}}})}function GPs(){const{data:e,isLoading:t,isError:n}=ZPs(),{getTracesHref:r}=BR(),{Link:s}=dn();return a.jsx(HPs,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:a.jsx(V6,{href:r(),LinkComponent:s})})}function Sce({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return a.jsx(a1e,{LinkComponent:r,data:e.map(s=>{const o=n?.(s),i=t?.(s);return o?{name:s.name,values:[s.completed,s.errors],hrefs:[i,o]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:By.blueDark},{label:"Errors",color:By.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:$l})}function QPs({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:o,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof o=="function"?o(l):o,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,y)=>m+y.completed+y.errors,0):0,p=m=>r?y=>r(m,y):void 0,h=m=>s?y=>s(m,y):void 0;return a.jsxs(tr,{children:[a.jsxs(tr.TopBar,{children:[a.jsx(tr.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&a.jsx(tr.Summary,{value:$l(f),label:"Total runs"}),u?a.jsx(tr.Actions,{children:u}):null]}),t?a.jsx(tr.Loading,{}):n?a.jsx(tr.Error,{message:"Failed to load trace volume data"}):a.jsx(tr.Content,{children:d?a.jsxs(ll,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[a.jsxs(al,{children:[a.jsx(Lr,{value:"agents",children:"Agents"}),a.jsx(Lr,{value:"workflows",children:"Workflows"}),a.jsx(Lr,{value:"tools",children:"Tools"})]}),a.jsx(Ss,{value:"agents",className:"pt-3",children:e.agentData.length>0?a.jsx(Sce,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):a.jsx(tr.NoData,{message:"No agent data yet"})}),a.jsx(Ss,{value:"workflows",className:"pt-3",children:e.workflowData.length>0?a.jsx(Sce,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):a.jsx(tr.NoData,{message:"No workflow data yet"})}),a.jsx(Ss,{value:"tools",className:"pt-3",children:e.toolData.length>0?a.jsx(Sce,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):a.jsx(tr.NoData,{message:"No tool data yet"})})]}):a.jsx(tr.NoData,{message:"No trace volume data yet"})})]})}async function kce(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const o of r.groups){const i=o.dimensions.entityName??"unknown",l=o.dimensions.status??"ok",c=FR(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=o.value:c.completed+=o.value}return Array.from(s.entries()).map(([o,i])=>({name:o,...i})).sort((o,i)=>i.completed+i.errors-(o.completed+o.errors))}function YPs(){const e=Xe(),{filters:t,filterKey:n}=sg();return wt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,o]=await Promise.all([kce(e,"mastra_agent_duration_ms",t),kce(e,"mastra_workflow_duration_ms",t),kce(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:o}}})}const dB={agents:lu.AGENT,workflows:lu.WORKFLOW_RUN,tools:lu.TOOL};function KPs(){const{data:e,isLoading:t,isError:n}=YPs(),{getTracesHref:r,getLogsHref:s}=BR(),{Link:o}=dn();return a.jsx(QPs,{data:e,isLoading:t,isError:n,LinkComponent:o,getRowHref:(i,l)=>r({rootEntityType:dB[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:dB[i],entityName:l.name,status:"error"}):void 0,actions:i=>a.jsxs(a.Fragment,{children:[a.jsx(V6,{href:r({rootEntityType:dB[i]}),LinkComponent:o}),a.jsx(HRs,{href:s({rootEntityType:dB[i],status:"error"}),LinkComponent:o})]})})}const Oce="period",fB="dateFrom",pB="dateTo";function XPs(){const[e,t]=so(),n=e.get(Oce),r=zRs(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(fB)),p=d(e.get(pB));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),o=g.useMemo(()=>RRs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Oce):p.set(Oce,d),d!=="custom"&&(p.delete(fB),p.delete(pB)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(fB,d.from.toISOString()):p.delete(fB),d?.to?p.set(pB,d.to.toISOString()):p.delete(pB),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return $Rs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,ARs(e)))return;const d=OJt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),a.jsx(URs,{preset:r,filterTokens:o,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:a.jsx(RPs,{children:a.jsx(JPs,{})})})}function JPs(){const{error:e,isLoading:t}=TJt(),{isInMemory:n}=F6(),{data:r,isLoading:s}=SJt(),{data:o,isLoading:i}=WMe(),{data:l,isLoading:c}=wJt(),{data:u,isLoading:d}=ZMe(),f=g.useMemo(()=>_Jt({availableTags:r??[],availableEntityNames:o??[],availableServiceNames:l??[],availableEnvironments:u??[],loading:{tags:s,entityNames:i,serviceNames:c,environments:d}}),[r,o,l,u,s,i,c,d]);return e&&_s(e)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Qs,{variant:"fill"})]}):e&&js(e)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(Fs,{variant:"fill",resource:"metrics"})]}):e?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:rD}),children:[a.jsx("h1",{className:"sr-only",children:"Metrics"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load metrics",descriptionSlot:e.message})]}):a.jsx(i1e,{filterFields:f,isLoading:t,children:a.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[n&&a.jsx(Jt,{variant:"info",title:"Metrics are not persisted",children:a.jsx(Jt.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."})}),a.jsxs(TRs,{children:[a.jsx(wPs,{}),a.jsx(SPs,{}),a.jsx(kPs,{}),a.jsx(OPs,{}),a.jsx(_Ps,{})]}),a.jsxs(jRs,{children:[a.jsx(MPs,{}),a.jsx(VPs,{}),a.jsx(GPs,{}),a.jsx(gPs,{}),a.jsx(KPs,{}),a.jsx(dPs,{})]})]})})}function e$s(){const{isCmsAvailable:e}=kb(),{paths:t}=dn();return e?a.jsx(mK,{href:t.cmsPromptBlockCreateLink(),tooltip:"Create a prompt",children:"New prompt"}):null}const lM=[Wr("/prompts")],t$s=50,n$s=["updatedAt"];function r$s(){const[e,t]=g.useState(""),[n,r]=g.useState(0),[s,o]=so(),{sort:i,onSortChange:l}=fk({searchParams:s,setSearchParams:o,allowedKeys:n$s}),c=g.useMemo(()=>i?{field:i.key,direction:i.direction==="asc"?"ASC":"DESC"}:void 0,[i]),{data:u,isLoading:d,error:f,isPlaceholderData:p}=wQt({page:n,perPage:t$s,orderBy:c}),h=u?.promptBlocks??[],m=u?.hasMore??!1,y=g.useCallback(()=>{p||r(w=>w+1)},[p]),v=g.useCallback(()=>{p||r(w=>Math.max(0,w-1))},[p]),b=g.useCallback(w=>{t(w),r(0)},[]),x=g.useCallback((w,k)=>{l(w,k),r(0)},[l]);return f&&_s(f)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Qs,{variant:"fill"})]}):f&&js(f)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(Fs,{variant:"fill",resource:"prompt blocks"})]}):f?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load prompt blocks",descriptionSlot:f.message})]}):h.length===0&&!d&&n===0?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(rxs,{})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:lM}),headerActions:a.jsx(e$s,{}),actionRow:a.jsx(Gn,{children:a.jsx(Gn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{onSearch:b,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),children:[a.jsx("h1",{className:"sr-only",children:"Prompts"}),a.jsx(nxs,{promptBlocks:h,isLoading:d,search:e,currentPage:n,hasMore:m,onNextPage:y,onPrevPage:v,updatedSort:i?.direction,onSortChange:x})]})}const s$s=[Wr("/request-context")];function o$s(){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:s$s}),children:[a.jsx("h1",{className:"sr-only",children:"Request Context"}),a.jsx("div",{children:a.jsx(fms,{children:a.jsx(pSe,{})})})]})}const i$s=[Wr("/resources")],a$s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:A$n,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:dSt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Ts,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:E3,href:"https://discord.gg/mastra-ai",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:ySt,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:r_e,href:"https://mastra.ai/contact?ref=studio",external:!0}];function l$s(){return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:i$s}),children:[a.jsx("h1",{className:"sr-only",children:"Resources"}),a.jsx("div",{children:a.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:a$s.map(e=>a.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group state-layer flex flex-col gap-3 rounded-lg border border-border bg-background p-5 hover:border-accent1",children:[a.jsxs("div",{className:"flex items-center gap-2.5",children:[a.jsx(e.icon,{className:W("h-5 w-5 text-muted-foreground group-hover:text-accent1",vn)}),a.jsx("span",{className:"text-subheading text-foreground",children:e.title}),e.external&&a.jsx(Ts,{className:"ml-auto h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]}),a.jsx("p",{className:"text-text3 text-caption",children:e.description})]},e.href))})})]})}function Sit(){const{isCmsAvailable:e}=kb(),{paths:t}=dn();return e?a.jsx(mK,{href:t.cmsScorersCreateLink(),tooltip:"Create a scorer",children:"New scorer"}):null}const cM=[Wr("/scorers")];function c$s(){const{data:e={},isLoading:t,error:n}=lh(),[r,s]=g.useState(""),[o,i]=g.useState("all"),[l,c]=g.useState();if(n&&_s(n))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Qs,{variant:"fill"})]});if(n&&js(n))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Fs,{variant:"fill",resource:"scorers"})]});if(n)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load scorers",descriptionSlot:n.message})]});if(Object.keys(e).length===0&&!t)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),headerActions:a.jsx(Sit,{}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Fgs,{})]});const u=o!=="all"||r!=="",d=()=>{s(""),i("all")};return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:cM}),headerActions:a.jsx(Sit,{}),actionRow:a.jsx(Bgs,{search:r,onSearchChange:s,sourceFilter:o,onSourceFilterChange:i,onReset:d,hasActiveFilters:u}),children:[a.jsx("h1",{className:"sr-only",children:"Scorers"}),a.jsx(Lgs,{scorers:e,isLoading:t,search:r,sourceFilter:o,sort:l,onSortChange:(f,p)=>c({key:p,direction:f})})]})}const MJt=["input","entity"],u$s={input:"Input",entity:"Entity"};function d$s(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function f$s(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(MJt.filter(o=>!e.has(o))),[e]),r=g.useMemo(()=>d$s(n),[n]),s=g.useCallback(o=>{t(i=>{const l=new Set(i);return l.has(o)?l.delete(o):l.add(o),l})},[]);return{visibleColumns:n,columns:r,toggleColumn:s}}function p$s({visibleColumns:e,toggleColumn:t}){return a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{icon:a.jsx(Vve,{}),children:"Columns"})}),a.jsxs(pt.Content,{align:"end",children:[a.jsx(pt.Label,{children:"Toggle columns"}),MJt.map(n=>a.jsx(pt.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:u$s[n]},n))]})]})}const kit=[Wr("/scorers"),xqn],h$s=["date","score"];function m$s(){const{scorerId:e}=fr(),[t,n]=so(),r=t.get("scoreId")??void 0,[s,o]=g.useState(r),[i,l]=g.useState(!1),c=zr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:p}=eqn(e),h=f$s(),{data:m={},isLoading:y,error:v}=ef(),{isLoading:b,error:x}=ih(),{sort:w,onSortChange:k}=fk({searchParams:t,setSearchParams:n,allowedKeys:h$s}),{data:_=[],isLoading:C,error:T,isFetchingNextPage:E,hasNextPage:I,setEndOfListElement:N}=JVn({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),A=g.useMemo(()=>G0(_,w,{date:K=>K.createdAt,score:K=>typeof K.score=="number"?K.score:void 0}),[_,w]),P=g.useMemo(()=>f?.agentIds?.filter(K=>m[K]).map(K=>({value:K,label:m[K].name,type:"AGENT"}))||[],[f?.agentIds,m]),F=g.useMemo(()=>f?.workflowIds?.map(K=>({value:K,label:K,type:"WORKFLOW"}))||[],[f?.workflowIds]),D=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...P,...F],[P,F]),H=t.get("entity")??"all",q=D.find(K=>K.value===H);q&&q.value!==u?.value&&d(q),g.useEffect(()=>{if(p){const K=p instanceof Error?p.message:"Failed to load scorer";Qe.error(`Error loading scorer: ${K}`)}},[p]),g.useEffect(()=>{if(v){const K=v instanceof Error?v.message:"Failed to load agents";Qe.error(`Error loading agents: ${K}`)}},[v]),g.useEffect(()=>{if(x){const K=x instanceof Error?x.message:"Failed to load workflows";Qe.error(`Error loading workflows: ${K}`)}},[x]);const V=K=>{K?.value&&n(ee=>{const ne=new URLSearchParams(ee);return ne.set("entity",K.value),ne})};g.useEffect(()=>{const K=t.get("scoreId")??void 0;if(K===s)return;if(!K){o(void 0);return}A.find(ne=>ne.id===K)&&o(K)},[t,A]);const B=g.useCallback(K=>{o(K||void 0),n(ee=>{const ne=new URLSearchParams(ee);return K?ne.set("scoreId",K):ne.delete("scoreId"),ne})},[n]);if(!f)return null;const Z=_s(p)||_s(v)||_s(x),z=p&&js(p),Y=!Z&&!z&&(p||v||x),L=!C&&A.length===0,R=u?.value!=="all",M=f?.source==="stored",U=e?a.jsx(ZX,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:K=>{c(`/experiments/${K}`)}}):null,Q=M?a.jsxs(pt,{children:[a.jsx(pt.Trigger,{asChild:!0,children:a.jsx(ae,{size:"lg","aria-label":"Scorer actions menu",children:a.jsx(U1,{})})}),a.jsx(pt.Content,{align:"end",className:"w-48",children:a.jsxs(pt.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[a.jsx(Bd,{})," Edit Scorer"]})})]}):null;if(Z||z||Y||L&&!R){const K=(p instanceof Error?p.message:void 0)??(v instanceof Error?v.message:void 0)??(x instanceof Error?x.message:void 0)??"An unexpected error occurred",ee=Z||z||Y;return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:kit}),actionRow:!ee&&Q?a.jsx(Gn,{children:a.jsx(Gn.End,{children:Q})}):void 0,children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"flex h-full items-center justify-center",children:Z?a.jsx(Qs,{}):z?a.jsx(Fs,{resource:"scorers"}):Y?a.jsx(un,{tone:"error",titleSlot:"Failed to load scorer",descriptionSlot:K}):a.jsx($gs,{onRunExperiment:()=>l(!0)})}),U]})}return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:kit}),actionRow:a.jsxs(Gn,{children:[a.jsx(Gn.Start,{children:a.jsx(Mgs,{selectedEntity:u,entityOptions:D,onEntityChange:V,onReset:()=>{n(K=>{const ee=new URLSearchParams(K);return ee.set("entity","all"),ee})},isLoading:C||y||b})}),a.jsxs(Gn.End,{children:[a.jsx(p$s,{visibleColumns:h.visibleColumns,toggleColumn:h.toggleColumn}),a.jsx(ae,{variant:"primary",onClick:()=>l(!0),icon:a.jsx(bu,{}),children:"Run Experiment"}),Q]})]}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Pgs,{scores:A,isLoading:C,selectedScoreId:s,isFetchingNextPage:E,hasNextPage:I,setEndOfListElement:N,onScoreClick:B,errorMsg:T?.message,columnsState:h,sort:w,onSortChange:k}),U]})}const g$s=[{value:"system",label:"System",icon:a.jsx(MSt,{})},{value:"light",label:"Light",icon:a.jsx(KDn,{})},{value:"dark",label:"Dark",icon:a.jsx(E2n,{})}],v$s={md:{itemGap:2,itemWidth:28,root:"gap-0.5 p-0.5",indicator:"inset-y-0.5 left-0.5",item:"h-6 [&_svg]:size-3.5"},xs:{itemGap:1,itemWidth:20,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-4 [&_svg]:size-icon-xs"},sm:{itemGap:1,itemWidth:24,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-5 [&_svg]:size-icon-xs"}},y$s=({value:e,onChange:t,options:n=g$s,size:r="md",className:s,"aria-label":o="Theme",...i})=>{const{theme:l,setTheme:c}=M3(),u=e??l,d=t??c,f=n.some(v=>v.value===u)?u:n[0]?.value??"system",p=v=>{const b=n.find(x=>x.value===v);b&&d(b.value)},h=Math.max(0,n.findIndex(v=>v.value===f)),m=v$s[r],y=h*(m.itemWidth+m.itemGap);return a.jsxs(g7t,{...i,value:f,onValueChange:p,"aria-label":o,className:W(ir,"relative inline-flex w-fit items-center rounded-full",m.root,s),children:[a.jsx("span",{"aria-hidden":"true",className:W("pointer-events-none absolute rounded-full bg-fill-hover motion-reduce:transition-none",vo.transform,m.indicator),style:{width:m.itemWidth,transform:`translateX(${y}px)`}}),n.map(v=>a.jsx(m7t,{value:v.value,"aria-label":v.label,style:{width:m.itemWidth},className:W("relative inline-flex cursor-pointer items-center justify-center rounded-full","text-muted-foreground hover:text-foreground data-[checked]:text-foreground",m.item,"focus-visible:outline-hidden","active:scale-90 motion-reduce:transition-none",vo.colors,vo.transform),children:a.jsx("span",{"aria-hidden":"true",className:"pointer-events-none inline-flex items-center justify-center",children:v.icon})},v.value))]})},b$s=[Wr("/settings")],x$s=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=N3();return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:b$s}),children:[a.jsx("h1",{className:"sr-only",children:"Settings"}),a.jsx(cvs,{children:a.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[a.jsxs(nrt,{children:[a.jsxs(rrt,{children:[a.jsx(srt,{children:"General"}),a.jsx(ort,{children:"Stored in this browser."})]}),a.jsx(IGt,{children:a.jsx(ySe,{label:"Theme",description:"Customize the appearance of the studio.",children:a.jsx(y$s,{})})})]}),a.jsxs(nrt,{children:[a.jsxs(rrt,{children:[a.jsx(srt,{children:"Mastra Connection"}),a.jsx(ort,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),a.jsx(VGt,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})]})};function w$s(){const[e]=so(),t=zr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return a.jsx(hJt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function S$s(e){return e.replace(/\/$/,"").split("/").pop()}function k$s({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?a.jsx("div",{className:W("grid gap-y-4",n),children:Array.from({length:5}).map((o,i)=>a.jsx("div",{className:"h-16 animate-pulse rounded-lg bg-card"},i))}):a.jsx("div",{className:W("grid gap-y-4",n),children:e.map(o=>{const i=o?.agents||o?.tools||o?.networks||o?.workflows||o?.mcp;return a.jsxs("article",{className:W(ir,"state-layer grid w-full grid-cols-[1fr_auto] overflow-hidden rounded-lg"),children:[a.jsxs(s,{to:`/templates/${o.slug}`,className:W("group grid",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":o.imageURL}),children:[o.imageURL&&a.jsx("div",{className:W("overflow-hidden"),children:a.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${o.imageURL})`}})}),a.jsxs("div",{className:W("grid w-full gap-0.5 px-4 py-3","[&_svg]:h-[1em] [&_svg]:w-[1em] [&_svg]:text-muted-foreground"),children:[a.jsx("h2",{className:"text-body text-foreground",children:o.title}),a.jsx("p",{className:W("text-body",Ky,vn),children:o.description}),a.jsxs("div",{className:"mt-3 hidden flex-wrap items-center gap-4 text-body text-muted-foreground 2xl:flex",children:[i&&a.jsxs("ul",{className:W("m-0 flex list-none gap-4 p-0 text-body text-muted-foreground","text-muted-foreground [&>li]:flex [&>li]:items-center [&>li]:gap-0.5"),children:[o?.agents&&o.agents.length>0&&a.jsxs("li",{children:[a.jsx(Pi,{})," ",o.agents.length]}),o?.tools&&o.tools.length>0&&a.jsxs("li",{children:[a.jsx(Hd,{})," ",o.tools.length]}),o?.networks&&o.networks.length>0&&a.jsxs("li",{children:[a.jsx(DSt,{})," ",o.networks.length]}),o?.workflows&&o.workflows.length>0&&a.jsxs("li",{children:[a.jsx(q1,{})," ",o.workflows.length]}),o?.mcp&&o.mcp.length>0&&a.jsxs("li",{children:[a.jsx(sE,{})," ",o.mcp.length]})]}),i&&o.supportedProviders&&a.jsx("small",{children:"|"}),a.jsx("div",{className:"flex items-center gap-4 text-muted-foreground",children:o.supportedProviders.map(l=>a.jsx("span",{className:"",children:l},l))})]})]})]}),a.jsx("a",{href:o.githubUrl,className:W("group ml-auto hidden items-center gap-2 pr-4 text-body","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:a.jsxs("span",{className:W("flex items-center gap-2 rounded bg-sidebar px-2 py-1",Xwt,Ky,vn),children:[a.jsx(hK,{})," ",S$s(o.githubUrl)]})})]},o.slug)})})}function O$s({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:o,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?a.jsxs("div",{className:W("flex h-[6.5rem] items-center gap-5","[&>div]:h-8 [&>div]:w-48 [&>div]:animate-pulse [&>div]:bg-card",u),children:[a.jsx("div",{})," ",a.jsx("div",{})," ",a.jsx("div",{})]}):a.jsxs("div",{className:W("sticky top-0 mx-auto flex flex-wrap gap-4 bg-background py-5",u),children:[a.jsx(nL,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),a.jsx(wu,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),a.jsx(wu,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:o,options:n}),c&&a.jsx(ae,{onClick:c,icon:a.jsx(Gt,{}),children:"Reset"})]})}const _$s=[{id:"templates",label:"Templates"}];function C$s(){const{data:e,isLoading:t}=Evr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[o,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,w)=>{w==="tag"?i(x):w==="provider"&&c(x)},m=x=>{d(x)},y=()=>{i("all"),c("all"),d("")},v=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||o!=="all"&&!x.tags.includes(o)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||o!=="all"||l!=="all";return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:_$s}),children:[a.jsx("h1",{className:"sr-only",children:"Templates"}),a.jsx(I3,{children:a.jsxs(b1t,{children:[a.jsx(_t,{children:a.jsx(zx,{})}),"Templates"]})}),a.jsxs("div",{className:W("z-10 h-full w-full overflow-y-auto px-5 pb-12"),children:[a.jsx(O$s,{selectedTag:o,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?y:void 0,className:"max-w-[80rem]",isLoading:t}),a.jsx(k$s,{templates:v,linkComponent:ml,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const E$s="1.71.0";function tJ({children:e,className:t}){return a.jsx("div",{className:W("transition-height mt-12 rounded-lg border border-border px-4 py-5 lg:min-h-[25rem] lg:px-12",t),children:e})}function T$s({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,o=()=>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:a.jsx(cu,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:a.jsx(H$n,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return a.jsxs(tJ,{className:"mb-5 content-center space-y-4 text-muted-foreground",children:[a.jsxs("div",{className:W("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[l,a.jsxs("div",{className:"space-y-2 text-center",children:[a.jsx("p",{className:"text-subheading text-foreground",children:c}),a.jsx("p",{className:"text-body text-muted-foreground",children:o()})]})]}),t&&t.length>0&&a.jsxs("details",{className:"text-caption",children:[a.jsxs("summary",{className:W(Pn,"cursor-pointer text-center select-none"),children:["Show Validation Issues (",t.length,")"]}),a.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-muted p-3 text-left text-caption",children:t.map((u,d)=>a.jsxs("div",{className:"border-l-2 border-destructive pl-2",children:[a.jsx("div",{className:"font-medium text-destructive",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),a.jsx("pre",{className:"mt-1 text-caption wrap-break-word whitespace-pre-wrap text-muted-foreground",children:u.message})]},d))})]}),n&&!s&&a.jsxs("details",{className:"text-caption",children:[a.jsx("summary",{className:W(Pn,"cursor-pointer text-center select-none"),children:"Show Details"}),a.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-muted p-3 text-left text-caption",children:a.jsx("pre",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}const j$s=g.createContext(null);function N$s(){const e=g.useContext(j$s);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const DJt=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{const[s]=g.useState(e),[o]=g.useState(t),[i,l]=g.useState(t),[c,u]=g.useState(e||""),[d,f]=g.useState(!1),[p,h]=g.useState(!1),[m,y]=g.useState(!1),{data:v,isLoading:b}=q5(),x=T0(),{models:w}=U0(),k=g.useMemo(()=>v?.providers||[],[v]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const _=si(c),T=bN(k,_)?.id||_,E=async D=>{if(l(D),D&&T){f(!0);try{const H=await n({provider:T,modelId:D});console.info("Model updated:",H)}catch(H){console.error("Failed to update model:",H)}finally{f(!1)}}},I=D=>{const H=si(D);u(H),H!==_&&(l(""),y(!0))},{registerResetFn:N}=N$s();if(g.useEffect(()=>(N(()=>{if(p||m)return;if(_&&_!==s&&(!i||i==="")){u(si(s)),l(o);const B=bN(k,s)?.id||s;B&&o&&n({provider:B,modelId:o}).catch(Z=>{console.error("Failed to reset model:",Z)})}}),()=>{N(null)}),[N,_,i,s,o,n,p,m,k]),b)return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Cn,{}),a.jsx("span",{className:"text-body text-muted-foreground",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(D){console.error("Failed to reset model:",D)}finally{f(!1)}},P=bN(k,_);if(x.active&&x.pickerVisible===!1){const D=x.default&&x.default.provider&&x.default.modelId?`${x.default.provider}/${x.default.modelId}`:c&&i?`${c}/${i}`:"Locked by admin";return a.jsxs("div",{className:W(ir,"flex items-center gap-2 rounded-md px-3 py-2"),"data-testid":"agent-metadata-model-locked",children:[a.jsx(ed,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a.jsx("span",{className:"truncate text-caption text-foreground",children:D}),a.jsx("span",{className:"ml-auto shrink-0 text-meta text-muted-foreground",children:"Set by admin"})]})}const F=!!(_&&i)&&x.active&&x.allowed!==void 0&&!w.some(D=>si(D.provider)===_&&D.model===i);return a.jsxs("div",{className:"@container",children:[a.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[a.jsx("div",{className:"w-full @xs:w-2/5",children:a.jsx(rk,{value:_,onValueChange:I,open:p,onOpenChange:h})}),a.jsx("div",{className:"w-full @xs:w-3/5",children:a.jsx(sk,{llmId:_,value:i,onValueChange:E,open:m,onOpenChange:y})}),a.jsx(ae,{variant:"default",size:"md",onClick:A,disabled:d,className:"flex items-center gap-1.5 border-0! text-caption whitespace-nowrap",title:"Reset to original model",children:a.jsx(QC,{className:"h-3.5 w-3.5"})})]}),F&&a.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:a.jsx(Jt,{variant:"warning",title:"Model not allowed",children:a.jsxs(Jt.Message,{children:[a.jsxs("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:[c,"/",i]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),P&&!P.connected&&a.jsx("div",{className:"p-2 pt-2",children:a.jsx(Jt,{variant:"warning",title:"Provider not connected",children:a.jsxs(Jt.Message,{children:["Set the"," ",a.jsx("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:Array.isArray(P.envVar)?P.envVar.join(", "):P.envVar})," ","environment"," ",Array.isArray(P.envVar)&&P.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function I$s({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:o,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return a.jsx(tJ,{children:a.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5",children:[a.jsxs("h2",{className:W("flex items-center gap-2 text-heading text-muted-foreground","[&_svg]:h-[1.2em] [&_svg]:opacity-70 [&>svg]:w-[1.2em]"),children:["Install Template ",a.jsx(LSt,{})]}),a.jsx(wu,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-body text-muted-foreground",children:"Set required Environmental Variables"}),a.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?a.jsxs("div",{className:W("col-span-2 flex items-center justify-center gap-4 text-caption text-muted-foreground","[&_svg]:h-[1.1em] [&_svg]:w-[1.1em] [&_svg]:opacity-50","animate-in duration-300 fade-in"),children:[a.jsx(Cn,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>a.jsxs(g.Fragment,{children:[a.jsx(qi,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),a.jsx(qi,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),a.jsxs("div",{className:"relative mt-3.5 border-t border-border pt-12",children:[a.jsx("div",{className:"absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full bg-background text-caption text-muted-foreground",children:"And"}),a.jsx("h3",{className:"text-body text-muted-foreground",children:"Set AI Model for Template Installation"}),a.jsx("p",{className:"mt-2 mb-5 text-body text-muted-foreground",children:"This model will be used by the workflow to process and install the template"}),a.jsx(DJt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&a.jsx(ae,{className:W("state-layer mt-4 flex min-h-10 w-full items-center justify-center gap-2 rounded-lg bg-card text-body text-foreground","[&_svg]:h-[1.1em] [&_svg]:text-foreground [&>svg]:w-[1.1em]"),onClick:o,disabled:!t||!u||!d||s.length>0||c,children:c?a.jsxs(a.Fragment,{children:[a.jsx(Cn,{className:"h-4 w-4"})," Installing..."]}):a.jsxs(a.Fragment,{children:["Install ",a.jsx(qf,{})]})})]})})}function A$s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:o}){const i=o?`feat/install-template-${o}`:"feat/install-template-[slug]";return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:W("mt-5 grid items-center"),children:a.jsxs("div",{className:W("flex items-center gap-3 text-title","[&>svg]:h-[1.2em] [&>svg]:w-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[a.jsx(zx,{}),a.jsx("h2",{className:W({"flex min-w-[50%] rounded-lg bg-muted":r}),children:r?a.jsx(a.Fragment,{children:" "}):e})]})}),a.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[a.jsxs("div",{className:"grid",children:[a.jsx("p",{className:W("mt-2 mb-4 text-body text-muted-foreground",{"rounded-lg bg-muted":r}),children:r?a.jsx(a.Fragment,{children:" "}):t}),!r&&o&&a.jsxs("div",{className:W("mb-4 rounded-lg border border-border bg-background p-4","flex items-start gap-3"),children:[a.jsx("div",{className:"mt-0.5 shrink-0",children:a.jsx(Hf,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(XN,{className:"h-[1em] w-[1em] text-muted-foreground"}),a.jsx("span",{className:"text-subheading text-foreground",children:"A new Git branch will be created"})]}),a.jsxs("div",{className:"space-y-1 text-caption text-muted-foreground",children:[a.jsxs("div",{children:[a.jsx("span",{className:"font-medium",children:"Branch name:"})," ",a.jsx(w1,{children:i})]}),a.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&a.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:W(Pn,"mt-auto flex items-center gap-2 text-body"),children:[a.jsx(hK,{}),n?.split("/")?.pop()]})]}),s&&a.jsx(Q$e,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Oit(e){switch(e){case"running":return a.jsx(Cn,{size:"sm","aria-hidden":!0});case"success":return a.jsx(Vn,{"aria-hidden":!0});case"failed":return a.jsx(Gt,{"aria-hidden":!0});default:return null}}function R$s(){return a.jsx("svg",{viewBox:"0 0 24 24",className:"text-placeholder","aria-hidden":!0,children:a.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function P$s({status:e,variant:t}){return t==="plain"?a.jsx("span",{className:W("flex size-4 items-center justify-center self-center [&>svg]:size-4",vo.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?a.jsx(R$s,{}):Oit(e)}):a.jsx("span",{className:W("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",vo.colors,vo.transform,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-placeholder":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark":e==="success","bg-accent2Dark":e==="failed","scale-110":e==="success"||e==="failed"}),children:Oit(e)})}function $$s({step:e,isActive:t,position:n,variant:r="default"}){return a.jsxs("div",{className:W("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",vo.colors,{"border border-transparent":r==="default","border-dashed border-placeholder bg-card":t&&r==="default"}),children:[a.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[a.jsxs("span",{className:W("flex min-w-6 justify-end text-body",vo.colors,{"text-foreground":t||e.status==="success","text-muted-foreground":!t&&e.status!=="success"}),children:[n,"."]}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h4",{className:W("text-body",vo.colors,{"text-foreground":t||e.status==="success","text-muted-foreground":!t&&e.status!=="success"}),children:e.title}),e.description&&a.jsx("p",{className:W("-mt-0.5 text-body text-placeholder",{truncate:r==="plain"}),children:e.description})]})]}),a.jsx(P$s,{status:e.status,variant:r})]})}function M$s({currentStep:e,steps:t=[],className:n}){return a.jsx("div",{className:W(n),children:t.map((r,s)=>a.jsx($$s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function D$s({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return a.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[a.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>a.jsx("div",{className:W("relative flex h-8 items-center justify-end",vo.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:a.jsx("div",{className:W("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-fill text-column text-muted-foreground motion-reduce:transition-none",vo.colors,vo.transform,{"border border-dashed border-placeholder":r.status==="pending","scale-110 bg-accent1Dark text-notice-success-fg":r.status==="success","scale-110 bg-accent2Dark text-notice-destructive-fg":r.status==="failed"}),children:r.status==="running"?a.jsx(Cn,{}):s+1})},r.id))}),a.jsxs("div",{className:W("text-center text-caption text-muted-foreground",vo.colors),children:[n," of ",t," steps completed"]})]})}function L$s({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",o=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=o?.steps||{},u=Object.keys(c).length>0,d=y=>y==="input"||y.endsWith(".input")||y.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(y)||/[0-9a-f]{8,}/.test(y)?!1:r?.allSteps?y in r.allSteps:!0,f=Object.entries(c).filter(([y,v])=>d(y)),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(([y,v])=>({id:y,status:v?.status,description:v?.description,title:y.charAt(0).toUpperCase()+y.slice(1).replace(/-/g," "),isActive:i?.id===y}));return a.jsxs(tJ,{className:"mb-5 content-center space-y-6 text-muted-foreground",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("h3",{className:"text-heading text-foreground",children:h()}),(t?.runId||n)&&a.jsxs("div",{className:"mt-2 text-caption text-muted-foreground",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&a.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-4",children:a.jsx(D$s,{steps:m})}),l&&s==="error"&&a.jsxs("div",{className:W("flex items-center gap-3 rounded-lg bg-red-500/10 p-4 text-body text-foreground","[&>svg]:h-6 [&>svg]:w-6 [&>svg]:text-red-500 [&>svg]:opacity-70"),children:[a.jsx(z2n,{}),l||"Something went wrong"]}),u&&a.jsx(M$s,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&a.jsxs("div",{className:"grid justify-items-center gap-4 text-center text-body text-muted-foreground",children:[a.jsx(Cn,{}),a.jsx("p",{children:"This may take some time..."})]})]})}function F$s({name:e,installedEntities:t}){return a.jsxs(tJ,{className:W("grid content-center items-center justify-items-center gap-4","[&>svg]:h-8 [&>svg]:w-8"),children:[a.jsx(LSt,{}),a.jsx("h2",{className:"text-heading",children:"Done!"}),a.jsxs("p",{className:"text-center text-body text-muted-foreground",children:["The ",a.jsx("b",{className:"text-muted-foreground",children:e})," template has been successfully installed.",t&&t.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&a.jsx(Q$e,{data:t})]})}function z$s(){const{templateSlug:e}=fr(),t=[{id:"templates",label:"Templates",to:"/templates"},{id:"template",label:LG(e)}],[n,r]=so(),[s,o]=g.useState(""),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState({}),[p,h]=g.useState([]),[m,y]=g.useState(null),[v,b]=g.useState(!1),[x,w]=g.useState(""),[k,_]=g.useState(!1),[C,T]=g.useState(!1),[E,I]=g.useState([]),{data:N,isLoading:A}=Tvr({repoOrSlug:e,owner:"mastra-ai"}),F=E$s?.includes("beta")??!1?"beta":"main",{data:D,isLoading:H}=jvr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:F}),{data:q,isLoading:V}=Nvr(),{mutateAsync:B,isPending:Z}=Ivr(),{mutateAsync:z}=Avr(),{streamInstall:Y,streamResult:L,isStreaming:R}=Pvr(q),{observeInstall:M,streamResult:U,isStreaming:Q}=$vr(q);g.useEffect(()=>{const se=n.get("runId");se&&!v&&!m&&!R&&!Q&&(console.info("🔄 Checking completed run after hot reload:",{runId:se}),w(se),z({runId:se}).then(ie=>{const fe=ie.snapshot;if(fe?.status==="success"&&fe?.result?.success)b(!0);else if(fe?.result?.success===!1)if(fe?.result?.validationResults&&!fe?.result?.validationResults?.valid&&fe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:xe,errors:Ne}=fe.result.validationResults,Ae=`Template installation completed but ${xe} validation issue${xe>1?"s":""} remain unresolved.`;y(Ae),I(Ne||[])}else{const xe=fe?.result?.message||fe?.result?.error||"Template installation failed";y(typeof xe=="string"?xe:String(xe))}}).catch(ie=>{console.error("❌ Failed to fetch run details:",ie),y("Failed to retrieve installation status after reload")}))},[n,v,m,R,Q,z]),g.useEffect(()=>{const se=n.get("runId"),ie=n.get("resume"),fe=n.get("provider");if(se&&ie==="true"&&fe&&!R&&!Q&&!k&&!C&&q){w(se),_(!0);try{z({runId:se}).then(he=>{if(he.snapshot?.status==="running")return M.mutateAsync({runId:se})}).then(()=>{r(he=>{const xe=new URLSearchParams(he);return xe.delete("resume"),xe})}).catch(he=>{console.error("❌ Failed to resume template installation:",he),he.message?.includes("404")||he.message?.includes("not found")?y("Template installation run not found. It may have expired or been completed."):y("Failed to resume template installation. Please try again.")})}catch(he){console.error("❌ Auto-resume failed with error:",he),y("Failed to resume template installation. Please refresh and try again.")}}},[n,e,R,Q,k,C,q,z,M,r]);const te=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],K=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(se=>se).join(", "):"n/a",icon:a.jsx(Hd,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(se=>se).join(", "):"n/a",icon:a.jsx(Pi,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(se=>se).join(", "):"n/a",icon:a.jsx(q1,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:a.jsx(yy,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:a.jsx(V1,{})}],ee=[{...K[0]},{...K[1]},{...K[2]}].filter(se=>se.value!=="n/a");g.useEffect(()=>{D&&f(D)},[D]),g.useEffect(()=>{const se=L||U;se?.phase==="error"&&se?.error&&y(typeof se.error=="string"?se.error:String(se.error))},[L?.phase,L?.error,U?.phase,U?.error]);const ne=se=>{o(se)},le=async se=>(l(se.provider),u(se.modelId),{message:"Model updated successfully"}),J=async()=>{const se=Object.entries(d).reduce((ie,[fe,he])=>(he===""&&ie.push(fe),ie),[]);if(se.length>0){h(se);return}if(N){y(null),b(!1),w(""),T(!0);try{const fe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:F,slug:N.slug,variables:d},{runId:he}=await B({});w(he),r(xe=>{const Ne=new URLSearchParams(xe);return Ne.set("runId",he),Ne.set("resume","true"),Ne.set("provider",s||"openai"),Ne}),await Y.mutateAsync({inputData:fe,selectedModel:{provider:i,modelId:c},runId:he})}catch(ie){T(!1),y(ie?.message||"Template installation failed"),console.error("Template installation failed",ie)}}},re=se=>{const{name:ie,value:fe}=se.target;fe.trim()===""?h(he=>[...he,ie]):h(he=>he.filter(xe=>xe!==ie)),f(he=>({...he,[ie]:fe}))};return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:W("h-full w-full overflow-y-scroll lg:px-12"),children:a.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-4",children:[a.jsx(A$s,{isLoading:A,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:K,templateSlug:e}),N&&a.jsxs(a.Fragment,{children:[(R||Q)&&a.jsx(L$s,{name:N.title,streamResult:Q?U:L,runId:x,workflowInfo:q}),v&&a.jsx(F$s,{name:N.title,installedEntities:ee,linkComponent:ml}),m&&a.jsx(T$s,{errorMsg:m,validationErrors:E.length>0?E:L?.validationResults?.errors||U?.validationResults?.errors}),!R&&!Q&&!v&&!m&&a.jsx(I$s,{providerOptions:te,selectedProvider:s,onProviderChange:ne,variables:d,setVariables:f,errors:p,setErrors:h,handleInstallTemplate:J,handleVariableChange:re,isLoadingEnvVars:H||V,isInstalling:Z,defaultModelProvider:i,defaultModelId:c,onModelUpdate:le})]})]})})]})}const B$s=()=>{const{toolId:e,agentId:t}=fr(),n=[Wr("/agents"),{...zCe,to:t?`/agents/${encodeURIComponent(t)}`:void 0},{id:"agent-tool",Component:S6n}];return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:n}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"h-full w-full overflow-y-auto",children:a.jsx(Cys,{toolId:e,agentId:t})})]})},U$s=()=>{const e=Xe();return wn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new IC;Object.entries(r??{}).forEach(([o,i])=>{s.set(o,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(o){throw Qe.error("Error executing dev tool"),console.error("Error executing dev tool:",o),o}}})},V$s=({toolId:e})=>{const{canExecute:t}=_a(),n=t("tools"),{data:r={}}=ef(),s=g.useMemo(()=>{for(const y of Object.values(r))if(y.tools){const v=Object.values(y.tools).find(b=>b.id===e);if(v)return v}return null},[r,e]),{data:o,isLoading:i,error:l}=oqn(e,{enabled:!s}),c=s||o,{mutateAsync:u,isPending:d,data:f}=U$s(),{requestContext:p}=bs();g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Qe.error(`Error loading tool: ${y}`)}},[l]);const h=async(y,v)=>{if(!c)return;const b={...p??{},...v??{}};return u({toolId:c.id,input:y,requestContext:b})},m=c?.inputSchema?Am(r0(c?.inputSchema)):mr({});return i?a.jsxs("div",{className:"p-4",children:[a.jsx(at,{className:"mb-4 h-8 w-48"}),a.jsx(at,{className:"h-32 w-full"})]}):l?null:c?n?a.jsx(oMe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(je,{variant:"caption",tone:"muted",children:"You don't have permission to execute tools."})}):a.jsx("div",{className:"px-4 py-8 text-center",children:a.jsx(je,{variant:"heading",tone:"muted",children:"Tool not found"})})},q$s=()=>{const{toolId:e}=fr(),t=[Wr("/tools"),wqn];return a.jsxs(gt,{variant:"fit",breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx("div",{className:"h-full w-full overflow-y-hidden",children:a.jsx(V$s,{toolId:e})})]})},uM=[Wr("/workflows")];function H$s(){const{data:e,isLoading:t,error:n}=ih(),[r,s]=g.useState(""),[o,i]=g.useState();return n&&_s(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Qs,{variant:"fill"})]}):n&&js(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(Fs,{variant:"fill",resource:"workflows"})]}):n?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load workflows",descriptionSlot:n.message})]}):Object.keys(e||{}).length===0&&!t?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(sls,{})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:uM}),actionRow:a.jsxs(Gn,{children:[a.jsx(Gn.Start,{children:a.jsx("div",{className:"max-w-120 flex-1",children:a.jsx(ju,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})})}),a.jsx(Gn.End,{children:a.jsx(ae,{render:a.jsx(ml,{to:"/workflows/schedules"}),variant:"primary",icon:a.jsx(t0,{}),children:"Schedules"})})]}),children:[a.jsx("h1",{className:"sr-only",children:"Workflows"}),a.jsx(rls,{workflows:e||{},isLoading:t,search:r,sort:o,onSortChange:(l,c)=>i({key:c,direction:l})})]})}const W$s={active:"bg-accent1",paused:"bg-accent3"},Z$s={active:"text-accent1",paused:"text-accent3"},LJt=({status:e})=>a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${W$s[e]}`,"aria-hidden":!0}),a.jsx("span",{className:`text-caption ${Z$s[e]}`,children:e})]});function FJt({status:e}){const{icon:t,color:n}=G$s(e);return a.jsxs("span",{className:`inline-flex items-center gap-1.5 text-caption whitespace-nowrap ${n}`,children:[a.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),a.jsx("span",{children:e})]})}function G$s(e){switch(e){case"success":return{icon:a.jsx(Vn,{size:14}),color:"text-accent1"};case"failed":return{icon:a.jsx(Gt,{size:14}),color:"text-accent2"};case"running":return{icon:a.jsx(Cn,{}),color:"text-muted-foreground"};case"suspended":return{icon:a.jsx(iG,{size:14}),color:"text-accent3"};case"canceled":return{icon:a.jsx(EA,{size:14}),color:"text-muted-foreground"};case"pending":case"waiting":return{icon:a.jsx(R_,{size:14}),color:"text-muted-foreground"};default:return{icon:null,color:"text-muted-foreground"}}}const _it="auto auto auto auto 1fr",Q$s=3e4,Y$s=5*6e4;function K$s({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:o}){const{Link:i,paths:l}=dn(),c=h=>!!(n&&h.runId&&h.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Bc({count:u});let p=-1;return t?a.jsx(dc,{columns:_it}):e.length===0?a.jsx(je,{variant:"body",tone:"muted",className:"p-4",children:"No trigger history yet."}):a.jsxs(Oe,{columns:_it,className:"min-w-0",scrollRef:d,children:[a.jsxs(Oe.Top,{children:[a.jsx(Oe.TopCell,{children:"Run"}),a.jsx(Oe.TopCell,{children:"Status"}),a.jsx(Oe.TopCell,{children:"Started"}),a.jsx(Oe.TopCell,{children:"Duration"}),a.jsx(Oe.TopCell,{children:" "})]}),e.map(h=>{const m=h.actualFireAt-h.scheduledFireAt,y=Zd(m,{signed:!0}),v=h.outcome==="failed",b=v?h.error:h.run?.error,x=Math.abs(m),w=!v&&x>Q$s&&x<=Y$s,k=`${h.scheduleId}-${h.runId}-${h.actualFireAt}`,_=c(h);_&&(p+=1);const C=a.jsx(je,{as:"span",variant:"caption",font:"mono",tone:_?void 0:"muted",className:_?"whitespace-nowrap text-accent1":"whitespace-nowrap",children:h.runId}),T=a.jsxs(a.Fragment,{children:[a.jsx(Oe.Cell,{children:C}),a.jsx(Oe.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2",children:[v?a.jsxs("span",{className:"inline-flex items-center gap-1.5 text-caption whitespace-nowrap text-accent2",children:[a.jsx(cu,{size:14}),"publish failed"]}):h.run?a.jsx(FJt,{status:h.run.status}):a.jsx("span",{className:"inline-flex items-center gap-1.5 text-caption whitespace-nowrap text-muted-foreground",children:"pending"}),b?a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-accent2",children:a.jsx(cu,{size:14})})}),a.jsx(kn,{children:b})]}):null]})}),a.jsx(Oe.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[h.actualFireAt?a.jsx(pN,{value:h.actualFireAt}):"—",w?a.jsxs(On,{children:[a.jsx(Sn,{asChild:!0,children:a.jsx("span",{className:"inline-flex text-accent3",children:a.jsx(cu,{size:14})})}),a.jsxs(kn,{children:["Published ",y," after the scheduled fire time"]})]}):null]})}),a.jsx(Oe.Cell,{children:h.run?a.jsx(je,{as:"span",variant:"body-sm",font:"mono",children:Zd(h.run.durationMs)||"—"}):a.jsx("span",{className:"text-muted-foreground",children:"—"})}),a.jsx(Oe.Cell,{children:" "})]});return _?a.jsx(Oe.RowLink,{to:l.workflowRunLink(n,h.runId),LinkComponent:i,...f(p),children:T},k):a.jsx(Oe.RowStatic,{children:T},k)}),a.jsx(Oe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:o})]})}const X$s=e=>{const t=Xe();return wt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Cit=25,J$s=e=>{const t=Xe(),{inView:n,setRef:r}=A0(),s=Tm({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Cit,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Cit))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}),o=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:o,setEndOfListElement:r}},eMs=e=>{const t=Xe(),n=Tr();return wn({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"]}),Qe.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Qe.error(r.message)}})},zJt={id:"workflow-schedules",label:"Schedules",icon:t0,to:"/workflows/schedules"};function hB({label:e,children:t}){return a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsx(je,{variant:"meta",tone:"muted",className:"tracking-wide uppercase",children:e}),a.jsx("div",{className:"text-body",children:t})]})}function tMs(){const{scheduleId:e}=fr(),t=[Wr("/workflows"),zJt,{id:"schedule",label:LG(e),icon:t0}],{paths:n}=dn(),{data:r,error:s}=X$s(e),{data:o,isLoading:i,error:l,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d}=J$s(e),f=eMs(e);if(s&&_s(s))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Qs,{variant:"fill"})]});if(s&&js(s))return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(Fs,{variant:"fill",resource:"schedules"})]});if(s)return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:t}),children:[a.jsx("h1",{className:"sr-only",children:e}),a.jsx(un,{tone:"error",variant:"fill",titleSlot:"Failed to load schedule",descriptionSlot:s.message})]});const p=r?.workflowId,h=r?.agentId;return a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:t}),actionRow:a.jsx(Gn,{children:a.jsxs(Gn.End,{children:[a.jsx(ae,{render:a.jsx(ml,{to:n.schedulesLink()}),variant:"ghost",icon:a.jsx(Cu,{}),children:"Back to schedules"}),p?a.jsx(ae,{icon:a.jsx(yl,{}),render:a.jsx(ml,{to:n.workflowLink(p)}),variant:"ghost",children:"Open workflow"}):null,r?a.jsx(ae,{onClick:()=>f.mutate(r.status==="active"?"pause":"resume"),disabled:f.isPending,"data-testid":"schedule-toggle-button",children:r.status==="active"?a.jsxs(a.Fragment,{children:[a.jsx(JS,{}),"Pause"]}):a.jsxs(a.Fragment,{children:[a.jsx(bu,{}),"Resume"]})}):null]})}),children:[a.jsx("h1",{className:"sr-only",children:e}),r?a.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden",children:[a.jsxs("div",{className:"flex h-fit flex-col gap-4 rounded-md border border-border p-4",children:[a.jsx(hB,{label:h?"Agent":"Workflow",children:p?a.jsx(ml,{to:n.workflowLink(p),className:"text-accent1 hover:underline",children:p}):h?a.jsx(ml,{to:n.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),a.jsxs(hB,{label:"Cron",children:[a.jsx(je,{as:"span",variant:"body",font:"mono",children:r.cron}),r.timezone?a.jsx("span",{className:"ml-2 text-caption text-muted-foreground",children:r.timezone}):null]}),a.jsx(hB,{label:"Status",children:a.jsx(LJt,{status:r.status})}),a.jsx(hB,{label:"Next fire",children:r.nextFireAt?a.jsx(pN,{value:r.nextFireAt}):"—"})]}),a.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[a.jsx(je,{variant:"body",className:"mb-3",children:"Trigger history"}),l?a.jsx(un,{tone:"error",titleSlot:"Failed to load trigger history",descriptionSlot:l.message}):a.jsx(K$s,{triggers:o??[],isLoading:i,workflowId:p,hasNextPage:c,isFetchingNextPage:u,setEndOfListElement:d})]})]}):null]})}const nMs={target:e=>e.workflowId??e.agentId??"",status:e=>e.status,nextFireAt:e=>e.nextFireAt,lastFireAt:e=>e.lastFireAt},Eit="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function rMs({schedules:e,isLoading:t,search:n="",sort:r,onSortChange:s}){const{paths:o,Link:i}=dn(),l=g.useMemo(()=>{const f=n.toLowerCase(),p=f?e.filter(h=>h.id.toLowerCase().includes(f)||(h.workflowId??h.agentId??"").toLowerCase().includes(f)):e;return G0(p,r,nMs)},[e,n,r]),{containerRef:c,getRowProps:u}=Bc({count:l.length,global:!0});if(t)return a.jsx(dc,{columns:Eit});const d=(f,p)=>s?a.jsx(Oe.SortableTopCell,{sortKey:f,sort:r?.key===f?r.direction:void 0,onSortChange:s,children:p}):a.jsx(Oe.TopCell,{children:p});return a.jsxs(Oe,{columns:Eit,className:"min-w-0",scrollRef:c,children:[a.jsxs(Oe.Top,{children:[d("target","Target"),a.jsx(Oe.TopCell,{children:"Schedule ID"}),a.jsx(Oe.TopCell,{children:"Cron"}),d("status","Status"),d("nextFireAt","Next fire"),d("lastFireAt","Last run")]}),l.length===0&&n?a.jsx(Oe.NoMatch,{message:"No schedules match your search"}):null,l.length===0&&!n?a.jsx(Oe.NoMatch,{message:"No schedules configured"}):null,l.map((f,p)=>a.jsxs(Oe.RowLink,{to:o.scheduleLink(f.id),LinkComponent:i,...u(p),children:[a.jsx(Oe.NameCell,{children:f.workflowId??f.agentId}),a.jsx(Oe.Cell,{className:"min-w-0",children:a.jsx(je,{as:"span",variant:"body-sm",tone:"muted",font:"mono",className:"block truncate",title:f.id,children:f.id})}),a.jsx(Oe.Cell,{children:a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(je,{as:"span",variant:"caption",font:"mono",children:f.cron}),f.timezone?a.jsx("span",{className:"text-meta text-muted-foreground",children:f.timezone}):null]})}),a.jsx(Oe.Cell,{children:a.jsx(LJt,{status:f.status})}),a.jsx(Oe.Cell,{children:f.nextFireAt?a.jsx(pN,{value:f.nextFireAt}):"—"}),a.jsx(Oe.Cell,{children:f.lastRun?a.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[a.jsx(FJt,{status:f.lastRun.status}),f.lastFireAt?a.jsx(je,{as:"span",variant:"caption",tone:"muted",children:a.jsx(pN,{value:f.lastFireAt})}):null]}):f.lastFireAt?a.jsx(pN,{value:f.lastFireAt}):a.jsx("span",{className:"text-muted-foreground",children:"Never"})})]},f.id))]})}function BJt({workflowId:e}={}){const{data:t,isLoading:n,error:r}=CQ(e?{workflowId:e}:{}),[s,o]=g.useState(""),[i,l]=g.useState();return r?a.jsx(un,{tone:"error",titleSlot:"Failed to load schedules",descriptionSlot:r.message}):a.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[a.jsx("div",{className:"max-w-120",children:a.jsx(ju,{onSearch:o,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),a.jsx("div",{className:"overflow-y-auto",children:a.jsx(rMs,{schedules:t??[],isLoading:n,search:s,sort:i,onSortChange:(c,u)=>l({key:u,direction:c})})})]})}const _ce=[Wr("/workflows"),zJt];function sMs(){const[e]=so(),t=e.get("workflowId")??void 0,{error:n}=CQ(t?{workflowId:t}:{});return n&&_s(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:_ce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Qs,{variant:"fill"})]}):n&&js(n)?a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:_ce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx(Fs,{variant:"fill",resource:"schedules"})]}):a.jsxs(gt,{breadcrumbs:a.jsx(kt,{crumbs:_ce}),children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),a.jsx("div",{className:"h-full",children:a.jsx(BJt,{workflowId:t})})]})}const oMs={"--belt-hue":"var(--warning1)"};function iMs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function aMs(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 lMs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:a.jsxs("section",{className:W(HTe,"pointer-events-auto relative isolate"),"data-testid":"workflow-suspended-steps","aria-label":"Step suspended",children:[a.jsxs("div",{className:"max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]",children:[a.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-border/50 bg-background px-5 py-4",children:[a.jsxs(je,{as:"h2",variant:"column",tone:"ink",className:"flex items-center gap-2",children:[a.jsx(_t,{children:a.jsx(iG,{})}),"Step suspended"]}),a.jsx(Mt,{variant:"orange",emphasis:"muted",children:"Needs input"})]}),e.map(s=>{const o=t.allSteps[s.stepId];if(!o||o.isWorkflow)return null;const i=o?.resumeSchema?Am(r0(o.resumeSchema)):bf(jn(),Nf());return a.jsx(cMs,{step:s,stepSchema:i,description:o.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),a.jsx(SAt,{status:"ready",label:"Needs input",className:"before:hidden",style:oMs})]})}function cMs({step:e,stepSchema:t,description:n,onResume:r}){const[s,o]=g.useState(!1),[i,l]=g.useState(!1),c=async u=>{l(!0);try{await r({stepId:e.stepId.split("."),runId:e.runId,resumeData:u})}catch(d){Qe.error(d instanceof Error?d.message:"Error resuming workflow")}finally{l(!1)}};return a.jsxs("div",{className:"space-y-5 p-5 [&+&]:border-t [&+&]:border-border/50",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsx(je,{as:"p",variant:"subheading",tone:"ink",className:"break-words",children:e.stepId}),n&&a.jsx(je,{as:"p",variant:"caption",tone:"muted",children:n})]}),e.suspendPayload!==void 0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs(je,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(_t,{children:a.jsx(j2n,{})}),"The step is asking"]}),a.jsxs(il,{open:s,onOpenChange:o,children:[a.jsxs(Va,{className:W(ir,"flex w-full items-center justify-between gap-2 rounded-lg px-3 py-2.5"),children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[a.jsx(_t,{children:a.jsx(wr,{className:W("text-muted-foreground transition-transform",{"rotate-90 transform":s})})}),a.jsx(je,{as:"span",variant:"body",tone:"ink",className:"truncate",children:aMs(e.suspendPayload,e.stepId)})]}),a.jsx(je,{as:"span",variant:"caption",tone:"muted",className:"shrink-0",children:iMs(e.suspendPayload)})]}),a.jsx(qa,{children:a.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:a.jsx(br,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs(je,{as:"p",variant:"caption",tone:"muted",className:"flex items-center gap-2",children:[a.jsx(_t,{children:a.jsx(R2n,{})}),"Your response"]}),a.jsx("div",{className:"-mx-5",children:a.jsx(BTe,{schema:t,isSubmitLoading:i,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:a.jsx(bu,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function uMs({hidden:e}){const{result:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(ac),{canExecute:o,isLoading:i}=_a(),l=kRt(t,r),c=Zmr(),u=t?.status==="suspended"&&l.length>0&&!s,d=!i&&o("workflows");return!n||!u||!d?null:a.jsx("div",{hidden:e,"data-testid":"workflow-suspended-overlay",className:"pointer-events-none absolute top-12 right-2 z-30 w-[380px] max-w-[calc(100%-16px)] animate-in duration-300 fade-in-0 slide-in-from-top-2 motion-reduce:animate-none",children:a.jsx(lMs,{suspendedSteps:l,workflow:n,isStreaming:s,onResume:c})},r)}const Tit={success:{label:"Completed",icon:Vn,color:"text-positive1",bar:"bg-muted-foreground/60"},failed:{label:"Failed",icon:VD,color:"text-negative1",bar:"bg-negative1/60"},suspended:{label:"Needs input",icon:JS,color:"text-accent3",bar:"bg-accent3/60"},waiting:{label:"Waiting",icon:t1,color:"text-muted-foreground",bar:"bg-muted-foreground/40"},paused:{label:"Paused",icon:JS,color:"text-muted-foreground",bar:"bg-muted-foreground/40"},skipped:{label:"Skipped",icon:FDn,color:"text-muted-foreground",bar:"bg-muted-foreground/25"},running:{label:"Running",icon:ko,color:"text-accent6",bar:"bg-accent6/60"},canceled:{label:"Canceled",icon:EA,color:"text-muted-foreground",bar:"bg-muted-foreground/40"}},dMs={label:"Status unavailable",icon:l$n,color:"text-muted-foreground",bar:"bg-muted-foreground/25"};function fMs({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:o,onOpenOutput:i}){const l=Object.hasOwn(Tit,e.status)?Tit[e.status]:dMs,c=l.icon,u=e.stepId.slice(0,e.stepId.lastIndexOf(".")),d=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(".")+1):e.stepId;return a.jsxs("div",{"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&s(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&s(null),className:W("grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1","@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2",(t||n)&&"bg-fill-subtle"),children:[a.jsxs("button",{type:"button",className:"flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left text-meta text-foreground focus-visible:rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-border-focus aria-disabled:cursor-default","aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,children:[a.jsx("span",{"aria-label":l.label,className:W("grid size-6 flex-none place-items-center rounded-md border border-border bg-background",l.color),children:a.jsx(c,{"aria-hidden":!0,className:W("size-3.5",e.status==="running"&&"motion-safe:animate-spin")})}),a.jsxs("span",{className:"min-w-0",children:[a.jsx("span",{className:"block truncate",children:d}),e.isNestedEntry&&a.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-meta text-muted-foreground",children:[a.jsx(o_e,{"aria-hidden":!0,className:"size-3 shrink-0"}),a.jsx("span",{className:"truncate",children:u})]})]})]}),a.jsx("div",{className:"relative h-5 min-w-0 overflow-hidden rounded-sm bg-muted @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]","aria-hidden":!0,children:e.timing&&a.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:W("absolute top-0 h-full min-w-0.5 rounded-sm",l.bar),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),a.jsx("span",{className:"text-right text-meta whitespace-nowrap text-muted-foreground",title:e.timing&&e.spansSuspension?"Includes time spent suspended waiting for input":void 0,children:e.timing?a.jsx(je,{as:"span",variant:"meta",font:"mono",children:Zd(e.timing.durationMs)}):a.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),a.jsxs("div",{className:"flex items-center",children:[a.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:e.step.input===void 0,onClick:f=>o(e,f.currentTarget),children:a.jsx(rG,{})}),a.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:e.step.output===void 0,onClick:f=>i(e,f.currentTarget),children:a.jsx(oG,{})})]})]})}const pMs=e=>e.includes("."),hMs=e=>e==="input"||e.endsWith(".input"),jit=1;function mMs(e,t){const n=FTe(e),r=n?.isLive?Math.max(t,n.start):n?.end;return{span:n&&r!==void 0?{start:n.start,end:r}:void 0,isLive:n?.isLive??!1,spansSuspension:n?.spansSuspension??!1}}function gMs(e,t){const n=Object.entries(e).filter(([l])=>!hMs(l)).map(([l,c])=>({stepId:l,step:c,...mMs(c,t)})).sort((l,c)=>(l.span?.start??1/0)-(c.span?.start??1/0)||l.stepId.localeCompare(c.stepId)),r=n.flatMap(l=>l.span?[l.span]:[]),s=Math.min(...r.map(l=>l.start)),o=Math.max(s,...r.map(l=>l.end)),i=Math.max(o-s,1);return n.map(({stepId:l,step:c,span:u,isLive:d,spansSuspension:f})=>{let p;if(u){const h=u.end-u.start,m=Math.min((u.start-s)/i*100,100-jit),y=Math.min(Math.max(h/i*100,jit),100-m);p={durationMs:h,offsetPct:m,widthPct:y}}return{stepId:l,step:c,status:_Q(c)?"suspended":c.status,timing:p,spansSuspension:f,isRunning:d,isNestedEntry:pMs(l)}})}function vMs(){const{steps:e}=AR(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=BG(),[o,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=X1(),p=g.useRef(null),h=gMs(e,o),m=h.some(y=>y.isRunning);return ckt(p,{enabled:m&&!l}),g.useEffect(()=>{if(!m||l)return;const y=setInterval(()=>i(Date.now()),100);return()=>clearInterval(y)},[m,l]),h.length===0?null:a.jsx("div",{"data-testid":"workflow-timeline",className:"relative z-20 shrink-0 px-2 pb-2",children:a.jsxs(il,{open:!l,onOpenChange:y=>c(!y),className:W(ir,"@container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl"),children:[a.jsxs("div",{className:"flex items-center",children:[a.jsxs(Va,{className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5 text-caption text-foreground hover:bg-fill-subtle","aria-label":l?"Expand timeline":"Collapse timeline",children:[a.jsx("span",{children:a.jsx(pSt,{"aria-hidden":!0,className:"size-4 text-muted-foreground"})}),a.jsx("span",{children:"Timeline"}),a.jsxs("span",{className:"text-meta text-muted-foreground",children:[h.length," events"]}),a.jsx("span",{className:"ml-auto",children:a.jsx(po,{"aria-hidden":!0,className:W("size-4 transition-transform motion-reduce:transition-none",l&&"-rotate-90")})})]}),!l&&a.jsx(ae,{variant:"ghost",size:"icon-sm",tooltip:u?"Restore timeline height":"Enlarge timeline","aria-pressed":u,onClick:()=>d(!u),className:"mr-2 shrink-0",children:u?a.jsx(WPn,{}):a.jsx(mSt,{})})]}),a.jsx(qa,{children:a.jsx("div",{ref:p,"data-testid":"workflow-timeline-list",className:W("overflow-auto overscroll-contain px-1.5 pb-1.5",u?"max-h-[min(720px,calc(100dvh-112px))]":"max-h-[min(320px,40dvh)]"),children:h.map(y=>a.jsx(fMs,{row:y,isSelected:t===y.stepId,isHovered:n===y.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:(v,b)=>f({type:"step-input",stepId:v.stepId},b),onOpenOutput:(v,b)=>f({type:"step-output",stepId:v.stepId},b)},y.stepId))})})]})})}const yMs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=X1(),s=KA(),o=r?.type==="data",i=a.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[a.jsx(T7t,{workflowId:e,workflow:t,isLoading:n}),a.jsx(uMs,{hidden:o}),o&&a.jsx("div",{className:"pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col",children:a.jsx(P7,{})}),a.jsx("div",{className:"pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20",children:a.jsx(vMs,{})})]});return s&&r&&!o?a.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:a.jsx(P7,{})}):a.jsxs("div",{className:"relative h-full min-h-0",children:[i,a.jsxs(vMe,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[a.jsx(EC,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),r&&!o&&a.jsxs(a.Fragment,{children:[a.jsx($W,{className:"pointer-events-auto"}),a.jsx(EC,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:a.jsx("div",{className:"pointer-events-auto h-full min-h-0 overflow-hidden rounded-studio-panel border border-border bg-background",children:a.jsx(P7,{})})})]})]})]})},Nit=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=v5(e);return r&&_s(r)?a.jsx(Qs,{variant:"fill"}):r&&js(r)?a.jsx(Fs,{variant:"fill",resource:"workflows"}):a.jsx(yMs,{workflowId:e,workflow:t??void 0,isLoading:n})};function bMs(){const{workflowId:e}=fr(),{error:t}=CQ(e?{workflowId:e}:{});if(!e)return null;let n;return t&&_s(t)?n=a.jsx(Qs,{variant:"fill"}):t&&js(t)?n=a.jsx(Fs,{variant:"fill",resource:"schedules"}):n=a.jsx("div",{className:"h-full",children:a.jsx(BJt,{workflowId:e})}),a.jsxs(gt,{children:[a.jsx("h1",{className:"sr-only",children:"Schedules"}),n]})}function xMs(){const{workflowId:e}=fr();return e?a.jsx(o2e,{scopedEntityId:e,scopedEntityType:lu.WORKFLOW_RUN}):null}function wMs(e,t){if(e==null)return{};var n,r,s=zjt(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function c1e(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 SMs(e){if(Array.isArray(e))return c1e(e)}function kMs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function OMs(e,t){if(e){if(typeof e=="string")return c1e(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)?c1e(e,t):void 0}}function _Ms(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
687
687
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function u1e(e){return SMs(e)||kMs(e)||OMs(e)||_Ms()}function F4(e){"@babel/helpers - typeof";return F4=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},F4(e)}function CMs(e,t){if(F4(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(F4(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function EMs(e){var t=CMs(e,"string");return F4(t)=="symbol"?t:t+""}function UJt(e,t,n){return(t=EMs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Iit(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 zj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Iit(Object(n),!0).forEach(function(r){UJt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Iit(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function TMs(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 Cce={};function jMs(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return Cce[t]||(Cce[t]=TMs(e)),Cce[t]}function NMs(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(o){return o!=="token"}),s=jMs(r);return s.reduce(function(o,i){return zj(zj({},o),n[i])},t)}function Ait(e){return e.join(" ")}function IMs(e,t){var n=0;return function(r){return n+=1,r.map(function(s,o){return VJt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(o)})})}}function VJt(e){var t=e.node,n=e.stylesheet,r=e.style,s=r===void 0?{}:r,o=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=IMs(n,o),p;if(!o)p=zj(zj({},l),{},{className:Ait(l.className)});else{var h=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(w){b.includes(w)||b.push(w)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],y=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=zj(zj({},l),{},{className:Ait(y)||void 0,style:NMs(l.className,Object.assign({},l.style,s),n)})}var v=f(t.children);return $e.createElement(u,tC({key:i},p),v)}}const AMs=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var RMs=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function Rit(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 yS(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Rit(Object(n),!0).forEach(function(r){UJt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Rit(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var PMs=/\n/g;function $Ms(e){return e.match(PMs)}function MMs(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,o){var i=o+n;return $e.createElement("span",{key:"line-".concat(o),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
688
688
  `))})}function DMs(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,s=r===void 0?{float:"left",paddingRight:"10px"}:r,o=e.numberStyle,i=o===void 0?{}:o,l=e.startingLineNumber;return $e.createElement("code",{style:Object.assign({},n,s)},MMs({lines:t.replace(/\n$/,"").split(`
689
689
  `),style:i,startingLineNumber:l}))}function LMs(e){return"".concat(e.toString().length,".25em")}function qJt(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 HJt(e,t,n){var r={display:"inline-block",minWidth:LMs(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,o=yS(yS({},r),s);return o}function q7(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,s=e.largestLineNumber,o=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?yS({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(u1e(m.className.trim().split(/\s+/)),u1e(u)):u,n&&o){var y=HJt(r,n,s);t.unshift(qJt(n,y))}return f&d&&(m.style=yS({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function WJt(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(q7({children:[s],className:u1e(new Set(t))}));else if(s.children){var o=t.concat(s.properties.className);WJt(s.children,o).forEach(function(i){return n.push(i)})}}return n}function FMs(e,t,n,r,s,o,i,l,c){var u,d=WJt(e.value),f=[],p=-1,h=0;function m(_,C){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return q7({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:T,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function y(_,C){if(r&&C&&s){var T=HJt(l,C,i);_.unshift(qJt(C,T))}return _}function v(_,C){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||T.length>0?m(_,C,T):y(_,C)}for(var b=function(){var C=d[h],T=C.children[0].value,E=$Ms(T);if(E){var I=T.split(`