@mastra/deployer-cloud 1.62.0-alpha.8 → 1.62.0-alpha.9

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-8uqV4bH7.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-CKwPFHqo.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js"])))=>i.map(i=>d[i]);
2
2
  import{_ as Da}from"./preload-helper-PPVm8Dsz.js";function oZt(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const a=Object.getOwnPropertyDescriptor(r,s);a&&Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var pj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var BK={exports:{}},QA={};var z$e;function lZt(){if(z$e)return QA;z$e=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,a){var i=null;if(a!==void 0&&(i=""+a),s.key!==void 0&&(i=""+s.key),"key"in s){a={};for(var l in s)l!=="key"&&(a[l]=s[l])}else a=s;return s=a.ref,{$$typeof:e,type:r,key:i,ref:s!==void 0?s:null,props:a}}return QA.Fragment=t,QA.jsx=n,QA.jsxs=n,QA}var B$e;function cZt(){return B$e||(B$e=1,BK.exports=lZt()),BK.exports}var o=cZt(),UK={exports:{}},Vr={},U$e;function uZt(){if(U$e)return Vr;U$e=1;var e={env:{}};var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),h=Symbol.iterator;function m(q){return q===null||typeof q!="object"?null:(q=h&&q[h]||q["@@iterator"],typeof q=="function"?q:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(q,$,z){this.props=q,this.context=$,this.refs=b,this.updater=z||v}x.prototype.isReactComponent={},x.prototype.setState=function(q,$){if(typeof q!="object"&&typeof q!="function"&&q!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,q,$,"setState")},x.prototype.forceUpdate=function(q){this.updater.enqueueForceUpdate(this,q,"forceUpdate")};function S(){}S.prototype=x.prototype;function k(q,$,z){this.props=q,this.context=$,this.refs=b,this.updater=z||v}var C=k.prototype=new S;C.constructor=k,y(C,x.prototype),C.isPureReactComponent=!0;var _=Array.isArray;function E(){}var T={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(q,$,z){var Z=z.ref;return{$$typeof:t,type:q,key:$,ref:Z!==void 0?Z:null,props:z}}function A(q,$){return I(q.type,$,q.props)}function R(q){return typeof q=="object"&&q!==null&&q.$$typeof===t}function L(q){var $={"=":"=0",":":"=2"};return"$"+q.replace(/[=:]/g,function(z){return $[z]})}var D=/\/+/g;function F(q,$){return typeof q=="object"&&q!==null&&q.key!=null?L(""+q.key):$.toString(36)}function H(q){switch(q.status){case"fulfilled":return q.value;case"rejected":throw q.reason;default:switch(typeof q.status=="string"?q.then(E,E):(q.status="pending",q.then(function($){q.status==="pending"&&(q.status="fulfilled",q.value=$)},function($){q.status==="pending"&&(q.status="rejected",q.reason=$)})),q.status){case"fulfilled":return q.value;case"rejected":throw q.reason}}throw q}function B(q,$,z,Z,K){var re=typeof q;(re==="undefined"||re==="boolean")&&(q=null);var ee=!1;if(q===null)ee=!0;else switch(re){case"bigint":case"string":case"number":ee=!0;break;case"object":switch(q.$$typeof){case t:case n:ee=!0;break;case f:return ee=q._init,B(ee(q._payload),$,z,Z,K)}}if(ee)return K=K(q),ee=Z===""?"."+F(q,0):Z,_(K)?(z="",ee!=null&&(z=ee.replace(D,"$&/")+"/"),B(K,$,z,"",function(fe){return fe})):K!=null&&(R(K)&&(K=A(K,z+(K.key==null||q&&q.key===K.key?"":(""+K.key).replace(D,"$&/")+"/")+ee)),$.push(K)),1;ee=0;var J=Z===""?".":Z+":";if(_(q))for(var ae=0;ae<q.length;ae++)Z=q[ae],re=J+F(Z,ae),ee+=B(Z,$,z,re,K);else if(ae=m(q),typeof ae=="function")for(q=ae.call(q),ae=0;!(Z=q.next()).done;)Z=Z.value,re=J+F(Z,ae++),ee+=B(Z,$,z,re,K);else if(re==="object"){if(typeof q.then=="function")return B(H(q),$,z,Z,K);throw $=String(q),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(q).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return ee}function U(q,$,z){if(q==null)return q;var Z=[],K=0;return B(q,Z,"","",function(re){return $.call(z,re,K++)}),Z}function V(q){if(q._status===-1){var $=q._result;$=$(),$.then(function(z){(q._status===0||q._status===-1)&&(q._status=1,q._result=z)},function(z){(q._status===0||q._status===-1)&&(q._status=2,q._result=z)}),q._status===-1&&(q._status=0,q._result=$)}if(q._status===1)return q._result.default;throw q._result}var M=typeof reportError=="function"?reportError:function(q){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof q=="object"&&q!==null&&typeof q.message=="string"?String(q.message):String(q),error:q});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",q);return}console.error(q)},G={map:U,forEach:function(q,$,z){U(q,function(){$.apply(this,arguments)},z)},count:function(q){var $=0;return U(q,function(){$++}),$},toArray:function(q){return U(q,function($){return $})||[]},only:function(q){if(!R(q))throw Error("React.Children.only expected to receive a single React element child.");return q}};return Vr.Activity=p,Vr.Children=G,Vr.Component=x,Vr.Fragment=r,Vr.Profiler=a,Vr.PureComponent=k,Vr.StrictMode=s,Vr.Suspense=u,Vr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,Vr.__COMPILER_RUNTIME={__proto__:null,c:function(q){return T.H.useMemoCache(q)}},Vr.cache=function(q){return function(){return q.apply(null,arguments)}},Vr.cacheSignal=function(){return null},Vr.cloneElement=function(q,$,z){if(q==null)throw Error("The argument must be a React element, but you passed "+q+".");var Z=y({},q.props),K=q.key;if($!=null)for(re in $.key!==void 0&&(K=""+$.key),$)!N.call($,re)||re==="key"||re==="__self"||re==="__source"||re==="ref"&&$.ref===void 0||(Z[re]=$[re]);var re=arguments.length-2;if(re===1)Z.children=z;else if(1<re){for(var ee=Array(re),J=0;J<re;J++)ee[J]=arguments[J+2];Z.children=ee}return I(q.type,K,Z)},Vr.createContext=function(q){return q={$$typeof:l,_currentValue:q,_currentValue2:q,_threadCount:0,Provider:null,Consumer:null},q.Provider=q,q.Consumer={$$typeof:i,_context:q},q},Vr.createElement=function(q,$,z){var Z,K={},re=null;if($!=null)for(Z in $.key!==void 0&&(re=""+$.key),$)N.call($,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(K[Z]=$[Z]);var ee=arguments.length-2;if(ee===1)K.children=z;else if(1<ee){for(var J=Array(ee),ae=0;ae<ee;ae++)J[ae]=arguments[ae+2];K.children=J}if(q&&q.defaultProps)for(Z in ee=q.defaultProps,ee)K[Z]===void 0&&(K[Z]=ee[Z]);return I(q,re,K)},Vr.createRef=function(){return{current:null}},Vr.forwardRef=function(q){return{$$typeof:c,render:q}},Vr.isValidElement=R,Vr.lazy=function(q){return{$$typeof:f,_payload:{_status:-1,_result:q},_init:V}},Vr.memo=function(q,$){return{$$typeof:d,type:q,compare:$===void 0?null:$}},Vr.startTransition=function(q){var $=T.T,z={};T.T=z;try{var Z=q(),K=T.S;K!==null&&K(z,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(E,M)}catch(re){M(re)}finally{$!==null&&z.types!==null&&($.types=z.types),T.T=$}},Vr.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},Vr.use=function(q){return T.H.use(q)},Vr.useActionState=function(q,$,z){return T.H.useActionState(q,$,z)},Vr.useCallback=function(q,$){return T.H.useCallback(q,$)},Vr.useContext=function(q){return T.H.useContext(q)},Vr.useDebugValue=function(){},Vr.useDeferredValue=function(q,$){return T.H.useDeferredValue(q,$)},Vr.useEffect=function(q,$){return T.H.useEffect(q,$)},Vr.useEffectEvent=function(q){return T.H.useEffectEvent(q)},Vr.useId=function(){return T.H.useId()},Vr.useImperativeHandle=function(q,$,z){return T.H.useImperativeHandle(q,$,z)},Vr.useInsertionEffect=function(q,$){return T.H.useInsertionEffect(q,$)},Vr.useLayoutEffect=function(q,$){return T.H.useLayoutEffect(q,$)},Vr.useMemo=function(q,$){return T.H.useMemo(q,$)},Vr.useOptimistic=function(q,$){return T.H.useOptimistic(q,$)},Vr.useReducer=function(q,$,z){return T.H.useReducer(q,$,z)},Vr.useRef=function(q){return T.H.useRef(q)},Vr.useState=function(q){return T.H.useState(q)},Vr.useSyncExternalStore=function(q,$,z){return T.H.useSyncExternalStore(q,$,z)},Vr.useTransition=function(){return T.H.useTransition()},Vr.version="19.2.7",Vr}var V$e;function FN(){return V$e||(V$e=1,UK.exports=uZt()),UK.exports}var g=FN();const Fe=Bl(g),zN=oZt({__proto__:null,default:Fe},[g]);var VK={exports:{}},YA={},qK={exports:{}},HK={};var q$e;function dZt(){return q$e||(q$e=1,(function(e){function t(H,B){var U=H.length;H.push(B);e:for(;0<U;){var V=U-1>>>1,M=H[V];if(0<s(M,B))H[V]=B,H[U]=M,U=V;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var B=H[0],U=H.pop();if(U!==B){H[0]=U;e:for(var V=0,M=H.length,G=M>>>1;V<G;){var q=2*(V+1)-1,$=H[q],z=q+1,Z=H[z];if(0>s($,U))z<M&&0>s(Z,$)?(H[V]=Z,H[z]=U,V=z):(H[V]=$,H[q]=U,V=q);else if(z<M&&0>s(Z,U))H[V]=Z,H[z]=U,V=z;else break e}}return B}function s(H,B){var U=H.sortIndex-B.sortIndex;return U!==0?U:H.id-B.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var i=Date,l=i.now();e.unstable_now=function(){return i.now()-l}}var c=[],u=[],d=1,f=null,p=3,h=!1,m=!1,v=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function k(H){for(var B=n(u);B!==null;){if(B.callback===null)r(u);else if(B.startTime<=H)r(u),B.sortIndex=B.expirationTime,t(c,B);else break;B=n(u)}}function C(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,_||(_=!0,R());else{var B=n(u);B!==null&&F(C,B.startTime-H)}}var _=!1,E=-1,T=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<T)}function A(){if(y=!1,_){var H=e.unstable_now();N=H;var B=!0;try{e:{m=!1,v&&(v=!1,x(E),E=-1),h=!0;var U=p;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var V=f.callback;if(typeof V=="function"){f.callback=null,p=f.priorityLevel;var M=V(f.expirationTime<=H);if(H=e.unstable_now(),typeof M=="function"){f.callback=M,k(H),B=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)B=!0;else{var G=n(u);G!==null&&F(C,G.startTime-H),B=!1}}break e}finally{f=null,p=U,h=!1}B=void 0}}finally{B?R():_=!1}}}var R;if(typeof S=="function")R=function(){S(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,D=L.port2;L.port1.onmessage=A,R=function(){D.postMessage(null)}}else R=function(){b(A,0)};function F(H,B){E=b(function(){H(e.unstable_now())},B)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):T=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(H){switch(p){case 1:case 2:case 3:var B=3;break;default:B=p}var U=p;p=B;try{return H()}finally{p=U}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,B){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var U=p;p=H;try{return B()}finally{p=U}},e.unstable_scheduleCallback=function(H,B,U){var V=e.unstable_now();switch(typeof U=="object"&&U!==null?(U=U.delay,U=typeof U=="number"&&0<U?V+U:V):U=V,H){case 1:var M=-1;break;case 2:M=250;break;case 5:M=1073741823;break;case 4:M=1e4;break;default:M=5e3}return M=U+M,H={id:d++,callback:B,priorityLevel:H,startTime:U,expirationTime:M,sortIndex:-1},U>V?(H.sortIndex=U,t(u,H),n(c)===null&&H===n(u)&&(v?(x(E),E=-1):v=!0,F(C,U-V))):(H.sortIndex=M,t(c,H),m||h||(m=!0,_||(_=!0,R()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var B=p;return function(){var U=p;p=B;try{return H.apply(this,arguments)}finally{p=U}}}})(HK)),HK}var H$e;function fZt(){return H$e||(H$e=1,qK.exports=dZt()),qK.exports}var WK={exports:{}},Su={};var W$e;function pZt(){if(W$e)return Su;W$e=1;var e=FN();function t(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function a(c,u,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:f==null?null:""+f,children:c,containerInfo:u,implementation:d}}var i=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return Su.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Su.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return a(c,u,null,d)},Su.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()}},Su.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))},Su.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},Su.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})}},Su.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)},Su.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})}},Su.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)},Su.requestFormReset=function(c){r.d.r(c)},Su.unstable_batchedUpdates=function(c,u){return c(u)},Su.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},Su.useFormStatus=function(){return i.H.useHostTransitionStatus()},Su.version="19.2.7",Su}var Z$e;function ult(){if(Z$e)return WK.exports;Z$e=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),WK.exports=pZt(),WK.exports}var G$e;function hZt(){if(G$e)return YA;G$e=1;var e={env:{}};var t=fZt(),n=FN(),r=ult();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)O+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+w+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(w){return!(!w||w.nodeType!==1&&w.nodeType!==9&&w.nodeType!==11)}function i(w){var O=w,j=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(j=O.return),w=O.return;while(w)}return O.tag===3?j:null}function l(w){if(w.tag===13){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function c(w){if(w.tag===31){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function u(w){if(i(w)!==w)throw Error(s(188))}function d(w){var O=w.alternate;if(!O){if(O=i(w),O===null)throw Error(s(188));return O!==w?null:w}for(var j=w,P=O;;){var W=j.return;if(W===null)break;var Q=W.alternate;if(Q===null){if(P=W.return,P!==null){j=P;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===j)return u(W),w;if(Q===P)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(j.return!==P.return)j=W,P=Q;else{for(var oe=!1,ke=W.child;ke;){if(ke===j){oe=!0,j=W,P=Q;break}if(ke===P){oe=!0,P=W,j=Q;break}ke=ke.sibling}if(!oe){for(ke=Q.child;ke;){if(ke===j){oe=!0,j=Q,P=W;break}if(ke===P){oe=!0,P=Q,j=W;break}ke=ke.sibling}if(!oe)throw Error(s(189))}}if(j.alternate!==P)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?w:O}function f(w){var O=w.tag;if(O===5||O===26||O===27||O===6)return w;for(w=w.child;w!==null;){if(O=f(w),O!==null)return O;w=w.sibling}return null}var p=Object.assign,h=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),k=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),R=Symbol.iterator;function L(w){return w===null||typeof w!="object"?null:(w=R&&w[R]||w["@@iterator"],typeof w=="function"?w:null)}var D=Symbol.for("react.client.reference");function F(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===D?null:w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){case y:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case _:return"Suspense";case E:return"SuspenseList";case I:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case v:return"Portal";case k:return w.displayName||"Context";case S:return(w._context.displayName||"Context")+".Consumer";case C:var O=w.render;return w=w.displayName,w||(w=O.displayName||O.name||"",w=w!==""?"ForwardRef("+w+")":"ForwardRef"),w;case T:return O=w.displayName||null,O!==null?O:F(w.type)||"Memo";case N:O=w._payload,w=w._init;try{return F(w(O))}catch{}}return null}var H=Array.isArray,B=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,U=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},M=[],G=-1;function q(w){return{current:w}}function $(w){0>G||(w.current=M[G],M[G]=null,G--)}function z(w,O){G++,M[G]=w.current,w.current=O}var Z=q(null),K=q(null),re=q(null),ee=q(null);function J(w,O){switch(z(re,O),z(K,w),z(Z,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?c$e(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=c$e(O),w=u$e(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(Z),z(Z,w)}function ae(){$(Z),$(K),$(re)}function fe(w){w.memoizedState!==null&&z(ee,w);var O=Z.current,j=u$e(O,w.type);O!==j&&(z(K,w),z(Z,j))}function Y(w){K.current===w&&($(Z),$(K)),ee.current===w&&($(ee),HA._currentValue=V)}var te,ue;function de(w){if(te===void 0)try{throw Error()}catch(j){var O=j.stack.trim().match(/\n( *(at )?)/);te=O&&O[1]||"",ue=-1<j.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+te+w+ue}var ce=!1;function ge(w,O){if(!w||ce)return"";ce=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var P={DetermineComponentFrameRoot:function(){try{if(O){var jt=function(){throw Error()};if(Object.defineProperty(jt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(jt,[])}catch(ht){var ut=ht}Reflect.construct(w,[],jt)}else{try{jt.call()}catch(ht){ut=ht}w.call(jt.prototype)}}else{try{throw Error()}catch(ht){ut=ht}(jt=w())&&typeof jt.catch=="function"&&jt.catch(function(){})}}catch(ht){if(ht&&ut&&typeof ht.stack=="string")return[ht.stack,ut.stack]}return[null,null]}};P.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor(P.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty(P.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=P.DetermineComponentFrameRoot(),oe=Q[0],ke=Q[1];if(oe&&ke){var Be=oe.split(`
@@ -231,7 +231,7 @@ attempted value: ${i}
231
231
  \${}
232
232
  }
233
233
  }`,{label:"class",detail:"definition",type:"keyword"}),sf('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),sf('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],tSt=Rke.concat([sf("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),sf("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),sf("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),M8e=new a0t,nSt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function wR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const KUn=["FunctionDeclaration"],XUn={FunctionDeclaration:wR("function"),ClassDeclaration:wR("class"),ClassExpression:()=>!0,EnumDeclaration:wR("constant"),TypeAliasDeclaration:wR("type"),NamespaceDeclaration:wR("namespace"),VariableDefinition(e,t){e.matchContext(KUn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function rSt(e,t){let n=M8e.get(t);if(n)return n;let r=[],s=!0;function a(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(La.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=XUn[i.name];if(l&&l(i,a)||nSt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of rSt(e,i.node))r.push(l);return!1}}),M8e.set(t,r),r}const TB=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Pke=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function sSt(e){let t=xi(e.state).resolveInner(e.pos,-1);if(Pke.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&TB.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)nSt.has(s.name)&&(r=r.concat(rSt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:TB}}function Iee(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,i;if(a?.name=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if(a?.name=="MemberExpression"&&((r=i=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(i)),t=a;else return null}}function aSt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=xi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?Iee(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?Iee(t,n.parent,""):Pke.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&TB.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?Iee(t,n,""):e.explicit?{path:[],name:""}:null}function JUn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let i=Object.getPrototypeOf(e);if(!i)return r;e=i}}function eVn(e){let t=new Map;return n=>{let r=aSt(n);if(!r)return null;let s=e;for(let i of r.path)if(s=s[i],!s)return null;let a=t.get(s);return a||t.set(s,a=JUn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:TB}}}const tm=zO.define({name:"javascript",parser:YUn.configure({props:[Z_.add({IfStatement:WT({except:/^\s*({|else\b)/}),TryStatement:WT({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:G8n,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:Z8n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":WT({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),G_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":pke,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:"$"}}),iSt={test:e=>/^JSX/.test(e.name),facet:MH({commentTokens:{block:{open:"{/*",close:"*/}"}}})},$ke=tm.configure({dialect:"ts"},"typescript"),Mke=tm.configure({dialect:"jsx",props:[uke.add(e=>e.isTop?[iSt]:void 0)]}),Dke=tm.configure({dialect:"jsx ts",props:[uke.add(e=>e.isTop?[iSt]:void 0)]},"typescript");let oSt=e=>({label:e,type:"keyword"});const lSt="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(oSt),tVn=lSt.concat(["declare","implements","private","protected","public"].map(oSt));function jB(e={}){let t=e.jsx?e.typescript?Dke:Mke:e.typescript?$ke:tm,n=e.typescript?tSt.concat(tVn):Rke.concat(lSt);return new UO(t,[tm.data.of({autocomplete:R9n(Pke,i1t(n))}),tm.data.of({autocomplete:sSt}),e.jsx?cSt:[]])}function nVn(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 D8e(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 rVn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),cSt=It.inputHandler.of((e,t,n,r,s)=>{if((rVn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!tm.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=xi(i).resolveInner(d-1,-1),p;if(f.name=="JSXStartTag"&&(f=f.parent),!(i.doc.sliceString(d-1,d)!=r||f.name=="JSXAttributeValue"&&f.to>d)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:d,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let h=f.parent,m=h.parent;if(m&&h.from==d-2&&((p=D8e(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${p}>`;return{range:bt.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let h=nVn(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=D8e(i.doc,h,d)))return{range:c,changes:{from:d,insert:`</${p}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function sVn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:i}of tm.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let u of e.verify(r.sliceDoc(a,i),t))s.push(aVn(u,r.doc,c))}return s}}function L8e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function aVn(e,t,n){let r=L8e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?L8e(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:i}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(u,d){u.dispatch({changes:{from:d+l,to:d+c,insert:i},scrollIntoView:!0})}}]}return s}const G6=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:cSt,completionPath:aSt,esLint:sVn,javascript:jB,javascriptLanguage:tm,jsxLanguage:Mke,localCompletionSource:sSt,scopeCompletionSource:eVn,snippets:Rke,tsxLanguage:Dke,typescriptLanguage:$ke,typescriptSnippets:tSt},Symbol.toStringTag,{value:"Module"})),SR=["_blank","_self","_top","_parent"],Aee=["ascii","utf-8","utf-16","latin1","latin1"],Ree=["get","post","put","delete"],Pee=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],up=["true","false"],tr={},iVn={a:{attrs:{href:null,ping:null,type:null,media:null,target:SR,hreflang:null}},abbr:tr,address:tr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:tr,aside:tr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:tr,base:{attrs:{href:null,target:SR}},bdi:tr,bdo:tr,blockquote:{attrs:{cite:null}},body:tr,br:tr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Pee,formmethod:Ree,formnovalidate:["novalidate"],formtarget:SR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:tr,center:tr,cite:tr,code:tr,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:tr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:tr,div:tr,dl:tr,dt:tr,em:tr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:tr,figure:tr,footer:tr,form:{attrs:{action:null,name:null,"accept-charset":Aee,autocomplete:["on","off"],enctype:Pee,method:Ree,novalidate:["novalidate"],target:SR}},h1:tr,h2:tr,h3:tr,h4:tr,h5:tr,h6:tr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:tr,hgroup:tr,hr:tr,html:{attrs:{manifest:null}},i:tr,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Pee,formmethod:Ree,formnovalidate:["novalidate"],formtarget:SR,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:tr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:tr,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:tr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:Aee,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:tr,noscript:tr,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:tr,param:{attrs:{name:null,value:null}},pre:tr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:tr,rt:tr,ruby:tr,samp:tr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:Aee}},section:tr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:tr,source:{attrs:{src:null,type:null,media:null}},span:tr,strong:tr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:tr,summary:tr,sup:tr,table:tr,tbody:tr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:tr,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:tr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:tr,time:{attrs:{datetime:null}},title:tr,tr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:tr,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:tr},uSt={accesskey:null,class:null,contenteditable:up,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:up,autocorrect:up,autocapitalize:up,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":up,"aria-autocomplete":["inline","list","both","none"],"aria-busy":up,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":up,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":up,"aria-hidden":up,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":up,"aria-multiselectable":up,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":up,"aria-relevant":null,"aria-required":up,"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},dSt="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 dSt)uSt[e]=null;class bM{constructor(t,n){this.tags={...iVn,...t},this.globalAttrs={...uSt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}bM.default=new bM;function Bj(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 Uj(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function fSt(e,t,n){let r=n.tags[Bj(e,Uj(t))];return r?.children||n.allTags}function Lke(e,t){let n=[];for(let r=Uj(t);r&&!r.type.isTop;r=Uj(r.parent)){let s=Bj(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 pSt=/^[:\-\.\w\u00b7-\uffff]*$/;function F8e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=Uj(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:fSt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(Lke(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function z8e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:Lke(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:pSt}}function oVn(e,t,n,r){let s=[],a=0;for(let i of fSt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of Lke(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function lVn(e,t,n,r,s){let a=Uj(n),i=a?t.tags[Bj(e.doc,a)]:null,l=i&&i.attrs?Object.keys(i.attrs):[],c=i&&i.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(u=>({label:u,type:"property"})),validFor:pSt}}function cVn(e,t,n,r,s){var a;let i=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(i){let u=e.sliceDoc(i.from,i.to),d=t.globalAttrs[u];if(!d){let f=Uj(n),p=f?t.tags[Bj(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 hSt(e,t){let{state:n,pos:r}=t,s=xi(n).resolveInner(r,-1),a=s.resolve(r);for(let i=r,l;a==s&&(l=s.childBefore(i));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,i=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?z8e(n,s,s.from,r):F8e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?F8e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?z8e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?lVn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?cVn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?oVn(n,e,s,r):null}function uVn(e){return hSt(bM.default,e)}function dVn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new bM(t,n):bM.default;return s=>hSt(r,s)}const fVn=tm.parser.configure({top:"SingleExpression"}),mSt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:$ke.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:Mke.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:Dke.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:fVn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:tm.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:EB.parser}],gSt=[{name:"style",parser:EB.parser.configure({top:"Styles"})}].concat(dSt.map(e=>({name:e,parser:tm.parser}))),vSt=zO.define({name:"html",parser:DBn.configure({props:[Z_.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),G_.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),Jwt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),j8=vSt.configure({wrap:G1t(mSt,gSt)});function pVn(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=G1t((e.nestedLanguages||[]).concat(mSt),(e.nestedAttributes||[]).concat(gSt)));let r=n?vSt.configure({wrap:n,dialect:t}):t?j8.configure({dialect:t}):j8;return new UO(r,[j8.data.of({autocomplete:dVn(e)}),e.autoCloseTags!==!1?hVn:[],jB().support,bUn().support])}const B8e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),hVn=It.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!j8.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let p=i.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,m=xi(i).resolveInner(h,-1),v;if(p&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(v=Bj(i.doc,y.parent,h))&&!B8e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`</${v}>`;return{range:c,changes:{from:h,to:b,insert:x}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==h-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(v=Bj(i.doc,y,h))&&!B8e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`${v}>`;return{range:bt.cursor(h+x.length,-1),changes:{from:h,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),ySt=MH({commentTokens:{block:{open:"<!--",close:"-->"}}}),bSt=new Dr,xSt=F7n.configure({props:[G_.add(e=>!e.is("Block")||e.is("Document")||Lge(e)!=null||mVn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),bSt.add(Lge),Z_.add({Document:()=>null}),Nw.add({Document:ySt})]});function Lge(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function mVn(e){return e.name=="OrderedList"||e.name=="BulletList"}function gVn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=Lge(r.type))!=null&&s<=t)break;n=r}return n.to}const vVn=Bwt.of((e,t,n)=>{for(let r=xi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(bSt);if(s==null)continue;let a=gVn(r,s);if(a>n)return{from:n,to:a}}return null});function Fke(e){return new Ip(ySt,e,[],"markdown")}const wSt=Fke(xSt),yVn=xSt.configure([Y7n,X7n,K7n,J7n,{props:[G_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),HO=Fke(yVn);function bVn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=og.matchLanguageName(e,n,!0),r instanceof og)return r.support?r.support.language.parser:BO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class $ee{constructor(t,n,r,s,a,i,l){this.node=t,this.from=n,this.to=r,this.spaceBefore=s,this.spaceAfter=a,this.type=i,this.item=l}blank(t,n=!0){let r=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(t!=null){for(;r.length<t;)r+=" ";return r}else{for(let s=this.to-this.from-r.length-this.spaceAfter.length;s>0;s--)r+=" ";return r+(n?this.spaceAfter:"")}}marker(t,n){let r=this.node.name=="OrderedList"?String(+kSt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function SSt(e,t){let n=[],r=[];for(let s=e;s;s=s.parent){if(s.name=="FencedCode")return r;(s.name=="ListItem"||s.name=="Blockquote")&&n.push(s)}for(let s=n.length-1;s>=0;s--){let a=n[s],i,l=t.lineAt(a.from),c=a.from-l.from;if(a.name=="Blockquote"&&(i=/^ *>( ?)/.exec(l.text.slice(c))))r.push(new $ee(a,c,c+i[0].length,"",i[1],">",null));else if(a.name=="ListItem"&&a.parent.name=="OrderedList"&&(i=/^( *)\d+([.)])( *)/.exec(l.text.slice(c)))){let u=i[3],d=i[0].length;u.length>=4&&(u=u.slice(0,u.length-4),d-=4),r.push(new $ee(a.parent,c,c+d,i[1],u,i[2],a))}else if(a.name=="ListItem"&&a.parent.name=="BulletList"&&(i=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(c)))){let u=i[4],d=i[0].length;u.length>4&&(u=u.slice(0,u.length-4),d-=4);let f=i[2];i[3]&&(f+=i[3].replace(/[xX]/," ")),r.push(new $ee(a.parent,c,c+d,i[1],u,f,a))}}return r}function kSt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function Mee(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=kSt(a,t),c=+l[2];if(s>=0){if(c!=s+1)return;n.push({from:a.from+l[1].length,to:a.from+l[0].length,insert:String(s+2+r)})}s=c}let i=a.nextSibling;if(!i)break;a=i}}function zke(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(dI)!=" ")return e;let r=Lg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const OSt=(e={})=>({state:t,dispatch:n})=>{let r=xi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!HO.isActiveAt(t,l.from,-1)&&!HO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=SSt(r.resolveInner(c,-1),s);for(;d.length&&d[d.length-1].from>c-u.from;)d.pop();if(!d.length)return a={range:l};let f=d[d.length-1];if(f.to-f.spaceAfter.length>c-u.from)return a={range:l};let p=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&p){let b=f.node.firstChild,x=f.node.getChild("ListItem","ListItem");if(b.to>=c||x&&x.to<c||u.from>0&&!/[^\s>]/.test(s.lineAt(u.from-1).text)||e.nonTightLists===!1){let S=d.length>1?d[d.length-2]:null,k,C="";S&&S.item?(k=u.from+S.from,C=S.marker(s,1)):k=u.from+(S?S.to:0);let _=[{from:k,to:c,insert:C}];return f.node.name=="OrderedList"&&Mee(f.item,s,_,-2),S&&S.node.name=="OrderedList"&&Mee(S.item,s,_),{range:bt.cursor(k+C.length),changes:_}}else{let S=V8e(d,t,u);return{range:bt.cursor(c+S.length+1),changes:{from:u.from,insert:S+t.lineBreak}}}}if(f.node.name=="Blockquote"&&p&&u.from){let b=s.lineAt(u.from-1),x=/>\s*$/.exec(b.text);if(x&&x.index==f.from){let S=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(S),changes:S}}}let h=[];f.node.name=="OrderedList"&&Mee(f.item,s,h);let m=f.item&&f.item.from<u.from,v="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)v+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?Lg(u.text,4,d[b+1].from)-v.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return v=zke(v,t),xVn(f.node,t.doc)&&(v=V8e(d,t,u)+t.lineBreak+v),h.push({from:y,to:c,insert:t.lineBreak+v}),{range:bt.cursor(y+v.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},_St=OSt();function U8e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function xVn(e,t){if(e.name!="OrderedList"&&e.name!="BulletList")return!1;let n=e.firstChild,r=e.getChild("ListItem","ListItem");if(!r)return!1;let s=t.lineAt(n.to),a=t.lineAt(r.from),i=/^[\s>]*$/.test(s.text);return s.number+(i?0:1)<a.number}function V8e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Lg(n.text,4,e[s+1].from)-r.length:null,s<a);return zke(r,t)}function wVn(e,t){let n=e.resolveInner(t,-1),r=t;U8e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(U8e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const CSt=({state:e,dispatch:t})=>{let n=xi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&HO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=SSt(wVn(n,i),l);if(u.length){let d=u[u.length-1],f=d.to-d.spaceAfter.length+(d.spaceAfter?1:0);if(i-c.from>f&&!/\S/.test(c.text.slice(f,i-c.from)))return{range:bt.cursor(c.from+f),changes:{from:c.from+f,to:i}};if(i-c.from==f&&(!d.item||c.from<=d.item.from||!/\S/.test(c.text.slice(0,d.to)))){let p=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let h=d.blank(Lg(c.text,4,d.to)-Lg(c.text,4,d.from));return p==c.from&&(h=zke(h,e)),{range:bt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:bt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},ESt=[{key:"Enter",run:_St},{key:"Backspace",run:CSt}],TSt=pVn({matchClosingTags:!1});function Bke(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=wSt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=TSt}=e;if(!(s instanceof zH))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,vVn],d;i&&u.push(jSt),n instanceof UO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?bVn(t,d):void 0;c.push(B7n({codeParser:f,htmlParser:l.language.parser})),r&&u.push(nh.high(uI.of(ESt)));let p=Fke(s.configure(c));return a&&u.push(p.data.of({autocomplete:SVn})),new UO(p,u)}function SVn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=xi(t).resolveInner(n,-1);for(;s&&!s.type.isTop;){if(s.name=="CodeBlock"||s.name=="FencedCode"||s.name=="ProcessingInstructionBlock"||s.name=="CommentBlock"||s.name=="Link"||s.name=="Image")return null;s=s.parent}return{from:n-r[0].length,to:n,options:kVn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let Dee=null;function kVn(){if(Dee)return Dee;let e=uVn(new vke(us.create({extensions:TSt}),0,!0));return Dee=e?e.options:[]}const OVn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,jSt=It.domEventHandlers({paste:(e,t)=>{var n;let{main:r}=t.state.selection;if(r.empty)return!1;let s=(n=e.clipboardData)===null||n===void 0?void 0:n.getData("text/plain");if(!s||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(s)||(/^www\./.test(s)&&(s="https://"+s),!HO.isActiveAt(t.state,r.from,1)))return!1;let a=xi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||OVn.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)}}),_Vn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:wSt,deleteMarkupBackward:CSt,insertNewlineContinueMarkup:_St,insertNewlineContinueMarkupCommand:OSt,markdown:Bke,markdownKeymap:ESt,markdownLanguage:HO,pasteURLAsLink:jSt},Symbol.toStringTag,{value:"Module"}));function WO(){return WO=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},WO.apply(null,arguments)}var CVn=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,a=s===void 0?[]:s,i={".cm-gutters":{}},l={};r.background&&(l.backgroundColor=r.background),r.backgroundImage&&(l.backgroundImage=r.backgroundImage),r.foreground&&(l.color=r.foreground),r.fontSize&&(l.fontSize=r.fontSize),(r.background||r.foreground)&&(i["&"]=l),r.fontFamily&&(i["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(i[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(i[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(i[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(i[".cm-content"]={caretColor:r.caret},i[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var c={};r.gutterActiveForeground&&(c.color=r.gutterActiveForeground),r.lineHighlight&&(i[".cm-activeLine"]={backgroundColor:r.lineHighlight},c.backgroundColor=r.lineHighlight),i[".cm-activeLineGutter"]=c,r.selection&&(i["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(i["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var u=It.theme(i,{dark:t==="dark"}),d=Wg.define(a),f=[u,eS(d)];return f},EVn={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)"},TVn=[{tag:he.comment,color:"#6272a4"},{tag:he.string,color:"#f1fa8c"},{tag:he.atom,color:"#bd93f9"},{tag:he.meta,color:"#f8f8f2"},{tag:[he.keyword,he.operator,he.tagName],color:"#ff79c6"},{tag:[he.function(he.propertyName),he.propertyName],color:"#66d9ef"},{tag:[he.definition(he.variableName),he.function(he.variableName),he.className,he.attributeName],color:"#50fa7b"},{tag:he.atom,color:"#bd93f9"}],pI=e=>{var t=e||{},n=t.theme,r=n===void 0?"dark":n,s=t.settings,a=s===void 0?{}:s,i=t.styles,l=i===void 0?[]:i;return CVn({theme:r,settings:WO({},EVn,a),styles:[...TVn,...l]})};pI();function NSt(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 jVn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=Vke(e.state,n.from);return r.line?NVn(e):r.block?AVn(e):!1};function Uke(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 NVn=Uke($Vn,0),IVn=Uke(ISt,0),AVn=Uke((e,t)=>ISt(e,t,PVn(t)),0);function Vke(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const kR=50;function RVn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-kR,r),i=e.sliceDoc(s,s+kR),l=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(i)[0].length,u=a.length-l;if(a.slice(u-t.length,u)==t&&i.slice(c,c+n.length)==n)return{open:{pos:r-l,margin:l&&1},close:{pos:s+c,margin:c&&1}};let d,f;s-r<=2*kR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+kR),f=e.sliceDoc(s-kR,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 PVn(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),s=n.to<=r.to?r:e.doc.lineAt(n.to);s.from>r.from&&s.from==n.to&&(s=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=s.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return t}function ISt(e,t,n=t.selection.ranges){let r=n.map(a=>Vke(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>RVn(t,r[i],a.from,a.to));if(e!=2&&!s.every(a=>a))return{changes:t.changes(n.map((a,i)=>s[i]?[]:[{from:a.from,insert:r[i].open+" "},{from:a.to,insert:" "+r[i].close}]))};if(e!=1&&s.some(a=>a)){let a=[];for(let i=0,l;i<s.length;i++)if(l=s[i]){let c=r[i],{open:u,close:d}=l;a.push({from:u.pos-c.open.length,to:u.pos+u.margin},{from:d.pos-d.margin,to:d.pos+c.close.length})}return{changes:a}}return null}function $Vn(e,t,n=t.selection.ranges){let r=[],s=-1;e:for(let{from:a,to:i}of n){let l=r.length,c=1e9,u;for(let d=a;d<=i;){let f=t.doc.lineAt(d);if(u==null&&(u=Vke(t,f.from).line,!u))continue e;if(f.from>s&&(a==i||i>f.from)){s=f.from;let p=/^\s*/.exec(f.text)[0].length,h=p==f.length,m=f.text.slice(p,p+u.length)==u?p:-1;p<f.text.length&&p<c&&(c=p),r.push({line:f,comment:m,token:u,indent:p,empty:h,single:!1})}d=f.to+1}if(c<1e9)for(let d=l;d<r.length;d++)r[d].indent<r[d].line.text.length&&(r[d].indent=c);r.length==l+1&&(r[l].single=!0)}if(e!=2&&r.some(a=>a.comment<0&&(!a.empty||a.single))){let a=[];for(let{line:l,token:c,indent:u,empty:d,single:f}of r)(f||!d)&&a.push({from:l.from+u,insert:c+" "});let i=t.changes(a);return{changes:i,selection:t.selection.map(i,1)}}else if(e!=1&&r.some(a=>a.comment>=0)){let a=[];for(let{line:i,comment:l,token:c}of r)if(l>=0){let u=i.from+l,d=u+c.length;i.text[d-i.from]==" "&&d++,a.push({from:u,to:d})}return{changes:a}}return null}const Fge=zy.define(),MVn=zy.define(),DVn=Tn.define(),ASt=Tn.define({combine(e){return By(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)})}}),RSt=bl.define({create(){return Zv.empty},update(e,t){let n=t.state.facet(ASt),r=t.annotation(Fge);if(r){let c=xf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=NB(d,d.length,n.minDepth,c):d=MSt(d,t.startState.selection),new Zv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(MVn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Pl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=xf.fromTransaction(t),i=t.annotation(Pl.time),l=t.annotation(Pl.userEvent);return a?e=e.addChanges(a,i,l,n,t):t.selection&&(e=e.addSelection(t.startState.selection,i,l,n.newGroupDelay)),(s=="full"||s=="after")&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(t=>t.toJSON()),undone:e.undone.map(t=>t.toJSON())}},fromJSON(e){return new Zv(e.done.map(xf.fromJSON),e.undone.map(xf.fromJSON))}});function LVn(e={}){return[RSt,ASt.of(e),It.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?PSt:t.inputType=="historyRedo"?zge:null;return r?(t.preventDefault(),r(n)):!1}})]}function BH(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(RSt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const PSt=BH(0,!1),zge=BH(1,!1),FVn=BH(0,!0),zVn=BH(1,!0);class xf{constructor(t,n,r,s,a){this.changes=t,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=a}setSelAfter(t){return new xf(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 xf(t.changes&&Al.fromJSON(t.changes),[],t.mapped&&ay.fromJSON(t.mapped),t.startSelection&&bt.fromJSON(t.startSelection),t.selectionsAfter.map(bt.fromJSON))}static fromTransaction(t,n){let r=Hh;for(let s of t.startState.facet(DVn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new xf(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,Hh)}static selection(t){return new xf(void 0,Hh,void 0,void 0,t)}}function NB(e,t,n,r){let s=t+1>n+20?t-n-1:0,a=e.slice(s,t);return a.push(r),a}function BVn(e,t){let n=[],r=!1;return e.iterChangedRanges((s,a)=>n.push(s,a)),t.iterChangedRanges((s,a,i,l)=>{for(let c=0;c<n.length;){let u=n[c++],d=n[c++];l>=u&&i<=d&&(r=!0)}}),r}function UVn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function $St(e,t){return e.length?t.length?e.concat(t):e:t}const Hh=[],VVn=200;function MSt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-VVn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),NB(e,e.length-1,1e9,n.setSelAfter(r)))}else return[xf.selection([t])]}function qVn(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 Lee(e,t){if(!e.length)return e;let n=e.length,r=Hh;for(;n;){let s=HVn(e[n-1],t,r);if(s.changes&&!s.changes.empty||s.effects.length){let a=e.slice(0,n);return a[n-1]=s,a}else t=s.mapped,n--,r=s.selectionsAfter}return r.length?[xf.selection(r)]:Hh}function HVn(e,t,n){let r=$St(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Hh,n);if(!e.changes)return xf.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new xf(s,xr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const WVn=/^(input\.type|delete)($|\.)/;class Zv{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 Zv(this.done,this.undone):this}addChanges(t,n,r,s,a){let i=this.done,l=i[i.length-1];return l&&l.changes&&!l.changes.empty&&t.changes&&(!r||WVn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,BVn(l.changes,t.changes))||r=="input.type.compose")?i=NB(i,i.length-1,s.minDepth,new xf(t.changes.compose(l.changes),$St(xr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Hh)):i=NB(i,i.length,s.minDepth,t),new Zv(i,Hh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Hh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&UVn(a[a.length-1],t)?this:new Zv(MSt(this.done,t),this.undone,n,r)}addMapping(t){return new Zv(Lee(this.done,t),Lee(this.undone,t),this.prevTime,this.prevUserEvent)}pop(t,n,r){let s=t==0?this.done:this.undone;if(s.length==0)return null;let a=s[s.length-1],i=a.selectionsAfter[0]||(a.startSelection?a.startSelection.map(a.changes.invertedDesc,1):n.selection);if(r&&a.selectionsAfter.length)return n.update({selection:a.selectionsAfter[a.selectionsAfter.length-1],annotations:Fge.of({side:t,rest:qVn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Hh:s.slice(0,s.length-1);return a.mapped&&(l=Lee(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:Fge.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Zv.empty=new Zv(Hh,Hh);const ZVn=[{key:"Mod-z",run:PSt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:zge,preventDefault:!0},{linux:"Ctrl-Shift-z",run:zge,preventDefault:!0},{key:"Mod-u",run:FVn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:zVn,preventDefault:!0}];function hI(e,t){return bt.create(e.ranges.map(t),e.mainIndex)}function Zg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function Gg({state:e,dispatch:t},n){let r=hI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Zg(e,r)),!0)}function UH(e,t){return bt.cursor(t?e.to:e.from)}function DSt(e,t){return Gg(e,n=>n.empty?e.moveByChar(n,t):UH(n,t))}function rd(e){return e.textDirectionAt(e.state.selection.main.head)==Ci.LTR}const LSt=e=>DSt(e,!rd(e)),FSt=e=>DSt(e,rd(e));function zSt(e,t){return Gg(e,n=>n.empty?e.moveByGroup(n,t):UH(n,t))}const GVn=e=>zSt(e,!rd(e)),QVn=e=>zSt(e,rd(e));function YVn(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 VH(e,t,n){let r=xi(e).resolveInner(t.head),s=n?Dr.closedBy:Dr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;YVn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?Wv(e,r.from,1):Wv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,bt.cursor(l,n?-1:1)}const KVn=e=>Gg(e,t=>VH(e.state,t,!rd(e))),XVn=e=>Gg(e,t=>VH(e.state,t,rd(e)));function BSt(e,t){return Gg(e,n=>{if(!n.empty)return UH(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const USt=e=>BSt(e,!1),VSt=e=>BSt(e,!0);function qSt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(It.scrollMargins)){let i=a(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}s=e.scrollDOM.clientHeight-n-r}else s=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,s-5)}}function HSt(e,t){let n=qSt(e),{state:r}=e,s=hI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):UH(i,t));if(s.eq(r.selection))return!1;let a;if(n.selfScroll){let i=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;i&&i.top>c&&i.bottom<u&&(a=It.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Zg(r,s),{effects:a}),!0}const q8e=e=>HSt(e,!1),Bge=e=>HSt(e,!0);function tS(e,t,n){let r=e.lineBlockAt(t.head),s=e.moveToLineBoundary(t,n);if(s.head==t.head&&s.head!=(n?r.to:r.from)&&(s=e.moveToLineBoundary(t,n,!1)),!n&&s.head==r.from&&r.length){let a=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;a&&t.head!=r.from+a&&(s=bt.cursor(r.from+a))}return s}const JVn=e=>Gg(e,t=>tS(e,t,!0)),eqn=e=>Gg(e,t=>tS(e,t,!1)),tqn=e=>Gg(e,t=>tS(e,t,!rd(e))),nqn=e=>Gg(e,t=>tS(e,t,rd(e))),rqn=e=>Gg(e,t=>bt.cursor(e.lineBlockAt(t.head).from,1)),sqn=e=>Gg(e,t=>bt.cursor(e.lineBlockAt(t.head).to,-1));function aqn(e,t,n){let r=!1,s=hI(e.selection,a=>{let i=Wv(e,a.head,-1)||Wv(e,a.head,1)||a.head>0&&Wv(e,a.head-1,1)||a.head<e.doc.length&&Wv(e,a.head+1,-1);if(!i||!i.end)return a;r=!0;let l=i.start.from==a.head?i.end.to:i.end.from;return bt.cursor(l)});return r?(t(Zg(e,s)),!0):!1}const iqn=({state:e,dispatch:t})=>aqn(e,t);function jm(e,t,n){let r=hI(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=bt.range(s.head,s.anchor));let a=n(s);return bt.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(Zg(e.state,r)),!0)}function WSt(e,t){return jm(e,t,n=>e.moveByChar(n,t))}const ZSt=e=>WSt(e,!rd(e)),GSt=e=>WSt(e,rd(e));function QSt(e,t){return jm(e,t,n=>e.moveByGroup(n,t))}const oqn=e=>QSt(e,!rd(e)),lqn=e=>QSt(e,rd(e)),cqn=e=>{let t=!rd(e);return jm(e,t,n=>VH(e.state,n,t))},uqn=e=>{let t=rd(e);return jm(e,t,n=>VH(e.state,n,t))};function YSt(e,t){return jm(e,t,n=>e.moveVertically(n,t))}const KSt=e=>YSt(e,!1),XSt=e=>YSt(e,!0);function JSt(e,t){return jm(e,t,n=>e.moveVertically(n,t,qSt(e).height))}const H8e=e=>JSt(e,!1),W8e=e=>JSt(e,!0),dqn=e=>jm(e,!0,t=>tS(e,t,!0)),fqn=e=>jm(e,!1,t=>tS(e,t,!1)),pqn=e=>{let t=!rd(e);return jm(e,t,n=>tS(e,n,t))},hqn=e=>{let t=rd(e);return jm(e,t,n=>tS(e,n,t))},mqn=e=>jm(e,!1,t=>bt.cursor(e.lineBlockAt(t.head).from)),gqn=e=>jm(e,!0,t=>bt.cursor(e.lineBlockAt(t.head).to)),Z8e=({state:e,dispatch:t})=>(t(Zg(e,{anchor:0})),!0),G8e=({state:e,dispatch:t})=>(t(Zg(e,{anchor:e.doc.length})),!0),Q8e=({state:e,dispatch:t})=>(t(Zg(e,{anchor:e.selection.main.anchor,head:0})),!0),Y8e=({state:e,dispatch:t})=>(t(Zg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),vqn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),yqn=({state:e,dispatch:t})=>{let n=qH(e).map(({from:r,to:s})=>bt.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:bt.create(n),userEvent:"select"})),!0},bqn=({state:e,dispatch:t})=>{let n=hI(e.selection,r=>{let s=xi(e),a=s.resolveStack(r.from,1);if(r.empty){let i=s.resolveStack(r.from,-1);i.node.from>=a.node.from&&i.node.to<=a.node.to&&(a=i)}for(let i=a;i;i=i.next){let{node:l}=i;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&i.next)return bt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Zg(e,n)),!0)};function ekt(e,t){let{state:n}=e,r=n.selection,s=n.selection.ranges.slice();for(let a of n.selection.ranges){let i=n.doc.lineAt(a.head);if(t?i.to<e.state.doc.length:i.from>0)for(let l=a;;){let c=e.moveVertically(l,t);if(c.head<i.from||c.head>i.to){s.some(u=>u.head==c.head)||s.push(c);break}else{if(c.head==l.head)break;l=c}}}return s.length==r.ranges.length?!1:(e.dispatch(Zg(n,bt.create(s,s.length-1))),!0)}const xqn=e=>ekt(e,!1),wqn=e=>ekt(e,!0),Sqn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=bt.create([n.main]):n.main.empty||(r=bt.create([bt.cursor(n.main.head)])),r?(t(Zg(e,r)),!0):!1};function P3(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(a=>{let{from:i,to:l}=a;if(i==l){let c=t(a);c<i?(n="delete.backward",c=Q6(e,c,!1)):c>i&&(n="delete.forward",c=Q6(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=Q6(e,i,!1),l=Q6(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:bt.cursor(i,i<a.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?It.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function Q6(e,t,n){if(e instanceof It)for(let r of e.state.facet(It.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const tkt=(e,t,n)=>P3(e,r=>{let s=r.from,{state:a}=e,i=a.doc.lineAt(s),l,c;if(n&&!t&&s>i.from&&s<i.from+200&&!/[^ \t]/.test(l=i.text.slice(0,s-i.from))){if(l[l.length-1]==" ")return s-1;let u=Lg(l,a.tabSize),d=u%VO(a)||VO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Oc(i.text,s-i.from,t,t)+i.from,c==s&&i.number!=(t?a.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(i.text.slice(c-i.from,s-i.from))&&(c=Oc(i.text,c-i.from,!1,!1)+i.from);return c}),Uge=e=>tkt(e,!1,!0),nkt=e=>tkt(e,!0,!1),rkt=(e,t)=>P3(e,n=>{let r=n.head,{state:s}=e,a=s.doc.lineAt(r),i=s.charCategorizer(r);for(let l=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?s.doc.lines:1)&&(r+=t?1:-1);break}let c=Oc(a.text,r-a.from,t)+a.from,u=a.text.slice(Math.min(r,c)-a.from,Math.max(r,c)-a.from),d=i(u);if(l!=null&&d!=l)break;(u!=" "||r!=n.head)&&(l=d),r=c}return r}),skt=e=>rkt(e,!1),kqn=e=>rkt(e,!0),Oqn=e=>P3(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),_qn=e=>P3(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),Cqn=e=>P3(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),Eqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:ka.of(["",""])},range:bt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},Tqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>{if(!r.empty||r.from==0||r.from==e.doc.length)return{range:r};let s=r.from,a=e.doc.lineAt(s),i=s==a.from?s-1:Oc(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Oc(a.text,s-a.from,!0)+a.from;return{changes:{from:i,to:l,insert:e.doc.slice(s,l).append(e.doc.slice(i,s))},range:bt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function qH(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=s.number){let i=t[t.length-1];i.to=a.to,i.ranges.push(r)}else t.push({from:s.from,to:a.to,ranges:[r]});n=a.number+1}return t}function akt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of qH(e)){if(n?a.to==e.doc.length:a.from==0)continue;let i=e.doc.lineAt(n?a.to+1:a.from-1),l=i.length+1;if(n){r.push({from:a.to,to:i.to},{from:a.from,insert:i.text+e.lineBreak});for(let c of a.ranges)s.push(bt.range(Math.min(e.doc.length,c.anchor+l),Math.min(e.doc.length,c.head+l)))}else{r.push({from:i.from,to:a.from},{from:a.to,insert:e.lineBreak+i.text});for(let c of a.ranges)s.push(bt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:bt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const jqn=({state:e,dispatch:t})=>akt(e,t,!1),Nqn=({state:e,dispatch:t})=>akt(e,t,!0);function ikt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of qH(e))n?r.push({from:a.from,insert:e.doc.slice(a.from,a.to)+e.lineBreak}):r.push({from:a.to,insert:e.lineBreak+e.doc.slice(a.from,a.to)});let s=e.changes(r);return t(e.update({changes:s,selection:e.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const Iqn=({state:e,dispatch:t})=>ikt(e,t,!1),Aqn=({state:e,dispatch:t})=>ikt(e,t,!0),Rqn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(qH(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=hI(t.selection,s=>{let a;if(e.lineWrapping){let i=e.lineBlockAt(s.head),l=e.coordsAtPos(s.head,s.assoc||1);l&&(a=i.bottom+e.documentTop-l.bottom+e.defaultLineHeight/2)}return e.moveVertically(s,!0,a)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function Pqn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=xi(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),a;return r&&s&&r.to<=t&&s.from>=t&&(a=r.type.prop(Dr.closedBy))&&a.indexOf(s.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(s.from).from&&!/\S/.test(e.sliceDoc(r.to,s.from))?{from:r.to,to:s.from}:null}const K8e=okt(!1),$qn=okt(!0);function okt(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(s=>{let{from:a,to:i}=s,l=t.doc.lineAt(a),c=!e&&a==i&&Pqn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new DH(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=dke(u,a);for(d==null&&(d=Lg(/^\s*/.exec(t.doc.lineAt(a).text)[0],t.tabSize));i<l.to&&/\s/.test(l.text[i-l.from]);)i++;c?{from:a,to:i}=c:a>l.from&&a<l.from+100&&!/\S/.test(l.text.slice(0,a))&&(a=l.from);let f=["",dM(t,d)];return c&&f.push(dM(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:ka.of(f)},range:bt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function qke(e,t){let n=-1;return e.changeByRange(r=>{let s=[];for(let i=r.from;i<=r.to;){let l=e.doc.lineAt(i);l.number>n&&(r.empty||r.to>l.from)&&(t(l,s,r),n=l.number),i=l.to+1}let a=e.changes(s);return{changes:s,range:bt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const Mqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new DH(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=qke(e,(a,i,l)=>{let c=dke(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=dM(e,c);(u!=d||l.from<a.from+u.length)&&(n[a.from]=c,i.push({from:a.from,to:a.from+u.length,insert:d}))});return s.changes.empty||t(e.update(s,{userEvent:"indent"})),!0},lkt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(qke(e,(n,r)=>{r.push({from:n.from,insert:e.facet(dI)})}),{userEvent:"input.indent"})),!0),ckt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(qke(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Lg(s,e.tabSize),i=0,l=dM(e,Math.max(0,a-VO(e)));for(;i<s.length&&i<l.length&&s.charCodeAt(i)==l.charCodeAt(i);)i++;r.push({from:n.from+i,to:n.from+s.length,insert:l.slice(i)})}),{userEvent:"delete.dedent"})),!0),Dqn=e=>(e.setTabFocusMode(),!0),Lqn=[{key:"Ctrl-b",run:LSt,shift:ZSt,preventDefault:!0},{key:"Ctrl-f",run:FSt,shift:GSt},{key:"Ctrl-p",run:USt,shift:KSt},{key:"Ctrl-n",run:VSt,shift:XSt},{key:"Ctrl-a",run:rqn,shift:mqn},{key:"Ctrl-e",run:sqn,shift:gqn},{key:"Ctrl-d",run:nkt},{key:"Ctrl-h",run:Uge},{key:"Ctrl-k",run:Oqn},{key:"Ctrl-Alt-h",run:skt},{key:"Ctrl-o",run:Eqn},{key:"Ctrl-t",run:Tqn},{key:"Ctrl-v",run:Bge}],Fqn=[{key:"ArrowLeft",run:LSt,shift:ZSt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:GVn,shift:oqn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:tqn,shift:pqn,preventDefault:!0},{key:"ArrowRight",run:FSt,shift:GSt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:QVn,shift:lqn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:nqn,shift:hqn,preventDefault:!0},{key:"ArrowUp",run:USt,shift:KSt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Z8e,shift:Q8e},{mac:"Ctrl-ArrowUp",run:q8e,shift:H8e},{key:"ArrowDown",run:VSt,shift:XSt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:G8e,shift:Y8e},{mac:"Ctrl-ArrowDown",run:Bge,shift:W8e},{key:"PageUp",run:q8e,shift:H8e},{key:"PageDown",run:Bge,shift:W8e},{key:"Home",run:eqn,shift:fqn,preventDefault:!0},{key:"Mod-Home",run:Z8e,shift:Q8e},{key:"End",run:JVn,shift:dqn,preventDefault:!0},{key:"Mod-End",run:G8e,shift:Y8e},{key:"Enter",run:K8e,shift:K8e},{key:"Mod-a",run:vqn},{key:"Backspace",run:Uge,shift:Uge,preventDefault:!0},{key:"Delete",run:nkt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:skt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:kqn,preventDefault:!0},{mac:"Mod-Backspace",run:_qn,preventDefault:!0},{mac:"Mod-Delete",run:Cqn,preventDefault:!0}].concat(Lqn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),zqn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:KVn,shift:cqn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:XVn,shift:uqn},{key:"Alt-ArrowUp",run:jqn},{key:"Shift-Alt-ArrowUp",run:Iqn},{key:"Alt-ArrowDown",run:Nqn},{key:"Shift-Alt-ArrowDown",run:Aqn},{key:"Mod-Alt-ArrowUp",run:xqn},{key:"Mod-Alt-ArrowDown",run:wqn},{key:"Escape",run:Sqn},{key:"Mod-Enter",run:$qn},{key:"Alt-l",mac:"Ctrl-l",run:yqn},{key:"Mod-i",run:bqn,preventDefault:!0},{key:"Mod-[",run:ckt},{key:"Mod-]",run:lkt},{key:"Mod-Alt-\\",run:Mqn},{key:"Shift-Mod-k",run:Rqn},{key:"Shift-Mod-\\",run:iqn},{key:"Mod-/",run:jVn},{key:"Alt-A",run:IVn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:Dqn}].concat(Fqn),Bqn={key:"Tab",run:lkt,shift:ckt},X8e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Px{constructor(t,n,r=0,s=t.length,a,i){this.test=i,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(X8e(l)):X8e,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 df(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=WSe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=$v(t);let s=this.normalize(n);if(s.length)for(let a=0,i=r,l=!0;;a++){let c=s.charCodeAt(a),u=this.match(c,i,l,this.bufferPos+this.bufferStart,a==s.length-1);if(u)return this.value=u,this;if(a==s.length-1)break;l&&a<n.length&&n.charCodeAt(a)==c?i++:l=!1}}}match(t,n,r,s,a){let i=null;for(let l=0;l<this.matches.length;){let c=this.matches[l],u=!1;this.query.charCodeAt(c.index)==t&&(c.index==this.query.length-1?i={from:c.from,to:s,precise:a&&c.precise}:(c.index++,u=!0)),u?l++:this.matches.splice(l,1)}return this.query.charCodeAt(0)==t&&(this.query.length==1?i={from:n,to:s,precise:r&&a}:this.matches.push({from:n,index:1,precise:r})),i&&this.test&&!this.test(i.from,i.to,this.buffer,this.bufferStart)&&(i=null),i}}typeof Symbol<"u"&&(Px.prototype[Symbol.iterator]=function(){return this});const ukt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},Hke="gm"+(/x/.unicode==null?"":"u");class dkt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=ukt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new fkt(t,n,r,s,a);this.re=new RegExp(n,Hke+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=IB(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=IB(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 Fee=new WeakMap;class GT{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Fee.get(t);if(!s||s.from>=r||s.to<=n){let l=new GT(n,t.sliceString(n,r));return Fee.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:i}=s;return i>n&&(a=t.sliceString(n,i)+a,i=n),s.to<r&&(a+=t.sliceString(s.to,r)),Fee.set(t,new GT(i,a)),new GT(n,a.slice(n-i,r-i))}}class fkt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=ukt,this.matchPos=IB(t,s),this.re=new RegExp(n,Hke+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=GT.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=IB(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=GT.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(dkt.prototype[Symbol.iterator]=fkt.prototype[Symbol.iterator]=function(){return this});function Uqn(e){try{return new RegExp(e,Hke),!0}catch{return!1}}function IB(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 Vqn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=O8n(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let i=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=i,p=d?+d.slice(1):0,h=u?+u:l.number;if(u&&f){let y=h/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*y)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),v=bt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,It.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},qqn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Hqn=Tn.define({combine(e){return By(e,qqn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function Wqn(e){return[Kqn,Yqn]}const Zqn=An.mark({class:"cm-selectionMatch"}),Gqn=An.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function J8e(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=So.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=So.Word)}function Qqn(e,t,n,r){return e(t.sliceDoc(n,n+1))==So.Word&&e(t.sliceDoc(r-1,r))==So.Word}const Yqn=Co.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(Hqn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return An.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return An.none;let c=n.wordAt(s.head);if(!c)return An.none;i=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return An.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(J8e(i,n,s.from,s.to)&&Qqn(i,n,s.from,s.to)))return An.none}else if(a=n.sliceDoc(s.from,s.to),!a)return An.none}let l=[];for(let c of e.visibleRanges){let u=new Px(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||J8e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(Gqn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(Zqn.range(d,f)),l.length>t.maxMatches))return An.none}}return An.set(l)}},{decorations:e=>e.decorations}),Kqn=It.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Xqn=({state:e,dispatch:t})=>{let{selection:n}=e,r=bt.create(n.ranges.map(s=>e.wordAt(s.head)||bt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function Jqn(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let i=!1,l=new Px(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new Px(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const eHn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return Xqn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=Jqn(e,r);return s?(t(e.update({selection:e.selection.addRange(bt.range(s.from,s.to),!1),effects:It.scrollIntoView(s.to)})),!0):!1},mI=Tn.define({combine(e){return By(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new hHn(t),scrollToMatch:t=>It.scrollIntoView(t)})}});class pkt{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||Uqn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
234
- `:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new iHn(this):new rHn(this)}getCursor(t,n=0,r){let s=t.doc?t:us.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?WE(this,s,n,r):HE(this,s,n,r)}}class hkt{constructor(t){this.spec=t}}function tHn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function HE(e,t,n,r){let s;return e.wholeWord&&(s=nHn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=tHn(e.test,t,s)),new Px(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function nHn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(AB(s,n-a))!=So.Word||t(RB(s,n-a))!=So.Word)&&(t(RB(s,r-a))!=So.Word||t(AB(s,r-a))!=So.Word))}class rHn extends hkt{constructor(t){super(t)}nextMatch(t,n,r){let s=HE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=HE(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=HE(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=HE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=HE(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function sHn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function WE(e,t,n,r){let s;return e.wholeWord&&(s=aHn(t.charCategorizer(t.selection.main.head))),e.test&&(s=sHn(e.test,t,s)),new dkt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function AB(e,t){return e.slice(Oc(e,t,!1),t)}function RB(e,t){return e.slice(t,Oc(e,t))}function aHn(e){return(t,n,r)=>!r[0].length||(e(AB(r.input,r.index))!=So.Word||e(RB(r.input,r.index))!=So.Word)&&(e(RB(r.input,r.index+r[0].length))!=So.Word||e(AB(r.input,r.index+r[0].length))!=So.Word)}class iHn extends hkt{nextMatch(t,n,r){let s=WE(this.spec,t,r,t.doc.length).next();return s.done&&(s=WE(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=WE(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=WE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=WE(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const xM=xr.define(),Wke=xr.define(),Qw=bl.define({create(e){return new zee(Vge(e).create(),null)},update(e,t){for(let n of t.effects)n.is(xM)?e=new zee(n.value.create(),e.panel):n.is(Wke)&&(e=new zee(e.query,n.value?Zke:null));return e},provide:e=>uM.from(e,t=>t.panel)});class zee{constructor(t,n){this.query=t,this.panel=n}}const oHn=An.mark({class:"cm-searchMatch"}),lHn=An.mark({class:"cm-searchMatch cm-searchMatch-selected"}),cHn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Qw))}update(e){let t=e.state.field(Qw);(t!=e.startState.field(Qw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return An.none;let{view:n}=this,r=new Dd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(p=>p.from==u&&p.to==d);r.add(u,d,f?lHn:oHn)})}return r.finish()}},{decorations:e=>e.decorations});function $3(e){return t=>{let n=t.state.field(Qw,!1);return n&&n.query.spec.valid?e(t,n):vkt(t)}}const PB=$3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=bt.single(r.from,r.to),a=e.state.facet(mI);return e.dispatch({selection:s,effects:[Gke(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),gkt(e),!0}),$B=$3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=bt.single(s.from,s.to),i=e.state.facet(mI);return e.dispatch({selection:a,effects:[Gke(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),gkt(e),!0}),uHn=$3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:bt.create(n.map(r=>bt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),dHn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new Px(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(bt.range(l.value.from,l.value.to))}return t(e.update({selection:bt.create(a,i),userEvent:"select.search.matches"})),!0},e9e=$3((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(It.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=bt.single(i.from,i.to).map(f),d.push(Gke(e,i)),d.push(n.facet(mI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),fHn=$3((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:It.announce.of(r),userEvent:"input.replace.all"}),!0});function Zke(e){return e.state.facet(mI).createPanel(e)}function Vge(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(mI);return new pkt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function mkt(e){let t=cke(e,Zke);return t&&t.dom.querySelector("[main-field]")}function gkt(e){let t=mkt(e);t&&t==e.root.activeElement&&t.select()}const vkt=e=>{let t=e.state.field(Qw,!1);if(t&&t.panel){let n=mkt(e);if(n&&n!=e.root.activeElement){let r=Vge(e.state,t.query.spec);r.valid&&e.dispatch({effects:xM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Wke.of(!0),t?xM.of(Vge(e.state,t.query.spec)):xr.appendConfig.of(gHn)]});return!0},ykt=e=>{let t=e.state.field(Qw,!1);if(!t||!t.panel)return!1;let n=cke(e,Zke);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Wke.of(!1)}),!0},pHn=[{key:"Mod-f",run:vkt,scope:"editor search-panel"},{key:"F3",run:PB,shift:$B,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:PB,shift:$B,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:ykt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:dHn},{key:"Mod-Alt-g",run:Vqn},{key:"Mod-d",run:eHn,preventDefault:!0}];class hHn{constructor(t){this.view=t;let n=this.query=t.state.field(Qw).query.spec;this.commit=this.commit.bind(this),this.searchField=hi("input",{value:n.search,placeholder:dp(t,"Find"),"aria-label":dp(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=hi("input",{value:n.replace,placeholder:dp(t,"Replace"),"aria-label":dp(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=hi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=hi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=hi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return hi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=hi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>PB(t),[dp(t,"next")]),r("prev",()=>$B(t),[dp(t,"previous")]),r("select",()=>uHn(t),[dp(t,"all")]),hi("label",null,[this.caseField,dp(t,"match case")]),hi("label",null,[this.reField,dp(t,"regexp")]),hi("label",null,[this.wordField,dp(t,"by word")]),...t.state.readOnly?[]:[hi("br"),this.replaceField,r("replace",()=>e9e(t),[dp(t,"replace")]),r("replaceAll",()=>fHn(t),[dp(t,"replace all")])],hi("button",{name:"close",onclick:()=>ykt(t),"aria-label":dp(t,"close"),type:"button"},["×"])])}commit(){let t=new pkt({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:xM.of(t)}))}keydown(t){Pzn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?$B:PB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),e9e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(xM)&&!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(mI).top}}function dp(e,t){return e.state.phrase(t)}const Y6=30,K6=/[\s\.,:;?!]/;function Gke(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-Y6),i=Math.min(s,n+Y6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<Y6;c++)if(!K6.test(l[c+1])&&K6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-Y6;c--)if(!K6.test(l[c-1])&&K6.test(l[c])){l=l.slice(0,c);break}}return It.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const mHn=It.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),gHn=[Qw,nh.low(cHn),mHn];class t9e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Ek{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(wM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Dd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=jHn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,An.widget({widget:new _Hn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,An.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new Ek(u,n,Vj(u))}}function Vj(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new t9e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new t9e(r.from,a,r.diagnostic)}}),r}function vHn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(wM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(bkt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function yHn(e,t){return e.field(Ap,!1)?t:t.concat(xr.appendConfig.of(NHn))}const bkt=xr.define(),Qke=xr.define(),xkt=xr.define(),Ap=bl.define({create(){return new Ek(An.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=Vj(n,e.selected.diagnostic,a)||Vj(n,null,a)}!n.size&&s&&t.state.facet(wM).autoPanel&&(s=null),e=new Ek(n,s,r)}for(let n of t.effects)if(n.is(bkt)){let r=t.state.facet(wM).autoPanel?n.value.length?SM.open:null:e.panel;e=Ek.init(n.value,r,t.state)}else n.is(Qke)?e=new Ek(e.diagnostics,n.value?SM.open:null,e.selected):n.is(xkt)&&(e=new Ek(e.diagnostics,e.panel,n.value));return e},provide:e=>[uM.from(e,t=>t.panel),It.decorations.from(e,t=>t.diagnostics)]}),bHn=An.mark({class:"cm-lintRange cm-lintRange-active"});function xHn(e,t,n){let{diagnostics:r}=e.state.field(Ap),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(wM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:wHn(e,s)}}}:null}function wHn(e,t){return hi("ul",{class:"cm-tooltip-lint"},t.map(n=>Skt(e,n,!1)))}const SHn=e=>{let t=e.state.field(Ap,!1);(!t||!t.panel)&&e.dispatch({effects:yHn(e.state,[Qke.of(!0)])});let n=cke(e,SM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},n9e=e=>{let t=e.state.field(Ap,!1);return!t||!t.panel?!1:(e.dispatch({effects:Qke.of(!1)}),!0)},kHn=e=>{let t=e.state.field(Ap,!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)},OHn=[{key:"Mod-Shift-m",run:SHn,preventDefault:!0},{key:"F8",run:kHn}],wM=Tn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...By(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:r9e,tooltipFilter:r9e,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function r9e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function wkt(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function Skt(e,t,n){var r;let s=n?wkt(t.actions):[];return hi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},hi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=Vj(e.state.field(Ap).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),hi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return hi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&hi("div",{class:"cm-diagnosticSource"},t.source))}class _Hn extends rh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return hi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class s9e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Skt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class SM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)n9e(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=wkt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=Vj(this.view.state.field(Ap).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=hi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=hi("div",{class:"cm-panel-lint"},this.list,hi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>n9e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ap).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(Ap),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new s9e(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new s9e(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Ap),r=Vj(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:xkt.of(r)})}static open(t){return new SM(t)}}function CHn(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 X6(e){return CHn(`<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 EHn=It.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:X6("#d11")},".cm-lintRange-warning":{backgroundImage:X6("orange")},".cm-lintRange-info":{backgroundImage:X6("#999")},".cm-lintRange-hint":{backgroundImage:X6("#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 THn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function jHn(e){let t="hint",n=1;for(let r of e){let s=THn(r.severity);s>n&&(n=s,t=r.severity)}return t}const NHn=[Ap,It.decorations.compute([Ap],e=>{let{selected:t,panel:n}=e.field(Ap);return!t||!n||t.from==t.to?An.none:An.set([bHn.range(t.from,t.to)])}),S8n(xHn,{hideOn:vHn}),EHn];var a9e=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(b7n)),t.defaultKeymap!==!1&&(a=a.concat(zqn)),t.searchKeymap!==!1&&(a=a.concat(pHn)),t.historyKeymap!==!1&&(a=a.concat(ZVn)),t.foldKeymap!==!1&&(a=a.concat(s9n)),t.completionKeymap!==!1&&(a=a.concat(g1t)),t.lintKeymap!==!1&&(a=a.concat(OHn));var i=[];return t.lineNumbers!==!1&&i.push(P8n()),t.highlightActiveLineGutter!==!1&&i.push(D8n()),t.highlightSpecialChars!==!1&&i.push(Yzn()),t.history!==!1&&i.push(LVn()),t.foldGutter!==!1&&i.push(l9n()),t.drawSelection!==!1&&i.push(zzn()),t.dropCursor!==!1&&i.push(Hzn()),t.allowMultipleSelections!==!1&&i.push(us.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(Y8n()),t.syntaxHighlighting!==!1&&i.push(eS(f9n,{fallback:!0})),t.bracketMatching!==!1&&i.push(b9n()),t.closeBrackets!==!1&&i.push(m7n()),t.autocompletion!==!1&&i.push(m1t()),t.rectangularSelection!==!1&&i.push(u8n()),s!==!1&&i.push(p8n()),t.highlightActiveLine!==!1&&i.push(n8n()),t.highlightSelectionMatches!==!1&&i.push(Wqn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(dI.of(" ".repeat(t.tabSize))),i.concat([uI.of(a.flat())]).filter(Boolean)};const IHn="#e5c07b",i9e="#e06c75",AHn="#56b6c2",RHn="#ffffff",N8="#abb2bf",qge="#7d8799",PHn="#61afef",$Hn="#98c379",o9e="#d19a66",MHn="#c678dd",DHn="#21252b",l9e="#2c313a",c9e="#282c34",Bee="#353a42",LHn="#3E4451",u9e="#528bff",FHn=It.theme({"&":{color:N8,backgroundColor:c9e},".cm-content":{caretColor:u9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:u9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:LHn},".cm-panels":{backgroundColor:DHn,color:N8},".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:c9e,color:qge,border:"none"},".cm-activeLineGutter":{backgroundColor:l9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Bee},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Bee,borderBottomColor:Bee},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:l9e,color:N8}}},{dark:!0}),zHn=Wg.define([{tag:he.keyword,color:MHn},{tag:[he.name,he.deleted,he.character,he.propertyName,he.macroName],color:i9e},{tag:[he.function(he.variableName),he.labelName],color:PHn},{tag:[he.color,he.constant(he.name),he.standard(he.name)],color:o9e},{tag:[he.definition(he.name),he.separator],color:N8},{tag:[he.typeName,he.className,he.number,he.changed,he.annotation,he.modifier,he.self,he.namespace],color:IHn},{tag:[he.operator,he.operatorKeyword,he.url,he.escape,he.regexp,he.link,he.special(he.string)],color:AHn},{tag:[he.meta,he.comment],color:qge},{tag:he.strong,fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:he.link,color:qge,textDecoration:"underline"},{tag:he.heading,fontWeight:"bold",color:i9e},{tag:[he.atom,he.bool,he.special(he.variableName)],color:o9e},{tag:[he.processingInstruction,he.string,he.inserted],color:$Hn},{tag:he.invalid,color:RHn}]),BHn=[FHn,eS(zHn)];var UHn=It.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),VHn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(uI.of([Bqn])),m&&(typeof m=="boolean"?v.unshift(a9e()):v.unshift(a9e(m))),p&&v.unshift(i8n(p)),d){case"light":v.push(UHn);break;case"dark":v.push(BHn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(It.editable.of(!1)),c&&v.push(us.readOnly.of(!0)),[...v]},qHn=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 HHn{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 d9e{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 Uee=null,WHn=()=>typeof window>"u"?new d9e:(Uee||(Uee=new d9e),Uee),ZHn=It.theme({"& .cm-scroller":{height:"100% !important"}}),f9e=null,Vee=null;function GHn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===f9e||(f9e=i,Vee=It.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),Vee}var p9e=zy.define(),QHn=200,YHn=[];function KHn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?YHn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,C=k===void 0?null:k,_=e.maxWidth,E=_===void 0?null:_,T=e.placeholder,N=T===void 0?"":T,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,F=D===void 0?!0:D,H=e.basicSetup,B=H===void 0?!0:H,U=e.root,V=e.initialState,M=g.useState(),G=M[0],q=M[1],$=g.useState(),z=$[0],Z=$[1],K=g.useState(),re=K[0],ee=K[1],J=g.useState(()=>({current:null}))[0],ae=g.useState(()=>({current:null}))[0],fe=GHn(h,v,b,S,C,E),Y=It.updateListener.of(de=>{if(de.docChanged&&typeof r=="function"&&!de.transactions.some(be=>be.annotation(p9e))){J.current?J.current.reset():(J.current=new HHn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},QHn),WHn().add(J.current));var ce=de.state.doc,ge=ce.toString();r(ge,de)}s&&s(qHn(de))}),te=VHn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:F,basicSetup:B}),ue=[Y,...fe?[fe]:[],ZHn,...te];return i&&typeof i=="function"&&ue.push(It.updateListener.of(i)),ue=ue.concat(c),g.useLayoutEffect(()=>{if(G&&!re){var de={doc:t,selection:n,extensions:ue},ce=V?us.fromJSON(V.json,de,V.fields):us.create(de);if(ee(ce),!z){var ge=new It({state:ce,parent:G,root:U});Z(ge),a&&a(ge,ce)}}return()=>{z&&(ee(void 0),Z(void 0))}},[G,re]),g.useEffect(()=>{e.container&&q(e.container)},[e.container]),g.useEffect(()=>()=>{z&&(z.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[z]),g.useEffect(()=>{u&&z&&z.focus()},[u,z]),g.useEffect(()=>{z&&z.dispatch({effects:xr.reconfigure.of(ue)})},[f,c,h,v,b,S,C,E,N,A,L,F,B,r,i]),g.useEffect(()=>{if(t!==void 0){var de=z?z.state.doc.toString():"";if(z&&t!==de){var ce=J.current&&!J.current.isDone,ge=()=>{z&&t!==z.state.doc.toString()&&z.dispatch({changes:{from:0,to:z.state.doc.toString().length,insert:t||""},annotations:[p9e.of(!0)]})};ce?ae.current=ge:ge()}}},[t,z]),{state:re,setState:ee,view:z,setView:Z,container:G,setContainer:q}}var XHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Ku=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,C=e.basicSetup,_=e.placeholder,E=e.indentWithTab,T=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=NSt(e,XHn),L=g.useRef(null),D=KHn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:C,placeholder:_,indentWithTab:E,editable:T,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),F=D.state,H=D.view,B=D.container,U=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:F,view:H}),[L,B,F,H]);var V=g.useCallback(G=>{L.current=G,U(G)},[U]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",WO({ref:V,className:""+M+(n?" "+n:"")},R))});Ku.displayName="CodeMirror";const JHn={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 qee=null;function eWn(){return qee||(qee=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Da(()=>import("./core-8uqV4bH7.js"),__vite__mapDeps([0,1,2]),import.meta.url),Da(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Da(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Da(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Da(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Da(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Da(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Da(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Da(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Da(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Da(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Da(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Da(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Da(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Da(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Da(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Da(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Da(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),qee}async function tWn(e,t){const n=JHn[t?.toLowerCase()];if(!n)return null;const r=await eWn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function nWn(e){return new UO(hke.define(e))}const kkt=[og.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Da(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript())}}),og.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Da(()=>Promise.resolve().then(()=>I9n),void 0,import.meta.url).then(e=>e.json())}}),og.of({name:"JSX",extensions:["jsx"],load(){return Da(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),og.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Da(()=>Promise.resolve().then(()=>_Vn),void 0,import.meta.url).then(e=>e.markdown())}}),og.of({name:"TSX",extensions:["tsx"],load(){return Da(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),og.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Da(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),og.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Da(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>nWn(e.shell))}})];function rWn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function sWn(e){const t=rWn(e);return m1t({override:[aWn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function aWn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const iWn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,oWn=An.mark({class:"cm-variable-highlight"}),h9e=new jwt({regexp:iWn,decoration:()=>oWn}),lWn=Co.fromClass(class{decorations;constructor(e){this.decorations=h9e.createDeco(e)}update(e){this.decorations=h9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),cWn=lWn;function uWn(){const e=pI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[he.className,he.propertyName],color:"var(--neutral6)"},{tag:he.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[he.heading1,he.heading2,he.heading3,he.heading4,he.heading5,he.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:he.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:he.link,color:"var(--accent3)",textDecoration:"underline"},{tag:he.url,color:"var(--accent3)"},{tag:he.monospace,color:"var(--neutral6)"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:he.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=It.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function dWn(){const e=It.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Wg.define([{tag:[he.comment,he.bracket],color:"var(--neutral2)"},{tag:[he.string,he.meta,he.regexp],color:"var(--accent1)"},{tag:[he.atom,he.bool,he.special(he.variableName)],color:"var(--accent6)"},{tag:[he.keyword,he.operator,he.tagName],color:"var(--accent2)"},{tag:[he.function(he.propertyName),he.propertyName],color:"var(--accent5)"},{tag:[he.definition(he.variableName),he.function(he.variableName),he.className,he.attributeName],color:"var(--accent3)"},{tag:[he.variableName,he.number],color:"var(--accent5)"},{tag:[he.name,he.quote],color:"var(--accent1)"},{tag:he.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[he.heading1,he.heading2,he.heading3,he.heading4,he.heading5,he.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[he.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[he.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:he.link,color:"var(--accent3)",textDecoration:"underline"},{tag:he.url,color:"var(--accent3)"},{tag:he.monospace,color:"var(--neutral6)"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:[he.deleted],color:"var(--accent2)"},{tag:he.invalid,color:"var(--error)"},{tag:[he.standard(he.tagName)],color:"var(--accent1)"}]);return[e,eS(t)]}const s0=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?uWn():dWn(),[e])},fWn=co(X("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),pWn=nh.highest(It.editorAttributes.of({style:"outline: none"})),hWn=nh.highest(It.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),mWn=[pWn,hWn],Hr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=s0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const S=[...mWn];return f&&S.push(It.lineWrapping),a==="json"?S.push(Lp):a==="markdown"&&S.push(Bke({base:HO,codeLanguages:kkt})),i&&a==="markdown"&&S.push(cWn),c&&a==="markdown"&&S.push(sWn(c)),p===!1&&S.push(us.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:X(fWn({variant:h}),s),...m,children:[r&&o.jsx(za,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(Ku,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),gWn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},vWn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=s0(),{settings:r,setSettings:s}=yH(),a=r?.tracingOptions,i=g.useMemo(()=>gWn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(Ku,{value:l,onChange:d,theme:n,extensions:[Lp],className:X("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(le,{type:"button",onClick:f,children:"Save"})})]})},yWn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Ue,{children:o.jsx(cq,{})})})}),o.jsx(On,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Options"}),o.jsx(zs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Ir,{children:o.jsx(vWn,{onSaved:()=>t(!1)})})]})})]})};function bWn({status:e}){switch(e){case"running":return o.jsx(en,{});case"failed":return o.jsx(ws,{className:"text-accent2"});case"canceled":return o.jsx(Lf,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(mj,{className:"text-neutral3"});case"suspended":return o.jsx(rq,{className:"text-accent3"});case"success":return o.jsx(da,{className:"text-accent1"});default:return o.jsx(mj,{className:"text-neutral3"})}}function Okt({status:e}){return o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(Ue,{"aria-label":e,className:"shrink-0",children:o.jsx(bWn,{status:e})})}),o.jsx(On,{children:e})]})}var Hee,m9e;function Yke(){if(m9e)return Hee;m9e=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var p=f;p!==void 0;p=this.parent(p))if(p===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var p=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return Hee=r,Hee}var Wee,g9e;function xWn(){return g9e||(g9e=1,Wee="2.2.4"),Wee}var Zee,v9e;function wWn(){return v9e||(v9e=1,Zee={Graph:Yke(),version:xWn()}),Zee}var Gee,y9e;function SWn(){if(y9e)return Gee;y9e=1;var e=Yke();Gee={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return Gee}var Qee,b9e;function kWn(){if(b9e)return Qee;b9e=1,Qee=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return Qee}var Yee,x9e;function _kt(){if(x9e)return Yee;x9e=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return Yee=e,Yee}var Kee,w9e;function Ckt(){if(w9e)return Kee;w9e=1;var e=_kt();Kee=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return Kee}var Xee,S9e;function OWn(){if(S9e)return Xee;S9e=1;var e=Ckt();Xee=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Xee}var Jee,k9e;function Ekt(){if(k9e)return Jee;k9e=1,Jee=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return Jee}var ete,O9e;function _Wn(){if(O9e)return ete;O9e=1;var e=Ekt();ete=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return ete}var tte,_9e;function CWn(){if(_9e)return tte;_9e=1,tte=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return tte}var nte,C9e;function Tkt(){if(C9e)return nte;C9e=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return nte=e,e.CycleException=t,nte}var rte,E9e;function EWn(){if(E9e)return rte;E9e=1;var e=Tkt();rte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return rte}var ste,T9e;function jkt(){if(T9e)return ste;T9e=1,ste=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return ste}var ate,j9e;function TWn(){if(j9e)return ate;j9e=1;var e=jkt();ate=t;function t(n,r){return e(n,r,"post")}return ate}var ite,N9e;function jWn(){if(N9e)return ite;N9e=1;var e=jkt();ite=t;function t(n,r){return e(n,r,"pre")}return ite}var ote,I9e;function NWn(){if(I9e)return ote;I9e=1;var e=Yke(),t=_kt();ote=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return ote}var lte,A9e;function IWn(){return A9e||(A9e=1,lte={components:kWn(),dijkstra:Ckt(),dijkstraAll:OWn(),findCycles:_Wn(),floydWarshall:CWn(),isAcyclic:EWn(),postorder:TWn(),preorder:jWn(),prim:NWn(),tarjan:Ekt(),topsort:Tkt()}),lte}var cte,R9e;function zg(){if(R9e)return cte;R9e=1;var e=wWn();return cte={Graph:e.Graph,json:SWn(),alg:IWn(),version:e.version},cte}var ute,P9e;function AWn(){if(P9e)return ute;P9e=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return ute=e,ute}var dte,$9e;function RWn(){if($9e)return dte;$9e=1;let e=zg().Graph,t=AWn();dte=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return dte}var fte,M9e;function Ml(){if(M9e)return fte;M9e=1;let e=zg().Graph;fte={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:C,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:E};function t(T,N,I,A){for(var R=A;T.hasNode(R);)R=S(A);return I.dummy=N,T.setNode(R,I),R}function n(T){let N=new e().setGraph(T.graph());return T.nodes().forEach(I=>N.setNode(I,T.node(I))),T.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=T.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(T){let N=new e({multigraph:T.isMultigraph()}).setGraph(T.graph());return T.nodes().forEach(I=>{T.children(I).length||N.setNode(I,T.node(I))}),T.edges().forEach(I=>{N.setEdge(I,T.edge(I))}),N}function s(T){let N=T.nodes().map(I=>{let A={};return T.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function a(T){let N=T.nodes().map(I=>{let A={};return T.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function i(T,N){let I=T.x,A=T.y,R=N.x-I,L=N.y-A,D=T.width/2,F=T.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,B;return Math.abs(L)*D>Math.abs(R)*F?(L<0&&(F=-F),H=F*R/L,B=F):(R<0&&(D=-D),H=D,B=D*L/R),{x:I+H,y:A+B}}function l(T){let N=k(m(T)+1).map(()=>[]);return T.nodes().forEach(I=>{let A=T.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(T){let N=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);T.nodes().forEach(A=>{let R=T.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(T){let N=T.nodes().map(D=>T.node(D).rank),I=h(Math.min,N),A=[];T.nodes().forEach(D=>{let F=T.node(D).rank-I;A[F]||(A[F]=[]),A[F].push(D)});let R=0,L=T.graph().nodeRankFactor;Array.from(A).forEach((D,F)=>{D===void 0&&F%L!==0?--R:D!==void 0&&R&&D.forEach(H=>T.node(H).rank+=R)})}function d(T,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(T,"border",R,N)}function f(T,N=p){const I=[];for(let A=0;A<T.length;A+=N){const R=T.slice(A,A+N);I.push(R)}return I}const p=65535;function h(T,N){if(N.length>p){const I=f(N);return T.apply(null,I.map(A=>T.apply(null,A)))}else return T.apply(null,N)}function m(T){const I=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(T,N){let I={lhs:[],rhs:[]};return T.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(T,N){let I=Date.now();try{return N()}finally{console.log(T+" time: "+(Date.now()-I)+"ms")}}function b(T,N){return N()}let x=0;function S(T){var N=++x;return T+(""+N)}function k(T,N,I=1){N==null&&(N=T,T=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=T;A(L);L+=I)R.push(L);return R}function C(T,N){const I={};for(const A of N)T[A]!==void 0&&(I[A]=T[A]);return I}function _(T,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(T).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(T,N){return T.reduce((I,A,R)=>(I[A]=N[R],I),{})}return fte}var pte,D9e;function PWn(){if(D9e)return pte;D9e=1;let e=RWn(),t=Ml().uniqueId;pte={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return pte}var hte,L9e;function $Wn(){if(L9e)return hte;L9e=1;let e=Ml();hte={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return hte}var mte,F9e;function MB(){if(F9e)return mte;F9e=1;const{applyWithChunking:e}=Ml();mte={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return mte}var gte,z9e;function Nkt(){if(z9e)return gte;z9e=1;var e=zg().Graph,t=MB().slack;gte=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return gte}var vte,B9e;function MWn(){if(B9e)return vte;B9e=1;var e=Nkt(),t=MB().slack,n=MB().longestPath,r=zg().alg.preorder,s=zg().alg.postorder,a=Ml().simplify;vte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,C;k=p(S);)C=h(S,x,k),m(S,x,k,C)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(C=>c(x,S,C))}function c(x,S,k){var C=x.node(k),_=C.parent;x.edge(k,_).cutvalue=u(x,S,k)}function u(x,S,k){var C=x.node(k),_=C.parent,E=!0,T=S.edge(k,_),N=0;return T||(E=!1,T=S.edge(_,k)),N=T.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==_){var L=A===E,D=S.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var F=x.edge(k,R).cutvalue;N+=L?-F:F}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,C,_){var E=k,T=x.node(C);return S[C]=!0,x.neighbors(C).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,C))}),T.low=E,T.lim=k++,_?T.parent=_:delete T.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var C=k.v,_=k.w;S.hasEdge(C,_)||(C=k.w,_=k.v);var E=x.node(C),T=x.node(_),N=E,I=!1;E.lim>T.lim&&(N=T,I=!0);var A=S.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(S,L)<t(S,R)?L:R)}function m(x,S,k,C){var _=k.v,E=k.w;x.removeEdge(_,E),x.setEdge(C.v,C.w,{}),d(x),l(x,S),v(x,S)}function v(x,S){var k=x.nodes().find(_=>!S.node(_).parent),C=r(x,k);C=C.slice(1),C.forEach(_=>{var E=x.node(_).parent,T=S.edge(_,E),N=!1;T||(T=S.edge(E,_),N=!0),S.node(_).rank=S.node(E).rank+(N?T.minlen:-T.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return vte}var yte,U9e;function DWn(){if(U9e)return yte;U9e=1;var e=MB(),t=e.longestPath,n=Nkt(),r=MWn();yte=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return yte}var bte,V9e;function LWn(){if(V9e)return bte;V9e=1,bte=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return bte}var xte,q9e;function FWn(){if(q9e)return xte;q9e=1;let e=Ml();xte={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,C=x.borderTop?u:2*u,_=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:C,minlen:_,nestingEdge:!0}),i.setEdge(k,v,{weight:C,minlen:_,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return xte}var wte,H9e;function zWn(){if(H9e)return wte;H9e=1;let e=Ml();wte=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return wte}var Ste,W9e;function BWn(){if(W9e)return Ste;W9e=1,Ste={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return Ste}var kte,Z9e;function UWn(){if(Z9e)return kte;Z9e=1;let e=Ml();kte=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return kte}var Ote,G9e;function VWn(){if(G9e)return Ote;G9e=1;let e=Ml().zipObject;Ote=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return Ote}var _te,Q9e;function qWn(){if(Q9e)return _te;Q9e=1,_te=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return _te}var Cte,Y9e;function HWn(){if(Y9e)return Cte;Y9e=1;let e=Ml();Cte=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return Cte}var Ete,K9e;function WWn(){if(K9e)return Ete;K9e=1;let e=Ml();Ete=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return Ete}var Tte,X9e;function ZWn(){if(X9e)return Tte;X9e=1;let e=qWn(),t=HWn(),n=WWn();Tte=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(x=>x!==p&&x!==h));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return Tte}var jte,J9e;function GWn(){if(J9e)return jte;J9e=1;let e=zg().Graph,t=Ml();jte=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return jte}var Nte,e7e;function QWn(){if(e7e)return Nte;e7e=1,Nte=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return Nte}var Ite,t7e;function YWn(){if(t7e)return Ite;t7e=1;let e=UWn(),t=VWn(),n=ZWn(),r=GWn(),s=QWn(),a=zg().Graph,i=Ml();Ite=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:v,S%4>=2),y=i.buildLayerMatrix(f);let C=t(f,y);C<b&&(k=0,x=Object.assign({},y),b=C)}d(f,x)}function c(f,p,h){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return Ite}var Ate,n7e;function KWn(){if(n7e)return Ate;n7e=1;let e=zg().Graph,t=Ml();Ate={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let x={};function S(k,C){let _=0,E=0,T=k.length,N=C[C.length-1];return C.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:T;(R||I===N)&&(C.slice(E,A+1).forEach(D=>{y.predecessors(D).forEach(F=>{let H=y.node(F),B=H.order;(B<_||L<B)&&!(H.dummy&&y.node(D).dummy)&&a(x,F,D)})}),E=A+1,_=L)}),C}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(C,_,E,T,N){let I;t.range(_,E).forEach(A=>{I=C[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<T||L.order>N)&&a(x,R,I)})})}function k(C,_){let E=-1,T,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(T=y.node(R[0]).order,S(_,N,A,E,T),N=A,E=T)}S(_,N,_.length,T,C.length)}),_}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},C={},_={};return b.forEach(E=>{E.forEach((T,N)=>{k[T]=T,C[T]=T,_[T]=N})}),b.forEach(E=>{let T=-1;E.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>_[R]-_[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];C[N]===N&&T<_[D]&&!i(x,N,D)&&(C[D]=N,C[N]=k[N]=k[D],T=_[D])}}})}),{root:k,align:C}}function c(y,b,x,S,k){let C={},_=u(y,b,x,k),E=k?"borderLeft":"borderRight";function T(A,R){let L=_.nodes(),D=L.pop(),F={};for(;D;)F[D]?A(D):(F[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){C[A]=_.inEdges(A).reduce((R,L)=>Math.max(R,C[L.v]+_.edge(L)),0)}function I(A){let R=_.outEdges(A).reduce((D,F)=>Math.min(D,C[F.w]-_.edge(F)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(C[A]=Math.max(C[A],R))}return T(N,_.predecessors.bind(_)),T(I,_.successors.bind(_)),Object.keys(S).forEach(A=>C[A]=C[x[A]]),C}function u(y,b,x,S){let k=new e,C=y.graph(),_=m(C.nodesep,C.edgesep,S);return b.forEach(E=>{let T;E.forEach(N=>{let I=x[N];if(k.setNode(I),T){var A=x[T],R=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,T),R||0))}T=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,C=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([E,T])=>{let N=v(y,E)/2;k=Math.max(T+N,k),C=Math.min(T-N,C)});const _=k-C;return _<x[0]&&(x=[_,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(C=>{["l","r"].forEach(_=>{let E=C+_,T=y[E];if(T===b)return;let N=Object.values(T),I=S-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(T,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(C=>C[S]).sort((C,_)=>C-_);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(_=>{k=_==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let T=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,T),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),S[_+E]=I})});let C=d(y,S);return f(S,C),p(S,y.graph().align)}function m(y,b,x){return(S,k,C)=>{let _=S.node(k),E=S.node(C),T=0,N;if(T+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(T+=x?N:-N),N=0,T+=(_.dummy?b:y)/2,T+=(E.dummy?b:y)/2,T+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(T+=x?N:-N),N=0,T}}function v(y,b){return y.node(b).width}return Ate}var Rte,r7e;function XWn(){if(r7e)return Rte;r7e=1;let e=Ml(),t=KWn().positionX;Rte=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Rte}var Pte,s7e;function JWn(){if(s7e)return Pte;s7e=1;let e=PWn(),t=$Wn(),n=DWn(),r=Ml().normalizeRanks,s=LWn(),a=Ml().removeEmptyRanks,i=FWn(),l=zWn(),c=BWn(),u=YWn(),d=XWn(),f=Ml(),p=zg().Graph;Pte=h;function h($,z){let Z=z&&z.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>T($));Z(" runLayout",()=>m(K,Z,z)),Z(" updateInputGraph",()=>v($,K))})}function m($,z,Z){z(" makeSpaceForEdgeLabels",()=>N($)),z(" removeSelfEdges",()=>U($)),z(" acyclic",()=>e.run($)),z(" nestingGraph.run",()=>i.run($)),z(" rank",()=>n(f.asNonCompoundGraph($))),z(" injectEdgeLabelProxies",()=>I($)),z(" removeEmptyRanks",()=>a($)),z(" nestingGraph.cleanup",()=>i.cleanup($)),z(" normalizeRanks",()=>r($)),z(" assignRankMinMax",()=>A($)),z(" removeEdgeLabelProxies",()=>R($)),z(" normalize.run",()=>t.run($)),z(" parentDummyChains",()=>s($)),z(" addBorderSegments",()=>l($)),z(" order",()=>u($,Z)),z(" insertSelfEdges",()=>V($)),z(" adjustCoordinateSystem",()=>c.adjust($)),z(" position",()=>d($)),z(" positionSelfEdges",()=>M($)),z(" removeBorderNodes",()=>B($)),z(" normalize.undo",()=>t.undo($)),z(" fixupEdgeLabelCoords",()=>F($)),z(" undoCoordinateSystem",()=>c.undo($)),z(" translateGraph",()=>L($)),z(" assignNodeIntersects",()=>D($)),z(" reversePoints",()=>H($)),z(" acyclic.undo",()=>e.undo($))}function v($,z){$.nodes().forEach(Z=>{let K=$.node(Z),re=z.node(Z);K&&(K.x=re.x,K.y=re.y,K.rank=re.rank,z.children(Z).length&&(K.width=re.width,K.height=re.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),re=z.edge(Z);K.points=re.points,Object.hasOwn(re,"x")&&(K.x=re.x,K.y=re.y)}),$.graph().width=z.graph().width,$.graph().height=z.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],S=["width","height","rank"],k={width:0,height:0},C=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function T($){let z=new p({multigraph:!0,compound:!0}),Z=q($.graph());return z.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(K=>{let re=q($.node(K));const ee=G(re,S);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),z.setNode(K,ee),z.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let re=q($.edge(K));z.setEdge(K,Object.assign({},_,G(re,C),f.pick(re,E)))}),z}function N($){let z=$.graph();z.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(z.rankdir==="TB"||z.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(z=>{let Z=$.edge(z);if(Z.width&&Z.height){let K=$.node(z.v),ee={rank:($.node(z.w).rank-K.rank)/2+K.rank,e:z};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let z=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,z=Math.max(z,K.maxRank))}),$.graph().maxRank=z}function R($){$.nodes().forEach(z=>{let Z=$.node(z);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(z))})}function L($){let z=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,re=0,ee=$.graph(),J=ee.marginx||0,ae=ee.marginy||0;function fe(Y){let te=Y.x,ue=Y.y,de=Y.width,ce=Y.height;z=Math.min(z,te-de/2),Z=Math.max(Z,te+de/2),K=Math.min(K,ue-ce/2),re=Math.max(re,ue+ce/2)}$.nodes().forEach(Y=>fe($.node(Y))),$.edges().forEach(Y=>{let te=$.edge(Y);Object.hasOwn(te,"x")&&fe(te)}),z-=J,K-=ae,$.nodes().forEach(Y=>{let te=$.node(Y);te.x-=z,te.y-=K}),$.edges().forEach(Y=>{let te=$.edge(Y);te.points.forEach(ue=>{ue.x-=z,ue.y-=K}),Object.hasOwn(te,"x")&&(te.x-=z),Object.hasOwn(te,"y")&&(te.y-=K)}),ee.width=Z-z+J,ee.height=re-K+ae}function D($){$.edges().forEach(z=>{let Z=$.edge(z),K=$.node(z.v),re=$.node(z.w),ee,J;Z.points?(ee=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],ee=re,J=K),Z.points.unshift(f.intersectRect(K,ee)),Z.points.push(f.intersectRect(re,J))})}function F($){$.edges().forEach(z=>{let Z=$.edge(z);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(z=>{let Z=$.edge(z);Z.reversed&&Z.points.reverse()})}function B($){$.nodes().forEach(z=>{if($.children(z).length){let Z=$.node(z),K=$.node(Z.borderTop),re=$.node(Z.borderBottom),ee=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-ee.x),Z.height=Math.abs(re.y-K.y),Z.x=ee.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(z=>{$.node(z).dummy==="border"&&$.removeNode(z)})}function U($){$.edges().forEach(z=>{if(z.v===z.w){var Z=$.node(z.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:z,label:$.edge(z)}),$.removeEdge(z)}})}function V($){var z=f.buildLayerMatrix($);z.forEach(Z=>{var K=0;Z.forEach((re,ee)=>{var J=$.node(re);J.order=ee+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:ee+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function M($){$.nodes().forEach(z=>{var Z=$.node(z);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),re=K.x+K.width/2,ee=K.y,J=Z.x-re,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(z),Z.label.points=[{x:re+2*J/3,y:ee-ae},{x:re+5*J/6,y:ee-ae},{x:re+J,y:ee},{x:re+5*J/6,y:ee+ae},{x:re+2*J/3,y:ee+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,z){return f.mapValues(f.pick($,z),Number)}function q($){var z={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),z[Z]=K}),z}return Pte}var $te,a7e;function eZn(){if(a7e)return $te;a7e=1;let e=Ml(),t=zg().Graph;$te={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return $te}var Mte,i7e;function tZn(){return i7e||(i7e=1,Mte="1.1.8"),Mte}var Dte,o7e;function nZn(){return o7e||(o7e=1,Dte={graphlib:zg(),layout:JWn(),debug:eZn(),util:{time:Ml().time,notime:Ml().notime},version:tZn()}),Dte}var rZn=nZn();const l7e=Bl(rZn);function Hl(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Hl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var sZn={value:()=>{}};function HH(){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 I8(n)}function I8(e){this._=e}function aZn(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}})}I8.prototype=HH.prototype={constructor:I8,on:function(e,t){var n=this._,r=aZn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=iZn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=c7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=c7e(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 I8(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function iZn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function c7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=sZn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Hge="http://www.w3.org/1999/xhtml";const u7e={svg:"http://www.w3.org/2000/svg",xhtml:Hge,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function WH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),u7e.hasOwnProperty(t)?{space:u7e[t],local:e}:e}function oZn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Hge&&t.documentElement.namespaceURI===Hge?t.createElement(e):t.createElementNS(n,e)}}function lZn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Ikt(e){var t=WH(e);return(t.local?lZn:oZn)(t)}function cZn(){}function Kke(e){return e==null?cZn:function(){return this.querySelector(e)}}function uZn(e){typeof e!="function"&&(e=Kke(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Kp(r,this._parents)}function dZn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function fZn(){return[]}function Akt(e){return e==null?fZn:function(){return this.querySelectorAll(e)}}function pZn(e){return function(){return dZn(e.apply(this,arguments))}}function hZn(e){typeof e=="function"?e=pZn(e):e=Akt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new Kp(r,s)}function Rkt(e){return function(){return this.matches(e)}}function Pkt(e){return function(t){return t.matches(e)}}var mZn=Array.prototype.find;function gZn(e){return function(){return mZn.call(this.children,e)}}function vZn(){return this.firstElementChild}function yZn(e){return this.select(e==null?vZn:gZn(typeof e=="function"?e:Pkt(e)))}var bZn=Array.prototype.filter;function xZn(){return Array.from(this.children)}function wZn(e){return function(){return bZn.call(this.children,e)}}function SZn(e){return this.selectAll(e==null?xZn:wZn(typeof e=="function"?e:Pkt(e)))}function kZn(e){typeof e!="function"&&(e=Rkt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Kp(r,this._parents)}function $kt(e){return new Array(e.length)}function OZn(){return new Kp(this._enter||this._groups.map($kt),this._parents)}function DB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}DB.prototype={constructor:DB,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 _Zn(e){return function(){return e}}function CZn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new DB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function EZn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new DB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function TZn(e){return e.__data__}function jZn(e,t){if(!arguments.length)return Array.from(this,TZn);var n=t?EZn:CZn,r=this._parents,s=this._groups;typeof e!="function"&&(e=_Zn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],p=f.length,h=NZn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var x=0,S=0,k,C;x<m;++x)if(k=v[x]){for(x>=S&&(S=x+1);!(C=y[S])&&++S<m;);k._next=C||null}}return i=new Kp(i,r),i._enter=l,i._exit=c,i}function NZn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function IZn(){return new Kp(this._exit||this._groups.map($kt),this._parents)}function AZn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function RZn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Kp(l,this._parents)}function PZn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function $Zn(e){e||(e=MZn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Kp(s,this._parents).order()}function MZn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function DZn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function LZn(){return Array.from(this)}function FZn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function zZn(){let e=0;for(const t of this)++e;return e}function BZn(){return!this.node()}function UZn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function VZn(e){return function(){this.removeAttribute(e)}}function qZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function HZn(e,t){return function(){this.setAttribute(e,t)}}function WZn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function ZZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function GZn(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 QZn(e,t){var n=WH(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?qZn:VZn:typeof t=="function"?n.local?GZn:ZZn:n.local?WZn:HZn)(n,t))}function Mkt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function YZn(e){return function(){this.style.removeProperty(e)}}function KZn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function XZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function JZn(e,t,n){return arguments.length>1?this.each((t==null?YZn:typeof t=="function"?XZn:KZn)(e,t,n??"")):qj(this.node(),e)}function qj(e,t){return e.style.getPropertyValue(t)||Mkt(e).getComputedStyle(e,null).getPropertyValue(t)}function eGn(e){return function(){delete this[e]}}function tGn(e,t){return function(){this[e]=t}}function nGn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function rGn(e,t){return arguments.length>1?this.each((t==null?eGn:typeof t=="function"?nGn:tGn)(e,t)):this.node()[e]}function Dkt(e){return e.trim().split(/^|\s+/)}function Xke(e){return e.classList||new Lkt(e)}function Lkt(e){this._node=e,this._names=Dkt(e.getAttribute("class")||"")}Lkt.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 Fkt(e,t){for(var n=Xke(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function zkt(e,t){for(var n=Xke(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function sGn(e){return function(){Fkt(this,e)}}function aGn(e){return function(){zkt(this,e)}}function iGn(e,t){return function(){(t.apply(this,arguments)?Fkt:zkt)(this,e)}}function oGn(e,t){var n=Dkt(e+"");if(arguments.length<2){for(var r=Xke(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?iGn:t?sGn:aGn)(n,t))}function lGn(){this.textContent=""}function cGn(e){return function(){this.textContent=e}}function uGn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function dGn(e){return arguments.length?this.each(e==null?lGn:(typeof e=="function"?uGn:cGn)(e)):this.node().textContent}function fGn(){this.innerHTML=""}function pGn(e){return function(){this.innerHTML=e}}function hGn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function mGn(e){return arguments.length?this.each(e==null?fGn:(typeof e=="function"?hGn:pGn)(e)):this.node().innerHTML}function gGn(){this.nextSibling&&this.parentNode.appendChild(this)}function vGn(){return this.each(gGn)}function yGn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function bGn(){return this.each(yGn)}function xGn(e){var t=typeof e=="function"?e:Ikt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function wGn(){return null}function SGn(e,t){var n=typeof e=="function"?e:Ikt(e),r=t==null?wGn:typeof t=="function"?t:Kke(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function kGn(){var e=this.parentNode;e&&e.removeChild(this)}function OGn(){return this.each(kGn)}function _Gn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function CGn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function EGn(e){return this.select(e?CGn:_Gn)}function TGn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function jGn(e){return function(t){e.call(this,t,this.__data__)}}function NGn(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 IGn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function AGn(e,t,n){return function(){var r=this.__on,s,a=jGn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function RGn(e,t,n){var r=NGn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?AGn:IGn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function Bkt(e,t,n){var r=Mkt(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 PGn(e,t){return function(){return Bkt(this,e,t)}}function $Gn(e,t){return function(){return Bkt(this,e,t.apply(this,arguments))}}function MGn(e,t){return this.each((typeof t=="function"?$Gn:PGn)(e,t))}function*DGn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var Ukt=[null];function Kp(e,t){this._groups=e,this._parents=t}function M3(){return new Kp([[document.documentElement]],Ukt)}function LGn(){return this}Kp.prototype=M3.prototype={constructor:Kp,select:uZn,selectAll:hZn,selectChild:yZn,selectChildren:SZn,filter:kZn,data:jZn,enter:OZn,exit:IZn,join:AZn,merge:RZn,selection:LGn,order:PZn,sort:$Zn,call:DZn,nodes:LZn,node:FZn,size:zZn,empty:BZn,each:UZn,attr:QZn,style:JZn,property:rGn,classed:oGn,text:dGn,html:mGn,raise:vGn,lower:bGn,append:xGn,insert:SGn,remove:OGn,clone:EGn,datum:TGn,on:RGn,dispatch:MGn,[Symbol.iterator]:DGn};function Tp(e){return typeof e=="string"?new Kp([[document.querySelector(e)]],[document.documentElement]):new Kp([[e]],Ukt)}function FGn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function lg(e,t){if(e=FGn(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 zGn={passive:!1},kM={capture:!0,passive:!1};function Lte(e){e.stopImmediatePropagation()}function QT(e){e.preventDefault(),e.stopImmediatePropagation()}function Vkt(e){var t=e.document.documentElement,n=Tp(e).on("dragstart.drag",QT,kM);"onselectstart"in t?n.on("selectstart.drag",QT,kM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function qkt(e,t){var n=e.document.documentElement,r=Tp(e).on("dragstart.drag",null);t&&(r.on("click.drag",QT,kM),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 J6=e=>()=>e;function Wge(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Wge.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function BGn(e){return!e.ctrlKey&&!e.button}function UGn(){return this.parentNode}function VGn(e,t){return t??{x:e.x,y:e.y}}function qGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function Hkt(){var e=BGn,t=UGn,n=VGn,r=qGn,s={},a=HH("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,zGn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,C){if(!(d||!e.call(this,k,C))){var _=S(this,t.call(this,k,C),k,C,"mouse");_&&(Tp(k.view).on("mousemove.drag",m,kM).on("mouseup.drag",v,kM),Vkt(k.view),Lte(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(QT(k),!u){var C=k.clientX-l,_=k.clientY-c;u=C*C+_*_>f}s.mouse("drag",k)}function v(k){Tp(k.view).on("mousemove.drag mouseup.drag",null),qkt(k.view,u),QT(k),s.mouse("end",k)}function y(k,C){if(e.call(this,k,C)){var _=k.changedTouches,E=t.call(this,k,C),T=_.length,N,I;for(N=0;N<T;++N)(I=S(this,E,k,C,_[N].identifier,_[N]))&&(Lte(k),I("start",k,_[N]))}}function b(k){var C=k.changedTouches,_=C.length,E,T;for(E=0;E<_;++E)(T=s[C[E].identifier])&&(QT(k),T("drag",k,C[E]))}function x(k){var C=k.changedTouches,_=C.length,E,T;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<_;++E)(T=s[C[E].identifier])&&(Lte(k),T("end",k,C[E]))}function S(k,C,_,E,T,N){var I=a.copy(),A=lg(N||_,C),R,L,D;if((D=n.call(k,new Wge("beforestart",{sourceEvent:_,target:p,identifier:T,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function F(H,B,U){var V=A,M;switch(H){case"start":s[T]=F,M=i++;break;case"end":delete s[T],--i;case"drag":A=lg(U||B,C),M=i;break}I.call(H,k,new Wge(H,{sourceEvent:B,subject:D,target:p,identifier:T,active:M,x:A[0]+R,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),E)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:J6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:J6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:J6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:J6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function Jke(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Wkt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function D3(){}var OM=.7,LB=1/OM,YT="\\s*([+-]?\\d+)\\s*",_M="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",iy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",HGn=/^#([0-9a-f]{3,8})$/,WGn=new RegExp(`^rgb\\(${YT},${YT},${YT}\\)$`),ZGn=new RegExp(`^rgb\\(${iy},${iy},${iy}\\)$`),GGn=new RegExp(`^rgba\\(${YT},${YT},${YT},${_M}\\)$`),QGn=new RegExp(`^rgba\\(${iy},${iy},${iy},${_M}\\)$`),YGn=new RegExp(`^hsl\\(${_M},${iy},${iy}\\)$`),KGn=new RegExp(`^hsla\\(${_M},${iy},${iy},${_M}\\)$`),d7e={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};Jke(D3,ZO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:f7e,formatHex:f7e,formatHex8:XGn,formatHsl:JGn,formatRgb:p7e,toString:p7e});function f7e(){return this.rgb().formatHex()}function XGn(){return this.rgb().formatHex8()}function JGn(){return Zkt(this).formatHsl()}function p7e(){return this.rgb().formatRgb()}function ZO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=HGn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?h7e(t):n===3?new wf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?eF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?eF(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=WGn.exec(e))?new wf(t[1],t[2],t[3],1):(t=ZGn.exec(e))?new wf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=GGn.exec(e))?eF(t[1],t[2],t[3],t[4]):(t=QGn.exec(e))?eF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=YGn.exec(e))?v7e(t[1],t[2]/100,t[3]/100,1):(t=KGn.exec(e))?v7e(t[1],t[2]/100,t[3]/100,t[4]):d7e.hasOwnProperty(e)?h7e(d7e[e]):e==="transparent"?new wf(NaN,NaN,NaN,0):null}function h7e(e){return new wf(e>>16&255,e>>8&255,e&255,1)}function eF(e,t,n,r){return r<=0&&(e=t=n=NaN),new wf(e,t,n,r)}function eQn(e){return e instanceof D3||(e=ZO(e)),e?(e=e.rgb(),new wf(e.r,e.g,e.b,e.opacity)):new wf}function Zge(e,t,n,r){return arguments.length===1?eQn(e):new wf(e,t,n,r??1)}function wf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Jke(wf,Zge,Wkt(D3,{brighter(e){return e=e==null?LB:Math.pow(LB,e),new wf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?OM:Math.pow(OM,e),new wf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new wf(rO(this.r),rO(this.g),rO(this.b),FB(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:m7e,formatHex:m7e,formatHex8:tQn,formatRgb:g7e,toString:g7e}));function m7e(){return`#${Fk(this.r)}${Fk(this.g)}${Fk(this.b)}`}function tQn(){return`#${Fk(this.r)}${Fk(this.g)}${Fk(this.b)}${Fk((isNaN(this.opacity)?1:this.opacity)*255)}`}function g7e(){const e=FB(this.opacity);return`${e===1?"rgb(":"rgba("}${rO(this.r)}, ${rO(this.g)}, ${rO(this.b)}${e===1?")":`, ${e})`}`}function FB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function rO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Fk(e){return e=rO(e),(e<16?"0":"")+e.toString(16)}function v7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new mg(e,t,n,r)}function Zkt(e){if(e instanceof mg)return new mg(e.h,e.s,e.l,e.opacity);if(e instanceof D3||(e=ZO(e)),!e)return new mg;if(e instanceof mg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new mg(i,l,c,e.opacity)}function nQn(e,t,n,r){return arguments.length===1?Zkt(e):new mg(e,t,n,r??1)}function mg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Jke(mg,nQn,Wkt(D3,{brighter(e){return e=e==null?LB:Math.pow(LB,e),new mg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?OM:Math.pow(OM,e),new mg(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 wf(Fte(e>=240?e-240:e+120,s,r),Fte(e,s,r),Fte(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new mg(y7e(this.h),tF(this.s),tF(this.l),FB(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=FB(this.opacity);return`${e===1?"hsl(":"hsla("}${y7e(this.h)}, ${tF(this.s)*100}%, ${tF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function y7e(e){return e=(e||0)%360,e<0?e+360:e}function tF(e){return Math.max(0,Math.min(1,e||0))}function Fte(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 eOe=e=>()=>e;function rQn(e,t){return function(n){return e+n*t}}function sQn(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 aQn(e){return(e=+e)==1?Gkt:function(t,n){return n-t?sQn(t,n,e):eOe(isNaN(t)?n:t)}}function Gkt(e,t){var n=t-e;return n?rQn(e,n):eOe(isNaN(e)?t:e)}const zB=(function e(t){var n=aQn(t);function r(s,a){var i=n((s=Zge(s)).r,(a=Zge(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=Gkt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function iQn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function oQn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function lQn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=hx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function cQn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ug(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function uQn(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(a){for(s in n)r[s]=n[s](a);return r}}var Gge=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,zte=new RegExp(Gge.source,"g");function dQn(e){return function(){return e}}function fQn(e){return function(t){return e(t)+""}}function Qkt(e,t){var n=Gge.lastIndex=zte.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Gge.exec(e))&&(s=zte.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:ug(r,s)})),n=zte.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?fQn(c[0].x):dQn(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"?eOe(t):(n==="number"?ug:n==="string"?(r=ZO(t))?(t=r,zB):Qkt:t instanceof ZO?zB:t instanceof Date?cQn:oQn(t)?iQn:Array.isArray(t)?lQn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?uQn:ug)(e,t)}function tOe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var b7e=180/Math.PI,Qge={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Ykt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*b7e,skewX:Math.atan(c)*b7e,scaleX:i,scaleY:l}}var nF;function pQn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Qge:Ykt(t.a,t.b,t.c,t.d,t.e,t.f)}function hQn(e){return e==null||(nF||(nF=document.createElementNS("http://www.w3.org/2000/svg","g")),nF.setAttribute("transform",e),!(e=nF.transform.baseVal.consolidate()))?Qge:(e=e.matrix,Ykt(e.a,e.b,e.c,e.d,e.e,e.f))}function Kkt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:ug(u,f)},{i:v-2,x:ug(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:ug(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:ug(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:ug(u,f)},{i:v-2,x:ug(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var mQn=Kkt(pQn,"px, ","px)","deg)"),gQn=Kkt(hQn,", ",")",")"),vQn=1e-12;function x7e(e){return((e=Math.exp(e))+1/e)/2}function yQn(e){return((e=Math.exp(e))-1/e)/2}function bQn(e){return((e=Math.exp(2*e))-1)/(e+1)}const A8=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<vQn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var x=Math.sqrt(v),S=(p*p-u*u+r*v)/(2*u*n*x),k=(p*p-u*u-r*v)/(2*p*n*x),C=Math.log(Math.sqrt(S*S+1)-S),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-C)/t,y=function(E){var T=E*b,N=x7e(C),I=u/(n*x)*(N*bQn(t*T+C)-yQn(C));return[l+I*h,c+I*m,u*N/x7e(t*T+C)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function xQn(e,t){t===void 0&&(t=e,e=hx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var Hj=0,BP=0,OR=0,Xkt=1e3,BB,UP,UB=0,GO=0,ZH=0,CM=typeof performance=="object"&&performance.now?performance:Date,Jkt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function nOe(){return GO||(Jkt(wQn),GO=CM.now()+ZH)}function wQn(){GO=0}function VB(){this._call=this._time=this._next=null}VB.prototype=eOt.prototype={constructor:VB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?nOe():+n)+(t==null?0:+t),!this._next&&UP!==this&&(UP?UP._next=this:BB=this,UP=this),this._call=e,this._time=n,Yge()},stop:function(){this._call&&(this._call=null,this._time=1/0,Yge())}};function eOt(e,t,n){var r=new VB;return r.restart(e,t,n),r}function SQn(){nOe(),++Hj;for(var e=BB,t;e;)(t=GO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Hj}function w7e(){GO=(UB=CM.now())+ZH,Hj=BP=0;try{SQn()}finally{Hj=0,OQn(),GO=0}}function kQn(){var e=CM.now(),t=e-UB;t>Xkt&&(ZH-=t,UB=e)}function OQn(){for(var e,t=BB,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:BB=n);UP=e,Yge(r)}function Yge(e){if(!Hj){BP&&(BP=clearTimeout(BP));var t=e-GO;t>24?(e<1/0&&(BP=setTimeout(w7e,e-CM.now()-ZH)),OR&&(OR=clearInterval(OR))):(OR||(UB=CM.now(),OR=setInterval(kQn,Xkt)),Hj=1,Jkt(w7e))}}function S7e(e,t,n){var r=new VB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var _Qn=HH("start","end","cancel","interrupt"),CQn=[],tOt=0,k7e=1,Kge=2,R8=3,O7e=4,Xge=5,P8=6;function GH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;EQn(e,n,{name:t,index:r,group:s,on:_Qn,tween:CQn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:tOt})}function rOe(e,t){var n=Qg(e,t);if(n.state>tOt)throw new Error("too late; already scheduled");return n}function Uy(e,t){var n=Qg(e,t);if(n.state>R8)throw new Error("too late; already running");return n}function Qg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function EQn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=eOt(a,0,n.time);function a(u){n.state=k7e,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!==k7e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===R8)return S7e(i);h.state===O7e?(h.state=P8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=P8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(S7e(function(){n.state===R8&&(n.state=O7e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Kge,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Kge){for(n.state=R8,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=Xge,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===Xge&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=P8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function $8(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Kge&&r.state<Xge,r.state=P8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function TQn(e){return this.each(function(){$8(this,e)})}function jQn(e,t){var n,r;return function(){var s=Uy(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function NQn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Uy(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function IQn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Qg(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?jQn:NQn)(n,e,t))}function sOe(e,t,n){var r=e._id;return e.each(function(){var s=Uy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Qg(s,r).value[t]}}function nOt(e,t){var n;return(typeof t=="number"?ug:t instanceof ZO?zB:(n=ZO(t))?(t=n,zB):Qkt)(e,t)}function AQn(e){return function(){this.removeAttribute(e)}}function RQn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function PQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function $Qn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function MQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function DQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function LQn(e,t){var n=WH(e),r=n==="transform"?gQn:nOt;return this.attrTween(e,typeof t=="function"?(n.local?DQn:MQn)(n,r,sOe(this,"attr."+e,t)):t==null?(n.local?RQn:AQn)(n):(n.local?$Qn:PQn)(n,r,t))}function FQn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function zQn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function BQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&zQn(e,a)),n}return s._value=t,s}function UQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&FQn(e,a)),n}return s._value=t,s}function VQn(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=WH(e);return this.tween(n,(r.local?BQn:UQn)(r,t))}function qQn(e,t){return function(){rOe(this,e).delay=+t.apply(this,arguments)}}function HQn(e,t){return t=+t,function(){rOe(this,e).delay=t}}function WQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?qQn:HQn)(t,e)):Qg(this.node(),t).delay}function ZQn(e,t){return function(){Uy(this,e).duration=+t.apply(this,arguments)}}function GQn(e,t){return t=+t,function(){Uy(this,e).duration=t}}function QQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?ZQn:GQn)(t,e)):Qg(this.node(),t).duration}function YQn(e,t){if(typeof t!="function")throw new Error;return function(){Uy(this,e).ease=t}}function KQn(e){var t=this._id;return arguments.length?this.each(YQn(t,e)):Qg(this.node(),t).ease}function XQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Uy(this,e).ease=n}}function JQn(e){if(typeof e!="function")throw new Error;return this.each(XQn(this._id,e))}function eYn(e){typeof e!="function"&&(e=Rkt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new $x(r,this._parents,this._name,this._id)}function tYn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new $x(i,this._parents,this._name,this._id)}function nYn(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 rYn(e,t,n){var r,s,a=nYn(t)?rOe:Uy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function sYn(e,t){var n=this._id;return arguments.length<2?Qg(this.node(),n).on.on(e):this.each(rYn(n,e,t))}function aYn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function iYn(){return this.on("end.remove",aYn(this._id))}function oYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Kke(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,GH(u[p],t,n,p,u,Qg(d,n)));return new $x(a,this._parents,t,n)}function lYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Akt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=Qg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&GH(h,t,n,v,p,m);a.push(p),i.push(d)}return new $x(a,i,t,n)}var cYn=M3.prototype.constructor;function uYn(){return new cYn(this._groups,this._parents)}function dYn(e,t){var n,r,s;return function(){var a=qj(this,e),i=(this.style.removeProperty(e),qj(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function rOt(e){return function(){this.style.removeProperty(e)}}function fYn(e,t,n){var r,s=n+"",a;return function(){var i=qj(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function pYn(e,t,n){var r,s,a;return function(){var i=qj(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),qj(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function hYn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Uy(this,e),u=c.on,d=c.value[a]==null?l||(l=rOt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function mYn(e,t,n){var r=(e+="")=="transform"?mQn:nOt;return t==null?this.styleTween(e,dYn(e,r)).on("end.style."+e,rOt(e)):typeof t=="function"?this.styleTween(e,pYn(e,r,sOe(this,"style."+e,t))).each(hYn(this._id,e)):this.styleTween(e,fYn(e,r,t),n).on("end.style."+e,null)}function gYn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function vYn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&gYn(e,i,n)),r}return a._value=t,a}function yYn(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,vYn(e,t,n??""))}function bYn(e){return function(){this.textContent=e}}function xYn(e){return function(){var t=e(this);this.textContent=t??""}}function wYn(e){return this.tween("text",typeof e=="function"?xYn(sOe(this,"text",e)):bYn(e==null?"":e+""))}function SYn(e){return function(t){this.textContent=e.call(this,t)}}function kYn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&SYn(s)),t}return r._value=e,r}function OYn(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,kYn(e))}function _Yn(){for(var e=this._name,t=this._id,n=sOt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=Qg(c,t);GH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new $x(r,this._parents,e,n)}function CYn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=Uy(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var EYn=0;function $x(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function sOt(){return++EYn}var wb=M3.prototype;$x.prototype={constructor:$x,select:oYn,selectAll:lYn,selectChild:wb.selectChild,selectChildren:wb.selectChildren,filter:eYn,merge:tYn,selection:uYn,transition:_Yn,call:wb.call,nodes:wb.nodes,node:wb.node,size:wb.size,empty:wb.empty,each:wb.each,on:sYn,attr:LQn,attrTween:VQn,style:mYn,styleTween:yYn,text:wYn,textTween:OYn,remove:iYn,tween:IQn,delay:WQn,duration:QQn,ease:KQn,easeVarying:JQn,end:CYn,[Symbol.iterator]:wb[Symbol.iterator]};function TYn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var jYn={time:null,delay:0,duration:250,ease:TYn};function NYn(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 IYn(e){var t,n;e instanceof $x?(t=e._id,e=e._name):(t=sOt(),(n=jYn).time=nOe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&GH(c,e,t,u,i,n||NYn(c,t));return new $x(r,this._parents,e,t)}M3.prototype.interrupt=TQn;M3.prototype.transition=IYn;const rF=e=>()=>e;function AYn(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 nx(e,t,n){this.k=e,this.x=t,this.y=n}nx.prototype={constructor:nx,scale:function(e){return e===1?this:new nx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new nx(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 QH=new nx(1,0,0);aOt.prototype=nx.prototype;function aOt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return QH;return e.__zoom}function Bte(e){e.stopImmediatePropagation()}function _R(e){e.preventDefault(),e.stopImmediatePropagation()}function RYn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function PYn(){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 _7e(){return this.__zoom||QH}function $Yn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function MYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function DYn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function iOt(){var e=RYn,t=PYn,n=DYn,r=$Yn,s=MYn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=A8,u=HH("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(D){D.property("__zoom",_7e).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,F,H,B){var U=D.selection?D.selection():D;U.property("__zoom",_7e),D!==U?C(D,F,H,B):U.interrupt().each(function(){_(this,arguments).event(B).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},b.scaleBy=function(D,F,H,B){b.scaleTo(D,function(){var U=this.__zoom.k,V=typeof F=="function"?F.apply(this,arguments):F;return U*V},H,B)},b.scaleTo=function(D,F,H,B){b.transform(D,function(){var U=t.apply(this,arguments),V=this.__zoom,M=H==null?k(U):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),q=typeof F=="function"?F.apply(this,arguments):F;return n(S(x(V,q),M,G),U,i)},H,B)},b.translateBy=function(D,F,H,B){b.transform(D,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,B)},b.translateTo=function(D,F,H,B,U){b.transform(D,function(){var V=t.apply(this,arguments),M=this.__zoom,G=B==null?k(V):typeof B=="function"?B.apply(this,arguments):B;return n(QH.translate(G[0],G[1]).scale(M.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},B,U)};function x(D,F){return F=Math.max(a[0],Math.min(a[1],F)),F===D.k?D:new nx(F,D.x,D.y)}function S(D,F,H){var B=F[0]-H[0]*D.k,U=F[1]-H[1]*D.k;return B===D.x&&U===D.y?D:new nx(D.k,B,U)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function C(D,F,H,B){D.on("start.zoom",function(){_(this,arguments).event(B).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(B).end()}).tween("zoom",function(){var U=this,V=arguments,M=_(U,V).event(B),G=t.apply(U,V),q=H==null?k(G):typeof H=="function"?H.apply(U,V):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),z=U.__zoom,Z=typeof F=="function"?F.apply(U,V):F,K=c(z.invert(q).concat($/z.k),Z.invert(q).concat($/Z.k));return function(re){if(re===1)re=Z;else{var ee=K(re),J=$/ee[2];re=new nx(J,q[0]-ee[0]*J,q[1]-ee[1]*J)}M.zoom(null,re)}})}function _(D,F,H){return!H&&D.__zooming||new E(D,F)}function E(D,F){this.that=D,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,F),this.taps=0}E.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,F){return this.mouse&&D!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var F=Tp(this.that).datum();u.call(D,this.that,new AYn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),F)}};function T(D,...F){if(!e.apply(this,arguments))return;var H=_(this,F).event(D),B=this.__zoom,U=Math.max(a[0],Math.min(a[1],B.k*Math.pow(2,r.apply(this,arguments)))),V=lg(D);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=B.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(B.k===U)return;H.mouse=[V,B.invert(V)],$8(this),H.start()}_R(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(B,U),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...F){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,B=_(this,F,!0).event(D),U=Tp(D.view).on("mousemove.zoom",q,!0).on("mouseup.zoom",$,!0),V=lg(D,H),M=D.clientX,G=D.clientY;Vkt(D.view),Bte(D),B.mouse=[V,this.__zoom.invert(V)],$8(this),B.start();function q(z){if(_R(z),!B.moved){var Z=z.clientX-M,K=z.clientY-G;B.moved=Z*Z+K*K>v}B.event(z).zoom("mouse",n(S(B.that.__zoom,B.mouse[0]=lg(z,H),B.mouse[1]),B.extent,i))}function $(z){U.on("mousemove.zoom mouseup.zoom",null),qkt(z.view,B.moved),_R(z),B.event(z).end()}}function I(D,...F){if(e.apply(this,arguments)){var H=this.__zoom,B=lg(D.changedTouches?D.changedTouches[0]:D,this),U=H.invert(B),V=H.k*(D.shiftKey?.5:2),M=n(S(x(H,V),B,U),t.apply(this,F),i);_R(D),l>0?Tp(this).transition().duration(l).call(C,M,B,D):Tp(this).call(b.transform,M,B,D)}}function A(D,...F){if(e.apply(this,arguments)){var H=D.touches,B=H.length,U=_(this,F,D.changedTouches.length===B).event(D),V,M,G,q;for(Bte(D),M=0;M<B;++M)G=H[M],q=lg(G,this),q=[q,this.__zoom.invert(q),G.identifier],U.touch0?!U.touch1&&U.touch0[2]!==q[2]&&(U.touch1=q,U.taps=0):(U.touch0=q,V=!0,U.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(U.taps<2&&(f=q[0],d=setTimeout(function(){d=null},h)),$8(this),U.start())}}function R(D,...F){if(this.__zooming){var H=_(this,F).event(D),B=D.changedTouches,U=B.length,V,M,G,q;for(_R(D),V=0;V<U;++V)M=B[V],G=lg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],z=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],re=(re=Z[0]-$[0])*re+(re=Z[1]-$[1])*re,ee=(ee=K[0]-z[0])*ee+(ee=K[1]-z[1])*ee;M=x(M,Math.sqrt(re/ee)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],q=[(z[0]+K[0])/2,(z[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],q=H.touch0[1];else return;H.zoom("touch",n(S(M,G,q),H.extent,i))}}function L(D,...F){if(this.__zooming){var H=_(this,F).event(D),B=D.changedTouches,U=B.length,V,M;for(Bte(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),V=0;V<U;++V)M=B[V],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=lg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Tp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:rF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:rF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:rF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:rF([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const Sy={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."},EM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],oOt=["Enter"," ","Escape"],lOt={"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 Wj;(function(e){e.Strict="strict",e.Loose="loose"})(Wj||(Wj={}));var sO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(sO||(sO={}));var TM;(function(e){e.Partial="partial",e.Full="full"})(TM||(TM={}));const cOt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Sw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Sw||(Sw={}));var jM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(jM||(jM={}));var sr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(sr||(sr={}));const C7e={[sr.Left]:sr.Right,[sr.Right]:sr.Left,[sr.Top]:sr.Bottom,[sr.Bottom]:sr.Top};function uOt(e){return e===null?null:e?"valid":"invalid"}const dOt=e=>"id"in e&&"source"in e&&"target"in e,LYn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),aOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),L3=(e,t=[0,0])=>{const{width:n,height:r}=a0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},FYn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):aOe(s)?s:t.nodeLookup.get(s.id));const l=i?qB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return YH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return KH(n)},F3=(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=YH(n,qB(s)),r=!0)}),r?KH(n):{x:0,y:0,width:0,height:0}},iOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...B3(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=NM(l,Gj(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},zYn=(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 BYn(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 UYn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=BYn(e,i),c=F3(l),u=oOe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function fOt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",Sy.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&Qj(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=Qj(f)?QO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",Sy.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 VYn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=zYn(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 Zj=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),QO=(e={x:0,y:0},t,n)=>({x:Zj(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Zj(e.y,t[0][1],t[1][1]-(n?.height??0))});function pOt(e,t,n){const{width:r,height:s}=a0(n),{x:a,y:i}=n.internals.positionAbsolute;return QO(e,[[a,i],[a+r,i+s]],t)}const E7e=(e,t,n)=>e<t?Zj(Math.abs(e-t),1,t)/t:e>n?-Zj(Math.abs(e-n),1,t)/t:0,hOt=(e,t,n=15,r=40)=>{const s=E7e(e.x,r,t.width-r)*n,a=E7e(e.y,r,t.height-r)*n;return[s,a]},YH=(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)}),Jge=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),KH=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Gj=(e,t=[0,0])=>{const{x:n,y:r}=aOe(e)?e.internals.positionAbsolute:L3(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}},qB=(e,t=[0,0])=>{const{x:n,y:r}=aOe(e)?e.internals.positionAbsolute:L3(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)}},mOt=(e,t)=>KH(YH(Jge(e),Jge(t))),NM=(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)},T7e=e=>wg(e.width)&&wg(e.height)&&wg(e.x)&&wg(e.y),wg=e=>!isNaN(e)&&isFinite(e),qYn=(e,t)=>{},z3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),B3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?z3(l,i):l},HB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function dE(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 HYn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=dE(e,n),s=dE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=dE(e.top??e.y??0,n),s=dE(e.bottom??e.y??0,n),a=dE(e.left??e.x??0,t),i=dE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function WYn(e,t,n,r,s,a){const{x:i,y:l}=HB(e,[t,n,r]),{x:c,y:u}=HB({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const oOe=(e,t,n,r,s,a)=>{const i=HYn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=Zj(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=WYn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},IM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function Qj(e){return e!=null&&e!=="parent"}function a0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function gOt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function vOt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function j7e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ZYn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function GYn(e){return{...lOt,...e||{}}}function k2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Sg(e),l=B3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?z3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const lOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),yOt=e=>e?.getRootNode?.()||window?.document,QYn=["INPUT","SELECT","TEXTAREA"];function bOt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:QYn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const xOt=e=>"clientX"in e,Sg=(e,t)=>{const n=xOt(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)}},N7e=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...lOe(i)}})};function wOt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function sF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function I7e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case sr.Left:return[t-sF(t-r,a),n];case sr.Right:return[t+sF(r-t,a),n];case sr.Top:return[t,n-sF(n-s,a)];case sr.Bottom:return[t,n+sF(s-n,a)]}}function cOe({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,curvature:i=.25}){const[l,c]=I7e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=I7e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=wOt({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 SOt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function YYn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function KYn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=YH(qB(e),qB(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return NM(i,KH(a))>0}const XYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,JYn=(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)),eKn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||XYn;let s;return dOt(e)?s={...e}:s={...e,id:r(e)},JYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function kOt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=SOt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const A7e={[sr.Left]:{x:-1,y:0},[sr.Right]:{x:1,y:0},[sr.Top]:{x:0,y:-1},[sr.Bottom]:{x:0,y:1}},tKn=({source:e,sourcePosition:t=sr.Bottom,target:n})=>t===sr.Left||t===sr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},R7e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function nKn({source:e,sourcePosition:t=sr.Bottom,target:n,targetPosition:r=sr.Top,center:s,offset:a,stepPosition:i}){const l=A7e[t],c=A7e[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=tKn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=SOt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const T=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?T:N:m=p==="x"?N:T}else{const T=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:T:m=l.y===h?T:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const F=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*F:x[p]=(d[p]>n[p]?-1:1)*F}}if(t!==r){const D=p==="x"?"y":"x",F=l[p]===c[D],H=u[D]>d[D],B=u[D]<d[D];(l[p]===1&&(!F&&H||F&&B)||l[p]!==1&&(!F&&B||F&&H))&&(m=p==="x"?T:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const C={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...C.x!==m[0].x||C.y!==m[0].y?[C]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],v,y,S,k]}function rKn(e,t,n,r){const s=Math.min(R7e(e,t)/2,R7e(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function eve({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=nKn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=rKn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function P7e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function sKn(e){const{sourceNode:t,targetNode:n}=e;if(!P7e(t)||!P7e(n))return null;const r=t.internals.handleBounds||$7e(t.handles),s=n.internals.handleBounds||$7e(n.handles),a=M7e(r?.source??[],e.sourceHandle),i=M7e(e.connectionMode===Wj.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",Sy.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||sr.Bottom,c=i?.position||sr.Top,u=YO(t,a,l),d=YO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function $7e(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function YO(e,t,n=sr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??a0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case sr.Top:return{x:s+i/2,y:a};case sr.Right:return{x:s+i,y:a+l/2};case sr.Bottom:return{x:s+i/2,y:a+l};case sr.Left:return{x:s,y:a+l/2}}}function M7e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function tve(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function aKn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=tve(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const OOt=1e3,iKn=10,uOe={nodeOrigin:[0,0],nodeExtent:EM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},oKn={...uOe,checkEquality:!0};function dOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function lKn(e,t,n){const r=dOe(uOe,n);for(const s of e.values())if(s.parentId)pOe(s,e,t,r);else{const a=L3(s,r.nodeOrigin),i=Qj(s.extent)?s.extent:r.nodeExtent,l=QO(a,i,a0(s));s.internals.positionAbsolute=l}}function cKn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function fOe(e){return e==="manual"}function nve(e,t,n,r={}){const s=dOe(oKn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!fOe(s.zIndexMode)?OOt: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=L3(d,s.nodeOrigin),h=Qj(d.extent)?d.extent:s.nodeExtent,m=QO(p,h,a0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:cKn(d,f),z:_Ot(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&&pOe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function uKn(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 pOe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=dOe(uOe,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}uKn(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*iKn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!fOe(c)?OOt:0,{x:p,y:h,z:m}=dKn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function _Ot(e,t,n){const r=wg(e.zIndex)?e.zIndex:0;return fOe(n)?r:r+(e.selected?t:0)}function dKn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=a0(e),u=L3(e,n),d=Qj(e.extent)?QO(u,e.extent,c):u;let f=QO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=pOt(f,c,t));const p=_Ot(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function hOe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??Gj(l),u=mOt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=a0(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function fKn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=lOe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=Qj(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=pOt(k,v,t.get(m.parentId)):S&&(k=QO(k,S,v));const C={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:N7e("source",h.nodeElement,x,f,m.id),target:N7e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,C),m.parentId&&pOe(C,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:Gj(C,s)}))}}if(p.length>0){const h=hOe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function pKn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function D7e(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function COt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;D7e("source",c,d,e,s,i),D7e("target",c,u,e,a,l),t.set(r.id,r)}}function EOt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:EOt(n,t):!1}function L7e(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 hKn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!EOt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Ute({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function mKn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=z3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function gKn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,p=null,h=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:C,nodeId:_,nodeClickDistance:E=0}){p=Tp(k);function T({x:R,y:L}){const{nodeLookup:D,nodeExtent:F,snapGrid:H,snapToGrid:B,nodeOrigin:U,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:q}=t();a={x:R,y:L};let $=!1;const z=l.size>1,Z=z&&F?Jge(F3(l)):null,K=z&&B?mKn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[re,ee]of l){if(!D.has(re))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};B&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:z3(J,H));let ae=null;if(z&&F&&!ee.extent&&Z){const{positionAbsolute:te}=ee.internals,ue=te.x-Z.x+F[0][0],de=te.x+ee.measured.width-Z.x2+F[1][0],ce=te.y-Z.y+F[0][1],ge=te.y+ee.measured.height-Z.y2+F[1][1];ae=[[ue,ce],[de,ge]]}const{position:fe,positionAbsolute:Y}=fOt({nodeId:re,nextPosition:J,nodeLookup:D,nodeExtent:ae||F,nodeOrigin:U,onError:G});$=$||ee.position.x!==fe.x||ee.position.y!==fe.y,ee.position=fe,ee.internals.positionAbsolute=Y}if(m=m||$,!!$&&(q(l,!0),v&&(r||V||!_&&M))){const[re,ee]=Ute({nodeId:_,dragItems:l,nodeLookup:D});r?.(v,l,re,ee),V?.(v,re,ee),_||M?.(v,ee)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:F}=t();if(!F){c=!1,cancelAnimationFrame(i);return}const[H,B]=hOt(u,d,D);(H!==0||B!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-B/R[2],await L({x:H,y:B})&&T(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:F,transform:H,snapGrid:B,snapToGrid:U,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:q}=t();f=!0,(!V||!C)&&!D&&_&&(L.get(_)?.selected||q()),C&&V&&_&&e?.(_);const $=k2(R.sourceEvent,{transform:H,snapGrid:B,snapToGrid:U,containerBounds:d});if(a=$,l=hKn(L,F,$,_),l.size>0&&(n||M||!_&&G)){const[z,Z]=Ute({nodeId:_,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,z,Z),M?.(R.sourceEvent,z,Z),_||G?.(R.sourceEvent,Z)}}const A=Hkt().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:F,snapGrid:H,snapToGrid:B}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,D===0&&I(R),a=k2(R.sourceEvent,{transform:F,snapGrid:H,snapToGrid:B,containerBounds:d}),u=Sg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:F,snapToGrid:H,nodeDragThreshold:B,nodeLookup:U}=t(),V=k2(R.sourceEvent,{transform:D,snapGrid:F,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||_&&!U.has(_))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=Sg(R.sourceEvent,d),G=M.x-u.x,q=M.y-u.y;Math.sqrt(G*G+q*q)>B&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Sg(R.sourceEvent,d),T(V))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:F,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||F||!_&&H){const[B,U]=Ute({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,B,U),F?.(R.sourceEvent,B,U),_||H?.(R.sourceEvent,U)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!L7e(L,`.${x}`,k))&&(!S||L7e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function vKn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())NM(s,Gj(a))>0&&r.push(a);return r}const yKn=250;function bKn(e,t,n,r){let s=[],a=1/0;const i=vKn(e,n,t+yKn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=YO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function TOt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...YO(i,c,c.position,!0)}:c}function jOt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function xKn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const NOt=()=>!0;function wKn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=NOt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:C,autoPanSpeed:_,dragThreshold:E=1,handleDomNode:T}){const N=yOt(e.target);let I=0,A;const{x:R,y:L}=Sg(e),D=jOt(a,T),F=l?.getBoundingClientRect();let H=!1;if(!F||!D)return;const B=TOt(s,D,r,c,t);if(!B)return;let U=Sg(e,F),V=!1,M=null,G=!1,q=null;function $(){if(!d||!F)return;const[fe,Y]=hOt(U,F,_);p({x:fe,y:Y}),I=requestAnimationFrame($)}const z={...B,nodeId:s,type:D,position:B.position},Z=c.get(s);let re={inProgress:!0,isValid:null,from:YO(Z,z,sr.Left,!0),fromHandle:z,fromPosition:z.position,fromNode:Z,to:U,toHandle:null,toPosition:C7e[z.position],toNode:null,pointer:U};function ee(){H=!0,S(re),m?.(e,{nodeId:s,handleId:r,handleType:D})}E===0&&ee();function J(fe){if(!H){const{x:ge,y:be}=Sg(fe),xe=ge-R,Ee=be-L;if(!(xe*xe+Ee*Ee>E*E))return;ee()}if(!C()||!z){ae(fe);return}const Y=k();U=Sg(fe,F),A=bKn(B3(U,Y,!1,[1,1]),n,c,z),V||($(),V=!0);const te=IOt(fe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});q=te.handleDomNode,M=te.connection,G=xKn(!!A,te.isValid);const ue=c.get(s),de=ue?YO(ue,z,sr.Left,!0):re.from,ce={...re,from:de,isValid:G,to:te.toHandle&&G?HB({x:te.toHandle.x,y:te.toHandle.y},Y):U,toHandle:te.toHandle,toPosition:G&&te.toHandle?te.toHandle.position:C7e[z.position],toNode:te.toHandle?c.get(te.toHandle.nodeId):null,pointer:U};S(ce),re=ce}function ae(fe){if(!("touches"in fe&&fe.touches.length>0)){if(H){(A||q)&&M&&G&&v?.(M);const{inProgress:Y,...te}=re,ue={...te,toPosition:re.toHandle?re.toPosition:null};y?.(fe,ue),a&&x?.(fe,ue)}h(),cancelAnimationFrame(I),V=!1,G=!1,M=null,q=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",J),N.addEventListener("touchend",ae)}function IOt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=NOt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=Sg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=jOt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),C=y.classList.contains("connectable"),_=y.classList.contains("connectableend");if(!S||!x)return b;const E={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=E;const N=C&&_&&(n===Wj.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(E),b.toHandle=TOt(S,x,k,d,n,!0)}return b}const rve={onPointerDown:wKn,isValid:IOt};function SKn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Tp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),C=S.sourceEvent.ctrlKey&&IM()?10:1,_=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,_*C);t.scaleTo(E)};let v=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(v=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const C=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],_=[C[0]-v[0],C[1]-v[1]];v=C;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),T={x:k[0]-_[0]*E,y:k[1]-_[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:T.x,y:T.y,zoom:k[2]},N,l)},x=iOt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:lg}}const XH=e=>({x:e.x,y:e.y,zoom:e.k}),Vte=({x:e,y:t,zoom:n})=>QH.translate(e,t).scale(n),fT=(e,t)=>e.target.closest(`.${t}`),AOt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),kKn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,qte=(e,t=0,n=kKn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},ROt=e=>{const t=e.ctrlKey&&IM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function OKn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(fT(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=lg(d),b=ROt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===sO.Vertical?0:d.deltaX*p,m=s===sO.Horizontal?0:d.deltaY*p;!IM()&&d.shiftKey&&s!==sO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=XH(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function _Kn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=fT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function CKn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=XH(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 EKn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&AOt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,XH(a.transform))}}function TKn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&AOt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=XH(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function jKn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(fT(f,`${u}-flow__node`)||fT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||fT(f,l)&&m||fT(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function NKn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=iOt().scaleExtent([t,n]).translateExtent(r),p=Tp(e).call(f);x({x:s.x,y:s.y,zoom:Zj(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(ROt);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:A8).transform(qte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:F,panOnDrag:H,panOnScrollMode:B,panOnScrollSpeed:U,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:q,zoomActivationKeyPressed:$,lib:z,onTransformChange:Z,connectionInProgress:K,paneClickDistance:re,selectionOnDrag:ee}){D&&!u.isZoomingOrPanning&&b();const J=F&&!$&&!D;f.clickDistance(ee?1/0:!wg(re)||re<0?0:re);const ae=J?OKn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:B,panOnScrollSpeed:U,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):_Kn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=CKn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const te=EKn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",te);const ue=TKn({zoomPanValues:u,panOnDrag:H,panOnScroll:F,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",ue)}const fe=jKn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:F,zoomOnDoubleClick:q,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:z,connectionInProgress:K});f.filter(fe),q?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=Vte(A),F=f?.constrain()(D,R,L);return F&&await v(F),new Promise(H=>H(F))}async function S(A,R){const L=Vte(A);return await v(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=Vte(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function C(){const A=p?aOt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:A8).scaleTo(qte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:A8).scaleBy(qte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!wg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:C,scaleTo:_,scaleBy:E,setScaleExtent:T,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var Yj;(function(e){e.Line="line",e.Handle="handle"})(Yj||(Yj={}));function IKn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function F7e(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 X0(e,t){return Math.max(0,t-e)}function J0(e,t){return Math.max(0,e-t)}function aF(e,t,n){return Math.max(0,t-e,e-n)}function z7e(e,t){return e?!t:t}function AKn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:C,height:_,aspectRatio:E}=e;let T=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=C+(c?-T:T),A=_+(u?-N:N),R=-a[0]*C,L=-a[1]*_;let D=aF(I,v,y),F=aF(A,b,x);if(i){let U=0,V=0;c&&T<0?U=X0(S+T+R,i[0][0]):!c&&T>0&&(U=J0(S+I+R,i[1][0])),u&&N<0?V=X0(k+N+L,i[0][1]):!u&&N>0&&(V=J0(k+A+L,i[1][1])),D=Math.max(D,U),F=Math.max(F,V)}if(l){let U=0,V=0;c&&T>0?U=J0(S+T,l[0][0]):!c&&T<0&&(U=X0(S+I,l[1][0])),u&&N>0?V=J0(k+N,l[0][1]):!u&&N<0&&(V=X0(k+A,l[1][1])),D=Math.max(D,U),F=Math.max(F,V)}if(s){if(d){const U=aF(I/E,b,x)*E;if(D=Math.max(D,U),i){let V=0;!c&&!u||c&&!u&&p?V=J0(k+L+I/E,i[1][1])*E:V=X0(k+L+(c?T:-T)/E,i[0][1])*E,D=Math.max(D,V)}if(l){let V=0;!c&&!u||c&&!u&&p?V=X0(k+I/E,l[1][1])*E:V=J0(k+(c?T:-T)/E,l[0][1])*E,D=Math.max(D,V)}}if(f){const U=aF(A*E,v,y)/E;if(F=Math.max(F,U),i){let V=0;!c&&!u||u&&!c&&p?V=J0(S+A*E+R,i[1][0])/E:V=X0(S+(u?N:-N)*E+R,i[0][0])/E,F=Math.max(F,V)}if(l){let V=0;!c&&!u||u&&!c&&p?V=X0(S+A*E,l[1][0])/E:V=J0(S+(u?N:-N)*E,l[0][0])/E,F=Math.max(F,V)}}}N=N+(N<0?F:-F),T=T+(T<0?D:-D),s&&(p?I>A*E?N=(z7e(c,u)?-T:T)/E:T=(z7e(c,u)?-N:N)*E:d?(N=T/E,u=c):(T=N*E,c=u));const H=c?S+T:S,B=u?k+N:k;return{width:C+(c?-T:T),height:_+(u?-N:N),x:a[0]*T*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+B}}const POt={width:0,height:0,x:0,y:0},RKn={...POt,pointerX:0,pointerY:0,aspectRatio:1};function PKn(e){return[[0,0],[e.measured.width,e.measured.height]]}function $Kn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function MKn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Tp(e);let i={controlDirection:F7e("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...POt},x={...RKn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:F7e(u)};let S,k=null,C=[],_,E,T,N=!1;const I=Hkt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:F,nodeOrigin:H,paneDomNode:B}=n();if(S=R.get(t),!S)return;k=B?.getBoundingClientRect()??null;const{xSnapped:U,ySnapped:V}=k2(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:F,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:U,pointerY:V,aspectRatio:b.width/b.height},_=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(_=R.get(S.parentId),E=_&&S.extent==="parent"?PKn(_):void 0),C=[],T=void 0;for(const[M,G]of R)if(G.parentId===t&&(C.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const q=$Kn(G,S,G.origin??H);T?T=[[Math.min(q[0][0],T[0][0]),Math.min(q[0][1],T[0][1])],[Math.max(q[1][0],T[1][0]),Math.max(q[1][1],T[1][1])]]:T=q}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:F}=n(),H=k2(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),B=[];if(!S)return;const{x:U,y:V,width:M,height:G}=b,q={},$=S.origin??F,{width:z,height:Z,x:K,y:re}=AKn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,T),ee=z!==M,J=Z!==G,ae=K!==U&&ee,fe=re!==V&&J;if(!ae&&!fe&&!ee&&!J)return;if((ae||fe||$[0]===1||$[1]===1)&&(q.x=ae?K:b.x,q.y=fe?re:b.y,b.x=q.x,b.y=q.y,C.length>0)){const de=K-U,ce=re-V;for(const ge of C)ge.position={x:ge.position.x-de+$[0]*(z-M),y:ge.position.y-ce+$[1]*(Z-G)},B.push(ge)}if((ee||J)&&(q.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?z:b.width,q.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=q.width,b.height=q.height),_&&S.expandParent){const de=$[0]*(q.width??0);q.x&&q.x<de&&(b.x=de,x.x=x.x-(q.x-de));const ce=$[1]*(q.height??0);q.y&&q.y<ce&&(b.y=ce,x.y=x.y-(q.y-ce))}const Y=IKn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...b,direction:Y};y?.(A,te)!==!1&&(N=!0,m?.(A,te),r(q,B))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const DKn={},B7e=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:()=>{(DKn?"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},LKn=e=>e?B7e(e):B7e,{useDebugValue:FKn}=Fe,{useSyncExternalStoreWithSelector:zKn}=_En,BKn=e=>e;function $Ot(e,t=BKn,n){const r=zKn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return FKn(r),r}const U7e=(e,t)=>{const n=LKn(e),r=(s,a=t)=>$Ot(n,s,a);return Object.assign(r,n),r},UKn=(e,t)=>e?U7e(e,t):U7e;function io(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const JH=g.createContext(null),VKn=JH.Provider,MOt=Sy.error001();function Us(e,t){const n=g.useContext(JH);if(n===null)throw new Error(MOt);return $Ot(n,e,t)}function To(){const e=g.useContext(JH);if(e===null)throw new Error(MOt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const V7e={display:"none"},qKn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},DOt="react-flow__node-desc",LOt="react-flow__edge-desc",HKn="react-flow__aria-live",WKn=e=>e.ariaLiveMessage,ZKn=e=>e.ariaLabelConfig;function GKn({rfId:e}){const t=Us(WKn);return o.jsx("div",{id:`${HKn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:qKn,children:t})}function QKn({rfId:e,disableKeyboardA11y:t}){const n=Us(ZKn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${DOt}-${e}`,style:V7e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${LOt}-${e}`,style:V7e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(GKn,{rfId:e})]})}const U3=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Hl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});U3.displayName="Panel";function YKn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(U3,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const KKn=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}},iF=e=>e.id;function XKn(e,t){return io(e.selectedNodes.map(iF),t.selectedNodes.map(iF))&&io(e.selectedEdges.map(iF),t.selectedEdges.map(iF))}function JKn({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Us(KKn,XKn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const eXn=e=>!!e.onSelectionChangeHandlers;function tXn({onSelectionChange:e}){const t=Us(eXn);return e||t?o.jsx(JKn,{onSelectionChange:e}):null}const sve=typeof window<"u"?g.useLayoutEffect:g.useEffect,FOt=[0,0],nXn={x:0,y:0,zoom:1},rXn=["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"],q7e=[...rXn,"rfId"],sXn=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}),H7e={translateExtent:EM,nodeOrigin:FOt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function aXn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Us(sXn,io),u=To();sve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=H7e,l()}),[]);const d=g.useRef(H7e);return sve(()=>{for(const f of q7e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:GYn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},q7e.map(f=>e[f])),null}function W7e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function iXn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=W7e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:W7e()?.matches?"dark":"light"}const Z7e=typeof document<"u"?document:null;function AM(e=null,t={target:Z7e,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
234
+ `:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new iHn(this):new rHn(this)}getCursor(t,n=0,r){let s=t.doc?t:us.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?WE(this,s,n,r):HE(this,s,n,r)}}class hkt{constructor(t){this.spec=t}}function tHn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function HE(e,t,n,r){let s;return e.wholeWord&&(s=nHn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=tHn(e.test,t,s)),new Px(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function nHn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(AB(s,n-a))!=So.Word||t(RB(s,n-a))!=So.Word)&&(t(RB(s,r-a))!=So.Word||t(AB(s,r-a))!=So.Word))}class rHn extends hkt{constructor(t){super(t)}nextMatch(t,n,r){let s=HE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=HE(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=HE(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=HE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=HE(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function sHn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function WE(e,t,n,r){let s;return e.wholeWord&&(s=aHn(t.charCategorizer(t.selection.main.head))),e.test&&(s=sHn(e.test,t,s)),new dkt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function AB(e,t){return e.slice(Oc(e,t,!1),t)}function RB(e,t){return e.slice(t,Oc(e,t))}function aHn(e){return(t,n,r)=>!r[0].length||(e(AB(r.input,r.index))!=So.Word||e(RB(r.input,r.index))!=So.Word)&&(e(RB(r.input,r.index+r[0].length))!=So.Word||e(AB(r.input,r.index+r[0].length))!=So.Word)}class iHn extends hkt{nextMatch(t,n,r){let s=WE(this.spec,t,r,t.doc.length).next();return s.done&&(s=WE(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=WE(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=WE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=WE(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const xM=xr.define(),Wke=xr.define(),Qw=bl.define({create(e){return new zee(Vge(e).create(),null)},update(e,t){for(let n of t.effects)n.is(xM)?e=new zee(n.value.create(),e.panel):n.is(Wke)&&(e=new zee(e.query,n.value?Zke:null));return e},provide:e=>uM.from(e,t=>t.panel)});class zee{constructor(t,n){this.query=t,this.panel=n}}const oHn=An.mark({class:"cm-searchMatch"}),lHn=An.mark({class:"cm-searchMatch cm-searchMatch-selected"}),cHn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Qw))}update(e){let t=e.state.field(Qw);(t!=e.startState.field(Qw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return An.none;let{view:n}=this,r=new Dd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(p=>p.from==u&&p.to==d);r.add(u,d,f?lHn:oHn)})}return r.finish()}},{decorations:e=>e.decorations});function $3(e){return t=>{let n=t.state.field(Qw,!1);return n&&n.query.spec.valid?e(t,n):vkt(t)}}const PB=$3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=bt.single(r.from,r.to),a=e.state.facet(mI);return e.dispatch({selection:s,effects:[Gke(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),gkt(e),!0}),$B=$3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=bt.single(s.from,s.to),i=e.state.facet(mI);return e.dispatch({selection:a,effects:[Gke(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),gkt(e),!0}),uHn=$3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:bt.create(n.map(r=>bt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),dHn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new Px(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(bt.range(l.value.from,l.value.to))}return t(e.update({selection:bt.create(a,i),userEvent:"select.search.matches"})),!0},e9e=$3((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(It.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=bt.single(i.from,i.to).map(f),d.push(Gke(e,i)),d.push(n.facet(mI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),fHn=$3((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:It.announce.of(r),userEvent:"input.replace.all"}),!0});function Zke(e){return e.state.facet(mI).createPanel(e)}function Vge(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(mI);return new pkt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function mkt(e){let t=cke(e,Zke);return t&&t.dom.querySelector("[main-field]")}function gkt(e){let t=mkt(e);t&&t==e.root.activeElement&&t.select()}const vkt=e=>{let t=e.state.field(Qw,!1);if(t&&t.panel){let n=mkt(e);if(n&&n!=e.root.activeElement){let r=Vge(e.state,t.query.spec);r.valid&&e.dispatch({effects:xM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Wke.of(!0),t?xM.of(Vge(e.state,t.query.spec)):xr.appendConfig.of(gHn)]});return!0},ykt=e=>{let t=e.state.field(Qw,!1);if(!t||!t.panel)return!1;let n=cke(e,Zke);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Wke.of(!1)}),!0},pHn=[{key:"Mod-f",run:vkt,scope:"editor search-panel"},{key:"F3",run:PB,shift:$B,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:PB,shift:$B,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:ykt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:dHn},{key:"Mod-Alt-g",run:Vqn},{key:"Mod-d",run:eHn,preventDefault:!0}];class hHn{constructor(t){this.view=t;let n=this.query=t.state.field(Qw).query.spec;this.commit=this.commit.bind(this),this.searchField=hi("input",{value:n.search,placeholder:dp(t,"Find"),"aria-label":dp(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=hi("input",{value:n.replace,placeholder:dp(t,"Replace"),"aria-label":dp(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=hi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=hi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=hi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return hi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=hi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>PB(t),[dp(t,"next")]),r("prev",()=>$B(t),[dp(t,"previous")]),r("select",()=>uHn(t),[dp(t,"all")]),hi("label",null,[this.caseField,dp(t,"match case")]),hi("label",null,[this.reField,dp(t,"regexp")]),hi("label",null,[this.wordField,dp(t,"by word")]),...t.state.readOnly?[]:[hi("br"),this.replaceField,r("replace",()=>e9e(t),[dp(t,"replace")]),r("replaceAll",()=>fHn(t),[dp(t,"replace all")])],hi("button",{name:"close",onclick:()=>ykt(t),"aria-label":dp(t,"close"),type:"button"},["×"])])}commit(){let t=new pkt({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:xM.of(t)}))}keydown(t){Pzn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?$B:PB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),e9e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(xM)&&!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(mI).top}}function dp(e,t){return e.state.phrase(t)}const Y6=30,K6=/[\s\.,:;?!]/;function Gke(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-Y6),i=Math.min(s,n+Y6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<Y6;c++)if(!K6.test(l[c+1])&&K6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-Y6;c--)if(!K6.test(l[c-1])&&K6.test(l[c])){l=l.slice(0,c);break}}return It.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const mHn=It.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),gHn=[Qw,nh.low(cHn),mHn];class t9e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Ek{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(wM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Dd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=jHn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,An.widget({widget:new _Hn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,An.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new Ek(u,n,Vj(u))}}function Vj(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new t9e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new t9e(r.from,a,r.diagnostic)}}),r}function vHn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(wM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(bkt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function yHn(e,t){return e.field(Ap,!1)?t:t.concat(xr.appendConfig.of(NHn))}const bkt=xr.define(),Qke=xr.define(),xkt=xr.define(),Ap=bl.define({create(){return new Ek(An.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=Vj(n,e.selected.diagnostic,a)||Vj(n,null,a)}!n.size&&s&&t.state.facet(wM).autoPanel&&(s=null),e=new Ek(n,s,r)}for(let n of t.effects)if(n.is(bkt)){let r=t.state.facet(wM).autoPanel?n.value.length?SM.open:null:e.panel;e=Ek.init(n.value,r,t.state)}else n.is(Qke)?e=new Ek(e.diagnostics,n.value?SM.open:null,e.selected):n.is(xkt)&&(e=new Ek(e.diagnostics,e.panel,n.value));return e},provide:e=>[uM.from(e,t=>t.panel),It.decorations.from(e,t=>t.diagnostics)]}),bHn=An.mark({class:"cm-lintRange cm-lintRange-active"});function xHn(e,t,n){let{diagnostics:r}=e.state.field(Ap),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(wM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:wHn(e,s)}}}:null}function wHn(e,t){return hi("ul",{class:"cm-tooltip-lint"},t.map(n=>Skt(e,n,!1)))}const SHn=e=>{let t=e.state.field(Ap,!1);(!t||!t.panel)&&e.dispatch({effects:yHn(e.state,[Qke.of(!0)])});let n=cke(e,SM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},n9e=e=>{let t=e.state.field(Ap,!1);return!t||!t.panel?!1:(e.dispatch({effects:Qke.of(!1)}),!0)},kHn=e=>{let t=e.state.field(Ap,!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)},OHn=[{key:"Mod-Shift-m",run:SHn,preventDefault:!0},{key:"F8",run:kHn}],wM=Tn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...By(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:r9e,tooltipFilter:r9e,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function r9e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function wkt(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function Skt(e,t,n){var r;let s=n?wkt(t.actions):[];return hi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},hi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=Vj(e.state.field(Ap).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),hi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return hi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&hi("div",{class:"cm-diagnosticSource"},t.source))}class _Hn extends rh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return hi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class s9e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Skt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class SM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)n9e(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=wkt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=Vj(this.view.state.field(Ap).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=hi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=hi("div",{class:"cm-panel-lint"},this.list,hi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>n9e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ap).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(Ap),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new s9e(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new s9e(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Ap),r=Vj(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:xkt.of(r)})}static open(t){return new SM(t)}}function CHn(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 X6(e){return CHn(`<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 EHn=It.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:X6("#d11")},".cm-lintRange-warning":{backgroundImage:X6("orange")},".cm-lintRange-info":{backgroundImage:X6("#999")},".cm-lintRange-hint":{backgroundImage:X6("#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 THn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function jHn(e){let t="hint",n=1;for(let r of e){let s=THn(r.severity);s>n&&(n=s,t=r.severity)}return t}const NHn=[Ap,It.decorations.compute([Ap],e=>{let{selected:t,panel:n}=e.field(Ap);return!t||!n||t.from==t.to?An.none:An.set([bHn.range(t.from,t.to)])}),S8n(xHn,{hideOn:vHn}),EHn];var a9e=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(b7n)),t.defaultKeymap!==!1&&(a=a.concat(zqn)),t.searchKeymap!==!1&&(a=a.concat(pHn)),t.historyKeymap!==!1&&(a=a.concat(ZVn)),t.foldKeymap!==!1&&(a=a.concat(s9n)),t.completionKeymap!==!1&&(a=a.concat(g1t)),t.lintKeymap!==!1&&(a=a.concat(OHn));var i=[];return t.lineNumbers!==!1&&i.push(P8n()),t.highlightActiveLineGutter!==!1&&i.push(D8n()),t.highlightSpecialChars!==!1&&i.push(Yzn()),t.history!==!1&&i.push(LVn()),t.foldGutter!==!1&&i.push(l9n()),t.drawSelection!==!1&&i.push(zzn()),t.dropCursor!==!1&&i.push(Hzn()),t.allowMultipleSelections!==!1&&i.push(us.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(Y8n()),t.syntaxHighlighting!==!1&&i.push(eS(f9n,{fallback:!0})),t.bracketMatching!==!1&&i.push(b9n()),t.closeBrackets!==!1&&i.push(m7n()),t.autocompletion!==!1&&i.push(m1t()),t.rectangularSelection!==!1&&i.push(u8n()),s!==!1&&i.push(p8n()),t.highlightActiveLine!==!1&&i.push(n8n()),t.highlightSelectionMatches!==!1&&i.push(Wqn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(dI.of(" ".repeat(t.tabSize))),i.concat([uI.of(a.flat())]).filter(Boolean)};const IHn="#e5c07b",i9e="#e06c75",AHn="#56b6c2",RHn="#ffffff",N8="#abb2bf",qge="#7d8799",PHn="#61afef",$Hn="#98c379",o9e="#d19a66",MHn="#c678dd",DHn="#21252b",l9e="#2c313a",c9e="#282c34",Bee="#353a42",LHn="#3E4451",u9e="#528bff",FHn=It.theme({"&":{color:N8,backgroundColor:c9e},".cm-content":{caretColor:u9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:u9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:LHn},".cm-panels":{backgroundColor:DHn,color:N8},".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:c9e,color:qge,border:"none"},".cm-activeLineGutter":{backgroundColor:l9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Bee},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Bee,borderBottomColor:Bee},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:l9e,color:N8}}},{dark:!0}),zHn=Wg.define([{tag:he.keyword,color:MHn},{tag:[he.name,he.deleted,he.character,he.propertyName,he.macroName],color:i9e},{tag:[he.function(he.variableName),he.labelName],color:PHn},{tag:[he.color,he.constant(he.name),he.standard(he.name)],color:o9e},{tag:[he.definition(he.name),he.separator],color:N8},{tag:[he.typeName,he.className,he.number,he.changed,he.annotation,he.modifier,he.self,he.namespace],color:IHn},{tag:[he.operator,he.operatorKeyword,he.url,he.escape,he.regexp,he.link,he.special(he.string)],color:AHn},{tag:[he.meta,he.comment],color:qge},{tag:he.strong,fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:he.link,color:qge,textDecoration:"underline"},{tag:he.heading,fontWeight:"bold",color:i9e},{tag:[he.atom,he.bool,he.special(he.variableName)],color:o9e},{tag:[he.processingInstruction,he.string,he.inserted],color:$Hn},{tag:he.invalid,color:RHn}]),BHn=[FHn,eS(zHn)];var UHn=It.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),VHn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(uI.of([Bqn])),m&&(typeof m=="boolean"?v.unshift(a9e()):v.unshift(a9e(m))),p&&v.unshift(i8n(p)),d){case"light":v.push(UHn);break;case"dark":v.push(BHn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(It.editable.of(!1)),c&&v.push(us.readOnly.of(!0)),[...v]},qHn=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 HHn{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 d9e{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 Uee=null,WHn=()=>typeof window>"u"?new d9e:(Uee||(Uee=new d9e),Uee),ZHn=It.theme({"& .cm-scroller":{height:"100% !important"}}),f9e=null,Vee=null;function GHn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===f9e||(f9e=i,Vee=It.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),Vee}var p9e=zy.define(),QHn=200,YHn=[];function KHn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?YHn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,C=k===void 0?null:k,_=e.maxWidth,E=_===void 0?null:_,T=e.placeholder,N=T===void 0?"":T,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,F=D===void 0?!0:D,H=e.basicSetup,B=H===void 0?!0:H,U=e.root,V=e.initialState,M=g.useState(),G=M[0],q=M[1],$=g.useState(),z=$[0],Z=$[1],K=g.useState(),re=K[0],ee=K[1],J=g.useState(()=>({current:null}))[0],ae=g.useState(()=>({current:null}))[0],fe=GHn(h,v,b,S,C,E),Y=It.updateListener.of(de=>{if(de.docChanged&&typeof r=="function"&&!de.transactions.some(be=>be.annotation(p9e))){J.current?J.current.reset():(J.current=new HHn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},QHn),WHn().add(J.current));var ce=de.state.doc,ge=ce.toString();r(ge,de)}s&&s(qHn(de))}),te=VHn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:F,basicSetup:B}),ue=[Y,...fe?[fe]:[],ZHn,...te];return i&&typeof i=="function"&&ue.push(It.updateListener.of(i)),ue=ue.concat(c),g.useLayoutEffect(()=>{if(G&&!re){var de={doc:t,selection:n,extensions:ue},ce=V?us.fromJSON(V.json,de,V.fields):us.create(de);if(ee(ce),!z){var ge=new It({state:ce,parent:G,root:U});Z(ge),a&&a(ge,ce)}}return()=>{z&&(ee(void 0),Z(void 0))}},[G,re]),g.useEffect(()=>{e.container&&q(e.container)},[e.container]),g.useEffect(()=>()=>{z&&(z.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[z]),g.useEffect(()=>{u&&z&&z.focus()},[u,z]),g.useEffect(()=>{z&&z.dispatch({effects:xr.reconfigure.of(ue)})},[f,c,h,v,b,S,C,E,N,A,L,F,B,r,i]),g.useEffect(()=>{if(t!==void 0){var de=z?z.state.doc.toString():"";if(z&&t!==de){var ce=J.current&&!J.current.isDone,ge=()=>{z&&t!==z.state.doc.toString()&&z.dispatch({changes:{from:0,to:z.state.doc.toString().length,insert:t||""},annotations:[p9e.of(!0)]})};ce?ae.current=ge:ge()}}},[t,z]),{state:re,setState:ee,view:z,setView:Z,container:G,setContainer:q}}var XHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Ku=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,C=e.basicSetup,_=e.placeholder,E=e.indentWithTab,T=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=NSt(e,XHn),L=g.useRef(null),D=KHn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:C,placeholder:_,indentWithTab:E,editable:T,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),F=D.state,H=D.view,B=D.container,U=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:F,view:H}),[L,B,F,H]);var V=g.useCallback(G=>{L.current=G,U(G)},[U]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",WO({ref:V,className:""+M+(n?" "+n:"")},R))});Ku.displayName="CodeMirror";const JHn={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 qee=null;function eWn(){return qee||(qee=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Da(()=>import("./core-CKwPFHqo.js"),__vite__mapDeps([0,1,2]),import.meta.url),Da(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Da(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Da(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Da(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Da(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Da(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Da(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Da(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Da(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Da(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Da(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Da(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Da(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Da(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Da(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Da(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Da(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),qee}async function tWn(e,t){const n=JHn[t?.toLowerCase()];if(!n)return null;const r=await eWn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function nWn(e){return new UO(hke.define(e))}const kkt=[og.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Da(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript())}}),og.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Da(()=>Promise.resolve().then(()=>I9n),void 0,import.meta.url).then(e=>e.json())}}),og.of({name:"JSX",extensions:["jsx"],load(){return Da(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),og.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Da(()=>Promise.resolve().then(()=>_Vn),void 0,import.meta.url).then(e=>e.markdown())}}),og.of({name:"TSX",extensions:["tsx"],load(){return Da(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),og.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Da(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),og.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Da(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>nWn(e.shell))}})];function rWn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function sWn(e){const t=rWn(e);return m1t({override:[aWn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function aWn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const iWn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,oWn=An.mark({class:"cm-variable-highlight"}),h9e=new jwt({regexp:iWn,decoration:()=>oWn}),lWn=Co.fromClass(class{decorations;constructor(e){this.decorations=h9e.createDeco(e)}update(e){this.decorations=h9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),cWn=lWn;function uWn(){const e=pI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[he.className,he.propertyName],color:"var(--neutral6)"},{tag:he.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[he.heading1,he.heading2,he.heading3,he.heading4,he.heading5,he.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:he.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:he.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:he.link,color:"var(--accent3)",textDecoration:"underline"},{tag:he.url,color:"var(--accent3)"},{tag:he.monospace,color:"var(--neutral6)"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:he.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=It.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function dWn(){const e=It.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Wg.define([{tag:[he.comment,he.bracket],color:"var(--neutral2)"},{tag:[he.string,he.meta,he.regexp],color:"var(--accent1)"},{tag:[he.atom,he.bool,he.special(he.variableName)],color:"var(--accent6)"},{tag:[he.keyword,he.operator,he.tagName],color:"var(--accent2)"},{tag:[he.function(he.propertyName),he.propertyName],color:"var(--accent5)"},{tag:[he.definition(he.variableName),he.function(he.variableName),he.className,he.attributeName],color:"var(--accent3)"},{tag:[he.variableName,he.number],color:"var(--accent5)"},{tag:[he.name,he.quote],color:"var(--accent1)"},{tag:he.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[he.heading1,he.heading2,he.heading3,he.heading4,he.heading5,he.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[he.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[he.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:he.link,color:"var(--accent3)",textDecoration:"underline"},{tag:he.url,color:"var(--accent3)"},{tag:he.monospace,color:"var(--neutral6)"},{tag:he.strikethrough,textDecoration:"line-through"},{tag:[he.deleted],color:"var(--accent2)"},{tag:he.invalid,color:"var(--error)"},{tag:[he.standard(he.tagName)],color:"var(--accent1)"}]);return[e,eS(t)]}const s0=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?uWn():dWn(),[e])},fWn=co(X("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),pWn=nh.highest(It.editorAttributes.of({style:"outline: none"})),hWn=nh.highest(It.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),mWn=[pWn,hWn],Hr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=s0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const S=[...mWn];return f&&S.push(It.lineWrapping),a==="json"?S.push(Lp):a==="markdown"&&S.push(Bke({base:HO,codeLanguages:kkt})),i&&a==="markdown"&&S.push(cWn),c&&a==="markdown"&&S.push(sWn(c)),p===!1&&S.push(us.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:X(fWn({variant:h}),s),...m,children:[r&&o.jsx(za,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(Ku,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),gWn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},vWn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=s0(),{settings:r,setSettings:s}=yH(),a=r?.tracingOptions,i=g.useMemo(()=>gWn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(Ku,{value:l,onChange:d,theme:n,extensions:[Lp],className:X("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(le,{type:"button",onClick:f,children:"Save"})})]})},yWn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Ue,{children:o.jsx(cq,{})})})}),o.jsx(On,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Options"}),o.jsx(zs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Ir,{children:o.jsx(vWn,{onSaved:()=>t(!1)})})]})})]})};function bWn({status:e}){switch(e){case"running":return o.jsx(en,{});case"failed":return o.jsx(ws,{className:"text-accent2"});case"canceled":return o.jsx(Lf,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(mj,{className:"text-neutral3"});case"suspended":return o.jsx(rq,{className:"text-accent3"});case"success":return o.jsx(da,{className:"text-accent1"});default:return o.jsx(mj,{className:"text-neutral3"})}}function Okt({status:e}){return o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(Ue,{"aria-label":e,className:"shrink-0",children:o.jsx(bWn,{status:e})})}),o.jsx(On,{children:e})]})}var Hee,m9e;function Yke(){if(m9e)return Hee;m9e=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var p=f;p!==void 0;p=this.parent(p))if(p===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var p=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return Hee=r,Hee}var Wee,g9e;function xWn(){return g9e||(g9e=1,Wee="2.2.4"),Wee}var Zee,v9e;function wWn(){return v9e||(v9e=1,Zee={Graph:Yke(),version:xWn()}),Zee}var Gee,y9e;function SWn(){if(y9e)return Gee;y9e=1;var e=Yke();Gee={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return Gee}var Qee,b9e;function kWn(){if(b9e)return Qee;b9e=1,Qee=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return Qee}var Yee,x9e;function _kt(){if(x9e)return Yee;x9e=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return Yee=e,Yee}var Kee,w9e;function Ckt(){if(w9e)return Kee;w9e=1;var e=_kt();Kee=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return Kee}var Xee,S9e;function OWn(){if(S9e)return Xee;S9e=1;var e=Ckt();Xee=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Xee}var Jee,k9e;function Ekt(){if(k9e)return Jee;k9e=1,Jee=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return Jee}var ete,O9e;function _Wn(){if(O9e)return ete;O9e=1;var e=Ekt();ete=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return ete}var tte,_9e;function CWn(){if(_9e)return tte;_9e=1,tte=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return tte}var nte,C9e;function Tkt(){if(C9e)return nte;C9e=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return nte=e,e.CycleException=t,nte}var rte,E9e;function EWn(){if(E9e)return rte;E9e=1;var e=Tkt();rte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return rte}var ste,T9e;function jkt(){if(T9e)return ste;T9e=1,ste=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return ste}var ate,j9e;function TWn(){if(j9e)return ate;j9e=1;var e=jkt();ate=t;function t(n,r){return e(n,r,"post")}return ate}var ite,N9e;function jWn(){if(N9e)return ite;N9e=1;var e=jkt();ite=t;function t(n,r){return e(n,r,"pre")}return ite}var ote,I9e;function NWn(){if(I9e)return ote;I9e=1;var e=Yke(),t=_kt();ote=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return ote}var lte,A9e;function IWn(){return A9e||(A9e=1,lte={components:kWn(),dijkstra:Ckt(),dijkstraAll:OWn(),findCycles:_Wn(),floydWarshall:CWn(),isAcyclic:EWn(),postorder:TWn(),preorder:jWn(),prim:NWn(),tarjan:Ekt(),topsort:Tkt()}),lte}var cte,R9e;function zg(){if(R9e)return cte;R9e=1;var e=wWn();return cte={Graph:e.Graph,json:SWn(),alg:IWn(),version:e.version},cte}var ute,P9e;function AWn(){if(P9e)return ute;P9e=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return ute=e,ute}var dte,$9e;function RWn(){if($9e)return dte;$9e=1;let e=zg().Graph,t=AWn();dte=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return dte}var fte,M9e;function Ml(){if(M9e)return fte;M9e=1;let e=zg().Graph;fte={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:C,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:E};function t(T,N,I,A){for(var R=A;T.hasNode(R);)R=S(A);return I.dummy=N,T.setNode(R,I),R}function n(T){let N=new e().setGraph(T.graph());return T.nodes().forEach(I=>N.setNode(I,T.node(I))),T.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=T.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(T){let N=new e({multigraph:T.isMultigraph()}).setGraph(T.graph());return T.nodes().forEach(I=>{T.children(I).length||N.setNode(I,T.node(I))}),T.edges().forEach(I=>{N.setEdge(I,T.edge(I))}),N}function s(T){let N=T.nodes().map(I=>{let A={};return T.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function a(T){let N=T.nodes().map(I=>{let A={};return T.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function i(T,N){let I=T.x,A=T.y,R=N.x-I,L=N.y-A,D=T.width/2,F=T.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,B;return Math.abs(L)*D>Math.abs(R)*F?(L<0&&(F=-F),H=F*R/L,B=F):(R<0&&(D=-D),H=D,B=D*L/R),{x:I+H,y:A+B}}function l(T){let N=k(m(T)+1).map(()=>[]);return T.nodes().forEach(I=>{let A=T.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(T){let N=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);T.nodes().forEach(A=>{let R=T.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(T){let N=T.nodes().map(D=>T.node(D).rank),I=h(Math.min,N),A=[];T.nodes().forEach(D=>{let F=T.node(D).rank-I;A[F]||(A[F]=[]),A[F].push(D)});let R=0,L=T.graph().nodeRankFactor;Array.from(A).forEach((D,F)=>{D===void 0&&F%L!==0?--R:D!==void 0&&R&&D.forEach(H=>T.node(H).rank+=R)})}function d(T,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(T,"border",R,N)}function f(T,N=p){const I=[];for(let A=0;A<T.length;A+=N){const R=T.slice(A,A+N);I.push(R)}return I}const p=65535;function h(T,N){if(N.length>p){const I=f(N);return T.apply(null,I.map(A=>T.apply(null,A)))}else return T.apply(null,N)}function m(T){const I=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(T,N){let I={lhs:[],rhs:[]};return T.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(T,N){let I=Date.now();try{return N()}finally{console.log(T+" time: "+(Date.now()-I)+"ms")}}function b(T,N){return N()}let x=0;function S(T){var N=++x;return T+(""+N)}function k(T,N,I=1){N==null&&(N=T,T=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=T;A(L);L+=I)R.push(L);return R}function C(T,N){const I={};for(const A of N)T[A]!==void 0&&(I[A]=T[A]);return I}function _(T,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(T).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(T,N){return T.reduce((I,A,R)=>(I[A]=N[R],I),{})}return fte}var pte,D9e;function PWn(){if(D9e)return pte;D9e=1;let e=RWn(),t=Ml().uniqueId;pte={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return pte}var hte,L9e;function $Wn(){if(L9e)return hte;L9e=1;let e=Ml();hte={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return hte}var mte,F9e;function MB(){if(F9e)return mte;F9e=1;const{applyWithChunking:e}=Ml();mte={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return mte}var gte,z9e;function Nkt(){if(z9e)return gte;z9e=1;var e=zg().Graph,t=MB().slack;gte=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return gte}var vte,B9e;function MWn(){if(B9e)return vte;B9e=1;var e=Nkt(),t=MB().slack,n=MB().longestPath,r=zg().alg.preorder,s=zg().alg.postorder,a=Ml().simplify;vte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,C;k=p(S);)C=h(S,x,k),m(S,x,k,C)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(C=>c(x,S,C))}function c(x,S,k){var C=x.node(k),_=C.parent;x.edge(k,_).cutvalue=u(x,S,k)}function u(x,S,k){var C=x.node(k),_=C.parent,E=!0,T=S.edge(k,_),N=0;return T||(E=!1,T=S.edge(_,k)),N=T.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==_){var L=A===E,D=S.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var F=x.edge(k,R).cutvalue;N+=L?-F:F}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,C,_){var E=k,T=x.node(C);return S[C]=!0,x.neighbors(C).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,C))}),T.low=E,T.lim=k++,_?T.parent=_:delete T.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var C=k.v,_=k.w;S.hasEdge(C,_)||(C=k.w,_=k.v);var E=x.node(C),T=x.node(_),N=E,I=!1;E.lim>T.lim&&(N=T,I=!0);var A=S.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(S,L)<t(S,R)?L:R)}function m(x,S,k,C){var _=k.v,E=k.w;x.removeEdge(_,E),x.setEdge(C.v,C.w,{}),d(x),l(x,S),v(x,S)}function v(x,S){var k=x.nodes().find(_=>!S.node(_).parent),C=r(x,k);C=C.slice(1),C.forEach(_=>{var E=x.node(_).parent,T=S.edge(_,E),N=!1;T||(T=S.edge(E,_),N=!0),S.node(_).rank=S.node(E).rank+(N?T.minlen:-T.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return vte}var yte,U9e;function DWn(){if(U9e)return yte;U9e=1;var e=MB(),t=e.longestPath,n=Nkt(),r=MWn();yte=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return yte}var bte,V9e;function LWn(){if(V9e)return bte;V9e=1,bte=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return bte}var xte,q9e;function FWn(){if(q9e)return xte;q9e=1;let e=Ml();xte={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,C=x.borderTop?u:2*u,_=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:C,minlen:_,nestingEdge:!0}),i.setEdge(k,v,{weight:C,minlen:_,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return xte}var wte,H9e;function zWn(){if(H9e)return wte;H9e=1;let e=Ml();wte=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return wte}var Ste,W9e;function BWn(){if(W9e)return Ste;W9e=1,Ste={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return Ste}var kte,Z9e;function UWn(){if(Z9e)return kte;Z9e=1;let e=Ml();kte=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return kte}var Ote,G9e;function VWn(){if(G9e)return Ote;G9e=1;let e=Ml().zipObject;Ote=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return Ote}var _te,Q9e;function qWn(){if(Q9e)return _te;Q9e=1,_te=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return _te}var Cte,Y9e;function HWn(){if(Y9e)return Cte;Y9e=1;let e=Ml();Cte=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return Cte}var Ete,K9e;function WWn(){if(K9e)return Ete;K9e=1;let e=Ml();Ete=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return Ete}var Tte,X9e;function ZWn(){if(X9e)return Tte;X9e=1;let e=qWn(),t=HWn(),n=WWn();Tte=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(x=>x!==p&&x!==h));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return Tte}var jte,J9e;function GWn(){if(J9e)return jte;J9e=1;let e=zg().Graph,t=Ml();jte=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return jte}var Nte,e7e;function QWn(){if(e7e)return Nte;e7e=1,Nte=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return Nte}var Ite,t7e;function YWn(){if(t7e)return Ite;t7e=1;let e=UWn(),t=VWn(),n=ZWn(),r=GWn(),s=QWn(),a=zg().Graph,i=Ml();Ite=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:v,S%4>=2),y=i.buildLayerMatrix(f);let C=t(f,y);C<b&&(k=0,x=Object.assign({},y),b=C)}d(f,x)}function c(f,p,h){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return Ite}var Ate,n7e;function KWn(){if(n7e)return Ate;n7e=1;let e=zg().Graph,t=Ml();Ate={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let x={};function S(k,C){let _=0,E=0,T=k.length,N=C[C.length-1];return C.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:T;(R||I===N)&&(C.slice(E,A+1).forEach(D=>{y.predecessors(D).forEach(F=>{let H=y.node(F),B=H.order;(B<_||L<B)&&!(H.dummy&&y.node(D).dummy)&&a(x,F,D)})}),E=A+1,_=L)}),C}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(C,_,E,T,N){let I;t.range(_,E).forEach(A=>{I=C[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<T||L.order>N)&&a(x,R,I)})})}function k(C,_){let E=-1,T,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(T=y.node(R[0]).order,S(_,N,A,E,T),N=A,E=T)}S(_,N,_.length,T,C.length)}),_}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},C={},_={};return b.forEach(E=>{E.forEach((T,N)=>{k[T]=T,C[T]=T,_[T]=N})}),b.forEach(E=>{let T=-1;E.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>_[R]-_[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];C[N]===N&&T<_[D]&&!i(x,N,D)&&(C[D]=N,C[N]=k[N]=k[D],T=_[D])}}})}),{root:k,align:C}}function c(y,b,x,S,k){let C={},_=u(y,b,x,k),E=k?"borderLeft":"borderRight";function T(A,R){let L=_.nodes(),D=L.pop(),F={};for(;D;)F[D]?A(D):(F[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){C[A]=_.inEdges(A).reduce((R,L)=>Math.max(R,C[L.v]+_.edge(L)),0)}function I(A){let R=_.outEdges(A).reduce((D,F)=>Math.min(D,C[F.w]-_.edge(F)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(C[A]=Math.max(C[A],R))}return T(N,_.predecessors.bind(_)),T(I,_.successors.bind(_)),Object.keys(S).forEach(A=>C[A]=C[x[A]]),C}function u(y,b,x,S){let k=new e,C=y.graph(),_=m(C.nodesep,C.edgesep,S);return b.forEach(E=>{let T;E.forEach(N=>{let I=x[N];if(k.setNode(I),T){var A=x[T],R=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,T),R||0))}T=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,C=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([E,T])=>{let N=v(y,E)/2;k=Math.max(T+N,k),C=Math.min(T-N,C)});const _=k-C;return _<x[0]&&(x=[_,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(C=>{["l","r"].forEach(_=>{let E=C+_,T=y[E];if(T===b)return;let N=Object.values(T),I=S-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(T,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(C=>C[S]).sort((C,_)=>C-_);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(_=>{k=_==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let T=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,T),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),S[_+E]=I})});let C=d(y,S);return f(S,C),p(S,y.graph().align)}function m(y,b,x){return(S,k,C)=>{let _=S.node(k),E=S.node(C),T=0,N;if(T+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(T+=x?N:-N),N=0,T+=(_.dummy?b:y)/2,T+=(E.dummy?b:y)/2,T+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(T+=x?N:-N),N=0,T}}function v(y,b){return y.node(b).width}return Ate}var Rte,r7e;function XWn(){if(r7e)return Rte;r7e=1;let e=Ml(),t=KWn().positionX;Rte=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Rte}var Pte,s7e;function JWn(){if(s7e)return Pte;s7e=1;let e=PWn(),t=$Wn(),n=DWn(),r=Ml().normalizeRanks,s=LWn(),a=Ml().removeEmptyRanks,i=FWn(),l=zWn(),c=BWn(),u=YWn(),d=XWn(),f=Ml(),p=zg().Graph;Pte=h;function h($,z){let Z=z&&z.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>T($));Z(" runLayout",()=>m(K,Z,z)),Z(" updateInputGraph",()=>v($,K))})}function m($,z,Z){z(" makeSpaceForEdgeLabels",()=>N($)),z(" removeSelfEdges",()=>U($)),z(" acyclic",()=>e.run($)),z(" nestingGraph.run",()=>i.run($)),z(" rank",()=>n(f.asNonCompoundGraph($))),z(" injectEdgeLabelProxies",()=>I($)),z(" removeEmptyRanks",()=>a($)),z(" nestingGraph.cleanup",()=>i.cleanup($)),z(" normalizeRanks",()=>r($)),z(" assignRankMinMax",()=>A($)),z(" removeEdgeLabelProxies",()=>R($)),z(" normalize.run",()=>t.run($)),z(" parentDummyChains",()=>s($)),z(" addBorderSegments",()=>l($)),z(" order",()=>u($,Z)),z(" insertSelfEdges",()=>V($)),z(" adjustCoordinateSystem",()=>c.adjust($)),z(" position",()=>d($)),z(" positionSelfEdges",()=>M($)),z(" removeBorderNodes",()=>B($)),z(" normalize.undo",()=>t.undo($)),z(" fixupEdgeLabelCoords",()=>F($)),z(" undoCoordinateSystem",()=>c.undo($)),z(" translateGraph",()=>L($)),z(" assignNodeIntersects",()=>D($)),z(" reversePoints",()=>H($)),z(" acyclic.undo",()=>e.undo($))}function v($,z){$.nodes().forEach(Z=>{let K=$.node(Z),re=z.node(Z);K&&(K.x=re.x,K.y=re.y,K.rank=re.rank,z.children(Z).length&&(K.width=re.width,K.height=re.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),re=z.edge(Z);K.points=re.points,Object.hasOwn(re,"x")&&(K.x=re.x,K.y=re.y)}),$.graph().width=z.graph().width,$.graph().height=z.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],S=["width","height","rank"],k={width:0,height:0},C=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function T($){let z=new p({multigraph:!0,compound:!0}),Z=q($.graph());return z.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(K=>{let re=q($.node(K));const ee=G(re,S);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),z.setNode(K,ee),z.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let re=q($.edge(K));z.setEdge(K,Object.assign({},_,G(re,C),f.pick(re,E)))}),z}function N($){let z=$.graph();z.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(z.rankdir==="TB"||z.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(z=>{let Z=$.edge(z);if(Z.width&&Z.height){let K=$.node(z.v),ee={rank:($.node(z.w).rank-K.rank)/2+K.rank,e:z};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let z=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,z=Math.max(z,K.maxRank))}),$.graph().maxRank=z}function R($){$.nodes().forEach(z=>{let Z=$.node(z);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(z))})}function L($){let z=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,re=0,ee=$.graph(),J=ee.marginx||0,ae=ee.marginy||0;function fe(Y){let te=Y.x,ue=Y.y,de=Y.width,ce=Y.height;z=Math.min(z,te-de/2),Z=Math.max(Z,te+de/2),K=Math.min(K,ue-ce/2),re=Math.max(re,ue+ce/2)}$.nodes().forEach(Y=>fe($.node(Y))),$.edges().forEach(Y=>{let te=$.edge(Y);Object.hasOwn(te,"x")&&fe(te)}),z-=J,K-=ae,$.nodes().forEach(Y=>{let te=$.node(Y);te.x-=z,te.y-=K}),$.edges().forEach(Y=>{let te=$.edge(Y);te.points.forEach(ue=>{ue.x-=z,ue.y-=K}),Object.hasOwn(te,"x")&&(te.x-=z),Object.hasOwn(te,"y")&&(te.y-=K)}),ee.width=Z-z+J,ee.height=re-K+ae}function D($){$.edges().forEach(z=>{let Z=$.edge(z),K=$.node(z.v),re=$.node(z.w),ee,J;Z.points?(ee=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],ee=re,J=K),Z.points.unshift(f.intersectRect(K,ee)),Z.points.push(f.intersectRect(re,J))})}function F($){$.edges().forEach(z=>{let Z=$.edge(z);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(z=>{let Z=$.edge(z);Z.reversed&&Z.points.reverse()})}function B($){$.nodes().forEach(z=>{if($.children(z).length){let Z=$.node(z),K=$.node(Z.borderTop),re=$.node(Z.borderBottom),ee=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-ee.x),Z.height=Math.abs(re.y-K.y),Z.x=ee.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(z=>{$.node(z).dummy==="border"&&$.removeNode(z)})}function U($){$.edges().forEach(z=>{if(z.v===z.w){var Z=$.node(z.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:z,label:$.edge(z)}),$.removeEdge(z)}})}function V($){var z=f.buildLayerMatrix($);z.forEach(Z=>{var K=0;Z.forEach((re,ee)=>{var J=$.node(re);J.order=ee+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:ee+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function M($){$.nodes().forEach(z=>{var Z=$.node(z);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),re=K.x+K.width/2,ee=K.y,J=Z.x-re,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(z),Z.label.points=[{x:re+2*J/3,y:ee-ae},{x:re+5*J/6,y:ee-ae},{x:re+J,y:ee},{x:re+5*J/6,y:ee+ae},{x:re+2*J/3,y:ee+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,z){return f.mapValues(f.pick($,z),Number)}function q($){var z={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),z[Z]=K}),z}return Pte}var $te,a7e;function eZn(){if(a7e)return $te;a7e=1;let e=Ml(),t=zg().Graph;$te={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return $te}var Mte,i7e;function tZn(){return i7e||(i7e=1,Mte="1.1.8"),Mte}var Dte,o7e;function nZn(){return o7e||(o7e=1,Dte={graphlib:zg(),layout:JWn(),debug:eZn(),util:{time:Ml().time,notime:Ml().notime},version:tZn()}),Dte}var rZn=nZn();const l7e=Bl(rZn);function Hl(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Hl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var sZn={value:()=>{}};function HH(){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 I8(n)}function I8(e){this._=e}function aZn(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}})}I8.prototype=HH.prototype={constructor:I8,on:function(e,t){var n=this._,r=aZn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=iZn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=c7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=c7e(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 I8(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function iZn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function c7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=sZn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Hge="http://www.w3.org/1999/xhtml";const u7e={svg:"http://www.w3.org/2000/svg",xhtml:Hge,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function WH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),u7e.hasOwnProperty(t)?{space:u7e[t],local:e}:e}function oZn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Hge&&t.documentElement.namespaceURI===Hge?t.createElement(e):t.createElementNS(n,e)}}function lZn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Ikt(e){var t=WH(e);return(t.local?lZn:oZn)(t)}function cZn(){}function Kke(e){return e==null?cZn:function(){return this.querySelector(e)}}function uZn(e){typeof e!="function"&&(e=Kke(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Kp(r,this._parents)}function dZn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function fZn(){return[]}function Akt(e){return e==null?fZn:function(){return this.querySelectorAll(e)}}function pZn(e){return function(){return dZn(e.apply(this,arguments))}}function hZn(e){typeof e=="function"?e=pZn(e):e=Akt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new Kp(r,s)}function Rkt(e){return function(){return this.matches(e)}}function Pkt(e){return function(t){return t.matches(e)}}var mZn=Array.prototype.find;function gZn(e){return function(){return mZn.call(this.children,e)}}function vZn(){return this.firstElementChild}function yZn(e){return this.select(e==null?vZn:gZn(typeof e=="function"?e:Pkt(e)))}var bZn=Array.prototype.filter;function xZn(){return Array.from(this.children)}function wZn(e){return function(){return bZn.call(this.children,e)}}function SZn(e){return this.selectAll(e==null?xZn:wZn(typeof e=="function"?e:Pkt(e)))}function kZn(e){typeof e!="function"&&(e=Rkt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Kp(r,this._parents)}function $kt(e){return new Array(e.length)}function OZn(){return new Kp(this._enter||this._groups.map($kt),this._parents)}function DB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}DB.prototype={constructor:DB,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 _Zn(e){return function(){return e}}function CZn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new DB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function EZn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new DB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function TZn(e){return e.__data__}function jZn(e,t){if(!arguments.length)return Array.from(this,TZn);var n=t?EZn:CZn,r=this._parents,s=this._groups;typeof e!="function"&&(e=_Zn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],p=f.length,h=NZn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var x=0,S=0,k,C;x<m;++x)if(k=v[x]){for(x>=S&&(S=x+1);!(C=y[S])&&++S<m;);k._next=C||null}}return i=new Kp(i,r),i._enter=l,i._exit=c,i}function NZn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function IZn(){return new Kp(this._exit||this._groups.map($kt),this._parents)}function AZn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function RZn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Kp(l,this._parents)}function PZn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function $Zn(e){e||(e=MZn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Kp(s,this._parents).order()}function MZn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function DZn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function LZn(){return Array.from(this)}function FZn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function zZn(){let e=0;for(const t of this)++e;return e}function BZn(){return!this.node()}function UZn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function VZn(e){return function(){this.removeAttribute(e)}}function qZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function HZn(e,t){return function(){this.setAttribute(e,t)}}function WZn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function ZZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function GZn(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 QZn(e,t){var n=WH(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?qZn:VZn:typeof t=="function"?n.local?GZn:ZZn:n.local?WZn:HZn)(n,t))}function Mkt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function YZn(e){return function(){this.style.removeProperty(e)}}function KZn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function XZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function JZn(e,t,n){return arguments.length>1?this.each((t==null?YZn:typeof t=="function"?XZn:KZn)(e,t,n??"")):qj(this.node(),e)}function qj(e,t){return e.style.getPropertyValue(t)||Mkt(e).getComputedStyle(e,null).getPropertyValue(t)}function eGn(e){return function(){delete this[e]}}function tGn(e,t){return function(){this[e]=t}}function nGn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function rGn(e,t){return arguments.length>1?this.each((t==null?eGn:typeof t=="function"?nGn:tGn)(e,t)):this.node()[e]}function Dkt(e){return e.trim().split(/^|\s+/)}function Xke(e){return e.classList||new Lkt(e)}function Lkt(e){this._node=e,this._names=Dkt(e.getAttribute("class")||"")}Lkt.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 Fkt(e,t){for(var n=Xke(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function zkt(e,t){for(var n=Xke(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function sGn(e){return function(){Fkt(this,e)}}function aGn(e){return function(){zkt(this,e)}}function iGn(e,t){return function(){(t.apply(this,arguments)?Fkt:zkt)(this,e)}}function oGn(e,t){var n=Dkt(e+"");if(arguments.length<2){for(var r=Xke(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?iGn:t?sGn:aGn)(n,t))}function lGn(){this.textContent=""}function cGn(e){return function(){this.textContent=e}}function uGn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function dGn(e){return arguments.length?this.each(e==null?lGn:(typeof e=="function"?uGn:cGn)(e)):this.node().textContent}function fGn(){this.innerHTML=""}function pGn(e){return function(){this.innerHTML=e}}function hGn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function mGn(e){return arguments.length?this.each(e==null?fGn:(typeof e=="function"?hGn:pGn)(e)):this.node().innerHTML}function gGn(){this.nextSibling&&this.parentNode.appendChild(this)}function vGn(){return this.each(gGn)}function yGn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function bGn(){return this.each(yGn)}function xGn(e){var t=typeof e=="function"?e:Ikt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function wGn(){return null}function SGn(e,t){var n=typeof e=="function"?e:Ikt(e),r=t==null?wGn:typeof t=="function"?t:Kke(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function kGn(){var e=this.parentNode;e&&e.removeChild(this)}function OGn(){return this.each(kGn)}function _Gn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function CGn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function EGn(e){return this.select(e?CGn:_Gn)}function TGn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function jGn(e){return function(t){e.call(this,t,this.__data__)}}function NGn(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 IGn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function AGn(e,t,n){return function(){var r=this.__on,s,a=jGn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function RGn(e,t,n){var r=NGn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?AGn:IGn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function Bkt(e,t,n){var r=Mkt(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 PGn(e,t){return function(){return Bkt(this,e,t)}}function $Gn(e,t){return function(){return Bkt(this,e,t.apply(this,arguments))}}function MGn(e,t){return this.each((typeof t=="function"?$Gn:PGn)(e,t))}function*DGn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var Ukt=[null];function Kp(e,t){this._groups=e,this._parents=t}function M3(){return new Kp([[document.documentElement]],Ukt)}function LGn(){return this}Kp.prototype=M3.prototype={constructor:Kp,select:uZn,selectAll:hZn,selectChild:yZn,selectChildren:SZn,filter:kZn,data:jZn,enter:OZn,exit:IZn,join:AZn,merge:RZn,selection:LGn,order:PZn,sort:$Zn,call:DZn,nodes:LZn,node:FZn,size:zZn,empty:BZn,each:UZn,attr:QZn,style:JZn,property:rGn,classed:oGn,text:dGn,html:mGn,raise:vGn,lower:bGn,append:xGn,insert:SGn,remove:OGn,clone:EGn,datum:TGn,on:RGn,dispatch:MGn,[Symbol.iterator]:DGn};function Tp(e){return typeof e=="string"?new Kp([[document.querySelector(e)]],[document.documentElement]):new Kp([[e]],Ukt)}function FGn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function lg(e,t){if(e=FGn(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 zGn={passive:!1},kM={capture:!0,passive:!1};function Lte(e){e.stopImmediatePropagation()}function QT(e){e.preventDefault(),e.stopImmediatePropagation()}function Vkt(e){var t=e.document.documentElement,n=Tp(e).on("dragstart.drag",QT,kM);"onselectstart"in t?n.on("selectstart.drag",QT,kM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function qkt(e,t){var n=e.document.documentElement,r=Tp(e).on("dragstart.drag",null);t&&(r.on("click.drag",QT,kM),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 J6=e=>()=>e;function Wge(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Wge.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function BGn(e){return!e.ctrlKey&&!e.button}function UGn(){return this.parentNode}function VGn(e,t){return t??{x:e.x,y:e.y}}function qGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function Hkt(){var e=BGn,t=UGn,n=VGn,r=qGn,s={},a=HH("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,zGn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,C){if(!(d||!e.call(this,k,C))){var _=S(this,t.call(this,k,C),k,C,"mouse");_&&(Tp(k.view).on("mousemove.drag",m,kM).on("mouseup.drag",v,kM),Vkt(k.view),Lte(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(QT(k),!u){var C=k.clientX-l,_=k.clientY-c;u=C*C+_*_>f}s.mouse("drag",k)}function v(k){Tp(k.view).on("mousemove.drag mouseup.drag",null),qkt(k.view,u),QT(k),s.mouse("end",k)}function y(k,C){if(e.call(this,k,C)){var _=k.changedTouches,E=t.call(this,k,C),T=_.length,N,I;for(N=0;N<T;++N)(I=S(this,E,k,C,_[N].identifier,_[N]))&&(Lte(k),I("start",k,_[N]))}}function b(k){var C=k.changedTouches,_=C.length,E,T;for(E=0;E<_;++E)(T=s[C[E].identifier])&&(QT(k),T("drag",k,C[E]))}function x(k){var C=k.changedTouches,_=C.length,E,T;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<_;++E)(T=s[C[E].identifier])&&(Lte(k),T("end",k,C[E]))}function S(k,C,_,E,T,N){var I=a.copy(),A=lg(N||_,C),R,L,D;if((D=n.call(k,new Wge("beforestart",{sourceEvent:_,target:p,identifier:T,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function F(H,B,U){var V=A,M;switch(H){case"start":s[T]=F,M=i++;break;case"end":delete s[T],--i;case"drag":A=lg(U||B,C),M=i;break}I.call(H,k,new Wge(H,{sourceEvent:B,subject:D,target:p,identifier:T,active:M,x:A[0]+R,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),E)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:J6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:J6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:J6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:J6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function Jke(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Wkt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function D3(){}var OM=.7,LB=1/OM,YT="\\s*([+-]?\\d+)\\s*",_M="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",iy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",HGn=/^#([0-9a-f]{3,8})$/,WGn=new RegExp(`^rgb\\(${YT},${YT},${YT}\\)$`),ZGn=new RegExp(`^rgb\\(${iy},${iy},${iy}\\)$`),GGn=new RegExp(`^rgba\\(${YT},${YT},${YT},${_M}\\)$`),QGn=new RegExp(`^rgba\\(${iy},${iy},${iy},${_M}\\)$`),YGn=new RegExp(`^hsl\\(${_M},${iy},${iy}\\)$`),KGn=new RegExp(`^hsla\\(${_M},${iy},${iy},${_M}\\)$`),d7e={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};Jke(D3,ZO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:f7e,formatHex:f7e,formatHex8:XGn,formatHsl:JGn,formatRgb:p7e,toString:p7e});function f7e(){return this.rgb().formatHex()}function XGn(){return this.rgb().formatHex8()}function JGn(){return Zkt(this).formatHsl()}function p7e(){return this.rgb().formatRgb()}function ZO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=HGn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?h7e(t):n===3?new wf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?eF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?eF(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=WGn.exec(e))?new wf(t[1],t[2],t[3],1):(t=ZGn.exec(e))?new wf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=GGn.exec(e))?eF(t[1],t[2],t[3],t[4]):(t=QGn.exec(e))?eF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=YGn.exec(e))?v7e(t[1],t[2]/100,t[3]/100,1):(t=KGn.exec(e))?v7e(t[1],t[2]/100,t[3]/100,t[4]):d7e.hasOwnProperty(e)?h7e(d7e[e]):e==="transparent"?new wf(NaN,NaN,NaN,0):null}function h7e(e){return new wf(e>>16&255,e>>8&255,e&255,1)}function eF(e,t,n,r){return r<=0&&(e=t=n=NaN),new wf(e,t,n,r)}function eQn(e){return e instanceof D3||(e=ZO(e)),e?(e=e.rgb(),new wf(e.r,e.g,e.b,e.opacity)):new wf}function Zge(e,t,n,r){return arguments.length===1?eQn(e):new wf(e,t,n,r??1)}function wf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Jke(wf,Zge,Wkt(D3,{brighter(e){return e=e==null?LB:Math.pow(LB,e),new wf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?OM:Math.pow(OM,e),new wf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new wf(rO(this.r),rO(this.g),rO(this.b),FB(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:m7e,formatHex:m7e,formatHex8:tQn,formatRgb:g7e,toString:g7e}));function m7e(){return`#${Fk(this.r)}${Fk(this.g)}${Fk(this.b)}`}function tQn(){return`#${Fk(this.r)}${Fk(this.g)}${Fk(this.b)}${Fk((isNaN(this.opacity)?1:this.opacity)*255)}`}function g7e(){const e=FB(this.opacity);return`${e===1?"rgb(":"rgba("}${rO(this.r)}, ${rO(this.g)}, ${rO(this.b)}${e===1?")":`, ${e})`}`}function FB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function rO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Fk(e){return e=rO(e),(e<16?"0":"")+e.toString(16)}function v7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new mg(e,t,n,r)}function Zkt(e){if(e instanceof mg)return new mg(e.h,e.s,e.l,e.opacity);if(e instanceof D3||(e=ZO(e)),!e)return new mg;if(e instanceof mg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new mg(i,l,c,e.opacity)}function nQn(e,t,n,r){return arguments.length===1?Zkt(e):new mg(e,t,n,r??1)}function mg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Jke(mg,nQn,Wkt(D3,{brighter(e){return e=e==null?LB:Math.pow(LB,e),new mg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?OM:Math.pow(OM,e),new mg(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 wf(Fte(e>=240?e-240:e+120,s,r),Fte(e,s,r),Fte(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new mg(y7e(this.h),tF(this.s),tF(this.l),FB(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=FB(this.opacity);return`${e===1?"hsl(":"hsla("}${y7e(this.h)}, ${tF(this.s)*100}%, ${tF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function y7e(e){return e=(e||0)%360,e<0?e+360:e}function tF(e){return Math.max(0,Math.min(1,e||0))}function Fte(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 eOe=e=>()=>e;function rQn(e,t){return function(n){return e+n*t}}function sQn(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 aQn(e){return(e=+e)==1?Gkt:function(t,n){return n-t?sQn(t,n,e):eOe(isNaN(t)?n:t)}}function Gkt(e,t){var n=t-e;return n?rQn(e,n):eOe(isNaN(e)?t:e)}const zB=(function e(t){var n=aQn(t);function r(s,a){var i=n((s=Zge(s)).r,(a=Zge(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=Gkt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function iQn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function oQn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function lQn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=hx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function cQn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ug(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function uQn(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(a){for(s in n)r[s]=n[s](a);return r}}var Gge=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,zte=new RegExp(Gge.source,"g");function dQn(e){return function(){return e}}function fQn(e){return function(t){return e(t)+""}}function Qkt(e,t){var n=Gge.lastIndex=zte.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Gge.exec(e))&&(s=zte.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:ug(r,s)})),n=zte.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?fQn(c[0].x):dQn(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"?eOe(t):(n==="number"?ug:n==="string"?(r=ZO(t))?(t=r,zB):Qkt:t instanceof ZO?zB:t instanceof Date?cQn:oQn(t)?iQn:Array.isArray(t)?lQn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?uQn:ug)(e,t)}function tOe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var b7e=180/Math.PI,Qge={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Ykt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*b7e,skewX:Math.atan(c)*b7e,scaleX:i,scaleY:l}}var nF;function pQn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Qge:Ykt(t.a,t.b,t.c,t.d,t.e,t.f)}function hQn(e){return e==null||(nF||(nF=document.createElementNS("http://www.w3.org/2000/svg","g")),nF.setAttribute("transform",e),!(e=nF.transform.baseVal.consolidate()))?Qge:(e=e.matrix,Ykt(e.a,e.b,e.c,e.d,e.e,e.f))}function Kkt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:ug(u,f)},{i:v-2,x:ug(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:ug(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:ug(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:ug(u,f)},{i:v-2,x:ug(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var mQn=Kkt(pQn,"px, ","px)","deg)"),gQn=Kkt(hQn,", ",")",")"),vQn=1e-12;function x7e(e){return((e=Math.exp(e))+1/e)/2}function yQn(e){return((e=Math.exp(e))-1/e)/2}function bQn(e){return((e=Math.exp(2*e))-1)/(e+1)}const A8=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<vQn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var x=Math.sqrt(v),S=(p*p-u*u+r*v)/(2*u*n*x),k=(p*p-u*u-r*v)/(2*p*n*x),C=Math.log(Math.sqrt(S*S+1)-S),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-C)/t,y=function(E){var T=E*b,N=x7e(C),I=u/(n*x)*(N*bQn(t*T+C)-yQn(C));return[l+I*h,c+I*m,u*N/x7e(t*T+C)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function xQn(e,t){t===void 0&&(t=e,e=hx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var Hj=0,BP=0,OR=0,Xkt=1e3,BB,UP,UB=0,GO=0,ZH=0,CM=typeof performance=="object"&&performance.now?performance:Date,Jkt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function nOe(){return GO||(Jkt(wQn),GO=CM.now()+ZH)}function wQn(){GO=0}function VB(){this._call=this._time=this._next=null}VB.prototype=eOt.prototype={constructor:VB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?nOe():+n)+(t==null?0:+t),!this._next&&UP!==this&&(UP?UP._next=this:BB=this,UP=this),this._call=e,this._time=n,Yge()},stop:function(){this._call&&(this._call=null,this._time=1/0,Yge())}};function eOt(e,t,n){var r=new VB;return r.restart(e,t,n),r}function SQn(){nOe(),++Hj;for(var e=BB,t;e;)(t=GO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Hj}function w7e(){GO=(UB=CM.now())+ZH,Hj=BP=0;try{SQn()}finally{Hj=0,OQn(),GO=0}}function kQn(){var e=CM.now(),t=e-UB;t>Xkt&&(ZH-=t,UB=e)}function OQn(){for(var e,t=BB,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:BB=n);UP=e,Yge(r)}function Yge(e){if(!Hj){BP&&(BP=clearTimeout(BP));var t=e-GO;t>24?(e<1/0&&(BP=setTimeout(w7e,e-CM.now()-ZH)),OR&&(OR=clearInterval(OR))):(OR||(UB=CM.now(),OR=setInterval(kQn,Xkt)),Hj=1,Jkt(w7e))}}function S7e(e,t,n){var r=new VB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var _Qn=HH("start","end","cancel","interrupt"),CQn=[],tOt=0,k7e=1,Kge=2,R8=3,O7e=4,Xge=5,P8=6;function GH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;EQn(e,n,{name:t,index:r,group:s,on:_Qn,tween:CQn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:tOt})}function rOe(e,t){var n=Qg(e,t);if(n.state>tOt)throw new Error("too late; already scheduled");return n}function Uy(e,t){var n=Qg(e,t);if(n.state>R8)throw new Error("too late; already running");return n}function Qg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function EQn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=eOt(a,0,n.time);function a(u){n.state=k7e,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!==k7e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===R8)return S7e(i);h.state===O7e?(h.state=P8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=P8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(S7e(function(){n.state===R8&&(n.state=O7e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Kge,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Kge){for(n.state=R8,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=Xge,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===Xge&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=P8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function $8(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Kge&&r.state<Xge,r.state=P8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function TQn(e){return this.each(function(){$8(this,e)})}function jQn(e,t){var n,r;return function(){var s=Uy(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function NQn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Uy(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function IQn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Qg(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?jQn:NQn)(n,e,t))}function sOe(e,t,n){var r=e._id;return e.each(function(){var s=Uy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Qg(s,r).value[t]}}function nOt(e,t){var n;return(typeof t=="number"?ug:t instanceof ZO?zB:(n=ZO(t))?(t=n,zB):Qkt)(e,t)}function AQn(e){return function(){this.removeAttribute(e)}}function RQn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function PQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function $Qn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function MQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function DQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function LQn(e,t){var n=WH(e),r=n==="transform"?gQn:nOt;return this.attrTween(e,typeof t=="function"?(n.local?DQn:MQn)(n,r,sOe(this,"attr."+e,t)):t==null?(n.local?RQn:AQn)(n):(n.local?$Qn:PQn)(n,r,t))}function FQn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function zQn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function BQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&zQn(e,a)),n}return s._value=t,s}function UQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&FQn(e,a)),n}return s._value=t,s}function VQn(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=WH(e);return this.tween(n,(r.local?BQn:UQn)(r,t))}function qQn(e,t){return function(){rOe(this,e).delay=+t.apply(this,arguments)}}function HQn(e,t){return t=+t,function(){rOe(this,e).delay=t}}function WQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?qQn:HQn)(t,e)):Qg(this.node(),t).delay}function ZQn(e,t){return function(){Uy(this,e).duration=+t.apply(this,arguments)}}function GQn(e,t){return t=+t,function(){Uy(this,e).duration=t}}function QQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?ZQn:GQn)(t,e)):Qg(this.node(),t).duration}function YQn(e,t){if(typeof t!="function")throw new Error;return function(){Uy(this,e).ease=t}}function KQn(e){var t=this._id;return arguments.length?this.each(YQn(t,e)):Qg(this.node(),t).ease}function XQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Uy(this,e).ease=n}}function JQn(e){if(typeof e!="function")throw new Error;return this.each(XQn(this._id,e))}function eYn(e){typeof e!="function"&&(e=Rkt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new $x(r,this._parents,this._name,this._id)}function tYn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new $x(i,this._parents,this._name,this._id)}function nYn(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 rYn(e,t,n){var r,s,a=nYn(t)?rOe:Uy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function sYn(e,t){var n=this._id;return arguments.length<2?Qg(this.node(),n).on.on(e):this.each(rYn(n,e,t))}function aYn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function iYn(){return this.on("end.remove",aYn(this._id))}function oYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Kke(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,GH(u[p],t,n,p,u,Qg(d,n)));return new $x(a,this._parents,t,n)}function lYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Akt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=Qg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&GH(h,t,n,v,p,m);a.push(p),i.push(d)}return new $x(a,i,t,n)}var cYn=M3.prototype.constructor;function uYn(){return new cYn(this._groups,this._parents)}function dYn(e,t){var n,r,s;return function(){var a=qj(this,e),i=(this.style.removeProperty(e),qj(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function rOt(e){return function(){this.style.removeProperty(e)}}function fYn(e,t,n){var r,s=n+"",a;return function(){var i=qj(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function pYn(e,t,n){var r,s,a;return function(){var i=qj(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),qj(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function hYn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Uy(this,e),u=c.on,d=c.value[a]==null?l||(l=rOt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function mYn(e,t,n){var r=(e+="")=="transform"?mQn:nOt;return t==null?this.styleTween(e,dYn(e,r)).on("end.style."+e,rOt(e)):typeof t=="function"?this.styleTween(e,pYn(e,r,sOe(this,"style."+e,t))).each(hYn(this._id,e)):this.styleTween(e,fYn(e,r,t),n).on("end.style."+e,null)}function gYn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function vYn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&gYn(e,i,n)),r}return a._value=t,a}function yYn(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,vYn(e,t,n??""))}function bYn(e){return function(){this.textContent=e}}function xYn(e){return function(){var t=e(this);this.textContent=t??""}}function wYn(e){return this.tween("text",typeof e=="function"?xYn(sOe(this,"text",e)):bYn(e==null?"":e+""))}function SYn(e){return function(t){this.textContent=e.call(this,t)}}function kYn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&SYn(s)),t}return r._value=e,r}function OYn(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,kYn(e))}function _Yn(){for(var e=this._name,t=this._id,n=sOt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=Qg(c,t);GH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new $x(r,this._parents,e,n)}function CYn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=Uy(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var EYn=0;function $x(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function sOt(){return++EYn}var wb=M3.prototype;$x.prototype={constructor:$x,select:oYn,selectAll:lYn,selectChild:wb.selectChild,selectChildren:wb.selectChildren,filter:eYn,merge:tYn,selection:uYn,transition:_Yn,call:wb.call,nodes:wb.nodes,node:wb.node,size:wb.size,empty:wb.empty,each:wb.each,on:sYn,attr:LQn,attrTween:VQn,style:mYn,styleTween:yYn,text:wYn,textTween:OYn,remove:iYn,tween:IQn,delay:WQn,duration:QQn,ease:KQn,easeVarying:JQn,end:CYn,[Symbol.iterator]:wb[Symbol.iterator]};function TYn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var jYn={time:null,delay:0,duration:250,ease:TYn};function NYn(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 IYn(e){var t,n;e instanceof $x?(t=e._id,e=e._name):(t=sOt(),(n=jYn).time=nOe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&GH(c,e,t,u,i,n||NYn(c,t));return new $x(r,this._parents,e,t)}M3.prototype.interrupt=TQn;M3.prototype.transition=IYn;const rF=e=>()=>e;function AYn(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 nx(e,t,n){this.k=e,this.x=t,this.y=n}nx.prototype={constructor:nx,scale:function(e){return e===1?this:new nx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new nx(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 QH=new nx(1,0,0);aOt.prototype=nx.prototype;function aOt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return QH;return e.__zoom}function Bte(e){e.stopImmediatePropagation()}function _R(e){e.preventDefault(),e.stopImmediatePropagation()}function RYn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function PYn(){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 _7e(){return this.__zoom||QH}function $Yn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function MYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function DYn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function iOt(){var e=RYn,t=PYn,n=DYn,r=$Yn,s=MYn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=A8,u=HH("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(D){D.property("__zoom",_7e).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,F,H,B){var U=D.selection?D.selection():D;U.property("__zoom",_7e),D!==U?C(D,F,H,B):U.interrupt().each(function(){_(this,arguments).event(B).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},b.scaleBy=function(D,F,H,B){b.scaleTo(D,function(){var U=this.__zoom.k,V=typeof F=="function"?F.apply(this,arguments):F;return U*V},H,B)},b.scaleTo=function(D,F,H,B){b.transform(D,function(){var U=t.apply(this,arguments),V=this.__zoom,M=H==null?k(U):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),q=typeof F=="function"?F.apply(this,arguments):F;return n(S(x(V,q),M,G),U,i)},H,B)},b.translateBy=function(D,F,H,B){b.transform(D,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,B)},b.translateTo=function(D,F,H,B,U){b.transform(D,function(){var V=t.apply(this,arguments),M=this.__zoom,G=B==null?k(V):typeof B=="function"?B.apply(this,arguments):B;return n(QH.translate(G[0],G[1]).scale(M.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},B,U)};function x(D,F){return F=Math.max(a[0],Math.min(a[1],F)),F===D.k?D:new nx(F,D.x,D.y)}function S(D,F,H){var B=F[0]-H[0]*D.k,U=F[1]-H[1]*D.k;return B===D.x&&U===D.y?D:new nx(D.k,B,U)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function C(D,F,H,B){D.on("start.zoom",function(){_(this,arguments).event(B).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(B).end()}).tween("zoom",function(){var U=this,V=arguments,M=_(U,V).event(B),G=t.apply(U,V),q=H==null?k(G):typeof H=="function"?H.apply(U,V):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),z=U.__zoom,Z=typeof F=="function"?F.apply(U,V):F,K=c(z.invert(q).concat($/z.k),Z.invert(q).concat($/Z.k));return function(re){if(re===1)re=Z;else{var ee=K(re),J=$/ee[2];re=new nx(J,q[0]-ee[0]*J,q[1]-ee[1]*J)}M.zoom(null,re)}})}function _(D,F,H){return!H&&D.__zooming||new E(D,F)}function E(D,F){this.that=D,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,F),this.taps=0}E.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,F){return this.mouse&&D!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var F=Tp(this.that).datum();u.call(D,this.that,new AYn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),F)}};function T(D,...F){if(!e.apply(this,arguments))return;var H=_(this,F).event(D),B=this.__zoom,U=Math.max(a[0],Math.min(a[1],B.k*Math.pow(2,r.apply(this,arguments)))),V=lg(D);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=B.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(B.k===U)return;H.mouse=[V,B.invert(V)],$8(this),H.start()}_R(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(B,U),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...F){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,B=_(this,F,!0).event(D),U=Tp(D.view).on("mousemove.zoom",q,!0).on("mouseup.zoom",$,!0),V=lg(D,H),M=D.clientX,G=D.clientY;Vkt(D.view),Bte(D),B.mouse=[V,this.__zoom.invert(V)],$8(this),B.start();function q(z){if(_R(z),!B.moved){var Z=z.clientX-M,K=z.clientY-G;B.moved=Z*Z+K*K>v}B.event(z).zoom("mouse",n(S(B.that.__zoom,B.mouse[0]=lg(z,H),B.mouse[1]),B.extent,i))}function $(z){U.on("mousemove.zoom mouseup.zoom",null),qkt(z.view,B.moved),_R(z),B.event(z).end()}}function I(D,...F){if(e.apply(this,arguments)){var H=this.__zoom,B=lg(D.changedTouches?D.changedTouches[0]:D,this),U=H.invert(B),V=H.k*(D.shiftKey?.5:2),M=n(S(x(H,V),B,U),t.apply(this,F),i);_R(D),l>0?Tp(this).transition().duration(l).call(C,M,B,D):Tp(this).call(b.transform,M,B,D)}}function A(D,...F){if(e.apply(this,arguments)){var H=D.touches,B=H.length,U=_(this,F,D.changedTouches.length===B).event(D),V,M,G,q;for(Bte(D),M=0;M<B;++M)G=H[M],q=lg(G,this),q=[q,this.__zoom.invert(q),G.identifier],U.touch0?!U.touch1&&U.touch0[2]!==q[2]&&(U.touch1=q,U.taps=0):(U.touch0=q,V=!0,U.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(U.taps<2&&(f=q[0],d=setTimeout(function(){d=null},h)),$8(this),U.start())}}function R(D,...F){if(this.__zooming){var H=_(this,F).event(D),B=D.changedTouches,U=B.length,V,M,G,q;for(_R(D),V=0;V<U;++V)M=B[V],G=lg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],z=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],re=(re=Z[0]-$[0])*re+(re=Z[1]-$[1])*re,ee=(ee=K[0]-z[0])*ee+(ee=K[1]-z[1])*ee;M=x(M,Math.sqrt(re/ee)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],q=[(z[0]+K[0])/2,(z[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],q=H.touch0[1];else return;H.zoom("touch",n(S(M,G,q),H.extent,i))}}function L(D,...F){if(this.__zooming){var H=_(this,F).event(D),B=D.changedTouches,U=B.length,V,M;for(Bte(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),V=0;V<U;++V)M=B[V],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=lg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Tp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:rF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:rF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:rF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:rF([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const Sy={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."},EM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],oOt=["Enter"," ","Escape"],lOt={"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 Wj;(function(e){e.Strict="strict",e.Loose="loose"})(Wj||(Wj={}));var sO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(sO||(sO={}));var TM;(function(e){e.Partial="partial",e.Full="full"})(TM||(TM={}));const cOt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Sw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Sw||(Sw={}));var jM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(jM||(jM={}));var sr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(sr||(sr={}));const C7e={[sr.Left]:sr.Right,[sr.Right]:sr.Left,[sr.Top]:sr.Bottom,[sr.Bottom]:sr.Top};function uOt(e){return e===null?null:e?"valid":"invalid"}const dOt=e=>"id"in e&&"source"in e&&"target"in e,LYn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),aOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),L3=(e,t=[0,0])=>{const{width:n,height:r}=a0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},FYn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):aOe(s)?s:t.nodeLookup.get(s.id));const l=i?qB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return YH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return KH(n)},F3=(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=YH(n,qB(s)),r=!0)}),r?KH(n):{x:0,y:0,width:0,height:0}},iOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...B3(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=NM(l,Gj(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},zYn=(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 BYn(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 UYn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=BYn(e,i),c=F3(l),u=oOe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function fOt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",Sy.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&Qj(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=Qj(f)?QO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",Sy.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 VYn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=zYn(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 Zj=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),QO=(e={x:0,y:0},t,n)=>({x:Zj(e.x,t[0][0],t[1][0]-(n?.width??0)),y:Zj(e.y,t[0][1],t[1][1]-(n?.height??0))});function pOt(e,t,n){const{width:r,height:s}=a0(n),{x:a,y:i}=n.internals.positionAbsolute;return QO(e,[[a,i],[a+r,i+s]],t)}const E7e=(e,t,n)=>e<t?Zj(Math.abs(e-t),1,t)/t:e>n?-Zj(Math.abs(e-n),1,t)/t:0,hOt=(e,t,n=15,r=40)=>{const s=E7e(e.x,r,t.width-r)*n,a=E7e(e.y,r,t.height-r)*n;return[s,a]},YH=(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)}),Jge=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),KH=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Gj=(e,t=[0,0])=>{const{x:n,y:r}=aOe(e)?e.internals.positionAbsolute:L3(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}},qB=(e,t=[0,0])=>{const{x:n,y:r}=aOe(e)?e.internals.positionAbsolute:L3(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)}},mOt=(e,t)=>KH(YH(Jge(e),Jge(t))),NM=(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)},T7e=e=>wg(e.width)&&wg(e.height)&&wg(e.x)&&wg(e.y),wg=e=>!isNaN(e)&&isFinite(e),qYn=(e,t)=>{},z3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),B3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?z3(l,i):l},HB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function dE(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 HYn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=dE(e,n),s=dE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=dE(e.top??e.y??0,n),s=dE(e.bottom??e.y??0,n),a=dE(e.left??e.x??0,t),i=dE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function WYn(e,t,n,r,s,a){const{x:i,y:l}=HB(e,[t,n,r]),{x:c,y:u}=HB({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const oOe=(e,t,n,r,s,a)=>{const i=HYn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=Zj(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=WYn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},IM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function Qj(e){return e!=null&&e!=="parent"}function a0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function gOt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function vOt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function j7e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ZYn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function GYn(e){return{...lOt,...e||{}}}function k2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Sg(e),l=B3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?z3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const lOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),yOt=e=>e?.getRootNode?.()||window?.document,QYn=["INPUT","SELECT","TEXTAREA"];function bOt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:QYn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const xOt=e=>"clientX"in e,Sg=(e,t)=>{const n=xOt(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)}},N7e=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...lOe(i)}})};function wOt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function sF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function I7e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case sr.Left:return[t-sF(t-r,a),n];case sr.Right:return[t+sF(r-t,a),n];case sr.Top:return[t,n-sF(n-s,a)];case sr.Bottom:return[t,n+sF(s-n,a)]}}function cOe({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,curvature:i=.25}){const[l,c]=I7e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=I7e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=wOt({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 SOt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function YYn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function KYn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=YH(qB(e),qB(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return NM(i,KH(a))>0}const XYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,JYn=(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)),eKn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||XYn;let s;return dOt(e)?s={...e}:s={...e,id:r(e)},JYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function kOt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=SOt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const A7e={[sr.Left]:{x:-1,y:0},[sr.Right]:{x:1,y:0},[sr.Top]:{x:0,y:-1},[sr.Bottom]:{x:0,y:1}},tKn=({source:e,sourcePosition:t=sr.Bottom,target:n})=>t===sr.Left||t===sr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},R7e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function nKn({source:e,sourcePosition:t=sr.Bottom,target:n,targetPosition:r=sr.Top,center:s,offset:a,stepPosition:i}){const l=A7e[t],c=A7e[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=tKn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=SOt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const T=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?T:N:m=p==="x"?N:T}else{const T=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:T:m=l.y===h?T:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const F=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*F:x[p]=(d[p]>n[p]?-1:1)*F}}if(t!==r){const D=p==="x"?"y":"x",F=l[p]===c[D],H=u[D]>d[D],B=u[D]<d[D];(l[p]===1&&(!F&&H||F&&B)||l[p]!==1&&(!F&&B||F&&H))&&(m=p==="x"?T:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const C={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...C.x!==m[0].x||C.y!==m[0].y?[C]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],v,y,S,k]}function rKn(e,t,n,r){const s=Math.min(R7e(e,t)/2,R7e(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function eve({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=nKn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=rKn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function P7e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function sKn(e){const{sourceNode:t,targetNode:n}=e;if(!P7e(t)||!P7e(n))return null;const r=t.internals.handleBounds||$7e(t.handles),s=n.internals.handleBounds||$7e(n.handles),a=M7e(r?.source??[],e.sourceHandle),i=M7e(e.connectionMode===Wj.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",Sy.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||sr.Bottom,c=i?.position||sr.Top,u=YO(t,a,l),d=YO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function $7e(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function YO(e,t,n=sr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??a0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case sr.Top:return{x:s+i/2,y:a};case sr.Right:return{x:s+i,y:a+l/2};case sr.Bottom:return{x:s+i/2,y:a+l};case sr.Left:return{x:s,y:a+l/2}}}function M7e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function tve(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function aKn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=tve(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const OOt=1e3,iKn=10,uOe={nodeOrigin:[0,0],nodeExtent:EM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},oKn={...uOe,checkEquality:!0};function dOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function lKn(e,t,n){const r=dOe(uOe,n);for(const s of e.values())if(s.parentId)pOe(s,e,t,r);else{const a=L3(s,r.nodeOrigin),i=Qj(s.extent)?s.extent:r.nodeExtent,l=QO(a,i,a0(s));s.internals.positionAbsolute=l}}function cKn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function fOe(e){return e==="manual"}function nve(e,t,n,r={}){const s=dOe(oKn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!fOe(s.zIndexMode)?OOt: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=L3(d,s.nodeOrigin),h=Qj(d.extent)?d.extent:s.nodeExtent,m=QO(p,h,a0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:cKn(d,f),z:_Ot(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&&pOe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function uKn(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 pOe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=dOe(uOe,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}uKn(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*iKn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!fOe(c)?OOt:0,{x:p,y:h,z:m}=dKn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function _Ot(e,t,n){const r=wg(e.zIndex)?e.zIndex:0;return fOe(n)?r:r+(e.selected?t:0)}function dKn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=a0(e),u=L3(e,n),d=Qj(e.extent)?QO(u,e.extent,c):u;let f=QO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=pOt(f,c,t));const p=_Ot(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function hOe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??Gj(l),u=mOt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=a0(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function fKn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=lOe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=Qj(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=pOt(k,v,t.get(m.parentId)):S&&(k=QO(k,S,v));const C={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:N7e("source",h.nodeElement,x,f,m.id),target:N7e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,C),m.parentId&&pOe(C,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:Gj(C,s)}))}}if(p.length>0){const h=hOe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function pKn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function D7e(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function COt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;D7e("source",c,d,e,s,i),D7e("target",c,u,e,a,l),t.set(r.id,r)}}function EOt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:EOt(n,t):!1}function L7e(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 hKn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!EOt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Ute({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function mKn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=z3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function gKn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,p=null,h=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:C,nodeId:_,nodeClickDistance:E=0}){p=Tp(k);function T({x:R,y:L}){const{nodeLookup:D,nodeExtent:F,snapGrid:H,snapToGrid:B,nodeOrigin:U,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:q}=t();a={x:R,y:L};let $=!1;const z=l.size>1,Z=z&&F?Jge(F3(l)):null,K=z&&B?mKn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[re,ee]of l){if(!D.has(re))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};B&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:z3(J,H));let ae=null;if(z&&F&&!ee.extent&&Z){const{positionAbsolute:te}=ee.internals,ue=te.x-Z.x+F[0][0],de=te.x+ee.measured.width-Z.x2+F[1][0],ce=te.y-Z.y+F[0][1],ge=te.y+ee.measured.height-Z.y2+F[1][1];ae=[[ue,ce],[de,ge]]}const{position:fe,positionAbsolute:Y}=fOt({nodeId:re,nextPosition:J,nodeLookup:D,nodeExtent:ae||F,nodeOrigin:U,onError:G});$=$||ee.position.x!==fe.x||ee.position.y!==fe.y,ee.position=fe,ee.internals.positionAbsolute=Y}if(m=m||$,!!$&&(q(l,!0),v&&(r||V||!_&&M))){const[re,ee]=Ute({nodeId:_,dragItems:l,nodeLookup:D});r?.(v,l,re,ee),V?.(v,re,ee),_||M?.(v,ee)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:F}=t();if(!F){c=!1,cancelAnimationFrame(i);return}const[H,B]=hOt(u,d,D);(H!==0||B!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-B/R[2],await L({x:H,y:B})&&T(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:F,transform:H,snapGrid:B,snapToGrid:U,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:q}=t();f=!0,(!V||!C)&&!D&&_&&(L.get(_)?.selected||q()),C&&V&&_&&e?.(_);const $=k2(R.sourceEvent,{transform:H,snapGrid:B,snapToGrid:U,containerBounds:d});if(a=$,l=hKn(L,F,$,_),l.size>0&&(n||M||!_&&G)){const[z,Z]=Ute({nodeId:_,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,z,Z),M?.(R.sourceEvent,z,Z),_||G?.(R.sourceEvent,Z)}}const A=Hkt().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:F,snapGrid:H,snapToGrid:B}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,D===0&&I(R),a=k2(R.sourceEvent,{transform:F,snapGrid:H,snapToGrid:B,containerBounds:d}),u=Sg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:F,snapToGrid:H,nodeDragThreshold:B,nodeLookup:U}=t(),V=k2(R.sourceEvent,{transform:D,snapGrid:F,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||_&&!U.has(_))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=Sg(R.sourceEvent,d),G=M.x-u.x,q=M.y-u.y;Math.sqrt(G*G+q*q)>B&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Sg(R.sourceEvent,d),T(V))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:F,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||F||!_&&H){const[B,U]=Ute({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,B,U),F?.(R.sourceEvent,B,U),_||H?.(R.sourceEvent,U)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!L7e(L,`.${x}`,k))&&(!S||L7e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function vKn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())NM(s,Gj(a))>0&&r.push(a);return r}const yKn=250;function bKn(e,t,n,r){let s=[],a=1/0;const i=vKn(e,n,t+yKn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=YO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function TOt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...YO(i,c,c.position,!0)}:c}function jOt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function xKn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const NOt=()=>!0;function wKn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=NOt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:C,autoPanSpeed:_,dragThreshold:E=1,handleDomNode:T}){const N=yOt(e.target);let I=0,A;const{x:R,y:L}=Sg(e),D=jOt(a,T),F=l?.getBoundingClientRect();let H=!1;if(!F||!D)return;const B=TOt(s,D,r,c,t);if(!B)return;let U=Sg(e,F),V=!1,M=null,G=!1,q=null;function $(){if(!d||!F)return;const[fe,Y]=hOt(U,F,_);p({x:fe,y:Y}),I=requestAnimationFrame($)}const z={...B,nodeId:s,type:D,position:B.position},Z=c.get(s);let re={inProgress:!0,isValid:null,from:YO(Z,z,sr.Left,!0),fromHandle:z,fromPosition:z.position,fromNode:Z,to:U,toHandle:null,toPosition:C7e[z.position],toNode:null,pointer:U};function ee(){H=!0,S(re),m?.(e,{nodeId:s,handleId:r,handleType:D})}E===0&&ee();function J(fe){if(!H){const{x:ge,y:be}=Sg(fe),xe=ge-R,Ee=be-L;if(!(xe*xe+Ee*Ee>E*E))return;ee()}if(!C()||!z){ae(fe);return}const Y=k();U=Sg(fe,F),A=bKn(B3(U,Y,!1,[1,1]),n,c,z),V||($(),V=!0);const te=IOt(fe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});q=te.handleDomNode,M=te.connection,G=xKn(!!A,te.isValid);const ue=c.get(s),de=ue?YO(ue,z,sr.Left,!0):re.from,ce={...re,from:de,isValid:G,to:te.toHandle&&G?HB({x:te.toHandle.x,y:te.toHandle.y},Y):U,toHandle:te.toHandle,toPosition:G&&te.toHandle?te.toHandle.position:C7e[z.position],toNode:te.toHandle?c.get(te.toHandle.nodeId):null,pointer:U};S(ce),re=ce}function ae(fe){if(!("touches"in fe&&fe.touches.length>0)){if(H){(A||q)&&M&&G&&v?.(M);const{inProgress:Y,...te}=re,ue={...te,toPosition:re.toHandle?re.toPosition:null};y?.(fe,ue),a&&x?.(fe,ue)}h(),cancelAnimationFrame(I),V=!1,G=!1,M=null,q=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",J),N.addEventListener("touchend",ae)}function IOt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=NOt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=Sg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=jOt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),C=y.classList.contains("connectable"),_=y.classList.contains("connectableend");if(!S||!x)return b;const E={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=E;const N=C&&_&&(n===Wj.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(E),b.toHandle=TOt(S,x,k,d,n,!0)}return b}const rve={onPointerDown:wKn,isValid:IOt};function SKn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Tp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),C=S.sourceEvent.ctrlKey&&IM()?10:1,_=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,_*C);t.scaleTo(E)};let v=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(v=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const C=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],_=[C[0]-v[0],C[1]-v[1]];v=C;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),T={x:k[0]-_[0]*E,y:k[1]-_[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:T.x,y:T.y,zoom:k[2]},N,l)},x=iOt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:lg}}const XH=e=>({x:e.x,y:e.y,zoom:e.k}),Vte=({x:e,y:t,zoom:n})=>QH.translate(e,t).scale(n),fT=(e,t)=>e.target.closest(`.${t}`),AOt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),kKn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,qte=(e,t=0,n=kKn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},ROt=e=>{const t=e.ctrlKey&&IM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function OKn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(fT(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=lg(d),b=ROt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===sO.Vertical?0:d.deltaX*p,m=s===sO.Horizontal?0:d.deltaY*p;!IM()&&d.shiftKey&&s!==sO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=XH(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function _Kn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=fT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function CKn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=XH(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 EKn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&AOt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,XH(a.transform))}}function TKn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&AOt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=XH(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function jKn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(fT(f,`${u}-flow__node`)||fT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||fT(f,l)&&m||fT(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function NKn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=iOt().scaleExtent([t,n]).translateExtent(r),p=Tp(e).call(f);x({x:s.x,y:s.y,zoom:Zj(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(ROt);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:A8).transform(qte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:F,panOnDrag:H,panOnScrollMode:B,panOnScrollSpeed:U,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:q,zoomActivationKeyPressed:$,lib:z,onTransformChange:Z,connectionInProgress:K,paneClickDistance:re,selectionOnDrag:ee}){D&&!u.isZoomingOrPanning&&b();const J=F&&!$&&!D;f.clickDistance(ee?1/0:!wg(re)||re<0?0:re);const ae=J?OKn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:B,panOnScrollSpeed:U,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):_Kn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=CKn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const te=EKn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",te);const ue=TKn({zoomPanValues:u,panOnDrag:H,panOnScroll:F,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",ue)}const fe=jKn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:F,zoomOnDoubleClick:q,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:z,connectionInProgress:K});f.filter(fe),q?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=Vte(A),F=f?.constrain()(D,R,L);return F&&await v(F),new Promise(H=>H(F))}async function S(A,R){const L=Vte(A);return await v(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=Vte(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function C(){const A=p?aOt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:A8).scaleTo(qte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:A8).scaleBy(qte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!wg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:C,scaleTo:_,scaleBy:E,setScaleExtent:T,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var Yj;(function(e){e.Line="line",e.Handle="handle"})(Yj||(Yj={}));function IKn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function F7e(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 X0(e,t){return Math.max(0,t-e)}function J0(e,t){return Math.max(0,e-t)}function aF(e,t,n){return Math.max(0,t-e,e-n)}function z7e(e,t){return e?!t:t}function AKn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:C,height:_,aspectRatio:E}=e;let T=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=C+(c?-T:T),A=_+(u?-N:N),R=-a[0]*C,L=-a[1]*_;let D=aF(I,v,y),F=aF(A,b,x);if(i){let U=0,V=0;c&&T<0?U=X0(S+T+R,i[0][0]):!c&&T>0&&(U=J0(S+I+R,i[1][0])),u&&N<0?V=X0(k+N+L,i[0][1]):!u&&N>0&&(V=J0(k+A+L,i[1][1])),D=Math.max(D,U),F=Math.max(F,V)}if(l){let U=0,V=0;c&&T>0?U=J0(S+T,l[0][0]):!c&&T<0&&(U=X0(S+I,l[1][0])),u&&N>0?V=J0(k+N,l[0][1]):!u&&N<0&&(V=X0(k+A,l[1][1])),D=Math.max(D,U),F=Math.max(F,V)}if(s){if(d){const U=aF(I/E,b,x)*E;if(D=Math.max(D,U),i){let V=0;!c&&!u||c&&!u&&p?V=J0(k+L+I/E,i[1][1])*E:V=X0(k+L+(c?T:-T)/E,i[0][1])*E,D=Math.max(D,V)}if(l){let V=0;!c&&!u||c&&!u&&p?V=X0(k+I/E,l[1][1])*E:V=J0(k+(c?T:-T)/E,l[0][1])*E,D=Math.max(D,V)}}if(f){const U=aF(A*E,v,y)/E;if(F=Math.max(F,U),i){let V=0;!c&&!u||u&&!c&&p?V=J0(S+A*E+R,i[1][0])/E:V=X0(S+(u?N:-N)*E+R,i[0][0])/E,F=Math.max(F,V)}if(l){let V=0;!c&&!u||u&&!c&&p?V=X0(S+A*E,l[1][0])/E:V=J0(S+(u?N:-N)*E,l[0][0])/E,F=Math.max(F,V)}}}N=N+(N<0?F:-F),T=T+(T<0?D:-D),s&&(p?I>A*E?N=(z7e(c,u)?-T:T)/E:T=(z7e(c,u)?-N:N)*E:d?(N=T/E,u=c):(T=N*E,c=u));const H=c?S+T:S,B=u?k+N:k;return{width:C+(c?-T:T),height:_+(u?-N:N),x:a[0]*T*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+B}}const POt={width:0,height:0,x:0,y:0},RKn={...POt,pointerX:0,pointerY:0,aspectRatio:1};function PKn(e){return[[0,0],[e.measured.width,e.measured.height]]}function $Kn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function MKn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Tp(e);let i={controlDirection:F7e("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...POt},x={...RKn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:F7e(u)};let S,k=null,C=[],_,E,T,N=!1;const I=Hkt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:F,nodeOrigin:H,paneDomNode:B}=n();if(S=R.get(t),!S)return;k=B?.getBoundingClientRect()??null;const{xSnapped:U,ySnapped:V}=k2(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:F,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:U,pointerY:V,aspectRatio:b.width/b.height},_=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(_=R.get(S.parentId),E=_&&S.extent==="parent"?PKn(_):void 0),C=[],T=void 0;for(const[M,G]of R)if(G.parentId===t&&(C.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const q=$Kn(G,S,G.origin??H);T?T=[[Math.min(q[0][0],T[0][0]),Math.min(q[0][1],T[0][1])],[Math.max(q[1][0],T[1][0]),Math.max(q[1][1],T[1][1])]]:T=q}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:F}=n(),H=k2(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),B=[];if(!S)return;const{x:U,y:V,width:M,height:G}=b,q={},$=S.origin??F,{width:z,height:Z,x:K,y:re}=AKn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,T),ee=z!==M,J=Z!==G,ae=K!==U&&ee,fe=re!==V&&J;if(!ae&&!fe&&!ee&&!J)return;if((ae||fe||$[0]===1||$[1]===1)&&(q.x=ae?K:b.x,q.y=fe?re:b.y,b.x=q.x,b.y=q.y,C.length>0)){const de=K-U,ce=re-V;for(const ge of C)ge.position={x:ge.position.x-de+$[0]*(z-M),y:ge.position.y-ce+$[1]*(Z-G)},B.push(ge)}if((ee||J)&&(q.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?z:b.width,q.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=q.width,b.height=q.height),_&&S.expandParent){const de=$[0]*(q.width??0);q.x&&q.x<de&&(b.x=de,x.x=x.x-(q.x-de));const ce=$[1]*(q.height??0);q.y&&q.y<ce&&(b.y=ce,x.y=x.y-(q.y-ce))}const Y=IKn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...b,direction:Y};y?.(A,te)!==!1&&(N=!0,m?.(A,te),r(q,B))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const DKn={},B7e=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:()=>{(DKn?"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},LKn=e=>e?B7e(e):B7e,{useDebugValue:FKn}=Fe,{useSyncExternalStoreWithSelector:zKn}=_En,BKn=e=>e;function $Ot(e,t=BKn,n){const r=zKn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return FKn(r),r}const U7e=(e,t)=>{const n=LKn(e),r=(s,a=t)=>$Ot(n,s,a);return Object.assign(r,n),r},UKn=(e,t)=>e?U7e(e,t):U7e;function io(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const JH=g.createContext(null),VKn=JH.Provider,MOt=Sy.error001();function Us(e,t){const n=g.useContext(JH);if(n===null)throw new Error(MOt);return $Ot(n,e,t)}function To(){const e=g.useContext(JH);if(e===null)throw new Error(MOt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const V7e={display:"none"},qKn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},DOt="react-flow__node-desc",LOt="react-flow__edge-desc",HKn="react-flow__aria-live",WKn=e=>e.ariaLiveMessage,ZKn=e=>e.ariaLabelConfig;function GKn({rfId:e}){const t=Us(WKn);return o.jsx("div",{id:`${HKn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:qKn,children:t})}function QKn({rfId:e,disableKeyboardA11y:t}){const n=Us(ZKn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${DOt}-${e}`,style:V7e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${LOt}-${e}`,style:V7e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(GKn,{rfId:e})]})}const U3=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Hl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});U3.displayName="Panel";function YKn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(U3,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const KKn=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}},iF=e=>e.id;function XKn(e,t){return io(e.selectedNodes.map(iF),t.selectedNodes.map(iF))&&io(e.selectedEdges.map(iF),t.selectedEdges.map(iF))}function JKn({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Us(KKn,XKn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const eXn=e=>!!e.onSelectionChangeHandlers;function tXn({onSelectionChange:e}){const t=Us(eXn);return e||t?o.jsx(JKn,{onSelectionChange:e}):null}const sve=typeof window<"u"?g.useLayoutEffect:g.useEffect,FOt=[0,0],nXn={x:0,y:0,zoom:1},rXn=["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"],q7e=[...rXn,"rfId"],sXn=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}),H7e={translateExtent:EM,nodeOrigin:FOt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function aXn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Us(sXn,io),u=To();sve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=H7e,l()}),[]);const d=g.useRef(H7e);return sve(()=>{for(const f of q7e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:GYn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},q7e.map(f=>e[f])),null}function W7e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function iXn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=W7e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:W7e()?.matches?"dark":"light"}const Z7e=typeof document<"u"?document:null;function AM(e=null,t={target:Z7e,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
235
235
  `).replace(`
236
236
 
237
237
  `,`
@@ -639,7 +639,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
639
639
  }
640
640
  ]`})]})]})}function Lps({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border-accent2/30 rounded-md border p-3",children:[o.jsxs("div",{className:"text-accent2 mb-2 flex items-center gap-2",children:[o.jsx(Ue,{children:o.jsx(Cf,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function Fps({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[p,h]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=dfs(),{batchInsertItems:b}=Ii(),x=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),S=g.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&Le.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),C=g.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),_=i&&i.items.length>0&&i.errors.length===0,E=()=>{switch(s){case"upload":return o.jsx(Dps,{onFileSelect:x,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(Lps,{errors:i.errors}),o.jsx("div",{className:"text-neutral4 text-sm",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-neutral4 text-sm",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(Mps,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(en,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},T=()=>{switch(s){case"upload":return o.jsx(le,{onClick:C,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(le,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(le,{variant:"primary",onClick:S,disabled:!_,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(le,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(vr,{open:t,onOpenChange:C,children:o.jsxs(yr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(br,{children:[o.jsx(hr,{children:N[s]}),o.jsx(zs,{children:"Import dataset items from a JSON file."})]}),o.jsx(Ir,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:E()}),o.jsx(sc,{className:"flex justify-end gap-2 px-6 pt-4",children:T()})]})})}const RAe=e=>{const t=He(),{data:n}=CD(e),r=n?.experiments;return gt({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:l.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},zps=e=>{const t=He(),{data:n}=CD(e),r=n?.experiments;return gt({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:l.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function Bps(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function lVt({datasetId:e,experimentId:t,featuredItemId:n}){const r=He(),{data:s}=n0(e),{data:a,isLoading:i}=RAe(e),{data:l,isLoading:c}=zps(e),u=g.useMemo(()=>t?(a??[]).filter(Se=>Se.experimentId===t):a,[a,t]),d=g.useMemo(()=>t?(l??[]).filter(Se=>Se.experimentId===t):l,[l,t]),{updateExperimentResult:f}=Ii(),[p,h]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,v]=g.useState(null),[y,b]=g.useState(new Set),[x,S]=g.useState(!1),[k,C]=g.useState(!1),[_,E]=g.useState(!1),[T,N]=g.useState(""),[I,A]=g.useState(""),[R,L]=g.useState(""),[D,F]=g.useState([]),[H,B]=g.useState(!1),[U,V]=g.useState(null),M=g.useMemo(()=>U??u??[],[U,u]);g.useEffect(()=>{V(null)},[e,t]),g.useEffect(()=>{u&&U===null&&V(u)},[u,U]);const G=g.useMemo(()=>{const Se=new Set;if(s?.tags)for(const _e of s.tags)Se.add(_e);for(const _e of M)for(const Ce of _e.tags)Se.add(Ce);return[...Se].sort()},[s,M]),q=g.useCallback(Se=>{!s||!e||(s.tags??[]).includes(Se)},[s,e]),$=g.useMemo(()=>m?m==="__untagged__"?M.filter(Se=>Se.tags.length===0):M.filter(Se=>Se.tags.includes(m)):M,[M,m]),z=g.useMemo(()=>{const Se=new Map;for(const _e of M)for(const Ce of _e.tags)Se.set(Ce,(Se.get(Ce)??0)+1);return[...Se.entries()].sort((_e,Ce)=>Ce[1]-_e[1])},[M]),Z=g.useMemo(()=>M.filter(Se=>Se.tags.length===0).length,[M]),K=g.useMemo(()=>{let Se=0;return m&&Se++,x&&Se++,Se},[m,x]),re=g.useCallback((Se,_e)=>{V(Ie=>(Ie??[]).map(Qe=>Qe.id===Se?{...Qe,tags:_e}:Qe));const Ce=M.find(Ie=>Ie.id===Se);Ce?.experimentId&&Ce?.datasetId&&f.mutate({datasetId:Ce.datasetId,experimentId:Ce.experimentId,resultId:Ce.id,tags:_e})},[M,f]),ee=g.useCallback((Se,_e)=>{const Ce=M.find(Ie=>Ie.id===Se);Ce?.traceId&&_e!==void 0&&r.createFeedback({feedback:{traceId:Ce.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:_e==="positive"?1:-1,experimentId:Ce.experimentId??void 0,sourceId:Ce.id}}).catch(()=>{}),V(Ie=>(Ie??[]).map(Qe=>Qe.id===Se?{...Qe,rating:_e}:Qe))},[M,r]),J=g.useCallback((Se,_e)=>{const Ce=M.find(Ie=>Ie.id===Se);Ce?.experimentId&&Ce?.datasetId&&f.mutate({datasetId:Ce.datasetId,experimentId:Ce.experimentId,resultId:Ce.id,comment:_e}),Ce?.traceId&&r.createFeedback({feedback:{traceId:Ce.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:_e,comment:_e,experimentId:Ce.experimentId??void 0,sourceId:Ce.id}}).catch(()=>{}),V(Ie=>(Ie??[]).map(Qe=>Qe.id===Se?{...Qe,comment:_e}:Qe))},[M,r,f]),ae=g.useCallback(Se=>{const _e=M.find(Ce=>Ce.id===Se);V(Ce=>(Ce??[]).filter(Ie=>Ie.id!==Se)),b(Ce=>{const Ie=new Set(Ce);return Ie.delete(Se),Ie}),p===Se&&h(null),_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:null})},[M,f,p]),fe=g.useCallback(Se=>{const _e=M.find(Ce=>Ce.id===Se);V(Ce=>(Ce??[]).filter(Ie=>Ie.id!==Se)),b(Ce=>{const Ie=new Set(Ce);return Ie.delete(Se),Ie}),p===Se&&h(null),_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:"complete"})},[M,f,p]),Y=g.useMemo(()=>{const Se=x?d??[]:$;return!x||!m?Se:m==="__untagged__"?Se.filter(_e=>_e.tags.length===0):Se.filter(_e=>_e.tags.includes(m))},[x,d,$,m]),te=x?c:!1,ue=g.useMemo(()=>new Set(Y.map(Se=>Se.id)),[Y]),de=g.useMemo(()=>[...y].filter(Se=>ue.has(Se)).length,[y,ue]),ce=Y.length>0&&de===Y.length,ge=de>0&&!ce,be=g.useCallback(Se=>{b(_e=>{const Ce=new Set(_e);return Ce.has(Se)?Ce.delete(Se):Ce.add(Se),Ce})},[]),xe=g.useCallback(()=>{b(ce?new Set:new Set(Y.map(Se=>Se.id)))},[ce,Y]),Ee=g.useCallback(Se=>{for(const _e of y){const Ce=M.find(Ie=>Ie.id===_e);Ce&&!Ce.tags.includes(Se)&&re(_e,[...Ce.tags,Se])}},[M,y,re]),Oe=g.useCallback(Se=>{for(const _e of y){const Ce=M.find(Ie=>Ie.id===_e);Ce&&Ce.tags.includes(Se)&&re(_e,Ce.tags.filter(Ie=>Ie!==Se))}},[M,y,re]),Ne=g.useCallback(()=>{for(const Se of y)fe(Se);b(new Set)},[y,fe]),Pe=g.useCallback(()=>{for(const Se of y)ae(Se);b(new Set)},[y,ae]),ie=g.useCallback(()=>{N(""),E(!0)},[]),ne=g.useCallback(async()=>{if(!(!I||!R)){C(!0),E(!1);try{const Se=M.filter(Ce=>y.has(Ce.id));if(Se.length===0){C(!1);return}const _e=await r.clusterFailures({modelId:`${I}/${R}`,items:Se.map(Ce=>({id:Ce.id,input:Ce.input,output:Ce.output??void 0,error:typeof Ce.error=="string"?Ce.error:Ce.error?String(Ce.error):void 0,scores:Ce.scores,existingTags:Ce.tags.length>0?Ce.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:T||void 0});_e.proposedTags&&_e.proposedTags.length>0&&(F(_e.proposedTags.map(Ce=>({...Ce,accepted:!0}))),B(!0))}catch(Se){console.error("Analysis failed:",Se)}finally{C(!1)}}},[I,R,M,y,r,G,T]),se=g.useCallback(()=>{for(const Se of D){if(!Se.accepted)continue;const _e=M.find(Ce=>Ce.id===Se.itemId);if(_e){const Ce=[...new Set([..._e.tags,...Se.tags])];re(_e.id,Ce)}}B(!1)},[D,M,re]),pe=g.useCallback(Se=>{h(_e=>_e===Se?null:Se)},[]),we=g.useMemo(()=>p?Y.find(Se=>Se.id===p)??null:null,[p,Y]),Te=p?Y.findIndex(Se=>Se.id===p):-1,Re=Te>0?()=>h(Y[Te-1].id):void 0,Ze=Te>=0&&Te<Y.length-1?()=>h(Y[Te+1].id):void 0,Ge="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(en,{className:"h-6 w-6"})}):o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[o.jsx(vr,{open:_,onOpenChange:E,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Analyze Items"}),o.jsx(zs,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Hy,{value:I,onValueChange:A})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Wy,{llmId:I,value:R,onValueChange:L})]})]}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:[y.size," item",y.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx($l,{value:T,onChange:Se=>N(Se.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(sc,{children:[o.jsx(le,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),o.jsxs(le,{onClick:ne,disabled:!I||!R||k,children:[k?o.jsx(en,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(vr,{open:H,onOpenChange:B,children:o.jsxs(yr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Review Proposed Tags"}),o.jsxs(zs,{children:[D.filter(Se=>Se.accepted).length," of ",D.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:D.map((Se,_e)=>{const Ce=M.find(Ie=>Ie.id===Se.itemId);return o.jsx("div",{className:X("p-3 border rounded-lg",!Se.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Bo,{checked:Se.accepted,onCheckedChange:Ie=>F(Qe=>Qe.map(($e,qe)=>qe===_e?{...$e,accepted:!!Ie}:$e))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Ce?typeof Ce.input=="string"?Ce.input.slice(0,100):JSON.stringify(Ce.input).slice(0,100):Se.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:Se.tags.map((Ie,Qe)=>o.jsx(qBt,{tag:Ie,onRename:$e=>F(qe=>qe.map((Je,At)=>At===_e?{...Je,tags:Je.tags.map((_t,Zt)=>Zt===Qe?$e:_t)}:Je)),onRemove:()=>F($e=>$e.map((qe,Je)=>Je===_e?{...qe,tags:qe.tags.filter((At,_t)=>_t!==Qe)}:qe))},`${Ie}-${Qe}`))}),Se.reason&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Se.reason})]})]})},Se.itemId)})}),o.jsxs(sc,{children:[o.jsx(le,{variant:"outline",onClick:()=>B(!1),children:"Cancel"}),o.jsxs(le,{onClick:se,disabled:D.filter(Se=>Se.accepted).length===0,children:["Accept ",D.filter(Se=>Se.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",we&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid w-full content-start gap-8 overflow-y-auto",children:[o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(lt,{children:[o.jsx(lt.Trigger,{asChild:!0,children:o.jsxs(le,{variant:"outline",size:"md",children:[o.jsx(Clt,{}),"Filter",K>0&&o.jsx("span",{className:X("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:K})]})}),o.jsxs(lt.Content,{align:"start",className:X("min-w-48"),children:[o.jsxs(lt.Sub,{children:[o.jsxs(lt.SubTrigger,{children:["Status",x&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(lt.SubContent,{children:[o.jsx(lt.CheckboxItem,{checked:!x,onCheckedChange:()=>{S(!1),h(null)},onSelect:Se=>Se.preventDefault(),children:"Review Queue"}),o.jsx(lt.CheckboxItem,{checked:x,onCheckedChange:()=>{S(!0),h(null)},onSelect:Se=>Se.preventDefault(),children:"Completed"})]})]}),o.jsxs(lt.Sub,{children:[o.jsxs(lt.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(lt.SubContent,{children:[o.jsx(lt.CheckboxItem,{checked:!m,onCheckedChange:()=>v(null),onSelect:Se=>Se.preventDefault(),children:"All"}),Z>0&&o.jsx(lt.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>v(m==="__untagged__"?null:"__untagged__"),onSelect:Se=>Se.preventDefault(),children:"Untagged"}),z.length>0&&o.jsx(lt.Separator,{}),z.map(([Se])=>o.jsx(lt.CheckboxItem,{checked:m===Se,onCheckedChange:()=>v(m===Se?null:Se),onSelect:_e=>_e.preventDefault(),children:Se},Se))]})]}),K>0&&o.jsxs(o.Fragment,{children:[o.jsx(lt.Separator,{}),o.jsxs(lt.Item,{onSelect:()=>{v(null),S(!1),h(null)},children:[o.jsx(ws,{}),"Clear all filters"]})]})]})]}),K>0&&o.jsxs(le,{variant:"outline",size:"md",onClick:()=>{v(null),S(!1),h(null)},children:[o.jsx(ws,{}),"Reset"]})]}),!x&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(VBt,{selectedCount:y.size,vocabulary:G,onApplyTag:Ee,onRemoveTag:Oe,onNewTag:Se=>Ee(Se)}),o.jsxs(lt,{children:[o.jsx(lt.Trigger,{asChild:!0,children:o.jsxs(le,{disabled:k,children:[k?o.jsx(en,{className:"h-4 w-4"}):o.jsx(Ue,{size:"sm",children:o.jsx(Na,{})}),"Actions"]})}),o.jsxs(lt.Content,{align:"end",children:[o.jsxs(lt.Item,{onSelect:Ne,children:[o.jsx(Ue,{size:"sm",children:o.jsx(hO,{})}),"Complete"]}),o.jsxs(lt.Item,{onSelect:Pe,children:[o.jsx(Ue,{size:"sm",children:o.jsx(gu,{})}),"Remove"]}),o.jsx(lt.Separator,{}),o.jsxs(lt.Item,{onSelect:ie,children:[o.jsx(Ue,{size:"sm",children:o.jsx(Ig,{})}),"Analyze"]})]})]})]})]}),te?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(en,{className:"h-6 w-6"})}):Y.length===0?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsxs("div",{className:"px-8 text-center",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block",children:x?"No completed reviews yet":"No items to review"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:x?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(me,{columns:Ge,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:!0,children:[x?o.jsx(me.TopCell,{children:" "}):o.jsx(me.TopSelectCell,{checked:ce?!0:ge?"indeterminate":!1,onToggle:()=>xe(),"aria-label":"Select all"}),o.jsxs(me.TopCells,{colStart:2,children:[o.jsx(me.TopCell,{children:"Input"}),o.jsx(me.TopCell,{children:"Comment"}),o.jsx(me.TopCell,{children:"Tags"}),o.jsx(me.TopCell,{children:"Rating"}),o.jsx(me.TopCell,{children:"Scores"})]})]}),Y.map(Se=>{const _e=Se.scores?Object.entries(Se.scores):[],Ce=p===Se.id,Ie=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:Bps(Se.input,200)})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Se.comment?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 truncate",children:Se.comment}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Se.tags.length>0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 truncate",children:Se.tags.join(", ")}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(me.Cell,{height:"compact",children:[Se.rating==="positive"&&o.jsx(Ue,{size:"sm",className:"text-positive1",children:o.jsx(Jxe,{})}),Se.rating==="negative"&&o.jsx(Ue,{size:"sm",className:"text-negative1",children:o.jsx(Xxe,{})}),!Se.rating&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(me.Cell,{height:"compact",children:_e.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ue,{size:"sm",className:"text-neutral3",children:o.jsx(lm,{})}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 font-mono",children:_e[0][1].toFixed(2)}),_e.length>1&&o.jsxs(ln,{variant:"default",children:["+",_e.length-1]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(me.RowWrapper,{children:[x?o.jsx(me.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Se.error?"Error":"Success",title:Se.error?"Error":"Success",className:X("w-2 h-2 rounded-full",Se.error?"bg-red-700":"bg-green-600")})}):o.jsx(me.SelectCell,{checked:y.has(Se.id),onToggle:()=>be(Se.id),"aria-label":`Select item ${Se.id}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:Ce,onClick:()=>pe(Se.id),children:Ie})]},Se.id)})]})]}),we&&o.jsx(UBt,{item:we,isCompleted:x,tagVocabulary:G,onRate:Se=>ee(we.id,Se),onSetTags:Se=>{re(we.id,Se);for(const _e of Se)G.includes(_e)||q(_e)},onComment:Se=>J(we.id,Se),onRemove:()=>ae(we.id),onComplete:x?void 0:()=>fe(we.id),onPrevious:Re,onNext:Ze,onClose:()=>h(null)})]})]})}function Ups({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=wn(),[s,a]=si(),{tab:i,activeVersion:l,handleTabChange:c}=IAe(s,a),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[S,k]=g.useState([]),[C,_]=g.useState(!1),[E,T]=g.useState([]),[N,I]=g.useState(0),[A,R]=g.useState(null),[L,D]=g.useState(""),[F]=bSe(L,300),{data:H}=n0(e),{data:B=[],total:U,isLoading:V,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:q}=z1(e,F||void 0,l),{total:$}=z1(e,void 0,l),[z,Z]=g.useState({}),{data:K,isLoading:re}=CD(e,void 0,z),{data:ee}=CD(e),{deleteItems:J}=Ii(),ae=K?.experiments??[],fe=ee?.experiments??[],Y=Vfs({hasSearchQuery:!!F,filteredItemsLength:B.length,unfilteredItemsTotal:$,itemsTotal:U}),{data:te}=RAe(e),ue=te?.length??0,de=se=>{R(se)},ce=()=>{R(null)},ge=se=>{y(se),m(!0)},be=se=>{k(se),x(!0)},xe=se=>{x(se),se||(k([]),I(pe=>pe+1))},Ee=se=>{r(`/datasets/${e}/items?items=${se.join(",")}`)},Oe=se=>{r(`/datasets/${e}/versions?ids=${se.join(",")}`)},Ne=se=>{T(se),_(!0)},Pe=async()=>{await J.mutateAsync({datasetId:e,itemIds:E}),Le.success(`Deleted ${E.length} items`),_(!1),T([]),I(se=>se+1)},ie=se=>{m(!1),y([]),I(pe=>pe+1),n?.(se)},ne=se=>{m(se),se||(y([]),I(pe=>pe+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(pc,{defaultTab:"items",value:i,onValueChange:c,className:"grid h-full grid-rows-[auto_1fr]",children:[o.jsxs(fc,{children:[o.jsxs(jr,{value:"items",children:["Items ",o.jsx(ea,{color:"gray",children:Y})]}),o.jsxs(jr,{value:"experiments",children:["Experiments",o.jsx(ea,{color:"gray",children:ae.length})]}),o.jsxs(jr,{value:"review",children:["Review",ue>0&&o.jsx(ea,{color:"orange",children:ue})]})]}),o.jsx(Xr,{value:"items",className:"mt-5 grid overflow-auto pb-0",children:o.jsx($ps,{datasetId:e,items:B,isLoading:V,featuredItemId:A,onItemSelect:de,onItemClose:ce,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ne,onCreateDatasetClick:ge,onAddToDatasetClick:be,onCompareItemsClick:Ee,datasetName:H?.name,clearSelectionTrigger:N,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:q,searchQuery:L,activeSearchQuery:F,onSearchChange:D,currentDatasetVersion:H?.version,onCompareVersionsClick:Oe})}),o.jsx(Xr,{value:"experiments",className:"mt-5 grid overflow-auto pb-0",children:o.jsx(ips,{experiments:ae,allExperiments:fe,isLoading:re,datasetId:e,filters:z,onFiltersChange:Z})}),o.jsx(Xr,{value:"review",className:"mt-2 overflow-auto pb-0",children:o.jsx(lVt,{datasetId:e})})]}),o.jsx(Xfs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(Fps,{datasetId:e,open:f,onOpenChange:p}),o.jsx(Tfs,{open:h,onOpenChange:ne,items:v,onSuccess:ie}),o.jsx(jfs,{open:b,onOpenChange:xe,items:S,currentDatasetId:e}),o.jsx(Rt,{open:C,onOpenChange:_,children:o.jsxs(Rt.Content,{children:[o.jsxs(Rt.Header,{children:[o.jsx(Rt.Title,{children:"Delete Items"}),o.jsxs(Rt.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Rt.Footer,{children:[o.jsx(Rt.Cancel,{children:"Cancel"}),o.jsx(Rt.Action,{onClick:Pe,children:J.isPending?"Deleting...":"Delete"})]})]})})]})}function Vps(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 pie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function qps({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,S]=g.useState(null),{addItem:k}=Ii(),C=()=>{a("{}"),l(""),u(""),f(""),h(!1),v([]),b(""),S(null)},_=R=>{R||C(),n(R)},E=async R=>{R.preventDefault();let L;try{L=JSON.parse(s)}catch{Le.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Le.error("Ground Truth must be valid JSON");return}let F;if(c.trim())try{F=JSON.parse(c)}catch{Le.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const U=JSON.parse(d);if(!Array.isArray(U)){Le.error("Tool Mocks must be a JSON array");return}H=U}catch{Le.error("Tool Mocks must be valid JSON");return}let B;if(y.trim())try{B=JSON.parse(y)}catch{Le.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:D,expectedTrajectory:F,toolMocks:H,scorerIds:p?m:void 0,requestContext:B}),Le.success("Item added successfully"),_(!1),r?.()}catch(U){const V=Vps(U);V?S(V):Le.error(`Failed to add item: ${U instanceof Error?U.message:"Unknown error"}`)}},T=R=>{a(R),x?.field==="input"&&S(null)},N=R=>{l(R),x?.field==="groundTruth"&&S(null)},I=R=>{f(R),x?.field==="toolMocks"&&S(null)},A=()=>{_(!1)};return o.jsx(vr,{open:t,onOpenChange:_,children:o.jsxs(yr,{className:"max-w-lg",children:[o.jsx(br,{children:o.jsx(hr,{children:"Add Item"})}),o.jsx(Ir,{children:o.jsxs("form",{onSubmit:E,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Hr,{value:s,onChange:T,showCopyButton:!1,className:"min-h-[120px]"}),x?.field==="input"&&o.jsx(pie,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Hr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[80px]"}),x?.field==="groundTruth"&&o.jsx(pie,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Hr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Hr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[80px]"}),x?.field==="toolMocks"&&o.jsx(pie,{field:"toolMocks",errors:x.errors})]}),o.jsx(aVt,{overrideEnabled:p,onOverrideEnabledChange:h,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Hr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(le,{type:"button",onClick:A,children:"Cancel"}),o.jsx(le,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})})]})})}function Hps({item:e}){return o.jsx(ha,{withMargins:!1,children:o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{size:"smaller",children:[o.jsx(BN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(za,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ha.Description,{children:[o.jsxs(Oo,{children:[o.jsx(ylt,{})," Created ",or(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Oo,{children:[o.jsx(w_,{})," Version v",e.datasetVersion]})]})]})})}function PAe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs(zIe,{children:[o.jsx(Os.CodeSection,{title:"Input",icon:o.jsx(mO,{}),codeStr:t}),o.jsx(Os.CodeSection,{title:"Ground Truth",icon:o.jsx(Eg,{}),codeStr:n}),s&&o.jsx(Os.CodeSection,{title:"Expected Trajectory",icon:o.jsx(Qxe,{}),codeStr:s}),o.jsx(Os.CodeSection,{title:"Scorers",icon:o.jsx(Hxe,{}),codeStr:e.scorerIds===void 0?"Inherited from dataset":JSON.stringify(e.scorerIds,null,2)}),o.jsx(Os.CodeSection,{title:"Metadata",icon:o.jsx(qN,{}),codeStr:r})]})}const Wps=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Zps({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Am(),{data:l,isLoading:c}=Zy(),{data:u,isLoading:d}=dh(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Target Type"}),o.jsx(Ll,{options:Wps,value:e,onValueChange:h,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:m}),o.jsx(Ll,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function Gps({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return mm(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context"}),o.jsx(T3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-sm",children:"Failed to parse request context schema"})}function Qps({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=g.useRef(null),[l,c]=g.useState(""),[u,d]=g.useState(""),[f,p]=g.useState([]),[h,m]=g.useState({}),[v,y]=g.useState(""),{triggerExperiment:b}=Ii(),x=!!(n&&Object.keys(n).length>0),S=l&&u,k=b.isPending,C=()=>{c(""),d(""),p([]),m({}),y("")},_=()=>{if(x){const N=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return N.length>0?Object.fromEntries(N):void 0}if(v.trim()){let N;try{N=JSON.parse(v)}catch{throw new Error("Request Context must be valid JSON")}if(!N||typeof N!="object"||Array.isArray(N))throw new Error("Request Context must be a JSON object");return N}},E=async()=>{if(!S)return;let N;try{N=_()}catch(I){const A=I instanceof Error?I.message:"Request Context must be valid JSON";ou.error(A);return}try{const I=await b.mutateAsync({datasetId:e,targetType:l,targetId:u,scorerIds:f.length>0?f:void 0,version:t,requestContext:N});ou.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),C()}catch(I){const A=I instanceof Error?I.message:"Failed to trigger experiment";ou.error(A)}},T=()=>{k||(s(!1),C())};return o.jsx(vr,{open:r,onOpenChange:T,children:o.jsxs(yr,{ref:i,children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Experiment"}),o.jsx(zs,{children:t?`Execute items from ${or(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs(Ir,{className:"grid gap-6",children:[o.jsx(Zps,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(sVt,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),x?o.jsx(Gps,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context (JSON, optional)"}),o.jsx(Hr,{value:v,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(sc,{className:"px-6 pt-4",children:[o.jsx(le,{onClick:T,disabled:k,children:"Cancel"}),o.jsx(le,{variant:"primary",onClick:E,disabled:!S||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(en,{className:"h-4 w-4"}),"Running..."]}):"Run"})]})]})})}const Yps=e=>{const t=He();return gt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},enabled:!!e})},$Ae=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),o.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]});function hie(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Kps({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,a=[...t.map(i=>({outcome:"served",toolName:i.toolName,args:i.args})),...r.map(i=>({outcome:"live",toolName:i.toolName,args:i.args})),...n.map(i=>({outcome:"unconsumed",toolName:i.toolName,args:i.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx(Sn.SectionHeading,{icon:o.jsx(Zp,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(xn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(xn.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",hie(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>hie(i.args)).join(", ")]})]})}),o.jsx("div",{className:"border-border1 divide-border1 divide-y rounded border text-sm",children:a.map((i,l)=>o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[o.jsxs("span",{className:"min-w-0 truncate",children:[o.jsx("span",{className:"text-neutral4 font-mono",children:i.toolName}),o.jsx("span",{className:"text-neutral3 ml-2 font-mono text-xs",children:hie(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${Xps(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function Xps(e){switch(e){case"served":return"bg-accent1/10 text-accent1";case"live":return"bg-orange-500/10 text-orange-400";case"unconsumed":return"bg-neutral3/10 text-neutral4"}}function Jps({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=g.useState(!1),m=d??p,v=f??h,y=!!e?.error,b=Az(e?.input),x=Az(e?.output),S=Az(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",C=Array.isArray(e.tags)?e.tags:[];return o.jsxs(Sn,{collapsed:m,children:[o.jsxs(Sn.Header,{children:[o.jsxs(Sn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[f&&o.jsx(le,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>v(!m),children:m?o.jsx(Slt,{}):o.jsx(wlt,{})}),o.jsx(Sn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(le,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx($Ae,{}),"Trace"]}),o.jsx(Sn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(Sn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(Ut,{children:[o.jsx(Ut.Key,{children:"Item Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Ut.Key,{children:"Created"}),o.jsx(Ut.Value,{children:or(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(xn,{variant:"destructive",title:"Error",children:o.jsx(xn.Message,{children:Az(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(me,{columns:"1fr 1fr",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Scorer"}),o.jsx(me.TopCell,{children:"Score"})]}),t.map(_=>o.jsxs(me.RowButton,{featured:c===_.id,onClick:()=>l?.(_.id),children:[o.jsx(me.Cell,{height:"compact",children:_.scorerId}),o.jsx(me.MonoCell,{children:_.score.toFixed(3)})]},_.id))]}),e.toolMockReport&&o.jsx(Kps,{report:e.toolMockReport}),(e.status||C.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Sn.SectionHeading,{icon:o.jsx(qN,{}),className:"mb-2",children:"Review"}),(e.status||C.length>0)&&o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),C.map(_=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:_},_))]}),k&&o.jsx("div",{children:o.jsxs(le,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(sq,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(le,{size:"sm",onClick:i,children:[o.jsx(Oa,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(Sn.CodeSection,{title:"Input",icon:o.jsx(BN,{}),codeStr:b}),o.jsx(Sn.CodeSection,{title:"Output",icon:o.jsx(Eg,{}),codeStr:x}),o.jsx(Sn.CodeSection,{title:"Ground Truth",icon:o.jsx(Kxe,{}),codeStr:S})]})]})]})}function Az(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function ehs({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const p=!!(d&&f),h=[p?"auto":"",...s.map(v=>v.size)].filter(Boolean).join(" "),m=s.some(v=>v.name==="input");return t?o.jsx(ol,{columns:h}):o.jsxs(me,{columns:h,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:p,children:[p&&o.jsx(me.TopCell,{children:" "}),p?o.jsx(me.TopCells,{colStart:2,children:s.map(v=>o.jsx(me.TopCell,{children:v.label},v.name))}):s.map(v=>o.jsx(me.TopCell,{children:v.label},v.name))]}),e.length===0?o.jsx(me.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(v=>{const y=!!v.error,b=v.id===n,x=o.jsxs(o.Fragment,{children:[o.jsx(me.IdCell,{id:v.itemId}),o.jsx(me.Cell,{height:"compact",children:o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("div",{className:"relative flex h-full w-10 items-center justify-center bg-transparent",children:o.jsx("div",{role:"img","aria-label":y?"Error":"Success",className:X("w-2 h-2 rounded-full",y?"bg-red-700":"bg-green-600")})})}),o.jsx(On,{children:y?"Error":"Success"})]})}),m&&o.jsx(me.MonoCell,{children:nhs(ths(v.input),200)}),i?.map(S=>{const C=a?.[v.itemId]?.find(_=>_.scorerId===S);return o.jsx(me.Cell,{height:"compact",className:"text-neutral3 text-ui-smd font-mono",children:C!=null?C.score.toFixed(3):"-"},S)})]});return p?o.jsxs(me.RowWrapper,{children:[o.jsx(me.SelectCell,{checked:d.has(v.id),onToggle:()=>f(v.id),"aria-label":`Select result ${v.itemId}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(v.id),children:x})]},v.id):o.jsx(me.RowButton,{featured:b,onClick:()=>r(v.id),children:x},v.id)}),o.jsx(me.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function ths(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function nhs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function rhs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function shs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=g.useState(!1),u=a??l,d=i??c,f=rhs(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(Sn,{collapsed:u,children:[o.jsxs(Sn.Header,{children:[o.jsxs(Sn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[i&&o.jsx(le,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx(Slt,{}):o.jsx(wlt,{})}),(n||t)&&o.jsx(Sn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(le,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx($Ae,{}),"Trace"]}),o.jsx(Sn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(Sn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(Sn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(lm,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(Sn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Nh,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(Sn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Nh,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(Sn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Nh,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(Sn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Nh,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const _et=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function ahs({scoresByItemId:e,experimentStatus:t}){const n=g.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Lr,{iconSlot:o.jsx(lm,{className:"text-neutral3 h-8 w-8"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(bn,{children:[o.jsxs(bn.Header,{columns:_et,children:[o.jsx(bn.HeaderCol,{children:"Scorer"}),o.jsx(bn.HeaderCol,{children:"Avg Score"}),o.jsx(bn.HeaderCol,{children:"Items Scored"})]}),o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:n.map(({scorerId:r,avg:s,count:a})=>o.jsxs(bn.Row,{columns:_et,children:[o.jsx(bn.TextCell,{children:r}),o.jsx(bn.TextCell,{className:"font-mono",children:s.toFixed(3)}),o.jsx(bn.TextCell,{className:"font-mono",children:a})]},r))})})]})}function cVt({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=g.useState(null),[d,f]=g.useState(null),[p,h]=g.useState(void 0),[m,v]=g.useState(null),[y,b]=g.useState(new Set),[x,S]=g.useState(!1),[k,C]=g.useState(!1),[_,E]=g.useState(!1),[T,N]=g.useState(!1),{updateExperimentResult:I}=Ii(),A=g.useCallback(ne=>{b(se=>{const pe=new Set(se);return pe.has(ne)?pe.delete(ne):pe.add(ne),pe})},[]),R=g.useCallback(()=>b(new Set),[]),L=g.useCallback(()=>{const ne=r.filter(se=>!!se.error).map(se=>se.id);b(new Set(ne))},[r]),D=g.useCallback(async ne=>{if(x||ne.length===0)return;S(!0);let se=0;const pe=new Set;try{for(const we of ne)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:we,status:"needs-review"}),se++,pe.add(we)}catch{}}finally{S(!1)}pe.size>0&&b(we=>{const Te=new Set(we);for(const Re of pe)Te.delete(Re);return Te}),se>0&&Le(`${se} result${se>1?"s":""} flagged for review`)},[t,e,x,I]),F=r.find(ne=>ne.id===c)??null,[H,B]=g.useState("summary"),[U,V]=g.useState(null),M=ne=>{B(ne),ne!=="reviews"&&V(null)},{data:G}=RAe(t),q=(G??[]).filter(ne=>ne.experimentId===e).length,{data:$}=LBt(e,n),z=g.useMemo(()=>{if(!$)return[];const ne=new Set;for(const se of Object.values($))for(const pe of se)ne.add(pe.scorerId);return[...ne].sort()},[$]),Z=ne=>{u(ne),f(null),h(void 0),v(null)},K=ne=>{Z(ne===c?null:ne)},re=()=>{Z(null)},ee=()=>{if(!F)return;const ne=r.findIndex(se=>se.id===F.id);if(ne>=0&&ne<r.length-1)return()=>Z(r[ne+1].id)},J=()=>{if(!F)return;const ne=r.findIndex(se=>se.id===F.id);if(ne>0)return()=>Z(r[ne-1].id)},ae=F?$?.[F.itemId]:void 0,fe=ae?.find(ne=>ne.id===m)??null,Y=ne=>{v(ne===m?null:ne),f(null),h(void 0)},te=()=>{if(!m||!ae)return;const ne=ae.findIndex(se=>se.id===m);if(ne>=0&&ne<ae.length-1)return()=>v(ae[ne+1].id)},ue=()=>{if(!m||!ae)return;const ne=ae.findIndex(se=>se.id===m);if(ne>0)return()=>v(ae[ne-1].id)},{data:de,isLoading:ce}=Yps(d),ge=de?.spans,{data:be,isLoading:xe}=_L(d,p),Ee=be?.span,{handlePreviousSpan:Oe,handleNextSpan:Ne}=TAe(ge,p??null,h),Pe=(()=>{const ne=[],se=!!fe,pe=!!d;return ne.push(k?"auto":se||pe?"2fr":"1fr"),se&&ne.push(T?"auto":"3fr"),pe&&ne.push(_?"auto":"3fr"),pe&&p&&ne.push("3fr"),ne.join(" ")})(),ie=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...z.map(ne=>({name:ne,label:ne,size:"12rem"}))],[z]);return o.jsxs(pc,{defaultTab:"summary",value:H,onValueChange:M,className:"grid h-full grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"summary",children:"Summary"}),o.jsx(jr,{value:"results",children:"Results"}),o.jsxs(jr,{value:"reviews",children:["Reviews",q>0&&o.jsx(ea,{color:"orange",children:q})]})]}),o.jsx(Xr,{value:"summary",className:"mt-5 overflow-y-auto",children:o.jsx(ahs,{scoresByItemId:$,experimentStatus:n})}),o.jsx(Xr,{value:"reviews",className:"mt-2 overflow-auto pb-0",children:o.jsx(lVt,{datasetId:t,experimentId:e,featuredItemId:U})}),o.jsxs(Xr,{value:"results",className:"mt-2 grid grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"bg-surface3 flex items-center gap-2 px-4 py-2",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(le,{variant:"outline",size:"sm",disabled:x,onClick:()=>D([...y]),children:[o.jsx(Ue,{size:"sm",children:o.jsx(sq,{})}),"Flag for Review"]}),o.jsx(le,{variant:"ghost",size:"sm",onClick:R,children:"Clear"})]}),r.length>0&&y.size===0&&!s&&o.jsx("div",{className:"flex items-center gap-2 px-4 py-2",children:o.jsx(le,{variant:"ghost",size:"sm",onClick:L,children:"Select loaded failures"})})]}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",F&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"flex w-full overflow-y-auto",children:o.jsx("div",{className:"grid w-full content-start gap-8 overflow-y-auto",children:o.jsx(ehs,{results:r,isLoading:s,featuredResultId:c,onResultClick:K,columns:ie,scoresByItemId:$,scorerIds:z,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:A})})}),F&&o.jsxs("div",{className:"grid max-h-full min-h-0 content-start gap-4 overflow-auto",style:{gridTemplateRows:Pe},children:[o.jsx(Jps,{result:F,scores:ae,onPrevious:J(),onNext:ee(),onClose:re,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{F.traceId&&(f(F.traceId),h(void 0),v(null),C(!0),E(!1))},onOpenInReview:()=>{V(F.id),B("reviews")},onFlagForReview:ne=>D([ne]),collapsed:k,onCollapsedChange:C}),fe&&o.jsx(shs,{score:fe,onNext:te(),onPrevious:ue(),onClose:()=>v(null),onShowTrace:()=>{fe.traceId&&(f(fe.traceId),h(void 0),C(!0),N(!0),E(!1))},collapsed:T,onCollapsedChange:N}),d&&o.jsxs(o.Fragment,{children:[o.jsx(xAe,{traceId:d,spans:ge,isLoading:ce,onClose:()=>{f(null),h(void 0),C(!1),N(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:_,onCollapsedChange:E,LinkComponent:sy,traceHref:`/traces/${d}`}),p&&o.jsx(vAe,{traceId:d,spanId:p,span:Ee,isLoading:xe,onPrevious:Oe,onNext:Ne,onClose:()=>h(void 0)})]})]})]})]})]})}const ihs={pending:o.jsx(mj,{}),running:o.jsx(vpe,{}),completed:o.jsx(da,{}),failed:o.jsx(ws,{})};function ohs({experiment:e,className:t}){const n=e.status,r=e.totalItems-e.succeededCount-e.failedCount;return o.jsxs("div",{className:X("grid justify-items-end gap-3",t),children:[o.jsxs("div",{className:"text-ui-lg text-neutral4 bg-surface5 flex items-center gap-2 rounded-lg p-1 px-3 capitalize",children:[o.jsx("span",{className:X("w-5 h-5 flex items-center justify-center rounded-full text-black","[&>svg]:w-4 [&>svg]:h-4",{"bg-green-700":n==="completed","bg-red-700":n==="failed","bg-cyan-600":n==="running","bg-yellow-600":n==="pending"}),children:ihs[n]}),e.status]}),o.jsxs("div",{className:X("flex items-center gap-3 text-neutral3 text-ui-md ","[&>span]:flex [&>span]:gap-1 [&>span]:items-center ","[&_b]:text-neutral4 [&_b]:font-semibold"),children:[o.jsxs("span",{children:["Total: ",o.jsx("b",{children:e.totalItems})]}),o.jsxs("span",{children:["Succeeded: ",o.jsx("b",{children:e.succeededCount})]}),o.jsxs("span",{children:["Failed: ",o.jsx("b",{children:e.failedCount})]}),(n==="pending"||n==="running")&&o.jsxs("span",{children:["Pending: ",o.jsx("b",{children:r})]})]})]})}function lhs({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs(Mr,{spacing:"close",children:[o.jsxs(le,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx(uH,{})," Prev"]}),o.jsxs(le,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(d3,{})]})]})}function MAe({delta:e}){const t=e>0?o.jsx(ea,{size:"small",color:"green",intensity:"muted",children:o.jsx(AD,{})}):e<0?o.jsx(ea,{size:"small",color:"red",intensity:"muted",children:o.jsx(CZt,{})}):null;return o.jsxs("span",{className:X("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function Rz(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function chs({item:e,baselineId:t,contenderId:n,baselineVersion:r,contenderVersion:s,onPrevious:a,onNext:i,onClose:l}){const c=e.results[t],u=e.results[n],d=!!(c&&u),f=new Set;if(c)for(const h of Object.keys(c.scores))f.add(h);if(u)for(const h of Object.keys(u.scores))f.add(h);const p=[...f].sort();return o.jsxs(Yr,{withLeftSeparator:!0,children:[o.jsxs(Yr.Toolbar,{children:[o.jsx(lhs,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx(Mr,{children:o.jsx(le,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(ws,{})})})]}),o.jsxs(Yr.Content,{className:"pb-6",children:[o.jsx(ha,{withMargins:!1,children:o.jsx(ha.Column,{children:o.jsxs(ha.Title,{size:"smaller",children:[o.jsx(BN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs(zIe,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-neutral5 text-sm font-medium",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,v=u?.scores[h]??null,y=m!=null&&v!=null?v-m:null;return o.jsxs("div",{className:"bg-surface2 flex items-center justify-between gap-4 rounded-lg px-3 py-2",children:[o.jsx("span",{className:"text-neutral5 text-sm font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-neutral3 text-sm",children:[m!=null?m.toFixed(3):"-"," →"," ",v!=null?v.toFixed(3):"-"]}),y!=null&&o.jsx(MAe,{delta:y})]})]},h)})})]}),o.jsx(Os.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(ea,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(Eg,{}),codeStr:Rz(c?.output)}),o.jsx(Os.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(ea,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(Eg,{}),codeStr:Rz(u?.output)}),o.jsx(Os.CodeSection,{title:"Item Input",icon:o.jsx(mO,{}),codeStr:Rz(e.input)}),o.jsx(Os.CodeSection,{title:"Item Ground Truth",icon:o.jsx(Kxe,{}),codeStr:Rz(e.groundTruth)})]})}):o.jsx(xn,{variant:"warning",title:"Comparison not available",children:o.jsx(xn.Message,{children:(()=>{const h=c?"Contender":"Baseline",m=c?s:r;return o.jsxs(o.Fragment,{children:["The ",h," experiment was run against dataset",m!=null?` v. ${m}`:"",", which does not contain this item."]})})()})})]})]})}function uhs({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Yr,{children:o.jsxs(bn,{children:[o.jsxs(bn.Header,{columns:a,children:[o.jsx(bn.HeaderCol,{children:"Item ID"}),!s&&r.map(l=>o.jsx(bn.HeaderCol,{className:"flex justify-center",children:l},l))]}),o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:e.map(l=>{const c=l.results[t],u=l.results[n],d=!!(c&&u);return o.jsx(bn.Row,{children:o.jsxs(bn.RowButton,{item:{id:l.itemId},columns:a,isFeatured:s===l.itemId,onClick:i,children:[o.jsx(bn.IdCell,{id:l.itemId,className:d?"":"text-neutral1"}),!s&&o.jsx(o.Fragment,{children:r.map(f=>{const p=c?.scores[f]??null,h=u?.scores[f]??null,m=p!=null&&h!=null?h-p:null;return o.jsx(bn.Cell,{className:"flex items-center justify-center gap-5 font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-neutral2 flex min-w-24 items-center",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(MAe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const dhs={baseline:{label:"Baseline",color:"purple",customStyle:"items-end justify-items-end [&>div]:justify-end border-r-0 rounded-r-none"},contender:{label:"Contender",color:"cyan",customStyle:"items-start justify-items-start [&>div]:justify-start border-l-0 rounded-l-none"}};function Cet({datasetId:e,experiment:t,type:n}){const{Link:r}=wn(),{label:s,color:a,customStyle:i}=dhs[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null,c=lS(t.id)??t.id,u=t.name||c,d=o.jsx(le,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"min-w-0 truncate",children:u})});return o.jsxs("div",{className:`border-border1 grid gap-3 rounded-lg border-2 p-5 ${i}`,children:[o.jsxs("div",{className:"flex w-full items-center gap-3 overflow-clip",children:[n==="contender"&&o.jsxs(ea,{size:"small",color:a,children:[s,o.jsx(wm,{})]}),t.description?o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:d}),o.jsx(On,{children:t.description})]}):d,n==="baseline"&&o.jsxs(ea,{size:"small",color:a,children:[o.jsx(Pc,{})," ",s]})]}),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Oo,{children:[o.jsx(mpe,{})," ",c]}),o.jsxs(Oo,{children:[o.jsx(Kxe,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(Oo,{children:[o.jsx(oq,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(Oo,{children:[o.jsx(blt,{})," ",or(l,"MMM d, yyyy HH:mm")]})]})]})}function fhs({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=g.useState(null),{data:i,isLoading:l,error:c}=tfs(e,t,n),{data:u}=GV(e,t),{data:d}=GV(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=g.useMemo(()=>{if(!i)return[];const E=new Set;for(const T of i.items)for(const N of Object.values(T.results))if(N)for(const I of Object.keys(N.scores))E.add(I);return[...E].sort()},[i]),h=g.useMemo(()=>{if(!i||p.length===0)return[];const E=i.baselineId,T=t===E?n:t;return p.map(N=>{let I=0,A=0,R=0,L=0;for(const B of i.items){const U=B.results[E]?.scores[N],V=B.results[T]?.scores[N];U!=null&&(I+=U,R++),V!=null&&(A+=V,L++)}const D=R>0?I/R:null,F=L>0?A/L:null,H=D!=null&&F!=null?F-D:null;return{scorerId:N,avgA:D,avgB:F,delta:H}})},[i,p,t,n]),m=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"baselineAvg",label:"Baseline Avg",size:"1fr"},{name:"comparisonAvg",label:"Comparison Avg",size:"1fr"},{name:"delta",label:"Delta",size:"1fr"}],v=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(E=>({name:E,label:E,size:"1fr"}))],[p,s]),y=i?.items.find(E=>E.itemId===s)??null,b=E=>{a(E===s?null:E)},x=()=>{a(null)},S=()=>{if(!i||!s)return;const E=i.items.findIndex(T=>T.itemId===s);if(E>=0&&E<i.items.length-1)return()=>a(i.items[E+1].itemId)},k=()=>{if(!i||!s)return;const E=i.items.findIndex(T=>T.itemId===s);if(E>0)return()=>a(i.items[E-1].itemId)};if(l)return o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(en,{})});if(c)return o.jsx(xn,{variant:"warning",title:"Error loading comparison",children:o.jsx(xn.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"});const C=i.baselineId,_=t===C?n:t;return o.jsxs("div",{className:"grid gap-10",children:[u&&d&&o.jsxs("div",{className:X("relative grid xl:grid-cols-[1fr_auto_1fr] gap-4 xl:gap-0"),children:[o.jsx(Cet,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"before:bg-border1 relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:w-[2px] before:-translate-x-1/2",children:o.jsx("div",{className:"bg-surface2 relative z-1 rounded-lg p-2",children:o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(le,{onClick:r,children:"VS"})}),o.jsx(On,{children:"Switch the order"})]})})}),o.jsx(Cet,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(xn,{variant:"warning",title:"Version mismatch",children:o.jsxs(xn.Message,{children:["These experiments used different dataset versions (v",u.datasetVersion," vs v",d.datasetVersion,"). Results may not be directly comparable."]})}),h.length>0&&o.jsxs(bn,{children:[o.jsxs(bn.Header,{columns:m,children:[o.jsx(bn.HeaderCol,{children:"Scorer"}),o.jsx(bn.HeaderCol,{className:"flex justify-center",children:o.jsxs(yJe,{children:[o.jsx(ea,{color:"purple",size:"small",intensity:"muted",children:"Baseline"}),o.jsx(ea,{color:"purple",size:"small",children:"Avg"})]})}),o.jsx(bn.HeaderCol,{className:"flex justify-center",children:o.jsxs(yJe,{children:[o.jsx(ea,{color:"cyan",size:"small",intensity:"muted",children:"Contender"}),o.jsx(ea,{color:"cyan",size:"small",children:"Avg"})]})}),o.jsx(bn.HeaderCol,{className:"flex justify-center",children:"Delta"})]}),o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:h.map(({scorerId:E,avgA:T,avgB:N,delta:I})=>o.jsxs(bn.Row,{columns:m,children:[o.jsx(bn.TextCell,{children:E}),o.jsx(bn.TextCell,{className:"text-center font-mono",children:T!=null?T.toFixed(3):"-"}),o.jsx(bn.TextCell,{className:"text-center font-mono",children:N!=null?N.toFixed(3):"-"}),o.jsx(bn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(MAe,{delta:I}):"-"})]},E))})})]}),o.jsxs(dy,{className:X({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(uhs,{items:i.items,baselineId:C,contenderId:_,scorerIds:p,featuredItemId:s,columns:v,onItemClick:b}),!!y&&o.jsx(chs,{item:y,baselineId:C,contenderId:_,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:S(),onClose:x})]})]})}function phs({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=NAe(e,t),[l,c]=g.useState(!1),[u,d]=g.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(x=>{const S=new Set(x);if(S.has(b))S.delete(b);else if(S.size>=2){const[k]=Array.from(S);return new Set([k,b])}else S.add(b);return S})},m=()=>{c(!1),d(new Set)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Yr,{className:"min-w-56",children:[l?o.jsx(Yr.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(Mr,{children:[o.jsx(le,{onClick:m,children:"Cancel"}),o.jsx(le,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(Yr.Toolbar,{children:o.jsxs(le,{onClick:v,className:"w-full",children:[o.jsx(n1,{})," Compare Ver."]})})}),i?o.jsx(hhs,{}):o.jsxs(bn,{children:[o.jsx(bn.Header,{children:o.jsx(bn.HeaderCol,{children:"Item Version History"})}),o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:a?.map(b=>{const x=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(bn.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(bn.LabelCell,{children:o.jsx(Bo,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(x)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(bn.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",children:o.jsx(bn.VersionCell,{version:b.datasetVersion,date:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function hhs(){return o.jsxs(bn,{children:[o.jsx(bn.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(bn.HeaderCol,{children:"Item Version History"})}),o.jsx(bn.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(bn.Row,{children:o.jsx(bn.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(bn.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function mhs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${or(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function ghs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=eAe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${mhs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Yr.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Cc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Cc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const vhs=[{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"}],yhs={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Zr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(Plt,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(QGt,{}),tooltip:"Same in both versions"}};function mie({red:e=!1,tooltip:t}){return o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx(MZt,{className:X("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx(On,{children:t})]})}function uk({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{color:n,icon:r,tooltip:s}=yhs[e];return o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx(ea,{color:n,size:"small",children:r})]})}),o.jsx(On,{children:s})]})}function bhs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function xhs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=wn(),l=t>n;return o.jsx(bn,{children:o.jsx(bn.Scroller,{children:o.jsx(bn.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=bhs(u,d);return o.jsxs(bn.Row,{columns:vhs,children:[o.jsx(bn.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(bn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!d&&l?o.jsx(uk,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(uk,{variant:"changed",version:u.datasetVersion}):o.jsx(uk,{version:u.datasetVersion})}):o.jsx(bn.Cell,{className:"flex items-center justify-center",children:o.jsx(mie,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(bn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!u&&!l?o.jsx(uk,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(uk,{variant:"changed",version:d.datasetVersion}):o.jsx(uk,{version:d.datasetVersion})}):o.jsx(bn.Cell,{className:"flex items-center justify-center",children:o.jsx(mie,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(bn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",children:o.jsx(uk,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(bn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(bn.Cell,{children:o.jsx(mie,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const Eet={needsReview:"#facc15",complete:"#22c55e"},whs=[{label:"Needs Review",color:Eet.needsReview},{label:"Reviewed",color:Eet.complete}];function Shs({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;p+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:x,values:[m.needsReview,m.complete]})}return{data:h,maxVal:f,totalInPipeline:p}},[e,t,n]),c=a.length>0;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Qt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Qt.Loading,{}):s?o.jsx(Qt.Error,{message:"Failed to load review data"}):o.jsx(Qt.Content,{children:c?o.jsx(PN,{data:a,segments:whs,maxVal:i,fmt:u=>String(u)}):o.jsx(Qt.NoData,{message:"No items have been sent to review yet"})})]})}function DAe(){const e=He();return gt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function uVt(e){const t=new Map;if(!e?.counts)return t;for(const n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}function khs(e,t){const n=new Map,r=uVt(e);if(!r.size||!t)return n;for(const s of t){const a=r.get(s.id);if(!a||!s.datasetId||a.needsReview+a.complete===0)continue;const l=n.get(s.datasetId)??{needsReview:0,complete:0};l.needsReview+=a.needsReview,l.complete+=a.complete,n.set(s.datasetId,l)}return n}function Ohs(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}const _hs=10;function Chs(){const[e,t]=g.useState(!1),[n,r]=g.useState(""),[s,a]=g.useState("all"),[i,l]=g.useState("all"),[c,u]=g.useState("all"),[d,f]=g.useState(0),{data:p,isLoading:h,error:m}=Hg({page:d,perPage:_hs}),{data:v,isLoading:y,error:b}=TQ(),{data:x}=DAe(),S=g.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,C=g.useMemo(()=>v?.experiments??[],[v?.experiments]),_=g.useMemo(()=>bfs(S),[S]),E=g.useMemo(()=>khs(x,C),[x,C]),T=h||y,N=m||b,I=()=>t(!0),A=g.useCallback(()=>f(V=>V+1),[]),R=g.useCallback(()=>f(V=>Math.max(0,V-1)),[]),L=g.useCallback(V=>{r(V),f(0)},[]),D=g.useCallback(V=>{a(V),f(0)},[]),F=g.useCallback(V=>{l(V),f(0)},[]),H=g.useCallback(V=>{u(V),f(0)},[]);if(N&&xs(N))return o.jsx(cr,{children:o.jsx(Zs,{})});if(N&&Ss(N))return o.jsx(cr,{children:o.jsx($s,{resource:"datasets"})});if(N)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load datasets",message:N.message})});if(S.length===0&&!T&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(cr,{children:o.jsx(Ofs,{onCreateClick:I})}),o.jsx(mxe,{open:e,onOpenChange:t})]});const B=s!=="all"||i!=="all"||c!=="all"||n!=="",U=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Efs,{search:n,onSearchChange:L,targetFilter:s,onTargetFilterChange:D,experimentFilter:i,onExperimentFilterChange:F,tagFilter:c,onTagFilterChange:H,tagOptions:_,onReset:U,hasActiveFilters:B,onCreateClick:I})}),o.jsx(kfs,{datasets:S,experiments:C,reviewByDataset:E,isLoading:T,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:A,onPrevPage:R}),o.jsx(mxe,{open:e,onOpenChange:t})]})}function Pz({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function Ehs(){const{datasetId:e}=Sr(),t=Ws(),[n,r]=si(),{activeVersion:s}=IAe(n,r),[a,i]=g.useState(!1),[l,c]=g.useState(!1),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),{data:v,error:y,isLoading:b}=n0(e),{data:x=[],isLoading:S}=z1(e,void 0,s),k=!S&&x.length===0;if(b)return null;if(y&&xs(y))return o.jsx(Pz,{children:o.jsx(Zs,{})});if(y&&Ss(y))return o.jsx(Pz,{children:o.jsx($s,{resource:"datasets"})});if(y&&NEe(y)||!b&&!y&&!v)return o.jsx(Pz,{children:o.jsx(Lr,{iconSlot:o.jsx(fy,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(le,{as:ni,to:"/datasets",children:[o.jsx(Pc,{}),"Back to Datasets"]})})});if(y)return o.jsx(Pz,{children:o.jsx(Hi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const C=E=>{t(`/datasets/${e}/experiments/${E}`)},_=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Vt,{height:"full",children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{children:[o.jsxs(Vt.Column,{children:[v?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:v.description}),o.jsxs(Ut,{numOfCol:2,children:[o.jsx(Ut.Key,{children:"Created at"}),o.jsx(Ut.Value,{children:v?.createdAt?or(new Date(v.createdAt),"MMM d, yyyy"):""}),o.jsx(Ut.Key,{children:"Latest version"}),o.jsxs(Ut.Value,{children:["v",v?.version??""]})]})]}),o.jsx(Vt.Column,{children:o.jsxs(Mr,{children:[k?o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsxs(le,{variant:"primary",children:[o.jsx(Wp,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx(On,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(le,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(Wp,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(lt,{children:[o.jsx(lt.Trigger,{asChild:!0,children:o.jsx(le,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(PD,{})})}),o.jsxs(lt.Content,{align:"end",className:"w-48",children:[o.jsxs(lt.Item,{onSelect:()=>d(!0),children:[o.jsx(cm,{})," Edit Dataset"]}),o.jsxs(lt.Item,{onSelect:()=>m(!0),children:[o.jsx(om,{})," Duplicate Dataset"]}),o.jsxs(lt.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(gu,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Vt.MainArea,{children:o.jsx(Ups,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(Qps,{datasetId:e,version:s??void 0,requestContextSchema:v?.requestContextSchema,open:a,onOpenChange:i,onSuccess:C}),o.jsx(qps,{datasetId:e,open:l,onOpenChange:c}),v&&o.jsx(Rfs,{open:u,onOpenChange:d,dataset:{id:v.id,name:v.name,description:v?.description||"",targetType:v.targetType,inputSchema:v.inputSchema,groundTruthSchema:v.groundTruthSchema,requestContextSchema:v.requestContextSchema}}),v&&o.jsx(Nfs,{open:h,onOpenChange:m,sourceDatasetId:v.id,sourceDatasetName:v.name,sourceDatasetDescription:v.description,sourceDatasetTargetType:v.targetType}),v&&o.jsx($fs,{open:f,onOpenChange:p,datasetId:v.id,datasetName:v.name,onSuccess:_})]})}function dVt({experiment:e}){const{Link:t,paths:n}=wn(),{data:r}=Am(),{data:s}=Zy(),{data:a}=dh(),i=()=>{if(!e.targetId)return null;switch(e.targetType){case"agent":return n.agentLink(e.targetId);case"workflow":return n.workflowLink(e.targetId);case"scorer":return n.scorerLink(e.targetId);default:return"#"}},l=()=>{const u=e.targetId;if(!u)return"External (caller-run)";switch(e.targetType){case"agent":return r?.[u]?.name??u;case"workflow":return s?.[u]?.name??u;case"scorer":return a?.[u]?.scorer?.config?.name??u;default:return u}},c=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{children:[o.jsx(Vt.Column,{children:o.jsxs(Ut,{numOfCol:2,children:[e.name&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Name"}),o.jsx(Ut.Value,{children:e.name})]}),e.description&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Description"}),o.jsx(Ut.Value,{children:e.description})]}),o.jsx(Ut.Key,{children:"Created at"}),o.jsx(Ut.Value,{children:or(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Completed at"}),o.jsx(Ut.Value,{children:or(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(Ut.Key,{children:"Target"}),(()=>{const u=i();return u?o.jsx(Ut.ValueLink,{href:u,as:t,children:l()}):o.jsx(Ut.Value,{children:l()})})(),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Version"}),c?o.jsx(Ut.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(Ut.Value,{children:e.agentVersion})]})]})}),o.jsx(Vt.Column,{children:o.jsx(ohs,{experiment:e})})]})})}function $z({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function Ths(){const{datasetId:e,experimentId:t}=Sr(),{data:n,isLoading:r,error:s}=GV(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=cQ({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&xs(s)?o.jsx($z,{children:o.jsx(Zs,{})}):s&&Ss(s)?o.jsx($z,{children:o.jsx($s,{resource:"datasets"})}):s&&NEe(s)||!r&&!s&&!n?o.jsx($z,{children:o.jsx(Lr,{iconSlot:o.jsx(Fxe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(le,{as:ni,to:`/datasets/${e}?tab=experiments`,children:[o.jsx(Pc,{}),"Back to Dataset"]})})}):s?o.jsx($z,{children:o.jsx(Hi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Vt,{height:"full",children:[o.jsx(dVt,{experiment:n}),o.jsx(Vt.MainArea,{children:o.jsx(cVt,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function jhs(){const{datasetId:e}=Sr(),[t,n]=si(),{error:r}=n0(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&xs(r)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):r&&Ss(r)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})}):!e||!s||!a?o.jsx(fs,{children:o.jsx(Cy,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(fs,{children:o.jsx(Cy,{children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[100rem] content-start px-12",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(n1,{})," Dataset Experiments Comparison"]}),o.jsxs(ha.Description,{children:["Comparing"," ",o.jsx(ni,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(ni,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ha.Column,{children:o.jsxs(le,{as:ni,to:`/datasets/${e}`,children:[o.jsx(Pc,{}),"Back to Dataset"]})})]}),o.jsx(fhs,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function Nhs(){const{datasetId:e,itemId:t}=Sr(),{Link:n}=wn(),r=Ws(),{data:s,isLoading:a,error:i}=NAe(e??"",t??""),{updateItem:l,deleteItem:c}=Ii(),{data:u}=n0(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=g.useState(null),m=g.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",scorerOverrideEnabled:!1,scorerIds:[],requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",scorerOverrideEnabled:d.scorerIds!==void 0,scorerIds:d.scorerIds??[],requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),v=d?.datasetVersion??0,[y,b]=g.useState(!1),[x,S]=g.useState(m.input),[k,C]=g.useState(m.groundTruth),[_,E]=g.useState(m.metadata),[T,N]=g.useState(m.trajectory),[I,A]=g.useState(m.toolMocks),[R,L]=g.useState(m.scorerOverrideEnabled),[D,F]=g.useState(m.scorerIds),[H,B]=g.useState(m.requestContext),[U,V]=g.useState(v);v!==U&&(V(v),S(m.input),C(m.groundTruth),E(m.metadata),N(m.trajectory),A(m.toolMocks),L(m.scorerOverrideEnabled),F(m.scorerIds),B(m.requestContext));const[M,G]=g.useState(!1),q=Y=>{h(f?Y:Y.isLatest?null:Y)},$=()=>{h(null)},z=!f&&p!=null,Z=()=>{z||b(!0)},K=()=>{z||G(!0)},re=async()=>{if(!e||!t)return;let Y;try{Y=JSON.parse(x)}catch{Le.error("Input must be valid JSON");return}let te;if(k.trim())try{te=JSON.parse(k)}catch{Le.error("Ground Truth must be valid JSON");return}let ue;if(_.trim())try{ue=JSON.parse(_)}catch{Le.error("Metadata must be valid JSON");return}let de;const ce=T!==m.trajectory;if(ce&&T.trim())try{de=JSON.parse(T)}catch{Le.error("Expected Trajectory must be valid JSON");return}let ge;const be=I!==m.toolMocks;if(be&&I.trim())try{const Pe=JSON.parse(I);if(!Array.isArray(Pe)){Le.error("Tool Mocks must be a JSON array");return}ge=Pe}catch{Le.error("Tool Mocks must be valid JSON");return}let xe;const Ee=H!==m.requestContext;if(Ee&&H.trim())try{xe=JSON.parse(H)}catch{Le.error("Request Context must be valid JSON");return}const Oe=R!==m.scorerOverrideEnabled||R&&(D.length!==m.scorerIds.length||D.some((Pe,ie)=>Pe!==m.scorerIds[ie])),Ne=R?D:null;try{await l.mutateAsync({datasetId:e,itemId:t,input:Y,groundTruth:te,metadata:ue,...ce?{expectedTrajectory:de??null}:{},...be?{toolMocks:ge??[]}:{},...Oe?{scorerIds:Ne}:{},...Ee?{requestContext:xe}:{}}),Le.success("Item updated successfully"),b(!1)}catch(Pe){Le.error(`Failed to update item: ${Pe instanceof Error?Pe.message:"Unknown error"}`)}},ee=()=>{d&&(S(JSON.stringify(d.input,null,2)),C(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),E(d.metadata?JSON.stringify(d.metadata,null,2):""),N(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),A(d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):""),L(d.scorerIds!==void 0),F(d.scorerIds??[]),B(d.requestContext?JSON.stringify(d.requestContext,null,2):"")),b(!1)},J=async()=>{if(!(!e||!t))try{await c.mutateAsync({datasetId:e,itemId:t}),Le.success("Item deleted successfully"),G(!1),r(`/datasets/${e}`)}catch(Y){Le.error(`Failed to delete item: ${Y instanceof Error?Y.message:"Unknown error"}`)}},ae=p??d,fe=ae?{id:t??"",datasetId:e??"",datasetVersion:ae.datasetVersion,input:ae.input,groundTruth:ae.groundTruth,expectedTrajectory:ae.expectedTrajectory,scorerIds:ae.scorerIds,metadata:ae.metadata,createdAt:ae.createdAt,updatedAt:ae.updatedAt}:null;return i&&xs(i)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):i&&Ss(i)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(fs,{children:o.jsx(Cy,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Item not found"})})}):o.jsxs(o.Fragment,{children:[o.jsx(fs,{children:o.jsx("div",{className:"h-full overflow-hidden px-6 pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[60rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(BN,{}),t," ",o.jsx(za,{content:t})]}),o.jsx(ha.Description,{children:o.jsxs(Oo,{children:["Item of ",o.jsx(fy,{})," ",u?.name]})}),o.jsxs(ha.Description,{children:[o.jsxs(Oo,{children:[o.jsx(ylt,{})," Created at"," ",d?.createdAt?or(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(Oo,{children:[o.jsx(w_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ha.Column,{children:!y&&!f&&o.jsxs(Mr,{children:[o.jsxs(le,{onClick:Z,disabled:z,title:z?"Return to latest version to edit":void 0,children:[o.jsx(Plt,{})," Edit"]}),o.jsxs(le,{onClick:K,disabled:z,title:z?"Return to latest version to delete":void 0,children:[o.jsx(gu,{})," Delete"]})]})})]}),o.jsxs(dy,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Yr,{withRightSeparator:!y,children:[f&&d&&o.jsx(xn,{variant:"destructive",title:"Item deleted",children:o.jsxs(xn.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&z&&p&&o.jsx(xn,{variant:"warning",title:"Previous version",action:o.jsxs(xn.Button,{onClick:$,children:[o.jsx(plt,{})," Return to the latest version"]}),children:o.jsxs(xn.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(iVt,{inputValue:x,setInputValue:S,groundTruthValue:k,setGroundTruthValue:C,metadataValue:_,setMetadataValue:E,trajectoryValue:T,setTrajectoryValue:N,toolMocksValue:I,setToolMocksValue:A,scorerOverrideEnabled:R,setScorerOverrideEnabled:L,selectedScorerIds:D,setSelectedScorerIds:F,requestContextValue:H,setRequestContextValue:B,validationErrors:null,onSave:re,onCancel:ee,isSaving:l.isPending}):fe?o.jsx(PAe,{item:fe,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Yr,{children:o.jsx(phs,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:q,onCompareVersionsClick:Y=>{r(`/datasets/${e}/items/${t}/versions?ids=${Y.join(",")}`)},activeVersion:p?.datasetVersion??null})})]})]})})}),o.jsx(Rt,{open:M,onOpenChange:G,children:o.jsxs(Rt.Content,{children:[o.jsxs(Rt.Header,{children:[o.jsx(Rt.Title,{children:"Delete Item"}),o.jsx(Rt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Rt.Footer,{children:[o.jsx(Rt.Cancel,{children:"Cancel"}),o.jsx(Rt.Action,{onClick:J,children:c.isPending?"Deleting...":"Delete"})]})]})})]})}function Tet(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Ihs(){const{datasetId:e}=Sr(),[t,n]=si(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=n0(e??""),{Link:i}=wn(),[l,c]=g.useState(!1),{data:u}=QV(e??"",r[0]??""),{data:d}=QV(e??"",r[1]??"");return a&&xs(a)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):a&&Ss(a)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})}):!e||r.length<2?o.jsx(fs,{children:o.jsx(Cy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(fs,{children:[o.jsx(Dy,{owner:"dataset-items-compare",children:o.jsxs(le,{as:ni,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(Pc,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:X("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":l}),children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(n1,{}),"Compare Dataset Items"]}),o.jsx(ha.Description,{children:o.jsxs(Oo,{children:["Comparing ",r.length," items of"," ",o.jsx(ni,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ha.Column,{children:o.jsx(Mr,{children:o.jsx(le,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(zxe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(BGt,{})," Diff View"]})})})})]}),o.jsx(dy,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(g.Fragment,{children:[o.jsx(Ahs,{datasetId:e,itemId:f,Link:i,idx:p,itemIds:r,showContent:!l,onItemChange:h=>{const m=[...r];m[p]=h,n({items:m.join(",")})}}),p==0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},f))}),l&&u&&d&&o.jsx(KTe,{codeA:Tet(u),codeB:Tet(d)})]})})]})}function Ahs({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=QV(e,t),{data:u}=z1(e),d=new Set(s.filter((p,h)=>h!==r)),f=(u??[]).map(p=>({value:p.id,label:p.id,disabled:d.has(p.id)}));return o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{className:"flex gap-4",children:[o.jsxs(ma,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(va,{"aria-label":"Item",children:o.jsx(ga,{placeholder:"Select item"})}),o.jsx(ya,{children:f.map(p=>o.jsx(Rr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(le,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(w_,{}),"Versions"]})]}),i&&o.jsx(Yr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Hps,{item:l}),o.jsx(PAe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function jet(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,scorerIds:e.scorerIds??null,metadata:e.metadata??null},null,2)}function Rhs(){const{datasetId:e,itemId:t}=Sr(),[n,r]=si(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=n0(e??""),{Link:u}=wn(),{data:d}=NAe(e??"",t??""),{data:f}=wxe(e??"",t??"",i[0]??0,l?.version),{data:p}=wxe(e??"",t??"",i[1]??0,l?.version);return c&&xs(c)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})}):c&&Ss(c)?o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(fs,{children:o.jsx(Cy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(fs,{children:[o.jsx(Dy,{owner:"dataset-item-versions-compare",children:o.jsxs(le,{as:ni,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(Pc,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:X("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(n1,{}),"Compare Dataset Item Versions"]}),o.jsx(ha.Description,{children:o.jsxs(Oo,{children:["Comparing ",i.length," versions of"," ",o.jsx(ni,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ha.Column,{children:o.jsx(Mr,{children:o.jsx(le,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(zxe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(CQt,{})," Diff View"]})})})})]}),o.jsx(dy,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Phs,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(KTe,{codeA:jet(f),codeB:jet(p)})]})})]})}function Phs({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=wxe(e,t,n,r),p=new Set(a.filter((v,y)=>y!==l)),h=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",or(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(ea,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,scorerIds:d.scorerIds,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(w_,{className:"h-6 w-6 opacity-50"}),o.jsxs(ma,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(va,{"aria-label":"Version",className:"w-full",children:o.jsx(ga,{placeholder:"Select version"})}),o.jsx(ya,{children:h.map(v=>o.jsx(Rr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(Yr.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(PAe,{item:m,Link:i})})]})}function $hs(){const{datasetId:e}=Sr(),[t]=si(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=Ws(),{data:s,error:a}=n0(e??""),i=z1(e??"",void 0,n[0]??null),l=z1(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),p=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&xs(a))return o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})})});if(a&&Ss(a))return o.jsx(fs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(fs,{children:o.jsx(Cy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(fs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(ha,{children:[o.jsxs(ha.Column,{children:[o.jsxs(ha.Title,{children:[o.jsx(mKt,{})," Compare Dataset Versions"]}),o.jsx(ha.Description,{children:o.jsxs(Oo,{children:[o.jsx(w_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ha.Column,{children:o.jsxs(le,{as:ni,to:`/datasets/${e}`,children:[o.jsx(Pc,{}),"Back to Dataset"]})})]}),o.jsx(dy,{children:o.jsxs(Yr,{children:[o.jsx(ghs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(xhs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function Sxe({children:e,className:t}){return o.jsx("div",{className:X("flex flex-wrap gap-8",t),children:e})}function Mhs(e){if(!e||e.length<2)return null;const t=[...e].sort((i,l)=>new Date(i.createdAt).getTime()-new Date(l.createdAt).getTime()),n=Math.floor(t.length/2),r=n,s=t.length-n;if(r===0)return null;const a=(s-r)/r*100;return{changePct:Math.round(a*10)/10,prevValue:String(r)}}function Dhs({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=Mhs(n);return o.jsxs(o.Fragment,{children:[o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Scorers"}),i?o.jsx(es.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(f)}),o.jsx(es.NoChange,{message:"Static count"})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Datasets"}),l?o.jsx(es.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(p)}),o.jsx(es.NoChange,{message:"Static count"})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Avg Score"}),u?o.jsx(es.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(r)}),m?o.jsx(es.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(es.NoChange,{})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Experiments"}),c?o.jsx(es.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(h)}),v?o.jsx(es.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(es.NoChange,{})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Needs Review"}),d?o.jsx(es.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(a)}),a>0?o.jsx(es.NoChange,{message:"items pending review"}):o.jsx(es.NoChange,{message:"All caught up"})]}):o.jsx(es.NoData,{})]})]})}const Net="minmax(9rem,1fr) 1fr auto auto auto auto auto auto auto";function Lhs(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const Fhs={completed:"success",running:"warning",failed:"error",pending:"neutral"};function zhs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=wn(),u=g.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=g.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=g.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",v=!p||h.id.toLowerCase().includes(p)||(h.name??"").toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return v&&y&&b})},[d,s,u,a,i]);return r?o.jsx(ol,{columns:Net}):o.jsxs(me,{columns:Net,variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Experiment"}),o.jsx(me.TopCell,{children:"Dataset"}),o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{className:"text-center",children:"Items"}),o.jsx(me.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(me.TopCell,{className:"text-center",children:"Failed"}),o.jsx(me.TopCell,{className:"text-center",children:"Review"}),o.jsx(me.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??lS(p.datasetId)??p.datasetId:"—",m=p.status??"pending",v=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,x=b>0?Math.round(v/b*100):0;return o.jsxs(me.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(me.Cell,{children:o.jsx(rVt,{experiment:p})}),o.jsx(me.TextCell,{children:h}),o.jsx(me.Cell,{children:o.jsx("span",{className:"truncate",children:p.targetType&&p.targetId?`${p.targetType} ${p.targetId}`:"external"})}),o.jsx(me.Cell,{children:o.jsx(Og,{variant:Fhs[m]??"neutral",withDot:!0,children:m})}),o.jsx(me.TextCell,{className:"text-center",children:b}),o.jsx(me.TextCell,{className:"text-center",children:o.jsxs("span",{className:v>0?"text-accent1":"",children:[v," (",x,"%)"]})}),o.jsx(me.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(me.Cell,{className:"text-center",children:(()=>{const S=n?.get(p.id);if(!S)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=S.needsReview+S.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):S.needsReview>0?o.jsxs(ea,{size:"small",color:"yellow",children:[S.needsReview," pending"]}):o.jsxs(ea,{size:"small",color:"green",children:[S.complete,"/",k," reviewed"]})})()}),o.jsx(me.TextCell,{children:Lhs(p.createdAt)})]},p.id)})]})}const Bhs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Uhs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const Mz={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},Vhs=[{label:"Completed",color:Mz.completed},{label:"Running",color:Mz.running},{label:"Pending",color:Mz.pending},{label:"Failed",color:Mz.failed}];function qhs({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Qt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Qt.Loading,{}):r?o.jsx(Qt.Error,{message:"Failed to load experiments data"}):o.jsx(Qt.Content,{children:i?o.jsx(PN,{data:s,segments:Vhs,maxVal:a,fmt:l=>String(l)}):o.jsx(Qt.NoData,{message:"No experiments have been run yet"})})]})}const Hhs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Lf,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsx("div",{className:"flex flex-col items-center gap-2",children:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Oa,{})]})})})});function Whs({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(Vf,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs(Mr,{children:[o.jsx(Cc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Bhs],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Cc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(le,{onClick:l,size:"sm",variant:"default",children:[o.jsx(ws,{className:"size-3"})," Reset"]})]})]})}function Zhs(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=dh(),{data:l,isLoading:c,error:u}=Hg(),{data:d,isLoading:f,error:p}=TQ(),{data:h,isLoading:m,isError:v,error:y}=hss(n),{data:b,isLoading:x,isError:S,error:k}=DAe(),C=l?.datasets,_=d?.experiments,E=g.useMemo(()=>Ohs(b),[b]),T=i||u||p||y||k;return T&&xs(T)?o.jsx(cr,{children:o.jsx(Zs,{})}):T&&Ss(T)?o.jsx(cr,{children:o.jsx($s,{resource:"evaluation"})}):T?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load evaluation data",message:T.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{children:o.jsx(g4,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(N,I)=>r(A=>I==="from"?{...A,start:N}:{...A,end:N})})})})}),o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(Sxe,{children:o.jsx(Dhs,{scorers:s,datasets:C,experiments:_,avgScore:h?.avgScore??null,prevAvgScore:h?.prevAvgScore??null,totalNeedsReview:E.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(Ors,{summaryData:h?.summaryData??[],overTimeData:h?.overTimeData??[],scorerNames:h?.scorerNames??[],avgScore:h?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(Cfs,{experiments:_,isLoading:f,isError:!!p}),o.jsx(qhs,{experiments:_,datasets:C,isLoading:f,isError:!!p})]}),o.jsx(Shs,{reviewSummary:b,experiments:_,datasets:C,isLoading:x,isError:!!S})]})]})}function Ghs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState("all"),{data:i,isLoading:l,error:c}=Hg(),{data:u,isLoading:d,error:f}=TQ(),{data:p}=DAe(),h=g.useMemo(()=>i?.datasets??[],[i?.datasets]),m=g.useMemo(()=>u?.experiments??[],[u?.experiments]),v=g.useMemo(()=>Uhs(h),[h]),y=g.useMemo(()=>uVt(p),[p]),b=l||d,x=f||c;if(x&&xs(x))return o.jsx(cr,{children:o.jsx(Zs,{})});if(f&&Ss(f))return o.jsx(cr,{children:o.jsx($s,{resource:"experiments"})});if(c&&Ss(c))return o.jsx(cr,{children:o.jsx($s,{resource:"datasets"})});if(x)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load experiments",message:x.message})});if(m.length===0&&!b)return o.jsx(cr,{children:o.jsx(Hhs,{})});const S=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Whs,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:v,onReset:k,hasActiveFilters:S})}),o.jsx(zhs,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function Dz({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function Qhs(){const{experimentId:e}=Sr(),{data:t,isLoading:n}=TQ(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=GV(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=cQ({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&xs(l)?o.jsx(Dz,{children:o.jsx(Zs,{})}):l&&Ss(l)?o.jsx(Dz,{children:o.jsx($s,{resource:"datasets"})}):l&&NEe(l)||!n&&!s||!i&&!l&&!a?o.jsx(Dz,{children:o.jsx(Lr,{iconSlot:o.jsx(Fxe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(le,{as:ni,to:"/experiments",children:[o.jsx(Pc,{}),"Back to Experiments"]})})}):l?o.jsx(Dz,{children:o.jsx(Hi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Vt,{height:"full",children:[o.jsx(dVt,{experiment:a}),o.jsx(Vt.MainArea,{children:o.jsx(cVt,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function Yhs({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"font-mono text-xs",children:e.connectionId}),o.jsxs("div",{className:"text-xs text-gray-500",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),o.jsx("button",{type:"button",className:"text-red-600 underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function fVt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Yhs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Khs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,a])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(fVt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Xhs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:a,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-lg font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):a?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):i?o.jsx("p",{className:"text-red-600",children:String(i)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(Khs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(fVt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Jhs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>p(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>h(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const Iet=e=>e.authorId?.trim()||"shared",ems=(e,t)=>{if(!t||new Set(e.map(Iet)).size<=1)return null;const r=new Map;for(const a of e){const i=Iet(a);r.set(i,[...r.get(i)??[],a])}const s=Array.from(r.entries());return s.sort(([a],[i])=>a==="shared"?1:i==="shared"?-1:a.localeCompare(i)),s},tms=["*","tool-providers:*","tool-providers:admin"];function nms(){const{data:e}=Im();return e?.permissions?.some(t=>tms.includes(t))??!1}function rms(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=UI(),l=AZ(e||null),c=mDt(e||null,n||null),u=hDt(),d=dDt(),f=nms(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>ems(m,f),[m,f]),y=S=>{t(S),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=S=>{d.mutate({providerId:e,connectionId:S})};return o.jsxs("div",{className:"p-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(Jhs,{providers:p,toolkits:h,providerId:e,toolkit:n,label:s,providersLoading:i.isLoading,providersError:i.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:a,onConnect:b}),o.jsx(Xhs,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function sms({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsxs("div",{className:"w-full max-w-sm space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[o.jsx(sm,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function pVt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=oc(),{mutate:i,isPending:l,error:c}=MAr(),{mutate:u,isPending:d,error:f}=LAr(),{mutate:p,isPending:h}=x$t(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,S]=g.useState(""),[k,C]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:_}=s,E=_.type==="sso"||_.type==="both",T=_.type==="credentials"||_.type==="both",N=_.sso,I=_.signUpEnabled!==!1,A=m==="signin"||!I,R=A?l:d,L=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=dQ("/")},F=M=>{M.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},B=()=>{v(A?"signup":"signin")},U=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(If,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:_.description})]}):null,V=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(sms,{title:A?"Sign in to Mastra Studio":"Create your account",description:U,errorBanner:V,children:[T&&o.jsxs("form",{onSubmit:F,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 block text-sm",children:"Name"}),o.jsx(Nn,{id:"name",type:"text",value:y,onChange:M=>b(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"text-neutral4 block text-sm",children:"Email"}),o.jsx(Nn,{id:"email",type:"email",value:x,onChange:M=>S(M.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"text-neutral4 block text-sm",children:"Password"}),o.jsx(Nn,{id:"password",type:"password",value:k,onChange:M=>C(M.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:L.message}),o.jsx(le,{type:"submit",disabled:R,className:"w-full",size:"lg",children:R?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:B,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),E&&T&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),E&&N&&o.jsxs(le,{onClick:H,disabled:h,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),h?"Redirecting...":N.text||"Sign in"]})]})}function ams(){const[e]=si(),t=Ws(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",a=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(pVt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}function ims({collapsed:e,children:t}){return o.jsx("section",{className:X("flex flex-col overflow-hidden rounded-xl border border-border1 bg-surface2",e?"h-auto":"h-full"),children:t})}function oms({onClick:e,tooltip:t="Close panel",className:n}){return o.jsx(le,{size:"md",onClick:e,"aria-label":"Close Panel",tooltip:t,className:n,children:o.jsx(pu,{})})}function lms(){return pI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[he.className,he.propertyName]}]})}function cms(){const e=It.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.75rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-activeLineGutter":{backgroundColor:"transparent"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"}}),t=Wg.define([{tag:[he.comment,he.bracket],color:"var(--neutral2)"},{tag:[he.string,he.meta,he.regexp],color:"var(--accent1)"},{tag:[he.atom,he.bool,he.special(he.variableName)],color:"var(--accent6)"},{tag:[he.keyword,he.operator,he.tagName],color:"var(--accent2)"},{tag:[he.function(he.propertyName),he.propertyName],color:"var(--accent5)"},{tag:[he.definition(he.variableName),he.function(he.variableName),he.className,he.attributeName],color:"var(--accent3)"},{tag:[he.variableName,he.number],color:"var(--accent5)"},{tag:[he.name,he.quote],color:"var(--accent1)"}]);return[e,eS(t)]}const ums=()=>{const e=q_().resolvedTheme==="dark";return g.useMemo(()=>e?lms():cms(),[e])};function dms({codeStr:e="",title:t,icon:n,simplified:r=!1,className:s}){const a=ums(),[i,l]=g.useState(!1),c=g.useMemo(()=>{try{const f=JSON.parse(e);return kxe(f||"")}catch{return!1}},[e]),u=i?e?.replace(/\\n/g,`
641
641
  `):e,d=r||i;return!e||e==="null"?null:o.jsxs("div",{className:X("flex flex-col gap-2",s),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:X("flex items-center gap-1.5 text-ui-xs tracking-widest text-neutral2 uppercase","[&>svg]:size-3.5"),children:[n,t]}),o.jsxs(Mr,{children:[o.jsx(za,{content:e||"No content",size:"sm"}),c&&o.jsx(le,{size:"sm","aria-label":i?"Show escaped newlines":"Show multiline text",onClick:()=>l(f=>!f),children:i?o.jsx(z$,{}):o.jsx(I7,{})})]})]}),o.jsx("div",{className:"border-border1 bg-surface3 text-ui-sm text-neutral4 max-h-[30vh] overflow-hidden overflow-y-auto rounded-lg border p-3 break-all dark:border-white/10 dark:bg-black/20",children:d?o.jsx("div",{className:"text-neutral4 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:u})}):o.jsx(Ku,{extensions:[Fj(),It.lineWrapping],theme:a,value:e,editable:!1})})]})}function kxe(e){if(typeof e=="string"){const t=e.indexOf(`
642
- `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>kxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>kxe(t))}return!1}function fms({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function pms({className:e,children:t}){return o.jsx("div",{className:X("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function hms({className:e,children:t}){return o.jsx("h3",{className:X("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function mms({className:e,children:t}){return o.jsx("dl",{className:X("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function gms({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function vms({className:e,children:t}){return o.jsx("dd",{className:X("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function yms({className:e,children:t}){return o.jsx("dt",{className:X("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const bms=Object.assign(mms,{Key:gms,Value:vms,Header:yms});function xms({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(en,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function wms({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const Bi=Object.assign(ims,{Header:pms,Heading:hms,CloseButton:oms,LoadingData:xms,NoData:wms,Content:fms,KeyValueList:bms,CodeSection:dms}),mp=Bi.KeyValueList;function Sms(e){return e instanceof Date?e:new Date(e)}function kms({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=Sms(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Bi,{collapsed:d,children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Log ",o.jsx("b",{children:or(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(fH,{}):o.jsx(C1e,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(le,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(uH,{})}),o.jsx(le,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(d3,{})})]}),o.jsx(Bi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Bi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:X("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(A7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(za,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(A7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(za,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(mp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Entity Type"}),o.jsx(mp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Entity Name"}),o.jsx(mp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Service"}),o.jsx(mp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Environment"}),o.jsx(mp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Source"}),o.jsx(mp.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(mp.Key,{children:v}),o.jsx(mp.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Bi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Oms({error:e,resource:t,errorTitle:n}){if(xs(e))return o.jsx(Zs,{});if(Ss(e))return o.jsx($s,{resource:t});if(b4(e))return o.jsx(Lr,{iconSlot:o.jsx(R7,{}),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(y4(e,"logs"))return o.jsx(Lr,{iconSlot:o.jsx(R7,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Hi,{title:n,message:r??"Unknown error"})}function _ms({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:X("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const Cms={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function Ems({level:e}){const t=Cms[e];return o.jsx(jo,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Tms({entityType:e,className:t}){const n=X("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Vo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(nd,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Ud,{className:n,"aria-hidden":!0});default:return null}}function jms({entityType:e,entityName:t}){const n=e??"";return o.jsxs(jo,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(Tms,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Nms({message:e}){return o.jsx(jo,{height:"compact",className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function Ims({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(jo,{height:"compact",children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(STe,{children:t})}const Ql=Object.assign(T4,{Top:FZ,TopCell:cC,TopCellWithTooltip:zZ,TopCellSmart:n3t,RowWrapper:CTe,RowButton:j4,RowLink:t3t,Spacer:ETe,NoMatch:LZ,DateCell:kTe,TimeCell:OTe,LevelCell:Ems,EntityCell:jms,MessageCell:Nms,DataCell:Ims,NextPageLoading:DZ}),Aet="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Ams=36,Rms=8;function Pms({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=qUt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Ams,overscan:Rms}),d=g.useRef(t);if(g.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ol,{columns:Aet});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Ql,{columns:Aet,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ql.Top,{children:[o.jsx(Ql.TopCell,{children:"Date"}),o.jsx(Ql.TopCell,{children:"Time"}),o.jsx(Ql.TopCell,{children:"Level"}),o.jsx(Ql.TopCell,{children:"Entity"}),o.jsx(Ql.TopCell,{children:"Message"}),o.jsx(Ql.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ql.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ql.Spacer,{height:h}),f.map(v=>{const y=e[v.index];if(!y)return null;const b=a.get(y);if(!b)return null;const x=b===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":v.index,onClick:()=>l(y),featured:x,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Ql.DateCell,{timestamp:y.timestamp}),o.jsx(Ql.TimeCell,{timestamp:y.timestamp}),o.jsx(Ql.LevelCell,{level:y.level}),o.jsx(Ql.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Ql.MessageCell,{message:y.message}),o.jsx(Ql.DataCell,{data:y.data})]},b)}),o.jsx(Ql.Spacer,{height:m})]}),o.jsx(Ql.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function $ms({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Mms(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(mAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(pAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Mms(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 Dms={"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"},gie="MMM d, yyyy HH:mm",vie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Lms({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Dms[e]}`,description:vie}:t&&n?{title:`No logs between ${or(t,gie)} and ${or(n,gie)}`,description:vie}:t?{title:`No logs since ${or(t,gie)}`,description:vie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Fms=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Lms({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(R7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(T1e,{})]})})})},zms=20,Bms=1e4;function Ums(e,t,n){if(e?.pagination?.hasMore)return n+1}function Vms(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function qms(e){return y4(e.state.error,"logs")||b4(e.state.error)?!1:Bms}const Hms=({filters:e}={})=>{const t=He(),{inView:n,setRef:r}=Q_(),s=G1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:zms},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:Ums,select:Vms,retry:!1,refetchInterval:qms}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},Lz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},hVt=[{label:"Agent",entityType:Lz.AGENT},{label:"Workflow",entityType:Lz.WORKFLOW},{label:"Scorer",entityType:Lz.SCORER},{label:"Ingest",entityType:Lz.INGEST}],Wms=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Zx="rootEntityType",Jb="datePreset",ex="dateFrom",tx="dateTo",Zms=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"},CL=Object.keys(Nl),LAe=new Set(["tags"]),FAe="mastra:logs:saved-filters";function Gms(e,t=FAe){const n=Jms(e),r=e.get(Jb);r&&n.set(Jb,r);const s=e.get(ex);s&&n.set(ex,s);const a=e.get(tx);a&&n.set(tx,a);try{localStorage.setItem(t,n.toString())}catch{}}function Qms(e=FAe){try{localStorage.removeItem(e)}catch{}}function Ret(e=FAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Yms(e){if(e.has(Jb)||e.has(ex)||e.has(tx)||e.has(Zx))return!0;for(const t of CL)if(e.has(Nl[t]))return!0;return!1}function Kms({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:hVt.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:Wms.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Xms(e){const t=[],n=new Map([[Zx,"rootEntityType"]]);for(const s of CL)n.set(Nl[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),LAe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Jms(e){const t=new URLSearchParams,n=e.get(Zx);n&&t.set(Zx,n);for(const r of CL){const s=Nl[r];if(LAe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function egs(e,t){e.delete(Zx);for(const n of CL)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Zx,n.value);continue}const r=Nl[n.fieldId];if(r){if(LAe.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 tgs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function ngs(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 rgs="Filters setting for Logs saved",sgs="Filters setting for Logs cleared up";function ags(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Ret(r)!==null),c=g.useCallback(()=>{Gms(e,r),l(!0);const f=s?.saved??rgs;f!==!1&&Le.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Qms(r),l(!1);const f=s?.cleared??sgs;f!==!1&&Le.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Yms(e)))return;const f=Ret(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function igs(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 ogs(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,igs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function lgs(e,t,n,r){const s=g.useMemo(()=>ogs(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const Oxe="logId",_xe="traceId",Cxe="spanId",mP=1440*60*1e3,cgs={"last-24h":mP,"last-3d":3*mP,"last-7d":7*mP,"last-14d":14*mP,"last-30d":30*mP};function Fz(e){e.delete(Oxe),e.delete(_xe),e.delete(Cxe)}function ugs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const C=e.get(Jb);return C&&Zms.has(C)?C:"last-24h"},[e]),a=e.get(ex),i=e.get(tx),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_}if(s==="all")return;const C=cgs[s];return C?new Date(Date.now()-C):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(Oxe),f=e.get(_xe),p=e.get(Cxe),h=g.useMemo(()=>hVt.find(C=>C.entityType===e.get(Zx)),[e]),m=g.useMemo(()=>Xms(e),[e]),v=g.useCallback(C=>{t(_=>{const E=new URLSearchParams(_);for(const[T,N]of Object.entries(C)){const I=T==="logId"?Oxe:T==="traceId"?_xe:Cxe;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=g.useCallback(C=>{t(_=>{const E=new URLSearchParams(_);return egs(E,C),Fz(E),E},{replace:!0})},[t]),b=y,x=g.useCallback((C,_)=>{if(u.current!=="custom")return;const E=_==="from"?ex:tx;t(T=>{const N=new URLSearchParams(T);return C?N.set(E,C.toISOString()):N.delete(E),Fz(N),N},{replace:!0})},[t]),S=g.useCallback(C=>{u.current=C,t(_=>{const E=new URLSearchParams(_);return C==="last-24h"?(E.delete(Jb),E.delete(ex),E.delete(tx)):C==="custom"?E.set(Jb,"custom"):(E.set(Jb,C),E.delete(ex),E.delete(tx)),Fz(E),E},{replace:!0})},[t]),k=g.useCallback(()=>{t(C=>{const _=new URLSearchParams(C);_.delete(Zx);for(const E of CL)_.delete(Nl[E]);return _.delete(Jb),_.delete(ex),_.delete(tx),Fz(_),_},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,x,S,k,y])}const Cb=Bi.KeyValueList;function dgs({spanId:e,span:t,isLoading:n,onClose:r}){const s=CQ(t?.startedAt,t?.endedAt),a=JV(t?.startedAt),i=JV(t?.endedAt);return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading span..."}):t?o.jsxs(Bi.Content,{children:[o.jsxs(Cb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Cb.Key,{children:"Type"}),o.jsx(Cb.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(Cb.Key,{children:"Started"}),o.jsx(Cb.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Cb.Key,{children:"Ended"}),o.jsx(Cb.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Cb.Key,{children:"Duration"}),o.jsx(Cb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Bi.CodeSection,{title:"Input",icon:o.jsx(rme,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Output",icon:o.jsx(sme,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Metadata",icon:o.jsx(Ew,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Attributes",icon:o.jsx(Ew,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Bi.NoData,{children:"Span not found."})]})}function fgs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>bAe(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(yAe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Bi.NoData,{children:"No spans found for this trace."}):o.jsx(Bi.Content,{children:o.jsx(BUt,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function pgs(){const[e,t]=si(),n=ugs(e,t),r=ags(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=CAe(),{data:d=[],isPending:f}=kAe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=OAe(),{data:m=[],isPending:v}=_Ae(),y=g.useMemo(()=>Kms({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>tgs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:E}=Hms({filters:b}),{logIdMap:T,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=lgs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=EAe(n.featuredTraceId??null),{data:F,isLoading:H}=_L(n.featuredTraceId??"",n.featuredSpanId??""),B=g.useCallback(()=>n.applyFilterTokens(ngs(y,n.filterTokens)),[y,n]),U=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),M=g.useCallback((K,re)=>n.handleFeaturedChange({traceId:K,spanId:re}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),q=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),z=o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(g4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(gAe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx($ms,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:B,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(Oms,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(Fms,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(_ms,{logCollapsed:i,listSlot:o.jsx(Pms,{logs:x,isLoading:S,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:E,logIdMap:T,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(kms,{log:N,onClose:U,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(fgs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(dgs,{spanId:n.featuredSpanId,span:F?.span,isLoading:H,onClose:q}):null})]})}function hgs({server:e}){const{paths:t,Link:n}=wn(),s=He().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=p7t(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=Kh(e.name,50);return o.jsxs(me.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(me.NameCell,{children:f}),o.jsx(me.DescriptionCell,{children:a}),o.jsx(me.TextCell,{className:"text-center",children:u||""}),o.jsx(me.TextCell,{className:"text-center",children:c||""}),o.jsx(me.TextCell,{className:"text-center",children:d||""})]})}function mgs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ol,{columns:"auto 1fr auto auto auto"}):o.jsxs(me,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"URL"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Tools",short:o.jsx(Ud,{}),tooltip:"Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Workflows",short:o.jsx(nd,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(me.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(hgs,{server:s},s.id))]})}const ggs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Lf,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Oa,{})]})})}),vgs=()=>{const{data:e=[],isLoading:t,error:n}=nQ(),[r,s]=g.useState("");return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"MCP servers"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(cr,{children:o.jsx(ggs,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Vf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(mgs,{mcpServers:e,isLoading:t,search:r})]})},ygs=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function bgs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=wn(),i=g.useMemo(()=>ygs(e,t),[e,t]),l=g.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ol,{columns:"auto 1fr auto"}):o.jsxs(me,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"Description"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(me.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=Kh(c.id,50),d=Kh(c.description??"",200),f=c.agents.length;return o.jsxs(me.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(me.NameCell,{children:u}),o.jsx(me.DescriptionCell,{children:d}),o.jsx(me.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const xgs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Lf,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Oa,{})]})})}),wgs=()=>{const e=He();return Dn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new j_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Le.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Sgs=({toolId:e})=>{const{canExecute:t}=Wo(),n=t("tools"),{data:r={}}=Am(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=GIr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=wgs(),{requestContext:p}=ps();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Le.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?mm(Ex(c?.inputSchema)):vs({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(St,{className:"mb-4 h-8 w-48"}),o.jsx(St,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(VIe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function kgs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=zI(),{data:p={},isLoading:h,isError:m,error:v}=Am(),{navigate:y,paths:b}=wn();g.useEffect(()=>{if(d){const C=f instanceof Error?f.message:"Failed to load tools";Le.error(`Error loading tools: ${C}`)}},[d,f]),g.useEffect(()=>{if(m){const C=v instanceof Error?v.message:"Failed to load agents";Le.error(`Error loading agents: ${C}`)}},[m,v]);const x=new Map;Object.values(p).forEach(C=>{C.tools&&Object.values(C.tools).forEach(_=>{x.has(_.id)||x.set(_.id,_)})}),Object.values(c).forEach(C=>{x.has(C.id)||x.set(C.id,C)});const S=Array.from(x.values()).map(C=>({label:C.id,value:C.id})),k=C=>{t?t(C):C&&C!==e&&y(b.toolLink(C))};return o.jsx(Ll,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Ogs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(Cy,{children:o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Cy,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(ln,{icon:o.jsx(LUt,{className:"text-neutral6"}),className:"text-neutral4! rounded-r-sm",children:"Version"}),o.jsx(ln,{className:"text-neutral4! rounded-l-sm",children:t.version_detail.version})]}),o.jsx(ye,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(_gs,{server:t})})]})},_gs=({server:e})=>{const{data:t={},isLoading:n}=p7t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(Ue,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(yC,{})}),o.jsx(ye,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(Egs,{tool:a,serverId:e.id},s)})})]})};function Cgs(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const Egs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=wn(),a=U7t[e.toolType||"tool"],i=Cgs(e._meta);return o.jsxs(Hf,{onClick:()=>n.current?.click(),children:[o.jsx(pDt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Zf,{children:[o.jsx(Wf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(ln,{className:"py-0 text-[10px]",children:"App"})]})}),o.jsx(ih,{children:e.description})]})]})},Tgs=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=nQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Ogs,{isLoading:n,server:r})})};function jgs(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const Ngs=({toolId:e,serverId:t})=>{const{canExecute:n}=Wo(),r=n("tools"),s=He(),{data:a,isLoading:i,error:l}=$Ie(t,e),{mutateAsync:c,isPending:u,data:d}=ots(t,e),f=a?jgs(a._meta):void 0,{data:p}=gt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Le.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(St,{className:"mb-4 h-8 w-48"}),o.jsx(St,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=mm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Le.error("Failed to process tool input schema."),v=vs({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(f7t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(VIe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},Igs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=$Ie(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Ngs,{toolId:t,serverId:e})})},mVt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],$N="rootEntityType",MN={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"},jQ=Object.keys(MN),zAe="mastra:metrics:saved-filters";function Ags(e){const t=Dgs(e);try{localStorage.setItem(zAe,t.toString())}catch{}}function Rgs(){try{localStorage.removeItem(zAe)}catch{}}function gVt(){try{const e=localStorage.getItem(zAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Pgs(e){if(e.has($N))return!0;for(const t of jQ)if(e.has(MN[t]))return!0;return!1}function $gs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:mVt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Mgs(e){const t=[],n=new Map([[$N,"rootEntityType"]]);for(const s of jQ)n.set(MN[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Dgs(e){const t=new URLSearchParams,n=e.getAll($N);for(const r of n)t.append($N,r);for(const r of jQ){const s=MN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Lgs(e,t){e.delete($N);for(const n of jQ)e.delete(MN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?$N:MN[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const Fgs="Any";function Pet(e){const t=e.trim();return t===""||t===Fgs}const zgs=new Set(mVt.map(e=>e.entityType));function $et(e){const t=e.trim();return zgs.has(t)?t:void 0}function Bgs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Pet(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?$et(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Pet(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=$et(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const vVt=[{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"}],Ugs=new Set(vVt.map(e=>e.value));function Vgs(e){return typeof e=="string"&&(Ugs.has(e)||e==="custom")}const yVt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function NQ(){return g.useContext(yVt)}function qgs(e,t){return e!=="custom"?vVt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${or(t.from,"MMM d, yyyy")} – ${or(t.to,"MMM d, yyyy")}`:or(t.from,"MMM d, yyyy"):"Custom range"}function Hgs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>Bgs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=qgs(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(yVt.Provider,{value:m,children:e})}const Wgs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Zgs(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 Ggs(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 Qgs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=NQ(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(g4,{preset:Zgs(e),onPresetChange:i=>{const l=Ggs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:Wgs})}const Exe=1440*60*1e3,Ygs={"24h":Exe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Kgs(e,t,n){if(e!=="custom"){const r=Ygs[e]??Exe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Exe),end:t?.to??new Date(n)}}function Mm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=NQ(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>Kgs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function bVt(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function EL({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(KNn,{})})}function Xgs({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx($In,{})})}function Jgs(e){return e==="agents"||e==="workflows"||e==="tools"}function Met(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function evs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const tvs=[{dataKey:"p50",label:"p50",color:Hp.blue,aggregate:e=>({value:Met(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Hp.yellow,aggregate:e=>({value:Met(e,"p95"),suffix:"avg ms"})}];function yie({data:e,onPointClick:t}){return e.length===0?o.jsx(Qt.NoData,{message:"No latency data yet"}):o.jsx(WV,{data:e,series:tvs,onPointClick:t?n=>evs(n)?t(n):void 0:void 0})}function nvs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Qt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Qt.Actions,{children:h}):null]}),t?o.jsx(Qt.Loading,{}):n?o.jsx(Qt.Error,{message:"Failed to load latency data"}):o.jsx(Qt.Content,{children:m?o.jsxs(pc,{value:p,onValueChange:b=>{Jgs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(jr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(jr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(yie,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(yie,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(yie,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Qt.NoData,{message:"No latency data yet"})})]})}function rvs(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 svs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function xVt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=rvs(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function wVt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Det({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Pw,"branches"),xVt(a,$w,Mw,Dw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Hx,i),r.status&&a.set(Wx,r.status),$o(a,jl.entityName,r.entityName??n.entityName),$o(a,jl.threadId,r.threadId??n.threadId),$o(a,jl.resourceId,r.resourceId??n.resourceId),$o(a,jl.entityId,n.entityId),$o(a,jl.runId,n.runId),$o(a,jl.sessionId,n.sessionId),$o(a,jl.requestId,n.requestId),$o(a,jl.userId,n.userId),$o(a,jl.organizationId,n.organizationId),$o(a,jl.experimentId,n.experimentId),$o(a,jl.serviceName,n.serviceName),$o(a,jl.environment,n.environment),wVt(a,jl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function avs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;xVt(a,Jb,ex,tx,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Zx,i),$o(a,Nl.entityName,r.entityName??n.entityName),$o(a,Nl.threadId,r.threadId??n.threadId),$o(a,Nl.resourceId,r.resourceId??n.resourceId),$o(a,Nl.runId,n.runId),$o(a,Nl.sessionId,n.sessionId),$o(a,Nl.requestId,n.requestId),$o(a,Nl.userId,n.userId),$o(a,Nl.organizationId,n.organizationId),$o(a,Nl.experimentId,n.experimentId),$o(a,Nl.serviceName,n.serviceName),$o(a,Nl.environment,n.environment),wVt(a,Nl.tags,n.tags),r.status==="error"&&a.append(Nl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function sA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=NQ(),a=g.useCallback((c={})=>Det({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>avs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=svs(u,d);return Det({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const SVt="1h";async function bie(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:SVt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function ivs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([bie(e,"mastra_agent_duration_ms",t),bie(e,"mastra_workflow_duration_ms",t),bie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:SVt}}})}const Let={agents:Tc.AGENT,workflows:Tc.WORKFLOW_RUN,tools:Tc.TOOL};function ovs(){const{data:e,isLoading:t,isError:n}=ivs(),{getTracesHref:r,getBucketTracesHref:s}=sA(),{Link:a}=wn(),i=Ws();return o.jsx(nvs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Let[l]},c.tsMs,"1h"))},actions:l=>o.jsx(EL,{href:r({rootEntityType:Let[l]}),LinkComponent:a})})}function lvs(e){return e==="threads"||e==="resources"}function xie(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function cvs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Qt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Qt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Qt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Qt.Loading,{}):m.isError?o.jsx(Qt.Error,{message:"Failed to load memory data"}):o.jsx(Qt.Content,{children:o.jsxs(pc,{defaultTab:"threads",value:i,onValueChange:y=>{lvs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"threads",children:"Threads"}),o.jsx(jr,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(me,{columns:"auto auto auto auto auto",...vxe,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:xie(y.threadId)}),o.jsx(me.NumberCell,{children:y.resourceId?xie(y.resourceId):"—"}),o.jsx(me.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(me.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(me.NumberCell,{children:y.cost!=null?qp(y.cost,y.costUnit):"—"})]});return b?o.jsx(me.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(me.RowStatic,{children:x},y.key)})]}):o.jsx(Qt.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(me,{columns:"auto auto auto auto",...vxe,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:xie(y.resourceId)}),o.jsx(me.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(me.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(me.NumberCell,{children:y.cost!=null?qp(y.cost,y.costUnit):"—"})]});return b?o.jsx(me.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(me.RowStatic,{children:x},y.key)})]}):o.jsx(Qt.NoData,{message:"No resource activity yet"})})]})})]})}const wie=20;function uvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:wie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:wie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:wie})]),l=new Map,c=d=>rA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const Sie=20;function dvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:Sie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Sie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Sie})]),l=new Map,c=d=>rA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function fvs(){const e=uvs(),t=dvs(),{getTracesHref:n}=sA(),{Link:r}=wn();return o.jsx(cvs,{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 TL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(es,{children:[o.jsx(es.Label,{children:e}),o.jsx(es.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(es.Error,{}):s?o.jsx(es.Loading,{}):i?r!=null?o.jsx(es.Change,{changePct:r,prevValue:n}):o.jsx(es.NoChange,{}):o.jsx(es.NoData,{})]})}function pvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function hvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function mvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function gvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function vvs(){const{data:e,isLoading:t,isError:n}=bVt();return o.jsx(TL,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function yvs(){const{data:e,isLoading:t,isError:n}=mvs();return o.jsx(TL,{label:"Total Model Cost",value:e?.cost!=null?qp(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?qp(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function bvs(){const{data:e,isLoading:t,isError:n}=gvs();return o.jsx(TL,{label:"Total Tokens",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function xvs(){const{data:e,isLoading:t,isError:n}=hvs();return o.jsx(TL,{label:"Total Threads",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function wvs(){const{data:e,isLoading:t,isError:n}=pvs();return o.jsx(TL,{label:"Total Resources",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Svs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>kvs(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(mAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(pAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function kvs(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 Ovs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.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?qp(l):"—":c.size===1?u=l>0?qp(l,[...c][0]):"—":u="Mixed",o.jsx(Qt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Qt.Actions,{children:s}):null]}),t?o.jsx(Qt.Loading,{}):n?o.jsx(Qt.Error,{message:"Failed to load model usage data"}):o.jsx(Qt.Content,{children:i?o.jsxs(me,{columns:"auto auto auto auto auto auto",...vxe,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Model"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(me.NumberCell,{children:l.input}),o.jsx(me.NumberCell,{children:l.output}),o.jsx(me.NumberCell,{children:l.cacheRead}),o.jsx(me.NumberCell,{children:l.cacheWrite}),o.jsx(me.NumberCell,{highlight:!0,children:l.cost!=null?qp(l.cost,l.costUnit):"—"})]});return c?o.jsx(me.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(me.RowStatic,{children:u},l.model)})]}):o.jsx(Qt.NoData,{message:"No model usage data yet"})})]})}function _vs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>rA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:al(f.input),output:al(f.output),cacheRead:al(f.cacheRead),cacheWrite:al(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function Cvs(){const{data:e,isLoading:t,isError:n}=_vs(),{getTracesHref:r}=sA(),{Link:s}=wn();return o.jsx(Ovs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Tc.AGENT}),actions:o.jsx(EL,{href:r({rootEntityType:Tc.AGENT}),LinkComponent:s})})}function Evs(e){return e==="tokens"||e==="cost"}function Tvs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&v>0;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Qt.Summary,{value:qp(v,m),label:"Total cost"}):o.jsx(Qt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Qt.Actions,{children:s}):null]}),t?o.jsx(Qt.Loading,{}):n?o.jsx(Qt.Error,{message:"Failed to load token usage data"}):o.jsx(Qt.Content,{children:u?o.jsxs(pc,{defaultTab:"tokens",value:i,onValueChange:b=>{Evs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"tokens",children:"Tokens"}),o.jsx(jr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(PN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Hp.blueDark},{label:"Output",color:Hp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:al})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(PN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Hp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>qp(b,m)}):o.jsx(Qt.NoData,{message:"No cost data yet"})})]}):o.jsx(Qt.NoData,{message:"No token usage data yet"})})]})}function jvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>rA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function Nvs(){const{data:e,isLoading:t,isError:n}=jvs(),{getTracesHref:r}=sA(),{Link:s}=wn();return o.jsx(Tvs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Tc.AGENT,entityName:a.name}),actions:o.jsx(EL,{href:r({rootEntityType:Tc.AGENT}),LinkComponent:s})})}function Txe(e,t=al){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const Ivs=[{dataKey:"input",label:"Input tokens",color:Hp.blue,aggregate:Txe("input")},{dataKey:"output",label:"Output tokens",color:Hp.yellow,aggregate:Txe("output")}];function Avs(e){return e==="tokens"||e==="cost"}function Rvs({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,C)=>k+C.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,C)=>k+(C.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:Hp.purple,aggregate:Txe("cost",k=>qp(k,v))}];return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Qt.Summary,{value:qp(y,v),label:"Total cost"}):o.jsx(Qt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Qt.Actions,{children:s}):null]}),n?o.jsx(Qt.Loading,{}):r?o.jsx(Qt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Qt.Content,{children:u?o.jsxs(pc,{defaultTab:"tokens",value:a,onValueChange:k=>{Avs(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"tokens",children:"Tokens"}),o.jsx(jr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(WV,{data:c,series:Ivs})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(WV,{data:p,series:S}):o.jsx(Qt.NoData,{message:"No cost data yet"})})]}):o.jsx(Qt.NoData,{message:"No token usage data yet"})})]})}function Pvs(e){return e==="24h"?"1h":"1d"}function $vs(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function Fet(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function Mvs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function Dvs(){const e=He(),{datePreset:t,filters:n,filterKey:r}=Mm(),s=Pvs(t);return gt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Fet(l,a.series[0],"input"),Fet(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:$vs(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:Mvs(u)}}),interval:s}}})}function Lvs(){const{data:e,isLoading:t,isError:n}=Dvs(),{getTracesHref:r}=sA(),{Link:s}=wn();return o.jsx(Rvs,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(EL,{href:r(),LinkComponent:s})})}function kie({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(PN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Hp.blueDark},{label:"Errors",color:Hp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:al})}function Fvs({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Qt.Summary,{value:al(f),label:"Total runs"}),u?o.jsx(Qt.Actions,{children:u}):null]}),t?o.jsx(Qt.Loading,{}):n?o.jsx(Qt.Error,{message:"Failed to load trace volume data"}):o.jsx(Qt.Content,{children:d?o.jsxs(pc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"agents",children:"Agents"}),o.jsx(jr,{value:"workflows",children:"Workflows"}),o.jsx(jr,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(kie,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Qt.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(kie,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Qt.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(kie,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Qt.NoData,{message:"No tool data yet"})})]}):o.jsx(Qt.NoData,{message:"No trace volume data yet"})})]})}async function Oie(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=rA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function zvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([Oie(e,"mastra_agent_duration_ms",t),Oie(e,"mastra_workflow_duration_ms",t),Oie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const zz={agents:Tc.AGENT,workflows:Tc.WORKFLOW_RUN,tools:Tc.TOOL};function Bvs(){const{data:e,isLoading:t,isError:n}=zvs(),{getTracesHref:r,getLogsHref:s}=sA(),{Link:a}=wn();return o.jsx(Fvs,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:zz[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:zz[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(EL,{href:r({rootEntityType:zz[i]}),LinkComponent:a}),o.jsx(Xgs,{href:s({rootEntityType:zz[i],status:"error"}),LinkComponent:a})]})})}const _ie="period",Bz="dateFrom",Uz="dateTo";function Uvs(){const[e,t]=si(),n=e.get(_ie),r=Vgs(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(Bz)),p=d(e.get(Uz));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>Mgs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(_ie):p.set(_ie,d),d!=="custom"&&(p.delete(Bz),p.delete(Uz)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(Bz,d.from.toISOString()):p.delete(Bz),d?.to?p.set(Uz,d.to.toISOString()):p.delete(Uz),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Lgs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,Pgs(e)))return;const d=gVt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Hgs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(Vvs,{})})}function Vvs(){const[e]=si(),{error:t,isLoading:n}=bVt(),{filterTokens:r,setFilterTokens:s}=NQ(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=jAe(),{data:d,isLoading:f}=CAe(),{data:p,isLoading:h}=kAe(),{data:m,isLoading:v}=_Ae(),{data:y,isLoading:b}=OAe(),x=g.useMemo(()=>$gs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[S,k]=g.useState(()=>gVt()!==null),C=g.useCallback(()=>{Ags(e),k(!0),Le.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{Rgs(),k(!1),Le.success("Filters setting for Metrics cleared up")},[]),E=g.useCallback(()=>{s([])},[s]),T=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&xs(t)?o.jsx(cr,{children:o.jsx(Zs,{})}):t&&Ss(t)?o.jsx(cr,{children:o.jsx($s,{resource:"metrics"})}):t?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Qgs,{}),o.jsx(gAe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(Svs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:T,onRemoveAll:E,onSave:C,onRemoveSaved:S?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(xn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(xn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(Sxe,{children:[o.jsx(vvs,{}),o.jsx(yvs,{}),o.jsx(bvs,{}),o.jsx(xvs,{}),o.jsx(wvs,{})]}),o.jsxs(Sxe,{children:[o.jsx(Cvs,{}),o.jsx(Nvs,{}),o.jsx(Lvs,{}),o.jsx(fvs,{}),o.jsx(Bvs,{}),o.jsx(ovs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Lf,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Oa,{})]})})})]})}const qvs=50;function Hvs(){const{paths:e}=wn(),{isCmsAvailable:t}=uS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=q7t({page:s,perPage:qvs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=g.useCallback(()=>{u||a(v=>v+1)},[u]),h=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&xs(c)?o.jsx(cr,{children:o.jsx(Zs,{})}):c&&Ss(c)?o.jsx(cr,{children:o.jsx($s,{resource:"prompt blocks"})}):c?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(cr,{children:o.jsx(Sas,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Vf,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(le,{as:ni,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Zr,{}),"Create Prompt"]})]})}),o.jsx(was,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function Wvs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx(Zts,{children:o.jsx(Qbe,{})})})})}const Zvs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:WGt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:glt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Oa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:gj,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:Olt,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:vlt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Gvs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:Zvs.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(Oa,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function Qvs(){const{data:e={},isLoading:t,error:n}=dh(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&xs(n))return o.jsx(cr,{children:o.jsx(Zs,{})});if(n&&Ss(n))return o.jsx(cr,{children:o.jsx($s,{resource:"scorers"})});if(n)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(cr,{children:o.jsx(jrs,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Irs,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(Trs,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Yvs(){const{scorerId:e}=Sr(),[t,n]=si(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=ars(e),{data:d={},isLoading:f,error:p}=Am(),{isLoading:h,error:m}=Zy(),{data:v=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k}=srs({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),C=g.useMemo(()=>c?.agentIds?.filter(V=>d[V]).map(V=>({value:V,label:d[V].name,type:"AGENT"}))||[],[c?.agentIds,d]),_=g.useMemo(()=>c?.workflowIds?.map(V=>({value:V,label:V,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...C,..._],[C,_]),T=t.get("entity")??"all",N=E.find(V=>V.value===T);N&&N.value!==i?.value&&l(N),g.useEffect(()=>{if(u){const V=u instanceof Error?u.message:"Failed to load scorer";Le.error(`Error loading scorer: ${V}`)}},[u]),g.useEffect(()=>{if(p){const V=p instanceof Error?p.message:"Failed to load agents";Le.error(`Error loading agents: ${V}`)}},[p]),g.useEffect(()=>{if(m){const V=m instanceof Error?m.message:"Failed to load workflows";Le.error(`Error loading workflows: ${V}`)}},[m]);const I=V=>{V?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",V.value),G})};g.useEffect(()=>{const V=t.get("scoreId")??void 0;if(V===s)return;if(!V){a(void 0);return}v.find(G=>G.id===V)&&a(V)},[t,v]);const A=g.useCallback(V=>{a(V||void 0),n(M=>{const G=new URLSearchParams(M);return V?G.set("scoreId",V):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=xs(u)||xs(p)||xs(m),L=u&&Ss(u),D=!R&&!L&&(u||p||m),F=!y&&v.length===0,H=i?.value!=="all",B=c?.scorer?.source==="stored"?o.jsx(Dy,{owner:"scorer-detail",children:o.jsxs(le,{variant:"default",as:ni,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(cm,{})," Edit"]})}):null;if(R||L||D||F&&!H){const V=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Vt,{width:"wide",height:"full",children:[B,o.jsx(Vt.MainArea,{isCentered:!0,children:R?o.jsx(Zs,{}):L?o.jsx($s,{resource:"scorers"}):D?o.jsx(Hi,{title:"Failed to load scorer",message:V}):o.jsx(Kns,{})})]})}return o.jsxs(Vt,{width:"wide",children:[B,o.jsx(Vt.TopArea,{children:o.jsx(Xns,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(V=>{const M=new URLSearchParams(V);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(Yns,{scores:v,isLoading:y,selectedScoreId:s,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function Kvs({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:X("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Dt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-neutral3 text-sm",children:t})]}),s]})}const kVt=[{value:"dark",label:"Dark",Icon:OYt},{value:"light",label:"Light",Icon:MKt},{value:"system",label:"System",Icon:Ilt}],Xvs=e=>kVt.some(t=>t.value===e);function Jvs({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const eys=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=hH(),{theme:r,setTheme:s}=q_();return o.jsx(Vt,{width:"narrow",children:o.jsxs(Vt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(jbe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Kvs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ma,{value:r,onValueChange:a=>{Xvs(a)&&s(a)},children:[o.jsx(va,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ga,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(ya,{children:kVt.map(a=>o.jsx(Rr,{value:a.value,children:o.jsx(Jvs,{option:a})},a.value))})]})})}),o.jsx(jbe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(d3t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function tys(){const[e]=si(),t=Ws(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(pVt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const OVt=e=>o.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})});function nys(e){return e.replace(/\/$/,"").split("/").pop()}function IQ({children:e,className:t}){return o.jsx("div",{className:X("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function rys({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:X("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:X("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:X("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:X("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:X("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:X("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:X("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Vo,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Ud,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Alt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(HN,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(yC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:X("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(OVt,{})," ",nys(a.githubUrl)]})})]},a.slug)})})}function sys({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:X("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:X("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(bN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Cc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Cc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(le,{onClick:c,children:["Reset ",o.jsx(ws,{})]})]})}function ays(){const{data:e,isLoading:t}=Ynr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(fs,{children:[o.jsx(q1e,{children:o.jsxs(Fyt,{children:[o.jsx(Ue,{children:o.jsx(ey,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(sys,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(rys,{templates:y,linkComponent:ni,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const iys="1.62.0-alpha.8";function oys({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(Cf,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(wQt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(IQ,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function lys({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(IQ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:X("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Rlt,{})]}),o.jsx(Cc,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:X("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(en,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(IO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(IO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(x7t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(le,{className:X("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(en,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(wm,{})]})})]})})}function cys({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:X("grid mt-8 items-center"),children:o.jsxs("div",{className:X("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(ey,{}),o.jsx("h2",{className:X({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:X("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:X("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(Qx,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Vxe,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(OVt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(FIe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function zet(e){switch(e){case"running":return o.jsx(en,{size:"sm","aria-hidden":!0});case"success":return o.jsx(yy,{"aria-hidden":!0});case"failed":return o.jsx(pu,{"aria-hidden":!0});default:return null}}function uys(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function dys({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:X("flex size-4 items-center justify-center self-center [&>svg]:size-4",Wr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(uys,{}):zet(e)}):o.jsx("span",{className:X("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Wr.colors,Wr.transform,Wr.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:zet(e)})}function fys({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Wr.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:X("flex min-w-6 justify-end text-ui-md",Wr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:X("text-ui-md",Wr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:X("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(dys,{status:e.status,variant:r})]})}function pys({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(fys,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function hys({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:X("relative flex h-8 items-center justify-end",Wr.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:X("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",Wr.colors,Wr.transform,Wr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(en,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",Wr.colors),children:[n," of ",t," steps completed"]})]})}function mys({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(IQ,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(hys,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:X("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(PYt,{}),l||"Something went wrong"]}),u&&o.jsx(pys,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(en,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function gys({name:e,installedEntities:t}){return o.jsxs(IQ,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Rlt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx(FIe,{data:t})]})}function vys(){const{templateSlug:e}=Sr(),[t,n]=si(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[S,k]=g.useState(!1),[C,_]=g.useState(!1),[E,T]=g.useState([]),{data:N,isLoading:I}=Knr({repoOrSlug:e,owner:"mastra-ai"}),R=iys?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=Xnr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:F,isLoading:H}=Jnr(),{mutateAsync:B,isPending:U}=err(),{mutateAsync:V}=trr(),{streamInstall:M,streamResult:G,isStreaming:q}=rrr(F),{observeInstall:$,streamResult:z,isStreaming:Z}=srr(F);g.useEffect(()=>{const te=t.get("runId");te&&!v&&!h&&!q&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:te}),x(te),V({runId:te}).then(ue=>{const de=ue.snapshot;if(de?.status==="success"&&de?.result?.success)y(!0);else if(de?.result?.success===!1)if(de?.result?.validationResults&&!de?.result?.validationResults?.valid&&de?.result?.validationResults?.remainingErrors>0){const{remainingErrors:ge,errors:be}=de.result.validationResults,xe=`Template installation completed but ${ge} validation issue${ge>1?"s":""} remain unresolved.`;m(xe),T(be||[])}else{const ge=de?.result?.message||de?.result?.error||"Template installation failed";m(typeof ge=="string"?ge:String(ge))}}).catch(ue=>{console.error("❌ Failed to fetch run details:",ue),m("Failed to retrieve installation status after reload")}))},[t,v,h,q,Z,V]),g.useEffect(()=>{const te=t.get("runId"),ue=t.get("resume"),de=t.get("provider");if(te&&ue==="true"&&de&&!q&&!Z&&!S&&!C&&F){x(te),k(!0);try{V({runId:te}).then(ce=>{if(ce.snapshot?.status==="running")return $.mutateAsync({runId:te})}).then(()=>{n(ce=>{const ge=new URLSearchParams(ce);return ge.delete("resume"),ge})}).catch(ce=>{console.error("❌ Failed to resume template installation:",ce),ce.message?.includes("404")||ce.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(ce){console.error("❌ Auto-resume failed with error:",ce),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,q,Z,S,C,F,V,$,n]);const K=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],re=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(te=>te).join(", "):"n/a",icon:o.jsx(Ud,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(te=>te).join(", "):"n/a",icon:o.jsx(Vo,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(te=>te).join(", "):"n/a",icon:o.jsx(HN,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Fv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(qN,{})}],ee=[{...re[0]},{...re[1]},{...re[2]}].filter(te=>te.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const te=G||z;te?.phase==="error"&&te?.error&&m(typeof te.error=="string"?te.error:String(te.error))},[G?.phase,G?.error,z?.phase,z?.error]);const J=te=>{s(te)},ae=async te=>(i(te.provider),c(te.modelId),{message:"Model updated successfully"}),fe=async()=>{const te=Object.entries(u).reduce((ue,[de,ce])=>(ce===""&&ue.push(de),ue),[]);if(te.length>0){p(te);return}if(N){m(null),y(!1),x(""),_(!0);try{const de={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ce}=await B({});x(ce),n(ge=>{const be=new URLSearchParams(ge);return be.set("runId",ce),be.set("resume","true"),be.set("provider",r||"openai"),be}),await M.mutateAsync({inputData:de,selectedModel:{provider:a,modelId:l},runId:ce})}catch(ue){_(!1),m(ue?.message||"Template installation failed"),console.error("Template installation failed",ue)}}},Y=te=>{const{name:ue,value:de}=te.target;de.trim()===""?p(ce=>[...ce,ue]):p(ce=>ce.filter(ge=>ge!==ue)),d(ce=>({...ce,[ue]:de}))};return o.jsx(fs,{children:o.jsx("div",{className:X("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(cys,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:re,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(q||Z)&&o.jsx(mys,{name:N.title,streamResult:Z?z:G,runId:b,workflowInfo:F}),v&&o.jsx(gys,{name:N.title,installedEntities:ee,linkComponent:ni}),h&&o.jsx(oys,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||z?.validationResults?.errors}),!q&&!Z&&!v&&!h&&o.jsx(lys,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:fe,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:U,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const yys=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Fss,{toolId:e,agentId:t})})},bys=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Sgs,{toolId:e})})};function xys(){const{traceId:e}=Sr(),[t,n]=si(),r=Ws(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=g.useState(s??null),[d,f]=g.useState(),[p,h]=g.useState(i),[m,v]=g.useState(0),[y,b]=g.useState(!1),{data:x,isLoading:S,error:k}=EAe(e),C=g.useMemo(()=>x?.spans??[],[x?.spans]),_=g.useMemo(()=>C.find(Y=>Y.parentSpanId==null),[C]),E=jAe(),T=bxe({traceIds:[e],enabled:!E.isLoading&&E.supportsMetrics,autoRefetch:!1}),{data:N,isLoading:I}=_L(e,c??"");g.useEffect(()=>v(0),[e,c]);const{data:A,isLoading:R}=dh(),{data:L,isLoading:D}=F7t({traceId:e,spanId:c??void 0,page:m}),[F,H]=g.useState(0);g.useEffect(()=>H(0),[e,c]);const{data:B,isLoading:U}=JUt({traceId:e,page:F});g.useEffect(()=>{if(l&&L?.scores&&!d){const Y=L.scores.find(te=>te.id===l);Y&&f(Y)}},[l,L?.scores,d]);const V=g.useCallback(Y=>{const te=new URLSearchParams(t);for(const[ue,de]of Object.entries(Y))de===null||de===""?te.delete(ue):te.set(ue,de);n(te,{replace:!0})},[t,n]),M=g.useCallback(Y=>{const te=Y??null,ue=te===c;u(te),ue||(f(void 0),h("details"),V({spanId:te,tab:null,scoreId:null}))},[c,V]),G=g.useCallback(()=>{u(null),f(void 0),h("details"),V({spanId:null,tab:null,scoreId:null})},[V]),q=g.useCallback(Y=>{u(Y),f(void 0),h("details"),V({spanId:Y,tab:null,scoreId:null})},[V]),{handlePreviousSpan:$,handleNextSpan:z}=TAe(C,c,q),Z=g.useCallback(Y=>{const te=Y;h(te),f(void 0),V({tab:te==="details"?null:te,scoreId:null})},[V]),K=g.useCallback(Y=>{f(Y),V({scoreId:Y.id})},[V]),re=g.useCallback(()=>{f(void 0),V({scoreId:null})},[V]),ee=g.useCallback(()=>{r("/traces")},[r]),J=g.useCallback(()=>{h("scoring"),_&&c!==_.spanId?(u(_.spanId),f(void 0),V({spanId:_.spanId,tab:"scoring",scoreId:null})):V({tab:"scoring"})},[_,c,V]),ae=_?o.jsx(Dy,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(le,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:J,children:[o.jsx(hGt,{}),"Evaluate"]}),o.jsxs(le,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(Id,{}),"Save"]})]})}):null,fe=_?o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{className:"w-full",children:o.jsx(DUt,{rootSpan:_,usage:T.data?.get(e),numOfCol:3})})}):null;return k?o.jsxs(Vt,{height:"full",children:[ae,fe&&o.jsx(Vt.TopArea,{children:fe}),o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(UUt,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Vt,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[ae,fe&&o.jsx(Vt.TopArea,{children:fe}),o.jsx(GUt,{rootSpanId:_?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:X("mt-4 grid min-h-0 items-stretch gap-4 overflow-hidden",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(xAe,{traceId:e,spans:C,isLoading:S,onClose:ee,onSpanSelect:M,onEvaluateTrace:J,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&o.jsxs("div",{className:X("grid h-full max-h-full min-h-0 gap-4 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(vAe,{traceId:e,spanId:c,span:N?.span,isLoading:I,onClose:G,onPrevious:$,onNext:z,activeTab:p,onTabChange:Z,feedbackTabBadge:B?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(YUt,{feedbackData:B,onPageChange:H,isLoadingFeedbackData:U}),scoringTabBadge:L?.pagination?.total??void 0,scoringTabSlot:({span:Y,traceId:te,spanId:ue})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(XUt,{traceId:te,isTopLevelSpan:!Y.parentSpanId,spanId:ue,entityType:Y.attributes?.agentId||Y.entityType===Tc.AGENT?"Agent":Y.attributes?.workflowId||Y.entityType===Tc.WORKFLOW_RUN?"Workflow":void 0,scorers:A,isLoadingScorers:R}),o.jsx(KUt,{scoresData:L,onPageChange:v,isLoadingScoresData:D,onScoreSelect:K})]})}),d&&o.jsx(LIe,{score:d,onClose:re})]})]})]})}function wys(){const{data:e,isLoading:t,error:n}=Zy(),[r,s]=g.useState("");return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"workflows"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(cr,{children:o.jsx(nHr,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Vf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(le,{as:ni,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(RD,{}),"Schedules"]})]})}),o.jsx(tHr,{workflows:e||{},isLoading:t,search:r})]})}const Sys={active:"bg-accent1",paused:"bg-accent3"},kys={active:"text-accent1",paused:"text-accent3"},_Vt=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Sys[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${kys[e]}`,children:e})]}),dj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),Z2=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function CVt({status:e}){const{icon:t,color:n}=Oys(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function Oys(e){switch(e){case"success":return{icon:o.jsx(da,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(ws,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(en,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(rq,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Lf,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(mj,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const Bet="auto auto auto auto 1fr";function _ys(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function Cys(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const Eys=3e4,Tys=5*6e4;function jys({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=wn();return t?o.jsx(ol,{columns:Bet}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(me,{columns:Bet,className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Run"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Started"}),o.jsx(me.TopCell,{children:"Duration"}),o.jsx(me.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=Cys(u),f=`Scheduled ${dj(c.scheduledFireAt)} — published ${dj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),v=!p&&m>Eys&&m<=Tys,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),x=o.jsx("span",{className:b?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",children:x}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(Cf,{size:14}),"publish failed"]}):c.run?o.jsx(CVt,{status:c.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),h?o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Cf,{size:14})})}),o.jsx(On,{children:h})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:Z2(c.actualFireAt)}),v?o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Cf,{size:14})})}),o.jsxs(On,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:c.run?o.jsx("span",{children:_ys(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(me.Cell,{height:"compact",children:" "})]});return b?o.jsx(me.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(me.RowStatic,{children:S},y)}),o.jsx(me.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Nys=e=>{const t=He();return gt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Uet=25,Iys=e=>{const t=He(),{inView:n,setRef:r}=Q_(),s=G1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Uet,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Uet))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},Ays=e=>{const t=He(),n=Br();return Dn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),Le.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Le.error(r.message)}})};function Vz({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function Rys(){const{scheduleId:e}=Sr(),{paths:t}=wn(),{data:n,error:r}=Nys(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=Iys(e),d=Ays(e);if(r&&xs(r))return o.jsx(cr,{children:o.jsx(Zs,{})});if(r&&Ss(r))return o.jsx(cr,{children:o.jsx($s,{resource:"schedules"})});if(r)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{className:"justify-end",children:o.jsxs(Vt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(le,{as:ni,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Pc,{}),"Back to schedules"]}),f?o.jsx(le,{as:ni,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(le,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(Zxe,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Wp,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(Vz,{label:p?"Agent":"Workflow",children:f?o.jsx(ni,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(ni,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(Vz,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(Vz,{label:"Status",children:o.jsx(_Vt,{status:n.status})}),o.jsx(Vz,{label:"Next fire",children:o.jsx("span",{title:dj(n.nextFireAt),children:Z2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ye,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Hi,{title:"Failed to load trigger history",message:i.message}):o.jsx(jys,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Vet="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function Pys({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=wn(),a=g.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(ol,{columns:Vet}):o.jsxs(me,{columns:Vet,variant:"striped",className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Schedule ID"}),o.jsx(me.TopCell,{children:"Cron"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Next fire"}),o.jsx(me.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(me.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(me.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(me.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(me.NameCell,{children:i.workflowId??i.agentId}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:i.id,children:i.id})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsx(_Vt,{status:i.status})}),o.jsx(me.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:dj(i.nextFireAt),children:Z2(i.nextFireAt)})}),o.jsx(me.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(CVt,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:dj(i.lastFireAt),children:i.lastFireAt?Z2(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:dj(i.lastFireAt),children:Z2(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function $ys({workflowId:e}={}){const{data:t,isLoading:n,error:r}=U1e(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Hi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(Vf,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(Pys,{schedules:t??[],isLoading:n,search:s})})]})}function Mys(){const[e]=si(),t=e.get("workflowId")??void 0,{error:n}=U1e(t?{workflowId:t}:{});return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"schedules"})}):o.jsx(Vt,{children:o.jsx("div",{className:"h-full",children:o.jsx($ys,{workflowId:t})})})}function Dys({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=vOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=h_t(r),[d]=m_t(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=G4t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(p_t,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(dje,{position:"bottom-left"}),o.jsx(v_t,{variant:oy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(en,{})})})}function Lys(){const{stepDetail:e,closeStepDetail:t}=lW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(g9,{className:"h-4 w-4",style:{color:Au.map}}),e.type==="nested-graph"&&o.jsx(nd,{className:"h-4 w-4",style:{color:Au.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(ws,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(q2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(gOe,{children:o.jsx(Dys,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function Fys(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function zys(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 Bys({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ye,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(Ue,{children:o.jsx(rq,{})}),"Step suspended"]}),o.jsx(ln,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?mm(Ex(i.resumeSchema)):cf(fr(),yf());return o.jsx(Uys,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function Uys({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Ue,{children:o.jsx(CYt,{})}),"The step is asking"]}),o.jsxs(Fd,{open:a,onOpenChange:i,children:[o.jsxs(Xu,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Ue,{children:o.jsx(aa,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:zys(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:Fys(e.suspendPayload)})]}),o.jsx(Ju,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Hr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Ue,{children:o.jsx(jYt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(GB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Wp,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function Vys(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(ql),{runId:a}=Sr(),i=O_t(e,r??""),l=fer(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(Bys,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const qys=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),Hys=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),Wys=e=>e.includes("."),Zys=e=>e==="input"||e.endsWith(".input"),Gys=1;function Qys(e){return`${Number((e/1e3).toPrecision(3))}s`}function Yys(e,t){const n=Object.entries(e).filter(([i])=>!Zys(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,p=Math.max(d/a*100,Gys);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:Wys(i)}})}const Kys=({status:e})=>o.jsxs(Ue,{children:[e==="success"&&o.jsx(qys,{className:"text-accent1"}),e==="failed"&&o.jsx(Hys,{className:"text-accent2"}),e==="suspended"&&o.jsx(rq,{className:"text-accent3"}),e==="waiting"&&o.jsx(gpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(gpe,{className:"text-icon3"}),e==="running"&&o.jsx(ca,{className:"text-accent6 animate-spin"})]}),Xys={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function EVt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const qet=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},Jys=e=>{const t=e;return F4t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},ebs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=Jys(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:X("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(Kys,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(NKt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(jV,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:EVt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${Xys[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(TKt,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:Qys(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function tbs(){const{steps:e}=M4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=wH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Kyt(f,{enabled:!l});const p=Yys(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Na,{className:X("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(ebs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:qet(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:qet(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(C_t,{data:u.data,title:`${EVt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const nbs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=lW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(nLt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(Vys,{}),o.jsx(tbs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(Lys,{})})]})},Het=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=H3(e);return r&&xs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})}):r&&Ss(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"workflows"})}):o.jsx($Oe,{children:o.jsx(nbs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function rbs(e,t){if(e==null)return{};var n,r,s=NSt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function jxe(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 sbs(e){if(Array.isArray(e))return jxe(e)}function abs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function ibs(e,t){if(e){if(typeof e=="string")return jxe(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)?jxe(e,t):void 0}}function obs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
642
+ `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>kxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>kxe(t))}return!1}function fms({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function pms({className:e,children:t}){return o.jsx("div",{className:X("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function hms({className:e,children:t}){return o.jsx("h3",{className:X("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function mms({className:e,children:t}){return o.jsx("dl",{className:X("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function gms({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function vms({className:e,children:t}){return o.jsx("dd",{className:X("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function yms({className:e,children:t}){return o.jsx("dt",{className:X("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const bms=Object.assign(mms,{Key:gms,Value:vms,Header:yms});function xms({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(en,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function wms({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const Bi=Object.assign(ims,{Header:pms,Heading:hms,CloseButton:oms,LoadingData:xms,NoData:wms,Content:fms,KeyValueList:bms,CodeSection:dms}),mp=Bi.KeyValueList;function Sms(e){return e instanceof Date?e:new Date(e)}function kms({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=Sms(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Bi,{collapsed:d,children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Log ",o.jsx("b",{children:or(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(fH,{}):o.jsx(C1e,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(le,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(uH,{})}),o.jsx(le,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(d3,{})})]}),o.jsx(Bi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Bi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:X("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(A7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(za,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(A7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(za,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(mp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Entity Type"}),o.jsx(mp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Entity Name"}),o.jsx(mp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Service"}),o.jsx(mp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Environment"}),o.jsx(mp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Source"}),o.jsx(mp.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(mp.Key,{children:v}),o.jsx(mp.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Bi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Oms({error:e,resource:t,errorTitle:n}){if(xs(e))return o.jsx(Zs,{});if(Ss(e))return o.jsx($s,{resource:t});if(b4(e))return o.jsx(Lr,{iconSlot:o.jsx(R7,{}),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(y4(e,"logs"))return o.jsx(Lr,{iconSlot:o.jsx(R7,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Hi,{title:n,message:r??"Unknown error"})}function _ms({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:X("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const Cms={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function Ems({level:e}){const t=Cms[e];return o.jsx(jo,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Tms({entityType:e,className:t}){const n=X("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Vo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(nd,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Ud,{className:n,"aria-hidden":!0});default:return null}}function jms({entityType:e,entityName:t}){const n=e??"";return o.jsxs(jo,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(Tms,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Nms({message:e}){return o.jsx(jo,{height:"compact",className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function Ims({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(jo,{height:"compact",children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(STe,{children:t})}const Ql=Object.assign(T4,{Top:FZ,TopCell:cC,TopCellWithTooltip:zZ,TopCellSmart:n3t,RowWrapper:CTe,RowButton:j4,RowLink:t3t,Spacer:ETe,NoMatch:LZ,DateCell:kTe,TimeCell:OTe,LevelCell:Ems,EntityCell:jms,MessageCell:Nms,DataCell:Ims,NextPageLoading:DZ}),Aet="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Ams=36,Rms=8;function Pms({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=qUt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Ams,overscan:Rms}),d=g.useRef(t);if(g.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ol,{columns:Aet});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Ql,{columns:Aet,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ql.Top,{children:[o.jsx(Ql.TopCell,{children:"Date"}),o.jsx(Ql.TopCell,{children:"Time"}),o.jsx(Ql.TopCell,{children:"Level"}),o.jsx(Ql.TopCell,{children:"Entity"}),o.jsx(Ql.TopCell,{children:"Message"}),o.jsx(Ql.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ql.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ql.Spacer,{height:h}),f.map(v=>{const y=e[v.index];if(!y)return null;const b=a.get(y);if(!b)return null;const x=b===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":v.index,onClick:()=>l(y),featured:x,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Ql.DateCell,{timestamp:y.timestamp}),o.jsx(Ql.TimeCell,{timestamp:y.timestamp}),o.jsx(Ql.LevelCell,{level:y.level}),o.jsx(Ql.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Ql.MessageCell,{message:y.message}),o.jsx(Ql.DataCell,{data:y.data})]},b)}),o.jsx(Ql.Spacer,{height:m})]}),o.jsx(Ql.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function $ms({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Mms(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(mAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(pAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Mms(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 Dms={"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"},gie="MMM d, yyyy HH:mm",vie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Lms({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Dms[e]}`,description:vie}:t&&n?{title:`No logs between ${or(t,gie)} and ${or(n,gie)}`,description:vie}:t?{title:`No logs since ${or(t,gie)}`,description:vie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Fms=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Lms({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(R7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(T1e,{})]})})})},zms=20,Bms=1e4;function Ums(e,t,n){if(e?.pagination?.hasMore)return n+1}function Vms(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function qms(e){return y4(e.state.error,"logs")||b4(e.state.error)?!1:Bms}const Hms=({filters:e}={})=>{const t=He(),{inView:n,setRef:r}=Q_(),s=G1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:zms},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:Ums,select:Vms,retry:!1,refetchInterval:qms}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},Lz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},hVt=[{label:"Agent",entityType:Lz.AGENT},{label:"Workflow",entityType:Lz.WORKFLOW},{label:"Scorer",entityType:Lz.SCORER},{label:"Ingest",entityType:Lz.INGEST}],Wms=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Zx="rootEntityType",Jb="datePreset",ex="dateFrom",tx="dateTo",Zms=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"},CL=Object.keys(Nl),LAe=new Set(["tags"]),FAe="mastra:logs:saved-filters";function Gms(e,t=FAe){const n=Jms(e),r=e.get(Jb);r&&n.set(Jb,r);const s=e.get(ex);s&&n.set(ex,s);const a=e.get(tx);a&&n.set(tx,a);try{localStorage.setItem(t,n.toString())}catch{}}function Qms(e=FAe){try{localStorage.removeItem(e)}catch{}}function Ret(e=FAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Yms(e){if(e.has(Jb)||e.has(ex)||e.has(tx)||e.has(Zx))return!0;for(const t of CL)if(e.has(Nl[t]))return!0;return!1}function Kms({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:hVt.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:Wms.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Xms(e){const t=[],n=new Map([[Zx,"rootEntityType"]]);for(const s of CL)n.set(Nl[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),LAe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Jms(e){const t=new URLSearchParams,n=e.get(Zx);n&&t.set(Zx,n);for(const r of CL){const s=Nl[r];if(LAe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function egs(e,t){e.delete(Zx);for(const n of CL)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Zx,n.value);continue}const r=Nl[n.fieldId];if(r){if(LAe.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 tgs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function ngs(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 rgs="Filters setting for Logs saved",sgs="Filters setting for Logs cleared up";function ags(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Ret(r)!==null),c=g.useCallback(()=>{Gms(e,r),l(!0);const f=s?.saved??rgs;f!==!1&&Le.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Qms(r),l(!1);const f=s?.cleared??sgs;f!==!1&&Le.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Yms(e)))return;const f=Ret(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function igs(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 ogs(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,igs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function lgs(e,t,n,r){const s=g.useMemo(()=>ogs(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const Oxe="logId",_xe="traceId",Cxe="spanId",mP=1440*60*1e3,cgs={"last-24h":mP,"last-3d":3*mP,"last-7d":7*mP,"last-14d":14*mP,"last-30d":30*mP};function Fz(e){e.delete(Oxe),e.delete(_xe),e.delete(Cxe)}function ugs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const C=e.get(Jb);return C&&Zms.has(C)?C:"last-24h"},[e]),a=e.get(ex),i=e.get(tx),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_}if(s==="all")return;const C=cgs[s];return C?new Date(Date.now()-C):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(Oxe),f=e.get(_xe),p=e.get(Cxe),h=g.useMemo(()=>hVt.find(C=>C.entityType===e.get(Zx)),[e]),m=g.useMemo(()=>Xms(e),[e]),v=g.useCallback(C=>{t(_=>{const E=new URLSearchParams(_);for(const[T,N]of Object.entries(C)){const I=T==="logId"?Oxe:T==="traceId"?_xe:Cxe;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=g.useCallback(C=>{t(_=>{const E=new URLSearchParams(_);return egs(E,C),Fz(E),E},{replace:!0})},[t]),b=y,x=g.useCallback((C,_)=>{if(u.current!=="custom")return;const E=_==="from"?ex:tx;t(T=>{const N=new URLSearchParams(T);return C?N.set(E,C.toISOString()):N.delete(E),Fz(N),N},{replace:!0})},[t]),S=g.useCallback(C=>{u.current=C,t(_=>{const E=new URLSearchParams(_);return C==="last-24h"?(E.delete(Jb),E.delete(ex),E.delete(tx)):C==="custom"?E.set(Jb,"custom"):(E.set(Jb,C),E.delete(ex),E.delete(tx)),Fz(E),E},{replace:!0})},[t]),k=g.useCallback(()=>{t(C=>{const _=new URLSearchParams(C);_.delete(Zx);for(const E of CL)_.delete(Nl[E]);return _.delete(Jb),_.delete(ex),_.delete(tx),Fz(_),_},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,x,S,k,y])}const Cb=Bi.KeyValueList;function dgs({spanId:e,span:t,isLoading:n,onClose:r}){const s=CQ(t?.startedAt,t?.endedAt),a=JV(t?.startedAt),i=JV(t?.endedAt);return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading span..."}):t?o.jsxs(Bi.Content,{children:[o.jsxs(Cb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Cb.Key,{children:"Type"}),o.jsx(Cb.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(Cb.Key,{children:"Started"}),o.jsx(Cb.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Cb.Key,{children:"Ended"}),o.jsx(Cb.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Cb.Key,{children:"Duration"}),o.jsx(Cb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Bi.CodeSection,{title:"Input",icon:o.jsx(rme,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Output",icon:o.jsx(sme,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Metadata",icon:o.jsx(Ew,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Bi.CodeSection,{title:"Attributes",icon:o.jsx(Ew,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Bi.NoData,{children:"Span not found."})]})}function fgs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>bAe(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(yAe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Bi,{children:[o.jsxs(Bi.Header,{children:[o.jsxs(Bi.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Bi.CloseButton,{onClick:r})]}),n?o.jsx(Bi.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Bi.NoData,{children:"No spans found for this trace."}):o.jsx(Bi.Content,{children:o.jsx(BUt,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function pgs(){const[e,t]=si(),n=ugs(e,t),r=ags(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=CAe(),{data:d=[],isPending:f}=kAe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=OAe(),{data:m=[],isPending:v}=_Ae(),y=g.useMemo(()=>Kms({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>tgs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:E}=Hms({filters:b}),{logIdMap:T,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=lgs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=EAe(n.featuredTraceId??null),{data:F,isLoading:H}=_L(n.featuredTraceId??"",n.featuredSpanId??""),B=g.useCallback(()=>n.applyFilterTokens(ngs(y,n.filterTokens)),[y,n]),U=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),M=g.useCallback((K,re)=>n.handleFeaturedChange({traceId:K,spanId:re}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),q=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),z=o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(g4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(gAe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx($ms,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:B,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(Oms,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(Fms,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Vt,{width:"wide",height:"full",children:[z,o.jsx(_ms,{logCollapsed:i,listSlot:o.jsx(Pms,{logs:x,isLoading:S,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:E,logIdMap:T,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(kms,{log:N,onClose:U,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(fgs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(dgs,{spanId:n.featuredSpanId,span:F?.span,isLoading:H,onClose:q}):null})]})}function hgs({server:e}){const{paths:t,Link:n}=wn(),s=He().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=p7t(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=Kh(e.name,50);return o.jsxs(me.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(me.NameCell,{children:f}),o.jsx(me.DescriptionCell,{children:a}),o.jsx(me.TextCell,{className:"text-center",children:u||""}),o.jsx(me.TextCell,{className:"text-center",children:c||""}),o.jsx(me.TextCell,{className:"text-center",children:d||""})]})}function mgs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ol,{columns:"auto 1fr auto auto auto"}):o.jsxs(me,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"URL"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Tools",short:o.jsx(Ud,{}),tooltip:"Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Workflows",short:o.jsx(nd,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(me.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(hgs,{server:s},s.id))]})}const ggs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Lf,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Oa,{})]})})}),vgs=()=>{const{data:e=[],isLoading:t,error:n}=nQ(),[r,s]=g.useState("");return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"MCP servers"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(cr,{children:o.jsx(ggs,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Vf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(mgs,{mcpServers:e,isLoading:t,search:r})]})},ygs=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function bgs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=wn(),i=g.useMemo(()=>ygs(e,t),[e,t]),l=g.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ol,{columns:"auto 1fr auto"}):o.jsxs(me,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"Description"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(Vo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(me.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=Kh(c.id,50),d=Kh(c.description??"",200),f=c.agents.length;return o.jsxs(me.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(me.NameCell,{children:u}),o.jsx(me.DescriptionCell,{children:d}),o.jsx(me.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const xgs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Lf,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Oa,{})]})})}),wgs=()=>{const e=He();return Dn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new j_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Le.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Sgs=({toolId:e})=>{const{canExecute:t}=Wo(),n=t("tools"),{data:r={}}=Am(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=GIr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=wgs(),{requestContext:p}=ps();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Le.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?mm(Ex(c?.inputSchema)):vs({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(St,{className:"mb-4 h-8 w-48"}),o.jsx(St,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(VIe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function kgs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=zI(),{data:p={},isLoading:h,isError:m,error:v}=Am(),{navigate:y,paths:b}=wn();g.useEffect(()=>{if(d){const C=f instanceof Error?f.message:"Failed to load tools";Le.error(`Error loading tools: ${C}`)}},[d,f]),g.useEffect(()=>{if(m){const C=v instanceof Error?v.message:"Failed to load agents";Le.error(`Error loading agents: ${C}`)}},[m,v]);const x=new Map;Object.values(p).forEach(C=>{C.tools&&Object.values(C.tools).forEach(_=>{x.has(_.id)||x.set(_.id,_)})}),Object.values(c).forEach(C=>{x.has(C.id)||x.set(C.id,C)});const S=Array.from(x.values()).map(C=>({label:C.id,value:C.id})),k=C=>{t?t(C):C&&C!==e&&y(b.toolLink(C))};return o.jsx(Ll,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Ogs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(Cy,{children:o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Cy,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ye,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(ln,{icon:o.jsx(LUt,{className:"text-neutral6"}),className:"text-neutral4! rounded-r-sm",children:"Version"}),o.jsx(ln,{className:"text-neutral4! rounded-l-sm",children:t.version_detail.version})]}),o.jsx(ye,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(ln,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ye,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(za,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(_gs,{server:t})})]})},_gs=({server:e})=>{const{data:t={},isLoading:n}=p7t(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(Ue,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(yC,{})}),o.jsx(ye,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(Egs,{tool:a,serverId:e.id},s)})})]})};function Cgs(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const Egs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=wn(),a=U7t[e.toolType||"tool"],i=Cgs(e._meta);return o.jsxs(Hf,{onClick:()=>n.current?.click(),children:[o.jsx(pDt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Zf,{children:[o.jsx(Wf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(ln,{className:"py-0 text-[10px]",children:"App"})]})}),o.jsx(ih,{children:e.description})]})]})},Tgs=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=nQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Ogs,{isLoading:n,server:r})})};function jgs(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const Ngs=({toolId:e,serverId:t})=>{const{canExecute:n}=Wo(),r=n("tools"),s=He(),{data:a,isLoading:i,error:l}=$Ie(t,e),{mutateAsync:c,isPending:u,data:d}=ots(t,e),f=a?jgs(a._meta):void 0,{data:p}=gt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Le.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(St,{className:"mb-4 h-8 w-48"}),o.jsx(St,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=mm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Le.error("Failed to process tool input schema."),v=vs({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(f7t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(VIe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},Igs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=$Ie(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Ngs,{toolId:t,serverId:e})})},mVt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],$N="rootEntityType",MN={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"},jQ=Object.keys(MN),zAe="mastra:metrics:saved-filters";function Ags(e){const t=Dgs(e);try{localStorage.setItem(zAe,t.toString())}catch{}}function Rgs(){try{localStorage.removeItem(zAe)}catch{}}function gVt(){try{const e=localStorage.getItem(zAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Pgs(e){if(e.has($N))return!0;for(const t of jQ)if(e.has(MN[t]))return!0;return!1}function $gs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:mVt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Mgs(e){const t=[],n=new Map([[$N,"rootEntityType"]]);for(const s of jQ)n.set(MN[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Dgs(e){const t=new URLSearchParams,n=e.getAll($N);for(const r of n)t.append($N,r);for(const r of jQ){const s=MN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Lgs(e,t){e.delete($N);for(const n of jQ)e.delete(MN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?$N:MN[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const Fgs="Any";function Pet(e){const t=e.trim();return t===""||t===Fgs}const zgs=new Set(mVt.map(e=>e.entityType));function $et(e){const t=e.trim();return zgs.has(t)?t:void 0}function Bgs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Pet(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?$et(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Pet(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=$et(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const vVt=[{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"}],Ugs=new Set(vVt.map(e=>e.value));function Vgs(e){return typeof e=="string"&&(Ugs.has(e)||e==="custom")}const yVt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function NQ(){return g.useContext(yVt)}function qgs(e,t){return e!=="custom"?vVt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${or(t.from,"MMM d, yyyy")} – ${or(t.to,"MMM d, yyyy")}`:or(t.from,"MMM d, yyyy"):"Custom range"}function Hgs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>Bgs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=qgs(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(yVt.Provider,{value:m,children:e})}const Wgs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Zgs(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 Ggs(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 Qgs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=NQ(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(g4,{preset:Zgs(e),onPresetChange:i=>{const l=Ggs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:Wgs})}const Exe=1440*60*1e3,Ygs={"24h":Exe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Kgs(e,t,n){if(e!=="custom"){const r=Ygs[e]??Exe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Exe),end:t?.to??new Date(n)}}function Mm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=NQ(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>Kgs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function bVt(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function EL({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(KNn,{})})}function Xgs({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx($In,{})})}function Jgs(e){return e==="agents"||e==="workflows"||e==="tools"}function Met(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function evs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const tvs=[{dataKey:"p50",label:"p50",color:Hp.blue,aggregate:e=>({value:Met(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Hp.yellow,aggregate:e=>({value:Met(e,"p95"),suffix:"avg ms"})}];function yie({data:e,onPointClick:t}){return e.length===0?o.jsx(Qt.NoData,{message:"No latency data yet"}):o.jsx(WV,{data:e,series:tvs,onPointClick:t?n=>evs(n)?t(n):void 0:void 0})}function nvs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Qt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Qt.Actions,{children:h}):null]}),t?o.jsx(Qt.Loading,{}):n?o.jsx(Qt.Error,{message:"Failed to load latency data"}):o.jsx(Qt.Content,{children:m?o.jsxs(pc,{value:p,onValueChange:b=>{Jgs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(jr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(jr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(yie,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(yie,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(yie,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Qt.NoData,{message:"No latency data yet"})})]})}function rvs(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 svs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function xVt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=rvs(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function wVt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Det({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Pw,"branches"),xVt(a,$w,Mw,Dw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Hx,i),r.status&&a.set(Wx,r.status),$o(a,jl.entityName,r.entityName??n.entityName),$o(a,jl.threadId,r.threadId??n.threadId),$o(a,jl.resourceId,r.resourceId??n.resourceId),$o(a,jl.entityId,n.entityId),$o(a,jl.runId,n.runId),$o(a,jl.sessionId,n.sessionId),$o(a,jl.requestId,n.requestId),$o(a,jl.userId,n.userId),$o(a,jl.organizationId,n.organizationId),$o(a,jl.experimentId,n.experimentId),$o(a,jl.serviceName,n.serviceName),$o(a,jl.environment,n.environment),wVt(a,jl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function avs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;xVt(a,Jb,ex,tx,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Zx,i),$o(a,Nl.entityName,r.entityName??n.entityName),$o(a,Nl.threadId,r.threadId??n.threadId),$o(a,Nl.resourceId,r.resourceId??n.resourceId),$o(a,Nl.runId,n.runId),$o(a,Nl.sessionId,n.sessionId),$o(a,Nl.requestId,n.requestId),$o(a,Nl.userId,n.userId),$o(a,Nl.organizationId,n.organizationId),$o(a,Nl.experimentId,n.experimentId),$o(a,Nl.serviceName,n.serviceName),$o(a,Nl.environment,n.environment),wVt(a,Nl.tags,n.tags),r.status==="error"&&a.append(Nl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function sA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=NQ(),a=g.useCallback((c={})=>Det({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>avs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=svs(u,d);return Det({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const SVt="1h";async function bie(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:SVt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function ivs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([bie(e,"mastra_agent_duration_ms",t),bie(e,"mastra_workflow_duration_ms",t),bie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:SVt}}})}const Let={agents:Tc.AGENT,workflows:Tc.WORKFLOW_RUN,tools:Tc.TOOL};function ovs(){const{data:e,isLoading:t,isError:n}=ivs(),{getTracesHref:r,getBucketTracesHref:s}=sA(),{Link:a}=wn(),i=Ws();return o.jsx(nvs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Let[l]},c.tsMs,"1h"))},actions:l=>o.jsx(EL,{href:r({rootEntityType:Let[l]}),LinkComponent:a})})}function lvs(e){return e==="threads"||e==="resources"}function xie(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function cvs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Qt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Qt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Qt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Qt.Loading,{}):m.isError?o.jsx(Qt.Error,{message:"Failed to load memory data"}):o.jsx(Qt.Content,{children:o.jsxs(pc,{defaultTab:"threads",value:i,onValueChange:y=>{lvs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"threads",children:"Threads"}),o.jsx(jr,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(me,{columns:"auto auto auto auto auto",...vxe,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:xie(y.threadId)}),o.jsx(me.NumberCell,{children:y.resourceId?xie(y.resourceId):"—"}),o.jsx(me.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(me.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(me.NumberCell,{children:y.cost!=null?qp(y.cost,y.costUnit):"—"})]});return b?o.jsx(me.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(me.RowStatic,{children:x},y.key)})]}):o.jsx(Qt.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(me,{columns:"auto auto auto auto",...vxe,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:xie(y.resourceId)}),o.jsx(me.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(me.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(me.NumberCell,{children:y.cost!=null?qp(y.cost,y.costUnit):"—"})]});return b?o.jsx(me.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(me.RowStatic,{children:x},y.key)})]}):o.jsx(Qt.NoData,{message:"No resource activity yet"})})]})})]})}const wie=20;function uvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:wie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:wie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:wie})]),l=new Map,c=d=>rA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const Sie=20;function dvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:Sie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Sie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Sie})]),l=new Map,c=d=>rA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function fvs(){const e=uvs(),t=dvs(),{getTracesHref:n}=sA(),{Link:r}=wn();return o.jsx(cvs,{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 TL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(es,{children:[o.jsx(es.Label,{children:e}),o.jsx(es.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(es.Error,{}):s?o.jsx(es.Loading,{}):i?r!=null?o.jsx(es.Change,{changePct:r,prevValue:n}):o.jsx(es.NoChange,{}):o.jsx(es.NoData,{})]})}function pvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function hvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function mvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function gvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function vvs(){const{data:e,isLoading:t,isError:n}=bVt();return o.jsx(TL,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function yvs(){const{data:e,isLoading:t,isError:n}=mvs();return o.jsx(TL,{label:"Total Model Cost",value:e?.cost!=null?qp(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?qp(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function bvs(){const{data:e,isLoading:t,isError:n}=gvs();return o.jsx(TL,{label:"Total Tokens",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function xvs(){const{data:e,isLoading:t,isError:n}=hvs();return o.jsx(TL,{label:"Total Threads",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function wvs(){const{data:e,isLoading:t,isError:n}=pvs();return o.jsx(TL,{label:"Total Resources",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Svs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>kvs(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(mAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(pAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function kvs(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 Ovs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.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?qp(l):"—":c.size===1?u=l>0?qp(l,[...c][0]):"—":u="Mixed",o.jsx(Qt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Qt.Actions,{children:s}):null]}),t?o.jsx(Qt.Loading,{}):n?o.jsx(Qt.Error,{message:"Failed to load model usage data"}):o.jsx(Qt.Content,{children:i?o.jsxs(me,{columns:"auto auto auto auto auto auto",...vxe,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Model"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(me.NumberCell,{children:l.input}),o.jsx(me.NumberCell,{children:l.output}),o.jsx(me.NumberCell,{children:l.cacheRead}),o.jsx(me.NumberCell,{children:l.cacheWrite}),o.jsx(me.NumberCell,{highlight:!0,children:l.cost!=null?qp(l.cost,l.costUnit):"—"})]});return c?o.jsx(me.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(me.RowStatic,{children:u},l.model)})]}):o.jsx(Qt.NoData,{message:"No model usage data yet"})})]})}function _vs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>rA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:al(f.input),output:al(f.output),cacheRead:al(f.cacheRead),cacheWrite:al(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function Cvs(){const{data:e,isLoading:t,isError:n}=_vs(),{getTracesHref:r}=sA(),{Link:s}=wn();return o.jsx(Ovs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Tc.AGENT}),actions:o.jsx(EL,{href:r({rootEntityType:Tc.AGENT}),LinkComponent:s})})}function Evs(e){return e==="tokens"||e==="cost"}function Tvs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&v>0;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Qt.Summary,{value:qp(v,m),label:"Total cost"}):o.jsx(Qt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Qt.Actions,{children:s}):null]}),t?o.jsx(Qt.Loading,{}):n?o.jsx(Qt.Error,{message:"Failed to load token usage data"}):o.jsx(Qt.Content,{children:u?o.jsxs(pc,{defaultTab:"tokens",value:i,onValueChange:b=>{Evs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"tokens",children:"Tokens"}),o.jsx(jr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(PN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Hp.blueDark},{label:"Output",color:Hp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:al})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(PN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Hp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>qp(b,m)}):o.jsx(Qt.NoData,{message:"No cost data yet"})})]}):o.jsx(Qt.NoData,{message:"No token usage data yet"})})]})}function jvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>rA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function Nvs(){const{data:e,isLoading:t,isError:n}=jvs(),{getTracesHref:r}=sA(),{Link:s}=wn();return o.jsx(Tvs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Tc.AGENT,entityName:a.name}),actions:o.jsx(EL,{href:r({rootEntityType:Tc.AGENT}),LinkComponent:s})})}function Txe(e,t=al){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const Ivs=[{dataKey:"input",label:"Input tokens",color:Hp.blue,aggregate:Txe("input")},{dataKey:"output",label:"Output tokens",color:Hp.yellow,aggregate:Txe("output")}];function Avs(e){return e==="tokens"||e==="cost"}function Rvs({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,C)=>k+C.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,C)=>k+(C.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:Hp.purple,aggregate:Txe("cost",k=>qp(k,v))}];return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Qt.Summary,{value:qp(y,v),label:"Total cost"}):o.jsx(Qt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Qt.Actions,{children:s}):null]}),n?o.jsx(Qt.Loading,{}):r?o.jsx(Qt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Qt.Content,{children:u?o.jsxs(pc,{defaultTab:"tokens",value:a,onValueChange:k=>{Avs(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"tokens",children:"Tokens"}),o.jsx(jr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(WV,{data:c,series:Ivs})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(WV,{data:p,series:S}):o.jsx(Qt.NoData,{message:"No cost data yet"})})]}):o.jsx(Qt.NoData,{message:"No token usage data yet"})})]})}function Pvs(e){return e==="24h"?"1h":"1d"}function $vs(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function Fet(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function Mvs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function Dvs(){const e=He(),{datePreset:t,filters:n,filterKey:r}=Mm(),s=Pvs(t);return gt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Fet(l,a.series[0],"input"),Fet(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:$vs(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:Mvs(u)}}),interval:s}}})}function Lvs(){const{data:e,isLoading:t,isError:n}=Dvs(),{getTracesHref:r}=sA(),{Link:s}=wn();return o.jsx(Rvs,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(EL,{href:r(),LinkComponent:s})})}function kie({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(PN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Hp.blueDark},{label:"Errors",color:Hp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:al})}function Fvs({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Qt,{children:[o.jsxs(Qt.TopBar,{children:[o.jsx(Qt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Qt.Summary,{value:al(f),label:"Total runs"}),u?o.jsx(Qt.Actions,{children:u}):null]}),t?o.jsx(Qt.Loading,{}):n?o.jsx(Qt.Error,{message:"Failed to load trace volume data"}):o.jsx(Qt.Content,{children:d?o.jsxs(pc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fc,{children:[o.jsx(jr,{value:"agents",children:"Agents"}),o.jsx(jr,{value:"workflows",children:"Workflows"}),o.jsx(jr,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(kie,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Qt.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(kie,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Qt.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(kie,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Qt.NoData,{message:"No tool data yet"})})]}):o.jsx(Qt.NoData,{message:"No trace volume data yet"})})]})}async function Oie(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=rA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function zvs(){const e=He(),{filters:t,filterKey:n}=Mm();return gt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([Oie(e,"mastra_agent_duration_ms",t),Oie(e,"mastra_workflow_duration_ms",t),Oie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const zz={agents:Tc.AGENT,workflows:Tc.WORKFLOW_RUN,tools:Tc.TOOL};function Bvs(){const{data:e,isLoading:t,isError:n}=zvs(),{getTracesHref:r,getLogsHref:s}=sA(),{Link:a}=wn();return o.jsx(Fvs,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:zz[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:zz[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(EL,{href:r({rootEntityType:zz[i]}),LinkComponent:a}),o.jsx(Xgs,{href:s({rootEntityType:zz[i],status:"error"}),LinkComponent:a})]})})}const _ie="period",Bz="dateFrom",Uz="dateTo";function Uvs(){const[e,t]=si(),n=e.get(_ie),r=Vgs(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(Bz)),p=d(e.get(Uz));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>Mgs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(_ie):p.set(_ie,d),d!=="custom"&&(p.delete(Bz),p.delete(Uz)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(Bz,d.from.toISOString()):p.delete(Bz),d?.to?p.set(Uz,d.to.toISOString()):p.delete(Uz),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Lgs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,Pgs(e)))return;const d=gVt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Hgs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(Vvs,{})})}function Vvs(){const[e]=si(),{error:t,isLoading:n}=bVt(),{filterTokens:r,setFilterTokens:s}=NQ(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=jAe(),{data:d,isLoading:f}=CAe(),{data:p,isLoading:h}=kAe(),{data:m,isLoading:v}=_Ae(),{data:y,isLoading:b}=OAe(),x=g.useMemo(()=>$gs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[S,k]=g.useState(()=>gVt()!==null),C=g.useCallback(()=>{Ags(e),k(!0),Le.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{Rgs(),k(!1),Le.success("Filters setting for Metrics cleared up")},[]),E=g.useCallback(()=>{s([])},[s]),T=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&xs(t)?o.jsx(cr,{children:o.jsx(Zs,{})}):t&&Ss(t)?o.jsx(cr,{children:o.jsx($s,{resource:"metrics"})}):t?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Qgs,{}),o.jsx(gAe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(Svs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:T,onRemoveAll:E,onSave:C,onRemoveSaved:S?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(xn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(xn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(Sxe,{children:[o.jsx(vvs,{}),o.jsx(yvs,{}),o.jsx(bvs,{}),o.jsx(xvs,{}),o.jsx(wvs,{})]}),o.jsxs(Sxe,{children:[o.jsx(Cvs,{}),o.jsx(Nvs,{}),o.jsx(Lvs,{}),o.jsx(fvs,{}),o.jsx(Bvs,{}),o.jsx(ovs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Lf,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Oa,{})]})})})]})}const qvs=50;function Hvs(){const{paths:e}=wn(),{isCmsAvailable:t}=uS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=q7t({page:s,perPage:qvs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=g.useCallback(()=>{u||a(v=>v+1)},[u]),h=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&xs(c)?o.jsx(cr,{children:o.jsx(Zs,{})}):c&&Ss(c)?o.jsx(cr,{children:o.jsx($s,{resource:"prompt blocks"})}):c?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(cr,{children:o.jsx(Sas,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Vf,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(le,{as:ni,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Zr,{}),"Create Prompt"]})]})}),o.jsx(was,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function Wvs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx(Zts,{children:o.jsx(Qbe,{})})})})}const Zvs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:WGt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:glt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Oa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:gj,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:Olt,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:vlt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Gvs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:Zvs.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(Oa,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function Qvs(){const{data:e={},isLoading:t,error:n}=dh(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&xs(n))return o.jsx(cr,{children:o.jsx(Zs,{})});if(n&&Ss(n))return o.jsx(cr,{children:o.jsx($s,{resource:"scorers"})});if(n)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(cr,{children:o.jsx(jrs,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Irs,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(Trs,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Yvs(){const{scorerId:e}=Sr(),[t,n]=si(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=ars(e),{data:d={},isLoading:f,error:p}=Am(),{isLoading:h,error:m}=Zy(),{data:v=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k}=srs({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),C=g.useMemo(()=>c?.agentIds?.filter(V=>d[V]).map(V=>({value:V,label:d[V].name,type:"AGENT"}))||[],[c?.agentIds,d]),_=g.useMemo(()=>c?.workflowIds?.map(V=>({value:V,label:V,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...C,..._],[C,_]),T=t.get("entity")??"all",N=E.find(V=>V.value===T);N&&N.value!==i?.value&&l(N),g.useEffect(()=>{if(u){const V=u instanceof Error?u.message:"Failed to load scorer";Le.error(`Error loading scorer: ${V}`)}},[u]),g.useEffect(()=>{if(p){const V=p instanceof Error?p.message:"Failed to load agents";Le.error(`Error loading agents: ${V}`)}},[p]),g.useEffect(()=>{if(m){const V=m instanceof Error?m.message:"Failed to load workflows";Le.error(`Error loading workflows: ${V}`)}},[m]);const I=V=>{V?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",V.value),G})};g.useEffect(()=>{const V=t.get("scoreId")??void 0;if(V===s)return;if(!V){a(void 0);return}v.find(G=>G.id===V)&&a(V)},[t,v]);const A=g.useCallback(V=>{a(V||void 0),n(M=>{const G=new URLSearchParams(M);return V?G.set("scoreId",V):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=xs(u)||xs(p)||xs(m),L=u&&Ss(u),D=!R&&!L&&(u||p||m),F=!y&&v.length===0,H=i?.value!=="all",B=c?.scorer?.source==="stored"?o.jsx(Dy,{owner:"scorer-detail",children:o.jsxs(le,{variant:"default",as:ni,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(cm,{})," Edit"]})}):null;if(R||L||D||F&&!H){const V=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Vt,{width:"wide",height:"full",children:[B,o.jsx(Vt.MainArea,{isCentered:!0,children:R?o.jsx(Zs,{}):L?o.jsx($s,{resource:"scorers"}):D?o.jsx(Hi,{title:"Failed to load scorer",message:V}):o.jsx(Kns,{})})]})}return o.jsxs(Vt,{width:"wide",children:[B,o.jsx(Vt.TopArea,{children:o.jsx(Xns,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(V=>{const M=new URLSearchParams(V);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(Yns,{scores:v,isLoading:y,selectedScoreId:s,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function Kvs({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:X("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Dt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-neutral3 text-sm",children:t})]}),s]})}const kVt=[{value:"dark",label:"Dark",Icon:OYt},{value:"light",label:"Light",Icon:MKt},{value:"system",label:"System",Icon:Ilt}],Xvs=e=>kVt.some(t=>t.value===e);function Jvs({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const eys=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=hH(),{theme:r,setTheme:s}=q_();return o.jsx(Vt,{width:"narrow",children:o.jsxs(Vt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(jbe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Kvs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ma,{value:r,onValueChange:a=>{Xvs(a)&&s(a)},children:[o.jsx(va,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ga,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(ya,{children:kVt.map(a=>o.jsx(Rr,{value:a.value,children:o.jsx(Jvs,{option:a})},a.value))})]})})}),o.jsx(jbe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(d3t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function tys(){const[e]=si(),t=Ws(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(pVt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const OVt=e=>o.jsx("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})});function nys(e){return e.replace(/\/$/,"").split("/").pop()}function IQ({children:e,className:t}){return o.jsx("div",{className:X("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function rys({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:X("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:X("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:X("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:X("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:X("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:X("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:X("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Vo,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Ud,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Alt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(HN,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(yC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:X("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(OVt,{})," ",nys(a.githubUrl)]})})]},a.slug)})})}function sys({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:X("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:X("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(bN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Cc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Cc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(le,{onClick:c,children:["Reset ",o.jsx(ws,{})]})]})}function ays(){const{data:e,isLoading:t}=Ynr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(fs,{children:[o.jsx(q1e,{children:o.jsxs(Fyt,{children:[o.jsx(Ue,{children:o.jsx(ey,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(sys,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(rys,{templates:y,linkComponent:ni,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const iys="1.62.0-alpha.9";function oys({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(Cf,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(wQt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(IQ,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function lys({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(IQ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:X("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Rlt,{})]}),o.jsx(Cc,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:X("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(en,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(IO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(IO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(x7t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(le,{className:X("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(en,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(wm,{})]})})]})})}function cys({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:X("grid mt-8 items-center"),children:o.jsxs("div",{className:X("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(ey,{}),o.jsx("h2",{className:X({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:X("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:X("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(Qx,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Vxe,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(OVt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(FIe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function zet(e){switch(e){case"running":return o.jsx(en,{size:"sm","aria-hidden":!0});case"success":return o.jsx(yy,{"aria-hidden":!0});case"failed":return o.jsx(pu,{"aria-hidden":!0});default:return null}}function uys(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function dys({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:X("flex size-4 items-center justify-center self-center [&>svg]:size-4",Wr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(uys,{}):zet(e)}):o.jsx("span",{className:X("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Wr.colors,Wr.transform,Wr.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:zet(e)})}function fys({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Wr.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:X("flex min-w-6 justify-end text-ui-md",Wr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:X("text-ui-md",Wr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:X("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(dys,{status:e.status,variant:r})]})}function pys({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(fys,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function hys({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:X("relative flex h-8 items-center justify-end",Wr.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:X("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",Wr.colors,Wr.transform,Wr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(en,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",Wr.colors),children:[n," of ",t," steps completed"]})]})}function mys({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(IQ,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(hys,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:X("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(PYt,{}),l||"Something went wrong"]}),u&&o.jsx(pys,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(en,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function gys({name:e,installedEntities:t}){return o.jsxs(IQ,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Rlt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx(FIe,{data:t})]})}function vys(){const{templateSlug:e}=Sr(),[t,n]=si(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[S,k]=g.useState(!1),[C,_]=g.useState(!1),[E,T]=g.useState([]),{data:N,isLoading:I}=Knr({repoOrSlug:e,owner:"mastra-ai"}),R=iys?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=Xnr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:F,isLoading:H}=Jnr(),{mutateAsync:B,isPending:U}=err(),{mutateAsync:V}=trr(),{streamInstall:M,streamResult:G,isStreaming:q}=rrr(F),{observeInstall:$,streamResult:z,isStreaming:Z}=srr(F);g.useEffect(()=>{const te=t.get("runId");te&&!v&&!h&&!q&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:te}),x(te),V({runId:te}).then(ue=>{const de=ue.snapshot;if(de?.status==="success"&&de?.result?.success)y(!0);else if(de?.result?.success===!1)if(de?.result?.validationResults&&!de?.result?.validationResults?.valid&&de?.result?.validationResults?.remainingErrors>0){const{remainingErrors:ge,errors:be}=de.result.validationResults,xe=`Template installation completed but ${ge} validation issue${ge>1?"s":""} remain unresolved.`;m(xe),T(be||[])}else{const ge=de?.result?.message||de?.result?.error||"Template installation failed";m(typeof ge=="string"?ge:String(ge))}}).catch(ue=>{console.error("❌ Failed to fetch run details:",ue),m("Failed to retrieve installation status after reload")}))},[t,v,h,q,Z,V]),g.useEffect(()=>{const te=t.get("runId"),ue=t.get("resume"),de=t.get("provider");if(te&&ue==="true"&&de&&!q&&!Z&&!S&&!C&&F){x(te),k(!0);try{V({runId:te}).then(ce=>{if(ce.snapshot?.status==="running")return $.mutateAsync({runId:te})}).then(()=>{n(ce=>{const ge=new URLSearchParams(ce);return ge.delete("resume"),ge})}).catch(ce=>{console.error("❌ Failed to resume template installation:",ce),ce.message?.includes("404")||ce.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(ce){console.error("❌ Auto-resume failed with error:",ce),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,q,Z,S,C,F,V,$,n]);const K=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],re=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(te=>te).join(", "):"n/a",icon:o.jsx(Ud,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(te=>te).join(", "):"n/a",icon:o.jsx(Vo,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(te=>te).join(", "):"n/a",icon:o.jsx(HN,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Fv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(qN,{})}],ee=[{...re[0]},{...re[1]},{...re[2]}].filter(te=>te.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const te=G||z;te?.phase==="error"&&te?.error&&m(typeof te.error=="string"?te.error:String(te.error))},[G?.phase,G?.error,z?.phase,z?.error]);const J=te=>{s(te)},ae=async te=>(i(te.provider),c(te.modelId),{message:"Model updated successfully"}),fe=async()=>{const te=Object.entries(u).reduce((ue,[de,ce])=>(ce===""&&ue.push(de),ue),[]);if(te.length>0){p(te);return}if(N){m(null),y(!1),x(""),_(!0);try{const de={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ce}=await B({});x(ce),n(ge=>{const be=new URLSearchParams(ge);return be.set("runId",ce),be.set("resume","true"),be.set("provider",r||"openai"),be}),await M.mutateAsync({inputData:de,selectedModel:{provider:a,modelId:l},runId:ce})}catch(ue){_(!1),m(ue?.message||"Template installation failed"),console.error("Template installation failed",ue)}}},Y=te=>{const{name:ue,value:de}=te.target;de.trim()===""?p(ce=>[...ce,ue]):p(ce=>ce.filter(ge=>ge!==ue)),d(ce=>({...ce,[ue]:de}))};return o.jsx(fs,{children:o.jsx("div",{className:X("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(cys,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:re,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(q||Z)&&o.jsx(mys,{name:N.title,streamResult:Z?z:G,runId:b,workflowInfo:F}),v&&o.jsx(gys,{name:N.title,installedEntities:ee,linkComponent:ni}),h&&o.jsx(oys,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||z?.validationResults?.errors}),!q&&!Z&&!v&&!h&&o.jsx(lys,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:fe,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:U,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const yys=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Fss,{toolId:e,agentId:t})})},bys=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Sgs,{toolId:e})})};function xys(){const{traceId:e}=Sr(),[t,n]=si(),r=Ws(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=g.useState(s??null),[d,f]=g.useState(),[p,h]=g.useState(i),[m,v]=g.useState(0),[y,b]=g.useState(!1),{data:x,isLoading:S,error:k}=EAe(e),C=g.useMemo(()=>x?.spans??[],[x?.spans]),_=g.useMemo(()=>C.find(Y=>Y.parentSpanId==null),[C]),E=jAe(),T=bxe({traceIds:[e],enabled:!E.isLoading&&E.supportsMetrics,autoRefetch:!1}),{data:N,isLoading:I}=_L(e,c??"");g.useEffect(()=>v(0),[e,c]);const{data:A,isLoading:R}=dh(),{data:L,isLoading:D}=F7t({traceId:e,spanId:c??void 0,page:m}),[F,H]=g.useState(0);g.useEffect(()=>H(0),[e,c]);const{data:B,isLoading:U}=JUt({traceId:e,page:F});g.useEffect(()=>{if(l&&L?.scores&&!d){const Y=L.scores.find(te=>te.id===l);Y&&f(Y)}},[l,L?.scores,d]);const V=g.useCallback(Y=>{const te=new URLSearchParams(t);for(const[ue,de]of Object.entries(Y))de===null||de===""?te.delete(ue):te.set(ue,de);n(te,{replace:!0})},[t,n]),M=g.useCallback(Y=>{const te=Y??null,ue=te===c;u(te),ue||(f(void 0),h("details"),V({spanId:te,tab:null,scoreId:null}))},[c,V]),G=g.useCallback(()=>{u(null),f(void 0),h("details"),V({spanId:null,tab:null,scoreId:null})},[V]),q=g.useCallback(Y=>{u(Y),f(void 0),h("details"),V({spanId:Y,tab:null,scoreId:null})},[V]),{handlePreviousSpan:$,handleNextSpan:z}=TAe(C,c,q),Z=g.useCallback(Y=>{const te=Y;h(te),f(void 0),V({tab:te==="details"?null:te,scoreId:null})},[V]),K=g.useCallback(Y=>{f(Y),V({scoreId:Y.id})},[V]),re=g.useCallback(()=>{f(void 0),V({scoreId:null})},[V]),ee=g.useCallback(()=>{r("/traces")},[r]),J=g.useCallback(()=>{h("scoring"),_&&c!==_.spanId?(u(_.spanId),f(void 0),V({spanId:_.spanId,tab:"scoring",scoreId:null})):V({tab:"scoring"})},[_,c,V]),ae=_?o.jsx(Dy,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(le,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:J,children:[o.jsx(hGt,{}),"Evaluate"]}),o.jsxs(le,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(Id,{}),"Save"]})]})}):null,fe=_?o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{className:"w-full",children:o.jsx(DUt,{rootSpan:_,usage:T.data?.get(e),numOfCol:3})})}):null;return k?o.jsxs(Vt,{height:"full",children:[ae,fe&&o.jsx(Vt.TopArea,{children:fe}),o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(UUt,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Vt,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[ae,fe&&o.jsx(Vt.TopArea,{children:fe}),o.jsx(GUt,{rootSpanId:_?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:X("mt-4 grid min-h-0 items-stretch gap-4 overflow-hidden",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(xAe,{traceId:e,spans:C,isLoading:S,onClose:ee,onSpanSelect:M,onEvaluateTrace:J,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&o.jsxs("div",{className:X("grid h-full max-h-full min-h-0 gap-4 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(vAe,{traceId:e,spanId:c,span:N?.span,isLoading:I,onClose:G,onPrevious:$,onNext:z,activeTab:p,onTabChange:Z,feedbackTabBadge:B?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(YUt,{feedbackData:B,onPageChange:H,isLoadingFeedbackData:U}),scoringTabBadge:L?.pagination?.total??void 0,scoringTabSlot:({span:Y,traceId:te,spanId:ue})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(XUt,{traceId:te,isTopLevelSpan:!Y.parentSpanId,spanId:ue,entityType:Y.attributes?.agentId||Y.entityType===Tc.AGENT?"Agent":Y.attributes?.workflowId||Y.entityType===Tc.WORKFLOW_RUN?"Workflow":void 0,scorers:A,isLoadingScorers:R}),o.jsx(KUt,{scoresData:L,onPageChange:v,isLoadingScoresData:D,onScoreSelect:K})]})}),d&&o.jsx(LIe,{score:d,onClose:re})]})]})]})}function wys(){const{data:e,isLoading:t,error:n}=Zy(),[r,s]=g.useState("");return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"workflows"})}):n?o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(cr,{children:o.jsx(nHr,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Vf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(le,{as:ni,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(RD,{}),"Schedules"]})]})}),o.jsx(tHr,{workflows:e||{},isLoading:t,search:r})]})}const Sys={active:"bg-accent1",paused:"bg-accent3"},kys={active:"text-accent1",paused:"text-accent3"},_Vt=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Sys[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${kys[e]}`,children:e})]}),dj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),Z2=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function CVt({status:e}){const{icon:t,color:n}=Oys(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function Oys(e){switch(e){case"success":return{icon:o.jsx(da,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(ws,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(en,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(rq,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Lf,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(mj,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const Bet="auto auto auto auto 1fr";function _ys(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function Cys(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const Eys=3e4,Tys=5*6e4;function jys({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=wn();return t?o.jsx(ol,{columns:Bet}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(me,{columns:Bet,className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Run"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Started"}),o.jsx(me.TopCell,{children:"Duration"}),o.jsx(me.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=Cys(u),f=`Scheduled ${dj(c.scheduledFireAt)} — published ${dj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),v=!p&&m>Eys&&m<=Tys,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),x=o.jsx("span",{className:b?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",children:x}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(Cf,{size:14}),"publish failed"]}):c.run?o.jsx(CVt,{status:c.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),h?o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Cf,{size:14})})}),o.jsx(On,{children:h})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:Z2(c.actualFireAt)}),v?o.jsxs(En,{children:[o.jsx(kn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Cf,{size:14})})}),o.jsxs(On,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:c.run?o.jsx("span",{children:_ys(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(me.Cell,{height:"compact",children:" "})]});return b?o.jsx(me.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(me.RowStatic,{children:S},y)}),o.jsx(me.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Nys=e=>{const t=He();return gt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Uet=25,Iys=e=>{const t=He(),{inView:n,setRef:r}=Q_(),s=G1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Uet,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Uet))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},Ays=e=>{const t=He(),n=Br();return Dn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),Le.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Le.error(r.message)}})};function Vz({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function Rys(){const{scheduleId:e}=Sr(),{paths:t}=wn(),{data:n,error:r}=Nys(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=Iys(e),d=Ays(e);if(r&&xs(r))return o.jsx(cr,{children:o.jsx(Zs,{})});if(r&&Ss(r))return o.jsx(cr,{children:o.jsx($s,{resource:"schedules"})});if(r)return o.jsx(cr,{children:o.jsx(Hi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{className:"justify-end",children:o.jsxs(Vt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(le,{as:ni,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Pc,{}),"Back to schedules"]}),f?o.jsx(le,{as:ni,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(le,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(Zxe,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Wp,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(Vz,{label:p?"Agent":"Workflow",children:f?o.jsx(ni,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(ni,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(Vz,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(Vz,{label:"Status",children:o.jsx(_Vt,{status:n.status})}),o.jsx(Vz,{label:"Next fire",children:o.jsx("span",{title:dj(n.nextFireAt),children:Z2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ye,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Hi,{title:"Failed to load trigger history",message:i.message}):o.jsx(jys,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Vet="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function Pys({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=wn(),a=g.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(ol,{columns:Vet}):o.jsxs(me,{columns:Vet,variant:"striped",className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Schedule ID"}),o.jsx(me.TopCell,{children:"Cron"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Next fire"}),o.jsx(me.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(me.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(me.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(me.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(me.NameCell,{children:i.workflowId??i.agentId}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:i.id,children:i.id})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsx(_Vt,{status:i.status})}),o.jsx(me.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:dj(i.nextFireAt),children:Z2(i.nextFireAt)})}),o.jsx(me.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(CVt,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:dj(i.lastFireAt),children:i.lastFireAt?Z2(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:dj(i.lastFireAt),children:Z2(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function $ys({workflowId:e}={}){const{data:t,isLoading:n,error:r}=U1e(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Hi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(Vf,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(Pys,{schedules:t??[],isLoading:n,search:s})})]})}function Mys(){const[e]=si(),t=e.get("workflowId")??void 0,{error:n}=U1e(t?{workflowId:t}:{});return n&&xs(n)?o.jsx(cr,{children:o.jsx(Zs,{})}):n&&Ss(n)?o.jsx(cr,{children:o.jsx($s,{resource:"schedules"})}):o.jsx(Vt,{children:o.jsx("div",{className:"h-full",children:o.jsx($ys,{workflowId:t})})})}function Dys({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=vOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=h_t(r),[d]=m_t(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=G4t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(p_t,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(dje,{position:"bottom-left"}),o.jsx(v_t,{variant:oy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(en,{})})})}function Lys(){const{stepDetail:e,closeStepDetail:t}=lW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(g9,{className:"h-4 w-4",style:{color:Au.map}}),e.type==="nested-graph"&&o.jsx(nd,{className:"h-4 w-4",style:{color:Au.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(ws,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(q2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(gOe,{children:o.jsx(Dys,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function Fys(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function zys(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 Bys({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ye,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(Ue,{children:o.jsx(rq,{})}),"Step suspended"]}),o.jsx(ln,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?mm(Ex(i.resumeSchema)):cf(fr(),yf());return o.jsx(Uys,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function Uys({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Ue,{children:o.jsx(CYt,{})}),"The step is asking"]}),o.jsxs(Fd,{open:a,onOpenChange:i,children:[o.jsxs(Xu,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Ue,{children:o.jsx(aa,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:zys(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:Fys(e.suspendPayload)})]}),o.jsx(Ju,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Hr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Ue,{children:o.jsx(jYt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(GB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Wp,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function Vys(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(ql),{runId:a}=Sr(),i=O_t(e,r??""),l=fer(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(Bys,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const qys=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),Hys=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),Wys=e=>e.includes("."),Zys=e=>e==="input"||e.endsWith(".input"),Gys=1;function Qys(e){return`${Number((e/1e3).toPrecision(3))}s`}function Yys(e,t){const n=Object.entries(e).filter(([i])=>!Zys(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,p=Math.max(d/a*100,Gys);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:Wys(i)}})}const Kys=({status:e})=>o.jsxs(Ue,{children:[e==="success"&&o.jsx(qys,{className:"text-accent1"}),e==="failed"&&o.jsx(Hys,{className:"text-accent2"}),e==="suspended"&&o.jsx(rq,{className:"text-accent3"}),e==="waiting"&&o.jsx(gpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(gpe,{className:"text-icon3"}),e==="running"&&o.jsx(ca,{className:"text-accent6 animate-spin"})]}),Xys={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function EVt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const qet=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},Jys=e=>{const t=e;return F4t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},ebs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=Jys(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:X("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(Kys,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(NKt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(jV,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:EVt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${Xys[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(TKt,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:Qys(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function tbs(){const{steps:e}=M4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=wH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Kyt(f,{enabled:!l});const p=Yys(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Na,{className:X("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(ebs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:qet(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:qet(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(C_t,{data:u.data,title:`${EVt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const nbs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=lW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(nLt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(Vys,{}),o.jsx(tbs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(Lys,{})})]})},Het=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=H3(e);return r&&xs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zs,{})}):r&&Ss(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($s,{resource:"workflows"})}):o.jsx($Oe,{children:o.jsx(nbs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function rbs(e,t){if(e==null)return{};var n,r,s=NSt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function jxe(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 sbs(e){if(Array.isArray(e))return jxe(e)}function abs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function ibs(e,t){if(e){if(typeof e=="string")return jxe(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)?jxe(e,t):void 0}}function obs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
643
643
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Nxe(e){return sbs(e)||abs(e)||ibs(e)||obs()}function jD(e){"@babel/helpers - typeof";return jD=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},jD(e)}function lbs(e,t){if(jD(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(jD(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function cbs(e){var t=lbs(e,"string");return jD(t)=="symbol"?t:t+""}function TVt(e,t,n){return(t=cbs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Wet(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 _T(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Wet(Object(n),!0).forEach(function(r){TVt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Wet(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function ubs(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 Cie={};function dbs(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return Cie[t]||(Cie[t]=ubs(e)),Cie[t]}function fbs(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(a){return a!=="token"}),s=dbs(r);return s.reduce(function(a,i){return _T(_T({},a),n[i])},t)}function Zet(e){return e.join(" ")}function pbs(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return jVt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function jVt(e){var t=e.node,n=e.stylesheet,r=e.style,s=r===void 0?{}:r,a=e.useInlineStyles,i=e.key,l=t.properties,c=t.type,u=t.tagName,d=t.value;if(c==="text")return d;if(u){var f=pbs(n,a),p;if(!a)p=_T(_T({},l),{},{className:Zet(l.className)});else{var h=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(S){b.includes(S)||b.push(S)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],v=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=_T(_T({},l),{},{className:Zet(v)||void 0,style:fbs(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return Fe.createElement(u,WO({key:i},p),y)}}const hbs=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var mbs=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function Get(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 Lw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Get(Object(n),!0).forEach(function(r){TVt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Get(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var gbs=/\n/g;function vbs(e){return e.match(gbs)}function ybs(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return Fe.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
644
644
  `))})}function bbs(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,s=r===void 0?{float:"left",paddingRight:"10px"}:r,a=e.numberStyle,i=a===void 0?{}:a,l=e.startingLineNumber;return Fe.createElement("code",{style:Object.assign({},n,s)},ybs({lines:t.replace(/\n$/,"").split(`
645
645
  `),style:i,startingLineNumber:l}))}function xbs(e){return"".concat(e.toString().length,".25em")}function NVt(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 IVt(e,t,n){var r={display:"inline-block",minWidth:xbs(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=Lw(Lw({},r),s);return a}function f9(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,s=e.largestLineNumber,a=e.showInlineLineNumbers,i=e.lineProps,l=i===void 0?{}:i,c=e.className,u=c===void 0?[]:c,d=e.showLineNumbers,f=e.wrapLongLines,p=e.wrapLines,h=p===void 0?!1:p,m=h?Lw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(Nxe(m.className.trim().split(/\s+/)),Nxe(u)):u,n&&a){var v=IVt(r,n,s);t.unshift(NVt(n,v))}return f&d&&(m.style=Lw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function AVt(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(f9({children:[s],className:Nxe(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);AVt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function wbs(e,t,n,r,s,a,i,l,c){var u,d=AVt(e.value),f=[],p=-1,h=0;function m(C,_){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return f9({children:C,lineNumber:_,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:E,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(C,_){if(r&&_&&s){var E=IVt(l,_,i);C.unshift(NVt(_,E))}return C}function y(C,_){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||E.length>0?m(C,_,E):v(C,_)}for(var b=function(){var _=d[h],E=_.children[0].value,T=vbs(E);if(T){var N=E.split(`