nterminal 1.3.24 → 1.3.26

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.
Files changed (37) hide show
  1. package/README.md +2 -1
  2. package/dist/client/assets/MarkdownPreview-Dz-gstWx.js +1 -0
  3. package/dist/client/assets/{TranscriptMarkdownBody-D_cxr-gq.js → TranscriptMarkdownBody-wSYk8MdN.js} +1 -1
  4. package/dist/client/assets/{index-BWGb94RV.js → index-D7G-v5g3.js} +1 -1
  5. package/dist/client/assets/index-WcP7tpZM.js +59 -0
  6. package/dist/client/index.html +1 -1
  7. package/dist/server/agent/agentRoutes.js +6 -1
  8. package/dist/server/agent/agentRoutes.js.map +1 -1
  9. package/dist/server/index.js +14 -3
  10. package/dist/server/index.js.map +1 -1
  11. package/dist/server/routes/activityRoutes.js +3 -2
  12. package/dist/server/routes/activityRoutes.js.map +1 -1
  13. package/dist/server/routes/agentManagementRoutes.js +19 -1
  14. package/dist/server/routes/agentManagementRoutes.js.map +1 -1
  15. package/dist/server/routes/terminalRoutes.d.ts +4 -1
  16. package/dist/server/routes/terminalRoutes.js +15 -1
  17. package/dist/server/routes/terminalRoutes.js.map +1 -1
  18. package/dist/server/routes/terminalWebSocket.js +4 -0
  19. package/dist/server/routes/terminalWebSocket.js.map +1 -1
  20. package/dist/server/storage/terminalLayoutCleanup.d.ts +4 -0
  21. package/dist/server/storage/terminalLayoutCleanup.js +103 -0
  22. package/dist/server/storage/terminalLayoutCleanup.js.map +1 -0
  23. package/dist/server/terminal/TerminalManager.d.ts +23 -1
  24. package/dist/server/terminal/TerminalManager.js +338 -77
  25. package/dist/server/terminal/TerminalManager.js.map +1 -1
  26. package/dist/server/terminal/terminalSessionStore.d.ts +27 -0
  27. package/dist/server/terminal/terminalSessionStore.js +124 -0
  28. package/dist/server/terminal/terminalSessionStore.js.map +1 -0
  29. package/dist/shared/layoutState.d.ts +2 -0
  30. package/dist/shared/layoutState.js +3 -0
  31. package/dist/shared/layoutState.js.map +1 -1
  32. package/dist/shared/protocol.d.ts +2 -0
  33. package/dist/shared/protocol.js.map +1 -1
  34. package/docs/configuration.md +53 -0
  35. package/package.json +1 -1
  36. package/dist/client/assets/MarkdownPreview--8XdSXg9.js +0 -1
  37. package/dist/client/assets/index-B82gs1vu.js +0 -59
@@ -0,0 +1,59 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownPreview-Dz-gstWx.js","assets/index-D7G-v5g3.js","assets/TranscriptMarkdownBody-wSYk8MdN.js"])))=>i.map(i=>d[i]);
2
+ (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const d of l.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&s(d)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function s(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();function _N(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Wg={exports:{}},sd={};var n1;function bN(){if(n1)return sd;n1=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(s,o,l){var d=null;if(l!==void 0&&(d=""+l),o.key!==void 0&&(d=""+o.key),"key"in o){l={};for(var f in o)f!=="key"&&(l[f]=o[f])}else l=o;return o=l.ref,{$$typeof:e,type:s,key:d,ref:o!==void 0?o:null,props:l}}return sd.Fragment=t,sd.jsx=n,sd.jsxs=n,sd}var i1;function yN(){return i1||(i1=1,Wg.exports=bN()),Wg.exports}var u=yN(),Kg={exports:{}},bt={};var r1;function SN(){if(r1)return bt;r1=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),d=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),b=Symbol.for("react.lazy"),_=Symbol.for("react.activity"),S=Symbol.iterator;function w(N){return N===null||typeof N!="object"?null:(N=S&&N[S]||N["@@iterator"],typeof N=="function"?N:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},R=Object.assign,L={};function A(N,V,se){this.props=N,this.context=V,this.refs=L,this.updater=se||x}A.prototype.isReactComponent={},A.prototype.setState=function(N,V){if(typeof N!="object"&&typeof N!="function"&&N!=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,N,V,"setState")},A.prototype.forceUpdate=function(N){this.updater.enqueueForceUpdate(this,N,"forceUpdate")};function W(){}W.prototype=A.prototype;function H(N,V,se){this.props=N,this.context=V,this.refs=L,this.updater=se||x}var U=H.prototype=new W;U.constructor=H,R(U,A.prototype),U.isPureReactComponent=!0;var q=Array.isArray;function Y(){}var I={H:null,A:null,T:null,S:null},F=Object.prototype.hasOwnProperty;function de(N,V,se){var Z=se.ref;return{$$typeof:e,type:N,key:V,ref:Z!==void 0?Z:null,props:se}}function me(N,V){return de(N.type,V,N.props)}function K(N){return typeof N=="object"&&N!==null&&N.$$typeof===e}function te(N){var V={"=":"=0",":":"=2"};return"$"+N.replace(/[=:]/g,function(se){return V[se]})}var J=/\/+/g;function Q(N,V){return typeof N=="object"&&N!==null&&N.key!=null?te(""+N.key):V.toString(36)}function X(N){switch(N.status){case"fulfilled":return N.value;case"rejected":throw N.reason;default:switch(typeof N.status=="string"?N.then(Y,Y):(N.status="pending",N.then(function(V){N.status==="pending"&&(N.status="fulfilled",N.value=V)},function(V){N.status==="pending"&&(N.status="rejected",N.reason=V)})),N.status){case"fulfilled":return N.value;case"rejected":throw N.reason}}throw N}function M(N,V,se,Z,Ee){var ye=typeof N;(ye==="undefined"||ye==="boolean")&&(N=null);var ze=!1;if(N===null)ze=!0;else switch(ye){case"bigint":case"string":case"number":ze=!0;break;case"object":switch(N.$$typeof){case e:case t:ze=!0;break;case b:return ze=N._init,M(ze(N._payload),V,se,Z,Ee)}}if(ze)return Ee=Ee(N),ze=Z===""?"."+Q(N,0):Z,q(Ee)?(se="",ze!=null&&(se=ze.replace(J,"$&/")+"/"),M(Ee,V,se,"",function(ve){return ve})):Ee!=null&&(K(Ee)&&(Ee=me(Ee,se+(Ee.key==null||N&&N.key===Ee.key?"":(""+Ee.key).replace(J,"$&/")+"/")+ze)),V.push(Ee)),1;ze=0;var Ke=Z===""?".":Z+":";if(q(N))for(var Be=0;Be<N.length;Be++)Z=N[Be],ye=Ke+Q(Z,Be),ze+=M(Z,V,se,ye,Ee);else if(Be=w(N),typeof Be=="function")for(N=Be.call(N),Be=0;!(Z=N.next()).done;)Z=Z.value,ye=Ke+Q(Z,Be++),ze+=M(Z,V,se,ye,Ee);else if(ye==="object"){if(typeof N.then=="function")return M(X(N),V,se,Z,Ee);throw V=String(N),Error("Objects are not valid as a React child (found: "+(V==="[object Object]"?"object with keys {"+Object.keys(N).join(", ")+"}":V)+"). If you meant to render a collection of children, use an array instead.")}return ze}function T(N,V,se){if(N==null)return N;var Z=[],Ee=0;return M(N,Z,"","",function(ye){return V.call(se,ye,Ee++)}),Z}function O(N){if(N._status===-1){var V=N._result;V=V(),V.then(function(se){(N._status===0||N._status===-1)&&(N._status=1,N._result=se)},function(se){(N._status===0||N._status===-1)&&(N._status=2,N._result=se)}),N._status===-1&&(N._status=0,N._result=V)}if(N._status===1)return N._result.default;throw N._result}var re=typeof reportError=="function"?reportError:function(N){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var V=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof N=="object"&&N!==null&&typeof N.message=="string"?String(N.message):String(N),error:N});if(!window.dispatchEvent(V))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",N);return}console.error(N)},he={map:T,forEach:function(N,V,se){T(N,function(){V.apply(this,arguments)},se)},count:function(N){var V=0;return T(N,function(){V++}),V},toArray:function(N){return T(N,function(V){return V})||[]},only:function(N){if(!K(N))throw Error("React.Children.only expected to receive a single React element child.");return N}};return bt.Activity=_,bt.Children=he,bt.Component=A,bt.Fragment=n,bt.Profiler=o,bt.PureComponent=H,bt.StrictMode=s,bt.Suspense=m,bt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=I,bt.__COMPILER_RUNTIME={__proto__:null,c:function(N){return I.H.useMemoCache(N)}},bt.cache=function(N){return function(){return N.apply(null,arguments)}},bt.cacheSignal=function(){return null},bt.cloneElement=function(N,V,se){if(N==null)throw Error("The argument must be a React element, but you passed "+N+".");var Z=R({},N.props),Ee=N.key;if(V!=null)for(ye in V.key!==void 0&&(Ee=""+V.key),V)!F.call(V,ye)||ye==="key"||ye==="__self"||ye==="__source"||ye==="ref"&&V.ref===void 0||(Z[ye]=V[ye]);var ye=arguments.length-2;if(ye===1)Z.children=se;else if(1<ye){for(var ze=Array(ye),Ke=0;Ke<ye;Ke++)ze[Ke]=arguments[Ke+2];Z.children=ze}return de(N.type,Ee,Z)},bt.createContext=function(N){return N={$$typeof:d,_currentValue:N,_currentValue2:N,_threadCount:0,Provider:null,Consumer:null},N.Provider=N,N.Consumer={$$typeof:l,_context:N},N},bt.createElement=function(N,V,se){var Z,Ee={},ye=null;if(V!=null)for(Z in V.key!==void 0&&(ye=""+V.key),V)F.call(V,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(Ee[Z]=V[Z]);var ze=arguments.length-2;if(ze===1)Ee.children=se;else if(1<ze){for(var Ke=Array(ze),Be=0;Be<ze;Be++)Ke[Be]=arguments[Be+2];Ee.children=Ke}if(N&&N.defaultProps)for(Z in ze=N.defaultProps,ze)Ee[Z]===void 0&&(Ee[Z]=ze[Z]);return de(N,ye,Ee)},bt.createRef=function(){return{current:null}},bt.forwardRef=function(N){return{$$typeof:f,render:N}},bt.isValidElement=K,bt.lazy=function(N){return{$$typeof:b,_payload:{_status:-1,_result:N},_init:O}},bt.memo=function(N,V){return{$$typeof:p,type:N,compare:V===void 0?null:V}},bt.startTransition=function(N){var V=I.T,se={};I.T=se;try{var Z=N(),Ee=I.S;Ee!==null&&Ee(se,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(Y,re)}catch(ye){re(ye)}finally{V!==null&&se.types!==null&&(V.types=se.types),I.T=V}},bt.unstable_useCacheRefresh=function(){return I.H.useCacheRefresh()},bt.use=function(N){return I.H.use(N)},bt.useActionState=function(N,V,se){return I.H.useActionState(N,V,se)},bt.useCallback=function(N,V){return I.H.useCallback(N,V)},bt.useContext=function(N){return I.H.useContext(N)},bt.useDebugValue=function(){},bt.useDeferredValue=function(N,V){return I.H.useDeferredValue(N,V)},bt.useEffect=function(N,V){return I.H.useEffect(N,V)},bt.useEffectEvent=function(N){return I.H.useEffectEvent(N)},bt.useId=function(){return I.H.useId()},bt.useImperativeHandle=function(N,V,se){return I.H.useImperativeHandle(N,V,se)},bt.useInsertionEffect=function(N,V){return I.H.useInsertionEffect(N,V)},bt.useLayoutEffect=function(N,V){return I.H.useLayoutEffect(N,V)},bt.useMemo=function(N,V){return I.H.useMemo(N,V)},bt.useOptimistic=function(N,V){return I.H.useOptimistic(N,V)},bt.useReducer=function(N,V,se){return I.H.useReducer(N,V,se)},bt.useRef=function(N){return I.H.useRef(N)},bt.useState=function(N){return I.H.useState(N)},bt.useSyncExternalStore=function(N,V,se){return I.H.useSyncExternalStore(N,V,se)},bt.useTransition=function(){return I.H.useTransition()},bt.version="19.2.6",bt}var s1;function Zb(){return s1||(s1=1,Kg.exports=SN()),Kg.exports}var v=Zb();const zt=_N(v);var qg={exports:{}},ad={},Vg={exports:{}},Yg={};var a1;function wN(){return a1||(a1=1,(function(e){function t(M,T){var O=M.length;M.push(T);e:for(;0<O;){var re=O-1>>>1,he=M[re];if(0<o(he,T))M[re]=T,M[O]=he,O=re;else break e}}function n(M){return M.length===0?null:M[0]}function s(M){if(M.length===0)return null;var T=M[0],O=M.pop();if(O!==T){M[0]=O;e:for(var re=0,he=M.length,N=he>>>1;re<N;){var V=2*(re+1)-1,se=M[V],Z=V+1,Ee=M[Z];if(0>o(se,O))Z<he&&0>o(Ee,se)?(M[re]=Ee,M[Z]=O,re=Z):(M[re]=se,M[V]=O,re=V);else if(Z<he&&0>o(Ee,O))M[re]=Ee,M[Z]=O,re=Z;else break e}}return T}function o(M,T){var O=M.sortIndex-T.sortIndex;return O!==0?O:M.id-T.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var d=Date,f=d.now();e.unstable_now=function(){return d.now()-f}}var m=[],p=[],b=1,_=null,S=3,w=!1,x=!1,R=!1,L=!1,A=typeof setTimeout=="function"?setTimeout:null,W=typeof clearTimeout=="function"?clearTimeout:null,H=typeof setImmediate<"u"?setImmediate:null;function U(M){for(var T=n(p);T!==null;){if(T.callback===null)s(p);else if(T.startTime<=M)s(p),T.sortIndex=T.expirationTime,t(m,T);else break;T=n(p)}}function q(M){if(R=!1,U(M),!x)if(n(m)!==null)x=!0,Y||(Y=!0,te());else{var T=n(p);T!==null&&X(q,T.startTime-M)}}var Y=!1,I=-1,F=5,de=-1;function me(){return L?!0:!(e.unstable_now()-de<F)}function K(){if(L=!1,Y){var M=e.unstable_now();de=M;var T=!0;try{e:{x=!1,R&&(R=!1,W(I),I=-1),w=!0;var O=S;try{t:{for(U(M),_=n(m);_!==null&&!(_.expirationTime>M&&me());){var re=_.callback;if(typeof re=="function"){_.callback=null,S=_.priorityLevel;var he=re(_.expirationTime<=M);if(M=e.unstable_now(),typeof he=="function"){_.callback=he,U(M),T=!0;break t}_===n(m)&&s(m),U(M)}else s(m);_=n(m)}if(_!==null)T=!0;else{var N=n(p);N!==null&&X(q,N.startTime-M),T=!1}}break e}finally{_=null,S=O,w=!1}T=void 0}}finally{T?te():Y=!1}}}var te;if(typeof H=="function")te=function(){H(K)};else if(typeof MessageChannel<"u"){var J=new MessageChannel,Q=J.port2;J.port1.onmessage=K,te=function(){Q.postMessage(null)}}else te=function(){A(K,0)};function X(M,T){I=A(function(){M(e.unstable_now())},T)}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(M){M.callback=null},e.unstable_forceFrameRate=function(M){0>M||125<M?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):F=0<M?Math.floor(1e3/M):5},e.unstable_getCurrentPriorityLevel=function(){return S},e.unstable_next=function(M){switch(S){case 1:case 2:case 3:var T=3;break;default:T=S}var O=S;S=T;try{return M()}finally{S=O}},e.unstable_requestPaint=function(){L=!0},e.unstable_runWithPriority=function(M,T){switch(M){case 1:case 2:case 3:case 4:case 5:break;default:M=3}var O=S;S=M;try{return T()}finally{S=O}},e.unstable_scheduleCallback=function(M,T,O){var re=e.unstable_now();switch(typeof O=="object"&&O!==null?(O=O.delay,O=typeof O=="number"&&0<O?re+O:re):O=re,M){case 1:var he=-1;break;case 2:he=250;break;case 5:he=1073741823;break;case 4:he=1e4;break;default:he=5e3}return he=O+he,M={id:b++,callback:T,priorityLevel:M,startTime:O,expirationTime:he,sortIndex:-1},O>re?(M.sortIndex=O,t(p,M),n(m)===null&&M===n(p)&&(R?(W(I),I=-1):R=!0,X(q,O-re))):(M.sortIndex=he,t(m,M),x||w||(x=!0,Y||(Y=!0,te()))),M},e.unstable_shouldYield=me,e.unstable_wrapCallback=function(M){var T=S;return function(){var O=S;S=T;try{return M.apply(this,arguments)}finally{S=O}}}})(Yg)),Yg}var o1;function xN(){return o1||(o1=1,Vg.exports=wN()),Vg.exports}var Gg={exports:{}},Bi={};var l1;function CN(){if(l1)return Bi;l1=1;var e=Zb();function t(m){var p="https://react.dev/errors/"+m;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var b=2;b<arguments.length;b++)p+="&args[]="+encodeURIComponent(arguments[b])}return"Minified React error #"+m+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var s={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},o=Symbol.for("react.portal");function l(m,p,b){var _=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:o,key:_==null?null:""+_,children:m,containerInfo:p,implementation:b}}var d=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function f(m,p){if(m==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return Bi.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,Bi.createPortal=function(m,p){var b=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(t(299));return l(m,p,null,b)},Bi.flushSync=function(m){var p=d.T,b=s.p;try{if(d.T=null,s.p=2,m)return m()}finally{d.T=p,s.p=b,s.d.f()}},Bi.preconnect=function(m,p){typeof m=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,s.d.C(m,p))},Bi.prefetchDNS=function(m){typeof m=="string"&&s.d.D(m)},Bi.preinit=function(m,p){if(typeof m=="string"&&p&&typeof p.as=="string"){var b=p.as,_=f(b,p.crossOrigin),S=typeof p.integrity=="string"?p.integrity:void 0,w=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;b==="style"?s.d.S(m,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:_,integrity:S,fetchPriority:w}):b==="script"&&s.d.X(m,{crossOrigin:_,integrity:S,fetchPriority:w,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},Bi.preinitModule=function(m,p){if(typeof m=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var b=f(p.as,p.crossOrigin);s.d.M(m,{crossOrigin:b,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&s.d.M(m)},Bi.preload=function(m,p){if(typeof m=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var b=p.as,_=f(b,p.crossOrigin);s.d.L(m,b,{crossOrigin:_,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},Bi.preloadModule=function(m,p){if(typeof m=="string")if(p){var b=f(p.as,p.crossOrigin);s.d.m(m,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:b,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else s.d.m(m)},Bi.requestFormReset=function(m){s.d.r(m)},Bi.unstable_batchedUpdates=function(m,p){return m(p)},Bi.useFormState=function(m,p,b){return d.H.useFormState(m,p,b)},Bi.useFormStatus=function(){return d.H.useHostTransitionStatus()},Bi.version="19.2.6",Bi}var c1;function XC(){if(c1)return Gg.exports;c1=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(),Gg.exports=CN(),Gg.exports}var u1;function kN(){if(u1)return ad;u1=1;var e=xN(),t=Zb(),n=XC();function s(i){var r="https://react.dev/errors/"+i;if(1<arguments.length){r+="?args[]="+encodeURIComponent(arguments[1]);for(var a=2;a<arguments.length;a++)r+="&args[]="+encodeURIComponent(arguments[a])}return"Minified React error #"+i+"; visit "+r+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function l(i){var r=i,a=i;if(i.alternate)for(;r.return;)r=r.return;else{i=r;do r=i,(r.flags&4098)!==0&&(a=r.return),i=r.return;while(i)}return r.tag===3?a:null}function d(i){if(i.tag===13){var r=i.memoizedState;if(r===null&&(i=i.alternate,i!==null&&(r=i.memoizedState)),r!==null)return r.dehydrated}return null}function f(i){if(i.tag===31){var r=i.memoizedState;if(r===null&&(i=i.alternate,i!==null&&(r=i.memoizedState)),r!==null)return r.dehydrated}return null}function m(i){if(l(i)!==i)throw Error(s(188))}function p(i){var r=i.alternate;if(!r){if(r=l(i),r===null)throw Error(s(188));return r!==i?null:i}for(var a=i,c=r;;){var h=a.return;if(h===null)break;var g=h.alternate;if(g===null){if(c=h.return,c!==null){a=c;continue}break}if(h.child===g.child){for(g=h.child;g;){if(g===a)return m(h),i;if(g===c)return m(h),r;g=g.sibling}throw Error(s(188))}if(a.return!==c.return)a=h,c=g;else{for(var y=!1,D=h.child;D;){if(D===a){y=!0,a=h,c=g;break}if(D===c){y=!0,c=h,a=g;break}D=D.sibling}if(!y){for(D=g.child;D;){if(D===a){y=!0,a=g,c=h;break}if(D===c){y=!0,c=g,a=h;break}D=D.sibling}if(!y)throw Error(s(189))}}if(a.alternate!==c)throw Error(s(190))}if(a.tag!==3)throw Error(s(188));return a.stateNode.current===a?i:r}function b(i){var r=i.tag;if(r===5||r===26||r===27||r===6)return i;for(i=i.child;i!==null;){if(r=b(i),r!==null)return r;i=i.sibling}return null}var _=Object.assign,S=Symbol.for("react.element"),w=Symbol.for("react.transitional.element"),x=Symbol.for("react.portal"),R=Symbol.for("react.fragment"),L=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),W=Symbol.for("react.consumer"),H=Symbol.for("react.context"),U=Symbol.for("react.forward_ref"),q=Symbol.for("react.suspense"),Y=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),de=Symbol.for("react.activity"),me=Symbol.for("react.memo_cache_sentinel"),K=Symbol.iterator;function te(i){return i===null||typeof i!="object"?null:(i=K&&i[K]||i["@@iterator"],typeof i=="function"?i:null)}var J=Symbol.for("react.client.reference");function Q(i){if(i==null)return null;if(typeof i=="function")return i.$$typeof===J?null:i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case R:return"Fragment";case A:return"Profiler";case L:return"StrictMode";case q:return"Suspense";case Y:return"SuspenseList";case de:return"Activity"}if(typeof i=="object")switch(i.$$typeof){case x:return"Portal";case H:return i.displayName||"Context";case W:return(i._context.displayName||"Context")+".Consumer";case U:var r=i.render;return i=i.displayName,i||(i=r.displayName||r.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case I:return r=i.displayName||null,r!==null?r:Q(i.type)||"Memo";case F:r=i._payload,i=i._init;try{return Q(i(r))}catch{}}return null}var X=Array.isArray,M=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,T=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,O={pending:!1,data:null,method:null,action:null},re=[],he=-1;function N(i){return{current:i}}function V(i){0>he||(i.current=re[he],re[he]=null,he--)}function se(i,r){he++,re[he]=i.current,i.current=r}var Z=N(null),Ee=N(null),ye=N(null),ze=N(null);function Ke(i,r){switch(se(ye,r),se(Ee,i),se(Z,null),r.nodeType){case 9:case 11:i=(i=r.documentElement)&&(i=i.namespaceURI)?kw(i):0;break;default:if(i=r.tagName,r=r.namespaceURI)r=kw(r),i=Tw(r,i);else switch(i){case"svg":i=1;break;case"math":i=2;break;default:i=0}}V(Z),se(Z,i)}function Be(){V(Z),V(Ee),V(ye)}function ve(i){i.memoizedState!==null&&se(ze,i);var r=Z.current,a=Tw(r,i.type);r!==a&&(se(Ee,i),se(Z,a))}function Fe(i){Ee.current===i&&(V(Z),V(Ee)),ze.current===i&&(V(ze),td._currentValue=O)}var Ie,j;function ge(i){if(Ie===void 0)try{throw Error()}catch(a){var r=a.stack.trim().match(/\n( *(at )?)/);Ie=r&&r[1]||"",j=-1<a.stack.indexOf(`
3
+ at`)?" (<anonymous>)":-1<a.stack.indexOf("@")?"@unknown:0:0":""}return`
4
+ `+Ie+i+j}var Ae=!1;function Oe(i,r){if(!i||Ae)return"";Ae=!0;var a=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var c={DetermineComponentFrameRoot:function(){try{if(r){var Re=function(){throw Error()};if(Object.defineProperty(Re.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Re,[])}catch(_e){var pe=_e}Reflect.construct(i,[],Re)}else{try{Re.call()}catch(_e){pe=_e}i.call(Re.prototype)}}else{try{throw Error()}catch(_e){pe=_e}(Re=i())&&typeof Re.catch=="function"&&Re.catch(function(){})}}catch(_e){if(_e&&pe&&typeof _e.stack=="string")return[_e.stack,pe.stack]}return[null,null]}};c.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var h=Object.getOwnPropertyDescriptor(c.DetermineComponentFrameRoot,"name");h&&h.configurable&&Object.defineProperty(c.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var g=c.DetermineComponentFrameRoot(),y=g[0],D=g[1];if(y&&D){var $=y.split(`
5
+ `),ue=D.split(`
6
+ `);for(h=c=0;c<$.length&&!$[c].includes("DetermineComponentFrameRoot");)c++;for(;h<ue.length&&!ue[h].includes("DetermineComponentFrameRoot");)h++;if(c===$.length||h===ue.length)for(c=$.length-1,h=ue.length-1;1<=c&&0<=h&&$[c]!==ue[h];)h--;for(;1<=c&&0<=h;c--,h--)if($[c]!==ue[h]){if(c!==1||h!==1)do if(c--,h--,0>h||$[c]!==ue[h]){var Se=`
7
+ `+$[c].replace(" at new "," at ");return i.displayName&&Se.includes("<anonymous>")&&(Se=Se.replace("<anonymous>",i.displayName)),Se}while(1<=c&&0<=h);break}}}finally{Ae=!1,Error.prepareStackTrace=a}return(a=i?i.displayName||i.name:"")?ge(a):""}function z(i,r){switch(i.tag){case 26:case 27:case 5:return ge(i.type);case 16:return ge("Lazy");case 13:return i.child!==r&&r!==null?ge("Suspense Fallback"):ge("Suspense");case 19:return ge("SuspenseList");case 0:case 15:return Oe(i.type,!1);case 11:return Oe(i.type.render,!1);case 1:return Oe(i.type,!0);case 31:return ge("Activity");default:return""}}function fe(i){try{var r="",a=null;do r+=z(i,a),a=i,i=i.return;while(i);return r}catch(c){return`
8
+ Error generating stack: `+c.message+`
9
+ `+c.stack}}var Te=Object.prototype.hasOwnProperty,Ne=e.unstable_scheduleCallback,Le=e.unstable_cancelCallback,be=e.unstable_shouldYield,$e=e.unstable_requestPaint,qe=e.unstable_now,je=e.unstable_getCurrentPriorityLevel,ht=e.unstable_ImmediatePriority,st=e.unstable_UserBlockingPriority,mt=e.unstable_NormalPriority,xt=e.unstable_LowPriority,on=e.unstable_IdlePriority,ot=e.log,Dn=e.unstable_setDisableYieldValue,Tn=null,ft=null;function Dt(i){if(typeof ot=="function"&&Dn(i),ft&&typeof ft.setStrictMode=="function")try{ft.setStrictMode(Tn,i)}catch{}}var Mt=Math.clz32?Math.clz32:xi,wi=Math.log,di=Math.LN2;function xi(i){return i>>>=0,i===0?32:31-(wi(i)/di|0)|0}var At=256,ae=262144,Pe=4194304;function tt(i){var r=i&42;if(r!==0)return r;switch(i&-i){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return i&261888;case 262144:case 524288:case 1048576:case 2097152:return i&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return i&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return i}}function _t(i,r,a){var c=i.pendingLanes;if(c===0)return 0;var h=0,g=i.suspendedLanes,y=i.pingedLanes;i=i.warmLanes;var D=c&134217727;return D!==0?(c=D&~g,c!==0?h=tt(c):(y&=D,y!==0?h=tt(y):a||(a=D&~i,a!==0&&(h=tt(a))))):(D=c&~g,D!==0?h=tt(D):y!==0?h=tt(y):a||(a=c&~i,a!==0&&(h=tt(a)))),h===0?0:r!==0&&r!==h&&(r&g)===0&&(g=h&-h,a=r&-r,g>=a||g===32&&(a&4194048)!==0)?r:h}function $t(i,r){return(i.pendingLanes&~(i.suspendedLanes&~i.pingedLanes)&r)===0}function en(i,r){switch(i){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ft(){var i=Pe;return Pe<<=1,(Pe&62914560)===0&&(Pe=4194304),i}function mn(i){for(var r=[],a=0;31>a;a++)r.push(i);return r}function Bn(i,r){i.pendingLanes|=r,r!==268435456&&(i.suspendedLanes=0,i.pingedLanes=0,i.warmLanes=0)}function Ct(i,r,a,c,h,g){var y=i.pendingLanes;i.pendingLanes=a,i.suspendedLanes=0,i.pingedLanes=0,i.warmLanes=0,i.expiredLanes&=a,i.entangledLanes&=a,i.errorRecoveryDisabledLanes&=a,i.shellSuspendCounter=0;var D=i.entanglements,$=i.expirationTimes,ue=i.hiddenUpdates;for(a=y&~a;0<a;){var Se=31-Mt(a),Re=1<<Se;D[Se]=0,$[Se]=-1;var pe=ue[Se];if(pe!==null)for(ue[Se]=null,Se=0;Se<pe.length;Se++){var _e=pe[Se];_e!==null&&(_e.lane&=-536870913)}a&=~Re}c!==0&&ln(i,c,0),g!==0&&h===0&&i.tag!==0&&(i.suspendedLanes|=g&~(y&~r))}function ln(i,r,a){i.pendingLanes|=r,i.suspendedLanes&=~r;var c=31-Mt(r);i.entangledLanes|=r,i.entanglements[c]=i.entanglements[c]|1073741824|a&261930}function cn(i,r){var a=i.entangledLanes|=r;for(i=i.entanglements;a;){var c=31-Mt(a),h=1<<c;h&r|i[c]&r&&(i[c]|=r),a&=~h}}function Kn(i,r){var a=r&-r;return a=(a&42)!==0?1:In(a),(a&(i.suspendedLanes|r))!==0?0:a}function In(i){switch(i){case 2:i=1;break;case 8:i=4;break;case 32:i=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:i=128;break;case 268435456:i=134217728;break;default:i=0}return i}function rt(i){return i&=-i,2<i?8<i?(i&134217727)!==0?32:268435456:8:2}function Tt(){var i=T.p;return i!==0?i:(i=window.event,i===void 0?32:Gw(i.type))}function gn(i,r){var a=T.p;try{return T.p=i,r()}finally{T.p=a}}var oe=Math.random().toString(36).slice(2),ke="__reactFiber$"+oe,Ge="__reactProps$"+oe,Je="__reactContainer$"+oe,Ze="__reactEvents$"+oe,tn="__reactListeners$"+oe,Sn="__reactHandles$"+oe,Gi="__reactResources$"+oe,Xt="__reactMarker$"+oe;function Xi(i){delete i[ke],delete i[Ge],delete i[Ze],delete i[tn],delete i[Sn]}function qn(i){var r=i[ke];if(r)return r;for(var a=i.parentNode;a;){if(r=a[Je]||a[ke]){if(a=r.alternate,r.child!==null||a!==null&&a.child!==null)for(i=Lw(i);i!==null;){if(a=i[ke])return a;i=Lw(i)}return r}i=a,a=i.parentNode}return null}function Mn(i){if(i=i[ke]||i[Je]){var r=i.tag;if(r===5||r===6||r===13||r===31||r===26||r===27||r===3)return i}return null}function Ri(i){var r=i.tag;if(r===5||r===26||r===27||r===6)return i.stateNode;throw Error(s(33))}function Zi(i){var r=i[Gi];return r||(r=i[Gi]={hoistableStyles:new Map,hoistableScripts:new Map}),r}function Wt(i){i[Xt]=!0}var Ks=new Set,dr={};function Qi(i,r){Ni(i,r),Ni(i+"Capture",r)}function Ni(i,r){for(dr[i]=r,i=0;i<r.length;i++)Ks.add(r[i])}var Yl=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),Ha={},qs={};function hi(i){return Te.call(qs,i)?!0:Te.call(Ha,i)?!1:Yl.test(i)?qs[i]=!0:(Ha[i]=!0,!1)}function zi(i,r,a){if(hi(r))if(a===null)i.removeAttribute(r);else{switch(typeof a){case"undefined":case"function":case"symbol":i.removeAttribute(r);return;case"boolean":var c=r.toLowerCase().slice(0,5);if(c!=="data-"&&c!=="aria-"){i.removeAttribute(r);return}}i.setAttribute(r,""+a)}}function Vs(i,r,a){if(a===null)i.removeAttribute(r);else{switch(typeof a){case"undefined":case"function":case"symbol":case"boolean":i.removeAttribute(r);return}i.setAttribute(r,""+a)}}function ni(i,r,a,c){if(c===null)i.removeAttribute(a);else{switch(typeof c){case"undefined":case"function":case"symbol":case"boolean":i.removeAttribute(a);return}i.setAttributeNS(r,a,""+c)}}function Pn(i){switch(typeof i){case"bigint":case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function Ys(i){var r=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(r==="checkbox"||r==="radio")}function gs(i,r,a){var c=Object.getOwnPropertyDescriptor(i.constructor.prototype,r);if(!i.hasOwnProperty(r)&&typeof c<"u"&&typeof c.get=="function"&&typeof c.set=="function"){var h=c.get,g=c.set;return Object.defineProperty(i,r,{configurable:!0,get:function(){return h.call(this)},set:function(y){a=""+y,g.call(this,y)}}),Object.defineProperty(i,r,{enumerable:c.enumerable}),{getValue:function(){return a},setValue:function(y){a=""+y},stopTracking:function(){i._valueTracker=null,delete i[r]}}}}function Gs(i){if(!i._valueTracker){var r=Ys(i)?"checked":"value";i._valueTracker=gs(i,r,""+i[r])}}function Ua(i){if(!i)return!1;var r=i._valueTracker;if(!r)return!0;var a=r.getValue(),c="";return i&&(c=Ys(i)?i.checked?"true":"false":i.value),i=c,i!==a?(r.setValue(i),!0):!1}function Di(i){if(i=i||(typeof document<"u"?document:void 0),typeof i>"u")return null;try{return i.activeElement||i.body}catch{return i.body}}var Gl=/[\n"\\]/g;function ii(i){return i.replace(Gl,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function vs(i,r,a,c,h,g,y,D){i.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?i.type=y:i.removeAttribute("type"),r!=null?y==="number"?(r===0&&i.value===""||i.value!=r)&&(i.value=""+Pn(r)):i.value!==""+Pn(r)&&(i.value=""+Pn(r)):y!=="submit"&&y!=="reset"||i.removeAttribute("value"),r!=null?Xs(i,y,Pn(r)):a!=null?Xs(i,y,Pn(a)):c!=null&&i.removeAttribute("value"),h==null&&g!=null&&(i.defaultChecked=!!g),h!=null&&(i.checked=h&&typeof h!="function"&&typeof h!="symbol"),D!=null&&typeof D!="function"&&typeof D!="symbol"&&typeof D!="boolean"?i.name=""+Pn(D):i.removeAttribute("name")}function Ko(i,r,a,c,h,g,y,D){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(i.type=g),r!=null||a!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){Gs(i);return}a=a!=null?""+Pn(a):"",r=r!=null?""+Pn(r):a,D||r===i.value||(i.value=r),i.defaultValue=r}c=c??h,c=typeof c!="function"&&typeof c!="symbol"&&!!c,i.checked=D?i.checked:!!c,i.defaultChecked=!!c,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(i.name=y),Gs(i)}function Xs(i,r,a){r==="number"&&Di(i.ownerDocument)===i||i.defaultValue===""+a||(i.defaultValue=""+a)}function hr(i,r,a,c){if(i=i.options,r){r={};for(var h=0;h<a.length;h++)r["$"+a[h]]=!0;for(a=0;a<i.length;a++)h=r.hasOwnProperty("$"+i[a].value),i[a].selected!==h&&(i[a].selected=h),h&&c&&(i[a].defaultSelected=!0)}else{for(a=""+Pn(a),r=null,h=0;h<i.length;h++){if(i[h].value===a){i[h].selected=!0,c&&(i[h].defaultSelected=!0);return}r!==null||i[h].disabled||(r=i[h])}r!==null&&(r.selected=!0)}}function $a(i,r,a){if(r!=null&&(r=""+Pn(r),r!==i.value&&(i.value=r),a==null)){i.defaultValue!==r&&(i.defaultValue=r);return}i.defaultValue=a!=null?""+Pn(a):""}function Zs(i,r,a,c){if(r==null){if(c!=null){if(a!=null)throw Error(s(92));if(X(c)){if(1<c.length)throw Error(s(93));c=c[0]}a=c}a==null&&(a=""),r=a}a=Pn(r),i.defaultValue=a,c=i.textContent,c===a&&c!==""&&c!==null&&(i.value=c),Gs(i)}function _s(i,r){if(r){var a=i.firstChild;if(a&&a===i.lastChild&&a.nodeType===3){a.nodeValue=r;return}}i.textContent=r}var Xl=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Zl(i,r,a){var c=r.indexOf("--")===0;a==null||typeof a=="boolean"||a===""?c?i.setProperty(r,""):r==="float"?i.cssFloat="":i[r]="":c?i.setProperty(r,a):typeof a!="number"||a===0||Xl.has(r)?r==="float"?i.cssFloat=a:i[r]=(""+a).trim():i[r]=a+"px"}function qo(i,r,a){if(r!=null&&typeof r!="object")throw Error(s(62));if(i=i.style,a!=null){for(var c in a)!a.hasOwnProperty(c)||r!=null&&r.hasOwnProperty(c)||(c.indexOf("--")===0?i.setProperty(c,""):c==="float"?i.cssFloat="":i[c]="");for(var h in r)c=r[h],r.hasOwnProperty(h)&&a[h]!==c&&Zl(i,h,c)}else for(var g in r)r.hasOwnProperty(g)&&Zl(i,g,r[g])}function Vo(i){if(i.indexOf("-")===-1)return!1;switch(i){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Hi=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),Yo=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function ts(i){return Yo.test(""+i)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":i}function Mi(){}var Dr=null;function pn(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var Mr=null,Ar=null;function Fa(i){var r=Mn(i);if(r&&(i=r.stateNode)){var a=i[Ge]||null;e:switch(i=r.stateNode,r.type){case"input":if(vs(i,a.value,a.defaultValue,a.defaultValue,a.checked,a.defaultChecked,a.type,a.name),r=a.name,a.type==="radio"&&r!=null){for(a=i;a.parentNode;)a=a.parentNode;for(a=a.querySelectorAll('input[name="'+ii(""+r)+'"][type="radio"]'),r=0;r<a.length;r++){var c=a[r];if(c!==i&&c.form===i.form){var h=c[Ge]||null;if(!h)throw Error(s(90));vs(c,h.value,h.defaultValue,h.defaultValue,h.checked,h.defaultChecked,h.type,h.name)}}for(r=0;r<a.length;r++)c=a[r],c.form===i.form&&Ua(c)}break e;case"textarea":$a(i,a.value,a.defaultValue);break e;case"select":r=a.value,r!=null&&hr(i,!!a.multiple,r,!1)}}}var ns=!1;function Ai(i,r,a){if(ns)return i(r,a);ns=!0;try{var c=i(r);return c}finally{if(ns=!1,(Mr!==null||Ar!==null)&&(Jh(),Mr&&(r=Mr,i=Ar,Ar=Mr=null,Fa(r),i)))for(r=0;r<i.length;r++)Fa(i[r])}}function is(i,r){var a=i.stateNode;if(a===null)return null;var c=a[Ge]||null;if(c===null)return null;a=c[r];e:switch(r){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(c=!c.disabled)||(i=i.type,c=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!c;break e;default:i=!1}if(i)return null;if(a&&typeof a!="function")throw Error(s(231,r,typeof a));return a}var fr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Lr=!1;if(fr)try{var rs={};Object.defineProperty(rs,"passive",{get:function(){Lr=!0}}),window.addEventListener("test",rs,rs),window.removeEventListener("test",rs,rs)}catch{Lr=!1}var jr=null,Qs=null,bs=null;function Js(){if(bs)return bs;var i,r=Qs,a=r.length,c,h="value"in jr?jr.value:jr.textContent,g=h.length;for(i=0;i<a&&r[i]===h[i];i++);var y=a-i;for(c=1;c<=y&&r[a-c]===h[g-c];c++);return bs=h.slice(i,1<c?1-c:void 0)}function ys(i){var r=i.keyCode;return"charCode"in i?(i=i.charCode,i===0&&r===13&&(i=13)):i=r,i===10&&(i=13),32<=i||i===13?i:0}function Ji(){return!0}function Ui(){return!1}function un(i){function r(a,c,h,g,y){this._reactName=a,this._targetInst=h,this.type=c,this.nativeEvent=g,this.target=y,this.currentTarget=null;for(var D in i)i.hasOwnProperty(D)&&(a=i[D],this[D]=a?a(g):g[D]);return this.isDefaultPrevented=(g.defaultPrevented!=null?g.defaultPrevented:g.returnValue===!1)?Ji:Ui,this.isPropagationStopped=Ui,this}return _(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():typeof a.returnValue!="unknown"&&(a.returnValue=!1),this.isDefaultPrevented=Ji)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():typeof a.cancelBubble!="unknown"&&(a.cancelBubble=!0),this.isPropagationStopped=Ji)},persist:function(){},isPersistent:Ji}),r}var pr={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},pt=un(pr),Or=_({},pr,{view:0,detail:0}),Ss=un(Or),Wa,mr,ws,ea=_({},Or,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Ka,button:0,buttons:0,relatedTarget:function(i){return i.relatedTarget===void 0?i.fromElement===i.srcElement?i.toElement:i.fromElement:i.relatedTarget},movementX:function(i){return"movementX"in i?i.movementX:(i!==ws&&(ws&&i.type==="mousemove"?(Wa=i.screenX-ws.screenX,mr=i.screenY-ws.screenY):mr=Wa=0,ws=i),Wa)},movementY:function(i){return"movementY"in i?i.movementY:mr}}),Go=un(ea),Ql=_({},ea,{dataTransfer:0}),Br=un(Ql),cu=_({},Or,{relatedTarget:0}),ta=un(cu),gr=_({},pr,{animationName:0,elapsedTime:0,pseudoElement:0}),Jl=un(gr),Xo=_({},pr,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),na=un(Xo),Zo=_({},pr,{data:0}),vr=un(Zo),ss={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},uu={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},fi={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Qo(i){var r=this.nativeEvent;return r.getModifierState?r.getModifierState(i):(i=fi[i])?!!r[i]:!1}function Ka(){return Qo}var as=_({},Or,{key:function(i){if(i.key){var r=ss[i.key]||i.key;if(r!=="Unidentified")return r}return i.type==="keypress"?(i=ys(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?uu[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Ka,charCode:function(i){return i.type==="keypress"?ys(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?ys(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),ec=un(as),ia=_({},ea,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Jo=un(ia),xs=_({},Or,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ka}),Ir=un(xs),tc=_({},pr,{propertyName:0,elapsedTime:0,pseudoElement:0}),el=un(tc),tl=_({},ea,{deltaX:function(i){return"deltaX"in i?i.deltaX:"wheelDeltaX"in i?-i.wheelDeltaX:0},deltaY:function(i){return"deltaY"in i?i.deltaY:"wheelDeltaY"in i?-i.wheelDeltaY:"wheelDelta"in i?-i.wheelDelta:0},deltaZ:0,deltaMode:0}),qa=un(tl),er=_({},pr,{newState:0,oldState:0}),Va=un(er),nc=[9,13,27,32],ra=fr&&"CompositionEvent"in window,_r=null;fr&&"documentMode"in document&&(_r=document.documentMode);var C=fr&&"TextEvent"in window&&!_r,E=fr&&(!ra||_r&&8<_r&&11>=_r),B=" ",ee=!1;function ie(i,r){switch(i){case"keyup":return nc.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function le(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var we=!1;function Ue(i,r){switch(i){case"compositionend":return le(r);case"keypress":return r.which!==32?null:(ee=!0,B);case"textInput":return i=r.data,i===B&&ee?null:i;default:return null}}function Ye(i,r){if(we)return i==="compositionend"||!ra&&ie(i,r)?(i=Js(),bs=Qs=jr=null,we=!1,i):null;switch(i){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1<r.char.length)return r.char;if(r.which)return String.fromCharCode(r.which)}return null;case"compositionend":return E&&r.locale!=="ko"?null:r.data;default:return null}}var We={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function St(i){var r=i&&i.nodeName&&i.nodeName.toLowerCase();return r==="input"?!!We[i.type]:r==="textarea"}function Vt(i,r,a,c){Mr?Ar?Ar.push(c):Ar=[c]:Mr=c,r=of(r,"onChange"),0<r.length&&(a=new pt("onChange","change",null,a,c),i.push({event:a,listeners:r}))}var Bt=null,vn=null;function Cs(i){bw(i,0)}function Ya(i){var r=Ri(i);if(Ua(r))return i}function ic(i,r){if(i==="change")return r}var nl=!1;if(fr){var ks;if(fr){var il="oninput"in document;if(!il){var du=document.createElement("div");du.setAttribute("oninput","return;"),il=typeof du.oninput=="function"}ks=il}else ks=!1;nl=ks&&(!document.documentMode||9<document.documentMode)}function pi(){Bt&&(Bt.detachEvent("onpropertychange",rl),vn=Bt=null)}function rl(i){if(i.propertyName==="value"&&Ya(vn)){var r=[];Vt(r,vn,i,pn(i)),Ai(Cs,r)}}function rc(i,r,a){i==="focusin"?(pi(),Bt=r,vn=a,Bt.attachEvent("onpropertychange",rl)):i==="focusout"&&pi()}function bh(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return Ya(vn)}function yh(i,r){if(i==="click")return Ya(r)}function sl(i,r){if(i==="input"||i==="change")return Ya(r)}function Ga(i,r){return i===r&&(i!==0||1/i===1/r)||i!==i&&r!==r}var Li=typeof Object.is=="function"?Object.is:Ga;function Pr(i,r){if(Li(i,r))return!0;if(typeof i!="object"||i===null||typeof r!="object"||r===null)return!1;var a=Object.keys(i),c=Object.keys(r);if(a.length!==c.length)return!1;for(c=0;c<a.length;c++){var h=a[c];if(!Te.call(r,h)||!Li(i[h],r[h]))return!1}return!0}function Vn(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function Sh(i,r){var a=Vn(i);i=0;for(var c;a;){if(a.nodeType===3){if(c=i+a.textContent.length,i<=r&&c>=r)return{node:a,offset:r-i};i=c}e:{for(;a;){if(a.nextSibling){a=a.nextSibling;break e}a=a.parentNode}a=void 0}a=Vn(a)}}function hu(i,r){return i&&r?i===r?!0:i&&i.nodeType===3?!1:r&&r.nodeType===3?hu(i,r.parentNode):"contains"in i?i.contains(r):i.compareDocumentPosition?!!(i.compareDocumentPosition(r)&16):!1:!1}function fu(i){i=i!=null&&i.ownerDocument!=null&&i.ownerDocument.defaultView!=null?i.ownerDocument.defaultView:window;for(var r=Di(i.document);r instanceof i.HTMLIFrameElement;){try{var a=typeof r.contentWindow.location.href=="string"}catch{a=!1}if(a)i=r.contentWindow;else break;r=Di(i.document)}return r}function sc(i){var r=i&&i.nodeName&&i.nodeName.toLowerCase();return r&&(r==="input"&&(i.type==="text"||i.type==="search"||i.type==="tel"||i.type==="url"||i.type==="password")||r==="textarea"||i.contentEditable==="true")}var pm=fr&&"documentMode"in document&&11>=document.documentMode,sa=null,tr=null,aa=null,pu=!1;function oa(i,r,a){var c=a.window===a?a.document:a.nodeType===9?a:a.ownerDocument;pu||sa==null||sa!==Di(c)||(c=sa,"selectionStart"in c&&sc(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset}),aa&&Pr(aa,c)||(aa=c,c=of(tr,"onSelect"),0<c.length&&(r=new pt("onSelect","select",null,r,a),i.push({event:r,listeners:c}),r.target=sa)))}function zr(i,r){var a={};return a[i.toLowerCase()]=r.toLowerCase(),a["Webkit"+i]="webkit"+r,a["Moz"+i]="moz"+r,a}var la={animationend:zr("Animation","AnimationEnd"),animationiteration:zr("Animation","AnimationIteration"),animationstart:zr("Animation","AnimationStart"),transitionrun:zr("Transition","TransitionRun"),transitionstart:zr("Transition","TransitionStart"),transitioncancel:zr("Transition","TransitionCancel"),transitionend:zr("Transition","TransitionEnd")},mu={},gu={};fr&&(gu=document.createElement("div").style,"AnimationEvent"in window||(delete la.animationend.animation,delete la.animationiteration.animation,delete la.animationstart.animation),"TransitionEvent"in window||delete la.transitionend.transition);function Ts(i){if(mu[i])return mu[i];if(!la[i])return i;var r=la[i],a;for(a in r)if(r.hasOwnProperty(a)&&a in gu)return mu[i]=r[a];return i}var vu=Ts("animationend"),_u=Ts("animationiteration"),bu=Ts("animationstart"),yu=Ts("transitionrun"),Su=Ts("transitionstart"),mm=Ts("transitioncancel"),al=Ts("transitionend"),ol=new Map,ac="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");ac.push("scrollEnd");function br(i,r){ol.set(i,r),Qi(r,[i])}var Xa=typeof reportError=="function"?reportError:function(i){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var r=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof i=="object"&&i!==null&&typeof i.message=="string"?String(i.message):String(i),error:i});if(!window.dispatchEvent(r))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",i);return}console.error(i)},ji=[],Es=0,Rs=0;function ll(){for(var i=Es,r=Rs=Es=0;r<i;){var a=ji[r];ji[r++]=null;var c=ji[r];ji[r++]=null;var h=ji[r];ji[r++]=null;var g=ji[r];if(ji[r++]=null,c!==null&&h!==null){var y=c.pending;y===null?h.next=h:(h.next=y.next,y.next=h),c.pending=h}g!==0&&wh(a,h,g)}}function cl(i,r,a,c){ji[Es++]=i,ji[Es++]=r,ji[Es++]=a,ji[Es++]=c,Rs|=c,i.lanes|=c,i=i.alternate,i!==null&&(i.lanes|=c)}function wu(i,r,a,c){return cl(i,r,a,c),oc(i)}function Ns(i,r){return cl(i,null,null,r),oc(i)}function wh(i,r,a){i.lanes|=a;var c=i.alternate;c!==null&&(c.lanes|=a);for(var h=!1,g=i.return;g!==null;)g.childLanes|=a,c=g.alternate,c!==null&&(c.childLanes|=a),g.tag===22&&(i=g.stateNode,i===null||i._visibility&1||(h=!0)),i=g,g=g.return;return i.tag===3?(g=i.stateNode,h&&r!==null&&(h=31-Mt(a),i=g.hiddenUpdates,c=i[h],c===null?i[h]=[r]:c.push(r),r.lane=a|536870912),g):null}function oc(i){if(50<Yu)throw Yu=0,pg=null,Error(s(185));for(var r=i.return;r!==null;)i=r,r=i.return;return i.tag===3?i.stateNode:null}var Za={};function Qa(i,r,a,c){this.tag=i,this.key=a,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=r,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=c,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ci(i,r,a,c){return new Qa(i,r,a,c)}function ca(i){return i=i.prototype,!(!i||!i.isReactComponent)}function Hr(i,r){var a=i.alternate;return a===null?(a=Ci(i.tag,r,i.key,i.mode),a.elementType=i.elementType,a.type=i.type,a.stateNode=i.stateNode,a.alternate=i,i.alternate=a):(a.pendingProps=r,a.type=i.type,a.flags=0,a.subtreeFlags=0,a.deletions=null),a.flags=i.flags&65011712,a.childLanes=i.childLanes,a.lanes=i.lanes,a.child=i.child,a.memoizedProps=i.memoizedProps,a.memoizedState=i.memoizedState,a.updateQueue=i.updateQueue,r=i.dependencies,a.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext},a.sibling=i.sibling,a.index=i.index,a.ref=i.ref,a.refCleanup=i.refCleanup,a}function xu(i,r){i.flags&=65011714;var a=i.alternate;return a===null?(i.childLanes=0,i.lanes=r,i.child=null,i.subtreeFlags=0,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=a.childLanes,i.lanes=a.lanes,i.child=a.child,i.subtreeFlags=0,i.deletions=null,i.memoizedProps=a.memoizedProps,i.memoizedState=a.memoizedState,i.updateQueue=a.updateQueue,i.type=a.type,r=a.dependencies,i.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),i}function lc(i,r,a,c,h,g){var y=0;if(c=i,typeof i=="function")ca(i)&&(y=1);else if(typeof i=="string")y=aN(i,a,Z.current)?26:i==="html"||i==="head"||i==="body"?27:5;else e:switch(i){case de:return i=Ci(31,a,r,h),i.elementType=de,i.lanes=g,i;case R:return Ds(a.children,h,g,r);case L:y=8,h|=24;break;case A:return i=Ci(12,a,r,h|2),i.elementType=A,i.lanes=g,i;case q:return i=Ci(13,a,r,h),i.elementType=q,i.lanes=g,i;case Y:return i=Ci(19,a,r,h),i.elementType=Y,i.lanes=g,i;default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case H:y=10;break e;case W:y=9;break e;case U:y=11;break e;case I:y=14;break e;case F:y=16,c=null;break e}y=29,a=Error(s(130,i===null?"null":typeof i,"")),c=null}return r=Ci(y,a,r,h),r.elementType=i,r.type=c,r.lanes=g,r}function Ds(i,r,a,c){return i=Ci(7,i,c,r),i.lanes=a,i}function cc(i,r,a){return i=Ci(6,i,null,r),i.lanes=a,i}function Cu(i){var r=Ci(18,null,null,0);return r.stateNode=i,r}function ku(i,r,a){return r=Ci(4,i.children!==null?i.children:[],i.key,r),r.lanes=a,r.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},r}var Tu=new WeakMap;function zn(i,r){if(typeof i=="object"&&i!==null){var a=Tu.get(i);return a!==void 0?a:(r={value:i,source:r,stack:fe(r)},Tu.set(i,r),r)}return{value:i,source:r,stack:fe(r)}}var Ja=[],eo=0,ul=null,dl=0,nr=[],Hn=0,Ms=null,yr=1,Ur="";function os(i,r){Ja[eo++]=dl,Ja[eo++]=ul,ul=i,dl=r}function xh(i,r,a){nr[Hn++]=yr,nr[Hn++]=Ur,nr[Hn++]=Ms,Ms=i;var c=yr;i=Ur;var h=32-Mt(c)-1;c&=~(1<<h),a+=1;var g=32-Mt(r)+h;if(30<g){var y=h-h%5;g=(c&(1<<y)-1).toString(32),c>>=y,h-=y,yr=1<<32-Mt(r)+h|a<<h|c,Ur=g+i}else yr=1<<g|a<<h|c,Ur=i}function Eu(i){i.return!==null&&(os(i,1),xh(i,1,0))}function uc(i){for(;i===ul;)ul=Ja[--eo],Ja[eo]=null,dl=Ja[--eo],Ja[eo]=null;for(;i===Ms;)Ms=nr[--Hn],nr[Hn]=null,Ur=nr[--Hn],nr[Hn]=null,yr=nr[--Hn],nr[Hn]=null}function $r(i,r){nr[Hn++]=yr,nr[Hn++]=Ur,nr[Hn++]=Ms,yr=r.id,Ur=r.overflow,Ms=i}var ri=null,dn=null,Et=!1,$i=null,ir=!1,Ru=Error(s(519));function ls(i){var r=Error(s(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw ct(zn(r,i)),Ru}function k(i){var r=i.stateNode,a=i.type,c=i.memoizedProps;switch(r[ke]=i,r[Ge]=c,a){case"dialog":Ot("cancel",r),Ot("close",r);break;case"iframe":case"object":case"embed":Ot("load",r);break;case"video":case"audio":for(a=0;a<Xu.length;a++)Ot(Xu[a],r);break;case"source":Ot("error",r);break;case"img":case"image":case"link":Ot("error",r),Ot("load",r);break;case"details":Ot("toggle",r);break;case"input":Ot("invalid",r),Ko(r,c.value,c.defaultValue,c.checked,c.defaultChecked,c.type,c.name,!0);break;case"select":Ot("invalid",r);break;case"textarea":Ot("invalid",r),Zs(r,c.value,c.defaultValue,c.children)}a=c.children,typeof a!="string"&&typeof a!="number"&&typeof a!="bigint"||r.textContent===""+a||c.suppressHydrationWarning===!0||xw(r.textContent,a)?(c.popover!=null&&(Ot("beforetoggle",r),Ot("toggle",r)),c.onScroll!=null&&Ot("scroll",r),c.onScrollEnd!=null&&Ot("scrollend",r),c.onClick!=null&&(r.onclick=Mi),r=!0):r=!1,r||ls(i,!0)}function P(i){for(ri=i.return;ri;)switch(ri.tag){case 5:case 31:case 13:ir=!1;return;case 27:case 3:ir=!0;return;default:ri=ri.return}}function xe(i){if(i!==ri)return!1;if(!Et)return P(i),Et=!0,!1;var r=i.tag,a;if((a=r!==3&&r!==27)&&((a=r===5)&&(a=i.type,a=!(a!=="form"&&a!=="button")||Ng(i.type,i.memoizedProps)),a=!a),a&&dn&&ls(i),P(i),r===13){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(s(317));dn=Aw(i)}else if(r===31){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(s(317));dn=Aw(i)}else r===27?(r=dn,po(i.type)?(i=jg,jg=null,dn=i):dn=r):dn=ri?Wr(i.stateNode.nextSibling):null;return!0}function Xe(){dn=ri=null,Et=!1}function et(){var i=$i;return i!==null&&(or===null?or=i:or.push.apply(or,i),$i=null),i}function ct(i){$i===null?$i=[i]:$i.push(i)}var Ht=N(null),Lt=null,nt=null;function ut(i,r,a){se(Ht,r._currentValue),r._currentValue=a}function Ut(i){i._currentValue=Ht.current,V(Ht)}function hn(i,r,a){for(;i!==null;){var c=i.alternate;if((i.childLanes&r)!==r?(i.childLanes|=r,c!==null&&(c.childLanes|=r)):c!==null&&(c.childLanes&r)!==r&&(c.childLanes|=r),i===a)break;i=i.return}}function Oi(i,r,a,c){var h=i.child;for(h!==null&&(h.return=i);h!==null;){var g=h.dependencies;if(g!==null){var y=h.child;g=g.firstContext;e:for(;g!==null;){var D=g;g=h;for(var $=0;$<r.length;$++)if(D.context===r[$]){g.lanes|=a,D=g.alternate,D!==null&&(D.lanes|=a),hn(g.return,a,i),c||(y=null);break e}g=D.next}}else if(h.tag===18){if(y=h.return,y===null)throw Error(s(341));y.lanes|=a,g=y.alternate,g!==null&&(g.lanes|=a),hn(y,a,i),y=null}else y=h.child;if(y!==null)y.return=h;else for(y=h;y!==null;){if(y===i){y=null;break}if(h=y.sibling,h!==null){h.return=y.return,y=h;break}y=y.return}h=y}}function Fi(i,r,a,c){i=null;for(var h=r,g=!1;h!==null;){if(!g){if((h.flags&524288)!==0)g=!0;else if((h.flags&262144)!==0)break}if(h.tag===10){var y=h.alternate;if(y===null)throw Error(s(387));if(y=y.memoizedProps,y!==null){var D=h.type;Li(h.pendingProps.value,y.value)||(i!==null?i.push(D):i=[D])}}else if(h===ze.current){if(y=h.alternate,y===null)throw Error(s(387));y.memoizedState.memoizedState!==h.memoizedState.memoizedState&&(i!==null?i.push(td):i=[td])}h=h.return}i!==null&&Oi(r,i,a,c),r.flags|=262144}function hl(i){for(i=i.firstContext;i!==null;){if(!Li(i.context._currentValue,i.memoizedValue))return!0;i=i.next}return!1}function _n(i){Lt=i,nt=null,i=i.dependencies,i!==null&&(i.firstContext=null)}function Yn(i){return Ch(Lt,i)}function ua(i,r){return Lt===null&&_n(i),Ch(i,r)}function Ch(i,r){var a=r._currentValue;if(r={context:r,memoizedValue:a,next:null},nt===null){if(i===null)throw Error(s(308));nt=r,i.dependencies={lanes:0,firstContext:r},i.flags|=524288}else nt=nt.next=r;return a}var Gn=typeof AbortController<"u"?AbortController:function(){var i=[],r=this.signal={aborted:!1,addEventListener:function(a,c){i.push(c)}};this.abort=function(){r.aborted=!0,i.forEach(function(a){return a()})}},kh=e.unstable_scheduleCallback,Th=e.unstable_NormalPriority,Xn={$$typeof:H,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function gm(){return{controller:new Gn,data:new Map,refCount:0}}function Nu(i){i.refCount--,i.refCount===0&&kh(Th,function(){i.controller.abort()})}var Du=null,vm=0,dc=0,hc=null;function sR(i,r){if(Du===null){var a=Du=[];vm=0,dc=yg(),hc={status:"pending",value:void 0,then:function(c){a.push(c)}}}return vm++,r.then(cS,cS),r}function cS(){if(--vm===0&&Du!==null){hc!==null&&(hc.status="fulfilled");var i=Du;Du=null,dc=0,hc=null;for(var r=0;r<i.length;r++)(0,i[r])()}}function aR(i,r){var a=[],c={status:"pending",value:null,reason:null,then:function(h){a.push(h)}};return i.then(function(){c.status="fulfilled",c.value=r;for(var h=0;h<a.length;h++)(0,a[h])(r)},function(h){for(c.status="rejected",c.reason=h,h=0;h<a.length;h++)(0,a[h])(void 0)}),c}var uS=M.S;M.S=function(i,r){V0=qe(),typeof r=="object"&&r!==null&&typeof r.then=="function"&&sR(i,r),uS!==null&&uS(i,r)};var fl=N(null);function _m(){var i=fl.current;return i!==null?i:fn.pooledCache}function Eh(i,r){r===null?se(fl,fl.current):se(fl,r.pool)}function dS(){var i=_m();return i===null?null:{parent:Xn._currentValue,pool:i}}var fc=Error(s(460)),bm=Error(s(474)),Rh=Error(s(542)),Nh={then:function(){}};function hS(i){return i=i.status,i==="fulfilled"||i==="rejected"}function fS(i,r,a){switch(a=i[a],a===void 0?i.push(r):a!==r&&(r.then(Mi,Mi),r=a),r.status){case"fulfilled":return r.value;case"rejected":throw i=r.reason,mS(i),i;default:if(typeof r.status=="string")r.then(Mi,Mi);else{if(i=fn,i!==null&&100<i.shellSuspendCounter)throw Error(s(482));i=r,i.status="pending",i.then(function(c){if(r.status==="pending"){var h=r;h.status="fulfilled",h.value=c}},function(c){if(r.status==="pending"){var h=r;h.status="rejected",h.reason=c}})}switch(r.status){case"fulfilled":return r.value;case"rejected":throw i=r.reason,mS(i),i}throw ml=r,fc}}function pl(i){try{var r=i._init;return r(i._payload)}catch(a){throw a!==null&&typeof a=="object"&&typeof a.then=="function"?(ml=a,fc):a}}var ml=null;function pS(){if(ml===null)throw Error(s(459));var i=ml;return ml=null,i}function mS(i){if(i===fc||i===Rh)throw Error(s(483))}var pc=null,Mu=0;function Dh(i){var r=Mu;return Mu+=1,pc===null&&(pc=[]),fS(pc,i,r)}function Au(i,r){r=r.props.ref,i.ref=r!==void 0?r:null}function Mh(i,r){throw r.$$typeof===S?Error(s(525)):(i=Object.prototype.toString.call(r),Error(s(31,i==="[object Object]"?"object with keys {"+Object.keys(r).join(", ")+"}":i)))}function gS(i){function r(ne,G){if(i){var ce=ne.deletions;ce===null?(ne.deletions=[G],ne.flags|=16):ce.push(G)}}function a(ne,G){if(!i)return null;for(;G!==null;)r(ne,G),G=G.sibling;return null}function c(ne){for(var G=new Map;ne!==null;)ne.key!==null?G.set(ne.key,ne):G.set(ne.index,ne),ne=ne.sibling;return G}function h(ne,G){return ne=Hr(ne,G),ne.index=0,ne.sibling=null,ne}function g(ne,G,ce){return ne.index=ce,i?(ce=ne.alternate,ce!==null?(ce=ce.index,ce<G?(ne.flags|=67108866,G):ce):(ne.flags|=67108866,G)):(ne.flags|=1048576,G)}function y(ne){return i&&ne.alternate===null&&(ne.flags|=67108866),ne}function D(ne,G,ce,Ce){return G===null||G.tag!==6?(G=cc(ce,ne.mode,Ce),G.return=ne,G):(G=h(G,ce),G.return=ne,G)}function $(ne,G,ce,Ce){var lt=ce.type;return lt===R?Se(ne,G,ce.props.children,Ce,ce.key):G!==null&&(G.elementType===lt||typeof lt=="object"&&lt!==null&&lt.$$typeof===F&&pl(lt)===G.type)?(G=h(G,ce.props),Au(G,ce),G.return=ne,G):(G=lc(ce.type,ce.key,ce.props,null,ne.mode,Ce),Au(G,ce),G.return=ne,G)}function ue(ne,G,ce,Ce){return G===null||G.tag!==4||G.stateNode.containerInfo!==ce.containerInfo||G.stateNode.implementation!==ce.implementation?(G=ku(ce,ne.mode,Ce),G.return=ne,G):(G=h(G,ce.children||[]),G.return=ne,G)}function Se(ne,G,ce,Ce,lt){return G===null||G.tag!==7?(G=Ds(ce,ne.mode,Ce,lt),G.return=ne,G):(G=h(G,ce),G.return=ne,G)}function Re(ne,G,ce){if(typeof G=="string"&&G!==""||typeof G=="number"||typeof G=="bigint")return G=cc(""+G,ne.mode,ce),G.return=ne,G;if(typeof G=="object"&&G!==null){switch(G.$$typeof){case w:return ce=lc(G.type,G.key,G.props,null,ne.mode,ce),Au(ce,G),ce.return=ne,ce;case x:return G=ku(G,ne.mode,ce),G.return=ne,G;case F:return G=pl(G),Re(ne,G,ce)}if(X(G)||te(G))return G=Ds(G,ne.mode,ce,null),G.return=ne,G;if(typeof G.then=="function")return Re(ne,Dh(G),ce);if(G.$$typeof===H)return Re(ne,ua(ne,G),ce);Mh(ne,G)}return null}function pe(ne,G,ce,Ce){var lt=G!==null?G.key:null;if(typeof ce=="string"&&ce!==""||typeof ce=="number"||typeof ce=="bigint")return lt!==null?null:D(ne,G,""+ce,Ce);if(typeof ce=="object"&&ce!==null){switch(ce.$$typeof){case w:return ce.key===lt?$(ne,G,ce,Ce):null;case x:return ce.key===lt?ue(ne,G,ce,Ce):null;case F:return ce=pl(ce),pe(ne,G,ce,Ce)}if(X(ce)||te(ce))return lt!==null?null:Se(ne,G,ce,Ce,null);if(typeof ce.then=="function")return pe(ne,G,Dh(ce),Ce);if(ce.$$typeof===H)return pe(ne,G,ua(ne,ce),Ce);Mh(ne,ce)}return null}function _e(ne,G,ce,Ce,lt){if(typeof Ce=="string"&&Ce!==""||typeof Ce=="number"||typeof Ce=="bigint")return ne=ne.get(ce)||null,D(G,ne,""+Ce,lt);if(typeof Ce=="object"&&Ce!==null){switch(Ce.$$typeof){case w:return ne=ne.get(Ce.key===null?ce:Ce.key)||null,$(G,ne,Ce,lt);case x:return ne=ne.get(Ce.key===null?ce:Ce.key)||null,ue(G,ne,Ce,lt);case F:return Ce=pl(Ce),_e(ne,G,ce,Ce,lt)}if(X(Ce)||te(Ce))return ne=ne.get(ce)||null,Se(G,ne,Ce,lt,null);if(typeof Ce.then=="function")return _e(ne,G,ce,Dh(Ce),lt);if(Ce.$$typeof===H)return _e(ne,G,ce,ua(G,Ce),lt);Mh(G,Ce)}return null}function Qe(ne,G,ce,Ce){for(var lt=null,Kt=null,it=G,kt=G=0,Pt=null;it!==null&&kt<ce.length;kt++){it.index>kt?(Pt=it,it=null):Pt=it.sibling;var qt=pe(ne,it,ce[kt],Ce);if(qt===null){it===null&&(it=Pt);break}i&&it&&qt.alternate===null&&r(ne,it),G=g(qt,G,kt),Kt===null?lt=qt:Kt.sibling=qt,Kt=qt,it=Pt}if(kt===ce.length)return a(ne,it),Et&&os(ne,kt),lt;if(it===null){for(;kt<ce.length;kt++)it=Re(ne,ce[kt],Ce),it!==null&&(G=g(it,G,kt),Kt===null?lt=it:Kt.sibling=it,Kt=it);return Et&&os(ne,kt),lt}for(it=c(it);kt<ce.length;kt++)Pt=_e(it,ne,kt,ce[kt],Ce),Pt!==null&&(i&&Pt.alternate!==null&&it.delete(Pt.key===null?kt:Pt.key),G=g(Pt,G,kt),Kt===null?lt=Pt:Kt.sibling=Pt,Kt=Pt);return i&&it.forEach(function(bo){return r(ne,bo)}),Et&&os(ne,kt),lt}function dt(ne,G,ce,Ce){if(ce==null)throw Error(s(151));for(var lt=null,Kt=null,it=G,kt=G=0,Pt=null,qt=ce.next();it!==null&&!qt.done;kt++,qt=ce.next()){it.index>kt?(Pt=it,it=null):Pt=it.sibling;var bo=pe(ne,it,qt.value,Ce);if(bo===null){it===null&&(it=Pt);break}i&&it&&bo.alternate===null&&r(ne,it),G=g(bo,G,kt),Kt===null?lt=bo:Kt.sibling=bo,Kt=bo,it=Pt}if(qt.done)return a(ne,it),Et&&os(ne,kt),lt;if(it===null){for(;!qt.done;kt++,qt=ce.next())qt=Re(ne,qt.value,Ce),qt!==null&&(G=g(qt,G,kt),Kt===null?lt=qt:Kt.sibling=qt,Kt=qt);return Et&&os(ne,kt),lt}for(it=c(it);!qt.done;kt++,qt=ce.next())qt=_e(it,ne,kt,qt.value,Ce),qt!==null&&(i&&qt.alternate!==null&&it.delete(qt.key===null?kt:qt.key),G=g(qt,G,kt),Kt===null?lt=qt:Kt.sibling=qt,Kt=qt);return i&&it.forEach(function(vN){return r(ne,vN)}),Et&&os(ne,kt),lt}function sn(ne,G,ce,Ce){if(typeof ce=="object"&&ce!==null&&ce.type===R&&ce.key===null&&(ce=ce.props.children),typeof ce=="object"&&ce!==null){switch(ce.$$typeof){case w:e:{for(var lt=ce.key;G!==null;){if(G.key===lt){if(lt=ce.type,lt===R){if(G.tag===7){a(ne,G.sibling),Ce=h(G,ce.props.children),Ce.return=ne,ne=Ce;break e}}else if(G.elementType===lt||typeof lt=="object"&&lt!==null&&lt.$$typeof===F&&pl(lt)===G.type){a(ne,G.sibling),Ce=h(G,ce.props),Au(Ce,ce),Ce.return=ne,ne=Ce;break e}a(ne,G);break}else r(ne,G);G=G.sibling}ce.type===R?(Ce=Ds(ce.props.children,ne.mode,Ce,ce.key),Ce.return=ne,ne=Ce):(Ce=lc(ce.type,ce.key,ce.props,null,ne.mode,Ce),Au(Ce,ce),Ce.return=ne,ne=Ce)}return y(ne);case x:e:{for(lt=ce.key;G!==null;){if(G.key===lt)if(G.tag===4&&G.stateNode.containerInfo===ce.containerInfo&&G.stateNode.implementation===ce.implementation){a(ne,G.sibling),Ce=h(G,ce.children||[]),Ce.return=ne,ne=Ce;break e}else{a(ne,G);break}else r(ne,G);G=G.sibling}Ce=ku(ce,ne.mode,Ce),Ce.return=ne,ne=Ce}return y(ne);case F:return ce=pl(ce),sn(ne,G,ce,Ce)}if(X(ce))return Qe(ne,G,ce,Ce);if(te(ce)){if(lt=te(ce),typeof lt!="function")throw Error(s(150));return ce=lt.call(ce),dt(ne,G,ce,Ce)}if(typeof ce.then=="function")return sn(ne,G,Dh(ce),Ce);if(ce.$$typeof===H)return sn(ne,G,ua(ne,ce),Ce);Mh(ne,ce)}return typeof ce=="string"&&ce!==""||typeof ce=="number"||typeof ce=="bigint"?(ce=""+ce,G!==null&&G.tag===6?(a(ne,G.sibling),Ce=h(G,ce),Ce.return=ne,ne=Ce):(a(ne,G),Ce=cc(ce,ne.mode,Ce),Ce.return=ne,ne=Ce),y(ne)):a(ne,G)}return function(ne,G,ce,Ce){try{Mu=0;var lt=sn(ne,G,ce,Ce);return pc=null,lt}catch(it){if(it===fc||it===Rh)throw it;var Kt=Ci(29,it,null,ne.mode);return Kt.lanes=Ce,Kt.return=ne,Kt}}}var gl=gS(!0),vS=gS(!1),to=!1;function ym(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Sm(i,r){i=i.updateQueue,r.updateQueue===i&&(r.updateQueue={baseState:i.baseState,firstBaseUpdate:i.firstBaseUpdate,lastBaseUpdate:i.lastBaseUpdate,shared:i.shared,callbacks:null})}function no(i){return{lane:i,tag:0,payload:null,callback:null,next:null}}function io(i,r,a){var c=i.updateQueue;if(c===null)return null;if(c=c.shared,(Yt&2)!==0){var h=c.pending;return h===null?r.next=r:(r.next=h.next,h.next=r),c.pending=r,r=oc(i),wh(i,null,a),r}return cl(i,c,r,a),oc(i)}function Lu(i,r,a){if(r=r.updateQueue,r!==null&&(r=r.shared,(a&4194048)!==0)){var c=r.lanes;c&=i.pendingLanes,a|=c,r.lanes=a,cn(i,a)}}function wm(i,r){var a=i.updateQueue,c=i.alternate;if(c!==null&&(c=c.updateQueue,a===c)){var h=null,g=null;if(a=a.firstBaseUpdate,a!==null){do{var y={lane:a.lane,tag:a.tag,payload:a.payload,callback:null,next:null};g===null?h=g=y:g=g.next=y,a=a.next}while(a!==null);g===null?h=g=r:g=g.next=r}else h=g=r;a={baseState:c.baseState,firstBaseUpdate:h,lastBaseUpdate:g,shared:c.shared,callbacks:c.callbacks},i.updateQueue=a;return}i=a.lastBaseUpdate,i===null?a.firstBaseUpdate=r:i.next=r,a.lastBaseUpdate=r}var xm=!1;function ju(){if(xm){var i=hc;if(i!==null)throw i}}function Ou(i,r,a,c){xm=!1;var h=i.updateQueue;to=!1;var g=h.firstBaseUpdate,y=h.lastBaseUpdate,D=h.shared.pending;if(D!==null){h.shared.pending=null;var $=D,ue=$.next;$.next=null,y===null?g=ue:y.next=ue,y=$;var Se=i.alternate;Se!==null&&(Se=Se.updateQueue,D=Se.lastBaseUpdate,D!==y&&(D===null?Se.firstBaseUpdate=ue:D.next=ue,Se.lastBaseUpdate=$))}if(g!==null){var Re=h.baseState;y=0,Se=ue=$=null,D=g;do{var pe=D.lane&-536870913,_e=pe!==D.lane;if(_e?(It&pe)===pe:(c&pe)===pe){pe!==0&&pe===dc&&(xm=!0),Se!==null&&(Se=Se.next={lane:0,tag:D.tag,payload:D.payload,callback:null,next:null});e:{var Qe=i,dt=D;pe=r;var sn=a;switch(dt.tag){case 1:if(Qe=dt.payload,typeof Qe=="function"){Re=Qe.call(sn,Re,pe);break e}Re=Qe;break e;case 3:Qe.flags=Qe.flags&-65537|128;case 0:if(Qe=dt.payload,pe=typeof Qe=="function"?Qe.call(sn,Re,pe):Qe,pe==null)break e;Re=_({},Re,pe);break e;case 2:to=!0}}pe=D.callback,pe!==null&&(i.flags|=64,_e&&(i.flags|=8192),_e=h.callbacks,_e===null?h.callbacks=[pe]:_e.push(pe))}else _e={lane:pe,tag:D.tag,payload:D.payload,callback:D.callback,next:null},Se===null?(ue=Se=_e,$=Re):Se=Se.next=_e,y|=pe;if(D=D.next,D===null){if(D=h.shared.pending,D===null)break;_e=D,D=_e.next,_e.next=null,h.lastBaseUpdate=_e,h.shared.pending=null}}while(!0);Se===null&&($=Re),h.baseState=$,h.firstBaseUpdate=ue,h.lastBaseUpdate=Se,g===null&&(h.shared.lanes=0),lo|=y,i.lanes=y,i.memoizedState=Re}}function _S(i,r){if(typeof i!="function")throw Error(s(191,i));i.call(r)}function bS(i,r){var a=i.callbacks;if(a!==null)for(i.callbacks=null,i=0;i<a.length;i++)_S(a[i],r)}var mc=N(null),Ah=N(0);function yS(i,r){i=ba,se(Ah,i),se(mc,r),ba=i|r.baseLanes}function Cm(){se(Ah,ba),se(mc,mc.current)}function km(){ba=Ah.current,V(mc),V(Ah)}var Sr=N(null),Fr=null;function ro(i){var r=i.alternate;se(Un,Un.current&1),se(Sr,i),Fr===null&&(r===null||mc.current!==null||r.memoizedState!==null)&&(Fr=i)}function Tm(i){se(Un,Un.current),se(Sr,i),Fr===null&&(Fr=i)}function SS(i){i.tag===22?(se(Un,Un.current),se(Sr,i),Fr===null&&(Fr=i)):so()}function so(){se(Un,Un.current),se(Sr,Sr.current)}function wr(i){V(Sr),Fr===i&&(Fr=null),V(Un)}var Un=N(0);function Lh(i){for(var r=i;r!==null;){if(r.tag===13){var a=r.memoizedState;if(a!==null&&(a=a.dehydrated,a===null||Ag(a)||Lg(a)))return r}else if(r.tag===19&&(r.memoizedProps.revealOrder==="forwards"||r.memoizedProps.revealOrder==="backwards"||r.memoizedProps.revealOrder==="unstable_legacy-backwards"||r.memoizedProps.revealOrder==="together")){if((r.flags&128)!==0)return r}else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===i)break;for(;r.sibling===null;){if(r.return===null||r.return===i)return null;r=r.return}r.sibling.return=r.return,r=r.sibling}return null}var da=0,wt=null,nn=null,Zn=null,jh=!1,gc=!1,vl=!1,Oh=0,Bu=0,vc=null,oR=0;function An(){throw Error(s(321))}function Em(i,r){if(r===null)return!1;for(var a=0;a<r.length&&a<i.length;a++)if(!Li(i[a],r[a]))return!1;return!0}function Rm(i,r,a,c,h,g){return da=g,wt=r,r.memoizedState=null,r.updateQueue=null,r.lanes=0,M.H=i===null||i.memoizedState===null?r0:Fm,vl=!1,g=a(c,h),vl=!1,gc&&(g=xS(r,a,c,h)),wS(i),g}function wS(i){M.H=zu;var r=nn!==null&&nn.next!==null;if(da=0,Zn=nn=wt=null,jh=!1,Bu=0,vc=null,r)throw Error(s(300));i===null||Qn||(i=i.dependencies,i!==null&&hl(i)&&(Qn=!0))}function xS(i,r,a,c){wt=i;var h=0;do{if(gc&&(vc=null),Bu=0,gc=!1,25<=h)throw Error(s(301));if(h+=1,Zn=nn=null,i.updateQueue!=null){var g=i.updateQueue;g.lastEffect=null,g.events=null,g.stores=null,g.memoCache!=null&&(g.memoCache.index=0)}M.H=s0,g=r(a,c)}while(gc);return g}function lR(){var i=M.H,r=i.useState()[0];return r=typeof r.then=="function"?Iu(r):r,i=i.useState()[0],(nn!==null?nn.memoizedState:null)!==i&&(wt.flags|=1024),r}function Nm(){var i=Oh!==0;return Oh=0,i}function Dm(i,r,a){r.updateQueue=i.updateQueue,r.flags&=-2053,i.lanes&=~a}function Mm(i){if(jh){for(i=i.memoizedState;i!==null;){var r=i.queue;r!==null&&(r.pending=null),i=i.next}jh=!1}da=0,Zn=nn=wt=null,gc=!1,Bu=Oh=0,vc=null}function Wi(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Zn===null?wt.memoizedState=Zn=i:Zn=Zn.next=i,Zn}function $n(){if(nn===null){var i=wt.alternate;i=i!==null?i.memoizedState:null}else i=nn.next;var r=Zn===null?wt.memoizedState:Zn.next;if(r!==null)Zn=r,nn=i;else{if(i===null)throw wt.alternate===null?Error(s(467)):Error(s(310));nn=i,i={memoizedState:nn.memoizedState,baseState:nn.baseState,baseQueue:nn.baseQueue,queue:nn.queue,next:null},Zn===null?wt.memoizedState=Zn=i:Zn=Zn.next=i}return Zn}function Bh(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Iu(i){var r=Bu;return Bu+=1,vc===null&&(vc=[]),i=fS(vc,i,r),r=wt,(Zn===null?r.memoizedState:Zn.next)===null&&(r=r.alternate,M.H=r===null||r.memoizedState===null?r0:Fm),i}function Ih(i){if(i!==null&&typeof i=="object"){if(typeof i.then=="function")return Iu(i);if(i.$$typeof===H)return Yn(i)}throw Error(s(438,String(i)))}function Am(i){var r=null,a=wt.updateQueue;if(a!==null&&(r=a.memoCache),r==null){var c=wt.alternate;c!==null&&(c=c.updateQueue,c!==null&&(c=c.memoCache,c!=null&&(r={data:c.data.map(function(h){return h.slice()}),index:0})))}if(r==null&&(r={data:[],index:0}),a===null&&(a=Bh(),wt.updateQueue=a),a.memoCache=r,a=r.data[r.index],a===void 0)for(a=r.data[r.index]=Array(i),c=0;c<i;c++)a[c]=me;return r.index++,a}function ha(i,r){return typeof r=="function"?r(i):r}function Ph(i){var r=$n();return Lm(r,nn,i)}function Lm(i,r,a){var c=i.queue;if(c===null)throw Error(s(311));c.lastRenderedReducer=a;var h=i.baseQueue,g=c.pending;if(g!==null){if(h!==null){var y=h.next;h.next=g.next,g.next=y}r.baseQueue=h=g,c.pending=null}if(g=i.baseState,h===null)i.memoizedState=g;else{r=h.next;var D=y=null,$=null,ue=r,Se=!1;do{var Re=ue.lane&-536870913;if(Re!==ue.lane?(It&Re)===Re:(da&Re)===Re){var pe=ue.revertLane;if(pe===0)$!==null&&($=$.next={lane:0,revertLane:0,gesture:null,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null}),Re===dc&&(Se=!0);else if((da&pe)===pe){ue=ue.next,pe===dc&&(Se=!0);continue}else Re={lane:0,revertLane:ue.revertLane,gesture:null,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null},$===null?(D=$=Re,y=g):$=$.next=Re,wt.lanes|=pe,lo|=pe;Re=ue.action,vl&&a(g,Re),g=ue.hasEagerState?ue.eagerState:a(g,Re)}else pe={lane:Re,revertLane:ue.revertLane,gesture:ue.gesture,action:ue.action,hasEagerState:ue.hasEagerState,eagerState:ue.eagerState,next:null},$===null?(D=$=pe,y=g):$=$.next=pe,wt.lanes|=Re,lo|=Re;ue=ue.next}while(ue!==null&&ue!==r);if($===null?y=g:$.next=D,!Li(g,i.memoizedState)&&(Qn=!0,Se&&(a=hc,a!==null)))throw a;i.memoizedState=g,i.baseState=y,i.baseQueue=$,c.lastRenderedState=g}return h===null&&(c.lanes=0),[i.memoizedState,c.dispatch]}function jm(i){var r=$n(),a=r.queue;if(a===null)throw Error(s(311));a.lastRenderedReducer=i;var c=a.dispatch,h=a.pending,g=r.memoizedState;if(h!==null){a.pending=null;var y=h=h.next;do g=i(g,y.action),y=y.next;while(y!==h);Li(g,r.memoizedState)||(Qn=!0),r.memoizedState=g,r.baseQueue===null&&(r.baseState=g),a.lastRenderedState=g}return[g,c]}function CS(i,r,a){var c=wt,h=$n(),g=Et;if(g){if(a===void 0)throw Error(s(407));a=a()}else a=r();var y=!Li((nn||h).memoizedState,a);if(y&&(h.memoizedState=a,Qn=!0),h=h.queue,Im(ES.bind(null,c,h,i),[i]),h.getSnapshot!==r||y||Zn!==null&&Zn.memoizedState.tag&1){if(c.flags|=2048,_c(9,{destroy:void 0},TS.bind(null,c,h,a,r),null),fn===null)throw Error(s(349));g||(da&127)!==0||kS(c,r,a)}return a}function kS(i,r,a){i.flags|=16384,i={getSnapshot:r,value:a},r=wt.updateQueue,r===null?(r=Bh(),wt.updateQueue=r,r.stores=[i]):(a=r.stores,a===null?r.stores=[i]:a.push(i))}function TS(i,r,a,c){r.value=a,r.getSnapshot=c,RS(r)&&NS(i)}function ES(i,r,a){return a(function(){RS(r)&&NS(i)})}function RS(i){var r=i.getSnapshot;i=i.value;try{var a=r();return!Li(i,a)}catch{return!0}}function NS(i){var r=Ns(i,2);r!==null&&lr(r,i,2)}function Om(i){var r=Wi();if(typeof i=="function"){var a=i;if(i=a(),vl){Dt(!0);try{a()}finally{Dt(!1)}}}return r.memoizedState=r.baseState=i,r.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:i},r}function DS(i,r,a,c){return i.baseState=a,Lm(i,nn,typeof c=="function"?c:ha)}function cR(i,r,a,c,h){if(Uh(i))throw Error(s(485));if(i=r.action,i!==null){var g={payload:h,action:i,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(y){g.listeners.push(y)}};M.T!==null?a(!0):g.isTransition=!1,c(g),a=r.pending,a===null?(g.next=r.pending=g,MS(r,g)):(g.next=a.next,r.pending=a.next=g)}}function MS(i,r){var a=r.action,c=r.payload,h=i.state;if(r.isTransition){var g=M.T,y={};M.T=y;try{var D=a(h,c),$=M.S;$!==null&&$(y,D),AS(i,r,D)}catch(ue){Bm(i,r,ue)}finally{g!==null&&y.types!==null&&(g.types=y.types),M.T=g}}else try{g=a(h,c),AS(i,r,g)}catch(ue){Bm(i,r,ue)}}function AS(i,r,a){a!==null&&typeof a=="object"&&typeof a.then=="function"?a.then(function(c){LS(i,r,c)},function(c){return Bm(i,r,c)}):LS(i,r,a)}function LS(i,r,a){r.status="fulfilled",r.value=a,jS(r),i.state=a,r=i.pending,r!==null&&(a=r.next,a===r?i.pending=null:(a=a.next,r.next=a,MS(i,a)))}function Bm(i,r,a){var c=i.pending;if(i.pending=null,c!==null){c=c.next;do r.status="rejected",r.reason=a,jS(r),r=r.next;while(r!==c)}i.action=null}function jS(i){i=i.listeners;for(var r=0;r<i.length;r++)(0,i[r])()}function OS(i,r){return r}function BS(i,r){if(Et){var a=fn.formState;if(a!==null){e:{var c=wt;if(Et){if(dn){t:{for(var h=dn,g=ir;h.nodeType!==8;){if(!g){h=null;break t}if(h=Wr(h.nextSibling),h===null){h=null;break t}}g=h.data,h=g==="F!"||g==="F"?h:null}if(h){dn=Wr(h.nextSibling),c=h.data==="F!";break e}}ls(c)}c=!1}c&&(r=a[0])}}return a=Wi(),a.memoizedState=a.baseState=r,c={pending:null,lanes:0,dispatch:null,lastRenderedReducer:OS,lastRenderedState:r},a.queue=c,a=t0.bind(null,wt,c),c.dispatch=a,c=Om(!1),g=$m.bind(null,wt,!1,c.queue),c=Wi(),h={state:r,dispatch:null,action:i,pending:null},c.queue=h,a=cR.bind(null,wt,h,g,a),h.dispatch=a,c.memoizedState=i,[r,a,!1]}function IS(i){var r=$n();return PS(r,nn,i)}function PS(i,r,a){if(r=Lm(i,r,OS)[0],i=Ph(ha)[0],typeof r=="object"&&r!==null&&typeof r.then=="function")try{var c=Iu(r)}catch(y){throw y===fc?Rh:y}else c=r;r=$n();var h=r.queue,g=h.dispatch;return a!==r.memoizedState&&(wt.flags|=2048,_c(9,{destroy:void 0},uR.bind(null,h,a),null)),[c,g,i]}function uR(i,r){i.action=r}function zS(i){var r=$n(),a=nn;if(a!==null)return PS(r,a,i);$n(),r=r.memoizedState,a=$n();var c=a.queue.dispatch;return a.memoizedState=i,[r,c,!1]}function _c(i,r,a,c){return i={tag:i,create:a,deps:c,inst:r,next:null},r=wt.updateQueue,r===null&&(r=Bh(),wt.updateQueue=r),a=r.lastEffect,a===null?r.lastEffect=i.next=i:(c=a.next,a.next=i,i.next=c,r.lastEffect=i),i}function HS(){return $n().memoizedState}function zh(i,r,a,c){var h=Wi();wt.flags|=i,h.memoizedState=_c(1|r,{destroy:void 0},a,c===void 0?null:c)}function Hh(i,r,a,c){var h=$n();c=c===void 0?null:c;var g=h.memoizedState.inst;nn!==null&&c!==null&&Em(c,nn.memoizedState.deps)?h.memoizedState=_c(r,g,a,c):(wt.flags|=i,h.memoizedState=_c(1|r,g,a,c))}function US(i,r){zh(8390656,8,i,r)}function Im(i,r){Hh(2048,8,i,r)}function dR(i){wt.flags|=4;var r=wt.updateQueue;if(r===null)r=Bh(),wt.updateQueue=r,r.events=[i];else{var a=r.events;a===null?r.events=[i]:a.push(i)}}function $S(i){var r=$n().memoizedState;return dR({ref:r,nextImpl:i}),function(){if((Yt&2)!==0)throw Error(s(440));return r.impl.apply(void 0,arguments)}}function FS(i,r){return Hh(4,2,i,r)}function WS(i,r){return Hh(4,4,i,r)}function KS(i,r){if(typeof r=="function"){i=i();var a=r(i);return function(){typeof a=="function"?a():r(null)}}if(r!=null)return i=i(),r.current=i,function(){r.current=null}}function qS(i,r,a){a=a!=null?a.concat([i]):null,Hh(4,4,KS.bind(null,r,i),a)}function Pm(){}function VS(i,r){var a=$n();r=r===void 0?null:r;var c=a.memoizedState;return r!==null&&Em(r,c[1])?c[0]:(a.memoizedState=[i,r],i)}function YS(i,r){var a=$n();r=r===void 0?null:r;var c=a.memoizedState;if(r!==null&&Em(r,c[1]))return c[0];if(c=i(),vl){Dt(!0);try{i()}finally{Dt(!1)}}return a.memoizedState=[c,r],c}function zm(i,r,a){return a===void 0||(da&1073741824)!==0&&(It&261930)===0?i.memoizedState=r:(i.memoizedState=a,i=G0(),wt.lanes|=i,lo|=i,a)}function GS(i,r,a,c){return Li(a,r)?a:mc.current!==null?(i=zm(i,a,c),Li(i,r)||(Qn=!0),i):(da&42)===0||(da&1073741824)!==0&&(It&261930)===0?(Qn=!0,i.memoizedState=a):(i=G0(),wt.lanes|=i,lo|=i,r)}function XS(i,r,a,c,h){var g=T.p;T.p=g!==0&&8>g?g:8;var y=M.T,D={};M.T=D,$m(i,!1,r,a);try{var $=h(),ue=M.S;if(ue!==null&&ue(D,$),$!==null&&typeof $=="object"&&typeof $.then=="function"){var Se=aR($,c);Pu(i,r,Se,kr(i))}else Pu(i,r,c,kr(i))}catch(Re){Pu(i,r,{then:function(){},status:"rejected",reason:Re},kr())}finally{T.p=g,y!==null&&D.types!==null&&(y.types=D.types),M.T=y}}function hR(){}function Hm(i,r,a,c){if(i.tag!==5)throw Error(s(476));var h=ZS(i).queue;XS(i,h,r,O,a===null?hR:function(){return QS(i),a(c)})}function ZS(i){var r=i.memoizedState;if(r!==null)return r;r={memoizedState:O,baseState:O,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:O},next:null};var a={};return r.next={memoizedState:a,baseState:a,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:a},next:null},i.memoizedState=r,i=i.alternate,i!==null&&(i.memoizedState=r),r}function QS(i){var r=ZS(i);r.next===null&&(r=i.alternate.memoizedState),Pu(i,r.next.queue,{},kr())}function Um(){return Yn(td)}function JS(){return $n().memoizedState}function e0(){return $n().memoizedState}function fR(i){for(var r=i.return;r!==null;){switch(r.tag){case 24:case 3:var a=kr();i=no(a);var c=io(r,i,a);c!==null&&(lr(c,r,a),Lu(c,r,a)),r={cache:gm()},i.payload=r;return}r=r.return}}function pR(i,r,a){var c=kr();a={lane:c,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},Uh(i)?n0(r,a):(a=wu(i,r,a,c),a!==null&&(lr(a,i,c),i0(a,r,c)))}function t0(i,r,a){var c=kr();Pu(i,r,a,c)}function Pu(i,r,a,c){var h={lane:c,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null};if(Uh(i))n0(r,h);else{var g=i.alternate;if(i.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,D=g(y,a);if(h.hasEagerState=!0,h.eagerState=D,Li(D,y))return cl(i,r,h,0),fn===null&&ll(),!1}catch{}if(a=wu(i,r,h,c),a!==null)return lr(a,i,c),i0(a,r,c),!0}return!1}function $m(i,r,a,c){if(c={lane:2,revertLane:yg(),gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Uh(i)){if(r)throw Error(s(479))}else r=wu(i,a,c,2),r!==null&&lr(r,i,2)}function Uh(i){var r=i.alternate;return i===wt||r!==null&&r===wt}function n0(i,r){gc=jh=!0;var a=i.pending;a===null?r.next=r:(r.next=a.next,a.next=r),i.pending=r}function i0(i,r,a){if((a&4194048)!==0){var c=r.lanes;c&=i.pendingLanes,a|=c,r.lanes=a,cn(i,a)}}var zu={readContext:Yn,use:Ih,useCallback:An,useContext:An,useEffect:An,useImperativeHandle:An,useLayoutEffect:An,useInsertionEffect:An,useMemo:An,useReducer:An,useRef:An,useState:An,useDebugValue:An,useDeferredValue:An,useTransition:An,useSyncExternalStore:An,useId:An,useHostTransitionStatus:An,useFormState:An,useActionState:An,useOptimistic:An,useMemoCache:An,useCacheRefresh:An};zu.useEffectEvent=An;var r0={readContext:Yn,use:Ih,useCallback:function(i,r){return Wi().memoizedState=[i,r===void 0?null:r],i},useContext:Yn,useEffect:US,useImperativeHandle:function(i,r,a){a=a!=null?a.concat([i]):null,zh(4194308,4,KS.bind(null,r,i),a)},useLayoutEffect:function(i,r){return zh(4194308,4,i,r)},useInsertionEffect:function(i,r){zh(4,2,i,r)},useMemo:function(i,r){var a=Wi();r=r===void 0?null:r;var c=i();if(vl){Dt(!0);try{i()}finally{Dt(!1)}}return a.memoizedState=[c,r],c},useReducer:function(i,r,a){var c=Wi();if(a!==void 0){var h=a(r);if(vl){Dt(!0);try{a(r)}finally{Dt(!1)}}}else h=r;return c.memoizedState=c.baseState=h,i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:h},c.queue=i,i=i.dispatch=pR.bind(null,wt,i),[c.memoizedState,i]},useRef:function(i){var r=Wi();return i={current:i},r.memoizedState=i},useState:function(i){i=Om(i);var r=i.queue,a=t0.bind(null,wt,r);return r.dispatch=a,[i.memoizedState,a]},useDebugValue:Pm,useDeferredValue:function(i,r){var a=Wi();return zm(a,i,r)},useTransition:function(){var i=Om(!1);return i=XS.bind(null,wt,i.queue,!0,!1),Wi().memoizedState=i,[!1,i]},useSyncExternalStore:function(i,r,a){var c=wt,h=Wi();if(Et){if(a===void 0)throw Error(s(407));a=a()}else{if(a=r(),fn===null)throw Error(s(349));(It&127)!==0||kS(c,r,a)}h.memoizedState=a;var g={value:a,getSnapshot:r};return h.queue=g,US(ES.bind(null,c,g,i),[i]),c.flags|=2048,_c(9,{destroy:void 0},TS.bind(null,c,g,a,r),null),a},useId:function(){var i=Wi(),r=fn.identifierPrefix;if(Et){var a=Ur,c=yr;a=(c&~(1<<32-Mt(c)-1)).toString(32)+a,r="_"+r+"R_"+a,a=Oh++,0<a&&(r+="H"+a.toString(32)),r+="_"}else a=oR++,r="_"+r+"r_"+a.toString(32)+"_";return i.memoizedState=r},useHostTransitionStatus:Um,useFormState:BS,useActionState:BS,useOptimistic:function(i){var r=Wi();r.memoizedState=r.baseState=i;var a={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return r.queue=a,r=$m.bind(null,wt,!0,a),a.dispatch=r,[i,r]},useMemoCache:Am,useCacheRefresh:function(){return Wi().memoizedState=fR.bind(null,wt)},useEffectEvent:function(i){var r=Wi(),a={impl:i};return r.memoizedState=a,function(){if((Yt&2)!==0)throw Error(s(440));return a.impl.apply(void 0,arguments)}}},Fm={readContext:Yn,use:Ih,useCallback:VS,useContext:Yn,useEffect:Im,useImperativeHandle:qS,useInsertionEffect:FS,useLayoutEffect:WS,useMemo:YS,useReducer:Ph,useRef:HS,useState:function(){return Ph(ha)},useDebugValue:Pm,useDeferredValue:function(i,r){var a=$n();return GS(a,nn.memoizedState,i,r)},useTransition:function(){var i=Ph(ha)[0],r=$n().memoizedState;return[typeof i=="boolean"?i:Iu(i),r]},useSyncExternalStore:CS,useId:JS,useHostTransitionStatus:Um,useFormState:IS,useActionState:IS,useOptimistic:function(i,r){var a=$n();return DS(a,nn,i,r)},useMemoCache:Am,useCacheRefresh:e0};Fm.useEffectEvent=$S;var s0={readContext:Yn,use:Ih,useCallback:VS,useContext:Yn,useEffect:Im,useImperativeHandle:qS,useInsertionEffect:FS,useLayoutEffect:WS,useMemo:YS,useReducer:jm,useRef:HS,useState:function(){return jm(ha)},useDebugValue:Pm,useDeferredValue:function(i,r){var a=$n();return nn===null?zm(a,i,r):GS(a,nn.memoizedState,i,r)},useTransition:function(){var i=jm(ha)[0],r=$n().memoizedState;return[typeof i=="boolean"?i:Iu(i),r]},useSyncExternalStore:CS,useId:JS,useHostTransitionStatus:Um,useFormState:zS,useActionState:zS,useOptimistic:function(i,r){var a=$n();return nn!==null?DS(a,nn,i,r):(a.baseState=i,[i,a.queue.dispatch])},useMemoCache:Am,useCacheRefresh:e0};s0.useEffectEvent=$S;function Wm(i,r,a,c){r=i.memoizedState,a=a(c,r),a=a==null?r:_({},r,a),i.memoizedState=a,i.lanes===0&&(i.updateQueue.baseState=a)}var Km={enqueueSetState:function(i,r,a){i=i._reactInternals;var c=kr(),h=no(c);h.payload=r,a!=null&&(h.callback=a),r=io(i,h,c),r!==null&&(lr(r,i,c),Lu(r,i,c))},enqueueReplaceState:function(i,r,a){i=i._reactInternals;var c=kr(),h=no(c);h.tag=1,h.payload=r,a!=null&&(h.callback=a),r=io(i,h,c),r!==null&&(lr(r,i,c),Lu(r,i,c))},enqueueForceUpdate:function(i,r){i=i._reactInternals;var a=kr(),c=no(a);c.tag=2,r!=null&&(c.callback=r),r=io(i,c,a),r!==null&&(lr(r,i,a),Lu(r,i,a))}};function a0(i,r,a,c,h,g,y){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(c,g,y):r.prototype&&r.prototype.isPureReactComponent?!Pr(a,c)||!Pr(h,g):!0}function o0(i,r,a,c){i=r.state,typeof r.componentWillReceiveProps=="function"&&r.componentWillReceiveProps(a,c),typeof r.UNSAFE_componentWillReceiveProps=="function"&&r.UNSAFE_componentWillReceiveProps(a,c),r.state!==i&&Km.enqueueReplaceState(r,r.state,null)}function _l(i,r){var a=r;if("ref"in r){a={};for(var c in r)c!=="ref"&&(a[c]=r[c])}if(i=i.defaultProps){a===r&&(a=_({},a));for(var h in i)a[h]===void 0&&(a[h]=i[h])}return a}function l0(i){Xa(i)}function c0(i){console.error(i)}function u0(i){Xa(i)}function $h(i,r){try{var a=i.onUncaughtError;a(r.value,{componentStack:r.stack})}catch(c){setTimeout(function(){throw c})}}function d0(i,r,a){try{var c=i.onCaughtError;c(a.value,{componentStack:a.stack,errorBoundary:r.tag===1?r.stateNode:null})}catch(h){setTimeout(function(){throw h})}}function qm(i,r,a){return a=no(a),a.tag=3,a.payload={element:null},a.callback=function(){$h(i,r)},a}function h0(i){return i=no(i),i.tag=3,i}function f0(i,r,a,c){var h=a.type.getDerivedStateFromError;if(typeof h=="function"){var g=c.value;i.payload=function(){return h(g)},i.callback=function(){d0(r,a,c)}}var y=a.stateNode;y!==null&&typeof y.componentDidCatch=="function"&&(i.callback=function(){d0(r,a,c),typeof h!="function"&&(co===null?co=new Set([this]):co.add(this));var D=c.stack;this.componentDidCatch(c.value,{componentStack:D!==null?D:""})})}function mR(i,r,a,c,h){if(a.flags|=32768,c!==null&&typeof c=="object"&&typeof c.then=="function"){if(r=a.alternate,r!==null&&Fi(r,a,h,!0),a=Sr.current,a!==null){switch(a.tag){case 31:case 13:return Fr===null?ef():a.alternate===null&&Ln===0&&(Ln=3),a.flags&=-257,a.flags|=65536,a.lanes=h,c===Nh?a.flags|=16384:(r=a.updateQueue,r===null?a.updateQueue=new Set([c]):r.add(c),vg(i,c,h)),!1;case 22:return a.flags|=65536,c===Nh?a.flags|=16384:(r=a.updateQueue,r===null?(r={transitions:null,markerInstances:null,retryQueue:new Set([c])},a.updateQueue=r):(a=r.retryQueue,a===null?r.retryQueue=new Set([c]):a.add(c)),vg(i,c,h)),!1}throw Error(s(435,a.tag))}return vg(i,c,h),ef(),!1}if(Et)return r=Sr.current,r!==null?((r.flags&65536)===0&&(r.flags|=256),r.flags|=65536,r.lanes=h,c!==Ru&&(i=Error(s(422),{cause:c}),ct(zn(i,a)))):(c!==Ru&&(r=Error(s(423),{cause:c}),ct(zn(r,a))),i=i.current.alternate,i.flags|=65536,h&=-h,i.lanes|=h,c=zn(c,a),h=qm(i.stateNode,c,h),wm(i,h),Ln!==4&&(Ln=2)),!1;var g=Error(s(520),{cause:c});if(g=zn(g,a),Vu===null?Vu=[g]:Vu.push(g),Ln!==4&&(Ln=2),r===null)return!0;c=zn(c,a),a=r;do{switch(a.tag){case 3:return a.flags|=65536,i=h&-h,a.lanes|=i,i=qm(a.stateNode,c,i),wm(a,i),!1;case 1:if(r=a.type,g=a.stateNode,(a.flags&128)===0&&(typeof r.getDerivedStateFromError=="function"||g!==null&&typeof g.componentDidCatch=="function"&&(co===null||!co.has(g))))return a.flags|=65536,h&=-h,a.lanes|=h,h=h0(h),f0(h,i,a,c),wm(a,h),!1}a=a.return}while(a!==null);return!1}var Vm=Error(s(461)),Qn=!1;function ki(i,r,a,c){r.child=i===null?vS(r,null,a,c):gl(r,i.child,a,c)}function p0(i,r,a,c,h){a=a.render;var g=r.ref;if("ref"in c){var y={};for(var D in c)D!=="ref"&&(y[D]=c[D])}else y=c;return _n(r),c=Rm(i,r,a,y,g,h),D=Nm(),i!==null&&!Qn?(Dm(i,r,h),fa(i,r,h)):(Et&&D&&Eu(r),r.flags|=1,ki(i,r,c,h),r.child)}function m0(i,r,a,c,h){if(i===null){var g=a.type;return typeof g=="function"&&!ca(g)&&g.defaultProps===void 0&&a.compare===null?(r.tag=15,r.type=g,g0(i,r,g,c,h)):(i=lc(a.type,null,c,r,r.mode,h),i.ref=r.ref,i.return=r,r.child=i)}if(g=i.child,!tg(i,h)){var y=g.memoizedProps;if(a=a.compare,a=a!==null?a:Pr,a(y,c)&&i.ref===r.ref)return fa(i,r,h)}return r.flags|=1,i=Hr(g,c),i.ref=r.ref,i.return=r,r.child=i}function g0(i,r,a,c,h){if(i!==null){var g=i.memoizedProps;if(Pr(g,c)&&i.ref===r.ref)if(Qn=!1,r.pendingProps=c=g,tg(i,h))(i.flags&131072)!==0&&(Qn=!0);else return r.lanes=i.lanes,fa(i,r,h)}return Ym(i,r,a,c,h)}function v0(i,r,a,c){var h=c.children,g=i!==null?i.memoizedState:null;if(i===null&&r.stateNode===null&&(r.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),c.mode==="hidden"){if((r.flags&128)!==0){if(g=g!==null?g.baseLanes|a:a,i!==null){for(c=r.child=i.child,h=0;c!==null;)h=h|c.lanes|c.childLanes,c=c.sibling;c=h&~g}else c=0,r.child=null;return _0(i,r,g,a,c)}if((a&536870912)!==0)r.memoizedState={baseLanes:0,cachePool:null},i!==null&&Eh(r,g!==null?g.cachePool:null),g!==null?yS(r,g):Cm(),SS(r);else return c=r.lanes=536870912,_0(i,r,g!==null?g.baseLanes|a:a,a,c)}else g!==null?(Eh(r,g.cachePool),yS(r,g),so(),r.memoizedState=null):(i!==null&&Eh(r,null),Cm(),so());return ki(i,r,h,a),r.child}function Hu(i,r){return i!==null&&i.tag===22||r.stateNode!==null||(r.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),r.sibling}function _0(i,r,a,c,h){var g=_m();return g=g===null?null:{parent:Xn._currentValue,pool:g},r.memoizedState={baseLanes:a,cachePool:g},i!==null&&Eh(r,null),Cm(),SS(r),i!==null&&Fi(i,r,c,!0),r.childLanes=h,null}function Fh(i,r){return r=Kh({mode:r.mode,children:r.children},i.mode),r.ref=i.ref,i.child=r,r.return=i,r}function b0(i,r,a){return gl(r,i.child,null,a),i=Fh(r,r.pendingProps),i.flags|=2,wr(r),r.memoizedState=null,i}function gR(i,r,a){var c=r.pendingProps,h=(r.flags&128)!==0;if(r.flags&=-129,i===null){if(Et){if(c.mode==="hidden")return i=Fh(r,c),r.lanes=536870912,Hu(null,i);if(Tm(r),(i=dn)?(i=Mw(i,ir),i=i!==null&&i.data==="&"?i:null,i!==null&&(r.memoizedState={dehydrated:i,treeContext:Ms!==null?{id:yr,overflow:Ur}:null,retryLane:536870912,hydrationErrors:null},a=Cu(i),a.return=r,r.child=a,ri=r,dn=null)):i=null,i===null)throw ls(r);return r.lanes=536870912,null}return Fh(r,c)}var g=i.memoizedState;if(g!==null){var y=g.dehydrated;if(Tm(r),h)if(r.flags&256)r.flags&=-257,r=b0(i,r,a);else if(r.memoizedState!==null)r.child=i.child,r.flags|=128,r=null;else throw Error(s(558));else if(Qn||Fi(i,r,a,!1),h=(a&i.childLanes)!==0,Qn||h){if(c=fn,c!==null&&(y=Kn(c,a),y!==0&&y!==g.retryLane))throw g.retryLane=y,Ns(i,y),lr(c,i,y),Vm;ef(),r=b0(i,r,a)}else i=g.treeContext,dn=Wr(y.nextSibling),ri=r,Et=!0,$i=null,ir=!1,i!==null&&$r(r,i),r=Fh(r,c),r.flags|=4096;return r}return i=Hr(i.child,{mode:c.mode,children:c.children}),i.ref=r.ref,r.child=i,i.return=r,i}function Wh(i,r){var a=r.ref;if(a===null)i!==null&&i.ref!==null&&(r.flags|=4194816);else{if(typeof a!="function"&&typeof a!="object")throw Error(s(284));(i===null||i.ref!==a)&&(r.flags|=4194816)}}function Ym(i,r,a,c,h){return _n(r),a=Rm(i,r,a,c,void 0,h),c=Nm(),i!==null&&!Qn?(Dm(i,r,h),fa(i,r,h)):(Et&&c&&Eu(r),r.flags|=1,ki(i,r,a,h),r.child)}function y0(i,r,a,c,h,g){return _n(r),r.updateQueue=null,a=xS(r,c,a,h),wS(i),c=Nm(),i!==null&&!Qn?(Dm(i,r,g),fa(i,r,g)):(Et&&c&&Eu(r),r.flags|=1,ki(i,r,a,g),r.child)}function S0(i,r,a,c,h){if(_n(r),r.stateNode===null){var g=Za,y=a.contextType;typeof y=="object"&&y!==null&&(g=Yn(y)),g=new a(c,g),r.memoizedState=g.state!==null&&g.state!==void 0?g.state:null,g.updater=Km,r.stateNode=g,g._reactInternals=r,g=r.stateNode,g.props=c,g.state=r.memoizedState,g.refs={},ym(r),y=a.contextType,g.context=typeof y=="object"&&y!==null?Yn(y):Za,g.state=r.memoizedState,y=a.getDerivedStateFromProps,typeof y=="function"&&(Wm(r,a,y,c),g.state=r.memoizedState),typeof a.getDerivedStateFromProps=="function"||typeof g.getSnapshotBeforeUpdate=="function"||typeof g.UNSAFE_componentWillMount!="function"&&typeof g.componentWillMount!="function"||(y=g.state,typeof g.componentWillMount=="function"&&g.componentWillMount(),typeof g.UNSAFE_componentWillMount=="function"&&g.UNSAFE_componentWillMount(),y!==g.state&&Km.enqueueReplaceState(g,g.state,null),Ou(r,c,g,h),ju(),g.state=r.memoizedState),typeof g.componentDidMount=="function"&&(r.flags|=4194308),c=!0}else if(i===null){g=r.stateNode;var D=r.memoizedProps,$=_l(a,D);g.props=$;var ue=g.context,Se=a.contextType;y=Za,typeof Se=="object"&&Se!==null&&(y=Yn(Se));var Re=a.getDerivedStateFromProps;Se=typeof Re=="function"||typeof g.getSnapshotBeforeUpdate=="function",D=r.pendingProps!==D,Se||typeof g.UNSAFE_componentWillReceiveProps!="function"&&typeof g.componentWillReceiveProps!="function"||(D||ue!==y)&&o0(r,g,c,y),to=!1;var pe=r.memoizedState;g.state=pe,Ou(r,c,g,h),ju(),ue=r.memoizedState,D||pe!==ue||to?(typeof Re=="function"&&(Wm(r,a,Re,c),ue=r.memoizedState),($=to||a0(r,a,$,c,pe,ue,y))?(Se||typeof g.UNSAFE_componentWillMount!="function"&&typeof g.componentWillMount!="function"||(typeof g.componentWillMount=="function"&&g.componentWillMount(),typeof g.UNSAFE_componentWillMount=="function"&&g.UNSAFE_componentWillMount()),typeof g.componentDidMount=="function"&&(r.flags|=4194308)):(typeof g.componentDidMount=="function"&&(r.flags|=4194308),r.memoizedProps=c,r.memoizedState=ue),g.props=c,g.state=ue,g.context=y,c=$):(typeof g.componentDidMount=="function"&&(r.flags|=4194308),c=!1)}else{g=r.stateNode,Sm(i,r),y=r.memoizedProps,Se=_l(a,y),g.props=Se,Re=r.pendingProps,pe=g.context,ue=a.contextType,$=Za,typeof ue=="object"&&ue!==null&&($=Yn(ue)),D=a.getDerivedStateFromProps,(ue=typeof D=="function"||typeof g.getSnapshotBeforeUpdate=="function")||typeof g.UNSAFE_componentWillReceiveProps!="function"&&typeof g.componentWillReceiveProps!="function"||(y!==Re||pe!==$)&&o0(r,g,c,$),to=!1,pe=r.memoizedState,g.state=pe,Ou(r,c,g,h),ju();var _e=r.memoizedState;y!==Re||pe!==_e||to||i!==null&&i.dependencies!==null&&hl(i.dependencies)?(typeof D=="function"&&(Wm(r,a,D,c),_e=r.memoizedState),(Se=to||a0(r,a,Se,c,pe,_e,$)||i!==null&&i.dependencies!==null&&hl(i.dependencies))?(ue||typeof g.UNSAFE_componentWillUpdate!="function"&&typeof g.componentWillUpdate!="function"||(typeof g.componentWillUpdate=="function"&&g.componentWillUpdate(c,_e,$),typeof g.UNSAFE_componentWillUpdate=="function"&&g.UNSAFE_componentWillUpdate(c,_e,$)),typeof g.componentDidUpdate=="function"&&(r.flags|=4),typeof g.getSnapshotBeforeUpdate=="function"&&(r.flags|=1024)):(typeof g.componentDidUpdate!="function"||y===i.memoizedProps&&pe===i.memoizedState||(r.flags|=4),typeof g.getSnapshotBeforeUpdate!="function"||y===i.memoizedProps&&pe===i.memoizedState||(r.flags|=1024),r.memoizedProps=c,r.memoizedState=_e),g.props=c,g.state=_e,g.context=$,c=Se):(typeof g.componentDidUpdate!="function"||y===i.memoizedProps&&pe===i.memoizedState||(r.flags|=4),typeof g.getSnapshotBeforeUpdate!="function"||y===i.memoizedProps&&pe===i.memoizedState||(r.flags|=1024),c=!1)}return g=c,Wh(i,r),c=(r.flags&128)!==0,g||c?(g=r.stateNode,a=c&&typeof a.getDerivedStateFromError!="function"?null:g.render(),r.flags|=1,i!==null&&c?(r.child=gl(r,i.child,null,h),r.child=gl(r,null,a,h)):ki(i,r,a,h),r.memoizedState=g.state,i=r.child):i=fa(i,r,h),i}function w0(i,r,a,c){return Xe(),r.flags|=256,ki(i,r,a,c),r.child}var Gm={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Xm(i){return{baseLanes:i,cachePool:dS()}}function Zm(i,r,a){return i=i!==null?i.childLanes&~a:0,r&&(i|=Cr),i}function x0(i,r,a){var c=r.pendingProps,h=!1,g=(r.flags&128)!==0,y;if((y=g)||(y=i!==null&&i.memoizedState===null?!1:(Un.current&2)!==0),y&&(h=!0,r.flags&=-129),y=(r.flags&32)!==0,r.flags&=-33,i===null){if(Et){if(h?ro(r):so(),(i=dn)?(i=Mw(i,ir),i=i!==null&&i.data!=="&"?i:null,i!==null&&(r.memoizedState={dehydrated:i,treeContext:Ms!==null?{id:yr,overflow:Ur}:null,retryLane:536870912,hydrationErrors:null},a=Cu(i),a.return=r,r.child=a,ri=r,dn=null)):i=null,i===null)throw ls(r);return Lg(i)?r.lanes=32:r.lanes=536870912,null}var D=c.children;return c=c.fallback,h?(so(),h=r.mode,D=Kh({mode:"hidden",children:D},h),c=Ds(c,h,a,null),D.return=r,c.return=r,D.sibling=c,r.child=D,c=r.child,c.memoizedState=Xm(a),c.childLanes=Zm(i,y,a),r.memoizedState=Gm,Hu(null,c)):(ro(r),Qm(r,D))}var $=i.memoizedState;if($!==null&&(D=$.dehydrated,D!==null)){if(g)r.flags&256?(ro(r),r.flags&=-257,r=Jm(i,r,a)):r.memoizedState!==null?(so(),r.child=i.child,r.flags|=128,r=null):(so(),D=c.fallback,h=r.mode,c=Kh({mode:"visible",children:c.children},h),D=Ds(D,h,a,null),D.flags|=2,c.return=r,D.return=r,c.sibling=D,r.child=c,gl(r,i.child,null,a),c=r.child,c.memoizedState=Xm(a),c.childLanes=Zm(i,y,a),r.memoizedState=Gm,r=Hu(null,c));else if(ro(r),Lg(D)){if(y=D.nextSibling&&D.nextSibling.dataset,y)var ue=y.dgst;y=ue,c=Error(s(419)),c.stack="",c.digest=y,ct({value:c,source:null,stack:null}),r=Jm(i,r,a)}else if(Qn||Fi(i,r,a,!1),y=(a&i.childLanes)!==0,Qn||y){if(y=fn,y!==null&&(c=Kn(y,a),c!==0&&c!==$.retryLane))throw $.retryLane=c,Ns(i,c),lr(y,i,c),Vm;Ag(D)||ef(),r=Jm(i,r,a)}else Ag(D)?(r.flags|=192,r.child=i.child,r=null):(i=$.treeContext,dn=Wr(D.nextSibling),ri=r,Et=!0,$i=null,ir=!1,i!==null&&$r(r,i),r=Qm(r,c.children),r.flags|=4096);return r}return h?(so(),D=c.fallback,h=r.mode,$=i.child,ue=$.sibling,c=Hr($,{mode:"hidden",children:c.children}),c.subtreeFlags=$.subtreeFlags&65011712,ue!==null?D=Hr(ue,D):(D=Ds(D,h,a,null),D.flags|=2),D.return=r,c.return=r,c.sibling=D,r.child=c,Hu(null,c),c=r.child,D=i.child.memoizedState,D===null?D=Xm(a):(h=D.cachePool,h!==null?($=Xn._currentValue,h=h.parent!==$?{parent:$,pool:$}:h):h=dS(),D={baseLanes:D.baseLanes|a,cachePool:h}),c.memoizedState=D,c.childLanes=Zm(i,y,a),r.memoizedState=Gm,Hu(i.child,c)):(ro(r),a=i.child,i=a.sibling,a=Hr(a,{mode:"visible",children:c.children}),a.return=r,a.sibling=null,i!==null&&(y=r.deletions,y===null?(r.deletions=[i],r.flags|=16):y.push(i)),r.child=a,r.memoizedState=null,a)}function Qm(i,r){return r=Kh({mode:"visible",children:r},i.mode),r.return=i,i.child=r}function Kh(i,r){return i=Ci(22,i,null,r),i.lanes=0,i}function Jm(i,r,a){return gl(r,i.child,null,a),i=Qm(r,r.pendingProps.children),i.flags|=2,r.memoizedState=null,i}function C0(i,r,a){i.lanes|=r;var c=i.alternate;c!==null&&(c.lanes|=r),hn(i.return,r,a)}function eg(i,r,a,c,h,g){var y=i.memoizedState;y===null?i.memoizedState={isBackwards:r,rendering:null,renderingStartTime:0,last:c,tail:a,tailMode:h,treeForkCount:g}:(y.isBackwards=r,y.rendering=null,y.renderingStartTime=0,y.last=c,y.tail=a,y.tailMode=h,y.treeForkCount=g)}function k0(i,r,a){var c=r.pendingProps,h=c.revealOrder,g=c.tail;c=c.children;var y=Un.current,D=(y&2)!==0;if(D?(y=y&1|2,r.flags|=128):y&=1,se(Un,y),ki(i,r,c,a),c=Et?dl:0,!D&&i!==null&&(i.flags&128)!==0)e:for(i=r.child;i!==null;){if(i.tag===13)i.memoizedState!==null&&C0(i,a,r);else if(i.tag===19)C0(i,a,r);else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===r)break e;for(;i.sibling===null;){if(i.return===null||i.return===r)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}switch(h){case"forwards":for(a=r.child,h=null;a!==null;)i=a.alternate,i!==null&&Lh(i)===null&&(h=a),a=a.sibling;a=h,a===null?(h=r.child,r.child=null):(h=a.sibling,a.sibling=null),eg(r,!1,h,a,g,c);break;case"backwards":case"unstable_legacy-backwards":for(a=null,h=r.child,r.child=null;h!==null;){if(i=h.alternate,i!==null&&Lh(i)===null){r.child=h;break}i=h.sibling,h.sibling=a,a=h,h=i}eg(r,!0,a,null,g,c);break;case"together":eg(r,!1,null,null,void 0,c);break;default:r.memoizedState=null}return r.child}function fa(i,r,a){if(i!==null&&(r.dependencies=i.dependencies),lo|=r.lanes,(a&r.childLanes)===0)if(i!==null){if(Fi(i,r,a,!1),(a&r.childLanes)===0)return null}else return null;if(i!==null&&r.child!==i.child)throw Error(s(153));if(r.child!==null){for(i=r.child,a=Hr(i,i.pendingProps),r.child=a,a.return=r;i.sibling!==null;)i=i.sibling,a=a.sibling=Hr(i,i.pendingProps),a.return=r;a.sibling=null}return r.child}function tg(i,r){return(i.lanes&r)!==0?!0:(i=i.dependencies,!!(i!==null&&hl(i)))}function vR(i,r,a){switch(r.tag){case 3:Ke(r,r.stateNode.containerInfo),ut(r,Xn,i.memoizedState.cache),Xe();break;case 27:case 5:ve(r);break;case 4:Ke(r,r.stateNode.containerInfo);break;case 10:ut(r,r.type,r.memoizedProps.value);break;case 31:if(r.memoizedState!==null)return r.flags|=128,Tm(r),null;break;case 13:var c=r.memoizedState;if(c!==null)return c.dehydrated!==null?(ro(r),r.flags|=128,null):(a&r.child.childLanes)!==0?x0(i,r,a):(ro(r),i=fa(i,r,a),i!==null?i.sibling:null);ro(r);break;case 19:var h=(i.flags&128)!==0;if(c=(a&r.childLanes)!==0,c||(Fi(i,r,a,!1),c=(a&r.childLanes)!==0),h){if(c)return k0(i,r,a);r.flags|=128}if(h=r.memoizedState,h!==null&&(h.rendering=null,h.tail=null,h.lastEffect=null),se(Un,Un.current),c)break;return null;case 22:return r.lanes=0,v0(i,r,a,r.pendingProps);case 24:ut(r,Xn,i.memoizedState.cache)}return fa(i,r,a)}function T0(i,r,a){if(i!==null)if(i.memoizedProps!==r.pendingProps)Qn=!0;else{if(!tg(i,a)&&(r.flags&128)===0)return Qn=!1,vR(i,r,a);Qn=(i.flags&131072)!==0}else Qn=!1,Et&&(r.flags&1048576)!==0&&xh(r,dl,r.index);switch(r.lanes=0,r.tag){case 16:e:{var c=r.pendingProps;if(i=pl(r.elementType),r.type=i,typeof i=="function")ca(i)?(c=_l(i,c),r.tag=1,r=S0(null,r,i,c,a)):(r.tag=0,r=Ym(null,r,i,c,a));else{if(i!=null){var h=i.$$typeof;if(h===U){r.tag=11,r=p0(null,r,i,c,a);break e}else if(h===I){r.tag=14,r=m0(null,r,i,c,a);break e}}throw r=Q(i)||i,Error(s(306,r,""))}}return r;case 0:return Ym(i,r,r.type,r.pendingProps,a);case 1:return c=r.type,h=_l(c,r.pendingProps),S0(i,r,c,h,a);case 3:e:{if(Ke(r,r.stateNode.containerInfo),i===null)throw Error(s(387));c=r.pendingProps;var g=r.memoizedState;h=g.element,Sm(i,r),Ou(r,c,null,a);var y=r.memoizedState;if(c=y.cache,ut(r,Xn,c),c!==g.cache&&Oi(r,[Xn],a,!0),ju(),c=y.element,g.isDehydrated)if(g={element:c,isDehydrated:!1,cache:y.cache},r.updateQueue.baseState=g,r.memoizedState=g,r.flags&256){r=w0(i,r,c,a);break e}else if(c!==h){h=zn(Error(s(424)),r),ct(h),r=w0(i,r,c,a);break e}else for(i=r.stateNode.containerInfo,i.nodeType===9?i=i.body:i=i.nodeName==="HTML"?i.ownerDocument.body:i,dn=Wr(i.firstChild),ri=r,Et=!0,$i=null,ir=!0,a=vS(r,null,c,a),r.child=a;a;)a.flags=a.flags&-3|4096,a=a.sibling;else{if(Xe(),c===h){r=fa(i,r,a);break e}ki(i,r,c,a)}r=r.child}return r;case 26:return Wh(i,r),i===null?(a=Iw(r.type,null,r.pendingProps,null))?r.memoizedState=a:Et||(a=r.type,i=r.pendingProps,c=lf(ye.current).createElement(a),c[ke]=r,c[Ge]=i,Ti(c,a,i),Wt(c),r.stateNode=c):r.memoizedState=Iw(r.type,i.memoizedProps,r.pendingProps,i.memoizedState),null;case 27:return ve(r),i===null&&Et&&(c=r.stateNode=jw(r.type,r.pendingProps,ye.current),ri=r,ir=!0,h=dn,po(r.type)?(jg=h,dn=Wr(c.firstChild)):dn=h),ki(i,r,r.pendingProps.children,a),Wh(i,r),i===null&&(r.flags|=4194304),r.child;case 5:return i===null&&Et&&((h=c=dn)&&(c=VR(c,r.type,r.pendingProps,ir),c!==null?(r.stateNode=c,ri=r,dn=Wr(c.firstChild),ir=!1,h=!0):h=!1),h||ls(r)),ve(r),h=r.type,g=r.pendingProps,y=i!==null?i.memoizedProps:null,c=g.children,Ng(h,g)?c=null:y!==null&&Ng(h,y)&&(r.flags|=32),r.memoizedState!==null&&(h=Rm(i,r,lR,null,null,a),td._currentValue=h),Wh(i,r),ki(i,r,c,a),r.child;case 6:return i===null&&Et&&((i=a=dn)&&(a=YR(a,r.pendingProps,ir),a!==null?(r.stateNode=a,ri=r,dn=null,i=!0):i=!1),i||ls(r)),null;case 13:return x0(i,r,a);case 4:return Ke(r,r.stateNode.containerInfo),c=r.pendingProps,i===null?r.child=gl(r,null,c,a):ki(i,r,c,a),r.child;case 11:return p0(i,r,r.type,r.pendingProps,a);case 7:return ki(i,r,r.pendingProps,a),r.child;case 8:return ki(i,r,r.pendingProps.children,a),r.child;case 12:return ki(i,r,r.pendingProps.children,a),r.child;case 10:return c=r.pendingProps,ut(r,r.type,c.value),ki(i,r,c.children,a),r.child;case 9:return h=r.type._context,c=r.pendingProps.children,_n(r),h=Yn(h),c=c(h),r.flags|=1,ki(i,r,c,a),r.child;case 14:return m0(i,r,r.type,r.pendingProps,a);case 15:return g0(i,r,r.type,r.pendingProps,a);case 19:return k0(i,r,a);case 31:return gR(i,r,a);case 22:return v0(i,r,a,r.pendingProps);case 24:return _n(r),c=Yn(Xn),i===null?(h=_m(),h===null&&(h=fn,g=gm(),h.pooledCache=g,g.refCount++,g!==null&&(h.pooledCacheLanes|=a),h=g),r.memoizedState={parent:c,cache:h},ym(r),ut(r,Xn,h)):((i.lanes&a)!==0&&(Sm(i,r),Ou(r,null,null,a),ju()),h=i.memoizedState,g=r.memoizedState,h.parent!==c?(h={parent:c,cache:c},r.memoizedState=h,r.lanes===0&&(r.memoizedState=r.updateQueue.baseState=h),ut(r,Xn,c)):(c=g.cache,ut(r,Xn,c),c!==h.cache&&Oi(r,[Xn],a,!0))),ki(i,r,r.pendingProps.children,a),r.child;case 29:throw r.pendingProps}throw Error(s(156,r.tag))}function pa(i){i.flags|=4}function ng(i,r,a,c,h){if((r=(i.mode&32)!==0)&&(r=!1),r){if(i.flags|=16777216,(h&335544128)===h)if(i.stateNode.complete)i.flags|=8192;else if(J0())i.flags|=8192;else throw ml=Nh,bm}else i.flags&=-16777217}function E0(i,r){if(r.type!=="stylesheet"||(r.state.loading&4)!==0)i.flags&=-16777217;else if(i.flags|=16777216,!$w(r))if(J0())i.flags|=8192;else throw ml=Nh,bm}function qh(i,r){r!==null&&(i.flags|=4),i.flags&16384&&(r=i.tag!==22?Ft():536870912,i.lanes|=r,wc|=r)}function Uu(i,r){if(!Et)switch(i.tailMode){case"hidden":r=i.tail;for(var a=null;r!==null;)r.alternate!==null&&(a=r),r=r.sibling;a===null?i.tail=null:a.sibling=null;break;case"collapsed":a=i.tail;for(var c=null;a!==null;)a.alternate!==null&&(c=a),a=a.sibling;c===null?r||i.tail===null?i.tail=null:i.tail.sibling=null:c.sibling=null}}function bn(i){var r=i.alternate!==null&&i.alternate.child===i.child,a=0,c=0;if(r)for(var h=i.child;h!==null;)a|=h.lanes|h.childLanes,c|=h.subtreeFlags&65011712,c|=h.flags&65011712,h.return=i,h=h.sibling;else for(h=i.child;h!==null;)a|=h.lanes|h.childLanes,c|=h.subtreeFlags,c|=h.flags,h.return=i,h=h.sibling;return i.subtreeFlags|=c,i.childLanes=a,r}function _R(i,r,a){var c=r.pendingProps;switch(uc(r),r.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return bn(r),null;case 1:return bn(r),null;case 3:return a=r.stateNode,c=null,i!==null&&(c=i.memoizedState.cache),r.memoizedState.cache!==c&&(r.flags|=2048),Ut(Xn),Be(),a.pendingContext&&(a.context=a.pendingContext,a.pendingContext=null),(i===null||i.child===null)&&(xe(r)?pa(r):i===null||i.memoizedState.isDehydrated&&(r.flags&256)===0||(r.flags|=1024,et())),bn(r),null;case 26:var h=r.type,g=r.memoizedState;return i===null?(pa(r),g!==null?(bn(r),E0(r,g)):(bn(r),ng(r,h,null,c,a))):g?g!==i.memoizedState?(pa(r),bn(r),E0(r,g)):(bn(r),r.flags&=-16777217):(i=i.memoizedProps,i!==c&&pa(r),bn(r),ng(r,h,i,c,a)),null;case 27:if(Fe(r),a=ye.current,h=r.type,i!==null&&r.stateNode!=null)i.memoizedProps!==c&&pa(r);else{if(!c){if(r.stateNode===null)throw Error(s(166));return bn(r),null}i=Z.current,xe(r)?k(r):(i=jw(h,c,a),r.stateNode=i,pa(r))}return bn(r),null;case 5:if(Fe(r),h=r.type,i!==null&&r.stateNode!=null)i.memoizedProps!==c&&pa(r);else{if(!c){if(r.stateNode===null)throw Error(s(166));return bn(r),null}if(g=Z.current,xe(r))k(r);else{var y=lf(ye.current);switch(g){case 1:g=y.createElementNS("http://www.w3.org/2000/svg",h);break;case 2:g=y.createElementNS("http://www.w3.org/1998/Math/MathML",h);break;default:switch(h){case"svg":g=y.createElementNS("http://www.w3.org/2000/svg",h);break;case"math":g=y.createElementNS("http://www.w3.org/1998/Math/MathML",h);break;case"script":g=y.createElement("div"),g.innerHTML="<script><\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof c.is=="string"?y.createElement("select",{is:c.is}):y.createElement("select"),c.multiple?g.multiple=!0:c.size&&(g.size=c.size);break;default:g=typeof c.is=="string"?y.createElement(h,{is:c.is}):y.createElement(h)}}g[ke]=r,g[Ge]=c;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Ti(g,h,c),h){case"button":case"input":case"select":case"textarea":c=!!c.autoFocus;break e;case"img":c=!0;break e;default:c=!1}c&&pa(r)}}return bn(r),ng(r,r.type,i===null?null:i.memoizedProps,r.pendingProps,a),null;case 6:if(i&&r.stateNode!=null)i.memoizedProps!==c&&pa(r);else{if(typeof c!="string"&&r.stateNode===null)throw Error(s(166));if(i=ye.current,xe(r)){if(i=r.stateNode,a=r.memoizedProps,c=null,h=ri,h!==null)switch(h.tag){case 27:case 5:c=h.memoizedProps}i[ke]=r,i=!!(i.nodeValue===a||c!==null&&c.suppressHydrationWarning===!0||xw(i.nodeValue,a)),i||ls(r,!0)}else i=lf(i).createTextNode(c),i[ke]=r,r.stateNode=i}return bn(r),null;case 31:if(a=r.memoizedState,i===null||i.memoizedState!==null){if(c=xe(r),a!==null){if(i===null){if(!c)throw Error(s(318));if(i=r.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(s(557));i[ke]=r}else Xe(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;bn(r),i=!1}else a=et(),i!==null&&i.memoizedState!==null&&(i.memoizedState.hydrationErrors=a),i=!0;if(!i)return r.flags&256?(wr(r),r):(wr(r),null);if((r.flags&128)!==0)throw Error(s(558))}return bn(r),null;case 13:if(c=r.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(h=xe(r),c!==null&&c.dehydrated!==null){if(i===null){if(!h)throw Error(s(318));if(h=r.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(s(317));h[ke]=r}else Xe(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;bn(r),h=!1}else h=et(),i!==null&&i.memoizedState!==null&&(i.memoizedState.hydrationErrors=h),h=!0;if(!h)return r.flags&256?(wr(r),r):(wr(r),null)}return wr(r),(r.flags&128)!==0?(r.lanes=a,r):(a=c!==null,i=i!==null&&i.memoizedState!==null,a&&(c=r.child,h=null,c.alternate!==null&&c.alternate.memoizedState!==null&&c.alternate.memoizedState.cachePool!==null&&(h=c.alternate.memoizedState.cachePool.pool),g=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(g=c.memoizedState.cachePool.pool),g!==h&&(c.flags|=2048)),a!==i&&a&&(r.child.flags|=8192),qh(r,r.updateQueue),bn(r),null);case 4:return Be(),i===null&&Cg(r.stateNode.containerInfo),bn(r),null;case 10:return Ut(r.type),bn(r),null;case 19:if(V(Un),c=r.memoizedState,c===null)return bn(r),null;if(h=(r.flags&128)!==0,g=c.rendering,g===null)if(h)Uu(c,!1);else{if(Ln!==0||i!==null&&(i.flags&128)!==0)for(i=r.child;i!==null;){if(g=Lh(i),g!==null){for(r.flags|=128,Uu(c,!1),i=g.updateQueue,r.updateQueue=i,qh(r,i),r.subtreeFlags=0,i=a,a=r.child;a!==null;)xu(a,i),a=a.sibling;return se(Un,Un.current&1|2),Et&&os(r,c.treeForkCount),r.child}i=i.sibling}c.tail!==null&&qe()>Zh&&(r.flags|=128,h=!0,Uu(c,!1),r.lanes=4194304)}else{if(!h)if(i=Lh(g),i!==null){if(r.flags|=128,h=!0,i=i.updateQueue,r.updateQueue=i,qh(r,i),Uu(c,!0),c.tail===null&&c.tailMode==="hidden"&&!g.alternate&&!Et)return bn(r),null}else 2*qe()-c.renderingStartTime>Zh&&a!==536870912&&(r.flags|=128,h=!0,Uu(c,!1),r.lanes=4194304);c.isBackwards?(g.sibling=r.child,r.child=g):(i=c.last,i!==null?i.sibling=g:r.child=g,c.last=g)}return c.tail!==null?(i=c.tail,c.rendering=i,c.tail=i.sibling,c.renderingStartTime=qe(),i.sibling=null,a=Un.current,se(Un,h?a&1|2:a&1),Et&&os(r,c.treeForkCount),i):(bn(r),null);case 22:case 23:return wr(r),km(),c=r.memoizedState!==null,i!==null?i.memoizedState!==null!==c&&(r.flags|=8192):c&&(r.flags|=8192),c?(a&536870912)!==0&&(r.flags&128)===0&&(bn(r),r.subtreeFlags&6&&(r.flags|=8192)):bn(r),a=r.updateQueue,a!==null&&qh(r,a.retryQueue),a=null,i!==null&&i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(a=i.memoizedState.cachePool.pool),c=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(c=r.memoizedState.cachePool.pool),c!==a&&(r.flags|=2048),i!==null&&V(fl),null;case 24:return a=null,i!==null&&(a=i.memoizedState.cache),r.memoizedState.cache!==a&&(r.flags|=2048),Ut(Xn),bn(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function bR(i,r){switch(uc(r),r.tag){case 1:return i=r.flags,i&65536?(r.flags=i&-65537|128,r):null;case 3:return Ut(Xn),Be(),i=r.flags,(i&65536)!==0&&(i&128)===0?(r.flags=i&-65537|128,r):null;case 26:case 27:case 5:return Fe(r),null;case 31:if(r.memoizedState!==null){if(wr(r),r.alternate===null)throw Error(s(340));Xe()}return i=r.flags,i&65536?(r.flags=i&-65537|128,r):null;case 13:if(wr(r),i=r.memoizedState,i!==null&&i.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Xe()}return i=r.flags,i&65536?(r.flags=i&-65537|128,r):null;case 19:return V(Un),null;case 4:return Be(),null;case 10:return Ut(r.type),null;case 22:case 23:return wr(r),km(),i!==null&&V(fl),i=r.flags,i&65536?(r.flags=i&-65537|128,r):null;case 24:return Ut(Xn),null;case 25:return null;default:return null}}function R0(i,r){switch(uc(r),r.tag){case 3:Ut(Xn),Be();break;case 26:case 27:case 5:Fe(r);break;case 4:Be();break;case 31:r.memoizedState!==null&&wr(r);break;case 13:wr(r);break;case 19:V(Un);break;case 10:Ut(r.type);break;case 22:case 23:wr(r),km(),i!==null&&V(fl);break;case 24:Ut(Xn)}}function $u(i,r){try{var a=r.updateQueue,c=a!==null?a.lastEffect:null;if(c!==null){var h=c.next;a=h;do{if((a.tag&i)===i){c=void 0;var g=a.create,y=a.inst;c=g(),y.destroy=c}a=a.next}while(a!==h)}}catch(D){Jt(r,r.return,D)}}function ao(i,r,a){try{var c=r.updateQueue,h=c!==null?c.lastEffect:null;if(h!==null){var g=h.next;c=g;do{if((c.tag&i)===i){var y=c.inst,D=y.destroy;if(D!==void 0){y.destroy=void 0,h=r;var $=a,ue=D;try{ue()}catch(Se){Jt(h,$,Se)}}}c=c.next}while(c!==g)}}catch(Se){Jt(r,r.return,Se)}}function N0(i){var r=i.updateQueue;if(r!==null){var a=i.stateNode;try{bS(r,a)}catch(c){Jt(i,i.return,c)}}}function D0(i,r,a){a.props=_l(i.type,i.memoizedProps),a.state=i.memoizedState;try{a.componentWillUnmount()}catch(c){Jt(i,r,c)}}function Fu(i,r){try{var a=i.ref;if(a!==null){switch(i.tag){case 26:case 27:case 5:var c=i.stateNode;break;case 30:c=i.stateNode;break;default:c=i.stateNode}typeof a=="function"?i.refCleanup=a(c):a.current=c}}catch(h){Jt(i,r,h)}}function As(i,r){var a=i.ref,c=i.refCleanup;if(a!==null)if(typeof c=="function")try{c()}catch(h){Jt(i,r,h)}finally{i.refCleanup=null,i=i.alternate,i!=null&&(i.refCleanup=null)}else if(typeof a=="function")try{a(null)}catch(h){Jt(i,r,h)}else a.current=null}function M0(i){var r=i.type,a=i.memoizedProps,c=i.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":a.autoFocus&&c.focus();break e;case"img":a.src?c.src=a.src:a.srcSet&&(c.srcset=a.srcSet)}}catch(h){Jt(i,i.return,h)}}function ig(i,r,a){try{var c=i.stateNode;UR(c,i.type,a,r),c[Ge]=r}catch(h){Jt(i,i.return,h)}}function A0(i){return i.tag===5||i.tag===3||i.tag===26||i.tag===27&&po(i.type)||i.tag===4}function rg(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||A0(i.return))return null;i=i.return}for(i.sibling.return=i.return,i=i.sibling;i.tag!==5&&i.tag!==6&&i.tag!==18;){if(i.tag===27&&po(i.type)||i.flags&2||i.child===null||i.tag===4)continue e;i.child.return=i,i=i.child}if(!(i.flags&2))return i.stateNode}}function sg(i,r,a){var c=i.tag;if(c===5||c===6)i=i.stateNode,r?(a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a).insertBefore(i,r):(r=a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a,r.appendChild(i),a=a._reactRootContainer,a!=null||r.onclick!==null||(r.onclick=Mi));else if(c!==4&&(c===27&&po(i.type)&&(a=i.stateNode,r=null),i=i.child,i!==null))for(sg(i,r,a),i=i.sibling;i!==null;)sg(i,r,a),i=i.sibling}function Vh(i,r,a){var c=i.tag;if(c===5||c===6)i=i.stateNode,r?a.insertBefore(i,r):a.appendChild(i);else if(c!==4&&(c===27&&po(i.type)&&(a=i.stateNode),i=i.child,i!==null))for(Vh(i,r,a),i=i.sibling;i!==null;)Vh(i,r,a),i=i.sibling}function L0(i){var r=i.stateNode,a=i.memoizedProps;try{for(var c=i.type,h=r.attributes;h.length;)r.removeAttributeNode(h[0]);Ti(r,c,a),r[ke]=i,r[Ge]=a}catch(g){Jt(i,i.return,g)}}var ma=!1,Jn=!1,ag=!1,j0=typeof WeakSet=="function"?WeakSet:Set,mi=null;function yR(i,r){if(i=i.containerInfo,Eg=mf,i=fu(i),sc(i)){if("selectionStart"in i)var a={start:i.selectionStart,end:i.selectionEnd};else e:{a=(a=i.ownerDocument)&&a.defaultView||window;var c=a.getSelection&&a.getSelection();if(c&&c.rangeCount!==0){a=c.anchorNode;var h=c.anchorOffset,g=c.focusNode;c=c.focusOffset;try{a.nodeType,g.nodeType}catch{a=null;break e}var y=0,D=-1,$=-1,ue=0,Se=0,Re=i,pe=null;t:for(;;){for(var _e;Re!==a||h!==0&&Re.nodeType!==3||(D=y+h),Re!==g||c!==0&&Re.nodeType!==3||($=y+c),Re.nodeType===3&&(y+=Re.nodeValue.length),(_e=Re.firstChild)!==null;)pe=Re,Re=_e;for(;;){if(Re===i)break t;if(pe===a&&++ue===h&&(D=y),pe===g&&++Se===c&&($=y),(_e=Re.nextSibling)!==null)break;Re=pe,pe=Re.parentNode}Re=_e}a=D===-1||$===-1?null:{start:D,end:$}}else a=null}a=a||{start:0,end:0}}else a=null;for(Rg={focusedElem:i,selectionRange:a},mf=!1,mi=r;mi!==null;)if(r=mi,i=r.child,(r.subtreeFlags&1028)!==0&&i!==null)i.return=r,mi=i;else for(;mi!==null;){switch(r=mi,g=r.alternate,i=r.flags,r.tag){case 0:if((i&4)!==0&&(i=r.updateQueue,i=i!==null?i.events:null,i!==null))for(a=0;a<i.length;a++)h=i[a],h.ref.impl=h.nextImpl;break;case 11:case 15:break;case 1:if((i&1024)!==0&&g!==null){i=void 0,a=r,h=g.memoizedProps,g=g.memoizedState,c=a.stateNode;try{var Qe=_l(a.type,h);i=c.getSnapshotBeforeUpdate(Qe,g),c.__reactInternalSnapshotBeforeUpdate=i}catch(dt){Jt(a,a.return,dt)}}break;case 3:if((i&1024)!==0){if(i=r.stateNode.containerInfo,a=i.nodeType,a===9)Mg(i);else if(a===1)switch(i.nodeName){case"HEAD":case"HTML":case"BODY":Mg(i);break;default:i.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((i&1024)!==0)throw Error(s(163))}if(i=r.sibling,i!==null){i.return=r.return,mi=i;break}mi=r.return}}function O0(i,r,a){var c=a.flags;switch(a.tag){case 0:case 11:case 15:va(i,a),c&4&&$u(5,a);break;case 1:if(va(i,a),c&4)if(i=a.stateNode,r===null)try{i.componentDidMount()}catch(y){Jt(a,a.return,y)}else{var h=_l(a.type,r.memoizedProps);r=r.memoizedState;try{i.componentDidUpdate(h,r,i.__reactInternalSnapshotBeforeUpdate)}catch(y){Jt(a,a.return,y)}}c&64&&N0(a),c&512&&Fu(a,a.return);break;case 3:if(va(i,a),c&64&&(i=a.updateQueue,i!==null)){if(r=null,a.child!==null)switch(a.child.tag){case 27:case 5:r=a.child.stateNode;break;case 1:r=a.child.stateNode}try{bS(i,r)}catch(y){Jt(a,a.return,y)}}break;case 27:r===null&&c&4&&L0(a);case 26:case 5:va(i,a),r===null&&c&4&&M0(a),c&512&&Fu(a,a.return);break;case 12:va(i,a);break;case 31:va(i,a),c&4&&P0(i,a);break;case 13:va(i,a),c&4&&z0(i,a),c&64&&(i=a.memoizedState,i!==null&&(i=i.dehydrated,i!==null&&(a=NR.bind(null,a),GR(i,a))));break;case 22:if(c=a.memoizedState!==null||ma,!c){r=r!==null&&r.memoizedState!==null||Jn,h=ma;var g=Jn;ma=c,(Jn=r)&&!g?_a(i,a,(a.subtreeFlags&8772)!==0):va(i,a),ma=h,Jn=g}break;case 30:break;default:va(i,a)}}function B0(i){var r=i.alternate;r!==null&&(i.alternate=null,B0(r)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(r=i.stateNode,r!==null&&Xi(r)),i.stateNode=null,i.return=null,i.dependencies=null,i.memoizedProps=null,i.memoizedState=null,i.pendingProps=null,i.stateNode=null,i.updateQueue=null}var wn=null,rr=!1;function ga(i,r,a){for(a=a.child;a!==null;)I0(i,r,a),a=a.sibling}function I0(i,r,a){if(ft&&typeof ft.onCommitFiberUnmount=="function")try{ft.onCommitFiberUnmount(Tn,a)}catch{}switch(a.tag){case 26:Jn||As(a,r),ga(i,r,a),a.memoizedState?a.memoizedState.count--:a.stateNode&&(a=a.stateNode,a.parentNode.removeChild(a));break;case 27:Jn||As(a,r);var c=wn,h=rr;po(a.type)&&(wn=a.stateNode,rr=!1),ga(i,r,a),Qu(a.stateNode),wn=c,rr=h;break;case 5:Jn||As(a,r);case 6:if(c=wn,h=rr,wn=null,ga(i,r,a),wn=c,rr=h,wn!==null)if(rr)try{(wn.nodeType===9?wn.body:wn.nodeName==="HTML"?wn.ownerDocument.body:wn).removeChild(a.stateNode)}catch(g){Jt(a,r,g)}else try{wn.removeChild(a.stateNode)}catch(g){Jt(a,r,g)}break;case 18:wn!==null&&(rr?(i=wn,Nw(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,a.stateNode),Dc(i)):Nw(wn,a.stateNode));break;case 4:c=wn,h=rr,wn=a.stateNode.containerInfo,rr=!0,ga(i,r,a),wn=c,rr=h;break;case 0:case 11:case 14:case 15:ao(2,a,r),Jn||ao(4,a,r),ga(i,r,a);break;case 1:Jn||(As(a,r),c=a.stateNode,typeof c.componentWillUnmount=="function"&&D0(a,r,c)),ga(i,r,a);break;case 21:ga(i,r,a);break;case 22:Jn=(c=Jn)||a.memoizedState!==null,ga(i,r,a),Jn=c;break;default:ga(i,r,a)}}function P0(i,r){if(r.memoizedState===null&&(i=r.alternate,i!==null&&(i=i.memoizedState,i!==null))){i=i.dehydrated;try{Dc(i)}catch(a){Jt(r,r.return,a)}}}function z0(i,r){if(r.memoizedState===null&&(i=r.alternate,i!==null&&(i=i.memoizedState,i!==null&&(i=i.dehydrated,i!==null))))try{Dc(i)}catch(a){Jt(r,r.return,a)}}function SR(i){switch(i.tag){case 31:case 13:case 19:var r=i.stateNode;return r===null&&(r=i.stateNode=new j0),r;case 22:return i=i.stateNode,r=i._retryCache,r===null&&(r=i._retryCache=new j0),r;default:throw Error(s(435,i.tag))}}function Yh(i,r){var a=SR(i);r.forEach(function(c){if(!a.has(c)){a.add(c);var h=DR.bind(null,i,c);c.then(h,h)}})}function sr(i,r){var a=r.deletions;if(a!==null)for(var c=0;c<a.length;c++){var h=a[c],g=i,y=r,D=y;e:for(;D!==null;){switch(D.tag){case 27:if(po(D.type)){wn=D.stateNode,rr=!1;break e}break;case 5:wn=D.stateNode,rr=!1;break e;case 3:case 4:wn=D.stateNode.containerInfo,rr=!0;break e}D=D.return}if(wn===null)throw Error(s(160));I0(g,y,h),wn=null,rr=!1,g=h.alternate,g!==null&&(g.return=null),h.return=null}if(r.subtreeFlags&13886)for(r=r.child;r!==null;)H0(r,i),r=r.sibling}var cs=null;function H0(i,r){var a=i.alternate,c=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:sr(r,i),ar(i),c&4&&(ao(3,i,i.return),$u(3,i),ao(5,i,i.return));break;case 1:sr(r,i),ar(i),c&512&&(Jn||a===null||As(a,a.return)),c&64&&ma&&(i=i.updateQueue,i!==null&&(c=i.callbacks,c!==null&&(a=i.shared.hiddenCallbacks,i.shared.hiddenCallbacks=a===null?c:a.concat(c))));break;case 26:var h=cs;if(sr(r,i),ar(i),c&512&&(Jn||a===null||As(a,a.return)),c&4){var g=a!==null?a.memoizedState:null;if(c=i.memoizedState,a===null)if(c===null)if(i.stateNode===null){e:{c=i.type,a=i.memoizedProps,h=h.ownerDocument||h;t:switch(c){case"title":g=h.getElementsByTagName("title")[0],(!g||g[Xt]||g[ke]||g.namespaceURI==="http://www.w3.org/2000/svg"||g.hasAttribute("itemprop"))&&(g=h.createElement(c),h.head.insertBefore(g,h.querySelector("head > title"))),Ti(g,c,a),g[ke]=i,Wt(g),c=g;break e;case"link":var y=Hw("link","href",h).get(c+(a.href||""));if(y){for(var D=0;D<y.length;D++)if(g=y[D],g.getAttribute("href")===(a.href==null||a.href===""?null:a.href)&&g.getAttribute("rel")===(a.rel==null?null:a.rel)&&g.getAttribute("title")===(a.title==null?null:a.title)&&g.getAttribute("crossorigin")===(a.crossOrigin==null?null:a.crossOrigin)){y.splice(D,1);break t}}g=h.createElement(c),Ti(g,c,a),h.head.appendChild(g);break;case"meta":if(y=Hw("meta","content",h).get(c+(a.content||""))){for(D=0;D<y.length;D++)if(g=y[D],g.getAttribute("content")===(a.content==null?null:""+a.content)&&g.getAttribute("name")===(a.name==null?null:a.name)&&g.getAttribute("property")===(a.property==null?null:a.property)&&g.getAttribute("http-equiv")===(a.httpEquiv==null?null:a.httpEquiv)&&g.getAttribute("charset")===(a.charSet==null?null:a.charSet)){y.splice(D,1);break t}}g=h.createElement(c),Ti(g,c,a),h.head.appendChild(g);break;default:throw Error(s(468,c))}g[ke]=i,Wt(g),c=g}i.stateNode=c}else Uw(h,i.type,i.stateNode);else i.stateNode=zw(h,c,i.memoizedProps);else g!==c?(g===null?a.stateNode!==null&&(a=a.stateNode,a.parentNode.removeChild(a)):g.count--,c===null?Uw(h,i.type,i.stateNode):zw(h,c,i.memoizedProps)):c===null&&i.stateNode!==null&&ig(i,i.memoizedProps,a.memoizedProps)}break;case 27:sr(r,i),ar(i),c&512&&(Jn||a===null||As(a,a.return)),a!==null&&c&4&&ig(i,i.memoizedProps,a.memoizedProps);break;case 5:if(sr(r,i),ar(i),c&512&&(Jn||a===null||As(a,a.return)),i.flags&32){h=i.stateNode;try{_s(h,"")}catch(Qe){Jt(i,i.return,Qe)}}c&4&&i.stateNode!=null&&(h=i.memoizedProps,ig(i,h,a!==null?a.memoizedProps:h)),c&1024&&(ag=!0);break;case 6:if(sr(r,i),ar(i),c&4){if(i.stateNode===null)throw Error(s(162));c=i.memoizedProps,a=i.stateNode;try{a.nodeValue=c}catch(Qe){Jt(i,i.return,Qe)}}break;case 3:if(df=null,h=cs,cs=cf(r.containerInfo),sr(r,i),cs=h,ar(i),c&4&&a!==null&&a.memoizedState.isDehydrated)try{Dc(r.containerInfo)}catch(Qe){Jt(i,i.return,Qe)}ag&&(ag=!1,U0(i));break;case 4:c=cs,cs=cf(i.stateNode.containerInfo),sr(r,i),ar(i),cs=c;break;case 12:sr(r,i),ar(i);break;case 31:sr(r,i),ar(i),c&4&&(c=i.updateQueue,c!==null&&(i.updateQueue=null,Yh(i,c)));break;case 13:sr(r,i),ar(i),i.child.flags&8192&&i.memoizedState!==null!=(a!==null&&a.memoizedState!==null)&&(Xh=qe()),c&4&&(c=i.updateQueue,c!==null&&(i.updateQueue=null,Yh(i,c)));break;case 22:h=i.memoizedState!==null;var $=a!==null&&a.memoizedState!==null,ue=ma,Se=Jn;if(ma=ue||h,Jn=Se||$,sr(r,i),Jn=Se,ma=ue,ar(i),c&8192)e:for(r=i.stateNode,r._visibility=h?r._visibility&-2:r._visibility|1,h&&(a===null||$||ma||Jn||bl(i)),a=null,r=i;;){if(r.tag===5||r.tag===26){if(a===null){$=a=r;try{if(g=$.stateNode,h)y=g.style,typeof y.setProperty=="function"?y.setProperty("display","none","important"):y.display="none";else{D=$.stateNode;var Re=$.memoizedProps.style,pe=Re!=null&&Re.hasOwnProperty("display")?Re.display:null;D.style.display=pe==null||typeof pe=="boolean"?"":(""+pe).trim()}}catch(Qe){Jt($,$.return,Qe)}}}else if(r.tag===6){if(a===null){$=r;try{$.stateNode.nodeValue=h?"":$.memoizedProps}catch(Qe){Jt($,$.return,Qe)}}}else if(r.tag===18){if(a===null){$=r;try{var _e=$.stateNode;h?Dw(_e,!0):Dw($.stateNode,!1)}catch(Qe){Jt($,$.return,Qe)}}}else if((r.tag!==22&&r.tag!==23||r.memoizedState===null||r===i)&&r.child!==null){r.child.return=r,r=r.child;continue}if(r===i)break e;for(;r.sibling===null;){if(r.return===null||r.return===i)break e;a===r&&(a=null),r=r.return}a===r&&(a=null),r.sibling.return=r.return,r=r.sibling}c&4&&(c=i.updateQueue,c!==null&&(a=c.retryQueue,a!==null&&(c.retryQueue=null,Yh(i,a))));break;case 19:sr(r,i),ar(i),c&4&&(c=i.updateQueue,c!==null&&(i.updateQueue=null,Yh(i,c)));break;case 30:break;case 21:break;default:sr(r,i),ar(i)}}function ar(i){var r=i.flags;if(r&2){try{for(var a,c=i.return;c!==null;){if(A0(c)){a=c;break}c=c.return}if(a==null)throw Error(s(160));switch(a.tag){case 27:var h=a.stateNode,g=rg(i);Vh(i,g,h);break;case 5:var y=a.stateNode;a.flags&32&&(_s(y,""),a.flags&=-33);var D=rg(i);Vh(i,D,y);break;case 3:case 4:var $=a.stateNode.containerInfo,ue=rg(i);sg(i,ue,$);break;default:throw Error(s(161))}}catch(Se){Jt(i,i.return,Se)}i.flags&=-3}r&4096&&(i.flags&=-4097)}function U0(i){if(i.subtreeFlags&1024)for(i=i.child;i!==null;){var r=i;U0(r),r.tag===5&&r.flags&1024&&r.stateNode.reset(),i=i.sibling}}function va(i,r){if(r.subtreeFlags&8772)for(r=r.child;r!==null;)O0(i,r.alternate,r),r=r.sibling}function bl(i){for(i=i.child;i!==null;){var r=i;switch(r.tag){case 0:case 11:case 14:case 15:ao(4,r,r.return),bl(r);break;case 1:As(r,r.return);var a=r.stateNode;typeof a.componentWillUnmount=="function"&&D0(r,r.return,a),bl(r);break;case 27:Qu(r.stateNode);case 26:case 5:As(r,r.return),bl(r);break;case 22:r.memoizedState===null&&bl(r);break;case 30:bl(r);break;default:bl(r)}i=i.sibling}}function _a(i,r,a){for(a=a&&(r.subtreeFlags&8772)!==0,r=r.child;r!==null;){var c=r.alternate,h=i,g=r,y=g.flags;switch(g.tag){case 0:case 11:case 15:_a(h,g,a),$u(4,g);break;case 1:if(_a(h,g,a),c=g,h=c.stateNode,typeof h.componentDidMount=="function")try{h.componentDidMount()}catch(ue){Jt(c,c.return,ue)}if(c=g,h=c.updateQueue,h!==null){var D=c.stateNode;try{var $=h.shared.hiddenCallbacks;if($!==null)for(h.shared.hiddenCallbacks=null,h=0;h<$.length;h++)_S($[h],D)}catch(ue){Jt(c,c.return,ue)}}a&&y&64&&N0(g),Fu(g,g.return);break;case 27:L0(g);case 26:case 5:_a(h,g,a),a&&c===null&&y&4&&M0(g),Fu(g,g.return);break;case 12:_a(h,g,a);break;case 31:_a(h,g,a),a&&y&4&&P0(h,g);break;case 13:_a(h,g,a),a&&y&4&&z0(h,g);break;case 22:g.memoizedState===null&&_a(h,g,a),Fu(g,g.return);break;case 30:break;default:_a(h,g,a)}r=r.sibling}}function og(i,r){var a=null;i!==null&&i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(a=i.memoizedState.cachePool.pool),i=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(i=r.memoizedState.cachePool.pool),i!==a&&(i!=null&&i.refCount++,a!=null&&Nu(a))}function lg(i,r){i=null,r.alternate!==null&&(i=r.alternate.memoizedState.cache),r=r.memoizedState.cache,r!==i&&(r.refCount++,i!=null&&Nu(i))}function us(i,r,a,c){if(r.subtreeFlags&10256)for(r=r.child;r!==null;)$0(i,r,a,c),r=r.sibling}function $0(i,r,a,c){var h=r.flags;switch(r.tag){case 0:case 11:case 15:us(i,r,a,c),h&2048&&$u(9,r);break;case 1:us(i,r,a,c);break;case 3:us(i,r,a,c),h&2048&&(i=null,r.alternate!==null&&(i=r.alternate.memoizedState.cache),r=r.memoizedState.cache,r!==i&&(r.refCount++,i!=null&&Nu(i)));break;case 12:if(h&2048){us(i,r,a,c),i=r.stateNode;try{var g=r.memoizedProps,y=g.id,D=g.onPostCommit;typeof D=="function"&&D(y,r.alternate===null?"mount":"update",i.passiveEffectDuration,-0)}catch($){Jt(r,r.return,$)}}else us(i,r,a,c);break;case 31:us(i,r,a,c);break;case 13:us(i,r,a,c);break;case 23:break;case 22:g=r.stateNode,y=r.alternate,r.memoizedState!==null?g._visibility&2?us(i,r,a,c):Wu(i,r):g._visibility&2?us(i,r,a,c):(g._visibility|=2,bc(i,r,a,c,(r.subtreeFlags&10256)!==0||!1)),h&2048&&og(y,r);break;case 24:us(i,r,a,c),h&2048&&lg(r.alternate,r);break;default:us(i,r,a,c)}}function bc(i,r,a,c,h){for(h=h&&((r.subtreeFlags&10256)!==0||!1),r=r.child;r!==null;){var g=i,y=r,D=a,$=c,ue=y.flags;switch(y.tag){case 0:case 11:case 15:bc(g,y,D,$,h),$u(8,y);break;case 23:break;case 22:var Se=y.stateNode;y.memoizedState!==null?Se._visibility&2?bc(g,y,D,$,h):Wu(g,y):(Se._visibility|=2,bc(g,y,D,$,h)),h&&ue&2048&&og(y.alternate,y);break;case 24:bc(g,y,D,$,h),h&&ue&2048&&lg(y.alternate,y);break;default:bc(g,y,D,$,h)}r=r.sibling}}function Wu(i,r){if(r.subtreeFlags&10256)for(r=r.child;r!==null;){var a=i,c=r,h=c.flags;switch(c.tag){case 22:Wu(a,c),h&2048&&og(c.alternate,c);break;case 24:Wu(a,c),h&2048&&lg(c.alternate,c);break;default:Wu(a,c)}r=r.sibling}}var Ku=8192;function yc(i,r,a){if(i.subtreeFlags&Ku)for(i=i.child;i!==null;)F0(i,r,a),i=i.sibling}function F0(i,r,a){switch(i.tag){case 26:yc(i,r,a),i.flags&Ku&&i.memoizedState!==null&&oN(a,cs,i.memoizedState,i.memoizedProps);break;case 5:yc(i,r,a);break;case 3:case 4:var c=cs;cs=cf(i.stateNode.containerInfo),yc(i,r,a),cs=c;break;case 22:i.memoizedState===null&&(c=i.alternate,c!==null&&c.memoizedState!==null?(c=Ku,Ku=16777216,yc(i,r,a),Ku=c):yc(i,r,a));break;default:yc(i,r,a)}}function W0(i){var r=i.alternate;if(r!==null&&(i=r.child,i!==null)){r.child=null;do r=i.sibling,i.sibling=null,i=r;while(i!==null)}}function qu(i){var r=i.deletions;if((i.flags&16)!==0){if(r!==null)for(var a=0;a<r.length;a++){var c=r[a];mi=c,q0(c,i)}W0(i)}if(i.subtreeFlags&10256)for(i=i.child;i!==null;)K0(i),i=i.sibling}function K0(i){switch(i.tag){case 0:case 11:case 15:qu(i),i.flags&2048&&ao(9,i,i.return);break;case 3:qu(i);break;case 12:qu(i);break;case 22:var r=i.stateNode;i.memoizedState!==null&&r._visibility&2&&(i.return===null||i.return.tag!==13)?(r._visibility&=-3,Gh(i)):qu(i);break;default:qu(i)}}function Gh(i){var r=i.deletions;if((i.flags&16)!==0){if(r!==null)for(var a=0;a<r.length;a++){var c=r[a];mi=c,q0(c,i)}W0(i)}for(i=i.child;i!==null;){switch(r=i,r.tag){case 0:case 11:case 15:ao(8,r,r.return),Gh(r);break;case 22:a=r.stateNode,a._visibility&2&&(a._visibility&=-3,Gh(r));break;default:Gh(r)}i=i.sibling}}function q0(i,r){for(;mi!==null;){var a=mi;switch(a.tag){case 0:case 11:case 15:ao(8,a,r);break;case 23:case 22:if(a.memoizedState!==null&&a.memoizedState.cachePool!==null){var c=a.memoizedState.cachePool.pool;c!=null&&c.refCount++}break;case 24:Nu(a.memoizedState.cache)}if(c=a.child,c!==null)c.return=a,mi=c;else e:for(a=i;mi!==null;){c=mi;var h=c.sibling,g=c.return;if(B0(c),c===a){mi=null;break e}if(h!==null){h.return=g,mi=h;break e}mi=g}}}var wR={getCacheForType:function(i){var r=Yn(Xn),a=r.data.get(i);return a===void 0&&(a=i(),r.data.set(i,a)),a},cacheSignal:function(){return Yn(Xn).controller.signal}},xR=typeof WeakMap=="function"?WeakMap:Map,Yt=0,fn=null,jt=null,It=0,Qt=0,xr=null,oo=!1,Sc=!1,cg=!1,ba=0,Ln=0,lo=0,yl=0,ug=0,Cr=0,wc=0,Vu=null,or=null,dg=!1,Xh=0,V0=0,Zh=1/0,Qh=null,co=null,si=0,uo=null,xc=null,ya=0,hg=0,fg=null,Y0=null,Yu=0,pg=null;function kr(){return(Yt&2)!==0&&It!==0?It&-It:M.T!==null?yg():Tt()}function G0(){if(Cr===0)if((It&536870912)===0||Et){var i=ae;ae<<=1,(ae&3932160)===0&&(ae=262144),Cr=i}else Cr=536870912;return i=Sr.current,i!==null&&(i.flags|=32),Cr}function lr(i,r,a){(i===fn&&(Qt===2||Qt===9)||i.cancelPendingCommit!==null)&&(Cc(i,0),ho(i,It,Cr,!1)),Bn(i,a),((Yt&2)===0||i!==fn)&&(i===fn&&((Yt&2)===0&&(yl|=a),Ln===4&&ho(i,It,Cr,!1)),Ls(i))}function X0(i,r,a){if((Yt&6)!==0)throw Error(s(327));var c=!a&&(r&127)===0&&(r&i.expiredLanes)===0||$t(i,r),h=c?TR(i,r):gg(i,r,!0),g=c;do{if(h===0){Sc&&!c&&ho(i,r,0,!1);break}else{if(a=i.current.alternate,g&&!CR(a)){h=gg(i,r,!1),g=!1;continue}if(h===2){if(g=r,i.errorRecoveryDisabledLanes&g)var y=0;else y=i.pendingLanes&-536870913,y=y!==0?y:y&536870912?536870912:0;if(y!==0){r=y;e:{var D=i;h=Vu;var $=D.current.memoizedState.isDehydrated;if($&&(Cc(D,y).flags|=256),y=gg(D,y,!1),y!==2){if(cg&&!$){D.errorRecoveryDisabledLanes|=g,yl|=g,h=4;break e}g=or,or=h,g!==null&&(or===null?or=g:or.push.apply(or,g))}h=y}if(g=!1,h!==2)continue}}if(h===1){Cc(i,0),ho(i,r,0,!0);break}e:{switch(c=i,g=h,g){case 0:case 1:throw Error(s(345));case 4:if((r&4194048)!==r)break;case 6:ho(c,r,Cr,!oo);break e;case 2:or=null;break;case 3:case 5:break;default:throw Error(s(329))}if((r&62914560)===r&&(h=Xh+300-qe(),10<h)){if(ho(c,r,Cr,!oo),_t(c,0,!0)!==0)break e;ya=r,c.timeoutHandle=Ew(Z0.bind(null,c,a,or,Qh,dg,r,Cr,yl,wc,oo,g,"Throttled",-0,0),h);break e}Z0(c,a,or,Qh,dg,r,Cr,yl,wc,oo,g,null,-0,0)}}break}while(!0);Ls(i)}function Z0(i,r,a,c,h,g,y,D,$,ue,Se,Re,pe,_e){if(i.timeoutHandle=-1,Re=r.subtreeFlags,Re&8192||(Re&16785408)===16785408){Re={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Mi},F0(r,g,Re);var Qe=(g&62914560)===g?Xh-qe():(g&4194048)===g?V0-qe():0;if(Qe=lN(Re,Qe),Qe!==null){ya=g,i.cancelPendingCommit=Qe(sw.bind(null,i,r,g,a,c,h,y,D,$,Se,Re,null,pe,_e)),ho(i,g,y,!ue);return}}sw(i,r,g,a,c,h,y,D,$)}function CR(i){for(var r=i;;){var a=r.tag;if((a===0||a===11||a===15)&&r.flags&16384&&(a=r.updateQueue,a!==null&&(a=a.stores,a!==null)))for(var c=0;c<a.length;c++){var h=a[c],g=h.getSnapshot;h=h.value;try{if(!Li(g(),h))return!1}catch{return!1}}if(a=r.child,r.subtreeFlags&16384&&a!==null)a.return=r,r=a;else{if(r===i)break;for(;r.sibling===null;){if(r.return===null||r.return===i)return!0;r=r.return}r.sibling.return=r.return,r=r.sibling}}return!0}function ho(i,r,a,c){r&=~ug,r&=~yl,i.suspendedLanes|=r,i.pingedLanes&=~r,c&&(i.warmLanes|=r),c=i.expirationTimes;for(var h=r;0<h;){var g=31-Mt(h),y=1<<g;c[g]=-1,h&=~y}a!==0&&ln(i,a,r)}function Jh(){return(Yt&6)===0?(Gu(0),!1):!0}function mg(){if(jt!==null){if(Qt===0)var i=jt.return;else i=jt,nt=Lt=null,Mm(i),pc=null,Mu=0,i=jt;for(;i!==null;)R0(i.alternate,i),i=i.return;jt=null}}function Cc(i,r){var a=i.timeoutHandle;a!==-1&&(i.timeoutHandle=-1,WR(a)),a=i.cancelPendingCommit,a!==null&&(i.cancelPendingCommit=null,a()),ya=0,mg(),fn=i,jt=a=Hr(i.current,null),It=r,Qt=0,xr=null,oo=!1,Sc=$t(i,r),cg=!1,wc=Cr=ug=yl=lo=Ln=0,or=Vu=null,dg=!1,(r&8)!==0&&(r|=r&32);var c=i.entangledLanes;if(c!==0)for(i=i.entanglements,c&=r;0<c;){var h=31-Mt(c),g=1<<h;r|=i[h],c&=~g}return ba=r,ll(),a}function Q0(i,r){wt=null,M.H=zu,r===fc||r===Rh?(r=pS(),Qt=3):r===bm?(r=pS(),Qt=4):Qt=r===Vm?8:r!==null&&typeof r=="object"&&typeof r.then=="function"?6:1,xr=r,jt===null&&(Ln=1,$h(i,zn(r,i.current)))}function J0(){var i=Sr.current;return i===null?!0:(It&4194048)===It?Fr===null:(It&62914560)===It||(It&536870912)!==0?i===Fr:!1}function ew(){var i=M.H;return M.H=zu,i===null?zu:i}function tw(){var i=M.A;return M.A=wR,i}function ef(){Ln=4,oo||(It&4194048)!==It&&Sr.current!==null||(Sc=!0),(lo&134217727)===0&&(yl&134217727)===0||fn===null||ho(fn,It,Cr,!1)}function gg(i,r,a){var c=Yt;Yt|=2;var h=ew(),g=tw();(fn!==i||It!==r)&&(Qh=null,Cc(i,r)),r=!1;var y=Ln;e:do try{if(Qt!==0&&jt!==null){var D=jt,$=xr;switch(Qt){case 8:mg(),y=6;break e;case 3:case 2:case 9:case 6:Sr.current===null&&(r=!0);var ue=Qt;if(Qt=0,xr=null,kc(i,D,$,ue),a&&Sc){y=0;break e}break;default:ue=Qt,Qt=0,xr=null,kc(i,D,$,ue)}}kR(),y=Ln;break}catch(Se){Q0(i,Se)}while(!0);return r&&i.shellSuspendCounter++,nt=Lt=null,Yt=c,M.H=h,M.A=g,jt===null&&(fn=null,It=0,ll()),y}function kR(){for(;jt!==null;)nw(jt)}function TR(i,r){var a=Yt;Yt|=2;var c=ew(),h=tw();fn!==i||It!==r?(Qh=null,Zh=qe()+500,Cc(i,r)):Sc=$t(i,r);e:do try{if(Qt!==0&&jt!==null){r=jt;var g=xr;t:switch(Qt){case 1:Qt=0,xr=null,kc(i,r,g,1);break;case 2:case 9:if(hS(g)){Qt=0,xr=null,iw(r);break}r=function(){Qt!==2&&Qt!==9||fn!==i||(Qt=7),Ls(i)},g.then(r,r);break e;case 3:Qt=7;break e;case 4:Qt=5;break e;case 7:hS(g)?(Qt=0,xr=null,iw(r)):(Qt=0,xr=null,kc(i,r,g,7));break;case 5:var y=null;switch(jt.tag){case 26:y=jt.memoizedState;case 5:case 27:var D=jt;if(y?$w(y):D.stateNode.complete){Qt=0,xr=null;var $=D.sibling;if($!==null)jt=$;else{var ue=D.return;ue!==null?(jt=ue,tf(ue)):jt=null}break t}}Qt=0,xr=null,kc(i,r,g,5);break;case 6:Qt=0,xr=null,kc(i,r,g,6);break;case 8:mg(),Ln=6;break e;default:throw Error(s(462))}}ER();break}catch(Se){Q0(i,Se)}while(!0);return nt=Lt=null,M.H=c,M.A=h,Yt=a,jt!==null?0:(fn=null,It=0,ll(),Ln)}function ER(){for(;jt!==null&&!be();)nw(jt)}function nw(i){var r=T0(i.alternate,i,ba);i.memoizedProps=i.pendingProps,r===null?tf(i):jt=r}function iw(i){var r=i,a=r.alternate;switch(r.tag){case 15:case 0:r=y0(a,r,r.pendingProps,r.type,void 0,It);break;case 11:r=y0(a,r,r.pendingProps,r.type.render,r.ref,It);break;case 5:Mm(r);default:R0(a,r),r=jt=xu(r,ba),r=T0(a,r,ba)}i.memoizedProps=i.pendingProps,r===null?tf(i):jt=r}function kc(i,r,a,c){nt=Lt=null,Mm(r),pc=null,Mu=0;var h=r.return;try{if(mR(i,h,r,a,It)){Ln=1,$h(i,zn(a,i.current)),jt=null;return}}catch(g){if(h!==null)throw jt=h,g;Ln=1,$h(i,zn(a,i.current)),jt=null;return}r.flags&32768?(Et||c===1?i=!0:Sc||(It&536870912)!==0?i=!1:(oo=i=!0,(c===2||c===9||c===3||c===6)&&(c=Sr.current,c!==null&&c.tag===13&&(c.flags|=16384))),rw(r,i)):tf(r)}function tf(i){var r=i;do{if((r.flags&32768)!==0){rw(r,oo);return}i=r.return;var a=_R(r.alternate,r,ba);if(a!==null){jt=a;return}if(r=r.sibling,r!==null){jt=r;return}jt=r=i}while(r!==null);Ln===0&&(Ln=5)}function rw(i,r){do{var a=bR(i.alternate,i);if(a!==null){a.flags&=32767,jt=a;return}if(a=i.return,a!==null&&(a.flags|=32768,a.subtreeFlags=0,a.deletions=null),!r&&(i=i.sibling,i!==null)){jt=i;return}jt=i=a}while(i!==null);Ln=6,jt=null}function sw(i,r,a,c,h,g,y,D,$){i.cancelPendingCommit=null;do nf();while(si!==0);if((Yt&6)!==0)throw Error(s(327));if(r!==null){if(r===i.current)throw Error(s(177));if(g=r.lanes|r.childLanes,g|=Rs,Ct(i,a,g,y,D,$),i===fn&&(jt=fn=null,It=0),xc=r,uo=i,ya=a,hg=g,fg=h,Y0=c,(r.subtreeFlags&10256)!==0||(r.flags&10256)!==0?(i.callbackNode=null,i.callbackPriority=0,MR(mt,function(){return uw(),null})):(i.callbackNode=null,i.callbackPriority=0),c=(r.flags&13878)!==0,(r.subtreeFlags&13878)!==0||c){c=M.T,M.T=null,h=T.p,T.p=2,y=Yt,Yt|=4;try{yR(i,r,a)}finally{Yt=y,T.p=h,M.T=c}}si=1,aw(),ow(),lw()}}function aw(){if(si===1){si=0;var i=uo,r=xc,a=(r.flags&13878)!==0;if((r.subtreeFlags&13878)!==0||a){a=M.T,M.T=null;var c=T.p;T.p=2;var h=Yt;Yt|=4;try{H0(r,i);var g=Rg,y=fu(i.containerInfo),D=g.focusedElem,$=g.selectionRange;if(y!==D&&D&&D.ownerDocument&&hu(D.ownerDocument.documentElement,D)){if($!==null&&sc(D)){var ue=$.start,Se=$.end;if(Se===void 0&&(Se=ue),"selectionStart"in D)D.selectionStart=ue,D.selectionEnd=Math.min(Se,D.value.length);else{var Re=D.ownerDocument||document,pe=Re&&Re.defaultView||window;if(pe.getSelection){var _e=pe.getSelection(),Qe=D.textContent.length,dt=Math.min($.start,Qe),sn=$.end===void 0?dt:Math.min($.end,Qe);!_e.extend&&dt>sn&&(y=sn,sn=dt,dt=y);var ne=Sh(D,dt),G=Sh(D,sn);if(ne&&G&&(_e.rangeCount!==1||_e.anchorNode!==ne.node||_e.anchorOffset!==ne.offset||_e.focusNode!==G.node||_e.focusOffset!==G.offset)){var ce=Re.createRange();ce.setStart(ne.node,ne.offset),_e.removeAllRanges(),dt>sn?(_e.addRange(ce),_e.extend(G.node,G.offset)):(ce.setEnd(G.node,G.offset),_e.addRange(ce))}}}}for(Re=[],_e=D;_e=_e.parentNode;)_e.nodeType===1&&Re.push({element:_e,left:_e.scrollLeft,top:_e.scrollTop});for(typeof D.focus=="function"&&D.focus(),D=0;D<Re.length;D++){var Ce=Re[D];Ce.element.scrollLeft=Ce.left,Ce.element.scrollTop=Ce.top}}mf=!!Eg,Rg=Eg=null}finally{Yt=h,T.p=c,M.T=a}}i.current=r,si=2}}function ow(){if(si===2){si=0;var i=uo,r=xc,a=(r.flags&8772)!==0;if((r.subtreeFlags&8772)!==0||a){a=M.T,M.T=null;var c=T.p;T.p=2;var h=Yt;Yt|=4;try{O0(i,r.alternate,r)}finally{Yt=h,T.p=c,M.T=a}}si=3}}function lw(){if(si===4||si===3){si=0,$e();var i=uo,r=xc,a=ya,c=Y0;(r.subtreeFlags&10256)!==0||(r.flags&10256)!==0?si=5:(si=0,xc=uo=null,cw(i,i.pendingLanes));var h=i.pendingLanes;if(h===0&&(co=null),rt(a),r=r.stateNode,ft&&typeof ft.onCommitFiberRoot=="function")try{ft.onCommitFiberRoot(Tn,r,void 0,(r.current.flags&128)===128)}catch{}if(c!==null){r=M.T,h=T.p,T.p=2,M.T=null;try{for(var g=i.onRecoverableError,y=0;y<c.length;y++){var D=c[y];g(D.value,{componentStack:D.stack})}}finally{M.T=r,T.p=h}}(ya&3)!==0&&nf(),Ls(i),h=i.pendingLanes,(a&261930)!==0&&(h&42)!==0?i===pg?Yu++:(Yu=0,pg=i):Yu=0,Gu(0)}}function cw(i,r){(i.pooledCacheLanes&=r)===0&&(r=i.pooledCache,r!=null&&(i.pooledCache=null,Nu(r)))}function nf(){return aw(),ow(),lw(),uw()}function uw(){if(si!==5)return!1;var i=uo,r=hg;hg=0;var a=rt(ya),c=M.T,h=T.p;try{T.p=32>a?32:a,M.T=null,a=fg,fg=null;var g=uo,y=ya;if(si=0,xc=uo=null,ya=0,(Yt&6)!==0)throw Error(s(331));var D=Yt;if(Yt|=4,K0(g.current),$0(g,g.current,y,a),Yt=D,Gu(0,!1),ft&&typeof ft.onPostCommitFiberRoot=="function")try{ft.onPostCommitFiberRoot(Tn,g)}catch{}return!0}finally{T.p=h,M.T=c,cw(i,r)}}function dw(i,r,a){r=zn(a,r),r=qm(i.stateNode,r,2),i=io(i,r,2),i!==null&&(Bn(i,2),Ls(i))}function Jt(i,r,a){if(i.tag===3)dw(i,i,a);else for(;r!==null;){if(r.tag===3){dw(r,i,a);break}else if(r.tag===1){var c=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof c.componentDidCatch=="function"&&(co===null||!co.has(c))){i=zn(a,i),a=h0(2),c=io(r,a,2),c!==null&&(f0(a,c,r,i),Bn(c,2),Ls(c));break}}r=r.return}}function vg(i,r,a){var c=i.pingCache;if(c===null){c=i.pingCache=new xR;var h=new Set;c.set(r,h)}else h=c.get(r),h===void 0&&(h=new Set,c.set(r,h));h.has(a)||(cg=!0,h.add(a),i=RR.bind(null,i,r,a),r.then(i,i))}function RR(i,r,a){var c=i.pingCache;c!==null&&c.delete(r),i.pingedLanes|=i.suspendedLanes&a,i.warmLanes&=~a,fn===i&&(It&a)===a&&(Ln===4||Ln===3&&(It&62914560)===It&&300>qe()-Xh?(Yt&2)===0&&Cc(i,0):ug|=a,wc===It&&(wc=0)),Ls(i)}function hw(i,r){r===0&&(r=Ft()),i=Ns(i,r),i!==null&&(Bn(i,r),Ls(i))}function NR(i){var r=i.memoizedState,a=0;r!==null&&(a=r.retryLane),hw(i,a)}function DR(i,r){var a=0;switch(i.tag){case 31:case 13:var c=i.stateNode,h=i.memoizedState;h!==null&&(a=h.retryLane);break;case 19:c=i.stateNode;break;case 22:c=i.stateNode._retryCache;break;default:throw Error(s(314))}c!==null&&c.delete(r),hw(i,a)}function MR(i,r){return Ne(i,r)}var rf=null,Tc=null,_g=!1,sf=!1,bg=!1,fo=0;function Ls(i){i!==Tc&&i.next===null&&(Tc===null?rf=Tc=i:Tc=Tc.next=i),sf=!0,_g||(_g=!0,LR())}function Gu(i,r){if(!bg&&sf){bg=!0;do for(var a=!1,c=rf;c!==null;){if(i!==0){var h=c.pendingLanes;if(h===0)var g=0;else{var y=c.suspendedLanes,D=c.pingedLanes;g=(1<<31-Mt(42|i)+1)-1,g&=h&~(y&~D),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(a=!0,gw(c,g))}else g=It,g=_t(c,c===fn?g:0,c.cancelPendingCommit!==null||c.timeoutHandle!==-1),(g&3)===0||$t(c,g)||(a=!0,gw(c,g));c=c.next}while(a);bg=!1}}function AR(){fw()}function fw(){sf=_g=!1;var i=0;fo!==0&&FR()&&(i=fo);for(var r=qe(),a=null,c=rf;c!==null;){var h=c.next,g=pw(c,r);g===0?(c.next=null,a===null?rf=h:a.next=h,h===null&&(Tc=a)):(a=c,(i!==0||(g&3)!==0)&&(sf=!0)),c=h}si!==0&&si!==5||Gu(i),fo!==0&&(fo=0)}function pw(i,r){for(var a=i.suspendedLanes,c=i.pingedLanes,h=i.expirationTimes,g=i.pendingLanes&-62914561;0<g;){var y=31-Mt(g),D=1<<y,$=h[y];$===-1?((D&a)===0||(D&c)!==0)&&(h[y]=en(D,r)):$<=r&&(i.expiredLanes|=D),g&=~D}if(r=fn,a=It,a=_t(i,i===r?a:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),c=i.callbackNode,a===0||i===r&&(Qt===2||Qt===9)||i.cancelPendingCommit!==null)return c!==null&&c!==null&&Le(c),i.callbackNode=null,i.callbackPriority=0;if((a&3)===0||$t(i,a)){if(r=a&-a,r===i.callbackPriority)return r;switch(c!==null&&Le(c),rt(a)){case 2:case 8:a=st;break;case 32:a=mt;break;case 268435456:a=on;break;default:a=mt}return c=mw.bind(null,i),a=Ne(a,c),i.callbackPriority=r,i.callbackNode=a,r}return c!==null&&c!==null&&Le(c),i.callbackPriority=2,i.callbackNode=null,2}function mw(i,r){if(si!==0&&si!==5)return i.callbackNode=null,i.callbackPriority=0,null;var a=i.callbackNode;if(nf()&&i.callbackNode!==a)return null;var c=It;return c=_t(i,i===fn?c:0,i.cancelPendingCommit!==null||i.timeoutHandle!==-1),c===0?null:(X0(i,c,r),pw(i,qe()),i.callbackNode!=null&&i.callbackNode===a?mw.bind(null,i):null)}function gw(i,r){if(nf())return null;X0(i,r,!0)}function LR(){KR(function(){(Yt&6)!==0?Ne(ht,AR):fw()})}function yg(){if(fo===0){var i=dc;i===0&&(i=At,At<<=1,(At&261888)===0&&(At=256)),fo=i}return fo}function vw(i){return i==null||typeof i=="symbol"||typeof i=="boolean"?null:typeof i=="function"?i:ts(""+i)}function _w(i,r){var a=r.ownerDocument.createElement("input");return a.name=r.name,a.value=r.value,i.id&&a.setAttribute("form",i.id),r.parentNode.insertBefore(a,r),i=new FormData(i),a.parentNode.removeChild(a),i}function jR(i,r,a,c,h){if(r==="submit"&&a&&a.stateNode===h){var g=vw((h[Ge]||null).action),y=c.submitter;y&&(r=(r=y[Ge]||null)?vw(r.formAction):y.getAttribute("formAction"),r!==null&&(g=r,y=null));var D=new pt("action","action",null,c,h);i.push({event:D,listeners:[{instance:null,listener:function(){if(c.defaultPrevented){if(fo!==0){var $=y?_w(h,y):new FormData(h);Hm(a,{pending:!0,data:$,method:h.method,action:g},null,$)}}else typeof g=="function"&&(D.preventDefault(),$=y?_w(h,y):new FormData(h),Hm(a,{pending:!0,data:$,method:h.method,action:g},g,$))},currentTarget:h}]})}}for(var Sg=0;Sg<ac.length;Sg++){var wg=ac[Sg],OR=wg.toLowerCase(),BR=wg[0].toUpperCase()+wg.slice(1);br(OR,"on"+BR)}br(vu,"onAnimationEnd"),br(_u,"onAnimationIteration"),br(bu,"onAnimationStart"),br("dblclick","onDoubleClick"),br("focusin","onFocus"),br("focusout","onBlur"),br(yu,"onTransitionRun"),br(Su,"onTransitionStart"),br(mm,"onTransitionCancel"),br(al,"onTransitionEnd"),Ni("onMouseEnter",["mouseout","mouseover"]),Ni("onMouseLeave",["mouseout","mouseover"]),Ni("onPointerEnter",["pointerout","pointerover"]),Ni("onPointerLeave",["pointerout","pointerover"]),Qi("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Qi("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Qi("onBeforeInput",["compositionend","keypress","textInput","paste"]),Qi("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Qi("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Qi("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Xu="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),IR=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Xu));function bw(i,r){r=(r&4)!==0;for(var a=0;a<i.length;a++){var c=i[a],h=c.event;c=c.listeners;e:{var g=void 0;if(r)for(var y=c.length-1;0<=y;y--){var D=c[y],$=D.instance,ue=D.currentTarget;if(D=D.listener,$!==g&&h.isPropagationStopped())break e;g=D,h.currentTarget=ue;try{g(h)}catch(Se){Xa(Se)}h.currentTarget=null,g=$}else for(y=0;y<c.length;y++){if(D=c[y],$=D.instance,ue=D.currentTarget,D=D.listener,$!==g&&h.isPropagationStopped())break e;g=D,h.currentTarget=ue;try{g(h)}catch(Se){Xa(Se)}h.currentTarget=null,g=$}}}}function Ot(i,r){var a=r[Ze];a===void 0&&(a=r[Ze]=new Set);var c=i+"__bubble";a.has(c)||(yw(r,i,2,!1),a.add(c))}function xg(i,r,a){var c=0;r&&(c|=4),yw(a,i,c,r)}var af="_reactListening"+Math.random().toString(36).slice(2);function Cg(i){if(!i[af]){i[af]=!0,Ks.forEach(function(a){a!=="selectionchange"&&(IR.has(a)||xg(a,!1,i),xg(a,!0,i))});var r=i.nodeType===9?i:i.ownerDocument;r===null||r[af]||(r[af]=!0,xg("selectionchange",!1,r))}}function yw(i,r,a,c){switch(Gw(r)){case 2:var h=dN;break;case 8:h=hN;break;default:h=zg}a=h.bind(null,r,a,i),h=void 0,!Lr||r!=="touchstart"&&r!=="touchmove"&&r!=="wheel"||(h=!0),c?h!==void 0?i.addEventListener(r,a,{capture:!0,passive:h}):i.addEventListener(r,a,!0):h!==void 0?i.addEventListener(r,a,{passive:h}):i.addEventListener(r,a,!1)}function kg(i,r,a,c,h){var g=c;if((r&1)===0&&(r&2)===0&&c!==null)e:for(;;){if(c===null)return;var y=c.tag;if(y===3||y===4){var D=c.stateNode.containerInfo;if(D===h)break;if(y===4)for(y=c.return;y!==null;){var $=y.tag;if(($===3||$===4)&&y.stateNode.containerInfo===h)return;y=y.return}for(;D!==null;){if(y=qn(D),y===null)return;if($=y.tag,$===5||$===6||$===26||$===27){c=g=y;continue e}D=D.parentNode}}c=c.return}Ai(function(){var ue=g,Se=pn(a),Re=[];e:{var pe=ol.get(i);if(pe!==void 0){var _e=pt,Qe=i;switch(i){case"keypress":if(ys(a)===0)break e;case"keydown":case"keyup":_e=ec;break;case"focusin":Qe="focus",_e=ta;break;case"focusout":Qe="blur",_e=ta;break;case"beforeblur":case"afterblur":_e=ta;break;case"click":if(a.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":_e=Go;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":_e=Br;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":_e=Ir;break;case vu:case _u:case bu:_e=Jl;break;case al:_e=el;break;case"scroll":case"scrollend":_e=Ss;break;case"wheel":_e=qa;break;case"copy":case"cut":case"paste":_e=na;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":_e=Jo;break;case"toggle":case"beforetoggle":_e=Va}var dt=(r&4)!==0,sn=!dt&&(i==="scroll"||i==="scrollend"),ne=dt?pe!==null?pe+"Capture":null:pe;dt=[];for(var G=ue,ce;G!==null;){var Ce=G;if(ce=Ce.stateNode,Ce=Ce.tag,Ce!==5&&Ce!==26&&Ce!==27||ce===null||ne===null||(Ce=is(G,ne),Ce!=null&&dt.push(Zu(G,Ce,ce))),sn)break;G=G.return}0<dt.length&&(pe=new _e(pe,Qe,null,a,Se),Re.push({event:pe,listeners:dt}))}}if((r&7)===0){e:{if(pe=i==="mouseover"||i==="pointerover",_e=i==="mouseout"||i==="pointerout",pe&&a!==Dr&&(Qe=a.relatedTarget||a.fromElement)&&(qn(Qe)||Qe[Je]))break e;if((_e||pe)&&(pe=Se.window===Se?Se:(pe=Se.ownerDocument)?pe.defaultView||pe.parentWindow:window,_e?(Qe=a.relatedTarget||a.toElement,_e=ue,Qe=Qe?qn(Qe):null,Qe!==null&&(sn=l(Qe),dt=Qe.tag,Qe!==sn||dt!==5&&dt!==27&&dt!==6)&&(Qe=null)):(_e=null,Qe=ue),_e!==Qe)){if(dt=Go,Ce="onMouseLeave",ne="onMouseEnter",G="mouse",(i==="pointerout"||i==="pointerover")&&(dt=Jo,Ce="onPointerLeave",ne="onPointerEnter",G="pointer"),sn=_e==null?pe:Ri(_e),ce=Qe==null?pe:Ri(Qe),pe=new dt(Ce,G+"leave",_e,a,Se),pe.target=sn,pe.relatedTarget=ce,Ce=null,qn(Se)===ue&&(dt=new dt(ne,G+"enter",Qe,a,Se),dt.target=ce,dt.relatedTarget=sn,Ce=dt),sn=Ce,_e&&Qe)t:{for(dt=PR,ne=_e,G=Qe,ce=0,Ce=ne;Ce;Ce=dt(Ce))ce++;Ce=0;for(var lt=G;lt;lt=dt(lt))Ce++;for(;0<ce-Ce;)ne=dt(ne),ce--;for(;0<Ce-ce;)G=dt(G),Ce--;for(;ce--;){if(ne===G||G!==null&&ne===G.alternate){dt=ne;break t}ne=dt(ne),G=dt(G)}dt=null}else dt=null;_e!==null&&Sw(Re,pe,_e,dt,!1),Qe!==null&&sn!==null&&Sw(Re,sn,Qe,dt,!0)}}e:{if(pe=ue?Ri(ue):window,_e=pe.nodeName&&pe.nodeName.toLowerCase(),_e==="select"||_e==="input"&&pe.type==="file")var Kt=ic;else if(St(pe))if(nl)Kt=sl;else{Kt=bh;var it=rc}else _e=pe.nodeName,!_e||_e.toLowerCase()!=="input"||pe.type!=="checkbox"&&pe.type!=="radio"?ue&&Vo(ue.elementType)&&(Kt=ic):Kt=yh;if(Kt&&(Kt=Kt(i,ue))){Vt(Re,Kt,a,Se);break e}it&&it(i,pe,ue),i==="focusout"&&ue&&pe.type==="number"&&ue.memoizedProps.value!=null&&Xs(pe,"number",pe.value)}switch(it=ue?Ri(ue):window,i){case"focusin":(St(it)||it.contentEditable==="true")&&(sa=it,tr=ue,aa=null);break;case"focusout":aa=tr=sa=null;break;case"mousedown":pu=!0;break;case"contextmenu":case"mouseup":case"dragend":pu=!1,oa(Re,a,Se);break;case"selectionchange":if(pm)break;case"keydown":case"keyup":oa(Re,a,Se)}var kt;if(ra)e:{switch(i){case"compositionstart":var Pt="onCompositionStart";break e;case"compositionend":Pt="onCompositionEnd";break e;case"compositionupdate":Pt="onCompositionUpdate";break e}Pt=void 0}else we?ie(i,a)&&(Pt="onCompositionEnd"):i==="keydown"&&a.keyCode===229&&(Pt="onCompositionStart");Pt&&(E&&a.locale!=="ko"&&(we||Pt!=="onCompositionStart"?Pt==="onCompositionEnd"&&we&&(kt=Js()):(jr=Se,Qs="value"in jr?jr.value:jr.textContent,we=!0)),it=of(ue,Pt),0<it.length&&(Pt=new vr(Pt,i,null,a,Se),Re.push({event:Pt,listeners:it}),kt?Pt.data=kt:(kt=le(a),kt!==null&&(Pt.data=kt)))),(kt=C?Ue(i,a):Ye(i,a))&&(Pt=of(ue,"onBeforeInput"),0<Pt.length&&(it=new vr("onBeforeInput","beforeinput",null,a,Se),Re.push({event:it,listeners:Pt}),it.data=kt)),jR(Re,i,ue,a,Se)}bw(Re,r)})}function Zu(i,r,a){return{instance:i,listener:r,currentTarget:a}}function of(i,r){for(var a=r+"Capture",c=[];i!==null;){var h=i,g=h.stateNode;if(h=h.tag,h!==5&&h!==26&&h!==27||g===null||(h=is(i,a),h!=null&&c.unshift(Zu(i,h,g)),h=is(i,r),h!=null&&c.push(Zu(i,h,g))),i.tag===3)return c;i=i.return}return[]}function PR(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5&&i.tag!==27);return i||null}function Sw(i,r,a,c,h){for(var g=r._reactName,y=[];a!==null&&a!==c;){var D=a,$=D.alternate,ue=D.stateNode;if(D=D.tag,$!==null&&$===c)break;D!==5&&D!==26&&D!==27||ue===null||($=ue,h?(ue=is(a,g),ue!=null&&y.unshift(Zu(a,ue,$))):h||(ue=is(a,g),ue!=null&&y.push(Zu(a,ue,$)))),a=a.return}y.length!==0&&i.push({event:r,listeners:y})}var zR=/\r\n?/g,HR=/\u0000|\uFFFD/g;function ww(i){return(typeof i=="string"?i:""+i).replace(zR,`
10
+ `).replace(HR,"")}function xw(i,r){return r=ww(r),ww(i)===r}function rn(i,r,a,c,h,g){switch(a){case"children":typeof c=="string"?r==="body"||r==="textarea"&&c===""||_s(i,c):(typeof c=="number"||typeof c=="bigint")&&r!=="body"&&_s(i,""+c);break;case"className":Vs(i,"class",c);break;case"tabIndex":Vs(i,"tabindex",c);break;case"dir":case"role":case"viewBox":case"width":case"height":Vs(i,a,c);break;case"style":qo(i,c,g);break;case"data":if(r!=="object"){Vs(i,"data",c);break}case"src":case"href":if(c===""&&(r!=="a"||a!=="href")){i.removeAttribute(a);break}if(c==null||typeof c=="function"||typeof c=="symbol"||typeof c=="boolean"){i.removeAttribute(a);break}c=ts(""+c),i.setAttribute(a,c);break;case"action":case"formAction":if(typeof c=="function"){i.setAttribute(a,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof g=="function"&&(a==="formAction"?(r!=="input"&&rn(i,r,"name",h.name,h,null),rn(i,r,"formEncType",h.formEncType,h,null),rn(i,r,"formMethod",h.formMethod,h,null),rn(i,r,"formTarget",h.formTarget,h,null)):(rn(i,r,"encType",h.encType,h,null),rn(i,r,"method",h.method,h,null),rn(i,r,"target",h.target,h,null)));if(c==null||typeof c=="symbol"||typeof c=="boolean"){i.removeAttribute(a);break}c=ts(""+c),i.setAttribute(a,c);break;case"onClick":c!=null&&(i.onclick=Mi);break;case"onScroll":c!=null&&Ot("scroll",i);break;case"onScrollEnd":c!=null&&Ot("scrollend",i);break;case"dangerouslySetInnerHTML":if(c!=null){if(typeof c!="object"||!("__html"in c))throw Error(s(61));if(a=c.__html,a!=null){if(h.children!=null)throw Error(s(60));i.innerHTML=a}}break;case"multiple":i.multiple=c&&typeof c!="function"&&typeof c!="symbol";break;case"muted":i.muted=c&&typeof c!="function"&&typeof c!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(c==null||typeof c=="function"||typeof c=="boolean"||typeof c=="symbol"){i.removeAttribute("xlink:href");break}a=ts(""+c),i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",a);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":c!=null&&typeof c!="function"&&typeof c!="symbol"?i.setAttribute(a,""+c):i.removeAttribute(a);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":c&&typeof c!="function"&&typeof c!="symbol"?i.setAttribute(a,""):i.removeAttribute(a);break;case"capture":case"download":c===!0?i.setAttribute(a,""):c!==!1&&c!=null&&typeof c!="function"&&typeof c!="symbol"?i.setAttribute(a,c):i.removeAttribute(a);break;case"cols":case"rows":case"size":case"span":c!=null&&typeof c!="function"&&typeof c!="symbol"&&!isNaN(c)&&1<=c?i.setAttribute(a,c):i.removeAttribute(a);break;case"rowSpan":case"start":c==null||typeof c=="function"||typeof c=="symbol"||isNaN(c)?i.removeAttribute(a):i.setAttribute(a,c);break;case"popover":Ot("beforetoggle",i),Ot("toggle",i),zi(i,"popover",c);break;case"xlinkActuate":ni(i,"http://www.w3.org/1999/xlink","xlink:actuate",c);break;case"xlinkArcrole":ni(i,"http://www.w3.org/1999/xlink","xlink:arcrole",c);break;case"xlinkRole":ni(i,"http://www.w3.org/1999/xlink","xlink:role",c);break;case"xlinkShow":ni(i,"http://www.w3.org/1999/xlink","xlink:show",c);break;case"xlinkTitle":ni(i,"http://www.w3.org/1999/xlink","xlink:title",c);break;case"xlinkType":ni(i,"http://www.w3.org/1999/xlink","xlink:type",c);break;case"xmlBase":ni(i,"http://www.w3.org/XML/1998/namespace","xml:base",c);break;case"xmlLang":ni(i,"http://www.w3.org/XML/1998/namespace","xml:lang",c);break;case"xmlSpace":ni(i,"http://www.w3.org/XML/1998/namespace","xml:space",c);break;case"is":zi(i,"is",c);break;case"innerText":case"textContent":break;default:(!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(a=Hi.get(a)||a,zi(i,a,c))}}function Tg(i,r,a,c,h,g){switch(a){case"style":qo(i,c,g);break;case"dangerouslySetInnerHTML":if(c!=null){if(typeof c!="object"||!("__html"in c))throw Error(s(61));if(a=c.__html,a!=null){if(h.children!=null)throw Error(s(60));i.innerHTML=a}}break;case"children":typeof c=="string"?_s(i,c):(typeof c=="number"||typeof c=="bigint")&&_s(i,""+c);break;case"onScroll":c!=null&&Ot("scroll",i);break;case"onScrollEnd":c!=null&&Ot("scrollend",i);break;case"onClick":c!=null&&(i.onclick=Mi);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!dr.hasOwnProperty(a))e:{if(a[0]==="o"&&a[1]==="n"&&(h=a.endsWith("Capture"),r=a.slice(2,h?a.length-7:void 0),g=i[Ge]||null,g=g!=null?g[a]:null,typeof g=="function"&&i.removeEventListener(r,g,h),typeof c=="function")){typeof g!="function"&&g!==null&&(a in i?i[a]=null:i.hasAttribute(a)&&i.removeAttribute(a)),i.addEventListener(r,c,h);break e}a in i?i[a]=c:c===!0?i.setAttribute(a,""):zi(i,a,c)}}}function Ti(i,r,a){switch(r){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Ot("error",i),Ot("load",i);var c=!1,h=!1,g;for(g in a)if(a.hasOwnProperty(g)){var y=a[g];if(y!=null)switch(g){case"src":c=!0;break;case"srcSet":h=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(s(137,r));default:rn(i,r,g,y,a,null)}}h&&rn(i,r,"srcSet",a.srcSet,a,null),c&&rn(i,r,"src",a.src,a,null);return;case"input":Ot("invalid",i);var D=g=y=h=null,$=null,ue=null;for(c in a)if(a.hasOwnProperty(c)){var Se=a[c];if(Se!=null)switch(c){case"name":h=Se;break;case"type":y=Se;break;case"checked":$=Se;break;case"defaultChecked":ue=Se;break;case"value":g=Se;break;case"defaultValue":D=Se;break;case"children":case"dangerouslySetInnerHTML":if(Se!=null)throw Error(s(137,r));break;default:rn(i,r,c,Se,a,null)}}Ko(i,g,D,$,ue,y,h,!1);return;case"select":Ot("invalid",i),c=y=g=null;for(h in a)if(a.hasOwnProperty(h)&&(D=a[h],D!=null))switch(h){case"value":g=D;break;case"defaultValue":y=D;break;case"multiple":c=D;default:rn(i,r,h,D,a,null)}r=g,a=y,i.multiple=!!c,r!=null?hr(i,!!c,r,!1):a!=null&&hr(i,!!c,a,!0);return;case"textarea":Ot("invalid",i),g=h=c=null;for(y in a)if(a.hasOwnProperty(y)&&(D=a[y],D!=null))switch(y){case"value":c=D;break;case"defaultValue":h=D;break;case"children":g=D;break;case"dangerouslySetInnerHTML":if(D!=null)throw Error(s(91));break;default:rn(i,r,y,D,a,null)}Zs(i,c,h,g);return;case"option":for($ in a)a.hasOwnProperty($)&&(c=a[$],c!=null)&&($==="selected"?i.selected=c&&typeof c!="function"&&typeof c!="symbol":rn(i,r,$,c,a,null));return;case"dialog":Ot("beforetoggle",i),Ot("toggle",i),Ot("cancel",i),Ot("close",i);break;case"iframe":case"object":Ot("load",i);break;case"video":case"audio":for(c=0;c<Xu.length;c++)Ot(Xu[c],i);break;case"image":Ot("error",i),Ot("load",i);break;case"details":Ot("toggle",i);break;case"embed":case"source":case"link":Ot("error",i),Ot("load",i);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(ue in a)if(a.hasOwnProperty(ue)&&(c=a[ue],c!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":throw Error(s(137,r));default:rn(i,r,ue,c,a,null)}return;default:if(Vo(r)){for(Se in a)a.hasOwnProperty(Se)&&(c=a[Se],c!==void 0&&Tg(i,r,Se,c,a,void 0));return}}for(D in a)a.hasOwnProperty(D)&&(c=a[D],c!=null&&rn(i,r,D,c,a,null))}function UR(i,r,a,c){switch(r){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var h=null,g=null,y=null,D=null,$=null,ue=null,Se=null;for(_e in a){var Re=a[_e];if(a.hasOwnProperty(_e)&&Re!=null)switch(_e){case"checked":break;case"value":break;case"defaultValue":$=Re;default:c.hasOwnProperty(_e)||rn(i,r,_e,null,c,Re)}}for(var pe in c){var _e=c[pe];if(Re=a[pe],c.hasOwnProperty(pe)&&(_e!=null||Re!=null))switch(pe){case"type":g=_e;break;case"name":h=_e;break;case"checked":ue=_e;break;case"defaultChecked":Se=_e;break;case"value":y=_e;break;case"defaultValue":D=_e;break;case"children":case"dangerouslySetInnerHTML":if(_e!=null)throw Error(s(137,r));break;default:_e!==Re&&rn(i,r,pe,_e,c,Re)}}vs(i,y,D,$,ue,Se,g,h);return;case"select":_e=y=D=pe=null;for(g in a)if($=a[g],a.hasOwnProperty(g)&&$!=null)switch(g){case"value":break;case"multiple":_e=$;default:c.hasOwnProperty(g)||rn(i,r,g,null,c,$)}for(h in c)if(g=c[h],$=a[h],c.hasOwnProperty(h)&&(g!=null||$!=null))switch(h){case"value":pe=g;break;case"defaultValue":D=g;break;case"multiple":y=g;default:g!==$&&rn(i,r,h,g,c,$)}r=D,a=y,c=_e,pe!=null?hr(i,!!a,pe,!1):!!c!=!!a&&(r!=null?hr(i,!!a,r,!0):hr(i,!!a,a?[]:"",!1));return;case"textarea":_e=pe=null;for(D in a)if(h=a[D],a.hasOwnProperty(D)&&h!=null&&!c.hasOwnProperty(D))switch(D){case"value":break;case"children":break;default:rn(i,r,D,null,c,h)}for(y in c)if(h=c[y],g=a[y],c.hasOwnProperty(y)&&(h!=null||g!=null))switch(y){case"value":pe=h;break;case"defaultValue":_e=h;break;case"children":break;case"dangerouslySetInnerHTML":if(h!=null)throw Error(s(91));break;default:h!==g&&rn(i,r,y,h,c,g)}$a(i,pe,_e);return;case"option":for(var Qe in a)pe=a[Qe],a.hasOwnProperty(Qe)&&pe!=null&&!c.hasOwnProperty(Qe)&&(Qe==="selected"?i.selected=!1:rn(i,r,Qe,null,c,pe));for($ in c)pe=c[$],_e=a[$],c.hasOwnProperty($)&&pe!==_e&&(pe!=null||_e!=null)&&($==="selected"?i.selected=pe&&typeof pe!="function"&&typeof pe!="symbol":rn(i,r,$,pe,c,_e));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var dt in a)pe=a[dt],a.hasOwnProperty(dt)&&pe!=null&&!c.hasOwnProperty(dt)&&rn(i,r,dt,null,c,pe);for(ue in c)if(pe=c[ue],_e=a[ue],c.hasOwnProperty(ue)&&pe!==_e&&(pe!=null||_e!=null))switch(ue){case"children":case"dangerouslySetInnerHTML":if(pe!=null)throw Error(s(137,r));break;default:rn(i,r,ue,pe,c,_e)}return;default:if(Vo(r)){for(var sn in a)pe=a[sn],a.hasOwnProperty(sn)&&pe!==void 0&&!c.hasOwnProperty(sn)&&Tg(i,r,sn,void 0,c,pe);for(Se in c)pe=c[Se],_e=a[Se],!c.hasOwnProperty(Se)||pe===_e||pe===void 0&&_e===void 0||Tg(i,r,Se,pe,c,_e);return}}for(var ne in a)pe=a[ne],a.hasOwnProperty(ne)&&pe!=null&&!c.hasOwnProperty(ne)&&rn(i,r,ne,null,c,pe);for(Re in c)pe=c[Re],_e=a[Re],!c.hasOwnProperty(Re)||pe===_e||pe==null&&_e==null||rn(i,r,Re,pe,c,_e)}function Cw(i){switch(i){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function $R(){if(typeof performance.getEntriesByType=="function"){for(var i=0,r=0,a=performance.getEntriesByType("resource"),c=0;c<a.length;c++){var h=a[c],g=h.transferSize,y=h.initiatorType,D=h.duration;if(g&&D&&Cw(y)){for(y=0,D=h.responseEnd,c+=1;c<a.length;c++){var $=a[c],ue=$.startTime;if(ue>D)break;var Se=$.transferSize,Re=$.initiatorType;Se&&Cw(Re)&&($=$.responseEnd,y+=Se*($<D?1:(D-ue)/($-ue)))}if(--c,r+=8*(g+y)/(h.duration/1e3),i++,10<i)break}}if(0<i)return r/i/1e6}return navigator.connection&&(i=navigator.connection.downlink,typeof i=="number")?i:5}var Eg=null,Rg=null;function lf(i){return i.nodeType===9?i:i.ownerDocument}function kw(i){switch(i){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function Tw(i,r){if(i===0)switch(r){case"svg":return 1;case"math":return 2;default:return 0}return i===1&&r==="foreignObject"?0:i}function Ng(i,r){return i==="textarea"||i==="noscript"||typeof r.children=="string"||typeof r.children=="number"||typeof r.children=="bigint"||typeof r.dangerouslySetInnerHTML=="object"&&r.dangerouslySetInnerHTML!==null&&r.dangerouslySetInnerHTML.__html!=null}var Dg=null;function FR(){var i=window.event;return i&&i.type==="popstate"?i===Dg?!1:(Dg=i,!0):(Dg=null,!1)}var Ew=typeof setTimeout=="function"?setTimeout:void 0,WR=typeof clearTimeout=="function"?clearTimeout:void 0,Rw=typeof Promise=="function"?Promise:void 0,KR=typeof queueMicrotask=="function"?queueMicrotask:typeof Rw<"u"?function(i){return Rw.resolve(null).then(i).catch(qR)}:Ew;function qR(i){setTimeout(function(){throw i})}function po(i){return i==="head"}function Nw(i,r){var a=r,c=0;do{var h=a.nextSibling;if(i.removeChild(a),h&&h.nodeType===8)if(a=h.data,a==="/$"||a==="/&"){if(c===0){i.removeChild(h),Dc(r);return}c--}else if(a==="$"||a==="$?"||a==="$~"||a==="$!"||a==="&")c++;else if(a==="html")Qu(i.ownerDocument.documentElement);else if(a==="head"){a=i.ownerDocument.head,Qu(a);for(var g=a.firstChild;g;){var y=g.nextSibling,D=g.nodeName;g[Xt]||D==="SCRIPT"||D==="STYLE"||D==="LINK"&&g.rel.toLowerCase()==="stylesheet"||a.removeChild(g),g=y}}else a==="body"&&Qu(i.ownerDocument.body);a=h}while(a);Dc(r)}function Dw(i,r){var a=i;i=0;do{var c=a.nextSibling;if(a.nodeType===1?r?(a._stashedDisplay=a.style.display,a.style.display="none"):(a.style.display=a._stashedDisplay||"",a.getAttribute("style")===""&&a.removeAttribute("style")):a.nodeType===3&&(r?(a._stashedText=a.nodeValue,a.nodeValue=""):a.nodeValue=a._stashedText||""),c&&c.nodeType===8)if(a=c.data,a==="/$"){if(i===0)break;i--}else a!=="$"&&a!=="$?"&&a!=="$~"&&a!=="$!"||i++;a=c}while(a)}function Mg(i){var r=i.firstChild;for(r&&r.nodeType===10&&(r=r.nextSibling);r;){var a=r;switch(r=r.nextSibling,a.nodeName){case"HTML":case"HEAD":case"BODY":Mg(a),Xi(a);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(a.rel.toLowerCase()==="stylesheet")continue}i.removeChild(a)}}function VR(i,r,a,c){for(;i.nodeType===1;){var h=a;if(i.nodeName.toLowerCase()!==r.toLowerCase()){if(!c&&(i.nodeName!=="INPUT"||i.type!=="hidden"))break}else if(c){if(!i[Xt])switch(r){case"meta":if(!i.hasAttribute("itemprop"))break;return i;case"link":if(g=i.getAttribute("rel"),g==="stylesheet"&&i.hasAttribute("data-precedence"))break;if(g!==h.rel||i.getAttribute("href")!==(h.href==null||h.href===""?null:h.href)||i.getAttribute("crossorigin")!==(h.crossOrigin==null?null:h.crossOrigin)||i.getAttribute("title")!==(h.title==null?null:h.title))break;return i;case"style":if(i.hasAttribute("data-precedence"))break;return i;case"script":if(g=i.getAttribute("src"),(g!==(h.src==null?null:h.src)||i.getAttribute("type")!==(h.type==null?null:h.type)||i.getAttribute("crossorigin")!==(h.crossOrigin==null?null:h.crossOrigin))&&g&&i.hasAttribute("async")&&!i.hasAttribute("itemprop"))break;return i;default:return i}}else if(r==="input"&&i.type==="hidden"){var g=h.name==null?null:""+h.name;if(h.type==="hidden"&&i.getAttribute("name")===g)return i}else return i;if(i=Wr(i.nextSibling),i===null)break}return null}function YR(i,r,a){if(r==="")return null;for(;i.nodeType!==3;)if((i.nodeType!==1||i.nodeName!=="INPUT"||i.type!=="hidden")&&!a||(i=Wr(i.nextSibling),i===null))return null;return i}function Mw(i,r){for(;i.nodeType!==8;)if((i.nodeType!==1||i.nodeName!=="INPUT"||i.type!=="hidden")&&!r||(i=Wr(i.nextSibling),i===null))return null;return i}function Ag(i){return i.data==="$?"||i.data==="$~"}function Lg(i){return i.data==="$!"||i.data==="$?"&&i.ownerDocument.readyState!=="loading"}function GR(i,r){var a=i.ownerDocument;if(i.data==="$~")i._reactRetry=r;else if(i.data!=="$?"||a.readyState!=="loading")r();else{var c=function(){r(),a.removeEventListener("DOMContentLoaded",c)};a.addEventListener("DOMContentLoaded",c),i._reactRetry=c}}function Wr(i){for(;i!=null;i=i.nextSibling){var r=i.nodeType;if(r===1||r===3)break;if(r===8){if(r=i.data,r==="$"||r==="$!"||r==="$?"||r==="$~"||r==="&"||r==="F!"||r==="F")break;if(r==="/$"||r==="/&")return null}}return i}var jg=null;function Aw(i){i=i.nextSibling;for(var r=0;i;){if(i.nodeType===8){var a=i.data;if(a==="/$"||a==="/&"){if(r===0)return Wr(i.nextSibling);r--}else a!=="$"&&a!=="$!"&&a!=="$?"&&a!=="$~"&&a!=="&"||r++}i=i.nextSibling}return null}function Lw(i){i=i.previousSibling;for(var r=0;i;){if(i.nodeType===8){var a=i.data;if(a==="$"||a==="$!"||a==="$?"||a==="$~"||a==="&"){if(r===0)return i;r--}else a!=="/$"&&a!=="/&"||r++}i=i.previousSibling}return null}function jw(i,r,a){switch(r=lf(a),i){case"html":if(i=r.documentElement,!i)throw Error(s(452));return i;case"head":if(i=r.head,!i)throw Error(s(453));return i;case"body":if(i=r.body,!i)throw Error(s(454));return i;default:throw Error(s(451))}}function Qu(i){for(var r=i.attributes;r.length;)i.removeAttributeNode(r[0]);Xi(i)}var Kr=new Map,Ow=new Set;function cf(i){return typeof i.getRootNode=="function"?i.getRootNode():i.nodeType===9?i:i.ownerDocument}var Sa=T.d;T.d={f:XR,r:ZR,D:QR,C:JR,L:eN,m:tN,X:iN,S:nN,M:rN};function XR(){var i=Sa.f(),r=Jh();return i||r}function ZR(i){var r=Mn(i);r!==null&&r.tag===5&&r.type==="form"?QS(r):Sa.r(i)}var Ec=typeof document>"u"?null:document;function Bw(i,r,a){var c=Ec;if(c&&typeof r=="string"&&r){var h=ii(r);h='link[rel="'+i+'"][href="'+h+'"]',typeof a=="string"&&(h+='[crossorigin="'+a+'"]'),Ow.has(h)||(Ow.add(h),i={rel:i,crossOrigin:a,href:r},c.querySelector(h)===null&&(r=c.createElement("link"),Ti(r,"link",i),Wt(r),c.head.appendChild(r)))}}function QR(i){Sa.D(i),Bw("dns-prefetch",i,null)}function JR(i,r){Sa.C(i,r),Bw("preconnect",i,r)}function eN(i,r,a){Sa.L(i,r,a);var c=Ec;if(c&&i&&r){var h='link[rel="preload"][as="'+ii(r)+'"]';r==="image"&&a&&a.imageSrcSet?(h+='[imagesrcset="'+ii(a.imageSrcSet)+'"]',typeof a.imageSizes=="string"&&(h+='[imagesizes="'+ii(a.imageSizes)+'"]')):h+='[href="'+ii(i)+'"]';var g=h;switch(r){case"style":g=Rc(i);break;case"script":g=Nc(i)}Kr.has(g)||(i=_({rel:"preload",href:r==="image"&&a&&a.imageSrcSet?void 0:i,as:r},a),Kr.set(g,i),c.querySelector(h)!==null||r==="style"&&c.querySelector(Ju(g))||r==="script"&&c.querySelector(ed(g))||(r=c.createElement("link"),Ti(r,"link",i),Wt(r),c.head.appendChild(r)))}}function tN(i,r){Sa.m(i,r);var a=Ec;if(a&&i){var c=r&&typeof r.as=="string"?r.as:"script",h='link[rel="modulepreload"][as="'+ii(c)+'"][href="'+ii(i)+'"]',g=h;switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=Nc(i)}if(!Kr.has(g)&&(i=_({rel:"modulepreload",href:i},r),Kr.set(g,i),a.querySelector(h)===null)){switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(a.querySelector(ed(g)))return}c=a.createElement("link"),Ti(c,"link",i),Wt(c),a.head.appendChild(c)}}}function nN(i,r,a){Sa.S(i,r,a);var c=Ec;if(c&&i){var h=Zi(c).hoistableStyles,g=Rc(i);r=r||"default";var y=h.get(g);if(!y){var D={loading:0,preload:null};if(y=c.querySelector(Ju(g)))D.loading=5;else{i=_({rel:"stylesheet",href:i,"data-precedence":r},a),(a=Kr.get(g))&&Og(i,a);var $=y=c.createElement("link");Wt($),Ti($,"link",i),$._p=new Promise(function(ue,Se){$.onload=ue,$.onerror=Se}),$.addEventListener("load",function(){D.loading|=1}),$.addEventListener("error",function(){D.loading|=2}),D.loading|=4,uf(y,r,c)}y={type:"stylesheet",instance:y,count:1,state:D},h.set(g,y)}}}function iN(i,r){Sa.X(i,r);var a=Ec;if(a&&i){var c=Zi(a).hoistableScripts,h=Nc(i),g=c.get(h);g||(g=a.querySelector(ed(h)),g||(i=_({src:i,async:!0},r),(r=Kr.get(h))&&Bg(i,r),g=a.createElement("script"),Wt(g),Ti(g,"link",i),a.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},c.set(h,g))}}function rN(i,r){Sa.M(i,r);var a=Ec;if(a&&i){var c=Zi(a).hoistableScripts,h=Nc(i),g=c.get(h);g||(g=a.querySelector(ed(h)),g||(i=_({src:i,async:!0,type:"module"},r),(r=Kr.get(h))&&Bg(i,r),g=a.createElement("script"),Wt(g),Ti(g,"link",i),a.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},c.set(h,g))}}function Iw(i,r,a,c){var h=(h=ye.current)?cf(h):null;if(!h)throw Error(s(446));switch(i){case"meta":case"title":return null;case"style":return typeof a.precedence=="string"&&typeof a.href=="string"?(r=Rc(a.href),a=Zi(h).hoistableStyles,c=a.get(r),c||(c={type:"style",instance:null,count:0,state:null},a.set(r,c)),c):{type:"void",instance:null,count:0,state:null};case"link":if(a.rel==="stylesheet"&&typeof a.href=="string"&&typeof a.precedence=="string"){i=Rc(a.href);var g=Zi(h).hoistableStyles,y=g.get(i);if(y||(h=h.ownerDocument||h,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(i,y),(g=h.querySelector(Ju(i)))&&!g._p&&(y.instance=g,y.state.loading=5),Kr.has(i)||(a={rel:"preload",as:"style",href:a.href,crossOrigin:a.crossOrigin,integrity:a.integrity,media:a.media,hrefLang:a.hrefLang,referrerPolicy:a.referrerPolicy},Kr.set(i,a),g||sN(h,i,a,y.state))),r&&c===null)throw Error(s(528,""));return y}if(r&&c!==null)throw Error(s(529,""));return null;case"script":return r=a.async,a=a.src,typeof a=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Nc(a),a=Zi(h).hoistableScripts,c=a.get(r),c||(c={type:"script",instance:null,count:0,state:null},a.set(r,c)),c):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,i))}}function Rc(i){return'href="'+ii(i)+'"'}function Ju(i){return'link[rel="stylesheet"]['+i+"]"}function Pw(i){return _({},i,{"data-precedence":i.precedence,precedence:null})}function sN(i,r,a,c){i.querySelector('link[rel="preload"][as="style"]['+r+"]")?c.loading=1:(r=i.createElement("link"),c.preload=r,r.addEventListener("load",function(){return c.loading|=1}),r.addEventListener("error",function(){return c.loading|=2}),Ti(r,"link",a),Wt(r),i.head.appendChild(r))}function Nc(i){return'[src="'+ii(i)+'"]'}function ed(i){return"script[async]"+i}function zw(i,r,a){if(r.count++,r.instance===null)switch(r.type){case"style":var c=i.querySelector('style[data-href~="'+ii(a.href)+'"]');if(c)return r.instance=c,Wt(c),c;var h=_({},a,{"data-href":a.href,"data-precedence":a.precedence,href:null,precedence:null});return c=(i.ownerDocument||i).createElement("style"),Wt(c),Ti(c,"style",h),uf(c,a.precedence,i),r.instance=c;case"stylesheet":h=Rc(a.href);var g=i.querySelector(Ju(h));if(g)return r.state.loading|=4,r.instance=g,Wt(g),g;c=Pw(a),(h=Kr.get(h))&&Og(c,h),g=(i.ownerDocument||i).createElement("link"),Wt(g);var y=g;return y._p=new Promise(function(D,$){y.onload=D,y.onerror=$}),Ti(g,"link",c),r.state.loading|=4,uf(g,a.precedence,i),r.instance=g;case"script":return g=Nc(a.src),(h=i.querySelector(ed(g)))?(r.instance=h,Wt(h),h):(c=a,(h=Kr.get(g))&&(c=_({},a),Bg(c,h)),i=i.ownerDocument||i,h=i.createElement("script"),Wt(h),Ti(h,"link",c),i.head.appendChild(h),r.instance=h);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(c=r.instance,r.state.loading|=4,uf(c,a.precedence,i));return r.instance}function uf(i,r,a){for(var c=a.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=c.length?c[c.length-1]:null,g=h,y=0;y<c.length;y++){var D=c[y];if(D.dataset.precedence===r)g=D;else if(g!==h)break}g?g.parentNode.insertBefore(i,g.nextSibling):(r=a.nodeType===9?a.head:a,r.insertBefore(i,r.firstChild))}function Og(i,r){i.crossOrigin==null&&(i.crossOrigin=r.crossOrigin),i.referrerPolicy==null&&(i.referrerPolicy=r.referrerPolicy),i.title==null&&(i.title=r.title)}function Bg(i,r){i.crossOrigin==null&&(i.crossOrigin=r.crossOrigin),i.referrerPolicy==null&&(i.referrerPolicy=r.referrerPolicy),i.integrity==null&&(i.integrity=r.integrity)}var df=null;function Hw(i,r,a){if(df===null){var c=new Map,h=df=new Map;h.set(a,c)}else h=df,c=h.get(a),c||(c=new Map,h.set(a,c));if(c.has(i))return c;for(c.set(i,null),a=a.getElementsByTagName(i),h=0;h<a.length;h++){var g=a[h];if(!(g[Xt]||g[ke]||i==="link"&&g.getAttribute("rel")==="stylesheet")&&g.namespaceURI!=="http://www.w3.org/2000/svg"){var y=g.getAttribute(r)||"";y=i+y;var D=c.get(y);D?D.push(g):c.set(y,[g])}}return c}function Uw(i,r,a){i=i.ownerDocument||i,i.head.insertBefore(a,r==="title"?i.querySelector("head > title"):null)}function aN(i,r,a){if(a===1||r.itemProp!=null)return!1;switch(i){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;return r.rel==="stylesheet"?(i=r.disabled,typeof r.precedence=="string"&&i==null):!0;case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function $w(i){return!(i.type==="stylesheet"&&(i.state.loading&3)===0)}function oN(i,r,a,c){if(a.type==="stylesheet"&&(typeof c.media!="string"||matchMedia(c.media).matches!==!1)&&(a.state.loading&4)===0){if(a.instance===null){var h=Rc(c.href),g=r.querySelector(Ju(h));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(i.count++,i=hf.bind(i),r.then(i,i)),a.state.loading|=4,a.instance=g,Wt(g);return}g=r.ownerDocument||r,c=Pw(c),(h=Kr.get(h))&&Og(c,h),g=g.createElement("link"),Wt(g);var y=g;y._p=new Promise(function(D,$){y.onload=D,y.onerror=$}),Ti(g,"link",c),a.instance=g}i.stylesheets===null&&(i.stylesheets=new Map),i.stylesheets.set(a,r),(r=a.state.preload)&&(a.state.loading&3)===0&&(i.count++,a=hf.bind(i),r.addEventListener("load",a),r.addEventListener("error",a))}}var Ig=0;function lN(i,r){return i.stylesheets&&i.count===0&&pf(i,i.stylesheets),0<i.count||0<i.imgCount?function(a){var c=setTimeout(function(){if(i.stylesheets&&pf(i,i.stylesheets),i.unsuspend){var g=i.unsuspend;i.unsuspend=null,g()}},6e4+r);0<i.imgBytes&&Ig===0&&(Ig=62500*$R());var h=setTimeout(function(){if(i.waitingForImages=!1,i.count===0&&(i.stylesheets&&pf(i,i.stylesheets),i.unsuspend)){var g=i.unsuspend;i.unsuspend=null,g()}},(i.imgBytes>Ig?50:800)+r);return i.unsuspend=a,function(){i.unsuspend=null,clearTimeout(c),clearTimeout(h)}}:null}function hf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)pf(this,this.stylesheets);else if(this.unsuspend){var i=this.unsuspend;this.unsuspend=null,i()}}}var ff=null;function pf(i,r){i.stylesheets=null,i.unsuspend!==null&&(i.count++,ff=new Map,r.forEach(cN,i),ff=null,hf.call(i))}function cN(i,r){if(!(r.state.loading&4)){var a=ff.get(i);if(a)var c=a.get(null);else{a=new Map,ff.set(i,a);for(var h=i.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g<h.length;g++){var y=h[g];(y.nodeName==="LINK"||y.getAttribute("media")!=="not all")&&(a.set(y.dataset.precedence,y),c=y)}c&&a.set(null,c)}h=r.instance,y=h.getAttribute("data-precedence"),g=a.get(y)||c,g===c&&a.set(null,h),a.set(y,h),this.count++,c=hf.bind(this),h.addEventListener("load",c),h.addEventListener("error",c),g?g.parentNode.insertBefore(h,g.nextSibling):(i=i.nodeType===9?i.head:i,i.insertBefore(h,i.firstChild)),r.state.loading|=4}}var td={$$typeof:H,Provider:null,Consumer:null,_currentValue:O,_currentValue2:O,_threadCount:0};function uN(i,r,a,c,h,g,y,D,$){this.tag=1,this.containerInfo=i,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=mn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=mn(0),this.hiddenUpdates=mn(null),this.identifierPrefix=c,this.onUncaughtError=h,this.onCaughtError=g,this.onRecoverableError=y,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=$,this.incompleteTransitions=new Map}function Fw(i,r,a,c,h,g,y,D,$,ue,Se,Re){return i=new uN(i,r,a,y,$,ue,Se,Re,D),r=1,g===!0&&(r|=24),g=Ci(3,null,null,r),i.current=g,g.stateNode=i,r=gm(),r.refCount++,i.pooledCache=r,r.refCount++,g.memoizedState={element:c,isDehydrated:a,cache:r},ym(g),i}function Ww(i){return i?(i=Za,i):Za}function Kw(i,r,a,c,h,g){h=Ww(h),c.context===null?c.context=h:c.pendingContext=h,c=no(r),c.payload={element:a},g=g===void 0?null:g,g!==null&&(c.callback=g),a=io(i,c,r),a!==null&&(lr(a,i,r),Lu(a,i,r))}function qw(i,r){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var a=i.retryLane;i.retryLane=a!==0&&a<r?a:r}}function Pg(i,r){qw(i,r),(i=i.alternate)&&qw(i,r)}function Vw(i){if(i.tag===13||i.tag===31){var r=Ns(i,67108864);r!==null&&lr(r,i,67108864),Pg(i,67108864)}}function Yw(i){if(i.tag===13||i.tag===31){var r=kr();r=In(r);var a=Ns(i,r);a!==null&&lr(a,i,r),Pg(i,r)}}var mf=!0;function dN(i,r,a,c){var h=M.T;M.T=null;var g=T.p;try{T.p=2,zg(i,r,a,c)}finally{T.p=g,M.T=h}}function hN(i,r,a,c){var h=M.T;M.T=null;var g=T.p;try{T.p=8,zg(i,r,a,c)}finally{T.p=g,M.T=h}}function zg(i,r,a,c){if(mf){var h=Hg(c);if(h===null)kg(i,r,c,gf,a),Xw(i,c);else if(pN(h,i,r,a,c))c.stopPropagation();else if(Xw(i,c),r&4&&-1<fN.indexOf(i)){for(;h!==null;){var g=Mn(h);if(g!==null)switch(g.tag){case 3:if(g=g.stateNode,g.current.memoizedState.isDehydrated){var y=tt(g.pendingLanes);if(y!==0){var D=g;for(D.pendingLanes|=2,D.entangledLanes|=2;y;){var $=1<<31-Mt(y);D.entanglements[1]|=$,y&=~$}Ls(g),(Yt&6)===0&&(Zh=qe()+500,Gu(0))}}break;case 31:case 13:D=Ns(g,2),D!==null&&lr(D,g,2),Jh(),Pg(g,2)}if(g=Hg(c),g===null&&kg(i,r,c,gf,a),g===h)break;h=g}h!==null&&c.stopPropagation()}else kg(i,r,c,null,a)}}function Hg(i){return i=pn(i),Ug(i)}var gf=null;function Ug(i){if(gf=null,i=qn(i),i!==null){var r=l(i);if(r===null)i=null;else{var a=r.tag;if(a===13){if(i=d(r),i!==null)return i;i=null}else if(a===31){if(i=f(r),i!==null)return i;i=null}else if(a===3){if(r.stateNode.current.memoizedState.isDehydrated)return r.tag===3?r.stateNode.containerInfo:null;i=null}else r!==i&&(i=null)}}return gf=i,null}function Gw(i){switch(i){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(je()){case ht:return 2;case st:return 8;case mt:case xt:return 32;case on:return 268435456;default:return 32}default:return 32}}var $g=!1,mo=null,go=null,vo=null,nd=new Map,id=new Map,_o=[],fN="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function Xw(i,r){switch(i){case"focusin":case"focusout":mo=null;break;case"dragenter":case"dragleave":go=null;break;case"mouseover":case"mouseout":vo=null;break;case"pointerover":case"pointerout":nd.delete(r.pointerId);break;case"gotpointercapture":case"lostpointercapture":id.delete(r.pointerId)}}function rd(i,r,a,c,h,g){return i===null||i.nativeEvent!==g?(i={blockedOn:r,domEventName:a,eventSystemFlags:c,nativeEvent:g,targetContainers:[h]},r!==null&&(r=Mn(r),r!==null&&Vw(r)),i):(i.eventSystemFlags|=c,r=i.targetContainers,h!==null&&r.indexOf(h)===-1&&r.push(h),i)}function pN(i,r,a,c,h){switch(r){case"focusin":return mo=rd(mo,i,r,a,c,h),!0;case"dragenter":return go=rd(go,i,r,a,c,h),!0;case"mouseover":return vo=rd(vo,i,r,a,c,h),!0;case"pointerover":var g=h.pointerId;return nd.set(g,rd(nd.get(g)||null,i,r,a,c,h)),!0;case"gotpointercapture":return g=h.pointerId,id.set(g,rd(id.get(g)||null,i,r,a,c,h)),!0}return!1}function Zw(i){var r=qn(i.target);if(r!==null){var a=l(r);if(a!==null){if(r=a.tag,r===13){if(r=d(a),r!==null){i.blockedOn=r,gn(i.priority,function(){Yw(a)});return}}else if(r===31){if(r=f(a),r!==null){i.blockedOn=r,gn(i.priority,function(){Yw(a)});return}}else if(r===3&&a.stateNode.current.memoizedState.isDehydrated){i.blockedOn=a.tag===3?a.stateNode.containerInfo:null;return}}}i.blockedOn=null}function vf(i){if(i.blockedOn!==null)return!1;for(var r=i.targetContainers;0<r.length;){var a=Hg(i.nativeEvent);if(a===null){a=i.nativeEvent;var c=new a.constructor(a.type,a);Dr=c,a.target.dispatchEvent(c),Dr=null}else return r=Mn(a),r!==null&&Vw(r),i.blockedOn=a,!1;r.shift()}return!0}function Qw(i,r,a){vf(i)&&a.delete(r)}function mN(){$g=!1,mo!==null&&vf(mo)&&(mo=null),go!==null&&vf(go)&&(go=null),vo!==null&&vf(vo)&&(vo=null),nd.forEach(Qw),id.forEach(Qw)}function _f(i,r){i.blockedOn===r&&(i.blockedOn=null,$g||($g=!0,e.unstable_scheduleCallback(e.unstable_NormalPriority,mN)))}var bf=null;function Jw(i){bf!==i&&(bf=i,e.unstable_scheduleCallback(e.unstable_NormalPriority,function(){bf===i&&(bf=null);for(var r=0;r<i.length;r+=3){var a=i[r],c=i[r+1],h=i[r+2];if(typeof c!="function"){if(Ug(c||a)===null)continue;break}var g=Mn(a);g!==null&&(i.splice(r,3),r-=3,Hm(g,{pending:!0,data:h,method:a.method,action:c},c,h))}}))}function Dc(i){function r($){return _f($,i)}mo!==null&&_f(mo,i),go!==null&&_f(go,i),vo!==null&&_f(vo,i),nd.forEach(r),id.forEach(r);for(var a=0;a<_o.length;a++){var c=_o[a];c.blockedOn===i&&(c.blockedOn=null)}for(;0<_o.length&&(a=_o[0],a.blockedOn===null);)Zw(a),a.blockedOn===null&&_o.shift();if(a=(i.ownerDocument||i).$$reactFormReplay,a!=null)for(c=0;c<a.length;c+=3){var h=a[c],g=a[c+1],y=h[Ge]||null;if(typeof g=="function")y||Jw(a);else if(y){var D=null;if(g&&g.hasAttribute("formAction")){if(h=g,y=g[Ge]||null)D=y.formAction;else if(Ug(h)!==null)continue}else D=y.action;typeof D=="function"?a[c+1]=D:(a.splice(c,3),c-=3),Jw(a)}}}function e1(){function i(g){g.canIntercept&&g.info==="react-transition"&&g.intercept({handler:function(){return new Promise(function(y){return h=y})},focusReset:"manual",scroll:"manual"})}function r(){h!==null&&(h(),h=null),c||setTimeout(a,20)}function a(){if(!c&&!navigation.transition){var g=navigation.currentEntry;g&&g.url!=null&&navigation.navigate(g.url,{state:g.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var c=!1,h=null;return navigation.addEventListener("navigate",i),navigation.addEventListener("navigatesuccess",r),navigation.addEventListener("navigateerror",r),setTimeout(a,100),function(){c=!0,navigation.removeEventListener("navigate",i),navigation.removeEventListener("navigatesuccess",r),navigation.removeEventListener("navigateerror",r),h!==null&&(h(),h=null)}}}function Fg(i){this._internalRoot=i}yf.prototype.render=Fg.prototype.render=function(i){var r=this._internalRoot;if(r===null)throw Error(s(409));var a=r.current,c=kr();Kw(a,c,i,r,null,null)},yf.prototype.unmount=Fg.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var r=i.containerInfo;Kw(i.current,2,null,i,null,null),Jh(),r[Je]=null}};function yf(i){this._internalRoot=i}yf.prototype.unstable_scheduleHydration=function(i){if(i){var r=Tt();i={blockedOn:null,target:i,priority:r};for(var a=0;a<_o.length&&r!==0&&r<_o[a].priority;a++);_o.splice(a,0,i),a===0&&Zw(i)}};var t1=t.version;if(t1!=="19.2.6")throw Error(s(527,t1,"19.2.6"));T.findDOMNode=function(i){var r=i._reactInternals;if(r===void 0)throw typeof i.render=="function"?Error(s(188)):(i=Object.keys(i).join(","),Error(s(268,i)));return i=p(r),i=i!==null?b(i):null,i=i===null?null:i.stateNode,i};var gN={bundleType:0,version:"19.2.6",rendererPackageName:"react-dom",currentDispatcherRef:M,reconcilerVersion:"19.2.6"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Sf=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Sf.isDisabled&&Sf.supportsFiber)try{Tn=Sf.inject(gN),ft=Sf}catch{}}return ad.createRoot=function(i,r){if(!o(i))throw Error(s(299));var a=!1,c="",h=l0,g=c0,y=u0;return r!=null&&(r.unstable_strictMode===!0&&(a=!0),r.identifierPrefix!==void 0&&(c=r.identifierPrefix),r.onUncaughtError!==void 0&&(h=r.onUncaughtError),r.onCaughtError!==void 0&&(g=r.onCaughtError),r.onRecoverableError!==void 0&&(y=r.onRecoverableError)),r=Fw(i,1,!1,null,null,a,c,null,h,g,y,e1),i[Je]=r.current,Cg(i),new Fg(r)},ad.hydrateRoot=function(i,r,a){if(!o(i))throw Error(s(299));var c=!1,h="",g=l0,y=c0,D=u0,$=null;return a!=null&&(a.unstable_strictMode===!0&&(c=!0),a.identifierPrefix!==void 0&&(h=a.identifierPrefix),a.onUncaughtError!==void 0&&(g=a.onUncaughtError),a.onCaughtError!==void 0&&(y=a.onCaughtError),a.onRecoverableError!==void 0&&(D=a.onRecoverableError),a.formState!==void 0&&($=a.formState)),r=Fw(i,1,!0,r,a??null,c,h,$,g,y,D,e1),r.context=Ww(null),a=r.current,c=kr(),c=In(c),h=no(c),h.callback=null,io(a,h,c),a=c,r.current.lanes=a,Bn(r,a),Ls(r),i[Je]=r.current,Cg(i),new yf(r)},ad.version="19.2.6",ad}var d1;function TN(){if(d1)return qg.exports;d1=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(),qg.exports=kN(),qg.exports}var EN=TN();class Sl extends Error{constructor(t,n){super(n),this.status=t,this.name="UploadClientError"}status}function ZC(e){const t=e.createXhr?.()??new XMLHttpRequest,n=new FormData,s=e.files.map((o,l)=>({fieldName:`file${l}`,relativePath:o.relativePath,size:o.file.size}));n.append("manifest",JSON.stringify({terminalId:e.terminalId,entries:s}));for(const[o,l]of e.files.entries())n.append(`file${o}`,l.file);return new Promise((o,l)=>{let d=!1;const f=()=>{e.signal?.removeEventListener("abort",b)},m=_=>{d||(d=!0,f(),o(_))},p=_=>{d||(d=!0,f(),l(_))},b=()=>{t.abort(),p(new Sl(0,"Upload aborted."))};if(e.signal?.aborted){p(new Sl(0,"Upload aborted."));return}e.signal?.addEventListener("abort",b,{once:!0}),t.open("POST",e.endpoint??"/api/uploads"),t.withCredentials=!0,t.upload.onprogress=_=>{if(e.onProgress){if(_.lengthComputable&&_.total>0){e.onProgress({loaded:_.loaded,total:_.total,percent:Math.round(_.loaded/_.total*100)});return}e.onProgress({loaded:_.loaded,total:null,percent:null})}},t.onload=()=>{if(t.status>=200&&t.status<300){try{m(JSON.parse(t.responseText))}catch{p(new Sl(t.status,"Invalid upload response."))}return}p(new Sl(t.status,RN(t.responseText,t.statusText||`HTTP ${t.status}`)))},t.onerror=()=>p(new Sl(0,"Upload failed.")),t.onabort=()=>p(new Sl(0,"Upload aborted.")),t.ontimeout=()=>p(new Sl(0,"Upload timed out.")),t.send(n)})}function RN(e,t){try{const n=JSON.parse(e),s=typeof n.error=="string"?n.error:n.message;if(typeof s=="string"&&s.trim())return s}catch{}return t}class Wn extends Error{constructor(t,n){super(n),this.status=t,this.name="ApiError"}status}function Hp(e=fetch){return{getSession:(t={})=>Me(e,`/api/auth/session${Ps(t)}`),setupPassword:t=>Me(e,"/api/auth/password",at("POST",t)),login:t=>Me(e,"/api/auth/login",at("POST",t)),reauth:t=>Me(e,"/api/auth/reauth",at("POST",t)),logout:()=>Me(e,"/api/auth/logout",{method:"POST",credentials:"same-origin"}),sendClientDiagnostics:t=>Me(e,"/api/client-diagnostics",at("POST",t)),setupTotp:()=>Me(e,"/api/auth/totp/setup",{method:"POST",credentials:"same-origin"}),activateTotp:t=>Me(e,"/api/auth/totp/activate",at("POST",t)),disableTotp:()=>Me(e,"/api/auth/totp",{method:"DELETE",credentials:"same-origin"}),listDevices:()=>Me(e,"/api/auth/devices"),revokeDevice:async t=>{await jc(e,`/api/auth/devices/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"})},listNetworks:()=>Me(e,"/api/auth/networks"),addNetwork:t=>Me(e,"/api/auth/networks",at("POST",t)),removeNetwork:async t=>{await jc(e,`/api/auth/networks/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"})},listAgents:()=>Me(e,"/api/agents"),addAgent:t=>Me(e,"/api/agents",at("POST",t)),reorderAgents:t=>Me(e,"/api/agents/order",at("PUT",{serverIds:t})),renameAgent:(t,n)=>Me(e,`/api/agents/${encodeURIComponent(t)}`,at("PATCH",{name:n})),getMainInfo:()=>Me(e,"/api/main"),renameMain:t=>Me(e,"/api/main",at("PATCH",{name:t})),removeAgent:async t=>{await jc(e,`/api/agents/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"})},uninstallAgent:t=>Me(e,`/api/agents/${encodeURIComponent(t)}/uninstall`,{method:"POST",credentials:"same-origin"}),pingAgent:t=>Me(e,`/api/agents/${encodeURIComponent(t)}/ping`),getMainStats:()=>Me(e,"/api/stats"),getAgentStats:t=>Me(e,`/api/agents/${encodeURIComponent(t)}/stats`),getVersion:()=>Me(e,"/api/version"),checkUpdate:()=>Me(e,"/api/update/check",{method:"POST",credentials:"same-origin"}),runUpdate:()=>Me(e,"/api/update",{method:"POST",credentials:"same-origin"}),getAgentVersion:t=>Me(e,`/api/agents/${encodeURIComponent(t)}/version`),checkAgentUpdate:t=>Me(e,`/api/agents/${encodeURIComponent(t)}/update/check`,{method:"POST",credentials:"same-origin"}),runAgentUpdate:t=>Me(e,`/api/agents/${encodeURIComponent(t)}/update`,{method:"POST",credentials:"same-origin"}),getCodeServerStatus:(t={})=>Me(e,`/api/code-server/status${Ps(t)}`),installCodeServer:()=>Me(e,"/api/code-server/install",{method:"POST",credentials:"same-origin"}),updateCodeServer:()=>Me(e,"/api/code-server/update",{method:"POST",credentials:"same-origin"}),openCodeServer:t=>Me(e,"/api/code-server/open",at("POST",t)),stopCodeServer:(t={})=>Me(e,"/api/code-server/stop",at("POST",t)),uninstallCodeServer:()=>Me(e,"/api/code-server/uninstall",{method:"POST",credentials:"same-origin"}),getFavorites:()=>Me(e,"/api/favorites"),saveFavorites:t=>Me(e,"/api/favorites",at("PUT",t)),listTerminals:()=>Me(e,"/api/terminals"),getTerminalLayout:()=>Me(e,"/api/terminal-layout"),saveTerminalLayout:t=>Me(e,"/api/terminal-layout",at("PUT",t)),createFileRoot:t=>Me(e,"/api/files/root",at("POST",t)),listFiles:t=>Me(e,"/api/files/list",at("POST",t)),readFile:t=>Me(e,"/api/files/read",at("POST",t)),writeFile:t=>Me(e,"/api/files/write",at("POST",t)),createFileEntry:t=>Me(e,"/api/files/create",at("POST",t)),moveFileEntry:t=>Me(e,"/api/files/move",at("POST",t)),previewDeleteFileEntry:t=>Me(e,"/api/files/delete-preview",at("POST",t)),deleteFileEntry:t=>Me(e,"/api/files/delete",at("POST",t)),openFileInTerminal:t=>Me(e,"/api/files/open",at("POST",t)),previewFile:t=>QC(e,"/api/files/preview",at("POST",t)),createTerminal:(t={})=>Me(e,"/api/terminals",at("POST",t)),closeTerminal:async t=>{await jc(e,`/api/terminals/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"})},renameTerminal:(t,n)=>Me(e,`/api/terminals/${encodeURIComponent(t)}`,at("PATCH",{title:n})),getTerminalHistory:(t,n={})=>Me(e,`/api/terminals/${encodeURIComponent(t)}/history${Ps(n)}`),getTerminalTranscriptHistory:(t,n={},s)=>Me(e,`/api/terminals/${encodeURIComponent(t)}/transcript-history${Ps(n)}`,s?{signal:s}:void 0),searchTerminalTranscript:(t,n,s)=>Me(e,`/api/terminals/${encodeURIComponent(t)}/transcript-search`,{...at("POST",n),...s?{signal:s}:{}}),getTerminalTranscriptSource:t=>Me(e,`/api/terminals/${encodeURIComponent(t)}/transcript-source`),getTerminalSubagents:t=>Me(e,`/api/terminals/${encodeURIComponent(t)}/subagents`),getTerminalSubagentTranscriptHistory:(t,n,s={})=>Me(e,`/api/terminals/${encodeURIComponent(t)}/subagents/${encodeURIComponent(n)}/transcript-history${Ps(s)}`),listNotificationAssets:()=>Me(e,"/api/notification-assets"),uploadNotificationAsset:t=>{const n=new FormData;return n.append("asset",t),Me(e,"/api/notification-assets",{method:"POST",credentials:"same-origin",body:n})},updateNotificationAssetSelection:t=>Me(e,"/api/notification-assets/selection",at("PUT",t)),deleteNotificationAsset:async t=>{await jc(e,`/api/notification-assets/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"})},getPushNotificationStatus:(t,n)=>Me(e,`/api/push-notifications/status${t||n?Ps({...t!==void 0?{clientId:t}:{},...n!==void 0?{endpointHash:n}:{}}):""}`),preparePushNotifications:t=>Me(e,"/api/push-notifications/prepare",at("POST",{clientId:t})),subscribePushNotifications:t=>Me(e,"/api/push-notifications/subscription",at("POST",t)),updatePushNotificationDevice:t=>Me(e,"/api/push-notifications/device",at("PATCH",t)),unsubscribePushNotifications:t=>Me(e,"/api/push-notifications/unsubscribe",at("POST",t)),updatePushPresence:t=>Me(e,"/api/push-notifications/presence",at("POST",t)),testPushNotification:t=>Me(e,"/api/push-notifications/test",at("POST",t))}}function Is(e,t=fetch){const n=s=>e?`/api/agents/${encodeURIComponent(e)}/${s}`:`/api/${s}`;return{transcriptCacheScope:e?`agent:${e}`:"local",isAgent:e!==null,listTerminals:()=>Me(t,n("terminals")),createTerminal:(s={})=>Me(t,n("terminals"),at("POST",s)),closeTerminal:async s=>{await jc(t,n(`terminals/${encodeURIComponent(s)}`),{method:"DELETE",credentials:"same-origin"})},renameTerminal:(s,o)=>Me(t,n(`terminals/${encodeURIComponent(s)}`),at("PATCH",{title:o})),getTerminalHistory:(s,o={})=>Me(t,`${n(`terminals/${encodeURIComponent(s)}/history`)}${Ps(o)}`),getTerminalTranscriptHistory:(s,o={},l)=>Me(t,`${n(`terminals/${encodeURIComponent(s)}/transcript-history`)}${Ps(o)}`,l?{signal:l}:void 0),searchTerminalTranscript:(s,o,l)=>Me(t,n(`terminals/${encodeURIComponent(s)}/transcript-search`),{...at("POST",o),...l?{signal:l}:{}}),getTerminalTranscriptSource:s=>Me(t,n(`terminals/${encodeURIComponent(s)}/transcript-source`)),getTerminalSubagents:s=>Me(t,n(`terminals/${encodeURIComponent(s)}/subagents`)),getTerminalSubagentTranscriptHistory:(s,o,l={})=>Me(t,`${n(`terminals/${encodeURIComponent(s)}/subagents/${encodeURIComponent(o)}/transcript-history`)}${Ps(l)}`),getTerminalLayout:()=>Me(t,n("terminal-layout")),saveTerminalLayout:s=>Me(t,n("terminal-layout"),at("PUT",s)),createFileRoot:s=>Me(t,n("files/root"),at("POST",s)),listFiles:s=>Me(t,n("files/list"),at("POST",s)),readFile:s=>Me(t,n("files/read"),at("POST",s)),writeFile:s=>Me(t,n("files/write"),at("POST",s)),createFileEntry:s=>Me(t,n("files/create"),at("POST",s)),moveFileEntry:s=>Me(t,n("files/move"),at("POST",s)),previewDeleteFileEntry:s=>Me(t,n("files/delete-preview"),at("POST",s)),deleteFileEntry:s=>Me(t,n("files/delete"),at("POST",s)),openFileInTerminal:s=>Me(t,n("files/open"),at("POST",s)),previewFile:s=>QC(t,n("files/preview"),at("POST",s)),uploadComposeAttachments:s=>ZC({...s,endpoint:n("attachments")}),getComposeAttachmentLimits:s=>Me(t,n("attachments/limits"),s?{credentials:"same-origin",signal:s}:void 0),deleteComposeAttachments:s=>Me(t,n("attachments/delete"),at("POST",s)),getCodeServerStatus:(s={})=>Me(t,`${n("code-server/status")}${Ps(s)}`),installCodeServer:()=>Me(t,n("code-server/install"),{method:"POST",credentials:"same-origin"}),updateCodeServer:()=>Me(t,n("code-server/update"),{method:"POST",credentials:"same-origin"}),openCodeServer:s=>Me(t,n("code-server/open"),at("POST",s)),stopCodeServer:(s={})=>Me(t,n("code-server/stop"),at("POST",s)),uninstallCodeServer:()=>Me(t,n("code-server/uninstall"),{method:"POST",credentials:"same-origin"}),getProviderHooks:s=>Me(t,n(`hooks/${s}`)),installProviderHooks:s=>Me(t,n(`hooks/${s}/install`),{method:"POST",credentials:"same-origin"}),removeProviderHooks:s=>Me(t,n(`hooks/${s}/remove`),{method:"POST",credentials:"same-origin"}),checkProviderHookTrust:s=>Me(t,n(`hooks/${s}/trust`)),trustProviderHooks:s=>Me(t,n(`hooks/${s}/trust`),{method:"POST",credentials:"same-origin"}),getAccounts:()=>Me(t,n("accounts")),getAccountUsage:s=>Me(t,n(`accounts/${s}/usage`),{method:"POST",credentials:"same-origin"}),getServerProcesses:()=>Me(t,n("server-info/processes")),renameServerProject:(s,o)=>Me(t,n("server-info/project-name"),at("POST",{path:s,name:o})),getServerExternalIp:(s=!1)=>Me(t,n("server-info/external-ip")+(s?"?refresh=1":"")),selectAccount:(s,o)=>Me(t,n(`accounts/${s}/select`),at("POST",{profileId:o})),renameAccount:(s,o,l)=>Me(t,n(`accounts/${s}/rename`),at("POST",{profileId:o,label:l})),removeAccount:(s,o)=>Me(t,n(`accounts/${s}/${encodeURIComponent(o)}`),{method:"DELETE",credentials:"same-origin"}),beginAccountLogin:s=>Me(t,n(`accounts/${s}/login`),{method:"POST",credentials:"same-origin"}),submitAccountLoginCode:(s,o)=>Me(t,n(`accounts/${s}/login/code`),at("POST",{code:o})),completeAccountLogin:(s,o)=>Me(t,n(`accounts/${s}/login/complete`),at("POST",{label:o})),cancelAccountLogin:s=>Me(t,n(`accounts/${s}/login/cancel`),{method:"POST",credentials:"same-origin"}),refreshAccount:(s,o)=>Me(t,n(`accounts/${s}/refresh`),at("POST",o?{profileId:o}:{})),terminateProviderSessions:s=>Me(t,n(`accounts/${s}/terminate`),{method:"POST",credentials:"same-origin"}),createWebSocketUrl:(s,o=window.location.href)=>NN(n(`terminals/${encodeURIComponent(s)}/ws`),o)}}function NN(e,t){const n=new URL(t);return n.protocol=n.protocol==="https:"?"wss:":"ws:",n.pathname=e,n.search="",n.hash="",n.toString()}function at(e,t){return{method:e,headers:{"content-type":"application/json"},credentials:"same-origin",body:JSON.stringify(t)}}function Ps(e){const t=new URLSearchParams;e.beforeLine!==void 0&&t.set("beforeLine",String(e.beforeLine)),e.snapshotHistorySize!==void 0&&t.set("snapshotHistorySize",String(e.snapshotHistorySize)),e.snapshotHistoryLimit!==void 0&&t.set("snapshotHistoryLimit",String(e.snapshotHistoryLimit)),e.snapshotHistoryToken!==void 0&&t.set("snapshotHistoryToken",e.snapshotHistoryToken),e.snapshotPaneWidth!==void 0&&t.set("snapshotPaneWidth",String(e.snapshotPaneWidth)),e.cursor!==void 0&&t.set("cursor",e.cursor),e.ifSnapshot!==void 0&&t.set("ifSnapshot",e.ifSnapshot),e.limit!==void 0&&t.set("limit",String(e.limit)),e.maxLines!==void 0&&t.set("maxLines",String(e.maxLines)),e.includeTools!==void 0&&t.set("includeTools",e.includeTools?"true":"false"),e.candidateId!==void 0&&t.set("candidateId",e.candidateId),e.expectedSessionId!==void 0&&t.set("expectedSessionId",e.expectedSessionId),e.around!==void 0&&t.set("around",e.around),e.invalidationSource!==void 0&&t.set("invalidationSource",e.invalidationSource),e.clientId!==void 0&&t.set("clientId",e.clientId),e.endpointHash!==void 0&&t.set("endpointHash",e.endpointHash),e.checkLatest!==void 0&&t.set("checkLatest",e.checkLatest?"true":"false");const n=t.toString();return n?`?${n}`:""}async function Me(e,t,n){const s=await e(t,n??{credentials:"same-origin"});await Qb(s);try{return await s.json()}catch{throw new Wn(s.status,"invalid_json_response")}}async function jc(e,t,n){const s=await e(t,n);await Qb(s)}async function QC(e,t,n){const s=await e(t,n);return await Qb(s),s.blob()}async function Qb(e){if(e.ok)return;let t=e.statusText||`HTTP ${e.status}`;try{const n=await e.json(),s=typeof n.error=="string"?n.error:n.message;typeof s=="string"&&s.trim()&&(t=s)}catch{}throw new Wn(e.status,t)}const Jb="nterminal.theme.id",JC="nterminal.theme.accent",Xv="nterminal:theme",rp=[{id:"midnight",label:"Midnight",description:"Current dark terminal look with aqua focus.",mode:"dark",tokens:{bg:"#0a0d10",bg2:"#0d1216",bgSidebar:"#08090b",line:"#1a2128",line2:"#2a3340",fg:"#e2e8ee",fg2:"#8896a3",fg3:"#54616d",fg4:"#3f4a54",accent:"#5eead4",accentSoft:"rgba(94, 234, 212, 0.10)",accentGlow:"rgba(94, 234, 212, 0.55)",onAccent:"#062423",ok:"#34d399",working:"#4ade80",unread:"#60a5fa",onUnread:"#06152f",danger:"#f87171",onDanger:"#190607",dangerSoft:"rgba(248, 113, 113, 0.08)",dangerLine:"rgba(248, 113, 113, 0.30)",warning:"#fbbf24",warningSoft:"rgba(247, 217, 119, 0.075)",warningGlow:"rgba(245, 158, 11, 0.55)",scrim:"rgba(0, 0, 0, 0.55)",scrimSoft:"rgba(0, 0, 0, 0.28)",shadow:"rgba(0, 0, 0, 0.35)",shadowStrong:"rgba(0, 0, 0, 0.50)",floatingBg:"rgba(10, 13, 16, 0.86)",floatingBgStrong:"rgba(10, 13, 16, 0.96)",floatingBgHover:"rgba(15, 23, 27, 0.94)",subtleFill:"rgba(255, 255, 255, 0.018)",hoverFill:"rgba(255, 255, 255, 0.015)",scrollbarThumb:"rgba(148, 163, 184, 0.50)",scrollbarThumbHover:"rgba(148, 163, 184, 0.70)",transcriptUser:"#f7d977",transcriptAssistant:"#5eead4",transcriptTool:"#9aa7b4",transcriptCommand:"#8fd6ff",transcriptCode:"#c4f1ff",transcriptSearch:"#f7d977",transcriptOnSearch:"#121417",qrBg:"#ffffff"},xterm:{background:"#0a0d10",foreground:"#e2e8ee",cursor:"#5eead4",selectionBackground:"#1f3f45"}},{id:"daylight",label:"Daylight",description:"Light workspace with dark terminal contrast.",mode:"light",tokens:{bg:"#f7f9fc",bg2:"#ffffff",bgSidebar:"#eef2f7",line:"#dbe3ec",line2:"#c3cedb",fg:"#17212b",fg2:"#526170",fg3:"#7b8794",fg4:"#a1acb8",accent:"#0f8f83",accentSoft:"rgba(15, 143, 131, 0.11)",accentGlow:"rgba(15, 143, 131, 0.24)",onAccent:"#021918",ok:"#16835c",working:"#137333",unread:"#1d4ed8",onUnread:"#ffffff",danger:"#c03545",onDanger:"#fff7f8",dangerSoft:"rgba(192, 53, 69, 0.10)",dangerLine:"rgba(192, 53, 69, 0.30)",warning:"#b7791f",warningSoft:"rgba(183, 121, 31, 0.12)",warningGlow:"rgba(183, 121, 31, 0.26)",scrim:"rgba(15, 23, 42, 0.34)",scrimSoft:"rgba(15, 23, 42, 0.20)",shadow:"rgba(15, 23, 42, 0.18)",shadowStrong:"rgba(15, 23, 42, 0.28)",floatingBg:"rgba(255, 255, 255, 0.92)",floatingBgStrong:"rgba(255, 255, 255, 0.98)",floatingBgHover:"rgba(239, 246, 249, 0.96)",subtleFill:"rgba(15, 23, 42, 0.025)",hoverFill:"rgba(15, 23, 42, 0.035)",scrollbarThumb:"rgba(82, 97, 112, 0.38)",scrollbarThumbHover:"rgba(82, 97, 112, 0.58)",transcriptUser:"#8b3f75",transcriptAssistant:"#0f8f83",transcriptTool:"#66717d",transcriptCommand:"#0b6fa4",transcriptCode:"#075985",transcriptSearch:"#f0c14b",transcriptOnSearch:"#1f1a10",qrBg:"#ffffff"},xterm:{background:"#ffffff",foreground:"#17212b",cursor:"#0f8f83",selectionBackground:"#cdeee9",...h1({foreground:"#17212b",foregroundMuted:"#526170",line:"#dbe3ec",red:"#b4232f",green:"#16794f",yellow:"#9a6700",blue:"#0b6fa4",magenta:"#8f3f85",cyan:"#0f766e"})}},{id:"signal-red",label:"Signal",description:"Dark control-room surface with red alerts.",mode:"dark",tokens:{bg:"#100d0f",bg2:"#171113",bgSidebar:"#0b080a",line:"#2a1b20",line2:"#452b32",fg:"#f1e7e9",fg2:"#a58d93",fg3:"#765f66",fg4:"#55434a",accent:"#ff2a3d",accentSoft:"rgba(255, 42, 61, 0.12)",accentGlow:"rgba(255, 42, 61, 0.52)",onAccent:"#210407",ok:"#34d399",working:"#4ade80",unread:"#60a5fa",onUnread:"#06152f",danger:"#ff4d5f",onDanger:"#210407",dangerSoft:"rgba(255, 77, 95, 0.10)",dangerLine:"rgba(255, 77, 95, 0.32)",warning:"#fbbf24",warningSoft:"rgba(251, 191, 36, 0.10)",warningGlow:"rgba(245, 158, 11, 0.50)",scrim:"rgba(0, 0, 0, 0.58)",scrimSoft:"rgba(0, 0, 0, 0.30)",shadow:"rgba(0, 0, 0, 0.36)",shadowStrong:"rgba(0, 0, 0, 0.52)",floatingBg:"rgba(16, 13, 15, 0.88)",floatingBgStrong:"rgba(16, 13, 15, 0.96)",floatingBgHover:"rgba(25, 16, 19, 0.96)",subtleFill:"rgba(255, 255, 255, 0.018)",hoverFill:"rgba(255, 255, 255, 0.018)",scrollbarThumb:"rgba(165, 141, 147, 0.45)",scrollbarThumbHover:"rgba(165, 141, 147, 0.65)",transcriptUser:"#f8d36f",transcriptAssistant:"#ff2a3d",transcriptTool:"#ad9ca2",transcriptCommand:"#ff9ca6",transcriptCode:"#ffd1d6",transcriptSearch:"#f8d36f",transcriptOnSearch:"#1b0e10",qrBg:"#ffffff"},xterm:{background:"#100d0f",foreground:"#f1e7e9",cursor:"#ff2a3d",selectionBackground:"#4a1b22"}},{id:"graphite",label:"Graphite",description:"Neutral dark theme with blue command focus.",mode:"dark",tokens:{bg:"#101214",bg2:"#171a1d",bgSidebar:"#0c0e10",line:"#262b30",line2:"#39414a",fg:"#eceff3",fg2:"#9aa4af",fg3:"#6c7680",fg4:"#4d5660",accent:"#7dd3fc",accentSoft:"rgba(125, 211, 252, 0.11)",accentGlow:"rgba(125, 211, 252, 0.38)",onAccent:"#071c26",ok:"#4ade80",working:"#4ade80",unread:"#60a5fa",onUnread:"#06152f",danger:"#fb7185",onDanger:"#26070d",dangerSoft:"rgba(251, 113, 133, 0.09)",dangerLine:"rgba(251, 113, 133, 0.30)",warning:"#facc15",warningSoft:"rgba(250, 204, 21, 0.09)",warningGlow:"rgba(250, 204, 21, 0.42)",scrim:"rgba(0, 0, 0, 0.55)",scrimSoft:"rgba(0, 0, 0, 0.28)",shadow:"rgba(0, 0, 0, 0.34)",shadowStrong:"rgba(0, 0, 0, 0.50)",floatingBg:"rgba(16, 18, 20, 0.88)",floatingBgStrong:"rgba(16, 18, 20, 0.96)",floatingBgHover:"rgba(22, 28, 33, 0.96)",subtleFill:"rgba(255, 255, 255, 0.018)",hoverFill:"rgba(255, 255, 255, 0.018)",scrollbarThumb:"rgba(154, 164, 175, 0.45)",scrollbarThumbHover:"rgba(154, 164, 175, 0.65)",transcriptUser:"#f2d675",transcriptAssistant:"#7dd3fc",transcriptTool:"#aab4bf",transcriptCommand:"#8fd6ff",transcriptCode:"#c4f1ff",transcriptSearch:"#f2d675",transcriptOnSearch:"#141513",qrBg:"#ffffff"},xterm:{background:"#101214",foreground:"#eceff3",cursor:"#7dd3fc",selectionBackground:"#263d4b"}},{id:"paper",label:"Paper",description:"Warm light surface with restrained amber accent.",mode:"light",tokens:{bg:"#fbfaf7",bg2:"#ffffff",bgSidebar:"#f2f0ea",line:"#e2ddd4",line2:"#cbc3b6",fg:"#25211d",fg2:"#62584e",fg3:"#8d8275",fg4:"#afa69b",accent:"#a35d00",accentSoft:"rgba(163, 93, 0, 0.11)",accentGlow:"rgba(163, 93, 0, 0.24)",onAccent:"#fffaf2",ok:"#26744d",working:"#137333",unread:"#1d4ed8",onUnread:"#ffffff",danger:"#b23a48",onDanger:"#fff8f8",dangerSoft:"rgba(178, 58, 72, 0.10)",dangerLine:"rgba(178, 58, 72, 0.30)",warning:"#a35d00",warningSoft:"rgba(163, 93, 0, 0.12)",warningGlow:"rgba(163, 93, 0, 0.26)",scrim:"rgba(37, 33, 29, 0.32)",scrimSoft:"rgba(37, 33, 29, 0.18)",shadow:"rgba(37, 33, 29, 0.18)",shadowStrong:"rgba(37, 33, 29, 0.28)",floatingBg:"rgba(255, 253, 249, 0.92)",floatingBgStrong:"rgba(255, 253, 249, 0.98)",floatingBgHover:"rgba(250, 247, 240, 0.96)",subtleFill:"rgba(37, 33, 29, 0.025)",hoverFill:"rgba(37, 33, 29, 0.035)",scrollbarThumb:"rgba(98, 88, 78, 0.35)",scrollbarThumbHover:"rgba(98, 88, 78, 0.55)",transcriptUser:"#7b3f8c",transcriptAssistant:"#a35d00",transcriptTool:"#776d63",transcriptCommand:"#176a94",transcriptCode:"#6f4b00",transcriptSearch:"#e9c46a",transcriptOnSearch:"#241b0a",qrBg:"#ffffff"},xterm:{background:"#fffdf9",foreground:"#25211d",cursor:"#a35d00",selectionBackground:"#f2dfc5",...h1({foreground:"#25211d",foregroundMuted:"#62584e",line:"#e2ddd4",red:"#a8323d",green:"#26744d",yellow:"#875600",blue:"#176a94",magenta:"#8b4b80",cyan:"#276f68"})}}],Xc="midnight";function Up(e){return rp.some(t=>t.id===e)?e:Xc}function ey(e){return rp.find(t=>t.id===e)??rp[0]}function Bo(){if(typeof window>"u")return Xc;try{const e=window.localStorage.getItem(Jb);return e?Up(e):jN(window.localStorage.getItem(JC))}catch{return Xc}}function DN(e){const t=Up(e);if(typeof window<"u"){try{window.localStorage.setItem(Jb,t)}catch{}ty(t),window.dispatchEvent(new CustomEvent(Xv,{detail:t}))}return t}function ty(e=Bo()){if(typeof document>"u")return;const t=ey(Up(e)),n=document.documentElement;n.dataset.ntTheme=t.id,n.style.setProperty("color-scheme",t.mode),yt(n,"--nt-bg",t.tokens.bg),yt(n,"--nt-bg-2",t.tokens.bg2),yt(n,"--nt-bg-sidebar",t.tokens.bgSidebar),yt(n,"--nt-line",t.tokens.line),yt(n,"--nt-line-2",t.tokens.line2),yt(n,"--nt-fg",t.tokens.fg),yt(n,"--nt-fg-2",t.tokens.fg2),yt(n,"--nt-fg-3",t.tokens.fg3),yt(n,"--nt-fg-4",t.tokens.fg4),yt(n,"--nt-accent",t.tokens.accent),yt(n,"--nt-accent-soft",t.tokens.accentSoft),yt(n,"--nt-accent-glow",t.tokens.accentGlow),yt(n,"--nt-on-accent",t.tokens.onAccent),yt(n,"--nt-ok",t.tokens.ok),yt(n,"--nt-working",t.tokens.working),yt(n,"--nt-unread",t.tokens.unread),yt(n,"--nt-on-unread",t.tokens.onUnread),yt(n,"--nt-danger",t.tokens.danger),yt(n,"--nt-on-danger",t.tokens.onDanger),yt(n,"--nt-danger-soft",t.tokens.dangerSoft),yt(n,"--nt-danger-line",t.tokens.dangerLine),yt(n,"--nt-warning",t.tokens.warning),yt(n,"--nt-warn",t.tokens.warning),yt(n,"--nt-warning-soft",t.tokens.warningSoft),yt(n,"--nt-warning-glow",t.tokens.warningGlow),yt(n,"--nt-scrim",t.tokens.scrim),yt(n,"--nt-scrim-soft",t.tokens.scrimSoft),yt(n,"--nt-shadow",t.tokens.shadow),yt(n,"--nt-shadow-strong",t.tokens.shadowStrong),yt(n,"--nt-floating-bg",t.tokens.floatingBg),yt(n,"--nt-floating-bg-strong",t.tokens.floatingBgStrong),yt(n,"--nt-floating-bg-hover",t.tokens.floatingBgHover),yt(n,"--nt-subtle-fill",t.tokens.subtleFill),yt(n,"--nt-hover-fill",t.tokens.hoverFill),yt(n,"--nt-scrollbar-thumb",t.tokens.scrollbarThumb),yt(n,"--nt-scrollbar-thumb-hover",t.tokens.scrollbarThumbHover),yt(n,"--nt-transcript-user",t.tokens.transcriptUser),yt(n,"--nt-transcript-assistant",t.tokens.transcriptAssistant),yt(n,"--nt-transcript-tool",t.tokens.transcriptTool),yt(n,"--nt-transcript-command",t.tokens.transcriptCommand),yt(n,"--nt-transcript-code",t.tokens.transcriptCode),yt(n,"--nt-transcript-search",t.tokens.transcriptSearch),yt(n,"--nt-transcript-on-search",t.tokens.transcriptOnSearch),yt(n,"--nt-qr-bg",t.tokens.qrBg)}function MN(e=Bo()){return ey(Up(e)).xterm}function ny(e){if(typeof window>"u")return()=>{};const t=n=>{(n.key===Jb||n.key===JC)&&(ty(Bo()),e())};return window.addEventListener(Xv,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Xv,e),window.removeEventListener("storage",t)}}function yt(e,t,n){e.style.setProperty(t,n)}function h1(e){const t=AN(237);return t[215]=e.foreground,t[221]=e.line,{black:e.foreground,red:e.red,green:e.green,yellow:e.yellow,blue:e.blue,magenta:e.magenta,cyan:e.cyan,white:e.foregroundMuted,brightBlack:e.foregroundMuted,brightRed:e.red,brightGreen:e.green,brightYellow:e.yellow,brightBlue:e.blue,brightMagenta:e.magenta,brightCyan:e.cyan,brightWhite:e.foreground,extendedAnsi:t}}function AN(e){const t=[];for(let n=16;n<=e;n+=1)t.push(LN(n));return t}function LN(e){if(e>=16&&e<=231){const t=e-16,n=[0,95,135,175,215,255],s=n[Math.floor(t/36)%6],o=n[Math.floor(t/6)%6],l=n[t%6];return f1(s,o,l)}if(e>=232&&e<=255){const t=8+(e-232)*10;return f1(t,t,t)}return"#000000"}function f1(e,t,n){return`#${Xg(e)}${Xg(t)}${Xg(n)}`}function Xg(e){return e.toString(16).padStart(2,"0")}function jN(e){return e==="signal-red"?"signal-red":Xc}function ek(){const e=v.useSyncExternalStore(ny,Bo,()=>Xc);return ey(e).mode==="light"?"-light":""}function tk({size:e=22}){const t=ek();return u.jsx("img",{className:"nterminal-mark",src:`/brand/nterminal-mark${t}.svg`,width:e,height:e,alt:"","aria-hidden":"true"})}function nk({height:e=18}){const t=ek(),n=Math.round(243/34*e);return u.jsx("img",{className:"nterminal-wordmark",src:`/brand/nterminal-wordmark${t}.svg`,width:n,height:e,alt:"NTerminal"})}var vd=XC();function ON(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v.useMemo(()=>s=>{t.forEach(o=>o(s))},t)}const $p=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function iu(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function iy(e){return"nodeType"in e}function qi(e){var t,n;return e?iu(e)?e:iy(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function ry(e){const{Document:t}=qi(e);return e instanceof t}function uh(e){return iu(e)?!1:e instanceof qi(e).HTMLElement}function ik(e){return e instanceof qi(e).SVGElement}function ru(e){return e?iu(e)?e.document:iy(e)?ry(e)?e:uh(e)||ik(e)?e.ownerDocument:document:document:document}const fs=$p?v.useLayoutEffect:v.useEffect;function Fp(e){const t=v.useRef(e);return fs(()=>{t.current=e}),v.useCallback(function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];return t.current==null?void 0:t.current(...s)},[])}function BN(){const e=v.useRef(null),t=v.useCallback((s,o)=>{e.current=setInterval(s,o)},[]),n=v.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function $d(e,t){t===void 0&&(t=[e]);const n=v.useRef(e);return fs(()=>{n.current!==e&&(n.current=e)},t),n}function dh(e,t){const n=v.useRef();return v.useMemo(()=>{const s=e(n.current);return n.current=s,s},[...t])}function sp(e){const t=Fp(e),n=v.useRef(null),s=v.useCallback(o=>{o!==n.current&&t?.(o,n.current),n.current=o},[]);return[n,s]}function ap(e){const t=v.useRef();return v.useEffect(()=>{t.current=e},[e]),t.current}let Zg={};function hh(e,t){return v.useMemo(()=>{if(t)return t;const n=Zg[e]==null?0:Zg[e]+1;return Zg[e]=n,e+"-"+n},[e,t])}function rk(e){return function(t){for(var n=arguments.length,s=new Array(n>1?n-1:0),o=1;o<n;o++)s[o-1]=arguments[o];return s.reduce((l,d)=>{const f=Object.entries(d);for(const[m,p]of f){const b=l[m];b!=null&&(l[m]=b+e*p)}return l},{...t})}}const qc=rk(1),op=rk(-1);function IN(e){return"clientX"in e&&"clientY"in e}function Wp(e){if(!e)return!1;const{KeyboardEvent:t}=qi(e.target);return t&&e instanceof t}function PN(e){if(!e)return!1;const{TouchEvent:t}=qi(e.target);return t&&e instanceof t}function lp(e){if(PN(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return IN(e)?{x:e.clientX,y:e.clientY}:null}const Oa=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Oa.Translate.toString(e),Oa.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:s}=e;return t+" "+n+"ms "+s}}}),p1="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function zN(e){return e.matches(p1)?e:e.querySelector(p1)}const HN={display:"none"};function UN(e){let{id:t,value:n}=e;return zt.createElement("div",{id:t,style:HN},n)}function $N(e){let{id:t,announcement:n,ariaLiveType:s="assertive"}=e;const o={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return zt.createElement("div",{id:t,style:o,role:"status","aria-live":s,"aria-atomic":!0},n)}function FN(){const[e,t]=v.useState("");return{announce:v.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const sk=v.createContext(null);function WN(e){const t=v.useContext(sk);v.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function KN(){const[e]=v.useState(()=>new Set),t=v.useCallback(s=>(e.add(s),()=>e.delete(s)),[e]);return[v.useCallback(s=>{let{type:o,event:l}=s;e.forEach(d=>{var f;return(f=d[o])==null?void 0:f.call(d,l)})},[e]),t]}const qN={draggable:`
11
+ To pick up a draggable item, press the space bar.
12
+ While dragging, use the arrow keys to move the item.
13
+ Press space again to drop the item in its new position, or press escape to cancel.
14
+ `},VN={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function YN(e){let{announcements:t=VN,container:n,hiddenTextDescribedById:s,screenReaderInstructions:o=qN}=e;const{announce:l,announcement:d}=FN(),f=hh("DndLiveRegion"),[m,p]=v.useState(!1);if(v.useEffect(()=>{p(!0)},[]),WN(v.useMemo(()=>({onDragStart(_){let{active:S}=_;l(t.onDragStart({active:S}))},onDragMove(_){let{active:S,over:w}=_;t.onDragMove&&l(t.onDragMove({active:S,over:w}))},onDragOver(_){let{active:S,over:w}=_;l(t.onDragOver({active:S,over:w}))},onDragEnd(_){let{active:S,over:w}=_;l(t.onDragEnd({active:S,over:w}))},onDragCancel(_){let{active:S,over:w}=_;l(t.onDragCancel({active:S,over:w}))}}),[l,t])),!m)return null;const b=zt.createElement(zt.Fragment,null,zt.createElement(UN,{id:s,value:o.draggable}),zt.createElement($N,{id:f,announcement:d}));return n?vd.createPortal(b,n):b}var ci;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(ci||(ci={}));function cp(){}function up(e,t){return v.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function ak(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v.useMemo(()=>[...t].filter(s=>s!=null),[...t])}const ps=Object.freeze({x:0,y:0});function GN(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function XN(e,t){const n=lp(e);if(!n)return"0 0";const s={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return s.x+"% "+s.y+"%"}function ZN(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return n-s}function QN(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return s-n}function JN(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function m1(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}const eD=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:s}=e;const o=m1(t,t.left,t.top),l=[];for(const d of s){const{id:f}=d,m=n.get(f);if(m){const p=GN(m1(m),o);l.push({id:f,data:{droppableContainer:d,value:p}})}}return l.sort(ZN)};function tD(e,t){const n=Math.max(t.top,e.top),s=Math.max(t.left,e.left),o=Math.min(t.left+t.width,e.left+e.width),l=Math.min(t.top+t.height,e.top+e.height),d=o-s,f=l-n;if(s<o&&n<l){const m=t.width*t.height,p=e.width*e.height,b=d*f,_=b/(m+p-b);return Number(_.toFixed(4))}return 0}const nD=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:s}=e;const o=[];for(const l of s){const{id:d}=l,f=n.get(d);if(f){const m=tD(f,t);m>0&&o.push({id:d,data:{droppableContainer:l,value:m}})}}return o.sort(QN)};function iD(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function ok(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:ps}function rD(e){return function(n){for(var s=arguments.length,o=new Array(s>1?s-1:0),l=1;l<s;l++)o[l-1]=arguments[l];return o.reduce((d,f)=>({...d,top:d.top+e*f.y,bottom:d.bottom+e*f.y,left:d.left+e*f.x,right:d.right+e*f.x}),{...n})}}const sD=rD(1);function lk(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function aD(e,t,n){const s=lk(t);if(!s)return e;const{scaleX:o,scaleY:l,x:d,y:f}=s,m=e.left-d-(1-o)*parseFloat(n),p=e.top-f-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),b=o?e.width/o:e.width,_=l?e.height/l:e.height;return{width:b,height:_,top:p,right:m+b,bottom:p+_,left:m}}const oD={ignoreTransform:!1};function su(e,t){t===void 0&&(t=oD);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:p,transformOrigin:b}=qi(e).getComputedStyle(e);p&&(n=aD(n,p,b))}const{top:s,left:o,width:l,height:d,bottom:f,right:m}=n;return{top:s,left:o,width:l,height:d,bottom:f,right:m}}function g1(e){return su(e,{ignoreTransform:!0})}function lD(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function cD(e,t){return t===void 0&&(t=qi(e).getComputedStyle(e)),t.position==="fixed"}function uD(e,t){t===void 0&&(t=qi(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{const l=t[o];return typeof l=="string"?n.test(l):!1})}function sy(e,t){const n=[];function s(o){if(t!=null&&n.length>=t||!o)return n;if(ry(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!uh(o)||ik(o)||n.includes(o))return n;const l=qi(e).getComputedStyle(o);return o!==e&&uD(o,l)&&n.push(o),cD(o,l)?n:s(o.parentNode)}return e?s(e):n}function ck(e){const[t]=sy(e,1);return t??null}function Qg(e){return!$p||!e?null:iu(e)?e:iy(e)?ry(e)||e===ru(e).scrollingElement?window:uh(e)?e:null:null}function uk(e){return iu(e)?e.scrollX:e.scrollLeft}function dk(e){return iu(e)?e.scrollY:e.scrollTop}function Zv(e){return{x:uk(e),y:dk(e)}}var vi;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(vi||(vi={}));function hk(e){return!$p||!e?!1:e===document.scrollingElement}function fk(e){const t={x:0,y:0},n=hk(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},s={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},o=e.scrollTop<=t.y,l=e.scrollLeft<=t.x,d=e.scrollTop>=s.y,f=e.scrollLeft>=s.x;return{isTop:o,isLeft:l,isBottom:d,isRight:f,maxScroll:s,minScroll:t}}const dD={x:.2,y:.2};function hD(e,t,n,s,o){let{top:l,left:d,right:f,bottom:m}=n;s===void 0&&(s=10),o===void 0&&(o=dD);const{isTop:p,isBottom:b,isLeft:_,isRight:S}=fk(e),w={x:0,y:0},x={x:0,y:0},R={height:t.height*o.y,width:t.width*o.x};return!p&&l<=t.top+R.height?(w.y=vi.Backward,x.y=s*Math.abs((t.top+R.height-l)/R.height)):!b&&m>=t.bottom-R.height&&(w.y=vi.Forward,x.y=s*Math.abs((t.bottom-R.height-m)/R.height)),!S&&f>=t.right-R.width?(w.x=vi.Forward,x.x=s*Math.abs((t.right-R.width-f)/R.width)):!_&&d<=t.left+R.width&&(w.x=vi.Backward,x.x=s*Math.abs((t.left+R.width-d)/R.width)),{direction:w,speed:x}}function fD(e){if(e===document.scrollingElement){const{innerWidth:l,innerHeight:d}=window;return{top:0,left:0,right:l,bottom:d,width:l,height:d}}const{top:t,left:n,right:s,bottom:o}=e.getBoundingClientRect();return{top:t,left:n,right:s,bottom:o,width:e.clientWidth,height:e.clientHeight}}function pk(e){return e.reduce((t,n)=>qc(t,Zv(n)),ps)}function pD(e){return e.reduce((t,n)=>t+uk(n),0)}function mD(e){return e.reduce((t,n)=>t+dk(n),0)}function mk(e,t){if(t===void 0&&(t=su),!e)return;const{top:n,left:s,bottom:o,right:l}=t(e);ck(e)&&(o<=0||l<=0||n>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const gD=[["x",["left","right"],pD],["y",["top","bottom"],mD]];class ay{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=sy(n),o=pk(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[l,d,f]of gD)for(const m of d)Object.defineProperty(this,m,{get:()=>{const p=f(s),b=o[l]-p;return this.rect[m]+b},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Md{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...n)})},this.target=t}add(t,n,s){var o;(o=this.target)==null||o.addEventListener(t,n,s),this.listeners.push([t,n,s])}}function vD(e){const{EventTarget:t}=qi(e);return e instanceof t?e:ru(e)}function Jg(e,t){const n=Math.abs(e.x),s=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+s**2)>t:"x"in t&&"y"in t?n>t.x&&s>t.y:"x"in t?n>t.x:"y"in t?s>t.y:!1}var Xr;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Xr||(Xr={}));function v1(e){e.preventDefault()}function _D(e){e.stopPropagation()}var Gt;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(Gt||(Gt={}));const gk={start:[Gt.Space,Gt.Enter],cancel:[Gt.Esc],end:[Gt.Space,Gt.Enter,Gt.Tab]},bD=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Gt.Right:return{...n,x:n.x+25};case Gt.Left:return{...n,x:n.x-25};case Gt.Down:return{...n,y:n.y+25};case Gt.Up:return{...n,y:n.y-25}}};class vk{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new Md(ru(n)),this.windowListeners=new Md(qi(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Xr.Resize,this.handleCancel),this.windowListeners.add(Xr.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Xr.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,s=t.node.current;s&&mk(s),n(ps)}handleKeyDown(t){if(Wp(t)){const{active:n,context:s,options:o}=this.props,{keyboardCodes:l=gk,coordinateGetter:d=bD,scrollBehavior:f="smooth"}=o,{code:m}=t;if(l.end.includes(m)){this.handleEnd(t);return}if(l.cancel.includes(m)){this.handleCancel(t);return}const{collisionRect:p}=s.current,b=p?{x:p.left,y:p.top}:ps;this.referenceCoordinates||(this.referenceCoordinates=b);const _=d(t,{active:n,context:s.current,currentCoordinates:b});if(_){const S=op(_,b),w={x:0,y:0},{scrollableAncestors:x}=s.current;for(const R of x){const L=t.code,{isTop:A,isRight:W,isLeft:H,isBottom:U,maxScroll:q,minScroll:Y}=fk(R),I=fD(R),F={x:Math.min(L===Gt.Right?I.right-I.width/2:I.right,Math.max(L===Gt.Right?I.left:I.left+I.width/2,_.x)),y:Math.min(L===Gt.Down?I.bottom-I.height/2:I.bottom,Math.max(L===Gt.Down?I.top:I.top+I.height/2,_.y))},de=L===Gt.Right&&!W||L===Gt.Left&&!H,me=L===Gt.Down&&!U||L===Gt.Up&&!A;if(de&&F.x!==_.x){const K=R.scrollLeft+S.x,te=L===Gt.Right&&K<=q.x||L===Gt.Left&&K>=Y.x;if(te&&!S.y){R.scrollTo({left:K,behavior:f});return}te?w.x=R.scrollLeft-K:w.x=L===Gt.Right?R.scrollLeft-q.x:R.scrollLeft-Y.x,w.x&&R.scrollBy({left:-w.x,behavior:f});break}else if(me&&F.y!==_.y){const K=R.scrollTop+S.y,te=L===Gt.Down&&K<=q.y||L===Gt.Up&&K>=Y.y;if(te&&!S.x){R.scrollTo({top:K,behavior:f});return}te?w.y=R.scrollTop-K:w.y=L===Gt.Down?R.scrollTop-q.y:R.scrollTop-Y.y,w.y&&R.scrollBy({top:-w.y,behavior:f});break}}this.handleMove(t,qc(op(_,this.referenceCoordinates),w))}}}handleMove(t,n){const{onMove:s}=this.props;t.preventDefault(),s(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}vk.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:s=gk,onActivation:o}=t,{active:l}=n;const{code:d}=e.nativeEvent;if(s.start.includes(d)){const f=l.activatorNode.current;return f&&e.target!==f?!1:(e.preventDefault(),o?.({event:e.nativeEvent}),!0)}return!1}}];function _1(e){return!!(e&&"distance"in e)}function b1(e){return!!(e&&"delay"in e)}class oy{constructor(t,n,s){var o;s===void 0&&(s=vD(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:l}=t,{target:d}=l;this.props=t,this.events=n,this.document=ru(d),this.documentListeners=new Md(this.document),this.listeners=new Md(s),this.windowListeners=new Md(qi(d)),this.initialCoordinates=(o=lp(l))!=null?o:ps,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:s}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(Xr.Resize,this.handleCancel),this.windowListeners.add(Xr.DragStart,v1),this.windowListeners.add(Xr.VisibilityChange,this.handleCancel),this.windowListeners.add(Xr.ContextMenu,v1),this.documentListeners.add(Xr.Keydown,this.handleKeydown),n){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(b1(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(_1(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:s,onPending:o}=this.props;o(s,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Xr.Click,_D,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Xr.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:s,initialCoordinates:o,props:l}=this,{onMove:d,options:{activationConstraint:f}}=l;if(!o)return;const m=(n=lp(t))!=null?n:ps,p=op(o,m);if(!s&&f){if(_1(f)){if(f.tolerance!=null&&Jg(p,f.tolerance))return this.handleCancel();if(Jg(p,f.distance))return this.handleStart()}if(b1(f)&&Jg(p,f.tolerance))return this.handleCancel();this.handlePending(f,p);return}t.cancelable&&t.preventDefault(),d(m)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Gt.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const yD={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class _k extends oy{constructor(t){const{event:n}=t,s=ru(n.target);super(t,yD,s)}}_k.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;return!n.isPrimary||n.button!==0?!1:(s?.({event:n}),!0)}}];const SD={move:{name:"mousemove"},end:{name:"mouseup"}};var Qv;(function(e){e[e.RightClick=2]="RightClick"})(Qv||(Qv={}));class ly extends oy{constructor(t){super(t,SD,ru(t.event.target))}}ly.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;return n.button===Qv.RightClick?!1:(s?.({event:n}),!0)}}];const ev={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class cy extends oy{constructor(t){super(t,ev)}static setup(){return window.addEventListener(ev.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(ev.move.name,t)};function t(){}}}cy.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;const{touches:o}=n;return o.length>1?!1:(s?.({event:n}),!0)}}];var Ad;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Ad||(Ad={}));var dp;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(dp||(dp={}));function wD(e){let{acceleration:t,activator:n=Ad.Pointer,canScroll:s,draggingRect:o,enabled:l,interval:d=5,order:f=dp.TreeOrder,pointerCoordinates:m,scrollableAncestors:p,scrollableAncestorRects:b,delta:_,threshold:S}=e;const w=CD({delta:_,disabled:!l}),[x,R]=BN(),L=v.useRef({x:0,y:0}),A=v.useRef({x:0,y:0}),W=v.useMemo(()=>{switch(n){case Ad.Pointer:return m?{top:m.y,bottom:m.y,left:m.x,right:m.x}:null;case Ad.DraggableRect:return o}},[n,o,m]),H=v.useRef(null),U=v.useCallback(()=>{const Y=H.current;if(!Y)return;const I=L.current.x*A.current.x,F=L.current.y*A.current.y;Y.scrollBy(I,F)},[]),q=v.useMemo(()=>f===dp.TreeOrder?[...p].reverse():p,[f,p]);v.useEffect(()=>{if(!l||!p.length||!W){R();return}for(const Y of q){if(s?.(Y)===!1)continue;const I=p.indexOf(Y),F=b[I];if(!F)continue;const{direction:de,speed:me}=hD(Y,F,W,t,S);for(const K of["x","y"])w[K][de[K]]||(me[K]=0,de[K]=0);if(me.x>0||me.y>0){R(),H.current=Y,x(U,d),L.current=me,A.current=de;return}}L.current={x:0,y:0},A.current={x:0,y:0},R()},[t,U,s,R,l,d,JSON.stringify(W),JSON.stringify(w),x,p,q,b,JSON.stringify(S)])}const xD={x:{[vi.Backward]:!1,[vi.Forward]:!1},y:{[vi.Backward]:!1,[vi.Forward]:!1}};function CD(e){let{delta:t,disabled:n}=e;const s=ap(t);return dh(o=>{if(n||!s||!o)return xD;const l={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[vi.Backward]:o.x[vi.Backward]||l.x===-1,[vi.Forward]:o.x[vi.Forward]||l.x===1},y:{[vi.Backward]:o.y[vi.Backward]||l.y===-1,[vi.Forward]:o.y[vi.Forward]||l.y===1}}},[n,t,s])}function kD(e,t){const n=t!=null?e.get(t):void 0,s=n?n.node.current:null;return dh(o=>{var l;return t==null?null:(l=s??o)!=null?l:null},[s,t])}function TD(e,t){return v.useMemo(()=>e.reduce((n,s)=>{const{sensor:o}=s,l=o.activators.map(d=>({eventName:d.eventName,handler:t(d.handler,s)}));return[...n,...l]},[]),[e,t])}var Fd;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Fd||(Fd={}));var Jv;(function(e){e.Optimized="optimized"})(Jv||(Jv={}));const y1=new Map;function ED(e,t){let{dragging:n,dependencies:s,config:o}=t;const[l,d]=v.useState(null),{frequency:f,measure:m,strategy:p}=o,b=v.useRef(e),_=L(),S=$d(_),w=v.useCallback(function(A){A===void 0&&(A=[]),!S.current&&d(W=>W===null?A:W.concat(A.filter(H=>!W.includes(H))))},[S]),x=v.useRef(null),R=dh(A=>{if(_&&!n)return y1;if(!A||A===y1||b.current!==e||l!=null){const W=new Map;for(let H of e){if(!H)continue;if(l&&l.length>0&&!l.includes(H.id)&&H.rect.current){W.set(H.id,H.rect.current);continue}const U=H.node.current,q=U?new ay(m(U),U):null;H.rect.current=q,q&&W.set(H.id,q)}return W}return A},[e,l,n,_,m]);return v.useEffect(()=>{b.current=e},[e]),v.useEffect(()=>{_||w()},[n,_]),v.useEffect(()=>{l&&l.length>0&&d(null)},[JSON.stringify(l)]),v.useEffect(()=>{_||typeof f!="number"||x.current!==null||(x.current=setTimeout(()=>{w(),x.current=null},f))},[f,_,w,...s]),{droppableRects:R,measureDroppableContainers:w,measuringScheduled:l!=null};function L(){switch(p){case Fd.Always:return!1;case Fd.BeforeDragging:return n;default:return!n}}}function uy(e,t){return dh(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function RD(e,t){return uy(e,t)}function ND(e){let{callback:t,disabled:n}=e;const s=Fp(t),o=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(s)},[s,n]);return v.useEffect(()=>()=>o?.disconnect(),[o]),o}function Kp(e){let{callback:t,disabled:n}=e;const s=Fp(t),o=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(s)},[n]);return v.useEffect(()=>()=>o?.disconnect(),[o]),o}function DD(e){return new ay(su(e),e)}function S1(e,t,n){t===void 0&&(t=DD);const[s,o]=v.useState(null);function l(){o(m=>{if(!e)return null;if(e.isConnected===!1){var p;return(p=m??n)!=null?p:null}const b=t(e);return JSON.stringify(m)===JSON.stringify(b)?m:b})}const d=ND({callback(m){if(e)for(const p of m){const{type:b,target:_}=p;if(b==="childList"&&_ instanceof HTMLElement&&_.contains(e)){l();break}}}}),f=Kp({callback:l});return fs(()=>{l(),e?(f?.observe(e),d?.observe(document.body,{childList:!0,subtree:!0})):(f?.disconnect(),d?.disconnect())},[e]),s}function MD(e){const t=uy(e);return ok(e,t)}const w1=[];function AD(e){const t=v.useRef(e),n=dh(s=>e?s&&s!==w1&&e&&t.current&&e.parentNode===t.current.parentNode?s:sy(e):w1,[e]);return v.useEffect(()=>{t.current=e},[e]),n}function LD(e){const[t,n]=v.useState(null),s=v.useRef(e),o=v.useCallback(l=>{const d=Qg(l.target);d&&n(f=>f?(f.set(d,Zv(d)),new Map(f)):null)},[]);return v.useEffect(()=>{const l=s.current;if(e!==l){d(l);const f=e.map(m=>{const p=Qg(m);return p?(p.addEventListener("scroll",o,{passive:!0}),[p,Zv(p)]):null}).filter(m=>m!=null);n(f.length?new Map(f):null),s.current=e}return()=>{d(e),d(l)};function d(f){f.forEach(m=>{const p=Qg(m);p?.removeEventListener("scroll",o)})}},[o,e]),v.useMemo(()=>e.length?t?Array.from(t.values()).reduce((l,d)=>qc(l,d),ps):pk(e):ps,[e,t])}function x1(e,t){t===void 0&&(t=[]);const n=v.useRef(null);return v.useEffect(()=>{n.current=null},t),v.useEffect(()=>{const s=e!==ps;s&&!n.current&&(n.current=e),!s&&n.current&&(n.current=null)},[e]),n.current?op(e,n.current):ps}function jD(e){v.useEffect(()=>{if(!$p)return;const t=e.map(n=>{let{sensor:s}=n;return s.setup==null?void 0:s.setup()});return()=>{for(const n of t)n?.()}},e.map(t=>{let{sensor:n}=t;return n}))}function OD(e,t){return v.useMemo(()=>e.reduce((n,s)=>{let{eventName:o,handler:l}=s;return n[o]=d=>{l(d,t)},n},{}),[e,t])}function bk(e){return v.useMemo(()=>e?lD(e):null,[e])}const C1=[];function BD(e,t){t===void 0&&(t=su);const[n]=e,s=bk(n?qi(n):null),[o,l]=v.useState(C1);function d(){l(()=>e.length?e.map(m=>hk(m)?s:new ay(t(m),m)):C1)}const f=Kp({callback:d});return fs(()=>{f?.disconnect(),d(),e.forEach(m=>f?.observe(m))},[e]),o}function yk(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return uh(t)?t:e}function ID(e){let{measure:t}=e;const[n,s]=v.useState(null),o=v.useCallback(p=>{for(const{target:b}of p)if(uh(b)){s(_=>{const S=t(b);return _?{..._,width:S.width,height:S.height}:S});break}},[t]),l=Kp({callback:o}),d=v.useCallback(p=>{const b=yk(p);l?.disconnect(),b&&l?.observe(b),s(b?t(b):null)},[t,l]),[f,m]=sp(d);return v.useMemo(()=>({nodeRef:f,rect:n,setRef:m}),[n,f,m])}const PD=[{sensor:_k,options:{}},{sensor:vk,options:{}}],zD={current:{}},Hf={draggable:{measure:g1},droppable:{measure:g1,strategy:Fd.WhileDragging,frequency:Jv.Optimized},dragOverlay:{measure:su}};class Ld extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,s;return(n=(s=this.get(t))==null?void 0:s.node.current)!=null?n:void 0}}const HD={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ld,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:cp},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Hf,measureDroppableContainers:cp,windowRect:null,measuringScheduled:!1},Sk={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:cp,draggableNodes:new Map,over:null,measureDroppableContainers:cp},fh=v.createContext(Sk),wk=v.createContext(HD);function UD(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ld}}}function $D(e,t){switch(t.type){case ci.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ci.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case ci.DragEnd:case ci.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ci.RegisterDroppable:{const{element:n}=t,{id:s}=n,o=new Ld(e.droppable.containers);return o.set(s,n),{...e,droppable:{...e.droppable,containers:o}}}case ci.SetDroppableDisabled:{const{id:n,key:s,disabled:o}=t,l=e.droppable.containers.get(n);if(!l||s!==l.key)return e;const d=new Ld(e.droppable.containers);return d.set(n,{...l,disabled:o}),{...e,droppable:{...e.droppable,containers:d}}}case ci.UnregisterDroppable:{const{id:n,key:s}=t,o=e.droppable.containers.get(n);if(!o||s!==o.key)return e;const l=new Ld(e.droppable.containers);return l.delete(n),{...e,droppable:{...e.droppable,containers:l}}}default:return e}}function FD(e){let{disabled:t}=e;const{active:n,activatorEvent:s,draggableNodes:o}=v.useContext(fh),l=ap(s),d=ap(n?.id);return v.useEffect(()=>{if(!t&&!s&&l&&d!=null){if(!Wp(l)||document.activeElement===l.target)return;const f=o.get(d);if(!f)return;const{activatorNode:m,node:p}=f;if(!m.current&&!p.current)return;requestAnimationFrame(()=>{for(const b of[m.current,p.current]){if(!b)continue;const _=zN(b);if(_){_.focus();break}}})}},[s,t,o,d,l]),null}function xk(e,t){let{transform:n,...s}=t;return e!=null&&e.length?e.reduce((o,l)=>l({transform:o,...s}),n):n}function WD(e){return v.useMemo(()=>({draggable:{...Hf.draggable,...e?.draggable},droppable:{...Hf.droppable,...e?.droppable},dragOverlay:{...Hf.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function KD(e){let{activeNode:t,measure:n,initialRect:s,config:o=!0}=e;const l=v.useRef(!1),{x:d,y:f}=typeof o=="boolean"?{x:o,y:o}:o;fs(()=>{if(!d&&!f||!t){l.current=!1;return}if(l.current||!s)return;const p=t?.node.current;if(!p||p.isConnected===!1)return;const b=n(p),_=ok(b,s);if(d||(_.x=0),f||(_.y=0),l.current=!0,Math.abs(_.x)>0||Math.abs(_.y)>0){const S=ck(p);S&&S.scrollBy({top:_.y,left:_.x})}},[t,d,f,s,n])}const qp=v.createContext({...ps,scaleX:1,scaleY:1});var To;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(To||(To={}));const Ck=v.memo(function(t){var n,s,o,l;let{id:d,accessibility:f,autoScroll:m=!0,children:p,sensors:b=PD,collisionDetection:_=nD,measuring:S,modifiers:w,...x}=t;const R=v.useReducer($D,void 0,UD),[L,A]=R,[W,H]=KN(),[U,q]=v.useState(To.Uninitialized),Y=U===To.Initialized,{draggable:{active:I,nodes:F,translate:de},droppable:{containers:me}}=L,K=I!=null?F.get(I):null,te=v.useRef({initial:null,translated:null}),J=v.useMemo(()=>{var Pe;return I!=null?{id:I,data:(Pe=K?.data)!=null?Pe:zD,rect:te}:null},[I,K]),Q=v.useRef(null),[X,M]=v.useState(null),[T,O]=v.useState(null),re=$d(x,Object.values(x)),he=hh("DndDescribedBy",d),N=v.useMemo(()=>me.getEnabled(),[me]),V=WD(S),{droppableRects:se,measureDroppableContainers:Z,measuringScheduled:Ee}=ED(N,{dragging:Y,dependencies:[de.x,de.y],config:V.droppable}),ye=kD(F,I),ze=v.useMemo(()=>T?lp(T):null,[T]),Ke=ae(),Be=RD(ye,V.draggable.measure);KD({activeNode:I!=null?F.get(I):null,config:Ke.layoutShiftCompensation,initialRect:Be,measure:V.draggable.measure});const ve=S1(ye,V.draggable.measure,Be),Fe=S1(ye?ye.parentElement:null),Ie=v.useRef({activatorEvent:null,active:null,activeNode:ye,collisionRect:null,collisions:null,droppableRects:se,draggableNodes:F,draggingNode:null,draggingNodeRect:null,droppableContainers:me,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),j=me.getNodeFor((n=Ie.current.over)==null?void 0:n.id),ge=ID({measure:V.dragOverlay.measure}),Ae=(s=ge.nodeRef.current)!=null?s:ye,Oe=Y?(o=ge.rect)!=null?o:ve:null,z=!!(ge.nodeRef.current&&ge.rect),fe=MD(z?null:ve),Te=bk(Ae?qi(Ae):null),Ne=AD(Y?j??ye:null),Le=BD(Ne),be=xk(w,{transform:{x:de.x-fe.x,y:de.y-fe.y,scaleX:1,scaleY:1},activatorEvent:T,active:J,activeNodeRect:ve,containerNodeRect:Fe,draggingNodeRect:Oe,over:Ie.current.over,overlayNodeRect:ge.rect,scrollableAncestors:Ne,scrollableAncestorRects:Le,windowRect:Te}),$e=ze?qc(ze,de):null,qe=LD(Ne),je=x1(qe),ht=x1(qe,[ve]),st=qc(be,je),mt=Oe?sD(Oe,be):null,xt=J&&mt?_({active:J,collisionRect:mt,droppableRects:se,droppableContainers:N,pointerCoordinates:$e}):null,on=JN(xt,"id"),[ot,Dn]=v.useState(null),Tn=z?be:qc(be,ht),ft=iD(Tn,(l=ot?.rect)!=null?l:null,ve),Dt=v.useRef(null),Mt=v.useCallback((Pe,tt)=>{let{sensor:_t,options:$t}=tt;if(Q.current==null)return;const en=F.get(Q.current);if(!en)return;const Ft=Pe.nativeEvent,mn=new _t({active:Q.current,activeNode:en,event:Ft,options:$t,context:Ie,onAbort(Ct){if(!F.get(Ct))return;const{onDragAbort:cn}=re.current,Kn={id:Ct};cn?.(Kn),W({type:"onDragAbort",event:Kn})},onPending(Ct,ln,cn,Kn){if(!F.get(Ct))return;const{onDragPending:rt}=re.current,Tt={id:Ct,constraint:ln,initialCoordinates:cn,offset:Kn};rt?.(Tt),W({type:"onDragPending",event:Tt})},onStart(Ct){const ln=Q.current;if(ln==null)return;const cn=F.get(ln);if(!cn)return;const{onDragStart:Kn}=re.current,In={activatorEvent:Ft,active:{id:ln,data:cn.data,rect:te}};vd.unstable_batchedUpdates(()=>{Kn?.(In),q(To.Initializing),A({type:ci.DragStart,initialCoordinates:Ct,active:ln}),W({type:"onDragStart",event:In}),M(Dt.current),O(Ft)})},onMove(Ct){A({type:ci.DragMove,coordinates:Ct})},onEnd:Bn(ci.DragEnd),onCancel:Bn(ci.DragCancel)});Dt.current=mn;function Bn(Ct){return async function(){const{active:cn,collisions:Kn,over:In,scrollAdjustedTranslate:rt}=Ie.current;let Tt=null;if(cn&&rt){const{cancelDrop:gn}=re.current;Tt={activatorEvent:Ft,active:cn,collisions:Kn,delta:rt,over:In},Ct===ci.DragEnd&&typeof gn=="function"&&await Promise.resolve(gn(Tt))&&(Ct=ci.DragCancel)}Q.current=null,vd.unstable_batchedUpdates(()=>{A({type:Ct}),q(To.Uninitialized),Dn(null),M(null),O(null),Dt.current=null;const gn=Ct===ci.DragEnd?"onDragEnd":"onDragCancel";if(Tt){const oe=re.current[gn];oe?.(Tt),W({type:gn,event:Tt})}})}}},[F]),wi=v.useCallback((Pe,tt)=>(_t,$t)=>{const en=_t.nativeEvent,Ft=F.get($t);if(Q.current!==null||!Ft||en.dndKit||en.defaultPrevented)return;const mn={active:Ft};Pe(_t,tt.options,mn)===!0&&(en.dndKit={capturedBy:tt.sensor},Q.current=$t,Mt(_t,tt))},[F,Mt]),di=TD(b,wi);jD(b),fs(()=>{ve&&U===To.Initializing&&q(To.Initialized)},[ve,U]),v.useEffect(()=>{const{onDragMove:Pe}=re.current,{active:tt,activatorEvent:_t,collisions:$t,over:en}=Ie.current;if(!tt||!_t)return;const Ft={active:tt,activatorEvent:_t,collisions:$t,delta:{x:st.x,y:st.y},over:en};vd.unstable_batchedUpdates(()=>{Pe?.(Ft),W({type:"onDragMove",event:Ft})})},[st.x,st.y]),v.useEffect(()=>{const{active:Pe,activatorEvent:tt,collisions:_t,droppableContainers:$t,scrollAdjustedTranslate:en}=Ie.current;if(!Pe||Q.current==null||!tt||!en)return;const{onDragOver:Ft}=re.current,mn=$t.get(on),Bn=mn&&mn.rect.current?{id:mn.id,rect:mn.rect.current,data:mn.data,disabled:mn.disabled}:null,Ct={active:Pe,activatorEvent:tt,collisions:_t,delta:{x:en.x,y:en.y},over:Bn};vd.unstable_batchedUpdates(()=>{Dn(Bn),Ft?.(Ct),W({type:"onDragOver",event:Ct})})},[on]),fs(()=>{Ie.current={activatorEvent:T,active:J,activeNode:ye,collisionRect:mt,collisions:xt,droppableRects:se,draggableNodes:F,draggingNode:Ae,draggingNodeRect:Oe,droppableContainers:me,over:ot,scrollableAncestors:Ne,scrollAdjustedTranslate:st},te.current={initial:Oe,translated:mt}},[J,ye,xt,mt,F,Ae,Oe,se,me,ot,Ne,st]),wD({...Ke,delta:de,draggingRect:mt,pointerCoordinates:$e,scrollableAncestors:Ne,scrollableAncestorRects:Le});const xi=v.useMemo(()=>({active:J,activeNode:ye,activeNodeRect:ve,activatorEvent:T,collisions:xt,containerNodeRect:Fe,dragOverlay:ge,draggableNodes:F,droppableContainers:me,droppableRects:se,over:ot,measureDroppableContainers:Z,scrollableAncestors:Ne,scrollableAncestorRects:Le,measuringConfiguration:V,measuringScheduled:Ee,windowRect:Te}),[J,ye,ve,T,xt,Fe,ge,F,me,se,ot,Z,Ne,Le,V,Ee,Te]),At=v.useMemo(()=>({activatorEvent:T,activators:di,active:J,activeNodeRect:ve,ariaDescribedById:{draggable:he},dispatch:A,draggableNodes:F,over:ot,measureDroppableContainers:Z}),[T,di,J,ve,A,he,F,ot,Z]);return zt.createElement(sk.Provider,{value:H},zt.createElement(fh.Provider,{value:At},zt.createElement(wk.Provider,{value:xi},zt.createElement(qp.Provider,{value:ft},p)),zt.createElement(FD,{disabled:f?.restoreFocus===!1})),zt.createElement(YN,{...f,hiddenTextDescribedById:he}));function ae(){const Pe=X?.autoScrollEnabled===!1,tt=typeof m=="object"?m.enabled===!1:m===!1,_t=Y&&!Pe&&!tt;return typeof m=="object"?{...m,enabled:_t}:{enabled:_t}}}),qD=v.createContext(null),k1="button",VD="Draggable";function dy(e){let{id:t,data:n,disabled:s=!1,attributes:o}=e;const l=hh(VD),{activators:d,activatorEvent:f,active:m,activeNodeRect:p,ariaDescribedById:b,draggableNodes:_,over:S}=v.useContext(fh),{role:w=k1,roleDescription:x="draggable",tabIndex:R=0}=o??{},L=m?.id===t,A=v.useContext(L?qp:qD),[W,H]=sp(),[U,q]=sp(),Y=OD(d,t),I=$d(n);fs(()=>(_.set(t,{id:t,key:l,node:W,activatorNode:U,data:I}),()=>{const de=_.get(t);de&&de.key===l&&_.delete(t)}),[_,t]);const F=v.useMemo(()=>({role:w,tabIndex:R,"aria-disabled":s,"aria-pressed":L&&w===k1?!0:void 0,"aria-roledescription":x,"aria-describedby":b.draggable}),[s,w,R,L,x,b.draggable]);return{active:m,activatorEvent:f,activeNodeRect:p,attributes:F,isDragging:L,listeners:s?void 0:Y,node:W,over:S,setNodeRef:H,setActivatorNodeRef:q,transform:A}}function kk(){return v.useContext(wk)}const YD="Droppable",GD={timeout:25};function Vp(e){let{data:t,disabled:n=!1,id:s,resizeObserverConfig:o}=e;const l=hh(YD),{active:d,dispatch:f,over:m,measureDroppableContainers:p}=v.useContext(fh),b=v.useRef({disabled:n}),_=v.useRef(!1),S=v.useRef(null),w=v.useRef(null),{disabled:x,updateMeasurementsFor:R,timeout:L}={...GD,...o},A=$d(R??s),W=v.useCallback(()=>{if(!_.current){_.current=!0;return}w.current!=null&&clearTimeout(w.current),w.current=setTimeout(()=>{p(Array.isArray(A.current)?A.current:[A.current]),w.current=null},L)},[L]),H=Kp({callback:W,disabled:x||!d}),U=v.useCallback((F,de)=>{H&&(de&&(H.unobserve(de),_.current=!1),F&&H.observe(F))},[H]),[q,Y]=sp(U),I=$d(t);return v.useEffect(()=>{!H||!q.current||(H.disconnect(),_.current=!1,H.observe(q.current))},[q,H]),v.useEffect(()=>(f({type:ci.RegisterDroppable,element:{id:s,key:l,disabled:n,node:q,rect:S,data:I}}),()=>f({type:ci.UnregisterDroppable,key:l,id:s})),[s]),v.useEffect(()=>{n!==b.current.disabled&&(f({type:ci.SetDroppableDisabled,id:s,key:l,disabled:n}),b.current.disabled=n)},[s,l,n,f]),{active:d,rect:S,isOver:m?.id===s,node:q,over:m,setNodeRef:Y}}function XD(e){let{animation:t,children:n}=e;const[s,o]=v.useState(null),[l,d]=v.useState(null),f=ap(n);return!n&&!s&&f&&o(f),fs(()=>{if(!l)return;const m=s?.key,p=s?.props.id;if(m==null||p==null){o(null);return}Promise.resolve(t(p,l)).then(()=>{o(null)})},[t,s,l]),zt.createElement(zt.Fragment,null,n,s?v.cloneElement(s,{ref:d}):null)}const ZD={x:0,y:0,scaleX:1,scaleY:1};function QD(e){let{children:t}=e;return zt.createElement(fh.Provider,{value:Sk},zt.createElement(qp.Provider,{value:ZD},t))}const JD={position:"fixed",touchAction:"none"},eM=e=>Wp(e)?"transform 250ms ease":void 0,tM=v.forwardRef((e,t)=>{let{as:n,activatorEvent:s,adjustScale:o,children:l,className:d,rect:f,style:m,transform:p,transition:b=eM}=e;if(!f)return null;const _=o?p:{...p,scaleX:1,scaleY:1},S={...JD,width:f.width,height:f.height,top:f.top,left:f.left,transform:Oa.Transform.toString(_),transformOrigin:o&&s?XN(s,f):void 0,transition:typeof b=="function"?b(s):b,...m};return zt.createElement(n,{className:d,style:S,ref:t},l)}),nM=e=>t=>{let{active:n,dragOverlay:s}=t;const o={},{styles:l,className:d}=e;if(l!=null&&l.active)for(const[f,m]of Object.entries(l.active))m!==void 0&&(o[f]=n.node.style.getPropertyValue(f),n.node.style.setProperty(f,m));if(l!=null&&l.dragOverlay)for(const[f,m]of Object.entries(l.dragOverlay))m!==void 0&&s.node.style.setProperty(f,m);return d!=null&&d.active&&n.node.classList.add(d.active),d!=null&&d.dragOverlay&&s.node.classList.add(d.dragOverlay),function(){for(const[m,p]of Object.entries(o))n.node.style.setProperty(m,p);d!=null&&d.active&&n.node.classList.remove(d.active)}},iM=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Oa.Transform.toString(t)},{transform:Oa.Transform.toString(n)}]},rM={duration:250,easing:"ease",keyframes:iM,sideEffects:nM({styles:{active:{opacity:"0"}}})};function sM(e){let{config:t,draggableNodes:n,droppableContainers:s,measuringConfiguration:o}=e;return Fp((l,d)=>{if(t===null)return;const f=n.get(l);if(!f)return;const m=f.node.current;if(!m)return;const p=yk(d);if(!p)return;const{transform:b}=qi(d).getComputedStyle(d),_=lk(b);if(!_)return;const S=typeof t=="function"?t:aM(t);return mk(m,o.draggable.measure),S({active:{id:l,data:f.data,node:m,rect:o.draggable.measure(m)},draggableNodes:n,dragOverlay:{node:d,rect:o.dragOverlay.measure(p)},droppableContainers:s,measuringConfiguration:o,transform:_})})}function aM(e){const{duration:t,easing:n,sideEffects:s,keyframes:o}={...rM,...e};return l=>{let{active:d,dragOverlay:f,transform:m,...p}=l;if(!t)return;const b={x:f.rect.left-d.rect.left,y:f.rect.top-d.rect.top},_={scaleX:m.scaleX!==1?d.rect.width*m.scaleX/f.rect.width:1,scaleY:m.scaleY!==1?d.rect.height*m.scaleY/f.rect.height:1},S={x:m.x-b.x,y:m.y-b.y,..._},w=o({...p,active:d,dragOverlay:f,transform:{initial:m,final:S}}),[x]=w,R=w[w.length-1];if(JSON.stringify(x)===JSON.stringify(R))return;const L=s?.({active:d,dragOverlay:f,...p}),A=f.node.animate(w,{duration:t,easing:n,fill:"forwards"});return new Promise(W=>{A.onfinish=()=>{L?.(),W()}})}}let T1=0;function oM(e){return v.useMemo(()=>{if(e!=null)return T1++,T1},[e])}const lM=zt.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:s,style:o,transition:l,modifiers:d,wrapperElement:f="div",className:m,zIndex:p=999}=e;const{activatorEvent:b,active:_,activeNodeRect:S,containerNodeRect:w,draggableNodes:x,droppableContainers:R,dragOverlay:L,over:A,measuringConfiguration:W,scrollableAncestors:H,scrollableAncestorRects:U,windowRect:q}=kk(),Y=v.useContext(qp),I=oM(_?.id),F=xk(d,{activatorEvent:b,active:_,activeNodeRect:S,containerNodeRect:w,draggingNodeRect:L.rect,over:A,overlayNodeRect:L.rect,scrollableAncestors:H,scrollableAncestorRects:U,transform:Y,windowRect:q}),de=uy(S),me=sM({config:s,draggableNodes:x,droppableContainers:R,measuringConfiguration:W}),K=de?L.setRef:void 0;return zt.createElement(QD,null,zt.createElement(XD,{animation:me},_&&I?zt.createElement(tM,{key:I,id:_.id,ref:K,as:f,activatorEvent:b,adjustScale:t,className:m,transition:l,rect:de,style:{zIndex:p,...o},transform:F},n):null))});function tv(e,t){return e.savedLayout&&e.savedLayout.revision>t.revision?e.savedLayout:t}const cM=128,uM=512,Io=100,dM="too_many_detached_terminals",hM=64,fM=4096;function Yp(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.activeWorkspaceId!="string"&&t.activeWorkspaceId!==null||!Array.isArray(t.workspaces)||t.workspaces.length>cM)return null;const n=t.workspaces.map(pM);if(n.some(d=>d===null))return null;const s=n,o=new Set,l=new Set;for(const d of s){if(o.has(d.id))return null;o.add(d.id);for(const f of d.tabs){if(l.has(f.id))return null;l.add(f.id)}}return{activeWorkspaceId:t.activeWorkspaceId,workspaces:s}}function Tk(e){if(!e||typeof e!="object")return!1;const t=e;return Array.isArray(t.workspaces)?t.workspaces.some(n=>{if(!n||typeof n!="object")return!1;const s=n.detachedTerminalIds;return Array.isArray(s)&&s.length>Io}):!1}function pM(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.id!="string"||typeof t.title!="string"||typeof t.activeTabId!="string"&&t.activeTabId!==null||!Array.isArray(t.tabs)||t.tabs.length>uM)return null;const n=t.tabs.map(mM);if(n.some(o=>o===null))return null;const s=bM(t.detachedTerminalIds,Io);return s===null?null:{id:t.id,title:t.title,defaultCwd:_M(t.defaultCwd),detachedTerminalIds:s,activeTabId:t.activeTabId,tabs:n}}function mM(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.id!="string"||typeof t.title!="string"||typeof t.activeTerminalId!="string")return null;const n=gM(t.root);return n?{id:t.id,title:t.title,activeTerminalId:t.activeTerminalId,root:n}:null}function gM(e){if(!e||typeof e!="object")return null;let t=0;return e_(e,1,()=>(t+=1,t<=fM))}function e_(e,t,n){if(!e||typeof e!="object"||t>hM||!n())return null;const s=e;if(s.type==="pane")return typeof s.terminalId=="string"?{type:"pane",terminalId:s.terminalId}:null;if(s.type!=="split"||s.direction!=="horizontal"&&s.direction!=="vertical")return null;const o=e_(s.first,t+1,n),l=e_(s.second,t+1,n);return!o||!l?null:{type:"split",direction:s.direction,ratio:vM(s.ratio),first:o,second:l}}function vM(e){return typeof e=="number"&&Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}function _M(e){if(typeof e!="string")return null;const t=e.trim();return t||null}function bM(e,t){if(e===void 0)return[];if(!Array.isArray(e)||e.length>t)return null;const n=new Set,s=[];for(const o of e)typeof o!="string"||!o||n.has(o)||(n.add(o),s.push(o));return s}const Ek=[{id:"builtin-character-2260",filename:"character-2260.mp4",contentType:"video/mp4",size:123288,createdAt:"2026-05-26T00:00:00.000Z",url:"/assets/notifications/character-2260.mp4"},{id:"builtin-character-2272",filename:"character-2272.mp4",contentType:"video/mp4",size:55873,createdAt:"2026-05-26T00:00:00.000Z",url:"/assets/notifications/character-2272.mp4"},{id:"builtin-character-2258",filename:"character-2258.mp4",contentType:"video/mp4",size:112612,createdAt:"2026-05-26T00:00:00.000Z",url:"/assets/notifications/character-2258.mp4"}],yM="nterminal-focus",SM=/^[A-Za-z0-9_.:-]{1,128}$/;function wM(e){if(!e.startsWith("#"))return null;const t=new URLSearchParams(e.slice(1));return t.get(yM)!=="terminal"?null:Gp({kind:"terminal",agentId:t.get("agentId"),terminalId:t.get("terminalId")})}function Gp(e){if(!e||typeof e!="object")return null;const t=e;if(t.kind!=="terminal"||!E1(t.terminalId))return null;const n=t.agentId===null||t.agentId===void 0||t.agentId===""?null:t.agentId;return n!==null&&!E1(n)?null:{kind:"terminal",agentId:n,terminalId:t.terminalId}}function E1(e){return typeof e=="string"&&SM.test(e)}const Zt="__main__",Rk=128,xM=600*1e3,Nk="nterminal.clientDiagnostics.v1",Dk="nterminal.terminalDiagnosticsCursor.v1",Xp=150,CM=24,kM=160,TM=48*1024,EM="terminal-connection-recovery";let R1=!1,od=null,ld=null,nv=0;function RM(){R1||typeof window>"u"||(R1=!0,Pi("page.load",{navigation:KM(),visibility:document.visibilityState,online:navigator.onLine,viewport:Ok(),standalone:WM()}),document.addEventListener("visibilitychange",()=>{Pi("page.visibility",{visibility:document.visibilityState,online:navigator.onLine})}),window.addEventListener("pageshow",e=>{Pi("page.show",{persisted:e.persisted,visibility:document.visibilityState,online:navigator.onLine})}),window.addEventListener("pagehide",e=>{Pi("page.hide",{persisted:e.persisted,visibility:document.visibilityState,online:navigator.onLine})}),window.addEventListener("online",()=>Pi("network.online")),window.addEventListener("offline",()=>Pi("network.offline")),window.addEventListener("focus",()=>Pi("window.focus")),window.addEventListener("blur",()=>Pi("window.blur")),window.addEventListener("error",e=>{Pi("runtime.error",{message:e.message,source:qM(e.filename),line:e.lineno||null})}),window.addEventListener("unhandledrejection",e=>{Pi("runtime.unhandledrejection",{reason:VM(e.reason)})}))}function Pi(e,t={}){const n={id:IM(),at:new Date().toISOString(),event:Wd(e,80),data:jk({...t,visibility:t.visibility??$M(),online:t.online??FM(),viewport:t.viewport??Ok()})},s=hy();return s.push(n),OM(s.slice(-Xp)),n}function hy(){try{const e=window.localStorage.getItem(Nk);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.map(BM).filter(n=>n!==null).slice(-Xp):[]}catch{return[]}}async function fy(e,t=fetch){if(od)return od;const n=hy(),s={reason:Wd(e,80),events:n},o=JSON.stringify(s);od=(async()=>{const l=await t("/api/client-diagnostics",{method:"POST",headers:{"content-type":"application/json"},credentials:"same-origin",keepalive:o.length<48e3,body:o});if(!l.ok)throw new Error(`diagnostics_send_failed_${l.status}`);return l.json()})();try{return await od}finally{od=null}}function Zp(){return Mk().events.length>0}async function NM(e=fetch){if(ld)return ld;ld=DM(e);try{return await ld}finally{ld=null}}async function DM(e){const t=Mk();if(t.events.length===0)return{outcome:"empty"};try{const n=await e("/api/client-diagnostics",{method:"POST",headers:{"content-type":"application/json"},credentials:"same-origin",keepalive:!0,body:t.body});return n.ok?(jM(t.events),{outcome:"sent",hasMore:t.hasMore}):n.status===401||n.status===403?{outcome:"auth_blocked"}:{outcome:"retryable"}}catch{return{outcome:"retryable"}}}function Mk(){const e=Ak(),t=hy().filter(o=>MM(o)&&LM(o,e)),n=[];let s=N1([]);for(const o of t){const l=[...n,o],d=N1(l);if(AM(d)>TM)break;n.push(o),s=d}return{events:n,body:s,hasMore:n.length<t.length}}function N1(e){return JSON.stringify({reason:EM,events:e})}function MM(e){return e.event.startsWith("terminal.connection.")||e.event.startsWith("terminal.input.")}function AM(e){return new TextEncoder().encode(e).byteLength}function LM(e,t){return t===null||e.at>t.at?!0:e.at===t.at&&!t.boundaryIds.includes(Lk(e))}function Ak(){try{const e=window.localStorage.getItem(Dk);if(!e)return null;if(!e.startsWith("{"))return{at:e.slice(0,40),boundaryIds:[]};const t=JSON.parse(e);return typeof t.at!="string"?null:{at:t.at.slice(0,40),boundaryIds:Array.isArray(t.boundaryIds)?t.boundaryIds.filter(n=>typeof n=="string").slice(-Xp):[]}}catch{return null}}function jM(e){const t=e.at(-1);if(!t)return;const n=Ak(),s=new Set(n?.at===t.at?n.boundaryIds:[]);for(const l of e)l.at===t.at&&s.add(Lk(l));const o={at:t.at.slice(0,40),boundaryIds:Array.from(s).slice(-Xp)};try{window.localStorage.setItem(Dk,JSON.stringify(o))}catch{}}function OM(e){try{window.localStorage.setItem(Nk,JSON.stringify(e))}catch{}}function BM(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.at!="string"||typeof t.event!="string"?null:{...typeof t.id=="string"?{id:Wd(t.id,128)}:{},at:t.at.slice(0,40),event:Wd(t.event,80),...t.data&&typeof t.data=="object"?{data:jk(t.data)}:{}}}function IM(){return nv=(nv+1)%Number.MAX_SAFE_INTEGER,`${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}-${nv.toString(36)}`.slice(0,128)}function Lk(e){if(e.id)return e.id;let t=2166136261;const n=`${e.at}\0${e.event}\0${JSON.stringify(e.data??{})}`;for(let s=0;s<n.length;s+=1)t^=n.charCodeAt(s),t=Math.imul(t,16777619);return`legacy-${(t>>>0).toString(16)}`}function jk(e){const t={};for(const[n,s]of Object.entries(e).slice(0,CM)){const o=Wd(n,64);if(!o||PM(o))continue;const l=zM(s);l!==void 0&&(t[o]=l)}return t}function PM(e){return/(?:password|secret|token|cookie|authorization|sessionid|session_id|nterminal_session|nterminal_device)/i.test(e)}function zM(e){if(typeof e=="string")return HM(e,kM);if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="boolean"||e===null)return e}function Wd(e,t){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_").slice(0,t)}function HM(e,t){return UM(e).replace(/[\r\n\t]+/g," ").replace(/[^\x20-\x7E]/g,"_").slice(0,t)}function UM(e){return e.replace(/https?:\/\/[^\s"'<>]+/gi,"[url]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer [redacted]").replace(/\b[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,"[redacted]").replace(/\b((?:auth|authorization|cookie|password|secret|session|sessionid|session_id|token)[a-z0-9_.:-]*\s*[:=]\s*)[^\s&,;]+/gi,"$1[redacted]").replace(/\b(nterminal_session|nterminal_device)\s*=\s*[^\s;,]+/gi,"$1=[redacted]").replace(/\b[A-Za-z0-9+/_=-]{48,}\b/g,"[redacted]")}function $M(){return typeof document>"u"?void 0:document.visibilityState}function FM(){return typeof navigator>"u"?void 0:navigator.onLine}function Ok(){if(typeof window>"u")return;const e=window.innerWidth||0;return e<640?"mobile":e<1024?"tablet":"desktop"}function WM(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches===!0||navigator.standalone===!0}function KM(){return performance.getEntriesByType?.("navigation")?.[0]?.type??"unknown"}function qM(e){if(!e)return null;try{const t=new URL(e);return t.pathname.split("/").pop()||t.pathname}catch{return e.split("/").pop()??e}}function VM(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:typeof e}const Bk="nterminal.notifications.completionEnabled",py="nterminal.notifications.completionToastEnabled",my="nterminal.notifications.completionToastDurationSeconds",gy="nterminal.notifications.completionToastPersistent",t_="nterminal:completion-toast-display",n_="nterminal:notification-focus",jd=6.5,i_=2,r_=60;function Qp(){return typeof window<"u"&&"Notification"in window}function vy(){try{return window.localStorage.getItem(Bk)==="true"}catch{return!1}}function D1(e){try{window.localStorage.setItem(Bk,e?"true":"false")}catch{}}function Bl(){return{enabled:ZM(),durationSeconds:XM(),persistUntilDismissed:QM()}}function YM(e){if(typeof window<"u"){try{window.localStorage.setItem(py,e?"true":"false")}catch{}_y()}return Bl()}function M1(e){const t=Pk(e);if(typeof window<"u"){try{window.localStorage.setItem(my,String(t))}catch{}_y()}return Bl()}function GM(e){if(typeof window<"u"){try{window.localStorage.setItem(gy,e?"true":"false")}catch{}_y()}return Bl()}function Ik(e){if(typeof window>"u")return()=>{};const t=n=>{(n.key===py||n.key===my||n.key===gy)&&e()};return window.addEventListener(t_,e),window.addEventListener("storage",t),()=>{window.removeEventListener(t_,e),window.removeEventListener("storage",t)}}function au(){return Qp()?window.Notification.permission:"unsupported"}function XM(){if(typeof window>"u")return jd;try{const e=window.localStorage.getItem(my);return e===null?jd:Pk(Number(e))}catch{return jd}}function ZM(){if(typeof window>"u")return!0;try{return window.localStorage.getItem(py)!=="false"}catch{return!0}}function QM(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(gy)==="true"}catch{return!1}}function Pk(e){if(!Number.isFinite(e))return jd;const t=Math.round(e*2)/2;return Math.max(i_,Math.min(r_,t))}function _y(){typeof window<"u"&&window.dispatchEvent(new CustomEvent(t_))}async function zk(){if(!Qp())return"unsupported";try{return await window.Notification.requestPermission()}catch{return au()}}function JM(e){if(!Qp()||au()!=="granted"||!vy()||typeof document<"u"&&document.visibilityState==="visible")return;const t=e.outcome==="stopped"?"stopped":"finished",n=e.commandName?`${e.commandName} ${t}`:`Command ${t}`,s=Gp({kind:"terminal",agentId:e.agentId,terminalId:e.terminalId});try{const o=new Notification(`NTerminal · ${e.tabTitle}`,{body:n,tag:e.terminalId,icon:"/icons/app-icon-384.png",data:s?{focus:s}:void 0,silent:!0});s&&(o.onclick=()=>{window.focus(),eA(s)})}catch{}}function eA(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(n_,{detail:e}))}const A1="nterminal.push.clientId",tA=2e4,L1=[5e3,3e4,12e4];function Da(){try{const e=window.localStorage.getItem(A1);if(e&&/^[A-Za-z0-9_.:-]{8,128}$/.test(e))return e;const t=`client-${a_()}`;return window.localStorage.setItem(A1,t),t}catch{return`client-${a_()}`}}function nA(){return`page-${a_()}`}function Jp(){const e=typeof window<"u"&&window.isSecureContext===!0,t=cA(),n=uA(),s=n==="mobile"||n==="tablet",o=e&&typeof window<"u"&&typeof navigator<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&t==="standalone"&&s;return{supported:o,secure:e,displayMode:t,deviceKind:n,reason:e?t!=="standalone"?"not_standalone":s?o?"supported":"unsupported":"not_mobile":"insecure"}}async function iA(e,t){const n=Jp();if(!n.supported)throw new Error(n.reason);if((au()==="granted"?"granted":await zk())!=="granted")throw new Error("permission_denied");const o=Da(),l=await navigator.serviceWorker.register("/sw.js"),d=await e.preparePushNotifications(o),m=await hA(l,d.publicKey)??await l.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:$k(d.publicKey)});await e.subscribePushNotifications({clientId:o,subscription:Uk(m),deviceKind:n.deviceKind,displayMode:n.displayMode,label:Hk(n.deviceKind),alwaysNotify:t})}async function rA(e){const t=Jp();if(!t.supported||au()!=="granted")return!1;const n=await navigator.serviceWorker.getRegistration(),s=await n?.pushManager.getSubscription();if(!n||!s)return!1;const o=Da(),l=await fA(s.endpoint),d=await e.getPushNotificationStatus(o,l);if(d.currentDevice&&d.endpointRegistered===!0&&d.vapidPublicKey&&s_(s,d.vapidPublicKey))return!1;const f=await e.preparePushNotifications(o),m=d.endpointRegistered===!0&&s_(s,f.publicKey);m||await s.unsubscribe();const p=m?s:await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:$k(f.publicKey)});return await e.subscribePushNotifications({clientId:o,subscription:Uk(p),deviceKind:t.deviceKind,displayMode:t.displayMode,label:Hk(t.deviceKind),alwaysNotify:!1}),!0}function sA(e){let t=!1,n=!1,s=0,o=null;const l=()=>{o!==null&&(window.clearTimeout(o),o=null)},d=b=>{t||n||(n=!0,rA(e).then(_=>{s=0,_&&Pi("push.subscription.reconciled",{trigger:b})}).catch(_=>{if(Pi("push.subscription.reconcile_failed",{trigger:b,reason:_ instanceof Error?_.message:String(_)}),!t&&s<L1.length){const S=L1[s++];o=window.setTimeout(()=>{o=null,d("retry")},S)}}).finally(()=>{n=!1}))},f=b=>{l(),s=0,d(b)},m=()=>f("online"),p=()=>f("pageshow");return window.addEventListener("online",m),window.addEventListener("pageshow",p),d("startup"),()=>{t=!0,l(),window.removeEventListener("online",m),window.removeEventListener("pageshow",p)}}async function aA(e){const t=Da();let n;try{const o=await(await navigator.serviceWorker.getRegistration("/sw.js"))?.pushManager.getSubscription();n=o?.endpoint,await o?.unsubscribe()}catch{}await e.unsubscribePushNotifications({clientId:t,...n?{endpoint:n}:{}})}async function oA(e,t){await e.updatePushNotificationDevice({clientId:Da(),alwaysNotify:t})}function lA(e){if(typeof window>"u")return()=>{};const t=Da(),n=nA();let s=null,o=!1;const l=(p=!0)=>{const b=Jp();e.updatePushPresence({clientId:t,pageId:n,visibilityState:dA(),focused:document.hasFocus(),deviceKind:b.deviceKind,displayMode:b.displayMode,browserNotificationsEnabled:vy()&&au()==="granted",active:p}).catch(()=>{})},d=()=>{o||s!==null||(s=window.setInterval(()=>l(!0),tA))},f=()=>l(!0),m=()=>l(!1);return window.addEventListener("focus",f),window.addEventListener("blur",f),document.addEventListener("visibilitychange",f),window.addEventListener("pagehide",m),l(!0),d(),()=>{o=!0,s!==null&&(window.clearInterval(s),s=null),window.removeEventListener("focus",f),window.removeEventListener("blur",f),document.removeEventListener("visibilitychange",f),window.removeEventListener("pagehide",m),l(!1)}}function cA(){return typeof window>"u"?"unknown":navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)").matches?"standalone":"browser"}function uA(){if(typeof navigator>"u")return"unknown";const e=navigator.userAgent.toLowerCase();return/ipad|tablet/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?"tablet":/mobi|android|iphone|ipod/.test(e)?"mobile":"desktop"}function Hk(e){return e==="mobile"?"Mobile PWA":e==="tablet"?"Tablet PWA":e==="desktop"?"Desktop PWA":"Installed PWA"}function dA(){const e=document.visibilityState;return e==="visible"||e==="hidden"||e==="prerender"?e:"unknown"}function Uk(e){const t=e.toJSON(),n=t.keys?.p256dh,s=t.keys?.auth;if(!t.endpoint||!n||!s)throw new Error("invalid_subscription");return{endpoint:t.endpoint,expirationTime:t.expirationTime??null,keys:{p256dh:n,auth:s}}}async function hA(e,t){const n=await e.pushManager.getSubscription();return n?s_(n,t)?n:(await n.unsubscribe(),null):null}function s_(e,t){const n=e.options.applicationServerKey;return n?Fk(n)===t:!0}async function fA(e){const t=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Fk(t)}function $k(e){const t="=".repeat((4-e.length%4)%4),n=`${e}${t}`.replace(/-/g,"+").replace(/_/g,"/"),s=window.atob(n),o=new ArrayBuffer(s.length),l=new Uint8Array(o);for(let d=0;d<s.length;d+=1)l[d]=s.charCodeAt(d);return o}function Fk(e){const t=new Uint8Array(e);let n="";for(const s of t)n+=String.fromCharCode(s);return window.btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function a_(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}const pA=e=>e?.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();function mA(e,t,n=[]){if(t==null)throw new Error("[lucide]: iconNode is required when icon name is used");return{name:pA(e),size:24,node:t,...n.length>0?{aliases:n}:{}}}const gA=e=>{let t="",n=!1;for(const s of e){if(s==="-"||s==="_"||s<=" "){n=t.length>0;continue}t.length===0?t+=s.toLowerCase():t+=n?s.toUpperCase():s,n=!1}return t};const vA=e=>{const t=gA(e);return t.charAt(0).toUpperCase()+t.slice(1)};const o_=(...e)=>e.filter((t,n,s)=>!!t&&t.trim()!==""&&s.indexOf(t)===n).join(" ").trim();const wl={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"};function iv(e){return e!=null}function _A(e,t={}){const n=t.attributeNames??{},s=S=>n[S]??S,o=e.size??e.width??wl.width,l=e.size??e.height??wl.height,d=e.aliases?.filter(S=>typeof S=="string"&&S.trim()!=="").map(S=>`lucide-${S}`)??[],f=[...e.name?[`lucide-${e.name}`]:[],...d],m=t.className?.split(" ").filter(Boolean)??[],p=t.includeDefaultClasses===!1?o_(...m):o_("lucide",...f,...m),b=t.absoluteStrokeWidth?Number(t.strokeWidth??wl["stroke-width"])*Number(e.size??e.width??wl.width)/Number(t.size??t.width??wl.width):t.strokeWidth??wl["stroke-width"];return["svg",{...Object.entries(wl).reduce((S,[w,x])=>(S[s(w)]=x,S),{}),..."color"in t&&t.color&&{[s("stroke")]:t.color},..."size"in t&&iv(t.size)&&{[s("width")]:t.size,[s("height")]:t.size},..."width"in t&&iv(t.width)&&{[s("width")]:t.width},..."height"in t&&iv(t.height)&&{[s("height")]:t.height},[s("stroke-width")]:b,...p&&{[s("class")]:p},[s("viewBox")]:`0 0 ${o} ${l}`,...t.hasA11yProp===!1?{[s("aria-hidden")]:"true"}:{},..."attributes"in t&&t.attributes},e.node.map(S=>{const[w,x,R]=S,L=t.nonScalingStroke?{[s("vector-effect")]:"non-scaling-stroke",...x}:x;return R?[w,L,R]:[w,L]})]}function bA(e,t={}){return _A(e,{...t,attributeNames:{...t.attributeNames,class:"className","stroke-width":"strokeWidth","stroke-linecap":"strokeLinecap","stroke-linejoin":"strokeLinejoin","vector-effect":"vectorEffect"}})}const yA=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},SA=v.createContext({}),wA=()=>v.useContext(SA),xA=v.forwardRef(({color:e,size:t,width:n,height:s,strokeWidth:o,absoluteStrokeWidth:l,nonScalingStroke:d,className:f="",children:m,iconNode:p=[],icon:b={node:p,aliases:[],size:24},..._},S)=>{const{size:w=24,strokeWidth:x=2,absoluteStrokeWidth:R=!1,nonScalingStroke:L=!1,color:A="currentColor",className:W=""}=wA()??{},H=!!m||yA(_),[U,q,Y=[]]=bA(b,{color:e??A,width:n??t??w,height:s??t??w,strokeWidth:o??x,absoluteStrokeWidth:l??R,nonScalingStroke:d??L,className:o_(W,f),hasA11yProp:H,attributes:_});return v.createElement(U,{ref:S,...q},[...Y.map(([I,F])=>v.createElement(I,F)),...Array.isArray(m)?m:[m]])});function kn(e,t=[],n=[]){const s=typeof e=="string"?mA(e,t,n):e,o=v.forwardRef(({className:l,...d},f)=>v.createElement(xA,{ref:f,icon:s,className:l,...d}));return s.name&&(o.displayName=vA(s.name)),o}const Wk={name:"arrow-big-up",size:24,node:[["path",{d:"M9 19a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-6a1 1 0 0 1 1-1h3.293a.707.707 0 0 0 .5-1.207l-7.086-7.086a1 1 0 0 0-1.414 0l-7.086 7.086a.707.707 0 0 0 .5 1.207H8a1 1 0 0 1 1 1z",key:"106j91"}]]};Wk.node;const CA=kn(Wk);const Kk={name:"arrow-down",size:24,node:[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]};Kk.node;const kA=kn(Kk);const qk={name:"arrow-right",size:24,node:[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]};qk.node;const TA=kn(qk);const Vk={name:"arrow-up-right",size:24,node:[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]};Vk.node;const EA=kn(Vk);const Yk={name:"arrow-up",size:24,node:[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]};Yk.node;const RA=kn(Yk);const Gk={name:"check",size:24,node:[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]};Gk.node;const Xk=kn(Gk);const Zk={name:"chevron-down",size:24,node:[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]};Zk.node;const NA=kn(Zk);const Qk={name:"chevron-right",size:24,node:[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]};Qk.node;const Jk=kn(Qk);const eT={name:"copy",size:24,node:[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]};eT.node;const hp=kn(eT);const tT={name:"external-link",size:24,node:[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]};tT.node;const DA=kn(tT);const nT={name:"folder",size:24,node:[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]};nT.node;const MA=kn(nT);const iT={name:"info",size:24,node:[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]};iT.node;const AA=kn(iT);const rT={name:"key-round",size:24,node:[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]};rT.node;const LA=kn(rT);const sT={name:"list",size:24,node:[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]]};sT.node;const jA=kn(sT);const aT={name:"loader-circle",size:24,node:[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],aliases:["loader-2"]};aT.node;const j1=kn(aT);const oT={name:"log-in",size:24,node:[["path",{d:"m10 17 5-5-5-5",key:"1bsop3"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}]]};oT.node;const OA=kn(oT);const lT={name:"pencil",size:24,node:[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]};lT.node;const cT=kn(lT);const uT={name:"plug",size:24,node:[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]]};uT.node;const rv=kn(uT);const dT={name:"plus",size:24,node:[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]};dT.node;const BA=kn(dT);const hT={name:"refresh-cw",size:24,node:[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]};hT.node;const Il=kn(hT);const fT={name:"shield-check",size:24,node:[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]};fT.node;const O1=kn(fT);const pT={name:"trash",size:24,node:[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],aliases:["trash-2"]};pT.node;const IA=kn(pT);const mT={name:"unplug",size:24,node:[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]]};mT.node;const B1=kn(mT);const gT={name:"x",size:24,node:[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]};gT.node;const fp=kn(gT);function Ea(e,t){const n=[Zt,...t.map(d=>d.id)],s=new Set(n),o=new Set,l=[];for(const d of e??[])!s.has(d)||o.has(d)||(o.add(d),l.push(d));for(const d of n)o.has(d)||l.push(d);return l}function PA(e,t){return Ea(e,t).map(n=>n===Zt?null:n)}function zA(e){return e===void 0?"unknown":e.status==="offline"?"offline":"ok"}function HA(e){const t=e.trim();return t?t.charAt(0).toUpperCase():"?"}const I1="Local",UA=3e4,$A=2,FA=6,vT="nterminal.serverList.viewMode.v1";function WA(){try{return window.localStorage.getItem(vT)==="list"?"list":"stats"}catch{return"stats"}}function KA(e){try{window.localStorage.setItem(vT,e)}catch{}}function qA(e,t){const n=new Map(e.map(s=>[s.id,s]));return Ea(t,e).flatMap(s=>{if(s===Zt)return[{kind:"main",id:Zt}];const o=n.get(s);return o?[{kind:"agent",id:s,agent:o}]:[]})}function P1(e,t){return e.length===t.length&&e.every((n,s)=>n===t[s])}function _T(e){return e===void 0?"":e.status==="offline"?"offline":e.value?[`CPU ${Qr(e.value.cpuPercent)} ${by(e.value)}`,`MEM ${Qr(e.value.memoryPercent)} ${ja(e.value.memoryUsedBytes,e.value.memoryTotalBytes)}`,`DISK ${Qr(e.value.diskPercent)} ${ja(e.value.diskUsedBytes,e.value.diskTotalBytes)}`,`SWAP ${Qr(e.value.swapPercent)} ${ja(e.value.swapUsedBytes,e.value.swapTotalBytes)}`].join(" · ")+(e.stale?" · last known":""):"stats unavailable"}function z1(e){if(e===void 0||e.status==="offline"||!e.value)return;const t=[`CPU ${Qr(e.value.cpuPercent)} (${by(e.value)})`,`RAM ${Qr(e.value.memoryPercent)} (${ja(e.value.memoryUsedBytes,e.value.memoryTotalBytes)})`,`Disk ${Qr(e.value.diskPercent)} (${ja(e.value.diskUsedBytes,e.value.diskTotalBytes)})`,`Swap ${Qr(e.value.swapPercent)} (${ja(e.value.swapUsedBytes,e.value.swapTotalBytes)})`].join(" · ");return e.stale?`Last known resource usage — ${t}`:t}function VA(e,t){const n=_T(t);return`${e}${n?` — ${n}`:""}. Double-click to rename.`}function Qr(e){return typeof e=="number"&&Number.isFinite(e)?`${Math.round(e)}%`:"–"}function by(e){const t=Number.isFinite(e.cores)&&e.cores>0?e.cores:null;return e.cpuPercent===null||e.cpuPercent===void 0||!Number.isFinite(e.cpuPercent)||t===null?`–/${t??"–"} cores`:`${l_(e.cpuPercent/100*t)}/${t} cores`}function ja(e,t){return!H1(e)||!H1(t)?"–/–":YA(e,t)}function YA(e,t){const n=t>=1073741824?"GB":t>=1048576?"MB":"KB",s=n==="GB"?1024**3:n==="MB"?1024**2:1024;return`${l_(e/s)}/${l_(t/s)} ${n}`}function l_(e){return e>=10||Number.isInteger(e)?e.toFixed(0):e.toFixed(1)}function H1(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function wf(e){return typeof e!="number"||!Number.isFinite(e)?"normal":e>95?"danger":e>90?"warning":"normal"}function GA(e){return[{label:"CPU",percent:Qr(e.cpuPercent),detail:by(e),tone:wf(e.cpuPercent)},{label:"MEM",percent:Qr(e.memoryPercent),detail:ja(e.memoryUsedBytes,e.memoryTotalBytes),tone:wf(e.memoryPercent)},{label:"DISK",percent:Qr(e.diskPercent),detail:ja(e.diskUsedBytes,e.diskTotalBytes),tone:wf(e.diskPercent)},{label:"SWAP",percent:Qr(e.swapPercent),detail:ja(e.swapUsedBytes,e.swapTotalBytes),tone:wf(e.swapPercent)}]}function XA({entry:e}){return e?.status==="offline"?u.jsx("span",{className:"server-list-stats server-list-stats--offline",children:"offline"}):e===void 0||!e.value?u.jsx("span",{className:"server-list-stats server-list-stats-grid",title:e?.status==="online"?"Server reachable; resource usage unavailable":void 0,"aria-label":e?.status==="online"?"Server reachable; resource usage unavailable":"Resource usage loading",children:["CPU","MEM","DISK","SWAP"].map(t=>u.jsxs("span",{className:"server-list-stat-cell",children:[u.jsxs("span",{className:"server-list-stat-head",children:[u.jsx("span",{className:"server-list-stat-label",children:t}),u.jsx("span",{className:"server-list-stat-value",children:"–"})]}),u.jsx("span",{className:"server-list-stat-detail",children:"–"})]},t))}):u.jsx("span",{className:`server-list-stats server-list-stats-grid${e.stale?" server-list-stats-grid--stale":""}`,title:z1(e),"aria-label":z1(e),children:GA(e.value).map(t=>u.jsxs("span",{className:"server-list-stat-cell",children:[u.jsxs("span",{className:"server-list-stat-head",children:[u.jsx("span",{className:"server-list-stat-label",children:t.label}),u.jsx("span",{className:"server-list-stat-value","data-tone":t.tone,children:t.percent})]}),u.jsx("span",{className:"server-list-stat-detail",children:t.detail})]},t.label))})}function U1({api:e,activeAgentId:t,onSelectServer:n,onSessionInvalid:s,refreshToken:o=0,onServerLabelsChange:l,onManageAccounts:d,onServerInfo:f,renderServerChildren:m,compact:p=!1}){const[b,_]=v.useState([]),[S,w]=v.useState([Zt]),[x,R]=v.useState(null),[L,A]=v.useState(!1),[W,H]=v.useState(!1),[U,q]=v.useState(null),[Y,I]=v.useState(""),F=v.useRef(null),[de,me]=v.useState(()=>WA()),[K,te]=v.useState(null),[J,Q]=v.useState(null),[X,M]=v.useState({}),T=v.useRef({}),O=v.useRef(0),re=v.useRef([]),he=v.useRef([Zt]),N=v.useRef(null);v.useEffect(()=>{re.current=b},[b]),v.useEffect(()=>{const z=Ea(S,b);he.current=z,P1(z,S)||w(z)},[b,S]),v.useEffect(()=>{let z=!1;return e.listAgents().then(fe=>{z||(_(fe.agents),H(!0),w(Ea(fe.serverOrder,fe.agents)))}).catch(()=>{}),e.getMainInfo().then(fe=>{z||(R(fe.name),A(!0))}).catch(()=>{}),()=>{z=!0}},[e,o]),v.useEffect(()=>{U&&(F.current?.focus(),F.current?.select())},[U]),v.useEffect(()=>{let z=!1;function fe(){const Ne=[{key:Zt,load:()=>e.getMainStats(),probe:async()=>(await e.getMainInfo(),!0)},...b.map(be=>({key:be.id,load:()=>e.getAgentStats(be.id),probe:async()=>(await e.pingAgent(be.id)).ok}))],Le=new Set(Ne.map(be=>be.key));for(const be of Object.keys(T.current))Le.has(be)||delete T.current[be];M(be=>{const $e={};for(const qe of Le)qe in be&&($e[qe]=be[qe]);return $e});for(const be of Ne)be.load().then($e=>{z||(T.current[be.key]=0,M(qe=>Le.has(be.key)?{...qe,[be.key]:{status:"online",value:$e,stale:!1}}:qe))}).catch(async $e=>{if(z)return;if($e instanceof Wn&&$e.status===401&&be.key===Zt){s?.({source:"main-stats-401",status:401,activeAgentId:null});return}if(be.key===Zt&&$e instanceof Wn){T.current[be.key]=0,M(je=>{if(!Le.has(be.key))return je;const ht=je[be.key];return{...je,[be.key]:{status:"online",value:ht?.value??null,stale:!0}}});return}if(be.probe)try{if(await be.probe()){if(z)return;T.current[be.key]=0,M(je=>{if(!Le.has(be.key))return je;const ht=je[be.key];return{...je,[be.key]:{status:"online",value:ht?.value??null,stale:!0}}});return}}catch(je){if(z)return;if(je instanceof Wn&&je.status===401){s?.({source:be.key===Zt?"main-health-401":"agent-health-401",status:401,activeAgentId:null});return}}const qe=(T.current[be.key]??0)+1;T.current[be.key]=qe,qe>=$A&&M(je=>Le.has(be.key)?{...je,[be.key]:{status:"offline",value:je[be.key]?.value??null,stale:!0}}:je)})}fe();const Te=window.setInterval(fe,UA);return()=>{z=!0,window.clearInterval(Te)}},[e,b,s]);function V(z){z==="main"?(I(x??""),q({kind:"main"})):(I(z.name),q({kind:"agent",id:z.id}))}async function se(){if(!U)return;const z=Y.trim(),fe=U;if(q(null),fe.kind==="main"){const Te=z||"";try{const Ne=await e.renameMain(Te);R(Ne.name)}catch{}}else{if(!z)return;const Te=b.find(Ne=>Ne.id===fe.id)?.name;_(Ne=>Ne.map(Le=>Le.id===fe.id?{...Le,name:z}:Le));try{await e.renameAgent(fe.id,z)}catch{Te!==void 0&&_(Ne=>Ne.map(Le=>Le.id===fe.id?{...Le,name:Te}:Le))}}}function Z(){q(null)}function Ee(z){me(z),KA(z)}function ye(z,fe,Te){if(z===fe)return;const Ne=Ea(he.current,re.current),Le=Ne.findIndex(mt=>mt===z),be=Ne.findIndex(mt=>mt===fe);if(Le<0||be<0)return;const $e=[...Ne],[qe]=$e.splice(Le,1);if(!qe)return;const je=$e.findIndex(mt=>mt===fe);if(je<0)return;const ht=Te==="before"?je:je+1;if($e.splice(ht,0,qe),P1($e,Ne))return;const st=O.current+1;O.current=st,he.current=$e,w($e),e.reorderAgents($e).then(mt=>{if(O.current===st){re.current=mt.agents;const xt=Ea(mt.serverOrder,mt.agents);he.current=xt,_(mt.agents),w(xt)}}).catch(async()=>{if(O.current===st)try{const mt=await e.listAgents();if(O.current===st){re.current=mt.agents;const xt=Ea(mt.serverOrder,mt.agents);he.current=xt,_(mt.agents),w(xt)}}catch{O.current===st&&(he.current=Ne,w(Ne))}})}function ze(z,fe){const Te=Ea(he.current,re.current),Ne=Te.findIndex(be=>be===z),Le=Te[Ne+fe];Ne<0||!Le||ye(z,Le,fe<0?"before":"after")}function Ke(z,fe){fe.pointerType==="mouse"&&fe.button!==0||(fe.stopPropagation(),N.current={sourceId:z,pointerId:fe.pointerId,startX:fe.clientX,startY:fe.clientY,active:!1,targetId:null,placement:"after"},fe.currentTarget.setPointerCapture?.(fe.pointerId))}function Be(z){const fe=N.current;if(!fe||fe.pointerId!==z.pointerId)return;const Te=Math.hypot(z.clientX-fe.startX,z.clientY-fe.startY);if(!fe.active){if(Te<FA)return;fe.active=!0,te(fe.sourceId)}const Le=document.elementFromPoint(z.clientX,z.clientY)?.closest("[data-server-id]"),be=Le?.dataset.serverId??null;if(!Le||!be||be===fe.sourceId){fe.targetId=null,Q(null);return}const $e=Le.getBoundingClientRect(),qe=z.clientY<$e.top+$e.height/2?"before":"after";fe.targetId=be,fe.placement=qe,Q({serverId:be,placement:qe})}function ve(z){const fe=N.current;!fe||fe.pointerId!==z.pointerId||(z.stopPropagation(),z.currentTarget.releasePointerCapture?.(z.pointerId),N.current=null,te(null),Q(null),fe.active&&fe.targetId&&ye(fe.sourceId,fe.targetId,fe.placement))}function Fe(z){const fe=N.current;fe&&fe.pointerId===z.pointerId&&z.currentTarget.releasePointerCapture?.(z.pointerId),N.current=null,te(null),Q(null)}const Ie=x?.trim()||I1,j=U?.kind==="main",ge=de==="stats",Ae=qA(b,S),Oe=Ae.length>1;return v.useEffect(()=>{l?.([...L?[{agentId:null,label:Ie}]:[],...W?b.map(z=>({agentId:z.id,label:z.name})):[]])},[b,W,Ie,L,l]),p?u.jsx("div",{className:"server-list server-list--compact",children:Ae.map(z=>{const fe=z.kind==="main",Te=fe?Ie:z.agent.name,Ne=fe?Zt:z.id,Le=X[Ne],be=_T(Le);return u.jsxs("button",{type:"button",className:`server-list-chip${(fe?t===null:t===z.id)?" server-list-chip--active":""}`,onClick:()=>n(fe?null:z.id),"aria-label":`${Te}${be?` — ${be}`:""}`,title:`${Te}${be?` — ${be}`:""}`,children:[u.jsx("span",{className:"server-list-chip-initial",children:HA(Te)}),u.jsx("span",{className:"server-list-chip-pip","data-status":zA(Le)})]},z.id)})}):u.jsxs("div",{className:`server-list server-list--${de}`,children:[u.jsxs("div",{className:"server-list-toolbar","aria-label":"Server list display",children:[u.jsx("button",{type:"button",className:"server-list-view-button","aria-pressed":de==="list",onClick:()=>Ee("list"),title:"Show server names only",children:"List"}),u.jsx("button",{type:"button",className:"server-list-view-button","aria-pressed":de==="stats",onClick:()=>Ee("stats"),title:"Show resource usage",children:"Stats"})]}),Ae.map(z=>{const fe=z.kind==="main",Te=fe?Ie:z.agent.name,Ne=fe?Zt:z.id,Le=fe?t===null:t===z.id,be=fe?j:U?.kind==="agent"&&U.id===z.id,$e=m?.({agentId:fe?null:z.id,serverId:z.id,label:Te,active:Le}),qe=J?.serverId===z.id&&K!==z.id?` server-list-section--drop-target server-list-section--drop-${J.placement}`:"";return u.jsxs("section",{className:`server-list-section${qe}`,"aria-label":`${Te} server`,children:[u.jsx("div",{className:["server-list-row",K===z.id?"server-list-row--dragging":"",J?.serverId===z.id&&K!==z.id?"server-list-row--drop-target":""].filter(Boolean).join(" "),"data-server-id":z.id,children:be?u.jsxs(u.Fragment,{children:[Oe?u.jsx("span",{className:"server-list-drag-spacer","aria-hidden":"true"}):null,u.jsx("form",{className:"server-list-editor",onSubmit:je=>{je.preventDefault(),se()},children:u.jsx("input",{ref:F,"aria-label":fe?"Rename main server":`Rename ${Te}`,value:Y,onChange:je=>I(je.target.value),onBlur:()=>{se()},onKeyDown:je=>{je.key==="Escape"&&(je.preventDefault(),Z())},placeholder:fe?I1:void 0})})]}):u.jsxs(u.Fragment,{children:[Oe?u.jsx("button",{type:"button",className:"server-list-drag-handle","data-server-drag-handle":z.id,title:"Drag to reorder","aria-label":`Reorder ${Te}`,"aria-grabbed":K===z.id,onPointerDown:je=>Ke(z.id,je),onPointerMove:Be,onPointerUp:ve,onPointerCancel:Fe,onKeyDown:je=>{(je.key==="ArrowUp"||je.key==="ArrowDown")&&(je.preventDefault(),je.stopPropagation(),ze(z.id,je.key==="ArrowUp"?-1:1))},onClick:je=>je.stopPropagation(),children:"::"}):null,u.jsxs("div",{className:`server-list-item${Le?" server-list-item--active":""}`,title:VA(Te,X[Ne]),children:[u.jsxs("div",{className:"server-list-item-header",children:[u.jsxs("button",{type:"button",className:"server-list-item-select server-list-item-select--header",onClick:()=>n(fe?null:z.id),onDoubleClick:je=>{je.preventDefault(),V(fe?"main":{id:z.id,name:Te})},children:[u.jsx("span",{className:"server-list-dot"}),u.jsx("span",{className:"server-list-name",title:fe?void 0:z.agent.url??"Outbound connection to main",children:Te})]}),d?u.jsx("span",{className:"server-list-provider-actions","aria-label":`${Te} account management`,children:["codex","claude"].map(je=>{const ht=je==="codex"?"Codex":"Claude",st=X[Ne]?.value?.accountsReloginRequired?.includes(je)===!0;return u.jsxs("button",{type:"button",className:`server-list-provider-button${st?" server-list-provider-button--attention":""}`,title:st?`Manage ${ht} accounts: a saved account needs re-login`:`Manage ${ht} accounts`,"aria-label":`Manage ${ht} accounts on ${Te}${st?" (re-login required)":""}`,onClick:()=>d({agentId:fe?null:z.id,label:Te},je),children:[u.jsx("img",{src:`/brand/${je}.webp`,alt:""}),st?u.jsx("span",{className:"server-list-provider-attention","aria-hidden":"true"}):null]},je)})}):null,f&&u.jsx("button",{type:"button",className:"server-list-provider-button",title:"Server information","aria-label":`Server information: ${Te}`,onClick:()=>f({agentId:fe?null:z.id,label:Te}),children:u.jsx(AA,{size:17})})]}),ge?u.jsx("button",{type:"button",className:"server-list-item-select server-list-item-select--stats",onClick:()=>n(fe?null:z.id),children:u.jsx(XA,{entry:X[Ne]})}):null]})]})}),$e?u.jsx("div",{className:"server-list-children",children:$e}):null]},z.id)})]})}function ZA(e,t){if(e.refresh?.state==="reauth_required")return e.refresh.code??"reauth_required";const n=e.refreshTokenExpiresAt?Date.parse(e.refreshTokenExpiresAt):NaN;return Number.isFinite(n)&&n<=t?"refresh_token_expired":null}function QA(e){return["refresh_token_invalidated","refresh_token_revoked","refresh_token_reused","invalid_grant"].includes(e)?"The provider revoked this login.":["refresh_token_expired","token_expired"].includes(e)?"Login expired.":e==="refresh_token_unavailable"?"No renewable login is stored for this account.":"The provider no longer accepts this login."}function JA(e,t){if(e.status!=="available")return e;let n=!1;const s=e.windows.map(o=>{const l=Date.parse(o.resetsAt??"");return!Number.isFinite(l)||l>t||o.estimatedReset?o:(n=!0,{...o,usedPercent:0,estimatedReset:!0})});return n?{...e,cached:!0,windows:s}:e}const eL={codex:[{host:"auth.openai.com",path:"/codex/device"}],claude:[{host:"claude.com",path:"/cai/oauth/authorize"},{host:"platform.claude.com",path:"/oauth/authorize"}]},tL=2048,nL=/^[A-Za-z0-9._~-]{8,512}#[A-Za-z0-9._~-]{8,512}$/,$1=1024;function iL(e,t){if(typeof t!="string"||t.length>tL)return null;let n;try{n=new URL(t)}catch{return null}if(n.protocol!=="https:"||n.username||n.password||n.port)return null;const s=n.hostname.toLowerCase();return eL[e].some(o=>o.host===s&&o.path===n.pathname)?n.toString():null}function rL(e,t){if(typeof t!="string"||t.length>$1+64)return null;const n=t.trim();return n.length>$1||!nL.test(n)?null:n}function sL({provider:e,serverLabel:t,api:n,disabled:s=!1,onBusyChange:o}){const[l,d]=v.useState(null),[f,m]=v.useState(!0),[p,b]=v.useState(!1),[_,S]=v.useState(null),[w,x]=v.useState(null),[R,L]=v.useState(null),A=v.useRef(null),W=v.useRef(null),H=v.useRef(null),U=v.useRef(null),q=v.useRef(null),Y=v.useRef(!1),I=v.useId(),F=v.useId(),de=e==="codex"?"Codex":"Claude",me=s||l?.reason==="preview_mode",K=F1(l),te=e==="codex"&&!!l?.installed&&!K&&l?.reason!=="hooks_disabled",J=v.useCallback(async()=>{const X=A.current;if(!X?.active||X.busy)return;const M=++X.generation;m(!0),x(null),L(null);let T=null;try{T=await n.getProviderHooks(e),X.active&&M===X.generation&&d(T)}catch(O){X.active&&M===X.generation&&x(q1(O))}finally{X.active&&M===X.generation&&m(!1)}if(!(e!=="codex"||!T?.installed||T.trust||T.reason==="preview_mode"||T.reason==="hooks_disabled"))try{const O=await n.checkProviderHookTrust(e);X.active&&M===X.generation&&!X.busy&&O.trust&&!O.trust.reason&&d(O)}catch{}},[n,e]);v.useEffect(()=>{const X={active:!0,busy:!1,generation:0};return A.current=X,d(null),S(null),b(!1),L(null),q.current=null,J(),()=>{X.active=!1}},[J]),v.useEffect(()=>{_&&!p?W.current?.focus():!p&&Y.current&&(q.current==="trust"&&U.current?U:H).current?.focus(),Y.current=!!_||p;const X=M=>{M.key!=="Escape"||!_&&!p||(M.preventDefault(),M.stopImmediatePropagation(),p||S(null))};return window.addEventListener("keydown",X,!0),()=>window.removeEventListener("keydown",X,!0)},[_,p]);async function Q(){const X=A.current;if(!(!X?.active||X.busy||me||!_)){X.busy=!0,X.generation++,b(!0),m(!1),x(null),L(null),o(!0),q.current=_;try{let M=await(_==="install"?n.installProviderHooks(e):_==="remove"?n.removeProviderHooks(e):n.trustProviderHooks(e));if(!X.active)return;d(M);let T=_==="trust";_==="install"&&e==="codex"&&M.installed&&(!M.reason||M.reason==="approval_unknown"||M.reason==="approval_required")&&(S(null),M=await n.trustProviderHooks(e),T=!0),X.active&&(d(M),S(null),T?M.trust?M.trust.reason?x(K1(M.trust.reason)):F1(M)?L(cL(M.trust)):x(K1("verification_failed")):x("Codex did not report a trust result. Use /hooks in Codex instead."):M.installed!==(_==="install")&&x(M.reason?c_(M.reason):"The requested hook change was not applied."))}catch(M){X.active&&x(q1(M))}finally{X.busy=!1,X.active&&(b(!1),o(!1))}}}return u.jsxs("section",{className:"provider-hooks","aria-labelledby":I,"aria-busy":f||p,children:[u.jsxs("div",{className:"provider-hooks-heading",children:[u.jsxs("div",{children:[u.jsxs("h3",{id:I,children:[u.jsx(rv,{size:14,"aria-hidden":"true"}),"Provider hooks"]}),u.jsx("span",{className:"provider-hooks-status",role:"status",children:f?"Checking...":l?oL(l):"Status unavailable"})]}),u.jsxs("div",{className:"provider-hooks-actions",children:[u.jsx("button",{type:"button",className:"account-icon-button",title:"Refresh hook status","aria-label":"Refresh hook status",disabled:s||f||p||!!_,onClick:()=>{J()},children:u.jsx(Il,{size:14,"aria-hidden":"true"})}),u.jsxs("button",{ref:H,type:"button",disabled:me||f||p||!l||!!_,onClick:()=>S(l?.installed?"remove":"install"),children:[l?.installed?u.jsx(B1,{size:14,"aria-hidden":"true"}):u.jsx(rv,{size:14,"aria-hidden":"true"}),l?.installed?"Remove hooks":"Install hooks"]})]})]}),l?.configPath?u.jsx("code",{className:"provider-hooks-path",children:l.configPath}):null,l?.notifyConfigPath?u.jsx("code",{className:"provider-hooks-path",children:l.notifyConfigPath}):null,l?.reason&&l.reason!=="approval_unknown"&&l.reason!=="approval_required"?u.jsxs("p",{className:"provider-hooks-reason",children:[c_(l.reason),l.reason==="unsafe_path"&&l.unsafePath?u.jsxs(u.Fragment,{children:[" ",u.jsx("code",{children:l.unsafePath})]}):null]}):null,l?.warnings?.length?u.jsx("ul",{className:"provider-hooks-warnings",children:l.warnings.map(X=>u.jsx("li",{children:uL(X)},X))}):null,e==="codex"&&K?u.jsxs("p",{className:"provider-hooks-trusted",children:["Codex reports ",lL(l?.trust?.total??l?.hookCount)," as trusted."]}):e==="codex"&&(l?.installed||l?.approvalRequired||l?.activity?.observed)&&!p?u.jsxs("p",{className:"provider-hooks-trust",children:["In Codex, open ",u.jsx("code",{children:"/hooks"})," and trust the NTerminal hooks.",l?.activity?.observed?" Events received from at least one hook; other hooks may still need approval.":null,l?.trust&&!l.trust.reason&&l.trust.pending>0?` Codex reports ${l.trust.pending} of ${l.trust.total} still need approval.`:null]}):null,te&&!p?u.jsx("div",{className:"provider-hooks-actions",children:u.jsxs("button",{ref:U,type:"button",disabled:me||f||p||!!_,onClick:()=>S("trust"),children:[u.jsx(O1,{size:14,"aria-hidden":"true"}),"Trust NTerminal hooks in Codex"]})}):null,e==="codex"&&l?.installed&&l.activity?.unboundPanes?.length?u.jsx(aL,{panes:l.activity.unboundPanes}):null,_?u.jsxs("div",{className:"provider-hooks-confirm",role:"group","aria-labelledby":F,children:[_==="trust"?u.jsxs(u.Fragment,{children:[u.jsxs("p",{id:F,children:["Trust ",W1(l?.hookCount)," Codex hooks on ",t,"?"]}),u.jsxs("p",{children:["This marks only ",W1(l?.hookCount)," Codex hooks as trusted in Codex's ",u.jsx("code",{children:"config.toml"}),", the same as pressing Trust in ",u.jsx("code",{children:"/hooks"}),". Codex performs the change; other hooks stay as they are."]}),u.jsxs("p",{children:["Trusted hooks run outside the Codex sandbox. The command it trusts is the NTerminal hook helper",l?.hookCommand?":":"."]}),l?.hookCommand?u.jsx("code",{className:"provider-hooks-path",children:l.hookCommand}):null]}):u.jsxs(u.Fragment,{children:[u.jsxs("p",{id:F,children:[_==="install"?"Install":"Remove"," ",de," hooks on ",t,"?"]}),u.jsx("p",{children:_==="install"?e==="codex"?"Install and trust only NTerminal hooks in Codex. Trusted hooks run outside the Codex sandbox; other hooks stay unchanged.":"Add NTerminal hooks to this provider's configuration?":"Remove NTerminal hooks from this provider's configuration?"})]}),u.jsxs("div",{className:"provider-hooks-actions",children:[u.jsx("button",{ref:W,type:"button",disabled:p,onClick:()=>S(null),children:"Cancel"}),u.jsxs("button",{type:"button",className:_==="remove"?"danger-button":"primary-button",disabled:me||p,onClick:()=>{Q()},children:[p?u.jsx(j1,{size:14,className:"provider-hooks-spinner","aria-hidden":"true"}):_==="install"?u.jsx(rv,{size:14,"aria-hidden":"true"}):_==="trust"?u.jsx(O1,{size:14,"aria-hidden":"true"}):u.jsx(B1,{size:14,"aria-hidden":"true"}),p?"Applying...":_==="install"?"Confirm installation":_==="trust"?"Confirm trust":"Confirm removal"]})]})]}):null,p&&!_?u.jsxs("p",{className:"provider-hooks-notice",role:"status",children:[u.jsx(j1,{size:14,className:"provider-hooks-spinner","aria-hidden":"true"})," Trusting NTerminal hooks in Codex..."]}):null,R?u.jsx("p",{className:"provider-hooks-notice",role:"status",children:R}):null,w?u.jsx("p",{className:"provider-hooks-error",role:"alert",children:w}):null]})}function aL({panes:e}){const t=e.some(o=>o.reason==="shared_daemon_same_cwd"),n=e.map(o=>o.title).filter(Boolean),s=e.length===1?"1 Codex pane is":`${e.length} Codex panes are`;return u.jsxs("p",{className:"provider-hooks-note",role:"note",children:[s," not linked to hook events",n.length?` (${n.join(", ")})`:"","."," ",t?"Codex runs sessions in a shared background server, and another session is open in the same directory, so events cannot be matched to a pane.":"Codex runs sessions in a shared background server, and NTerminal could not confirm which session belongs to the pane."," ","These panes use transcript detection instead. Run one Codex per directory, or start Codex with ",u.jsx("code",{children:"--no-daemon"}),"."]})}function oL(e){return e.installed?e.activity?.observed?"Receiving events":e.trust&&!e.trust.reason?e.trust.pending>0?"Installed; awaiting approval":"Installed and trusted; awaiting events":e.approvalRequired===!1?"Installed; awaiting events":"Installed; awaiting approval or events":e.activity?.observed?"Not installed; receiving events":"Not installed"}function F1(e){return!!(e?.installed&&e.trust&&!e.trust.reason&&e.trust.pending===0&&e.trust.total>0)}function lL(e){return e===void 0?"all NTerminal hooks":e===1?"the NTerminal hook":`all ${e} NTerminal hooks`}function W1(e){return e===void 0?"NTerminal's":`NTerminal's ${e}`}function cL(e){const t=[e.trusted===0?"All NTerminal hooks were already trusted in Codex.":`Codex trusted ${e.trusted} NTerminal hook${e.trusted===1?"":"s"}.`];return e.trusted>0&&e.alreadyTrusted>0&&t.push(`${e.alreadyTrusted} ${e.alreadyTrusted===1?"was":"were"} already trusted.`),e.skipped>0&&t.push(`${e.skipped} other hook${e.skipped===1?" was":"s were"} left unchanged.`),t.push("New Codex sessions use the trusted hooks."),t.join(" ")}function K1(e){return{codex_unavailable:"The Codex CLI was not found on this server. Trust the hooks with /hooks in Codex instead.",codex_timeout:"Codex did not respond in time. Try again, or trust the hooks with /hooks in Codex.",codex_rpc_failed:"Codex could not complete the request. Trust the hooks with /hooks in Codex instead.",hooks_not_installed:"NTerminal hooks are not installed.",hooks_not_listed:"Codex did not list every NTerminal hook exactly as installed. Nothing was trusted; reinstall the hooks or use /hooks.",verification_failed:"Codex did not confirm trust for every NTerminal hook. Check /hooks in Codex."}[e]??c_(e)}function q1(e){if(e instanceof Wn){if(e.message==="preview_mode")return"Hook changes are disabled in preview mode.";if(e.status===401)return"Your session expired. Sign in again.";if(e.status===404)return"Hook integration is unavailable on this server.";if(e.status===502)return"The remote server could not be reached."}return"The hook operation could not be completed. Refresh the status before trying again."}function c_(e){return{preview_mode:"Hook changes are disabled in preview mode.",notify_conflict:"An existing Codex notify command conflicts with this integration.",ownership_conflict:"The configuration has changed. NTerminal cannot safely update these hooks.",installation_incomplete:"The previous hook installation did not finish.",helper_missing:"The installed hook helper is missing.",helper_unavailable:"The hook helper is unavailable on this server.",node_unavailable:"The Node executable for these hooks is unavailable.",hooks_disabled:"Hooks are disabled by provider configuration or policy.",approval_unknown:"Hook trust must be checked in Codex.",approval_required:"Codex reports NTerminal hooks that still need approval.",config_malformed:"The provider configuration could not be parsed.",manifest_malformed:"The hook installation metadata could not be parsed.",config_too_large:"The provider configuration exceeds the supported size.",config_changed:"The provider configuration changed during this operation.",installation_busy:"Another hook installation operation is in progress.",lock_identity_unavailable:"The installation lock owner could not be verified. No hook settings were changed.",lock_host_mismatch:"An installation lock belongs to another host or boot identity. It was left unchanged.",lock_host_unknown:"An existing installation lock has unknown host ownership. It was left unchanged.",unsafe_path:"The hook configuration path could not be safely accessed.",installation_unavailable:"Hook installation is unavailable on this server."}[e]??"Hook status could not be verified."}function uL(e){return{notify_foreign:"Your own Codex notify command was left unchanged; hooks work alongside it.",notify_profile_override:"A Codex profile sets its own notify command, which overrides the older NTerminal notify.",profile_hooks_disabled:"A Codex profile disables hooks; sessions using it will not send events.",managed_policy_unreadable:"A managed provider policy could not be read, so hooks may be restricted.",legacy_definitions:"Older NTerminal hook definitions are installed. Reinstall to update them."}[e]??e}function dL(e){const[t,n]=v.useState({api:e.api,provider:e.provider,revision:0});return t.api!==e.api||t.provider!==e.provider?(n({api:e.api,provider:e.provider,revision:t.revision+1}),null):u.jsx(hL,{...e},t.revision)}function hL({provider:e,serverLabel:t,api:n,onClose:s}){const[o,l]=v.useState(null),[d,f]=v.useState(!0),[m,p]=v.useState(null),[b,_]=v.useState(!1),[S,w]=v.useState(null),[x,R]=v.useState(""),[L,A]=v.useState(null),[W,H]=v.useState(!1),[U,q]=v.useState(()=>Date.now()),[Y,I]=v.useState({}),[F,de]=v.useState(!0),[me,K]=v.useState(!1),[te,J]=v.useState(!1),Q=v.useRef(null),X=v.useCallback(async(N=!1)=>{const V=Q.current;if(!V?.active||V.actionPending||N&&V.statusPending)return;const se=++V.statusGeneration;V.statusPending=!0,N||(f(!0),w(null));try{const Z=await n.getAccounts();V.active&&se===V.statusGeneration&&l(Z)}catch(Z){V.active&&se===V.statusGeneration&&!N&&w(Y1(Z))}finally{V.active&&se===V.statusGeneration&&(V.statusPending=!1,N||f(!1))}},[n]),M=v.useCallback(async()=>{const N=Q.current;if(!(!N?.active||N.actionPending)&&(N.usageGeneration+=1,N.usageQueued=!0,!N.usagePending)){N.usagePending=!0,de(!0);do{N.usageQueued=!1;const V=N.usageGeneration;try{const se=await n.getAccountUsage(e);if(se.provider!==e)throw new Error("Unexpected account usage provider");N.active&&V===N.usageGeneration&&(I(Object.fromEntries(se.profiles.map(Z=>[Z.profileId,Z.usage]))),K(!1),J(!1),q(Date.now()))}catch{N.active&&V===N.usageGeneration&&(K(!0),J(!0))}}while(N.active&&N.usageQueued&&!N.actionPending);N.usagePending=!1,N.active&&de(!1)}},[n,e]),T=v.useMemo(()=>o?.providers.find(N=>N.provider===e)??null,[e,o]);v.useEffect(()=>{const N={active:!0,actionPending:!1,statusGeneration:0,statusPending:!1,usageGeneration:0,usagePending:!1,usageQueued:!1};return Q.current=N,X(),M(),()=>{N.active=!1}},[X,M]),v.useEffect(()=>{const N=V=>{V.key==="Escape"&&!V.defaultPrevented&&!m&&!b&&(W?H(!1):s())};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[s,m,b,W]),v.useEffect(()=>{const N=window.setInterval(()=>q(Date.now()),6e4);return()=>window.clearInterval(N)},[]),v.useEffect(()=>{if(!T?.pendingLogin||m)return;const V=window.setInterval(()=>{X(!0)},1500);return()=>window.clearInterval(V)},[m,T?.pendingLogin,X]),v.useEffect(()=>{if(!T?.pendingLogin)return;const N=window.setInterval(()=>q(Date.now()),15e3);return()=>window.clearInterval(N)},[T?.pendingLogin]);async function O(N,V){const se=Q.current;if(!se?.active||se.actionPending||b)return!1;se.actionPending=!0,se.statusGeneration+=1,se.statusPending=!1,se.usageGeneration+=1,K(!0),f(!1),p(N),w(null);try{const Z=await V();return se.active&&l(Z),!0}catch(Z){return se.active&&w(Y1(Z)),!1}finally{se.actionPending=!1,se.active&&(p(null),X(!0),M())}}async function re(N=null){A(N?.label??null),R(""),await O("login",()=>n.beginAccountLogin(e))}const he=e==="codex"?"Codex":"Claude";return u.jsxs("div",{className:"account-dialog-backdrop",role:"presentation",onMouseDown:N=>{N.target===N.currentTarget&&!m&&!b&&s()},children:[u.jsxs("section",{className:"account-dialog",role:"dialog","aria-modal":"true","aria-label":`${he} accounts on ${t}`,children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsxs("div",{className:"account-dialog-title",children:[u.jsx(CL,{provider:e}),u.jsxs("div",{children:[u.jsxs("h2",{children:[he," accounts"]}),u.jsx("p",{children:t})]})]}),u.jsx("button",{type:"button",className:"security-panel-close","aria-label":"Close accounts",title:"Close accounts",onClick:s,disabled:!!m||b,children:u.jsx(fp,{size:16,"aria-hidden":"true"})})]}),u.jsxs("div",{className:"account-dialog-scroll",children:[d&&!T?u.jsx("p",{className:"account-dialog-muted",children:"Loading account metadata..."}):null,T?u.jsx(fL,{provider:e,status:T,pendingAction:m??(b?"hooks":null),clock:U,usage:Y,usageLoading:F,usageStale:me,label:x,onLabelChange:R,onSelect:N=>{O(`select:${N}`,()=>n.selectAccount(e,N))},onRename:(N,V)=>O(`rename:${N}`,()=>n.renameAccount(e,N,V)),onDelete:N=>{O(`delete:${N}`,()=>n.removeAccount(e,N))},onRefresh:N=>{O(`refresh:${N}`,()=>n.refreshAccount(e,N))},onBeginLogin:()=>{re()},onRelogin:N=>{re(N)},reloginFor:L,onCompleteLogin:()=>{O("complete",()=>n.completeAccountLogin(e,x))},onCancelLogin:()=>{O("cancel",()=>n.cancelAccountLogin(e))},onSubmitCode:async N=>{await O("code",()=>n.submitAccountLoginCode(e,N))},onRequestTerminate:()=>H(!0)}):null,te?u.jsx("p",{className:"account-dialog-muted account-usage-error",role:"status",children:"Usage could not be updated. Previous readings, if any, are stale."}):null,S?u.jsx("p",{className:"account-dialog-error",role:"alert",children:S}):null,u.jsx(sL,{provider:e,serverLabel:t,api:n,disabled:!!m||W,onBusyChange:_})]}),u.jsxs("footer",{className:"account-dialog-footer",children:[u.jsxs("button",{type:"button",title:"Reload account metadata and usage; does not refresh OAuth credentials",onClick:()=>{X(),M()},disabled:d||!!m||b,children:[u.jsx(Il,{size:14,"aria-hidden":"true"}),"Refresh"]}),u.jsx("button",{type:"button",className:"secondary-button",onClick:s,disabled:!!m||b,children:"Close"})]})]}),W?u.jsx("div",{className:"account-terminate-backdrop",role:"presentation",onMouseDown:N=>{N.target===N.currentTarget&&!m&&H(!1)},children:u.jsxs("section",{className:"account-terminate-dialog",role:"alertdialog","aria-modal":"true","aria-label":`Exit all ${he} sessions`,children:[u.jsxs("h3",{children:["Exit all ",he," sessions?"]}),u.jsxs("p",{children:["This stops detected ",he," processes on ",t,", but keeps their terminal panes open. Unsaved work in those sessions may be lost."]}),e==="codex"?u.jsx("p",{children:"The shared Codex daemon will also stop. All Codex work using that daemon is affected."}):null,u.jsxs("div",{children:[u.jsx("button",{type:"button",onClick:()=>H(!1),disabled:!!m,children:"Cancel"}),u.jsx("button",{type:"button",className:"danger-button",disabled:!!m,onClick:()=>{H(!1),O("terminate",()=>n.terminateProviderSessions(e))},children:"Exit all sessions"})]})]})}):null]})}function fL({provider:e,status:t,pendingAction:n,clock:s,usage:o,usageLoading:l,usageStale:d,label:f,onLabelChange:m,onSelect:p,onRename:b,onDelete:_,onRefresh:S,onBeginLogin:w,onRelogin:x,reloginFor:R,onCompleteLogin:L,onCancelLogin:A,onSubmitCode:W,onRequestTerminate:H}){const U=t.runningProcesses??[],q=t.runningPanes.length>0||U.length>0||t.processCheckUnavailable===!0,Y=e==="codex"?"Codex":"Claude",I=t.application?.profileId===t.activeProfileId&&t.application.state==="pending",F=I?t.application?.reason??null:null,de=e==="codex"&&t.runningPanes.length===0&&U.length>0&&U.every(T=>T.role==="daemon")&&t.processCheckUnavailable!==!0,me=F==="daemon_in_use"||F==="daemon_busy"||F==="daemon_unverified"||F==="sessions_running",K=q?u.jsxs("div",{className:"account-dialog-running",role:"status",children:[u.jsx("strong",{children:de?"Only the shared Codex background server is running. Apply restarts it automatically when no Codex session is using it.":`${Y} is running. Changing accounts here does not stop these sessions; they keep their current account until restarted.`}),e==="codex"&&!de?u.jsx("small",{children:"New Codex sessions started through the shared background server may also use the previous account until that server restarts."}):null,t.runningPanes.map(T=>u.jsxs("span",{children:[u.jsx("b",{children:T.title}),u.jsx("small",{children:T.cwd})]},T.terminalId)),U.map(T=>u.jsxs("span",{children:[u.jsxs("b",{children:[T.command," ",u.jsxs("em",{children:["PID ",T.pid]})]}),u.jsx("small",{children:T.role==="daemon"?"Shared Codex daemon / manager":"Provider process on this server"})]},T.pid)),t.processCheckUnavailable?u.jsxs("span",{children:[u.jsx("b",{children:"Process check unavailable"}),u.jsx("small",{children:"Running sessions could not be listed. Refreshing the active account's credentials is paused until they can."})]}):null,!t.processCheckUnavailable&&(!de||me)?u.jsxs("button",{type:"button",className:"danger-button",disabled:!!n,onClick:H,children:["Exit all ",Y," sessions"]}):null]}):null;if(t.pendingLogin){const T=t.pendingLogin,O=T.ready&&(T.login?.phase??"done")==="done";return u.jsxs(u.Fragment,{children:[K,u.jsxs("div",{className:"account-dialog-section account-login",children:[R?u.jsxs("p",{className:"account-dialog-muted",children:["Signing in again to ",u.jsx("b",{children:R}),". Use the same account: its saved name is kept, and it becomes the active account when saved."]}):null,O?u.jsxs(u.Fragment,{children:[u.jsx("p",{children:"Sign-in completed. Name this account to save it in the server vault."}),u.jsxs("label",{className:"account-dialog-label",children:["Account name",u.jsx("input",{value:f,onChange:re=>m(re.target.value),placeholder:T.suggestedLabel??(R?"Leave blank to keep the saved name":`${Y} account`),maxLength:80,autoFocus:!0})]}),T.suggestedLabel?u.jsxs("p",{className:"account-dialog-muted account-login-suggested",children:["Leave blank to save it as ",u.jsx("b",{children:T.suggestedLabel}),". You can rename it later by clicking its name."]}):null]}):u.jsx(_L,{provider:e,pending:T,clock:s,busy:!!n,onSubmitCode:W}),u.jsxs("div",{className:"account-dialog-inline-actions",children:[O?u.jsx("button",{type:"button",className:"primary-button",disabled:!!n,onClick:L,children:"Save account"}):null,u.jsx("button",{type:"button",className:"secondary-button",disabled:!!n,onClick:A,children:"Cancel and restore previous"})]})]})]})}const te=t.lastExternalSwitch??null,J=te?t.profiles.find(T=>T.id===te.fromProfileId&&T.id!==t.activeProfileId):void 0,Q=te?.toProfileId?t.profiles.find(T=>T.id===te.toProfileId):void 0,X=J?u.jsxs("div",{className:"account-dialog-running",role:"status",children:[u.jsx("strong",{children:Q?`${Y} on this server was switched to ${Q.label} outside NTerminal, for example by a running session that still used it.`:`The ${Y} login on this server was removed outside NTerminal.`}),u.jsxs("span",{children:[J.label," is still saved. Restart old ",Y," sessions, then press Use on ",J.label,"."]})]}):null,M=t.loginNotice?.code==="login_timed_out"?u.jsx("p",{className:"account-dialog-error",role:"status",children:"The sign-in timed out and was stopped. The previous account was restored."}):null;return u.jsxs(u.Fragment,{children:[K,X,M,I?u.jsxs("p",{className:"account-dialog-error",role:"status",children:["Account saved; CLI setup is pending. ",pL(F,Y)]}):null,u.jsxs("div",{className:"account-dialog-section",children:[u.jsxs("div",{className:"account-dialog-section-heading",children:[u.jsx("span",{children:"Saved accounts"}),u.jsxs("button",{type:"button",className:"primary-button",disabled:!!n,onClick:w,children:[u.jsx(BA,{size:14,"aria-hidden":"true"}),"Add account"]})]}),t.profiles.length===0?u.jsx("p",{className:"account-dialog-muted",children:"No saved account on this server."}):t.profiles.map(T=>{const O=T.id===t.activeProfileId,re=ZA(T,s);return u.jsxs("article",{className:`account-profile${O?" account-profile--active":""}${re?" account-profile--relogin":""}`,children:[u.jsxs("div",{children:[u.jsx(mL,{profile:T,pending:n===`rename:${T.id}`,disabled:!!n,onRename:he=>b(T.id,he)}),T.email&&T.email!==T.label?u.jsx("small",{className:"account-profile-email",title:T.email,children:T.email}):null,u.jsxs("small",{title:TL(T.expiresAt),children:[O?I?"Selected (setup pending)":"Active":"Saved"," · ",kL(T.expiresAt,s)," · ",EL(T.updatedAt,s)]}),u.jsx(xL,{refresh:T.refresh,clock:s}),re?u.jsxs("div",{className:"account-relogin",role:"status","aria-label":`${T.label}: re-login required`,children:[u.jsx("span",{className:"account-relogin-badge",children:"Re-login required"}),u.jsx("span",{className:"account-relogin-reason",children:QA(re)}),u.jsxs("button",{type:"button",className:"primary-button",title:`Sign in to ${T.label} again; its saved name is kept`,disabled:!!n,onClick:()=>x(T),children:[u.jsx(OA,{size:14,"aria-hidden":"true"}),"Sign in again"]})]}):null]}),u.jsxs("div",{className:"account-profile-actions",children:[u.jsxs("button",{type:"button",title:O?`Apply ${T.label} to new CLI sessions`:`Use ${T.label}`,disabled:!!n||O&&t.application?.state==="ready",onClick:()=>p(T.id),children:[u.jsx(TA,{size:14,"aria-hidden":"true"}),O?"Apply":"Use"]}),u.jsxs("button",{type:"button",title:O&&q?t.processCheckUnavailable?"Credential refresh deferred: process check unavailable":"Managed by running CLI":"Refresh OAuth credentials (rotates tokens); does not reset usage limits",disabled:O&&q||!!n,onClick:()=>S(T.id),children:[u.jsx(LA,{size:14,"aria-hidden":"true"}),"Refresh credentials"]}),u.jsx("button",{type:"button",className:"danger-button account-icon-button","aria-label":`Remove ${T.label}`,title:`Remove ${T.label}`,disabled:!!n||O,onClick:()=>_(T.id),children:u.jsx(IA,{size:14,"aria-hidden":"true"})})]}),u.jsx(wL,{usage:o[T.id],loading:l,stale:d,clock:s})]},T.id)})]})]})}function pL(e,t){switch(e){case"sessions_running":return`Exit existing ${t} sessions, then press Apply again.`;case"daemon_in_use":return"A Codex session is still connected to the shared Codex background server or is still running a turn. Exit it, then press Apply again.";case"daemon_busy":return"The shared Codex background server is still running commands started by Codex. Wait for them to finish, or exit all Codex sessions, then press Apply again.";case"daemon_unverified":return"The shared Codex background server could not be verified for a safe restart. Exit all Codex sessions, then press Apply again.";default:return"CLI setup could not be verified. Your credentials are saved. Press Apply to retry."}}function mL({profile:e,pending:t,disabled:n,onRename:s}){const[o,l]=v.useState(null),d=v.useRef(!1),f=v.useRef(!1),m=v.useRef(null),p=v.useRef(null),b=v.useRef(!1);v.useEffect(()=>{o===null&&b.current&&(b.current=!1,m.current?.focus())},[o]);function _(){d.current=!1,b.current=!0,l(null)}async function S(){if(o===null||!d.current||f.current)return;if(o.trim()===e.label){_();return}f.current=!0;const w=await s(o);f.current=!1,d.current&&(w?_():window.setTimeout(()=>p.current?.focus(),0))}return o===null?u.jsx("span",{className:"account-profile-name",children:u.jsxs("button",{type:"button",ref:m,className:"account-profile-name-button","aria-label":`Rename ${e.label}`,title:"Click to rename",disabled:n,onClick:()=>{d.current=!0,l(e.label)},children:[u.jsx("strong",{children:e.label}),u.jsx(cT,{size:11,"aria-hidden":"true"})]})}):u.jsxs("span",{className:"account-profile-name account-profile-name--editing",children:[u.jsx("input",{ref:p,className:"account-profile-name-input","aria-label":`Account name for ${e.label}`,value:o,maxLength:80,autoFocus:!0,disabled:t,"aria-busy":t||void 0,placeholder:e.email??"Account name",onFocus:w=>w.currentTarget.select(),onChange:w=>l(w.target.value),onKeyDown:w=>{w.key==="Enter"?(w.preventDefault(),S()):w.key==="Escape"&&(w.preventDefault(),w.stopPropagation(),_())},onBlur:()=>{S()}}),t?u.jsx("small",{role:"status",children:"Saving..."}):null]})}const gL=2*6e4,vL=2e4;function _L({provider:e,pending:t,clock:n,busy:s,onSubmitCode:o}){const[l,d]=v.useState(""),[f,m]=v.useState(null),p=t.login??{phase:"starting"},b=e==="codex"?"Codex":"Claude",_=iL(e,p.verificationUrl),S=e==="codex"&&p.userCode&&/^[A-Z0-9-]{3,40}$/.test(p.userCode)?p.userCode:null,w=p.expiresAt?yy(p.expiresAt,n):null,x=p.phase==="starting"&&n-Date.parse(t.startedAt)>vL,R=p.recentOutput??[];async function L(A){A.preventDefault();const W=rL("claude",l);if(!W){m("Paste the complete code shown after approval, including the part after #.");return}m(null),await o(W),d("")}return p.phase==="failed"?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"account-dialog-error account-login-failed",role:"alert",children:p.message??`The ${b} sign-in failed.`}),u.jsx("p",{className:"account-dialog-muted",children:"Cancel to restore the previous account, then start the sign-in again."}),u.jsx(V1,{lines:R,open:!0})]}):p.phase==="starting"||!_?u.jsxs(u.Fragment,{children:[u.jsxs("p",{role:"status",children:["Starting the ",b," sign-in on the server..."]}),x?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"account-dialog-muted",children:"This is taking longer than expected. The login command may be waiting for something else."}),u.jsx(V1,{lines:R})]}):null]}):u.jsxs(u.Fragment,{children:[u.jsxs("ol",{className:"account-login-steps",children:[u.jsxs("li",{children:[u.jsx("span",{children:e==="codex"?"Open this page in any browser and sign in:":"Open this page in any browser and approve access:"}),u.jsx(bL,{url:_})]}),e==="codex"?u.jsxs("li",{children:[u.jsxs("span",{children:["Enter this one-time code",w?u.jsxs("small",{children:[" (expires ",w,")"]}):null,":"]}),S?u.jsx(yL,{code:S}):u.jsx("small",{className:"account-dialog-muted",children:"Waiting for the code..."})]}):u.jsxs("li",{children:[u.jsx("span",{children:"After approving, copy the code the page shows and paste it here:"}),u.jsxs("form",{className:"account-login-code-form",onSubmit:A=>{L(A)},children:[u.jsxs("label",{className:"account-dialog-label",children:["Authorization code",u.jsx("input",{value:l,onChange:A=>{d(A.target.value),m(null)},autoComplete:"off",autoCapitalize:"off",spellCheck:!1,maxLength:1100,disabled:s||p.phase==="completing","aria-invalid":f?!0:void 0,placeholder:"code#state"})]}),u.jsx("button",{type:"submit",className:"primary-button",disabled:s||p.phase==="completing"||!l.trim(),children:"Submit"})]})]})]}),f?u.jsx("p",{className:"account-dialog-error",role:"alert",children:f}):null,p.message&&p.phase!=="completing"?u.jsx("p",{className:"account-dialog-error",role:"alert",children:p.message}):null,u.jsx("p",{className:"account-login-waiting",role:"status",children:p.phase==="completing"?"Completing...":e==="codex"?"Waiting for approval...":"Waiting for the code..."}),u.jsxs("p",{className:"account-dialog-muted",children:["Only continue if you started this sign-in. The link and code come from the official ",b," CLI running on this server."]})]})}function V1({lines:e,open:t=!1}){return e.length===0?null:u.jsxs("details",{className:"account-login-output",open:t,children:[u.jsx("summary",{children:"Recent login output"}),u.jsx("pre",{children:e.join(`
15
+ `)})]})}function bL({url:e}){const t=v.useRef(null),[n,s]=bT();return u.jsxs("div",{className:"account-login-url",children:[u.jsx("code",{ref:t,children:e}),u.jsxs("div",{className:"account-dialog-inline-actions",children:[u.jsxs("a",{className:"account-login-open",href:e,target:"_blank",rel:"noopener noreferrer",children:[u.jsx(DA,{size:14,"aria-hidden":"true"}),"Open"]}),u.jsxs("button",{type:"button",onClick:()=>{s(e,t.current)},children:[u.jsx(hp,{size:14,"aria-hidden":"true"}),"Copy link"]}),n?u.jsx("small",{className:"account-login-copied",role:"status",children:n}):null]})]})}function yL({code:e}){const t=v.useRef(null),[n,s]=bT();return u.jsxs("div",{className:"account-login-user-code",children:[u.jsx("code",{ref:t,"aria-label":"One-time code",children:e}),u.jsxs("button",{type:"button",onClick:()=>{s(e,t.current)},children:[u.jsx(hp,{size:14,"aria-hidden":"true"}),"Copy code"]}),n?u.jsx("small",{className:"account-login-copied",role:"status",children:n}):null]})}function bT(){const[e,t]=v.useState(null),n=v.useRef(null);v.useEffect(()=>()=>{n.current!==null&&window.clearTimeout(n.current)},[]);const s=v.useCallback(async(o,l)=>{const d=await SL(o,l);t(d==="copied"?"Copied":d==="selected"?"Selected: press Ctrl+C (Cmd+C) to copy":"Copy failed: select the text manually"),n.current!==null&&window.clearTimeout(n.current),n.current=window.setTimeout(()=>t(null),d==="copied"?2e3:6e3)},[]);return[e,s]}async function SL(e,t){try{if(window.isSecureContext&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),"copied"}catch{}const n=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("textarea");s.value=e,s.setAttribute("readonly","true"),s.style.position="fixed",s.style.top="0",s.style.left="0",s.style.opacity="0",document.body.appendChild(s);try{if(s.select(),typeof document.execCommand=="function"&&document.execCommand("copy"))return"copied"}catch{}finally{s.remove(),n?.focus()}if(t){const o=window.getSelection(),l=document.createRange();return l.selectNodeContents(t),o?.removeAllRanges(),o?.addRange(l),"selected"}return"failed"}function wL({usage:e,loading:t,stale:n,clock:s}){e&&(e=JA(e,s));const o=e?.status==="available"?e.windows.filter(m=>Number.isFinite(m.usedPercent)&&m.usedPercent>=0&&m.usedPercent<=100):[],l=e?Date.parse(e.checkedAt):NaN,d=!!e&&(n||!Number.isFinite(l)||s-l>=gL||o.some(m=>m.resetsAt&&Date.parse(m.resetsAt)<=s)),f=!e&&t?"Checking weekly usage...":e?.status==="reauth_required"?"Weekly usage unavailable: sign-in required":e?.status==="unsupported"?"Weekly usage not provided":e?.code==="access_token_expired"?"Weekly usage unavailable: no saved reading":e?.code==="usage_authentication_required"?"Weekly usage unavailable: access token not accepted":"Weekly usage unavailable";return u.jsxs("div",{className:"account-quota","aria-label":"Account usage","aria-busy":t,title:"Read-only usage check; does not rotate credentials",children:[o.some(m=>m.kind==="weekly")?null:u.jsx("span",{className:"account-quota-unavailable",children:f}),["weekly","session"].map(m=>{const p=o.find(_=>_.kind===m);if(!p)return null;const b=Math.round((100-p.usedPercent)*10)/10;return u.jsxs("div",{className:"account-quota-window",children:[u.jsxs("span",{children:[m==="weekly"?"Weekly":"Session"," ",u.jsxs("b",{className:b<=10?"account-quota-critical":b<=25?"account-quota-warning":void 0,children:[b,"% remaining"]})]}),u.jsx("small",{title:p.estimatedReset?`Estimated from the previous reset time: ${Od(p.resetsAt)}. Usage since then has not been checked.`:Od(p.resetsAt),children:p.estimatedReset?"Reset (estimated)":p.resetsAt&&Number.isFinite(Date.parse(p.resetsAt))?`Resets ${yy(p.resetsAt,s)}`:"Reset time unavailable"})]},m)}),u.jsxs("small",{className:"account-quota-check",children:[e?u.jsxs(u.Fragment,{children:["Last checked ",u.jsx("time",{dateTime:e.checkedAt,children:Od(e.checkedAt)})]}):"Not yet checked",e?.cached?u.jsx("span",{children:"Cached"}):d?u.jsx("span",{className:"account-quota-warning",children:"Stale"}):null,t&&e?u.jsx("span",{children:"Updating..."}):null]}),e?.code&&e.code!=="access_token_expired"?u.jsx("small",{className:"account-diagnostic-code",children:e.code}):null]})}function xL({refresh:e,clock:t}){if(!e)return null;const n={success:"Credentials refreshed",retrying:"Credential refresh retrying",reauth_required:"Sign-in required",deferred:"Credential refresh deferred"},s=e.state==="deferred"&&e.code==="active_cli_refresh_deferred"?"Managed by running CLI":e.state==="deferred"&&e.code==="account_process_check_unavailable"?"Refresh deferred: process check unavailable":n[e.state];return u.jsxs("div",{className:`account-refresh-status account-refresh-status--${e.state}`,children:[u.jsxs("span",{children:[s,e.nextRetryAt?` · Next retry ${yy(e.nextRetryAt,t)}`:""]}),e.lastAttemptAt?u.jsxs("small",{children:["Last attempt ",Od(e.lastAttemptAt)]}):null,e.lastSuccessAt?u.jsxs("small",{children:["Last success ",Od(e.lastSuccessAt)]}):null,e.code||e.httpStatus!==null?u.jsx("small",{className:"account-diagnostic-code",children:[e.code,e.httpStatus!==null?`HTTP ${e.httpStatus}`:null].filter(Boolean).join(" · ")}):null]})}function Od(e){return e&&Number.isFinite(Date.parse(e))?new Date(e).toLocaleString():"Timestamp unavailable"}function yy(e,t){const n=Date.parse(e)-t;if(!Number.isFinite(n))return"time unavailable";if(n<=0)return"due now";const s=Math.ceil(n/6e4),o=Math.floor(s/1440),l=Math.floor(s%1440/60);return`in ${o?`${o}d `:""}${l?`${l}h `:""}${o?"":`${s%60}m`}`.trim()}function CL({provider:e}){return u.jsx("img",{className:"account-provider-mark",src:`/brand/${e}.webp`,alt:""})}function kL(e,t=Date.now()){if(!e||!Number.isFinite(Date.parse(e)))return"Access token expiry unavailable";const n=Math.ceil((Date.parse(e)-t)/6e4);if(n<=0)return"Access token expired";const s=Math.floor(n/1440),o=Math.floor(n%1440/60),l=n%60;return`Access token ${[s?`${s}d`:null,o?`${o}h`:null,`${l}m`].filter(Boolean).join(" ")} remaining`}function TL(e){return!e||!Number.isFinite(Date.parse(e))?"Access token expiry timestamp unavailable":`Access token expires ${new Date(e).toLocaleString()}`}function EL(e,t=Date.now()){const n=Math.max(0,Math.floor((t-Date.parse(e))/6e4));return!Number.isFinite(n)||n>1440?"Updated earlier":n===0?"Updated now":n<60?`Updated ${n}m ago`:`Updated ${Math.floor(n/60)}h ago`}function Y1(e){return e instanceof Wn?{provider_panes_running:"Exit this provider in every terminal, including SSH sessions, before changing accounts.",codex_daemon_stop_failed:"Could not stop the shared Codex daemon. No account was switched. Stop the daemon and try again.",account_operation_busy:"Another account operation is in progress. Try again shortly.",account_process_check_unavailable:"Could not verify running CLI processes. Refreshing the active account is paused.",active_cli_refresh_deferred:"Credentials are managed by the running CLI. Refresh is deferred.",account_credential_changed:"Credentials changed during refresh. Refresh the account list before trying again.",account_login_already_pending:"Finish or cancel the current sign-in first.",account_login_not_complete:"The provider login has not finished yet.",account_login_not_pending:"No sign-in is in progress. Start it again.",account_login_code_invalid:"Paste the complete code shown after approval, including the part after #.",account_login_code_not_expected:"The login command is not waiting for a code right now.",account_login_code_attempts_exceeded:"Too many codes were submitted. Cancel and start the sign-in again.",account_login_process_unavailable:"The login command is not running on the server. Cancel and try again.",account_refresh_failed:"The credential refresh failed. Check the account refresh status for details.",account_refresh_unavailable:"The provider refresh endpoint is temporarily unavailable.",account_reauth_required:"The account needs a new sign-in. Add the account again to update its credentials.",account_not_found:"That account is no longer saved on this server. Refresh the list.",account_label_required:"Enter a name for this account.",account_label_invalid:"Account names can be at most 80 characters.",preview_mode:"Account changes are disabled in preview mode."}[e.message]??"The account operation could not be completed.":"The account operation could not be completed."}function RL(e){const t=new Map(e.map(l=>[l.pid,{process:l,children:[],count:1,cpuPercent:l.cpuPercent,memoryBytes:l.memoryBytes}])),n=[];for(const l of t.values()){const d=t.get(l.process.ppid);d&&d!==l?d.children.push(l):n.push(l)}const s=[...n],o=new Set;for(let l=0;l<s.length;l++){const d=s[l];o.add(d.process.pid);for(const f of d.children)s.push(f)}for(const l of t.values())o.has(l.process.pid)||(l.children=[],n.push(l));for(let l=s.length-1;l>=0;l--){const d=s[l];for(const f of d.children)d.count+=f.count,d.cpuPercent+=f.cpuPercent,d.memoryBytes+=f.memoryBytes}return n}const u_=e=>e>=1024**3?`${(e/1024**3).toFixed(1)} GiB`:`${Math.round(e/1024**2)} MiB`;function NL({api:e,label:t,main:n,favorites:s,targets:o,onClose:l,onFavorite:d,onTarget:f,getRuntimeStatus:m,targetStatus:p}){const[b,_]=v.useState(null),[S,w]=v.useState(null),[x,R]=v.useState(!0),[L,A]=v.useState(!0),[W,H]=v.useState(null),[U,q]=v.useState(!1),[Y,I]=v.useState(null),[F,de]=v.useState(""),[me,K]=v.useState(!1),[te,J]=v.useState(null),Q=v.useRef(null),X=v.useRef(l);X.current=l;const M=v.useRef(!0);async function T(Z=!1){R(!0);try{const Ee=await e.getServerExternalIp(Z);M.current&&_(Ee)}catch{M.current&&_(Ee=>({address:Ee?.address??null,checkedAt:Ee?.checkedAt??null,error:"Server unavailable. Could not retrieve IPv4."}))}finally{M.current&&R(!1)}}async function O(){A(!0),H(null);try{const Z=await e.getServerProcesses();M.current&&w(Z)}catch{M.current&&H("Could not retrieve processes. The server may be offline or need an update.")}finally{M.current&&A(!1)}}v.useEffect(()=>(M.current=!0,T(),O(),()=>{M.current=!1}),[e]),v.useEffect(()=>{const Z=document.activeElement;Q.current?.focus();const Ee=ye=>{if(ye.key==="Escape"){ye.preventDefault(),ye.stopImmediatePropagation(),X.current();return}if(ye.key==="Tab"){const ze=[...Q.current?.querySelectorAll("button:not(:disabled), input:not(:disabled), summary, select")??[]].filter(Be=>Be.getClientRects().length>0),Ke=ze.indexOf(document.activeElement);ze.length&&(Ke<0||(ye.shiftKey?Ke===0:Ke===ze.length-1))&&(ye.preventDefault(),ze[ye.shiftKey?ze.length-1:0]?.focus()),ye.stopPropagation();return}Q.current?.contains(ye.target)||(ye.preventDefault(),ye.stopImmediatePropagation())};return window.addEventListener("keydown",Ee,!0),()=>{window.removeEventListener("keydown",Ee,!0),Z instanceof HTMLButtonElement&&Z.isConnected&&Z.focus({preventScroll:!0})}},[]);async function re(Z){try{await navigator.clipboard.writeText(Z),q(!1)}catch{q(!0)}}async function he(Z){if(!(me||!F.trim())){K(!0),J(null);try{const Ee=await e.renameServerProject(Z,F.trim());if(!M.current)return;w(ye=>ye&&{...ye,projects:ye.projects.map(ze=>ze.path===Z?{...ze,name:Ee.name}:ze)}),I(null)}catch{M.current&&J("Could not save project name.")}finally{M.current&&K(!1)}}}const N=v.useMemo(()=>S?.projects.filter(Z=>Z.category!=="services")??[],[S]),V=v.useMemo(()=>{const Z=S?.projects.filter(Ee=>Ee.category==="services")??[];return N.length?[...Z,{name:"Development tools",path:"",category:"tools",cpuPercent:N.reduce((Ee,ye)=>Ee+ye.cpuPercent,0),memoryBytes:N.reduce((Ee,ye)=>Ee+ye.memoryBytes,0),processes:N.flatMap(Ee=>Ee.processes)}]:Z},[S,N]);function se(Z){const Ee=Z.path?o.filter(ye=>ye.cwd===Z.path||ye.cwd.startsWith(Z.path.replace(/\/$/,"")+"/")):[];return u.jsxs(u.Fragment,{children:[Z.category!=="services"&&u.jsxs("div",{className:"server-info-tool-name",children:[u.jsx(MA,{size:15,"aria-hidden":"true"}),u.jsx("strong",{children:Z.path?Z.name:"Shared tools"})]}),u.jsxs("div",{className:"server-info-path",children:[u.jsx("code",{children:Z.path||"Shared across projects"}),Z.path&&u.jsxs(u.Fragment,{children:[u.jsx("button",{title:"Copy project path","aria-label":"Copy project path",onClick:()=>{re(Z.path)},children:u.jsx(hp,{size:14})}),u.jsx("button",{disabled:L||me,title:"Rename project","aria-label":`Rename ${Z.name}`,onClick:()=>{I(`${Z.category}:${Z.path}`),de(Z.name),J(null)},children:u.jsx(cT,{size:14})})]})]}),Y===`${Z.category}:${Z.path}`&&u.jsxs("form",{className:"server-info-rename",onSubmit:ye=>{ye.preventDefault(),he(Z.path)},children:[u.jsx("input",{"aria-label":"Project display name",maxLength:80,value:F,disabled:me,onChange:ye=>de(ye.target.value)}),u.jsx("button",{type:"submit",title:"Save name","aria-label":"Save project name",disabled:me||!F.trim(),children:u.jsx(Xk,{size:16})}),u.jsx("button",{type:"button",title:"Cancel rename","aria-label":"Cancel rename",disabled:me,onClick:()=>I(null),children:u.jsx(fp,{size:16})}),te&&u.jsx("small",{role:"alert",className:"server-info-error",children:te})]}),Z.path&&u.jsx("div",{className:"server-info-targets",children:Ee.length?Ee.map(ye=>u.jsxs("button",{onClick:()=>f(ye),title:`Open ${ye.label}`,children:[u.jsx(EA,{size:14}),ye.label]},ye.terminalId)):u.jsx("button",{disabled:!0,children:p??"No open tab"})}),u.jsx(DL,{processes:Z.processes})]})}return u.jsx("div",{className:"server-info-backdrop",onMouseDown:Z=>{Z.target===Z.currentTarget&&l()},children:u.jsxs("section",{className:"server-info",role:"dialog","aria-modal":"true","aria-label":`Server information: ${t}`,tabIndex:-1,ref:Q,onKeyDown:Z=>Z.stopPropagation(),children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{children:t}),u.jsx("small",{children:n?"Main":"Secondary"})]}),u.jsx("button",{title:"Close","aria-label":"Close server information",onClick:l,children:u.jsx(fp,{size:18})})]}),u.jsxs("div",{className:"server-info-body",children:[u.jsxs("section",{children:[u.jsxs("div",{className:"server-info-ip",children:[u.jsx("h3",{title:"External IPv4",children:"IPv4"}),u.jsx("code",{title:b?.checkedAt?`Checked ${new Date(b.checkedAt).toLocaleString()}`:void 0,children:b?.address??(x?"Loading...":"Unavailable")}),u.jsxs("span",{className:"server-info-ip-actions",children:[b?.address&&u.jsx("button",{title:"Copy IPv4","aria-label":"Copy IPv4",onClick:()=>{re(b.address)},children:u.jsx(hp,{size:16})}),u.jsx("button",{disabled:x,title:"Refresh external IPv4","aria-label":"Refresh external IPv4",onClick:()=>{T(!0)},children:u.jsx(Il,{size:16})})]})]}),b?.error&&u.jsx("p",{role:"status",className:"server-info-error",children:b.error})]}),u.jsxs("section",{children:[u.jsx("h3",{children:"Favorites"}),u.jsx("div",{className:"server-info-favorites",children:s.map(Z=>u.jsxs("button",{onClick:()=>d(Z),children:[u.jsx("strong",{children:Z.tabName}),u.jsxs("small",{children:[Z.workspaceName," · ",m?.(Z)?.state??"Not loaded"]}),u.jsx("span",{children:Z.providers.map(Ee=>u.jsx("img",{alt:Ee,src:`/brand/${Ee}.webp`},Ee))})]},`${Z.workspaceId}:${Z.tabId}`))}),!s.length&&u.jsx("small",{children:"No favorite tabs on this server."})]}),u.jsxs("section",{children:[u.jsxs("div",{className:"server-info-heading",children:[u.jsx("h3",{children:"Projects"}),u.jsx("button",{disabled:L||me,title:"Refresh processes","aria-label":"Refresh processes",onClick:()=>{O()},children:u.jsx(Il,{size:16})})]}),L&&u.jsx("p",{role:"status",children:"Sampling processes..."}),W&&u.jsx("p",{role:"alert",className:"server-info-error",children:W}),S&&u.jsxs("small",{children:["Sampled ",new Date(S.checkedAt).toLocaleTimeString()," · CPU: 100% = 1 core · Memory: summed RSS"]}),V.map(Z=>u.jsxs(ST,{className:"server-info-project",children:[u.jsxs("summary",{children:[u.jsxs("span",{className:"server-info-project-label",children:[u.jsx(Jk,{className:"server-info-chevron",size:16,"aria-hidden":"true"}),u.jsx("strong",{title:Z.name,children:Z.name}),u.jsx("small",{className:"server-info-project-location",title:Z.path,children:Z.path}),u.jsx("small",{className:"server-info-project-count",title:`${Z.processes.length} processes`,children:Z.processes.length})]}),u.jsxs("span",{className:"server-info-metrics",children:[u.jsxs("span",{children:[Z.cpuPercent.toFixed(1),"%"]}),u.jsx("span",{children:u_(Z.memoryBytes)})]})]}),u.jsx("div",{className:"server-info-project-body",children:Z.category==="services"?se(Z):N.map(Ee=>u.jsx("div",{className:"server-info-tool-project",children:se(Ee)},`${Ee.category}:${Ee.path}`))})]},`${Z.category}:${Z.path}`)),S&&!S.projects.length&&u.jsx("p",{children:"No processes found for the runtime user."})]}),U&&u.jsx("p",{role:"status",children:"Clipboard unavailable. Select the address or path to copy."})]})]})})}function DL({processes:e}){const t=v.useMemo(()=>RL(e),[e]);return u.jsx("div",{className:"server-info-process-list",children:t.map(n=>u.jsx("div",{className:"server-info-process-root",children:u.jsx(yT,{node:n})},n.process.pid))})}function yT({node:e}){const t=e.process,n=u.jsxs(u.Fragment,{children:[u.jsxs("span",{className:"server-info-process-label",children:[e.children.length?u.jsx(Jk,{className:"server-info-chevron",size:14,"aria-hidden":"true"}):u.jsx("span",{className:"server-info-process-dot","aria-hidden":"true"}),u.jsxs("span",{children:[u.jsx("strong",{children:t.name}),u.jsxs("small",{children:["PID ",t.pid," · ",t.manager??"Unmanaged",e.count>1?` · ${e.count} processes · Total`:""]})]})]}),u.jsxs("span",{className:"server-info-metrics",title:e.count>1?"Total for this process and its descendants":"Process usage",children:[u.jsxs("span",{children:[e.cpuPercent.toFixed(1),"%"]}),u.jsx("span",{children:u_(e.memoryBytes)})]})]});return e.children.length?u.jsxs(ST,{className:"server-info-process-group",children:[u.jsx("summary",{className:"server-info-process",children:n}),u.jsxs("div",{className:"server-info-process-children",children:[u.jsxs("div",{className:"server-info-process",children:[u.jsxs("span",{children:[u.jsx("strong",{children:t.name}),u.jsxs("small",{children:["PID ",t.pid," · Parent"]})]}),u.jsxs("span",{className:"server-info-metrics",children:[u.jsxs("span",{children:[t.cpuPercent.toFixed(1),"%"]}),u.jsx("span",{children:u_(t.memoryBytes)})]})]}),e.children.map(s=>u.jsx(yT,{node:s},s.process.pid))]})]}):u.jsx("div",{className:"server-info-process",children:n})}function ST({children:e,className:t}){const[n,s]=v.useState(!1),[o,...l]=zt.Children.toArray(e);return u.jsxs("details",{className:t,onToggle:d=>{d.target===d.currentTarget&&s(d.currentTarget.open)},children:[o,n?l:null]})}function ML({api:e}){const[t,n]=v.useState([]),[s,o]=v.useState([]),[l,d]=v.useState(!1),[f,m]=v.useState(null),[p,b]=v.useState(""),[_,S]=v.useState("");async function w(){try{const[A,W,H]=await Promise.all([e.listDevices(),e.listNetworks(),e.getSession()]);n(A.devices),o(W.networks),d(H.totpEnabled),m(null)}catch(A){m(A instanceof Error?A.message:"Failed to load")}}v.useEffect(()=>{w()},[]);async function x(A){await e.revokeDevice(A),await w()}async function R(A){await e.removeNetwork(A),await w()}async function L(A){A.preventDefault(),m(null);try{await e.addNetwork({value:p.trim(),label:_.trim()}),b(""),S(""),await w()}catch(W){m(W instanceof Error?W.message:"Failed to add network")}}return u.jsxs(u.Fragment,{children:[f?u.jsx("p",{className:"form-error",children:f}):null,u.jsxs("section",{className:"security-section",children:[u.jsx("h3",{children:"Trusted devices"}),u.jsx("p",{className:"muted",children:"Devices that can re-authenticate with a 2FA code only (no password) for 30 days."}),t.length===0?u.jsx("p",{className:"muted",children:"No trusted devices."}):u.jsx("ul",{className:"security-list",children:t.map(A=>u.jsxs("li",{children:[u.jsxs("div",{children:[u.jsxs("span",{className:"security-item-label",children:[A.label,A.current?u.jsx("span",{className:"security-badge",children:"this device"}):null]}),u.jsxs("span",{className:"security-item-meta",children:["last seen ",new Date(A.lastSeenAt).toLocaleString()]})]}),u.jsx("button",{type:"button",className:"security-remove",onClick:()=>{x(A.id)},children:"revoke"})]},A.id))})]}),u.jsxs("section",{className:"security-section",children:[u.jsx("h3",{children:"Trusted networks"}),u.jsx("p",{className:"muted",children:"Sessions from these IPs/ranges skip the 2FA re-auth prompt."}),s.length===0?u.jsx("p",{className:"muted",children:"No trusted networks."}):u.jsx("ul",{className:"security-list",children:s.map(A=>u.jsxs("li",{children:[u.jsxs("div",{children:[u.jsx("span",{className:"security-item-label",children:A.value}),A.label!==A.value?u.jsx("span",{className:"security-item-meta",children:A.label}):null]}),u.jsx("button",{type:"button",className:"security-remove",onClick:()=>{R(A.id)},children:"remove"})]},A.id))}),u.jsxs("form",{className:"security-add-form",onSubmit:L,children:[u.jsx("input",{type:"text",placeholder:"IP or CIDR (e.g. 203.0.113.4 or 192.168.0.0/24)",value:p,onChange:A=>b(A.currentTarget.value),required:!0}),u.jsx("input",{type:"text",placeholder:"Label (optional)",value:_,onChange:A=>S(A.currentTarget.value)}),u.jsx("button",{type:"submit",disabled:!p.trim(),children:"Add"})]})]}),l?u.jsxs("section",{className:"security-section",children:[u.jsx("h3",{children:"Two-factor authentication"}),u.jsx("p",{className:"muted",children:"2FA is enabled. Disabling it removes the requirement; you will be asked to set it up again on next login."}),u.jsx("button",{type:"button",className:"security-remove",onClick:async()=>{await e.disableTotp(),await w()},children:"Disable 2FA"})]}):null]})}const AL=1500,Sy="nterminal.terminal.fontSize",wy="nterminal.terminal.fontFamily",d_="nterminal:terminal-font-size",h_="nterminal:terminal-font-family",f_=11,p_=20,Ml=14,pp=[{id:"meslo",label:"MesloLGS NF",cssFamily:['"MesloLGS NF"','"MesloLGS Nerd Font Mono"','"MesloLGSNerdFontMono"','"JetBrainsMono Nerd Font"','"Hack Nerd Font"','"FiraCode Nerd Font"','"SF Mono"',"Menlo","Monaco","Consolas",'"Liberation Mono"','"Symbols Nerd Font Mono"','"Apple Symbols"','"Apple Color Emoji"',"monospace"].join(", "),webFontFamilies:['"MesloLGS NF"']},{id:"jetbrains",label:"JetBrains Mono",cssFamily:['"JetBrainsMono Nerd Font"','"JetBrains Mono"','"Hack Nerd Font"','"FiraCode Nerd Font"','"SF Mono"',"Menlo","Monaco","Consolas",'"Liberation Mono"','"Symbols Nerd Font Mono"','"Apple Symbols"','"Apple Color Emoji"',"monospace"].join(", "),webFontFamilies:[]},{id:"system",label:"System mono",cssFamily:['"SF Mono"',"Menlo","Monaco","Consolas",'"Liberation Mono"','"Symbols Nerd Font Mono"','"Apple Symbols"','"Apple Color Emoji"',"monospace"].join(", "),webFontFamilies:[]}],Zc="meslo";m_(Zc);async function sv(e=Ml,t=Zc){if(typeof document>"u"||!document.fonts)return;const n=CT(t).webFontFamilies;if(n.length===0)return;const s=Promise.all(n.map(o=>document.fonts.load(`${e}px ${o}`))).then(()=>{}).catch(()=>{});await Promise.race([s,new Promise(o=>{globalThis.setTimeout(o,AL)})])}function wT(e){const t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return Ml;const n=Math.round(t);return Math.max(f_,Math.min(p_,n))}function xT(e){return pp.some(t=>t.id===e)?e:Zc}function m_(e){return CT(e).cssFamily}function CT(e){return pp.find(t=>t.id===e)??pp[0]}function g_(){if(typeof window>"u")return Ml;try{const e=window.localStorage.getItem(Sy);return e?wT(e):Ml}catch{return Ml}}function v_(){if(typeof window>"u")return Zc;try{return xT(window.localStorage.getItem(wy))}catch{return Zc}}function xf(e){const t=wT(e);if(typeof window>"u")return t;try{window.localStorage.setItem(Sy,String(t))}catch{}return window.dispatchEvent(new CustomEvent(d_,{detail:t})),t}function LL(e){const t=xT(e);if(typeof window>"u")return t;try{window.localStorage.setItem(wy,t)}catch{}return window.dispatchEvent(new CustomEvent(h_,{detail:t})),t}function kT(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===Sy&&e()};return window.addEventListener(d_,e),window.addEventListener("storage",t),()=>{window.removeEventListener(d_,e),window.removeEventListener("storage",t)}}function TT(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===wy&&e()};return window.addEventListener(h_,e),window.addEventListener("storage",t),()=>{window.removeEventListener(h_,e),window.removeEventListener("storage",t)}}const Kd=3,ET=1,RT=5,NT=30;function xy(e){return Number.isFinite(e)?Math.max(ET,Math.min(RT,Math.round(e))):Kd}function jL(e,t){const n=Number.isFinite(t)?Math.max(1,Math.min(NT,Math.trunc(t))):1;return n===1?e:e.replace(/\x1b\[<(\d+);\d+;\d+M/g,(s,o)=>{const l=Number(o)&-29;return l===64||l===65?s.repeat(n):s})}class OL{remainder=0;direction=0;scale=0;reset(){this.remainder=0,this.direction=0,this.scale=0}consume(t,n,s){if(!Number.isFinite(t)||!Number.isFinite(n)||n<=0)return this.reset(),0;if(t===0)return 0;const o=xy(s)/(n*3),l=Math.sign(t);(l!==this.direction||o!==this.scale)&&(this.remainder=0),this.direction=l,this.scale=o;const d=this.remainder+Math.abs(t)*o,f=Math.floor(d+1e-9);return this.remainder=Math.max(0,d-f),l*Math.min(NT,f)}}const Cy="nterminal.terminal.showScrollProgress",__="nterminal:terminal-scroll-progress",ky="nterminal.terminal.tmuxScrollback.shell",Ty="nterminal.terminal.tmuxScrollback.agent",Ey="nterminal.terminal.tmuxScrollback.overrides",Qc="nterminal:terminal-tmux-scrollback",BL=200,mp="nterminal.terminal.codexScrollSpeed";let b_=Kd,gp=!1;function y_(){if(typeof window>"u")return Kd;if(gp)return b_;try{const e=window.localStorage.getItem(mp);return e===null||e.trim()===""?Kd:xy(Number(e))}catch{return b_}}function IL(e){const t=xy(e);if(b_=t,typeof window<"u"){try{window.localStorage.setItem(mp,String(t)),gp=!1}catch{gp=!0}window.dispatchEvent(new CustomEvent(Qc))}return t}function S_(){if(typeof window>"u")return!0;try{return window.localStorage.getItem(Cy)!=="false"}catch{return!0}}function PL(e){if(typeof window<"u"){try{window.localStorage.setItem(Cy,e?"true":"false")}catch{}window.dispatchEvent(new CustomEvent(__,{detail:e}))}return e}function DT(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===Cy&&e()};return window.addEventListener(__,e),window.addEventListener("storage",t),()=>{window.removeEventListener(__,e),window.removeEventListener("storage",t)}}function w_(){return MT(ky,!0)}function zL(e){return AT(ky,e,Qc)}function x_(){return MT(Ty,!0)}function HL(e){return AT(Ty,e,Qc)}function _d(e){if(typeof window>"u")return()=>{};const t=n=>{(n.key===mp||n.key===null)&&(gp=!1),(n.key===ky||n.key===Ty||n.key===mp||n.key===null||n.key===Ey)&&e()};return window.addEventListener(Qc,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Qc,e),window.removeEventListener("storage",t)}}function av(e){const n=LT()[e];return typeof n=="boolean"?n:null}function UL(e,t){if(typeof window<"u"){try{const n=LT(),s=Object.entries(n).filter(([l])=>l!==e);s.push([e,t]);const o=s.slice(-BL);window.localStorage.setItem(Ey,JSON.stringify(Object.fromEntries(o)))}catch{}window.dispatchEvent(new CustomEvent(Qc,{detail:{terminalId:e,enabled:t}}))}return t}function MT(e,t){if(typeof window>"u")return t;try{const n=window.localStorage.getItem(e);if(n==="true")return!0;if(n==="false")return!1}catch{}return t}function AT(e,t,n){if(typeof window<"u"){try{window.localStorage.setItem(e,t?"true":"false")}catch{}window.dispatchEvent(new CustomEvent(n,{detail:t}))}return t}function LT(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(Ey);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};const n={};for(const[s,o]of Object.entries(t))typeof o=="boolean"&&(n[s]=o);return n}catch{return{}}}const Ry="nterminal.shortcuts.workspace.v1",C_="nterminal:workspace-shortcuts",qd=[{id:"server.previous",label:"Previous workspace",group:"Workspaces"},{id:"server.next",label:"Next workspace",group:"Workspaces"},{id:"tab.previous",label:"Previous tab",group:"Tabs"},{id:"tab.next",label:"Next tab",group:"Tabs"},{id:"tab.index",label:"Select tab 1-9",group:"Tabs",indexed:!0},{id:"pane.index",label:"Select pane 1-9",group:"Panes",indexed:!0},{id:"split.right",label:"Split right",group:"Panes"},{id:"split.down",label:"Split down",group:"Panes"},{id:"history.toggle",label:"Toggle view history",group:"Panes",requiresPrimaryModifier:!0},{id:"subagents.toggle",label:"Toggle view agents",group:"Panes",requiresPrimaryModifier:!0},{id:"scrollback.toggle",label:"Toggle tmux scrollback",group:"Panes",requiresPrimaryModifier:!0},{id:"favorites.toggle",label:"Open favorite tabs",group:"Tabs",requiresPrimaryModifier:!0}],em={"server.previous":xn("ArrowUp",{ctrlKey:!0}),"server.next":xn("ArrowDown",{ctrlKey:!0}),"tab.previous":xn("ArrowLeft",{ctrlKey:!0}),"tab.next":xn("ArrowRight",{ctrlKey:!0}),"tab.index":xn("Digit",{ctrlKey:!0,altKey:!0}),"pane.index":xn("Digit",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.right":xn("ArrowRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.down":xn("ArrowDown",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"history.toggle":xn("KeyH",{altKey:!0}),"subagents.toggle":xn("KeyA",{altKey:!0}),"scrollback.toggle":xn("KeyS",{altKey:!0}),"favorites.toggle":xn("KeyF",{ctrlKey:!0,altKey:!0})},$L={"server.previous":xn("BracketLeft",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"server.next":xn("BracketRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"tab.previous":xn("BracketLeft",{ctrlKey:!0,altKey:!0}),"tab.next":xn("BracketRight",{ctrlKey:!0,altKey:!0}),"tab.index":xn("Digit",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"pane.index":xn("Digit",{ctrlKey:!0,altKey:!0}),"split.right":xn("ArrowRight",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"split.down":xn("ArrowDown",{ctrlKey:!0,altKey:!0,shiftKey:!0}),"history.toggle":xn("KeyH",{altKey:!0}),"subagents.toggle":xn("KeyA",{altKey:!0}),"scrollback.toggle":xn("KeyS",{altKey:!0}),"favorites.toggle":xn("KeyF",{ctrlKey:!0,altKey:!0})};function Pl(){const e=BT(em);if(typeof window>"u")return e;try{const t=window.localStorage.getItem(Ry);if(!t)return e;const n=JSON.parse(t);for(const s of qd){const o=n[s.id];if(XL(o)){const l=IT(o,s);GL(l,$L[s.id])||(e[s.id]=l)}}}catch{return e}return e}function G1(){return JSON.stringify(Pl())}function FL(e,t){const n=Pl(),s=qd.find(o=>o.id===e);return s&&(n[e]=IT(t,s),Ny(n)),n}function WL(e){const t=Pl();return t[e]={...em[e]},Ny(t),t}function KL(){const e=BT(em);return Ny(e),e}function Bd(e){if(typeof window>"u")return()=>{};const t=n=>{n.key===Ry&&e()};return window.addEventListener(C_,e),window.addEventListener("storage",t),()=>{window.removeEventListener(C_,e),window.removeEventListener("storage",t)}}function qL(e,t){const n=HT(e);return!n||QL(n)||t.indexed&&zT(e)===null||t.requiresPrimaryModifier&&!PT(e)?null:{ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey,metaKey:e.metaKey,code:t.indexed?"Digit":n}}function jT(e){const t=Pl();for(const n of qd){const s=t[n.id];if(!(!s||!ZL(e,s))){if(n.indexed){if(s.code!=="Digit")continue;const o=zT(e);if(o!==null)return{id:n.id,index:o};continue}if(HT(e)===s.code)return{id:n.id,index:null}}}return null}function Id(e){return OT(Pl()[e])}function OT(e){const t=[];return e.ctrlKey&&t.push("Ctrl"),e.altKey&&t.push("Alt"),e.shiftKey&&t.push("Shift"),e.metaKey&&t.push("Meta"),t.push(JL(e.code)),t.join("+")}const VL=()=>Id("split.right"),YL=()=>Id("split.down");function xn(e,t){return{ctrlKey:t.ctrlKey??!1,altKey:t.altKey??!1,shiftKey:t.shiftKey??!1,metaKey:t.metaKey??!1,code:e}}function BT(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{...n}]))}function GL(e,t){return e.ctrlKey===t.ctrlKey&&e.altKey===t.altKey&&e.shiftKey===t.shiftKey&&e.metaKey===t.metaKey&&e.code===t.code}function Ny(e){if(!(typeof window>"u")){try{window.localStorage.setItem(Ry,JSON.stringify(e))}catch{}window.dispatchEvent(new CustomEvent(C_))}}function IT(e,t){return t.requiresPrimaryModifier&&!PT(e)?{...em[t.id]}:{ctrlKey:!!e.ctrlKey,altKey:!!e.altKey,shiftKey:!!e.shiftKey,metaKey:!!e.metaKey,code:t.indexed?"Digit":e.code}}function PT(e){return e.ctrlKey||e.altKey||e.metaKey}function XL(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.ctrlKey=="boolean"&&typeof t.altKey=="boolean"&&typeof t.shiftKey=="boolean"&&typeof t.metaKey=="boolean"&&typeof t.code=="string"&&t.code.length>0}function ZL(e,t){return e.ctrlKey===t.ctrlKey&&e.altKey===t.altKey&&e.shiftKey===t.shiftKey&&e.metaKey===t.metaKey}function zT(e){const t=/^Digit([1-9])$/.exec(e.code);return t?.[1]?Number(t[1]):/^[1-9]$/.test(e.key)?Number(e.key):null}function HT(e){if(e.code)return e.code;if(/^[a-z]$/i.test(e.key))return`Key${e.key.toUpperCase()}`;if(/^[0-9]$/.test(e.key))return`Digit${e.key}`;switch(e.key){case"[":case"{":return"BracketLeft";case"]":case"}":return"BracketRight";case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":case"Tab":case"Enter":case"Escape":case"Space":return e.key==="Space"?"Space":e.key;default:return null}}function QL(e){return e==="ControlLeft"||e==="ControlRight"||e==="AltLeft"||e==="AltRight"||e==="ShiftLeft"||e==="ShiftRight"||e==="MetaLeft"||e==="MetaRight"}function JL(e){if(e==="Digit")return"1-9";const t=/^Digit([0-9])$/.exec(e);if(t?.[1])return t[1];const n=/^Key([A-Z])$/.exec(e);if(n?.[1])return n[1];switch(e){case"BracketLeft":return"[";case"BracketRight":return"]";case"ArrowLeft":return"Left";case"ArrowRight":return"Right";case"ArrowUp":return"Up";case"ArrowDown":return"Down";case"Space":return"Space";default:return e.replace(/^(Numpad|Digit|Key)/,"")}}const ej="Automatic update needs write access to the global npm install. Run this from a normal NTerminal runtime-user shell; only the npm install step uses sudo.";function tj(e="nterminal",t=new Date){return{reason:"permission",message:ej,command:`sudo npm i -g ${e}@latest --prefer-online && nterminal restart-after-update`,detectedAt:t.toISOString()}}function nj(e){return/\b(?:EACCES|EPERM)\b|permission denied|missing write access|access denied|operation was rejected by your operating system|operation not permitted|root-owned files/i.test(e)}const UT=3600*1e3,ij="local",k_=new Set,Do=new Map;let Po={checking:!1,hasUpdates:!1,lastCheckedAt:null},Dy=null,Pd=null,vp=0,ko=null;function rj(e){return k_.add(e),()=>{k_.delete(e)}}function X1(){return Po}function sj(e){const t=uj();Dy=e,My(),T_(e,t);const n=()=>{if(document.visibilityState!=="visible"||!zo(e,t))return;const s=Po.lastCheckedAt;(s===null||Date.now()-s>=UT)&&T_(e,t)};return document.addEventListener("visibilitychange",n),()=>{document.removeEventListener("visibilitychange",n),zo(e,t)&&cj()}}function aj(e,t){Do.set(e,$T(t)),Jc({...Po,hasUpdates:Ay(),lastCheckedAt:Date.now()})}function ov(e){e===void 0?Do.clear():Do.set(e,!1),Jc({...Po,hasUpdates:Ay()})}async function T_(e,t){if(!zo(e,t))return;if(ko&&ko.api===e&&ko.runId===t)return ko.promise;Jc({...Po,checking:!0});const n=oj(e,t).finally(()=>{ko?.promise===n&&(ko=null),zo(e,t)&&(Jc({...Po,checking:!1,lastCheckedAt:Date.now()}),lj(e,t))});return ko={api:e,runId:t,promise:n},n}async function oj(e,t){try{const n=await e.listAgents();if(!zo(e,t))return;const s=[{key:ij,check:()=>e.checkUpdate()},...n.agents.map(l=>({key:l.id,check:()=>e.checkAgentUpdate(l.id)}))],o=new Map;if(await Promise.all(s.map(async l=>{try{const d=await l.check();o.set(l.key,$T(d))}catch{o.set(l.key,Do.get(l.key)??!1)}})),!zo(e,t))return;Do.clear();for(const[l,d]of o)Do.set(l,d);Jc({...Po,hasUpdates:Ay()})}catch{}}function lj(e,t){zo(e,t)&&(My(),Pd=window.setTimeout(()=>{Pd=null,zo(e,t)&&T_(e,t)},UT))}function cj(){vp+=1,My(),Dy=null,ko=null,Do.clear(),Jc({checking:!1,hasUpdates:!1,lastCheckedAt:null})}function My(){Pd!==null&&(window.clearTimeout(Pd),Pd=null)}function uj(){return vp+=1,vp}function zo(e,t){return Dy===e&&vp===t}function $T(e){return e.updateAvailable===!0}function Ay(){return Array.from(Do.values()).some(Boolean)}function Jc(e){Po=e;for(const t of Array.from(k_))t()}const dj=e=>new Promise(t=>setTimeout(t,e));function hj({api:e,onAgentRemoved:t}){const[n,s]=v.useState([{key:"local",id:null,name:"Local"}]),[o,l]=v.useState({}),[d,f]=v.useState(!1),[m,p]=v.useState(null),[b,_]=v.useState(!1),[S,w]=v.useState({});function x(T,O){l(re=>({...re,[T]:{...re[T],...O}}))}function R(T,O){w(re=>({...re,[T]:{status:re[T]?.status??null,busy:re[T]?.busy??!1,error:re[T]?.error??null,...O}}))}const L=T=>T.id===null?e.getVersion():e.getAgentVersion(T.id),A=T=>T.id===null?e.checkUpdate():e.checkAgentUpdate(T.id),W=T=>T.id===null?e.runUpdate():e.runAgentUpdate(T.id),H=T=>T.id===null?e:Is(T.id);v.useEffect(()=>{let T=!1;return e.listAgents().then(async O=>{if(T)return;let re="Local";try{re=(await e.getMainInfo()).name?.trim()||re}catch{}if(T)return;const he=new Map(O.agents.map(V=>[V.id,V])),N=Ea(O.serverOrder,O.agents).flatMap(V=>{if(V===Zt)return[{key:"local",id:null,name:re}];const se=he.get(V);return se?[{key:se.id,id:se.id,name:se.name}]:[]});s(N);for(const V of N)L(V).then(se=>x(V.key,{version:se,manualUpdate:se.manualUpdate??null})).catch(se=>x(V.key,{error:se instanceof Error?se.message:"unreachable"})),Q(V)}).catch(()=>{}),()=>{T=!0}},[]);async function U(T){x(T.key,{busy:!0,status:"checking…",error:void 0});try{const O=await A(T);aj(T.key,O),x(T.key,{latestVersion:O.latestVersion,updateAvailable:O.updateAvailable,status:K(O),...O.updateAvailable===!1?{manualUpdate:null}:{},busy:!1})}catch(O){x(T.key,{busy:!1,error:O instanceof Error?O.message:"check failed"})}}async function q(){f(!0),await Promise.all(n.map(T=>U(T))),f(!1)}async function Y(T,O){const re=Date.now()+18e4;for(;Date.now()<re;){await dj(3e3);try{const he=await L(T);if(O&&he.runningVersion!==O.runningVersion)return he}catch{}}return null}async function I(T){let O=o[T.key]?.version;if(!O)try{O=await L(T),x(T.key,{version:O,manualUpdate:O.manualUpdate??null})}catch(N){return x(T.key,{busy:!1,error:N instanceof Error?N.message:"version check failed"}),"failed"}x(T.key,{busy:!0,status:"updating…",error:void 0});let re;try{re=await W(T)}catch(N){return x(T.key,{busy:!1,error:N instanceof Error?N.message:"update failed"}),"failed"}if(!re.ok){const N=re.manualUpdate??(nj(re.message)?tj():null);return N?(x(T.key,{busy:!1,status:"manual update required",error:void 0,manualUpdate:N}),"manual"):(x(T.key,{busy:!1,status:void 0,error:re.message}),"failed")}if(!re.changed)return x(T.key,{busy:!1,status:"already up to date",updateAvailable:!1,manualUpdate:null}),ov(T.key),"unchanged";x(T.key,{status:"restarting…"});const he=await Y(T,O);return he?(x(T.key,{busy:!1,version:he,updateAvailable:!1,status:"updated",manualUpdate:he.manualUpdate??null}),ov(T.key),T.id===null&&(_(!0),p("Main server updated. Reload the page to use the new client.")),"updated"):(x(T.key,{busy:!1,status:void 0,error:"timed out — check the server log"}),"failed")}async function F(T){if(!(T.id===null||!window.confirm([`Delete secondary server "${T.name}"?`,"","If the secondary is reachable, NTerminal will schedule a clean uninstall on that host, stop its runtime, remove its local state, and remove it from this main server.","If it is already gone or unreachable, only the stale registration on this main server will be removed.","","This can close live terminals on that secondary. Continue?"].join(`
16
+ `)))){x(T.key,{busy:!0,status:"deleting…",error:void 0}),p(null);try{const re=await e.uninstallAgent(T.id);s(he=>he.filter(N=>N.key!==T.key)),l(he=>{const N={...he};return delete N[T.key],N}),ov(T.key),t?.(T.id),p(re.message)}catch(re){x(T.key,{busy:!1,status:void 0,error:re instanceof Error?re.message:"delete failed"})}}}async function de(){f(!0),p(null);const T=n.filter(se=>se.id!==null),O=n.find(se=>se.id===null),re=await Promise.all(T.map(se=>I(se))),he=re.filter(se=>se==="failed").length;let N=re.filter(se=>se==="manual").length,V=null;if(O&&(V=await I(O),V==="manual"&&(N+=1),V==="updated")){he>0&&p("Main server updated. Reload the page to use the new client. Some secondary servers failed; check their rows and retry."),f(!1);return}he>0&&N>0?p("Some servers failed and some need manual update. Check each marked row."):he>0?p("Some secondary servers failed to update. Check their rows and retry."):N>0&&p("Some servers need manual update. Copy and run the command shown on each marked server."),f(!1)}function me(T){return T?T.error?T.error:T.status?T.status:T.manualUpdate?"manual update required":T.version?`v${T.version.version}`:"…":"…"}function K(T){return T.error?T.error:typeof T.updateAvailable=="boolean"?T.updateAvailable?`latest v${T.latestVersion??"available"}`:"up to date":"unknown"}function te(T){const O=T?.version;return O?`npm package v${O.runningVersion}`:""}async function J(T,O){try{await pj(O),x(T,{copiedCommand:!0}),window.setTimeout(()=>x(T,{copiedCommand:!1}),1800)}catch(re){x(T,{error:re instanceof Error?re.message:"copy failed"})}}async function Q(T,O=!1){try{const re=await H(T).getCodeServerStatus(O?{checkLatest:!0}:void 0);R(T.key,{status:re,error:null})}catch(re){R(T.key,{error:re instanceof Error?re.message:"code-server status failed"})}}async function X(T,O){if(O==="uninstall"&&!window.confirm(`Uninstall the VS Code add-on on ${T.name} and stop its running VS Code sessions?`))return;const re=H(T);R(T.key,{busy:!0,error:null});try{if(O==="install"){const he=await re.installCodeServer();R(T.key,{status:he.status})}else if(O==="update"){const he=await re.updateCodeServer();R(T.key,{status:he.status})}else{const he=await re.uninstallCodeServer();R(T.key,{status:he.status})}}catch(he){R(T.key,{error:he instanceof Error?he.message:"code-server action failed"})}finally{R(T.key,{busy:!1})}}const M=n.filter(T=>S[T.key]?.status?.job?.status==="running").map(T=>T.key).join("|");return v.useEffect(()=>{const T=n.filter(re=>S[re.key]?.status?.job?.status==="running");if(T.length===0)return;const O=window.setInterval(()=>{for(const re of T)Q(re)},1e3);return()=>window.clearInterval(O)},[M]),u.jsxs("section",{className:"security-section",children:[u.jsx("h3",{children:"Servers"}),u.jsxs("div",{className:"update-actions",children:[u.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{q()},disabled:d,children:"Check for updates"}),u.jsx("button",{type:"button",onClick:()=>{de()},disabled:d,children:"Update all"})]}),m?u.jsx("p",{className:"settings-status",children:m}):null,b?u.jsxs("div",{className:"server-reload-required",role:"status",children:[u.jsx("span",{children:"Main server update is ready."}),u.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload page"})]}):null,u.jsx("ul",{className:"security-list",children:n.map(T=>{const O=o[T.key],re=te(O),he=O?.manualUpdate??null,N=S[T.key]??{status:null,busy:!1,error:null},V=O?.version!==void 0&&O?.updateAvailable!==!1&&!O?.busy&&!d,se=T.id!==null&&!O?.busy&&!d;return u.jsxs("li",{children:[u.jsxs("div",{className:"server-row-main",children:[u.jsxs("div",{children:[u.jsxs("span",{className:"security-item-label",children:[T.name,T.id===null?u.jsx("span",{className:"security-badge",children:"Main"}):null]}),u.jsxs("span",{className:"security-item-meta",children:[re?`${re} — `:"",me(O)]})]}),he?u.jsxs("div",{className:"server-manual-update",children:[u.jsx("span",{children:he.message}),u.jsxs("div",{className:"server-manual-command",children:[u.jsx("code",{children:he.command}),u.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{J(T.key,he.command)},children:O?.copiedCommand?"Copied":"Copy"})]})]}):null,u.jsx(fj,{status:N.status,busy:N.busy,error:N.error,onCheck:()=>{Q(T,!0)},onInstall:()=>{X(T,"install")},onUpdate:()=>{X(T,"update")},onUninstall:()=>{X(T,"uninstall")}})]}),u.jsxs("div",{className:"server-row-actions",children:[u.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{I(T)},disabled:!V,children:O?.busy?"…":"Update"}),T.id!==null?u.jsx("button",{type:"button",className:"server-delete-button",onClick:()=>{F(T)},disabled:!se,children:"Delete"}):null]})]},T.key)})})]})}function fj({status:e,busy:t,error:n,onCheck:s,onInstall:o,onUpdate:l,onUninstall:d}){const f=e?.job??null,m=f?.status==="running",p=e!==null,b=e?.installed===!0,_=e?.supported!==!1,S=e===null&&!n;return u.jsxs("div",{className:"server-code-addon-inline",children:[u.jsxs("div",{className:"server-code-addon-summary",children:[u.jsx("img",{className:"server-code-addon-mark",src:"/brand/vscode.png",width:"14",height:"14",alt:"","aria-hidden":"true",draggable:!1}),u.jsxs("span",{className:"security-item-meta",children:[_?S?"checking...":b?`code-server v${e?.version??"unknown"}`:"not installed":e?.unsupportedReason??"unsupported",e?.updateAvailable?" — update available":""]})]}),n?u.jsx("p",{className:"settings-error",children:n}):null,f?u.jsx("span",{className:"server-code-addon-job",children:f.status==="running"?`${f.action}...`:`${f.action} ${f.status}`}):null,u.jsxs("div",{className:"server-code-addon-actions","aria-label":"VS Code add-on actions",children:[u.jsx("a",{className:"server-code-addon-icon-button",href:"https://github.com/coder/code-server",target:"_blank",rel:"noreferrer",title:"Open code-server on GitHub","aria-label":"Open code-server on GitHub",children:"↗"}),b?u.jsxs(u.Fragment,{children:[e?.updateAvailable?u.jsx("button",{type:"button",className:"server-code-addon-icon-button",onClick:l,disabled:t||m||!_,title:"Update code-server","aria-label":"Update code-server",children:"↑"}):u.jsx("button",{type:"button",className:"server-code-addon-icon-button",onClick:s,disabled:t||m||!_,title:"Check code-server updates","aria-label":"Check code-server updates",children:"↻"}),u.jsx("button",{type:"button",className:"server-code-addon-icon-button server-code-addon-icon-button--delete",onClick:d,disabled:t||m,title:"Uninstall code-server","aria-label":"Uninstall code-server",children:"×"})]}):u.jsx("button",{type:"button",className:"server-code-addon-icon-button",onClick:o,disabled:!p||S||t||m||!_,title:"Install code-server","aria-label":"Install code-server",children:"↓"})]})]})}async function pj(e){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{if(!document.execCommand("copy"))throw new Error("copy failed")}finally{t.remove()}}const Cf=[{id:"appearance",label:"Appearance"},{id:"shortcuts",label:"Shortcuts"},{id:"notifications",label:"Notifications"},{id:"security",label:"Security"},{id:"servers",label:"Servers"}];function mj({onClose:e,api:t,updateAvailable:n=!1,onNotificationAssetsChanged:s,onAgentRemoved:o}){const l=v.useMemo(()=>t??Hp(),[t]),[d,f]=v.useState(()=>g_()),[m,p]=v.useState(()=>v_()),[b,_]=v.useState(()=>S_()),[S,w]=v.useState(()=>w_()),[x,R]=v.useState(()=>x_()),[L,A]=v.useState(()=>y_()),[W,H]=v.useState(()=>Bo()),[U,q]=v.useState(()=>Pl()),[Y,I]=v.useState(null),[F,de]=v.useState(null),[me,K]=v.useState("appearance"),[te,J]=v.useState(()=>vy()),[Q,X]=v.useState(()=>Bl()),[M,T]=v.useState(()=>au()),[O,re]=v.useState([]),[he,N]=v.useState([]),[V,se]=v.useState([]),[Z,Ee]=v.useState(5*1024*1024),[ye,ze]=v.useState(!1),[Ke,Be]=v.useState(null),[ve,Fe]=v.useState(null),[Ie,j]=v.useState(!1),[ge,Ae]=v.useState(null),[Oe,z]=v.useState(null),fe=v.useRef(null),Te=v.useRef(null),Ne=v.useRef({appearance:null,shortcuts:null,notifications:null,security:null,servers:null}),Le=v.useMemo(()=>new Set(he),[he]),be=!vj(he,V),$e=v.useMemo(()=>Jp(),[]),qe=ve?.displayMode==="standalone"&&(ve.deviceKind==="mobile"||ve.deviceKind==="tablet");v.useEffect(()=>kT(()=>f(g_())),[]),v.useEffect(()=>TT(()=>p(v_())),[]),v.useEffect(()=>DT(()=>_(S_())),[]),v.useEffect(()=>_d(()=>{w(w_()),R(x_()),A(y_())}),[]),v.useEffect(()=>ny(()=>H(Bo())),[]),v.useEffect(()=>Bd(()=>q(Pl())),[]),v.useEffect(()=>Ik(()=>X(Bl())),[]),v.useEffect(()=>{if(!Y)return;const ae=qd.find(tt=>tt.id===Y);if(!ae)return;const Pe=tt=>{if(tt.preventDefault(),tt.stopPropagation(),tt.key==="Escape"){I(null),de(null);return}const _t=qL(tt,ae);if(!_t){de(gj(ae));return}q(FL(Y,_t)),I(null),de(null)};return window.addEventListener("keydown",Pe,!0),()=>window.removeEventListener("keydown",Pe,!0)},[Y]),v.useEffect(()=>{let ae=!1;return l.listNotificationAssets().then(Pe=>{ae||ot(Pe)}).catch(Pe=>{ae||Be(Oc(Pe))}),()=>{ae=!0}},[l]),v.useEffect(()=>{let ae=!1;return l.getPushNotificationStatus(Da()).then(Pe=>{ae||(Fe(Pe.currentDevice),Ae(null))}).catch(Pe=>{ae||Ae(Oc(Pe))}),()=>{ae=!0}},[l]);function je(ae){f(xf(Number(ae)))}function ht(ae){X(M1(Number(ae)))}function st(ae){K(ae);const Pe=Te.current,tt=Ne.current[ae];if(!Pe||!tt)return;const _t=Math.max(0,Z1(tt,Pe)-12);typeof Pe.scrollTo=="function"?Pe.scrollTo({top:_t,behavior:"smooth"}):Pe.scrollTop=_t}function mt(){const ae=Te.current;if(!ae)return;if(ae.scrollTop+ae.clientHeight>=ae.scrollHeight-2){K(Cf[Cf.length-1].id);return}let Pe="appearance";const tt=ae.scrollTop+Math.min(180,Math.max(48,ae.clientHeight*.28));for(const _t of Cf){const $t=Ne.current[_t.id];$t&&Z1($t,ae)<=tt&&(Pe=_t.id)}K(Pe)}function xt(ae){q(WL(ae)),I(null),de(null)}function on(){q(KL()),I(null),de(null)}function ot(ae){const Pe=ae.assets.filter(tt=>tt.enabled).map(tt=>tt.id);re(ae.assets),N(Pe),se(Pe),Ee(ae.maxFileBytes),Be(null)}async function Dn(){if(te){D1(!1),J(!1);return}let ae=M;ae==="default"&&(ae=await zk(),T(ae)),ae==="granted"&&(D1(!0),J(!0))}async function Tn(){j(!0),Ae(null),z(null);try{if(ve)await aA(l),Fe(null);else{await iA(l,!1);const ae=await l.getPushNotificationStatus(Da());Fe(ae.currentDevice)}}catch(ae){Ae(cv(ae))}finally{j(!1)}}async function ft(ae){j(!0),Ae(null),z(null);try{await oA(l,ae);const Pe=await l.getPushNotificationStatus(Da());Fe(Pe.currentDevice)}catch(Pe){Ae(cv(Pe))}finally{j(!1)}}async function Dt(){j(!0),Ae(null),z(null);try{await l.testPushNotification({clientId:Da()}),z("Test notification accepted by the push service.")}catch(ae){Ae(cv(ae))}finally{j(!1)}}async function Mt(ae){const Pe=ae?.[0];if(Pe){if(Pe.size>Z){Be(`File must be ${lv(Z)} or smaller.`),di();return}if(Pe.type!=="video/mp4"&&Pe.type!=="video/webm"){Be("Upload an MP4 or WebM video."),di();return}ze(!0),Be(null);try{await l.uploadNotificationAsset(Pe),ot(await l.listNotificationAssets()),s?.()}catch(tt){Be(Oc(tt))}finally{ze(!1),di()}}}async function wi(ae){ze(!0),Be(null);try{await l.deleteNotificationAsset(ae),ot(await l.listNotificationAssets()),s?.()}catch(Pe){Be(Oc(Pe))}finally{ze(!1)}}function di(){fe.current&&(fe.current.value="")}function xi(ae,Pe){const tt=new Set(he);if(Pe?tt.add(ae):tt.delete(ae),tt.size===0){Be("Keep at least one toast video selected.");return}Be(null),N(Array.from(tt))}async function At(){if(he.length===0){Be("Keep at least one toast video selected.");return}ze(!0),Be(null);try{const ae=await l.updateNotificationAssetSelection({enabledAssetIds:he});ot(ae),s?.()}catch(ae){Be(Oc(ae))}finally{ze(!1)}}return u.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-label":"Settings",onClick:e,children:u.jsxs("div",{className:"security-panel settings-panel",onClick:ae=>ae.stopPropagation(),children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsx("h2",{children:"Settings"}),u.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:e,children:"×"})]}),u.jsxs("div",{className:"settings-layout",children:[u.jsx("nav",{className:"settings-nav","aria-label":"Settings categories",children:Cf.map(ae=>u.jsxs("button",{type:"button","data-active":me===ae.id?"true":"false","aria-current":me===ae.id?"true":void 0,onClick:()=>st(ae.id),children:[ae.label,ae.id==="servers"&&n?u.jsx("span",{className:"update-pulse-dot settings-update-dot","aria-hidden":"true"}):null]},ae.id))}),u.jsxs("div",{ref:Te,className:"settings-content",onScroll:mt,children:[u.jsxs("section",{id:"settings-appearance",ref:ae=>{Ne.current.appearance=ae},className:"security-section settings-section",children:[u.jsx("h3",{children:"Appearance"}),u.jsx("div",{className:"settings-section-heading",children:u.jsxs("div",{children:[u.jsx("span",{className:"settings-control-title",children:"Theme"}),u.jsx("p",{className:"muted settings-control-description",children:"Choose the workspace and terminal color preset."})]})}),u.jsx("div",{className:"settings-theme-picker",role:"radiogroup","aria-label":"Interface theme",children:rp.map(ae=>u.jsxs("button",{type:"button",className:"settings-theme-card",role:"radio","aria-checked":W===ae.id,"data-active":W===ae.id?"true":"false",onClick:()=>H(DN(ae.id)),style:{"--settings-theme-bg":ae.tokens.bg,"--settings-theme-bg-2":ae.tokens.bg2,"--settings-theme-sidebar":ae.tokens.bgSidebar,"--settings-theme-line":ae.tokens.line,"--settings-theme-fg":ae.tokens.fg,"--settings-theme-fg-2":ae.tokens.fg2,"--settings-theme-accent":ae.tokens.accent,"--settings-theme-xterm-bg":ae.xterm.background,"--settings-theme-xterm-fg":ae.xterm.foreground,"--settings-theme-xterm-selection":ae.xterm.selectionBackground},children:[u.jsxs("span",{className:"settings-theme-preview","aria-hidden":"true",children:[u.jsxs("span",{className:"settings-theme-preview-sidebar",children:[u.jsx("span",{}),u.jsx("span",{}),u.jsx("span",{})]}),u.jsxs("span",{className:"settings-theme-preview-main",children:[u.jsxs("span",{className:"settings-theme-preview-tabs",children:[u.jsx("span",{}),u.jsx("span",{})]}),u.jsxs("span",{className:"settings-theme-preview-terminal",children:[u.jsx("span",{}),u.jsx("span",{}),u.jsx("span",{})]})]})]}),u.jsxs("span",{className:"settings-theme-card-copy",children:[u.jsx("strong",{children:ae.label}),u.jsx("small",{children:ae.description})]})]},ae.id))}),u.jsxs("label",{className:"settings-control",children:[u.jsx("span",{children:"Font size"}),u.jsxs("span",{className:"settings-control-value",children:[d,"px"]}),u.jsx("input",{type:"range",min:f_,max:p_,step:1,value:d,"aria-label":"Terminal font size",onChange:ae=>je(ae.currentTarget.value)})]}),u.jsxs("div",{className:"settings-stepper-row",children:[u.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>f(xf(d-1)),children:"-"}),u.jsx("input",{type:"number",min:f_,max:p_,step:1,value:d,"aria-label":"Terminal font size value",onChange:ae=>je(ae.currentTarget.value)}),u.jsx("button",{type:"button",className:"secondary-button settings-stepper-button",onClick:()=>f(xf(d+1)),children:"+"}),u.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:()=>f(xf(Ml)),children:"Reset"})]}),u.jsxs("label",{className:"settings-control",children:[u.jsx("span",{children:"Font family"}),u.jsx("select",{value:m,"aria-label":"Terminal font family",onChange:ae=>p(LL(ae.currentTarget.value)),children:pp.map(ae=>u.jsx("option",{value:ae.id,children:ae.label},ae.id))})]}),u.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[u.jsx("input",{type:"checkbox",checked:b,onChange:ae=>_(PL(ae.currentTarget.checked))}),"Show scroll progress"]}),u.jsx("div",{className:"settings-section-heading",children:u.jsxs("div",{children:[u.jsx("span",{className:"settings-control-title",children:"Scrollback source"}),u.jsx("p",{className:"muted settings-control-description",children:"Choose whether wheel and touch scroll input use tmux scrollback by default."})]})}),u.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[u.jsx("input",{type:"checkbox",checked:S,onChange:ae=>w(zL(ae.currentTarget.checked))}),"Shell panes"]}),u.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[u.jsx("input",{type:"checkbox",checked:x,onChange:ae=>R(HL(ae.currentTarget.checked))}),"Codex/Claude panes"]}),u.jsxs("label",{className:"settings-control",children:[u.jsx("span",{children:"Codex scroll speed"}),u.jsxs("span",{className:"settings-control-value",children:[L,"x"]}),u.jsx("input",{type:"range",min:ET,max:RT,step:1,value:L,"aria-label":"Codex scroll speed","aria-valuetext":`${L}x`,onChange:ae=>A(IL(Number(ae.currentTarget.value)))})]})]}),u.jsxs("section",{id:"settings-shortcuts",ref:ae=>{Ne.current.shortcuts=ae},className:"security-section settings-section",children:[u.jsxs("div",{className:"settings-section-heading",children:[u.jsx("h3",{children:"Shortcuts"}),u.jsx("button",{type:"button",className:"secondary-button settings-reset-button",onClick:on,children:"Reset all"})]}),u.jsx("p",{className:"muted",children:"Defaults avoid Chrome's browser-tab shortcuts. Click a shortcut, then press the new key combo."}),F?u.jsx("p",{className:"settings-error",children:F}):null,u.jsx("ul",{className:"settings-shortcut-list","aria-label":"Workspace shortcuts",children:qd.map(ae=>{const Pe=Y===ae.id;return u.jsxs("li",{children:[u.jsxs("div",{children:[u.jsx("span",{className:"settings-shortcut-label",children:ae.label}),u.jsx("span",{className:"settings-shortcut-group",children:ae.group})]}),u.jsxs("div",{className:"settings-shortcut-actions",children:[u.jsx("button",{type:"button",className:"settings-shortcut-recorder","data-recording":Pe?"true":"false",onClick:()=>{I(ae.id),de(null)},children:Pe?"Press keys…":OT(U[ae.id])}),u.jsx("button",{type:"button",className:"secondary-button settings-shortcut-reset",onClick:()=>xt(ae.id),children:"Reset"})]})]},ae.id)})})]}),u.jsxs("section",{id:"settings-notifications",ref:ae=>{Ne.current.notifications=ae},className:"security-section settings-section",children:[u.jsx("h3",{children:"Notifications"}),Qp()?u.jsxs(u.Fragment,{children:[u.jsxs("label",{className:"auth-checkbox",children:[u.jsx("input",{type:"checkbox",checked:te&&M==="granted",onChange:()=>{Dn()},disabled:M==="denied"}),"System notification when page is hidden"]}),M==="denied"?u.jsx("p",{className:"muted",children:"Notification permission is blocked for this site. Re-enable it in the browser's site settings, then come back here to turn the toggle on."}):u.jsx("p",{className:"muted",children:"Uses browser notifications only when this page isn't visible. Animated toast is controlled separately below."})]}):u.jsx("p",{className:"muted",children:"This browser doesn't expose the Notification API; animated toast and in-app badges can still work."}),u.jsxs("div",{className:"settings-subsection",children:[u.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[u.jsx("input",{type:"checkbox",checked:!!ve,onChange:()=>{Tn()},disabled:Ie||!$e.supported}),"Installed app push notifications"]}),u.jsx("p",{className:"muted",children:"Sends native completion alerts to this installed PWA when no live page can show the usual in-app or browser notification."}),$e.supported?null:u.jsx("p",{className:"muted",children:Uf($e.reason)}),ve?u.jsxs(u.Fragment,{children:[u.jsxs("p",{className:"muted",children:["Registered as ",ve.label,". Last active ",new Date(ve.lastActiveAt).toLocaleString(),"."]}),u.jsx("button",{type:"button",className:"secondary-button settings-push-test-button",onClick:()=>{Dt()},disabled:Ie,children:"Send test notification"})]}):null,qe?u.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[u.jsx("input",{type:"checkbox",checked:ve?.alwaysNotify===!0,onChange:ae=>{ft(ae.currentTarget.checked)},disabled:Ie||!ve}),"Always notify this mobile device"]}):null,ge?u.jsx("p",{className:"form-error",children:ge}):null,Oe?u.jsx("p",{className:"muted",role:"status",children:Oe}):null]}),u.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[u.jsx("input",{type:"checkbox",checked:Q.enabled,onChange:ae=>X(YM(ae.currentTarget.checked))}),"Show animated completion toast"]}),u.jsxs("label",{className:"settings-control",children:[u.jsx("span",{children:"Toast duration"}),u.jsx("span",{className:"settings-control-value",children:Q.persistUntilDismissed?"Until closed":`${Q.durationSeconds}s`}),u.jsx("input",{type:"range",min:i_,max:r_,step:.5,value:Q.durationSeconds,disabled:!Q.enabled||Q.persistUntilDismissed,"aria-label":"Completion toast duration",onChange:ae=>ht(ae.currentTarget.value)})]}),u.jsxs("div",{className:"settings-stepper-row settings-duration-row",children:[u.jsx("input",{type:"number",min:i_,max:r_,step:.5,value:Q.durationSeconds,disabled:!Q.enabled||Q.persistUntilDismissed,"aria-label":"Completion toast duration value",onChange:ae=>ht(ae.currentTarget.value)}),u.jsx("button",{type:"button",className:"secondary-button settings-reset-button",disabled:!Q.enabled||Q.persistUntilDismissed,onClick:()=>X(M1(jd)),children:"Reset"})]}),u.jsxs("label",{className:"auth-checkbox settings-checkbox",children:[u.jsx("input",{type:"checkbox",checked:Q.persistUntilDismissed,disabled:!Q.enabled,onChange:ae=>X(GM(ae.currentTarget.checked))}),"Keep toast until dismissed"]}),u.jsxs("div",{className:"settings-assets-header",children:[u.jsx("span",{children:"Toast videos"}),u.jsxs("span",{children:[lv(Z)," max"]})]}),u.jsx("input",{ref:fe,type:"file",accept:"video/mp4,video/webm",className:"settings-asset-input","aria-label":"Upload toast video",onChange:ae=>{Mt(ae.currentTarget.files)}}),u.jsx("button",{type:"button",className:"secondary-button settings-upload-button",disabled:ye,onClick:()=>fe.current?.click(),children:"Upload video"}),Ke?u.jsx("p",{className:"settings-error",children:Ke}):null,O.length>0?u.jsx("ul",{className:"settings-asset-list","aria-label":"Toast videos",children:O.map(ae=>u.jsxs("li",{"data-enabled":Le.has(ae.id)?"true":"false",children:[u.jsxs("label",{className:"settings-asset-choice",children:[u.jsx("input",{type:"checkbox",checked:Le.has(ae.id),disabled:ye,"aria-label":`Use ${ae.filename}`,onChange:Pe=>xi(ae.id,Pe.currentTarget.checked)}),u.jsx("video",{src:ae.url,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"}),u.jsxs("span",{className:"settings-asset-copy",children:[u.jsx("span",{children:ae.filename}),u.jsx("small",{children:ae.source==="built-in"?"Built-in":lv(ae.size)})]})]}),ae.source==="uploaded"?u.jsx("button",{type:"button",className:"secondary-button settings-asset-delete",disabled:ye,"aria-label":`Delete ${ae.filename}`,onClick:()=>{wi(ae.id)},children:"x"}):null]},ae.id))}):u.jsx("p",{className:"muted",children:"Built-in videos will be used."}),u.jsx("button",{type:"button",className:"secondary-button settings-save-assets-button",disabled:ye||O.length===0||!be,onClick:()=>{At()},children:"Save selected videos"})]}),u.jsx("div",{id:"settings-security",ref:ae=>{Ne.current.security=ae},className:"settings-section-group",children:u.jsx(ML,{api:l})}),u.jsx("div",{id:"settings-servers",ref:ae=>{Ne.current.servers=ae},className:"settings-section-group",children:u.jsx(hj,{api:l,...o?{onAgentRemoved:o}:{}})})]})]})]})})}function Z1(e,t){const n=e.getBoundingClientRect(),s=t.getBoundingClientRect();return n.top-s.top+t.scrollTop}function lv(e){return e>=1024*1024?`${Math.round(e/1024/1024*10)/10} MB`:e>=1024?`${Math.round(e/1024*10)/10} KB`:`${e} B`}function Oc(e){return e instanceof Error?e.message:"Request failed."}function Uf(e){return e==="insecure"?"Installed app push notifications require HTTPS or localhost.":e==="not_standalone"?"Install NTerminal as an app first. On iOS, add it to the Home Screen before enabling push.":e==="not_mobile"?"Installed app push notifications are available on mobile and tablet devices.":"This browser does not support installed app push notifications."}function cv(e){const t=Oc(e);return t==="permission_denied"?"Notification permission was not granted.":t==="not_standalone"?Uf("not_standalone"):t==="insecure"?Uf("insecure"):t==="not_mobile"?Uf("not_mobile"):t==="push_subscription_not_found"?"This app is no longer registered for push. Turn installed app notifications off and on again.":t==="push_delivery_failed"?"The push service rejected the test notification. Check Android notification permission and try re-registering this app.":t}function gj(e){return e.indexed?"Press a shortcut ending in a number from 1 to 9.":e.requiresPrimaryModifier?"Use Ctrl, Alt, or Meta with another key.":"Press a complete shortcut."}function vj(e,t){if(e.length!==t.length)return!1;const n=new Set(t);return e.every(s=>n.has(s))}const _j="modulepreload",bj=function(e){return"/"+e},Q1={},Ly=function(t,n,s){let o=Promise.resolve();if(n&&n.length>0){let m=function(p){return Promise.all(p.map(b=>Promise.resolve(b).then(_=>({status:"fulfilled",value:_}),_=>({status:"rejected",reason:_}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),f=d?.nonce||d?.getAttribute("nonce");o=m(n.map(p=>{if(p=bj(p),p in Q1)return;Q1[p]=!0;const b=p.endsWith(".css"),_=b?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${_}`))return;const S=document.createElement("link");if(S.rel=b?"stylesheet":_j,b||(S.as="script"),S.crossOrigin="",S.href=p,f&&S.setAttribute("nonce",f),document.head.appendChild(S),b)return new Promise((w,x)=>{S.addEventListener("load",w),S.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${p}`)))})}))}function l(d){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=d,window.dispatchEvent(f),!f.defaultPrevented)throw d}return o.then(d=>{for(const f of d||[])f.status==="rejected"&&l(f.reason);return t().catch(l)})},yj=v.lazy(()=>Ly(()=>import("./MarkdownPreview-Dz-gstWx.js"),__vite__mapDeps([0,1])));function Sj({api:e,activeTerminalId:t,activeTerminalCwd:n,workspaceRootPath:s=null,onOpenFile:o}){const[l,d]=v.useState(null),[f,m]=v.useState(""),[p,b]=v.useState({}),[_,S]=v.useState(()=>new Set),[w,x]=v.useState(null),[R,L]=v.useState({type:"empty"}),[A,W]=v.useState("idle"),[H,U]=v.useState(null),q=v.useRef(null),Y=v.useRef(null),I=v.useRef(!1),F=v.useRef(0),de=v.useRef(null);de.current===null&&t&&(de.current=t);const me=de.current,K=s?xj(s):t?J1(t,n):null,te=l?[l.rootPath,f].filter(Boolean).join("/"):"",J=w?.path??null;v.useEffect(()=>(I.current=!0,()=>{I.current=!1,F.current+=1,Fe()}),[]),v.useEffect(()=>{de.current=t,Y.current=null,Q(K)},[e]),v.useEffect(()=>{s&&K!==Y.current&&X(s,K)},[s,K]),v.useEffect(()=>{if(s||!me||t!==me)return;const z=J1(me,n);z!==Y.current&&M(me,z)},[me,t,n,s]);async function Q(z=K){if(s){await X(s,z);return}await M(t,z)}async function X(z,fe=K){const Te=Ie();if(Y.current=fe,Fe(),d(null),m(""),b({}),S(new Set),x(null),L({type:"empty"}),U(null),!z){W("idle");return}W("loading");try{const Ne=await e.createFileRoot({path:z});if(!j(Te))return;d({rootToken:Ne.rootToken,rootPath:Ne.rootPath});const Le=await e.listFiles({rootToken:Ne.rootToken,path:""});if(!j(Te))return;re(Le),W("idle")}catch(Ne){j(Te)&&(U(wa(Ne)),W("idle"))}}async function M(z,fe=K){const Te=Ie();if(Y.current=fe,Fe(),d(null),m(""),b({}),S(new Set),x(null),L({type:"empty"}),U(null),!z){W("idle");return}W("loading");try{const Ne=await e.createFileRoot({terminalId:z});if(!j(Te))return;d({rootToken:Ne.rootToken,rootPath:Ne.rootPath});const Le=await e.listFiles({rootToken:Ne.rootToken,path:""});if(!j(Te))return;re(Le),W("idle")}catch(Ne){if(await ge(Ne,Te))return;j(Te)&&(U(wa(Ne)),W("idle"))}}async function T(z=f,fe=l){if(!fe)return;const Te=Ie();W("loading"),U(null);try{const Ne=await e.listFiles({rootToken:fe.rootToken,path:z});if(!j(Te))return;re(Ne),W("idle")}catch(Ne){if(await ge(Ne,Te))return;j(Te)&&(U(wa(Ne)),W("idle"))}}async function O(){if(s){await X(s,K);return}de.current=t,await M(t,K)}function re(z){b(fe=>({...fe,[z.path]:Cj(z.entries)}))}async function he(z){if(!(!uv(z)||!l)){if(x(z),U(null),z.kind==="directory"){m(z.path),ve(),await V(z);return}if(m(xl(z.path)),z.editable){await Z(z);return}z.previewKind!=="none"&&await ye(z,z.previewKind)}}async function N(z){if(!(!uv(z)||!l)){if(x(z),U(null),z.kind==="directory"){m(z.path),ve(),await V(z);return}if(m(xl(z.path)),z.editable){await Ee(z);return}z.previewKind!=="none"&&await ye(z,z.previewKind)}}async function V(z){if(_.has(z.path)){S(fe=>{const Te=new Set(fe);return Te.delete(z.path),Te});return}S(fe=>new Set(fe).add(z.path)),await T(z.path)}function se(z,fe){z.key==="Enter"&&(z.preventDefault(),N(fe))}async function Z(z){if(!l)return;const fe=Ie();W("loading"),Fe();try{const Te=await e.readFile({rootToken:l.rootToken,path:z.path});if(!j(fe))return;L({type:"text-preview",file:z,read:Te}),W("idle")}catch(Te){if(await ge(Te,fe))return;j(fe)&&(U(wa(Te)),W("idle"))}}async function Ee(z){if(!l)return;const fe=Ie();W("loading");try{await o({rootToken:l.rootToken,path:z.path,...t?{terminalId:t}:{}}),j(fe)&&W("idle")}catch(Te){if(await ge(Te,fe))return;j(fe)&&(U(wa(Te)),W("idle"))}}async function ye(z,fe){if(!l)return;const Te=Ie();W("loading"),Fe();try{const Ne=await e.previewFile({rootToken:l.rootToken,path:z.path});if(!j(Te))return;const Le=URL.createObjectURL(Ne);if(!j(Te)){URL.revokeObjectURL(Le);return}q.current=Le,L({type:"preview",file:z,previewKind:fe,url:Le}),W("idle")}catch(Ne){if(await ge(Ne,Te))return;j(Te)&&(U(wa(Ne)),W("idle"))}}async function ze(z){if(!l)return;const fe=z==="file"?"New file":"New folder",Te=window.prompt(fe,""),Ne=w?w.kind==="directory"?w.path:xl(w.path):f,Le=ex(Te,Ne);if(Le){U(null);try{const be=await e.createFileEntry({rootToken:l.rootToken,path:Le,kind:z});x(be.entry),await T(Ne)}catch(be){if(await ge(be))return;U(wa(be))}}}async function Ke(){if(!l||!w)return;const z=window.prompt("Move selected entry",w.path),fe=ex(z,"");if(!fe||fe===w.path)return;const Te=xl(w.path),Ne=xl(fe);U(null);try{const Le=await e.moveFileEntry({rootToken:l.rootToken,sourcePath:w.path,destinationPath:fe});x(Le.entry),m(Le.entry.kind==="directory"?Le.entry.path:xl(Le.entry.path)),ve(),await T(Te),Ne!==Te&&await T(Ne)}catch(Le){if(await ge(Le))return;U(wa(Le))}}async function Be(){if(!l||!w)return;const z=w.path,fe=xl(z);U(null);try{const Te=await e.previewDeleteFileEntry({rootToken:l.rootToken,path:w.path}),Ne=Te.descendantCount>0?` and ${Te.descendantCount} nested item${Te.descendantCount===1?"":"s"}`:"";if(!window.confirm(`Delete ${Te.path}${Ne}?`))return;await e.deleteFileEntry({rootToken:l.rootToken,path:w.path,previewToken:Te.previewToken}),x(null),m(fe),S(Le=>{const be=new Set(Le);for(const $e of Le)($e===z||$e.startsWith(`${z}/`))&&be.delete($e);return be}),ve(),await T(fe)}catch(Te){if(await ge(Te))return;U(wa(Te))}}function ve(){F.current+=1,Fe(),L({type:"empty"})}function Fe(){q.current&&(URL.revokeObjectURL(q.current),q.current=null)}function Ie(){return F.current+=1,F.current}function j(z){return I.current&&z===F.current}async function ge(z,fe){return kj(z)?(fe!==void 0&&!j(fe)||await Q(K),!0):!1}function Ae(z,fe){const Te=uv(z),Ne=z.kind==="directory"&&_.has(z.path),Le=p[z.path]??[],be={"--file-tree-depth":fe};return u.jsxs(zt.Fragment,{children:[u.jsxs("button",{type:"button",className:"file-entry-button","data-kind":z.kind,"data-expanded":Ne,"data-active":J===z.path,disabled:!Te,style:be,"aria-expanded":z.kind==="directory"?Ne:void 0,"aria-label":`${z.kind==="directory"?"Open folder":"Open file"} ${z.name}`,title:z.kind==="directory"?"Expand or collapse folder":"Click to preview. Double-click or press Enter to open.",onClick:()=>{he(z)},onDoubleClick:()=>{N(z)},onKeyDown:$e=>se($e,z),children:[u.jsx("span",{className:"file-entry-disclosure","aria-hidden":"true",children:z.kind==="directory"?Ne?"▾":"▸":""}),u.jsx("span",{className:"file-entry-name",children:z.name}),u.jsx("small",{children:wj(z)})]}),Ne?u.jsx("div",{className:"file-tree-children",role:"group",children:Le.map($e=>Ae($e,fe+1))}):null]},z.path)}const Oe=p[""]??[];return u.jsxs("section",{className:"file-explorer","aria-label":"Files","aria-busy":A==="loading",children:[u.jsxs("header",{className:"file-explorer-header",children:[u.jsx("div",{className:"file-explorer-path",title:te,children:te||"No active pane"}),u.jsxs("div",{className:"file-explorer-toolbar","aria-label":"File actions",children:[u.jsx("button",{type:"button","aria-label":"Refresh files",title:"Refresh",disabled:!s&&!t,onClick:()=>{O()},children:"↻"}),u.jsx("button",{type:"button","aria-label":"New file",title:"New file",disabled:!l,onClick:()=>{ze("file")},children:"+"}),u.jsx("button",{type:"button","aria-label":"New folder",title:"New folder",disabled:!l,onClick:()=>{ze("directory")},children:"▣"})]})]}),H?u.jsx("div",{className:"file-explorer-alert",role:"alert",children:H}):null,u.jsxs("div",{className:"file-explorer-layout",children:[u.jsx("div",{className:"file-tree","aria-label":te?`Files in ${te}`:"Files",children:Oe.map(z=>Ae(z,0))}),u.jsxs("section",{className:"file-detail","aria-label":"File detail",children:[u.jsxs("div",{className:"file-detail-header",children:[u.jsx("strong",{children:w?.name??"detail"}),u.jsxs("div",{className:"file-detail-actions",children:[u.jsx("button",{type:"button","aria-label":"Move selected entry",disabled:!w,onClick:()=>{Ke()},children:"Move"}),u.jsx("button",{type:"button","aria-label":"Delete selected entry",disabled:!w,onClick:()=>{Be()},children:"Delete"})]})]}),A==="loading"?u.jsx("div",{className:"file-detail-empty",children:"loading"}):null,R.type==="empty"&&A!=="loading"?u.jsx("div",{className:"file-detail-empty",children:"No file selected"}):null,R.type==="preview"?u.jsxs("div",{className:"file-preview-frame",children:[R.previewKind==="image"?u.jsx("img",{src:R.url,alt:R.file.name}):null,R.previewKind==="pdf"?u.jsx("iframe",{src:R.url,title:R.file.name}):null]}):null,R.type==="text-preview"&&R.read.language==="markdown"?u.jsx("div",{className:"file-markdown-preview","aria-label":`Preview for ${R.file.name}`,children:u.jsx(v.Suspense,{fallback:u.jsx("div",{className:"file-markdown-preview-loading",children:"loading preview"}),children:u.jsx(yj,{content:R.read.content})})}):null,R.type==="text-preview"&&R.read.language==="text"?u.jsx("pre",{className:"file-text-preview","aria-label":`Preview for ${R.file.name}`,children:R.read.content}):null]})]})]})}function uv(e){return e.kind==="directory"||e.editable||e.previewKind!=="none"}function wj(e){return e.kind==="directory"?"dir":e.editable?"edit":e.previewKind!=="none"?e.previewKind:"unsupported"}function J1(e,t){return`${e}\0${t??""}`}function xj(e){return`workspace\0${e}`}function Cj(e){return[...e].sort((t,n)=>t.kind==="directory"&&n.kind!=="directory"?-1:t.kind!=="directory"&&n.kind==="directory"?1:t.name.localeCompare(n.name))}function xl(e){const t=e.split("/").filter(Boolean);return t.pop(),t.join("/")}function ex(e,t){if(e===null)return null;const n=e.trim().replace(/^\/+/,"").replace(/\/{2,}/g,"/").replace(/\/$/,"");return n?!t||n.includes("/")?n:`${t}/${n}`:null}function wa(e){return e instanceof Error?e.message:"Request failed"}function kj(e){return e instanceof Wn&&e.status===409&&e.message==="terminal_cwd_changed"}const Tj=v.lazy(()=>Ly(()=>import("./MarkdownPreview-Dz-gstWx.js"),__vite__mapDeps([0,1])));function tx({api:e,editor:t,canClose:n,onClose:s}){const[o,l]=v.useState(t.read),[d,f]=v.useState(t.read.content),[m,p]=v.useState("idle"),[b,_]=v.useState(null),[S,w]=v.useState(!1),[x,R]=v.useState("edit"),L=v.useRef(t),A=v.useRef(t.read),W=v.useRef(t.read.content),H=v.useRef(!1),U=v.useRef(!1),q=v.useRef(0),Y=d!==o.content&&m!=="saving"&&!S;v.useEffect(()=>(U.current=!0,()=>{U.current=!1,q.current+=1}),[]),v.useEffect(()=>{q.current+=1,H.current=!1,L.current=t,A.current=t.read,W.current=t.read.content,l(t.read),f(t.read.content),p("idle"),_(null),w(!1),R("edit")},[t.id,t.read]),v.useEffect(()=>{L.current=t},[t]),v.useEffect(()=>{A.current=o},[o]),v.useEffect(()=>{W.current=d},[d]),v.useEffect(()=>{if(d===o.content||S)return;const K=window.setInterval(()=>{!H.current&&W.current!==A.current.content&&I()},1e3);return()=>window.clearInterval(K)},[d===o.content,S,t.id]);async function I(){if(H.current)return;const K=W.current,te=A.current;if(K===te.content)return;const J=L.current,Q=q.current;H.current=!0,p("saving"),_(null),w(!1);try{const X=await e.writeFile({rootToken:J.rootToken,path:J.path,content:K,expectedVersion:te.version});if(!U.current||Q!==q.current)return;const M={...te,content:K,version:X.version};A.current=M,l(M),p(W.current===K?"saved":"idle")}catch(X){if(!U.current||Q!==q.current)return;if(X instanceof Wn&&X.status===409){w(!0),p("idle");return}_(Ej(X)),p("idle")}finally{Q===q.current&&(H.current=!1)}}const F=m==="saving"?"saving":m==="saved"?"saved":o.language,de=o.language==="markdown",me=de&&x==="preview";return u.jsxs("section",{className:"editor-pane","aria-label":`Editor pane ${t.title}`,children:[u.jsxs("header",{className:"editor-pane-header",children:[u.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),u.jsx("strong",{children:t.title}),u.jsx("span",{className:"terminal-pane-spacer"}),u.jsx("span",{className:"terminal-pane-state",children:F}),u.jsx("button",{type:"button","aria-label":`Save ${t.title}`,disabled:!Y,onClick:()=>{I()},children:"Save"}),de?u.jsx("button",{type:"button","aria-label":`${me?"Edit":"Preview"} ${t.title}`,onClick:()=>R(K=>K==="preview"?"edit":"preview"),children:me?"Edit":"Preview"}):null,n?u.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close editor ${t.title}`,onClick:s,children:"x"}):null]}),b?u.jsx("div",{className:"editor-pane-alert",role:"alert",children:b}):null,S?u.jsx("div",{className:"editor-pane-alert",role:"alert",children:"File changed on disk."}):null,me?u.jsx("div",{className:"editor-markdown-preview","aria-label":`Markdown preview for ${t.title}`,children:u.jsx(v.Suspense,{fallback:u.jsx("div",{className:"editor-markdown-preview-loading",children:"loading preview"}),children:u.jsx(Tj,{content:d})})}):u.jsx("textarea",{className:"editor-pane-textarea","aria-label":`Editor for ${t.title}`,spellCheck:!1,value:d,onChange:K=>{const te=K.target.value;W.current=te,f(te),p("idle"),_(null),w(!1)}})]})}function Ej(e){return e instanceof Error?e.message:"Request failed"}var Rj=2,Nj=1,Dj=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(n.getPropertyValue("height")),o=Math.max(0,parseInt(n.getPropertyValue("width"))),l=window.getComputedStyle(this._terminal.element),d={top:parseInt(l.getPropertyValue("padding-top")),bottom:parseInt(l.getPropertyValue("padding-bottom")),right:parseInt(l.getPropertyValue("padding-right")),left:parseInt(l.getPropertyValue("padding-left"))},f=d.top+d.bottom,m=d.right+d.left,p=s-f,b=o-m-t;return{cols:Math.max(Rj,Math.floor(b/e.css.cell.width)),rows:Math.max(Nj,Math.floor(p/e.css.cell.height))}}};var FT=Object.defineProperty,Mj=Object.getOwnPropertyDescriptor,Aj=(e,t)=>{for(var n in t)FT(e,n,{get:t[n],enumerable:!0})},On=(e,t,n,s)=>{for(var o=s>1?void 0:s?Mj(t,n):t,l=e.length-1,d;l>=0;l--)(d=e[l])&&(o=(s?d(t,n,o):d(o))||o);return s&&o&&FT(t,n,o),o},Ve=(e,t)=>(n,s)=>t(n,s,e),nx="Terminal input",E_={get:()=>nx,set:e=>nx=e},ix="Too much output to announce, navigate to rows manually to read",R_={get:()=>ix,set:e=>ix=e};function Lj(e){return e.replace(/\r?\n/g,"\r")}function jj(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function Oj(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Bj(e,t,n,s){if(e.stopPropagation(),e.clipboardData){let o=e.clipboardData.getData("text/plain");WT(o,t,n,s)}}function WT(e,t,n,s){e=Lj(e),e=jj(e,n.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=""}function KT(e,t,n){let s=n.getBoundingClientRect(),o=e.clientX-s.left-10,l=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${o}px`,t.style.top=`${l}px`,t.style.zIndex="1000",t.focus()}function rx(e,t,n,s,o){KT(e,t,n),o&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function Eo(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function tm(e,t=0,n=e.length){let s="";for(let o=t;o<n;++o){let l=e[o];l>65535?(l-=65536,s+=String.fromCharCode((l>>10)+55296)+String.fromCharCode(l%1024+56320)):s+=String.fromCharCode(l)}return s}var Ij=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let s=0,o=0;if(this._interim){let l=e.charCodeAt(o++);56320<=l&&l<=57343?t[s++]=(this._interim-55296)*1024+l-56320+65536:(t[s++]=this._interim,t[s++]=l),this._interim=0}for(let l=o;l<n;++l){let d=e.charCodeAt(l);if(55296<=d&&d<=56319){if(++l>=n)return this._interim=d,s;let f=e.charCodeAt(l);56320<=f&&f<=57343?t[s++]=(d-55296)*1024+f-56320+65536:(t[s++]=d,t[s++]=f);continue}d!==65279&&(t[s++]=d)}return s}},Pj=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let s=0,o,l,d,f,m=0,p=0;if(this.interim[0]){let S=!1,w=this.interim[0];w&=(w&224)===192?31:(w&240)===224?15:7;let x=0,R;for(;(R=this.interim[++x]&63)&&x<4;)w<<=6,w|=R;let L=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,A=L-x;for(;p<A;){if(p>=n)return 0;if(R=e[p++],(R&192)!==128){p--,S=!0;break}else this.interim[x++]=R,w<<=6,w|=R&63}S||(L===2?w<128?p--:t[s++]=w:L===3?w<2048||w>=55296&&w<=57343||w===65279||(t[s++]=w):w<65536||w>1114111||(t[s++]=w)),this.interim.fill(0)}let b=n-4,_=p;for(;_<n;){for(;_<b&&!((o=e[_])&128)&&!((l=e[_+1])&128)&&!((d=e[_+2])&128)&&!((f=e[_+3])&128);)t[s++]=o,t[s++]=l,t[s++]=d,t[s++]=f,_+=4;if(o=e[_++],o<128)t[s++]=o;else if((o&224)===192){if(_>=n)return this.interim[0]=o,s;if(l=e[_++],(l&192)!==128){_--;continue}if(m=(o&31)<<6|l&63,m<128){_--;continue}t[s++]=m}else if((o&240)===224){if(_>=n)return this.interim[0]=o,s;if(l=e[_++],(l&192)!==128){_--;continue}if(_>=n)return this.interim[0]=o,this.interim[1]=l,s;if(d=e[_++],(d&192)!==128){_--;continue}if(m=(o&15)<<12|(l&63)<<6|d&63,m<2048||m>=55296&&m<=57343||m===65279)continue;t[s++]=m}else if((o&248)===240){if(_>=n)return this.interim[0]=o,s;if(l=e[_++],(l&192)!==128){_--;continue}if(_>=n)return this.interim[0]=o,this.interim[1]=l,s;if(d=e[_++],(d&192)!==128){_--;continue}if(_>=n)return this.interim[0]=o,this.interim[1]=l,this.interim[2]=d,s;if(f=e[_++],(f&192)!==128){_--;continue}if(m=(o&7)<<18|(l&63)<<12|(d&63)<<6|f&63,m<65536||m>1114111)continue;t[s++]=m}}return s}},qT="",No=" ",ph=class VT{constructor(){this.fg=0,this.bg=0,this.extended=new _p}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new VT;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},_p=class YT{constructor(t=0,n=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=n}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new YT(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Jr=class GT extends ph{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new _p,this.combinedData=""}static fromCharData(t){let n=new GT;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Eo(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let n=!1;if(t[1].length>2)n=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let o=t[1].charCodeAt(1);56320<=o&&o<=57343?this.content=(s-55296)*1024+o-56320+65536|t[2]<<22:n=!0}else n=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;n&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},sx="di$target",N_="di$dependencies",dv=new Map;function zj(e){return e[N_]||[]}function Si(e){if(dv.has(e))return dv.get(e);let t=function(n,s,o){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Hj(t,n,o)};return t._id=e,dv.set(e,t),t}function Hj(e,t,n){t[sx]===t?t[N_].push({id:e,index:n}):(t[N_]=[{id:e,index:n}],t[sx]=t)}var Vi=Si("BufferService"),XT=Si("CoreMouseService"),Fl=Si("CoreService"),Uj=Si("CharsetService"),jy=Si("InstantiationService"),ZT=Si("LogService"),Yi=Si("OptionsService"),QT=Si("OscLinkService"),$j=Si("UnicodeService"),mh=Si("DecorationService"),D_=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let s=[],o=this._optionsService.rawOptions.linkHandler,l=new Jr,d=n.getTrimmedLength(),f=-1,m=-1,p=!1;for(let b=0;b<d;b++)if(!(m===-1&&!n.hasContent(b))){if(n.loadCell(b,l),l.hasExtendedAttrs()&&l.extended.urlId)if(m===-1){m=b,f=l.extended.urlId;continue}else p=l.extended.urlId!==f;else m!==-1&&(p=!0);if(p||m!==-1&&b===d-1){let _=this._oscLinkService.getLinkData(f)?.uri;if(_){let S={start:{x:m+1,y:e},end:{x:b+(!p&&b===d-1?1:0),y:e}},w=!1;if(!o?.allowNonHttpProtocols)try{let x=new URL(_);["http:","https:"].includes(x.protocol)||(w=!0)}catch{w=!0}w||s.push({text:_,range:S,activate:(x,R)=>o?o.activate(x,R,S):Fj(x,R),hover:(x,R)=>o?.hover?.(x,R,S),leave:(x,R)=>o?.leave?.(x,R,S)})}p=!1,l.hasExtendedAttrs()&&l.extended.urlId?(m=b,f=l.extended.urlId):(m=-1,f=-1)}}t(s)}};D_=On([Ve(0,Vi),Ve(1,Yi),Ve(2,QT)],D_);function Fj(e,t){if(confirm(`Do you want to navigate to ${t}?
17
+
18
+ WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var nm=Si("CharSizeService"),Pa=Si("CoreBrowserService"),Oy=Si("MouseService"),za=Si("RenderService"),Wj=Si("SelectionService"),JT=Si("CharacterJoinerService"),ou=Si("ThemeService"),eE=Si("LinkProviderService"),Kj=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?ax.isErrorNoTelemetry(e)?new ax(e.message+`
19
+
20
+ `+e.stack):new Error(e.message+`
21
+
22
+ `+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},qj=new Kj;function $f(e){Vj(e)||qj.onUnexpectedError(e)}var M_="Canceled";function Vj(e){return e instanceof Yj?!0:e instanceof Error&&e.name===M_&&e.message===M_}var Yj=class extends Error{constructor(){super(M_),this.name=this.message}};function Gj(e){return new Error(`Illegal argument: ${e}`)}var ax=class A_ extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof A_)return t;let n=new A_;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},L_=class tE extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,tE.prototype)}};function Tr(e,t=0){return e[e.length-(1+t)]}var Xj;(e=>{function t(l){return l<0}e.isLessThan=t;function n(l){return l<=0}e.isLessThanOrEqual=n;function s(l){return l>0}e.isGreaterThan=s;function o(l){return l===0}e.isNeitherLessOrGreaterThan=o,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Xj||={});function Zj(e,t){let n=this,s=!1,o;return function(){return s||(s=!0,t||(o=e.apply(n,arguments))),o}}var nE;(e=>{function t(U){return U&&typeof U=="object"&&typeof U[Symbol.iterator]=="function"}e.is=t;let n=Object.freeze([]);function s(){return n}e.empty=s;function*o(U){yield U}e.single=o;function l(U){return t(U)?U:o(U)}e.wrap=l;function d(U){return U||n}e.from=d;function*f(U){for(let q=U.length-1;q>=0;q--)yield U[q]}e.reverse=f;function m(U){return!U||U[Symbol.iterator]().next().done===!0}e.isEmpty=m;function p(U){return U[Symbol.iterator]().next().value}e.first=p;function b(U,q){let Y=0;for(let I of U)if(q(I,Y++))return!0;return!1}e.some=b;function _(U,q){for(let Y of U)if(q(Y))return Y}e.find=_;function*S(U,q){for(let Y of U)q(Y)&&(yield Y)}e.filter=S;function*w(U,q){let Y=0;for(let I of U)yield q(I,Y++)}e.map=w;function*x(U,q){let Y=0;for(let I of U)yield*q(I,Y++)}e.flatMap=x;function*R(...U){for(let q of U)yield*q}e.concat=R;function L(U,q,Y){let I=Y;for(let F of U)I=q(I,F);return I}e.reduce=L;function*A(U,q,Y=U.length){for(q<0&&(q+=U.length),Y<0?Y+=U.length:Y>U.length&&(Y=U.length);q<Y;q++)yield U[q]}e.slice=A;function W(U,q=Number.POSITIVE_INFINITY){let Y=[];if(q===0)return[Y,U];let I=U[Symbol.iterator]();for(let F=0;F<q;F++){let de=I.next();if(de.done)return[Y,e.empty()];Y.push(de.value)}return[Y,{[Symbol.iterator](){return I}}]}e.consume=W;async function H(U){let q=[];for await(let Y of U)q.push(Y);return Promise.resolve(q)}e.asyncToArray=H})(nE||={});function zl(e){if(nE.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(s){t.push(s)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function Qj(...e){return Cn(()=>zl(e))}function Cn(e){return{dispose:Zj(()=>{e()})}}var iE=class rE{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{zl(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?rE.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};iE.DISABLE_DISPOSED_WARNING=!1;var Mo=iE,Nt=class{constructor(){this._store=new Mo,this._store}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Nt.None=Object.freeze({dispose(){}});var eu=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Ma=typeof window=="object"?window:globalThis,j_=class O_{constructor(t){this.element=t,this.next=O_.Undefined,this.prev=O_.Undefined}};j_.Undefined=new j_(void 0);var En=j_,ox=class{constructor(){this._first=En.Undefined,this._last=En.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===En.Undefined}clear(){let e=this._first;for(;e!==En.Undefined;){let t=e.next;e.prev=En.Undefined,e.next=En.Undefined,e=t}this._first=En.Undefined,this._last=En.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new En(e);if(this._first===En.Undefined)this._first=n,this._last=n;else if(t){let o=this._last;this._last=n,n.prev=o,o.next=n}else{let o=this._first;this._first=n,n.next=o,o.prev=n}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(n))}}shift(){if(this._first!==En.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==En.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==En.Undefined&&e.next!==En.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===En.Undefined&&e.next===En.Undefined?(this._first=En.Undefined,this._last=En.Undefined):e.next===En.Undefined?(this._last=this._last.prev,this._last.next=En.Undefined):e.prev===En.Undefined&&(this._first=this._first.next,this._first.prev=En.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==En.Undefined;)yield e.element,e=e.next}},Jj=globalThis.performance&&typeof globalThis.performance.now=="function",e3=class sE{static create(t){return new sE(t)}constructor(t){this._now=Jj&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},Ei;(e=>{e.None=()=>Nt.None;function t(te,J){return _(te,()=>{},0,void 0,!0,void 0,J)}e.defer=t;function n(te){return(J,Q=null,X)=>{let M=!1,T;return T=te(O=>{if(!M)return T?T.dispose():M=!0,J.call(Q,O)},null,X),M&&T.dispose(),T}}e.once=n;function s(te,J,Q){return p((X,M=null,T)=>te(O=>X.call(M,J(O)),null,T),Q)}e.map=s;function o(te,J,Q){return p((X,M=null,T)=>te(O=>{J(O),X.call(M,O)},null,T),Q)}e.forEach=o;function l(te,J,Q){return p((X,M=null,T)=>te(O=>J(O)&&X.call(M,O),null,T),Q)}e.filter=l;function d(te){return te}e.signal=d;function f(...te){return(J,Q=null,X)=>{let M=Qj(...te.map(T=>T(O=>J.call(Q,O))));return b(M,X)}}e.any=f;function m(te,J,Q,X){let M=Q;return s(te,T=>(M=J(M,T),M),X)}e.reduce=m;function p(te,J){let Q,X={onWillAddFirstListener(){Q=te(M.fire,M)},onDidRemoveLastListener(){Q?.dispose()}},M=new He(X);return J?.add(M),M.event}function b(te,J){return J instanceof Array?J.push(te):J&&J.add(te),te}function _(te,J,Q=100,X=!1,M=!1,T,O){let re,he,N,V=0,se,Z={leakWarningThreshold:T,onWillAddFirstListener(){re=te(ye=>{V++,he=J(he,ye),X&&!N&&(Ee.fire(he),he=void 0),se=()=>{let ze=he;he=void 0,N=void 0,(!X||V>1)&&Ee.fire(ze),V=0},typeof Q=="number"?(clearTimeout(N),N=setTimeout(se,Q)):N===void 0&&(N=0,queueMicrotask(se))})},onWillRemoveListener(){M&&V>0&&se?.()},onDidRemoveLastListener(){se=void 0,re.dispose()}},Ee=new He(Z);return O?.add(Ee),Ee.event}e.debounce=_;function S(te,J=0,Q){return e.debounce(te,(X,M)=>X?(X.push(M),X):[M],J,void 0,!0,void 0,Q)}e.accumulate=S;function w(te,J=(X,M)=>X===M,Q){let X=!0,M;return l(te,T=>{let O=X||!J(T,M);return X=!1,M=T,O},Q)}e.latch=w;function x(te,J,Q){return[e.filter(te,J,Q),e.filter(te,X=>!J(X),Q)]}e.split=x;function R(te,J=!1,Q=[],X){let M=Q.slice(),T=te(he=>{M?M.push(he):re.fire(he)});X&&X.add(T);let O=()=>{M?.forEach(he=>re.fire(he)),M=null},re=new He({onWillAddFirstListener(){T||(T=te(he=>re.fire(he)),X&&X.add(T))},onDidAddFirstListener(){M&&(J?setTimeout(O):O())},onDidRemoveLastListener(){T&&T.dispose(),T=null}});return X&&X.add(re),re.event}e.buffer=R;function L(te,J){return(Q,X,M)=>{let T=J(new W);return te(function(O){let re=T.evaluate(O);re!==A&&Q.call(X,re)},void 0,M)}}e.chain=L;let A=Symbol("HaltChainable");class W{constructor(){this.steps=[]}map(J){return this.steps.push(J),this}forEach(J){return this.steps.push(Q=>(J(Q),Q)),this}filter(J){return this.steps.push(Q=>J(Q)?Q:A),this}reduce(J,Q){let X=Q;return this.steps.push(M=>(X=J(X,M),X)),this}latch(J=(Q,X)=>Q===X){let Q=!0,X;return this.steps.push(M=>{let T=Q||!J(M,X);return Q=!1,X=M,T?M:A}),this}evaluate(J){for(let Q of this.steps)if(J=Q(J),J===A)break;return J}}function H(te,J,Q=X=>X){let X=(...re)=>O.fire(Q(...re)),M=()=>te.on(J,X),T=()=>te.removeListener(J,X),O=new He({onWillAddFirstListener:M,onDidRemoveLastListener:T});return O.event}e.fromNodeEventEmitter=H;function U(te,J,Q=X=>X){let X=(...re)=>O.fire(Q(...re)),M=()=>te.addEventListener(J,X),T=()=>te.removeEventListener(J,X),O=new He({onWillAddFirstListener:M,onDidRemoveLastListener:T});return O.event}e.fromDOMEventEmitter=U;function q(te){return new Promise(J=>n(te)(J))}e.toPromise=q;function Y(te){let J=new He;return te.then(Q=>{J.fire(Q)},()=>{J.fire(void 0)}).finally(()=>{J.dispose()}),J.event}e.fromPromise=Y;function I(te,J){return te(Q=>J.fire(Q))}e.forward=I;function F(te,J,Q){return J(Q),te(X=>J(X))}e.runAndSubscribe=F;class de{constructor(J,Q){this._observable=J,this._counter=0,this._hasChanged=!1;let X={onWillAddFirstListener:()=>{J.addObserver(this)},onDidRemoveLastListener:()=>{J.removeObserver(this)}};this.emitter=new He(X),Q&&Q.add(this.emitter)}beginUpdate(J){this._counter++}handlePossibleChange(J){}handleChange(J,Q){this._hasChanged=!0}endUpdate(J){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function me(te,J){return new de(te,J).emitter.event}e.fromObservable=me;function K(te){return(J,Q,X)=>{let M=0,T=!1,O={beginUpdate(){M++},endUpdate(){M--,M===0&&(te.reportChanges(),T&&(T=!1,J.call(Q)))},handlePossibleChange(){},handleChange(){T=!0}};te.addObserver(O),te.reportChanges();let re={dispose(){te.removeObserver(O)}};return X instanceof Mo?X.add(re):Array.isArray(X)&&X.push(re),re}}e.fromObservableLight=K})(Ei||={});var B_=class I_{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${I_._idPool++}`,I_.all.add(this)}start(t){this._stopWatch=new e3,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};B_.all=new Set,B_._idPool=0;var t3=B_,n3=-1,aE=class oE{constructor(t,n,s=(oE._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=n,this.name=s,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,n){let s=this.threshold;if(s<=0||n<s)return;this._stacks||(this._stacks=new Map);let o=this._stacks.get(t.value)||0;if(this._stacks.set(t.value,o+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=s*.5;let[l,d]=this.getMostFrequentStack(),f=`[${this.name}] potential listener LEAK detected, having ${n} listeners already. MOST frequent listener (${d}):`;console.warn(f),console.warn(l);let m=new s3(f,l);this._errorHandler(m)}return()=>{let l=this._stacks.get(t.value)||0;this._stacks.set(t.value,l-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,n=0;for(let[s,o]of this._stacks)(!t||n<o)&&(t=[s,o],n=o);return t}};aE._idPool=1;var i3=aE,r3=class lE{constructor(t){this.value=t}static create(){let t=new Error;return new lE(t.stack??"")}print(){console.warn(this.value.split(`
23
+ `).slice(2).join(`
24
+ `))}},s3=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},a3=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},o3=0,hv=class{constructor(e){this.value=e,this.id=o3++}},l3=2,c3,He=class{constructor(e){this._size=0,this._options=e,this._leakageMon=this._options?.leakWarningThreshold?new i3(e?.onListenerError??$f,this._options?.leakWarningThreshold??n3):void 0,this._perfMon=this._options?._profName?new t3(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let d=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(d);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],m=new a3(`${d}. HINT: Stack shows most frequent listener (${f[1]}-times)`,f[0]);return(this._options?.onListenerError||$f)(m),Nt.None}if(this._disposed)return Nt.None;t&&(e=e.bind(t));let s=new hv(e),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(s.stack=r3.create(),o=this._leakageMon.check(s.stack,this._size+1)),this._listeners?this._listeners instanceof hv?(this._deliveryQueue??=new u3,this._listeners=[this._listeners,s]):this._listeners.push(s):(this._options?.onWillAddFirstListener?.(this),this._listeners=s,this._options?.onDidAddFirstListener?.(this)),this._size++;let l=Cn(()=>{o?.(),this._removeListener(s)});return n instanceof Mo?n.add(l):Array.isArray(n)&&n.push(l),l},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[n]=void 0;let s=this._deliveryQueue.current===this;if(this._size*l3<=t.length){let o=0;for(let l=0;l<t.length;l++)t[l]?t[o++]=t[l]:s&&(this._deliveryQueue.end--,o<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=o}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||$f;if(!n){e.value(t);return}try{e.value(t)}catch(s){n(s)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof hv)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}},u3=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},P_=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new He,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new He,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,n){if(this.getZoomLevel(n)===t)return;let s=this.getWindowId(n);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,n){this.mapWindowIdToZoomFactor.set(this.getWindowId(n),t)}setFullscreen(t,n){if(this.isFullscreen(n)===t)return;let s=this.getWindowId(n);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};P_.INSTANCE=new P_;var By=P_;function d3(e,t,n){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",n)}By.INSTANCE.onDidChangeZoomLevel;function h3(e){return By.INSTANCE.getZoomFactor(e)}By.INSTANCE.onDidChangeFullscreen;var lu=typeof navigator=="object"?navigator.userAgent:"",z_=lu.indexOf("Firefox")>=0,f3=lu.indexOf("AppleWebKit")>=0,Iy=lu.indexOf("Chrome")>=0,p3=!Iy&&lu.indexOf("Safari")>=0;lu.indexOf("Electron/")>=0;lu.indexOf("Android")>=0;var fv=!1;if(typeof Ma.matchMedia=="function"){let e=Ma.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Ma.matchMedia("(display-mode: fullscreen)");fv=e.matches,d3(Ma,e,({matches:n})=>{fv&&t.matches||(fv=n)})}var Hc="en",H_=!1,U_=!1,Ff=!1,cE=!1,kf,Wf=Hc,lx=Hc,m3,ka,Al=globalThis,Rr;typeof Al.vscode<"u"&&typeof Al.vscode.process<"u"?Rr=Al.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(Rr=process);var g3=typeof Rr?.versions?.electron=="string",v3=g3&&Rr?.type==="renderer";if(typeof Rr=="object"){H_=Rr.platform==="win32",U_=Rr.platform==="darwin",Ff=Rr.platform==="linux",Ff&&Rr.env.SNAP&&Rr.env.SNAP_REVISION,Rr.env.CI||Rr.env.BUILD_ARTIFACTSTAGINGDIRECTORY,kf=Hc,Wf=Hc;let e=Rr.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);kf=t.userLocale,lx=t.osLocale,Wf=t.resolvedLanguage||Hc,m3=t.languagePack?.translationsConfigFile}catch{}cE=!0}else typeof navigator=="object"&&!v3?(ka=navigator.userAgent,H_=ka.indexOf("Windows")>=0,U_=ka.indexOf("Macintosh")>=0,(ka.indexOf("Macintosh")>=0||ka.indexOf("iPad")>=0||ka.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Ff=ka.indexOf("Linux")>=0,ka?.indexOf("Mobi")>=0,Wf=globalThis._VSCODE_NLS_LANGUAGE||Hc,kf=navigator.language.toLowerCase(),lx=kf):console.error("Unable to resolve platform.");var uE=H_,Hs=U_,_3=Ff,cx=cE,Fs=ka,yo=Wf,b3;(e=>{function t(){return yo}e.value=t;function n(){return yo.length===2?yo==="en":yo.length>=3?yo[0]==="e"&&yo[1]==="n"&&yo[2]==="-":!1}e.isDefaultVariant=n;function s(){return yo==="en"}e.isDefault=s})(b3||={});var y3=typeof Al.postMessage=="function"&&!Al.importScripts;(()=>{if(y3){let e=[];Al.addEventListener("message",n=>{if(n.data&&n.data.vscodeScheduleAsyncWork)for(let s=0,o=e.length;s<o;s++){let l=e[s];if(l.id===n.data.vscodeScheduleAsyncWork){e.splice(s,1),l.callback();return}}});let t=0;return n=>{let s=++t;e.push({id:s,callback:n}),Al.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var S3=!!(Fs&&Fs.indexOf("Chrome")>=0);Fs&&Fs.indexOf("Firefox")>=0;!S3&&Fs&&Fs.indexOf("Safari")>=0;Fs&&Fs.indexOf("Edg/")>=0;Fs&&Fs.indexOf("Android")>=0;var Mc=typeof navigator=="object"?navigator:{};cx||document.queryCommandSupported&&document.queryCommandSupported("copy")||Mc&&Mc.clipboard&&Mc.clipboard.writeText,cx||Mc&&Mc.clipboard&&Mc.clipboard.readText;var Py=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},pv=new Py,ux=new Py,dx=new Py,w3=new Array(230),dE;(e=>{function t(f){return pv.keyCodeToStr(f)}e.toString=t;function n(f){return pv.strToKeyCode(f)}e.fromString=n;function s(f){return ux.keyCodeToStr(f)}e.toUserSettingsUS=s;function o(f){return dx.keyCodeToStr(f)}e.toUserSettingsGeneral=o;function l(f){return ux.strToKeyCode(f)||dx.strToKeyCode(f)}e.fromUserSettings=l;function d(f){if(f>=98&&f<=113)return null;switch(f){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return pv.keyCodeToStr(f)}e.toElectronAccelerator=d})(dE||={});var x3=class hE{constructor(t,n,s,o,l){this.ctrlKey=t,this.shiftKey=n,this.altKey=s,this.metaKey=o,this.keyCode=l}equals(t){return t instanceof hE&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",n=this.shiftKey?"1":"0",s=this.altKey?"1":"0",o=this.metaKey?"1":"0";return`K${t}${n}${s}${o}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new C3([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},C3=class{constructor(e){if(e.length===0)throw Gj("chords");this.chords=e}getHashCode(){let e="";for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=";"),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function k3(e){if(e.charCode){let n=String.fromCharCode(e.charCode).toUpperCase();return dE.fromString(n)}let t=e.keyCode;if(t===3)return 7;if(z_)switch(t){case 59:return 85;case 60:if(_3)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Hs)return 57;break}else if(f3&&(Hs&&t===93||!Hs&&t===92))return 57;return w3[t]||0}var T3=Hs?256:2048,E3=512,R3=1024,N3=Hs?2048:256,hx=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.("AltGraph"),this.keyCode=k3(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=T3),this.altKey&&(t|=E3),this.shiftKey&&(t|=R3),this.metaKey&&(t|=N3),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new x3(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},fx=new WeakMap;function D3(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!=="null"&&n.origin!=="null"&&t.origin!==n.origin)return null}catch{return null}return e.parent}var M3=class{static getSameOriginWindowChain(e){let t=fx.get(e);if(!t){t=[],fx.set(e,t);let n=e,s;do s=D3(n),s?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=s;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,s=0,o=this.getSameOriginWindowChain(e);for(let l of o){let d=l.window.deref();if(n+=d?.scrollY??0,s+=d?.scrollX??0,d===t||!l.iframeElement)break;let f=l.iframeElement.getBoundingClientRect();n+=f.top,s+=f.left}return{top:n,left:s}}},Tf=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type==="dblclick"&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX=="number"?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=M3.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},px=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let s=!1;if(Iy){let o=navigator.userAgent.match(/Chrome\/(\d+)/);s=(o?parseInt(o[1]):123)<=122}if(e){let o=e,l=e,d=e.view?.devicePixelRatio||1;if(typeof o.wheelDeltaY<"u")s?this.deltaY=o.wheelDeltaY/(120*d):this.deltaY=o.wheelDeltaY/120;else if(typeof l.VERTICAL_AXIS<"u"&&l.axis===l.VERTICAL_AXIS)this.deltaY=-l.detail/3;else if(e.type==="wheel"){let f=e;f.deltaMode===f.DOM_DELTA_LINE?z_&&!Hs?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof o.wheelDeltaX<"u")p3&&uE?this.deltaX=-(o.wheelDeltaX/120):s?this.deltaX=o.wheelDeltaX/(120*d):this.deltaX=o.wheelDeltaX/120;else if(typeof l.HORIZONTAL_AXIS<"u"&&l.axis===l.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type==="wheel"){let f=e;f.deltaMode===f.DOM_DELTA_LINE?z_&&!Hs?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(s?this.deltaY=e.wheelDelta/(120*d):this.deltaY=e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},fE=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),A3;(e=>{function t(n){return n===e.None||n===e.Cancelled||n instanceof L3?!0:!n||typeof n!="object"?!1:typeof n.isCancellationRequested=="boolean"&&typeof n.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Ei.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:fE})})(A3||={});var L3=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?fE:(this._emitter||(this._emitter=new He),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},zy=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new L_("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new L_("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},j3=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new L_("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=n.setInterval(()=>{e()},t);this.disposable=Cn(()=>{n.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},O3;(e=>{async function t(s){let o,l=await Promise.all(s.map(d=>d.then(f=>f,f=>{o||(o=f)})));if(typeof o<"u")throw o;return l}e.settled=t;function n(s){return new Promise(async(o,l)=>{try{await s(o,l)}catch(d){l(d)}})}e.withAsyncBody=n})(O3||={});var mx=class Vr{static fromArray(t){return new Vr(n=>{n.emitMany(t)})}static fromPromise(t){return new Vr(async n=>{n.emitMany(await t)})}static fromPromises(t){return new Vr(async n=>{await Promise.all(t.map(async s=>n.emitOne(await s)))})}static merge(t){return new Vr(async n=>{await Promise.all(t.map(async s=>{for await(let o of s)n.emitOne(o)}))})}constructor(t,n){this._state=0,this._results=[],this._error=null,this._onReturn=n,this._onStateChanged=new He,queueMicrotask(async()=>{let s={emitOne:o=>this.emitOne(o),emitMany:o=>this.emitMany(o),reject:o=>this.reject(o)};try{await Promise.resolve(t(s)),this.resolve()}catch(o){this.reject(o)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t<this._results.length)return{done:!1,value:this._results[t++]};if(this._state===1)return{done:!0,value:void 0};await Ei.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new Vr(async s=>{for await(let o of t)s.emitOne(n(o))})}map(t){return Vr.map(this,t)}static filter(t,n){return new Vr(async s=>{for await(let o of t)n(o)&&s.emitOne(o)})}filter(t){return Vr.filter(this,t)}static coalesce(t){return Vr.filter(t,n=>!!n)}coalesce(){return Vr.coalesce(this)}static async toPromise(t){let n=[];for await(let s of t)n.push(s);return n}toPromise(){return Vr.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};mx.EMPTY=mx.fromArray([]);var{getWindow:zs,getWindowId:B3,onDidRegisterWindow:I3}=(function(){let e=new Map,t={window:Ma,disposables:new Mo};e.set(Ma.vscodeWindowId,t);let n=new He,s=new He,o=new He;function l(d,f){return(typeof d=="number"?e.get(d):void 0)??(f?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:o.event,onDidUnregisterWindow:s.event,registerWindow(d){if(e.has(d.vscodeWindowId))return Nt.None;let f=new Mo,m={window:d,disposables:f.add(new Mo)};return e.set(d.vscodeWindowId,m),f.add(Cn(()=>{e.delete(d.vscodeWindowId),s.fire(d)})),f.add(vt(d,gi.BEFORE_UNLOAD,()=>{o.fire(d)})),n.fire(m),f},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(d){return d.vscodeWindowId},hasWindow(d){return e.has(d)},getWindowById:l,getWindow(d){let f=d;if(f?.ownerDocument?.defaultView)return f.ownerDocument.defaultView.window;let m=d;return m?.view?m.view.window:Ma},getDocument(d){return zs(d).document}}})(),P3=class{constructor(e,t,n,s){this._node=e,this._type=t,this._handler=n,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function vt(e,t,n,s){return new P3(e,t,n,s)}var gx=function(e,t,n,s){return vt(e,t,n,s)},Hy,z3=class extends j3{constructor(e){super(),this.defaultTarget=e&&zs(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},vx=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){$f(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,s=new Map,o=l=>{n.set(l,!1);let d=e.get(l)??[];for(t.set(l,d),e.set(l,[]),s.set(l,!0);d.length>0;)d.sort(vx.sort),d.shift().execute();s.set(l,!1)};Hy=(l,d,f=0)=>{let m=B3(l),p=new vx(d,f),b=e.get(m);return b||(b=[],e.set(m,b)),b.push(p),n.get(m)||(n.set(m,!0),l.requestAnimationFrame(()=>o(m))),p}})();function H3(e){let t=e.getBoundingClientRect(),n=zs(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}var gi={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},U3=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=cr(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=cr(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=cr(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=cr(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=cr(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=cr(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=cr(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=cr(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=cr(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=cr(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=cr(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=cr(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=cr(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=cr(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function cr(e){return typeof e=="number"?`${e}px`:e}function zd(e){return new U3(e)}var pE=class{constructor(){this._hooks=new Mo,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,s,o){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=o;let l=e;try{e.setPointerCapture(t),this._hooks.add(Cn(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{l=zs(e)}this._hooks.add(vt(l,gi.POINTER_MOVE,d=>{if(d.buttons!==n){this.stopMonitoring(!0);return}d.preventDefault(),this._pointerMoveCallback(d)})),this._hooks.add(vt(l,gi.POINTER_UP,d=>this.stopMonitoring(!0)))}};function $3(e,t,n){let s=null,o=null;if(typeof n.value=="function"?(s="value",o=n.value,o.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof n.get=="function"&&(s="get",o=n.get),!o)throw new Error("not supported");let l=`$memoize$${t}`;n[s]=function(...d){return this.hasOwnProperty(l)||Object.defineProperty(this,l,{configurable:!1,enumerable:!1,writable:!1,value:o.apply(this,d)}),this[l]}}var Bs;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Bs||={});var bd=class Ii extends Nt{constructor(){super(),this.dispatched=!1,this.targets=new ox,this.ignoreTargets=new ox,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Ei.runAndSubscribe(I3,({window:t,disposables:n})=>{n.add(vt(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),n.add(vt(t.document,"touchend",s=>this.onTouchEnd(t,s))),n.add(vt(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:Ma,disposables:this._store}))}static addTarget(t){if(!Ii.isTouchDevice())return Nt.None;Ii.INSTANCE||(Ii.INSTANCE=new Ii);let n=Ii.INSTANCE.targets.push(t);return Cn(n)}static ignoreTarget(t){if(!Ii.isTouchDevice())return Nt.None;Ii.INSTANCE||(Ii.INSTANCE=new Ii);let n=Ii.INSTANCE.ignoreTargets.push(t);return Cn(n)}static isTouchDevice(){return"ontouchstart"in Ma||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let n=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,o=t.targetTouches.length;s<o;s++){let l=t.targetTouches.item(s);this.activeTouches[l.identifier]={id:l.identifier,initialTarget:l.target,initialTimeStamp:n,initialPageX:l.pageX,initialPageY:l.pageY,rollingTimestamps:[n],rollingPageX:[l.pageX],rollingPageY:[l.pageY]};let d=this.newGestureEvent(Bs.Start,l.target);d.pageX=l.pageX,d.pageY=l.pageY,this.dispatchEvent(d)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}onTouchEnd(t,n){let s=Date.now(),o=Object.keys(this.activeTouches).length;for(let l=0,d=n.changedTouches.length;l<d;l++){let f=n.changedTouches.item(l);if(!this.activeTouches.hasOwnProperty(String(f.identifier))){console.warn("move of an UNKNOWN touch",f);continue}let m=this.activeTouches[f.identifier],p=Date.now()-m.initialTimeStamp;if(p<Ii.HOLD_DELAY&&Math.abs(m.initialPageX-Tr(m.rollingPageX))<30&&Math.abs(m.initialPageY-Tr(m.rollingPageY))<30){let b=this.newGestureEvent(Bs.Tap,m.initialTarget);b.pageX=Tr(m.rollingPageX),b.pageY=Tr(m.rollingPageY),this.dispatchEvent(b)}else if(p>=Ii.HOLD_DELAY&&Math.abs(m.initialPageX-Tr(m.rollingPageX))<30&&Math.abs(m.initialPageY-Tr(m.rollingPageY))<30){let b=this.newGestureEvent(Bs.Contextmenu,m.initialTarget);b.pageX=Tr(m.rollingPageX),b.pageY=Tr(m.rollingPageY),this.dispatchEvent(b)}else if(o===1){let b=Tr(m.rollingPageX),_=Tr(m.rollingPageY),S=Tr(m.rollingTimestamps)-m.rollingTimestamps[0],w=b-m.rollingPageX[0],x=_-m.rollingPageY[0],R=[...this.targets].filter(L=>m.initialTarget instanceof Node&&L.contains(m.initialTarget));this.inertia(t,R,s,Math.abs(w)/S,w>0?1:-1,b,Math.abs(x)/S,x>0?1:-1,_)}this.dispatchEvent(this.newGestureEvent(Bs.End,m.initialTarget)),delete this.activeTouches[f.identifier]}this.dispatched&&(n.preventDefault(),n.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,n){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=n,s.tapCount=0,s}dispatchEvent(t){if(t.type===Bs.Tap){let n=new Date().getTime(),s=0;n-this._lastSetTapCountTime>Ii.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=n,t.tapCount=s}else(t.type===Bs.Change||t.type===Bs.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let n=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let o=0,l=t.initialTarget;for(;l&&l!==s;)o++,l=l.parentElement;n.push([o,s])}n.sort((s,o)=>s[0]-o[0]);for(let[s,o]of n)o.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,s,o,l,d,f,m,p){this.handle=Hy(t,()=>{let b=Date.now(),_=b-s,S=0,w=0,x=!0;o+=Ii.SCROLL_FRICTION*_,f+=Ii.SCROLL_FRICTION*_,o>0&&(x=!1,S=l*o*_),f>0&&(x=!1,w=m*f*_);let R=this.newGestureEvent(Bs.Change);R.translationX=S,R.translationY=w,n.forEach(L=>L.dispatchEvent(R)),x||this.inertia(t,n,b,o,l,d+S,f,m,p+w)})}onTouchMove(t){let n=Date.now();for(let s=0,o=t.changedTouches.length;s<o;s++){let l=t.changedTouches.item(s);if(!this.activeTouches.hasOwnProperty(String(l.identifier))){console.warn("end of an UNKNOWN touch",l);continue}let d=this.activeTouches[l.identifier],f=this.newGestureEvent(Bs.Change,d.initialTarget);f.translationX=l.pageX-Tr(d.rollingPageX),f.translationY=l.pageY-Tr(d.rollingPageY),f.pageX=l.pageX,f.pageY=l.pageY,this.dispatchEvent(f),d.rollingPageX.length>3&&(d.rollingPageX.shift(),d.rollingPageY.shift(),d.rollingTimestamps.shift()),d.rollingPageX.push(l.pageX),d.rollingPageY.push(l.pageY),d.rollingTimestamps.push(n)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};bd.SCROLL_FRICTION=-.005,bd.HOLD_DELAY=700,bd.CLEAR_TAP_COUNT_TIME=400,On([$3],bd,"isTouchDevice",1);var F3=bd,Uy=class extends Nt{onclick(e,t){this._register(vt(e,gi.CLICK,n=>t(new Tf(zs(e),n))))}onmousedown(e,t){this._register(vt(e,gi.MOUSE_DOWN,n=>t(new Tf(zs(e),n))))}onmouseover(e,t){this._register(vt(e,gi.MOUSE_OVER,n=>t(new Tf(zs(e),n))))}onmouseleave(e,t){this._register(vt(e,gi.MOUSE_LEAVE,n=>t(new Tf(zs(e),n))))}onkeydown(e,t){this._register(vt(e,gi.KEY_DOWN,n=>t(new hx(n))))}onkeyup(e,t){this._register(vt(e,gi.KEY_UP,n=>t(new hx(n))))}oninput(e,t){this._register(vt(e,gi.INPUT,t))}onblur(e,t){this._register(vt(e,gi.BLUR,t))}onfocus(e,t){this._register(vt(e,gi.FOCUS,t))}onchange(e,t){this._register(vt(e,gi.CHANGE,t))}ignoreGesture(e){return F3.ignoreTarget(e)}},_x=11,W3=class extends Uy{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=_x+"px",this.domNode.style.height=_x+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new pE),this._register(gx(this.bgDomNode,gi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(gx(this.domNode,gi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new z3),this._pointerdownScheduleRepeatTimer=this._register(new zy)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,zs(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,n=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},K3=class $_{constructor(t,n,s,o,l,d,f){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(n=n|0,s=s|0,o=o|0,l=l|0,d=d|0,f=f|0),this.rawScrollLeft=o,this.rawScrollTop=f,n<0&&(n=0),o+n>s&&(o=s-n),o<0&&(o=0),l<0&&(l=0),f+l>d&&(f=d-l),f<0&&(f=0),this.width=n,this.scrollWidth=s,this.scrollLeft=o,this.height=l,this.scrollHeight=d,this.scrollTop=f}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,n){return new $_(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new $_(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,n){let s=this.width!==t.width,o=this.scrollWidth!==t.scrollWidth,l=this.scrollLeft!==t.scrollLeft,d=this.height!==t.height,f=this.scrollHeight!==t.scrollHeight,m=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:n,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:o,scrollLeftChanged:l,heightChanged:d,scrollHeightChanged:f,scrollTopChanged:m}}},q3=class extends Nt{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new He),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new K3(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let s;t?s=new yx(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let n=this._state.withScrollPosition(e);this._smoothScrolling=yx.start(this._state,n,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},bx=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function mv(e,t){let n=t-e;return function(s){return e+n*G3(s)}}function V3(e,t,n){return function(s){return s<n?e(s/n):t((s-n)/(1-n))}}var yx=class F_{constructor(t,n,s,o){this.from=t,this.to=n,this.duration=o,this.startTime=s,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(t,n,s){if(Math.abs(t-n)>2.5*s){let o,l;return t<n?(o=t+.75*s,l=n-.75*s):(o=t-.75*s,l=n+.75*s),V3(mv(t,o),mv(l,n),.33)}return mv(t,n)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(t){this.to=t.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(t){let n=(t-this.startTime)/this.duration;if(n<1){let s=this.scrollLeft(n),o=this.scrollTop(n);return new bx(s,o,!1)}return new bx(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,s){return F_.start(t,n,s)}static start(t,n,s){s=s+10;let o=Date.now()-10;return new F_(t,n,o,s)}};function Y3(e){return Math.pow(e,3)}function G3(e){return 1-Y3(1-e)}var X3=class extends Nt{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new zy)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},Z3=140,mE=class extends Uy{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new X3(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new pE),this._shouldRender=!0,this.domNode=zd(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(vt(this.domNode.domNode,gi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new W3(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,s){this.slider=zd(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof n=="number"&&this.slider.setWidth(n),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(vt(this.slider.domNode,gi.POINTER_DOWN,o=>{o.button===0&&(o.preventDefault(),this._sliderPointerDown(o))})),this.onclick(this.slider.domNode,o=>{o.leftButton&&o.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),o=this._sliderPointerPosition(e);n<=o&&o<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,n=e.offsetY;else{let o=H3(this.domNode.domNode);t=e.pageX-o.left,n=e.pageY-o.top}let s=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,o=>{let l=this._sliderOrthogonalPointerPosition(o),d=Math.abs(l-n);if(uE&&d>Z3){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let f=this._sliderPointerPosition(o)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(f))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},gE=class W_{constructor(t,n,s,o,l,d){this._scrollbarSize=Math.round(n),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=o,this._scrollSize=l,this._scrollPosition=d,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new W_(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let n=Math.round(t);return this._visibleSize!==n?(this._visibleSize=n,this._refreshComputedValues(),!0):!1}setScrollSize(t){let n=Math.round(t);return this._scrollSize!==n?(this._scrollSize=n,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let n=Math.round(t);return this._scrollPosition!==n?(this._scrollPosition=n,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,n,s,o,l){let d=Math.max(0,s-t),f=Math.max(0,d-2*n),m=o>0&&o>s;if(!m)return{computedAvailableSize:Math.round(d),computedIsNeeded:m,computedSliderSize:Math.round(f),computedSliderRatio:0,computedSliderPosition:0};let p=Math.round(Math.max(20,Math.floor(s*f/o))),b=(f-p)/(o-s),_=l*b;return{computedAvailableSize:Math.round(d),computedIsNeeded:m,computedSliderSize:Math.round(p),computedSliderRatio:b,computedSliderPosition:Math.round(_)}}_refreshComputedValues(){let t=W_._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize-this._computedSliderSize/2;return Math.round(n/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let n=t-this._arrowSize,s=this._scrollPosition;return n<this._computedSliderPosition?s-=this._visibleSize:s+=this._visibleSize,s}getDesiredScrollPositionFromDelta(t){if(!this._computedIsNeeded)return 0;let n=this._computedSliderPosition+t;return Math.round(n/this._computedSliderRatio)}},Q3=class extends mE{constructor(e,t,n){let s=e.getScrollDimensions(),o=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new gE(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,s.width,s.scrollWidth,o.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:"horizontal",scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},J3=class extends mE{constructor(e,t,n){let s=e.getScrollDimensions(),o=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new gE(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,s.height,s.scrollHeight,o.scrollTop),visibility:t.vertical,extraScrollbarClassName:"vertical",scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},eO=500,Sx=50,tO=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},K_=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let t=1,n=0,s=1,o=this._rear;do{let l=o===this._front?t:Math.pow(2,-s);if(t-=l,n+=this._memory[o].score*l,o===this._front)break;o=(this._capacity+o-1)%this._capacity,s++}while(!0);return n<=.5}acceptStandardWheelEvent(t){if(Iy){let n=zs(t.browserEvent),s=h3(n);this.accept(Date.now(),t.deltaX*s,t.deltaY*s)}else this.accept(Date.now(),t.deltaX,t.deltaY)}accept(t,n,s){let o=null,l=new tO(t,n,s);this._front===-1&&this._rear===-1?(this._memory[0]=l,this._front=0,this._rear=0):(o=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=l),l.score=this._computeScore(l,o)}_computeScore(t,n){if(Math.abs(t.deltaX)>0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),n){let o=Math.abs(t.deltaX),l=Math.abs(t.deltaY),d=Math.abs(n.deltaX),f=Math.abs(n.deltaY),m=Math.max(Math.min(o,d),1),p=Math.max(Math.min(l,f),1),b=Math.max(o,d),_=Math.max(l,f);b%m===0&&_%p===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};K_.INSTANCE=new K_;var nO=K_,iO=class extends Uy{constructor(e,t,n){super(),this._onScroll=this._register(new He),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new He),this.onWillScroll=this._onWillScroll.event,this._options=sO(t),this._scrollable=n,this._register(this._scrollable.onScroll(o=>{this._onWillScroll.fire(o),this._onDidScroll(o),this._onScroll.fire(o)}));let s={onMouseWheel:o=>this._onMouseWheel(o),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new J3(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Q3(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=zd(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=zd(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=zd(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,o=>this._onMouseOver(o)),this.onmouseleave(this._listenOnDomNode,o=>this._onMouseLeave(o)),this._hideTimeout=this._register(new zy),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=zl(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Hs&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new px(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=zl(this._mouseWheelToDispose),e)){let t=n=>{this._onMouseWheel(new px(n))};this._mouseWheelToDispose.push(vt(this._listenOnDomNode,gi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=nO.INSTANCE;t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,l=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&l+o===0?l=o=0:Math.abs(o)>=Math.abs(l)?l=0:o=0),this._options.flipAxes&&([o,l]=[l,o]);let d=!Hs&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||d)&&!l&&(l=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(l=l*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let f=this._scrollable.getFutureScrollPosition(),m={};if(o){let p=Sx*o,b=f.scrollTop-(p<0?Math.floor(p):Math.ceil(p));this._verticalScrollbar.writeScrollPosition(m,b)}if(l){let p=Sx*l,b=f.scrollLeft-(p<0?Math.floor(p):Math.ceil(p));this._horizontalScrollbar.writeScrollPosition(m,b)}m=this._scrollable.validateScrollPosition(m),(f.scrollLeft!==m.scrollLeft||f.scrollTop!==m.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(m):this._scrollable.setScrollPositionNow(m),n=!0)}let s=n;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,s=n?" left":"",o=t?" top":"",l=n||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${o}`),this._topLeftShadowDomNode.setClassName(`shadow${l}${o}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),eO)}},rO=class extends iO{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function sO(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Hs&&(t.className+=" mac"),t}var q_=class extends Nt{constructor(e,t,n,s,o,l,d,f){super(),this._bufferService=n,this._optionsService=d,this._renderService=f,this._onRequestScrollLines=this._register(new He),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let m=this._register(new q3({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:p=>Hy(s.window,p)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{m.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new rO(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},m)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(o.onProtocolChange(p=>{this._scrollableElement.updateOptions({handleMouseWheel:!(p&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Ei.runAndSubscribe(l.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=l.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(Cn(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(Cn(()=>this._styleElement.remove())),this._register(Ei.runAndSubscribe(l.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${l.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${l.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${l.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
25
+ `)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(p=>this._handleScroll(p)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};q_=On([Ve(2,Vi),Ve(3,Pa),Ve(4,XT),Ve(5,ou),Ve(6,Yi),Ve(7,za)],q_);var V_=class extends Nt{constructor(e,t,n,s,o){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=s,this._renderService=o,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(l=>this._removeDecoration(l))),this._register(Cn(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};V_=On([Ve(1,Vi),Ve(2,Pa),Ve(3,mh),Ve(4,za)],V_);var aO=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||"full"]&&t<=e.endBufferLine+this._linePadding[n||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},js={full:0,left:0,center:0,right:0},So={full:0,left:0,center:0,right:0},cd={full:0,left:0,center:0,right:0},bp=class extends Nt{constructor(e,t,n,s,o,l,d,f){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=s,this._renderService=o,this._optionsService=l,this._themeService=d,this._coreBrowserService=f,this._colorZoneStore=new aO,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(Cn(()=>this._canvas?.remove()));let m=this._canvas.getContext("2d");if(m)this._ctx=m;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);So.full=this._canvas.width,So.left=e,So.center=t,So.right=e,this._refreshDrawHeightConstants(),cd.full=1,cd.left=1,cd.center=1+So.left,cd.right=1+So.left+So.center}_refreshDrawHeightConstants(){js.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);js.left=t,js.center=t,js.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*js.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*js.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*js.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*js.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(cd[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-js[e.position||"full"]/2),So[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+js[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};bp=On([Ve(2,Vi),Ve(3,mh),Ve(4,za),Ve(5,Yi),Ve(6,ou),Ve(7,Pa)],bp);var De;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=`
26
+ `,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(De||={});var Kf;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(Kf||={});var vE;(e=>e.ST=`${De.ESC}\\`)(vE||={});var Y_=class{constructor(e,t,n,s,o,l){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=s,this._coreService=o,this._renderService=l,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let n;t.start+=this._dataAlreadySent.length,this._isComposing?n=this._textarea.value.substring(t.start,this._compositionPosition.start):n=this._textarea.value.substring(t.start),n.length>0&&this._coreService.triggerDataEvent(n,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,"");this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${De.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let t=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),n=this._renderService.dimensions.css.cell.height,s=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,o=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=o+"px",this._compositionView.style.top=s+"px",this._compositionView.style.height=n+"px",this._compositionView.style.lineHeight=n+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let l=this._compositionView.getBoundingClientRect();this._textarea.style.left=o+"px",this._textarea.style.top=s+"px",this._textarea.style.width=Math.max(l.width,1)+"px",this._textarea.style.height=Math.max(l.height,1)+"px",this._textarea.style.lineHeight=l.height+"px"}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};Y_=On([Ve(2,Vi),Ve(3,Yi),Ve(4,Fl),Ve(5,za)],Y_);var _i=0,bi=0,yi=0,jn=0,wx={css:"#00000000",rgba:0},ti;(e=>{function t(o,l,d,f){return f!==void 0?`#${Cl(o)}${Cl(l)}${Cl(d)}${Cl(f)}`:`#${Cl(o)}${Cl(l)}${Cl(d)}`}e.toCss=t;function n(o,l,d,f=255){return(o<<24|l<<16|d<<8|f)>>>0}e.toRgba=n;function s(o,l,d,f){return{css:e.toCss(o,l,d,f),rgba:e.toRgba(o,l,d,f)}}e.toColor=s})(ti||={});var yn;(e=>{function t(m,p){if(jn=(p.rgba&255)/255,jn===1)return{css:p.css,rgba:p.rgba};let b=p.rgba>>24&255,_=p.rgba>>16&255,S=p.rgba>>8&255,w=m.rgba>>24&255,x=m.rgba>>16&255,R=m.rgba>>8&255;_i=w+Math.round((b-w)*jn),bi=x+Math.round((_-x)*jn),yi=R+Math.round((S-R)*jn);let L=ti.toCss(_i,bi,yi),A=ti.toRgba(_i,bi,yi);return{css:L,rgba:A}}e.blend=t;function n(m){return(m.rgba&255)===255}e.isOpaque=n;function s(m,p,b){let _=qf.ensureContrastRatio(m.rgba,p.rgba,b);if(_)return ti.toColor(_>>24&255,_>>16&255,_>>8&255)}e.ensureContrastRatio=s;function o(m){let p=(m.rgba|255)>>>0;return[_i,bi,yi]=qf.toChannels(p),{css:ti.toCss(_i,bi,yi),rgba:p}}e.opaque=o;function l(m,p){return jn=Math.round(p*255),[_i,bi,yi]=qf.toChannels(m.rgba),{css:ti.toCss(_i,bi,yi,jn),rgba:ti.toRgba(_i,bi,yi,jn)}}e.opacity=l;function d(m,p){return jn=m.rgba&255,l(m,jn*p/255)}e.multiplyOpacity=d;function f(m){return[m.rgba>>24&255,m.rgba>>16&255,m.rgba>>8&255]}e.toColorRGB=f})(yn||={});var Rn;(e=>{let t,n;try{let o=document.createElement("canvas");o.width=1,o.height=1;let l=o.getContext("2d",{willReadFrequently:!0});l&&(t=l,t.globalCompositeOperation="copy",n=t.createLinearGradient(0,0,1,1))}catch{}function s(o){if(o.match(/#[\da-f]{3,8}/i))switch(o.length){case 4:return _i=parseInt(o.slice(1,2).repeat(2),16),bi=parseInt(o.slice(2,3).repeat(2),16),yi=parseInt(o.slice(3,4).repeat(2),16),ti.toColor(_i,bi,yi);case 5:return _i=parseInt(o.slice(1,2).repeat(2),16),bi=parseInt(o.slice(2,3).repeat(2),16),yi=parseInt(o.slice(3,4).repeat(2),16),jn=parseInt(o.slice(4,5).repeat(2),16),ti.toColor(_i,bi,yi,jn);case 7:return{css:o,rgba:(parseInt(o.slice(1),16)<<8|255)>>>0};case 9:return{css:o,rgba:parseInt(o.slice(1),16)>>>0}}let l=o.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(l)return _i=parseInt(l[1]),bi=parseInt(l[2]),yi=parseInt(l[3]),jn=Math.round((l[5]===void 0?1:parseFloat(l[5]))*255),ti.toColor(_i,bi,yi,jn);if(!t||!n)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=n,t.fillStyle=o,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[_i,bi,yi,jn]=t.getImageData(0,0,1,1).data,jn!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:ti.toRgba(_i,bi,yi,jn),css:o}}e.toColor=s})(Rn||={});var Ki;(e=>{function t(s){return n(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function n(s,o,l){let d=s/255,f=o/255,m=l/255,p=d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4),b=f<=.03928?f/12.92:Math.pow((f+.055)/1.055,2.4),_=m<=.03928?m/12.92:Math.pow((m+.055)/1.055,2.4);return p*.2126+b*.7152+_*.0722}e.relativeLuminance2=n})(Ki||={});var qf;(e=>{function t(d,f){if(jn=(f&255)/255,jn===1)return f;let m=f>>24&255,p=f>>16&255,b=f>>8&255,_=d>>24&255,S=d>>16&255,w=d>>8&255;return _i=_+Math.round((m-_)*jn),bi=S+Math.round((p-S)*jn),yi=w+Math.round((b-w)*jn),ti.toRgba(_i,bi,yi)}e.blend=t;function n(d,f,m){let p=Ki.relativeLuminance(d>>8),b=Ki.relativeLuminance(f>>8);if(xa(p,b)<m){if(b<p){let w=s(d,f,m),x=xa(p,Ki.relativeLuminance(w>>8));if(x<m){let R=o(d,f,m),L=xa(p,Ki.relativeLuminance(R>>8));return x>L?w:R}return w}let _=o(d,f,m),S=xa(p,Ki.relativeLuminance(_>>8));if(S<m){let w=s(d,f,m),x=xa(p,Ki.relativeLuminance(w>>8));return S>x?_:w}return _}}e.ensureContrastRatio=n;function s(d,f,m){let p=d>>24&255,b=d>>16&255,_=d>>8&255,S=f>>24&255,w=f>>16&255,x=f>>8&255,R=xa(Ki.relativeLuminance2(S,w,x),Ki.relativeLuminance2(p,b,_));for(;R<m&&(S>0||w>0||x>0);)S-=Math.max(0,Math.ceil(S*.1)),w-=Math.max(0,Math.ceil(w*.1)),x-=Math.max(0,Math.ceil(x*.1)),R=xa(Ki.relativeLuminance2(S,w,x),Ki.relativeLuminance2(p,b,_));return(S<<24|w<<16|x<<8|255)>>>0}e.reduceLuminance=s;function o(d,f,m){let p=d>>24&255,b=d>>16&255,_=d>>8&255,S=f>>24&255,w=f>>16&255,x=f>>8&255,R=xa(Ki.relativeLuminance2(S,w,x),Ki.relativeLuminance2(p,b,_));for(;R<m&&(S<255||w<255||x<255);)S=Math.min(255,S+Math.ceil((255-S)*.1)),w=Math.min(255,w+Math.ceil((255-w)*.1)),x=Math.min(255,x+Math.ceil((255-x)*.1)),R=xa(Ki.relativeLuminance2(S,w,x),Ki.relativeLuminance2(p,b,_));return(S<<24|w<<16|x<<8|255)>>>0}e.increaseLuminance=o;function l(d){return[d>>24&255,d>>16&255,d>>8&255,d&255]}e.toChannels=l})(qf||={});function Cl(e){let t=e.toString(16);return t.length<2?"0"+t:t}function xa(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var oO=class extends ph{constructor(e,t,n){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},yp=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Jr}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],s=t.translateToString(!0),o=0,l=0,d=0,f=t.getFg(0),m=t.getBg(0);for(let p=0;p<t.getTrimmedLength();p++)if(t.loadCell(p,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==f||this._workCell.bg!==m){if(p-o>1){let b=this._getJoinedRanges(s,d,l,t,o);for(let _=0;_<b.length;_++)n.push(b[_])}o=p,d=l,f=this._workCell.fg,m=this._workCell.bg}l+=this._workCell.getChars().length||No.length}if(this._bufferService.cols-o>1){let p=this._getJoinedRanges(s,d,l,t,o);for(let b=0;b<p.length;b++)n.push(p[b])}return n}_getJoinedRanges(e,t,n,s,o){let l=e.substring(t,n),d=[];try{d=this._characterJoiners[0].handler(l)}catch(f){console.error(f)}for(let f=1;f<this._characterJoiners.length;f++)try{let m=this._characterJoiners[f].handler(l);for(let p=0;p<m.length;p++)yp._mergeRanges(d,m[p])}catch(m){console.error(m)}return this._stringRangesToCellRanges(d,s,o),d}_stringRangesToCellRanges(e,t,n){let s=0,o=!1,l=0,d=e[s];if(d){for(let f=n;f<this._bufferService.cols;f++){let m=t.getWidth(f),p=t.getString(f).length||No.length;if(m!==0){if(!o&&d[0]<=l&&(d[0]=f,o=!0),d[1]<=l){if(d[1]=f,d=e[++s],!d)break;d[0]<=l?(d[0]=f,o=!0):o=!1}l+=p}}d&&(d[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let s=0;s<e.length;s++){let o=e[s];if(n){if(t[1]<=o[0])return e[s-1][1]=t[1],e;if(t[1]<=o[1])return e[s-1][1]=Math.max(t[1],o[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=o[0])return e.splice(s,0,t),e;if(t[1]<=o[1])return o[0]=Math.min(t[0],o[0]),e;t[0]<o[1]&&(o[0]=Math.min(t[0],o[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};yp=On([Ve(0,Vi)],yp);function lO(e){return 57508<=e&&e<=57558}function cO(e){return 9472<=e&&e<=9631}function uO(e){return lO(e)||cO(e)}function dO(){return{css:{canvas:Ef(),cell:Ef()},device:{canvas:Ef(),cell:Ef(),char:{width:0,height:0,left:0,top:0}}}}function Ef(){return{width:0,height:0}}var G_=class{constructor(e,t,n,s,o,l,d){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=s,this._coreService=o,this._decorationService=l,this._themeService=d,this._workCell=new Jr,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,s,o,l,d,f,m,p,b){let _=[],S=this._characterJoinerService.getJoinedCharacters(t),w=this._themeService.colors,x=e.getNoBgTrimmedLength();n&&x<l+1&&(x=l+1);let R,L=0,A="",W=0,H=0,U=0,q=0,Y=!1,I=0,F=!1,de=0,me=0,K=[],te=p!==-1&&b!==-1;for(let J=0;J<x;J++){e.loadCell(J,this._workCell);let Q=this._workCell.getWidth();if(Q===0)continue;let X=!1,M=J>=me,T=J,O=this._workCell;if(S.length>0&&J===S[0][0]&&M){let j=S.shift(),ge=this._isCellInSelection(j[0],t);for(W=j[0]+1;W<j[1];W++)M&&=ge===this._isCellInSelection(W,t);M&&=!n||l<j[0]||l>=j[1],M?(X=!0,O=new oO(this._workCell,e.translateToString(!0,j[0],j[1]),j[1]-j[0]),T=j[1]-1,Q=O.getWidth()):me=j[1]}let re=this._isCellInSelection(J,t),he=n&&J===l,N=te&&J>=p&&J<=b,V=!1;this._decorationService.forEachDecorationAtCell(J,t,void 0,j=>{V=!0});let se=O.getChars()||No;if(se===" "&&(O.isUnderline()||O.isOverline())&&(se=" "),de=Q*f-m.get(se,O.isBold(),O.isItalic()),!R)R=this._document.createElement("span");else if(L&&(re&&F||!re&&!F&&O.bg===H)&&(re&&F&&w.selectionForeground||O.fg===U)&&O.extended.ext===q&&N===Y&&de===I&&!he&&!X&&!V&&M){O.isInvisible()?A+=No:A+=se,L++;continue}else L&&(R.textContent=A),R=this._document.createElement("span"),L=0,A="";if(H=O.bg,U=O.fg,q=O.extended.ext,Y=N,I=de,F=re,X&&l>=J&&l<=T&&(l=J),!this._coreService.isCursorHidden&&he&&this._coreService.isCursorInitialized){if(K.push("xterm-cursor"),this._coreBrowserService.isFocused)d&&K.push("xterm-cursor-blink"),K.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(o)switch(o){case"outline":K.push("xterm-cursor-outline");break;case"block":K.push("xterm-cursor-block");break;case"bar":K.push("xterm-cursor-bar");break;case"underline":K.push("xterm-cursor-underline");break}}if(O.isBold()&&K.push("xterm-bold"),O.isItalic()&&K.push("xterm-italic"),O.isDim()&&K.push("xterm-dim"),O.isInvisible()?A=No:A=O.getChars()||No,O.isUnderline()&&(K.push(`xterm-underline-${O.extended.underlineStyle}`),A===" "&&(A=" "),!O.isUnderlineColorDefault()))if(O.isUnderlineColorRGB())R.style.textDecorationColor=`rgb(${ph.toColorRGB(O.getUnderlineColor()).join(",")})`;else{let j=O.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&O.isBold()&&j<8&&(j+=8),R.style.textDecorationColor=w.ansi[j].css}O.isOverline()&&(K.push("xterm-overline"),A===" "&&(A=" ")),O.isStrikethrough()&&K.push("xterm-strikethrough"),N&&(R.style.textDecoration="underline");let Z=O.getFgColor(),Ee=O.getFgColorMode(),ye=O.getBgColor(),ze=O.getBgColorMode(),Ke=!!O.isInverse();if(Ke){let j=Z;Z=ye,ye=j;let ge=Ee;Ee=ze,ze=ge}let Be,ve,Fe=!1;this._decorationService.forEachDecorationAtCell(J,t,void 0,j=>{j.options.layer!=="top"&&Fe||(j.backgroundColorRGB&&(ze=50331648,ye=j.backgroundColorRGB.rgba>>8&16777215,Be=j.backgroundColorRGB),j.foregroundColorRGB&&(Ee=50331648,Z=j.foregroundColorRGB.rgba>>8&16777215,ve=j.foregroundColorRGB),Fe=j.options.layer==="top")}),!Fe&&re&&(Be=this._coreBrowserService.isFocused?w.selectionBackgroundOpaque:w.selectionInactiveBackgroundOpaque,ye=Be.rgba>>8&16777215,ze=50331648,Fe=!0,w.selectionForeground&&(Ee=50331648,Z=w.selectionForeground.rgba>>8&16777215,ve=w.selectionForeground)),Fe&&K.push("xterm-decoration-top");let Ie;switch(ze){case 16777216:case 33554432:Ie=w.ansi[ye],K.push(`xterm-bg-${ye}`);break;case 50331648:Ie=ti.toColor(ye>>16,ye>>8&255,ye&255),this._addStyle(R,`background-color:#${xx((ye>>>0).toString(16),"0",6)}`);break;default:Ke?(Ie=w.foreground,K.push("xterm-bg-257")):Ie=w.background}switch(Be||O.isDim()&&(Be=yn.multiplyOpacity(Ie,.5)),Ee){case 16777216:case 33554432:O.isBold()&&Z<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Z+=8),this._applyMinimumContrast(R,Ie,w.ansi[Z],O,Be,void 0)||K.push(`xterm-fg-${Z}`);break;case 50331648:let j=ti.toColor(Z>>16&255,Z>>8&255,Z&255);this._applyMinimumContrast(R,Ie,j,O,Be,ve)||this._addStyle(R,`color:#${xx(Z.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(R,Ie,w.foreground,O,Be,ve)||Ke&&K.push("xterm-fg-257")}K.length&&(R.className=K.join(" "),K.length=0),!he&&!X&&!V&&M?L++:R.textContent=A,de!==this.defaultSpacing&&(R.style.letterSpacing=`${de}px`),_.push(R),J=T}return R&&L&&(R.textContent=A),_}_applyMinimumContrast(e,t,n,s,o,l){if(this._optionsService.rawOptions.minimumContrastRatio===1||uO(s.getCode()))return!1;let d=this._getContrastCache(s),f;if(!o&&!l&&(f=d.getColor(t.rgba,n.rgba)),f===void 0){let m=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);f=yn.ensureContrastRatio(o||t,l||n,m),d.setColor((o||t).rgba,(l||n).rgba,f??null)}return f?(this._addStyle(e,`color:${f.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,s=this._selectionEnd;return!n||!s?!1:this._columnSelectMode?n[0]<=s[0]?e>=n[0]&&t>=n[1]&&e<s[0]&&t<=s[1]:e<n[0]&&t>=n[1]&&e>=s[0]&&t<=s[1]:t>n[1]&&t<s[1]||n[1]===s[1]&&t===n[1]&&e>=n[0]&&e<s[0]||n[1]<s[1]&&t===s[1]&&e<s[0]||n[1]<s[1]&&t===n[1]&&e>=n[0]}};G_=On([Ve(1,JT),Ve(2,Yi),Ve(3,Pa),Ve(4,Fl),Ve(5,mh),Ve(6,ou)],G_);function xx(e,t,n){for(;e.length<n;)e=t+e;return e}var hO=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let n=e.createElement("span");n.classList.add("xterm-char-measure-element");let s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";let o=e.createElement("span");o.classList.add("xterm-char-measure-element"),o.style.fontStyle="italic";let l=e.createElement("span");l.classList.add("xterm-char-measure-element"),l.style.fontWeight="bold",l.style.fontStyle="italic",this._measureElements=[n,s,o,l],this._container.appendChild(n),this._container.appendChild(s),this._container.appendChild(o),this._container.appendChild(l),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,s){e===this._font&&t===this._fontSize&&n===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,n){let s=0;if(!t&&!n&&e.length===1&&(s=e.charCodeAt(0))<256){if(this._flat[s]!==-9999)return this._flat[s];let d=this._measure(e,0);return d>0&&(this._flat[s]=d),d}let o=e;t&&(o+="B"),n&&(o+="I");let l=this._holey.get(o);if(l===void 0){let d=0;t&&(d|=1),n&&(d|=2),l=this._measure(e,d),l>0&&this._holey.set(o,l)}return l}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},fO=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,s=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let o=e.buffers.active.ydisp,l=t[1]-o,d=n[1]-o,f=Math.max(l,0),m=Math.min(d,e.rows-1);if(f>=e.rows||m<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=l,this.viewportEndRow=d,this.viewportCappedStartRow=f,this.viewportCappedEndRow=m,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function pO(){return new fO}var gv="xterm-dom-renderer-owner-",qr="xterm-rows",Rf="xterm-fg-",Cx="xterm-bg-",ud="xterm-focus",Nf="xterm-selection",mO=1,X_=class extends Nt{constructor(e,t,n,s,o,l,d,f,m,p,b,_,S,w){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=s,this._viewportElement=o,this._helperContainer=l,this._linkifier2=d,this._charSizeService=m,this._optionsService=p,this._bufferService=b,this._coreService=_,this._coreBrowserService=S,this._themeService=w,this._terminalClass=mO++,this._rowElements=[],this._selectionRenderModel=pO(),this.onRequestRedraw=this._register(new He).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(qr),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Nf),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=dO(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(x=>this._injectCss(x))),this._injectCss(this._themeService.colors),this._rowFactory=f.createInstance(G_,document),this._element.classList.add(gv+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(x=>this._handleLinkHover(x))),this._register(this._linkifier2.onHideLinkUnderline(x=>this._handleLinkLeave(x))),this._register(Cn(()=>{this._element.classList.remove(gv+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new hO(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let n of this._rowElements)n.style.width=`${this.dimensions.css.canvas.width}px`,n.style.height=`${this.dimensions.css.cell.height}px`,n.style.lineHeight=`${this.dimensions.css.cell.height}px`,n.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${qr} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${qr} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${qr} .xterm-dim { color: ${yn.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,o=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${o} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${qr}.${ud} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${qr}.${ud} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${qr}.${ud} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${o} 1s step-end infinite;}${this._terminalSelector} .${qr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${qr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${qr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${qr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${qr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Nf} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Nf} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Nf} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[l,d]of e.ansi.entries())t+=`${this._terminalSelector} .${Rf}${l} { color: ${d.css}; }${this._terminalSelector} .${Rf}${l}.xterm-dim { color: ${yn.multiplyOpacity(d,.5).css}; }${this._terminalSelector} .${Cx}${l} { background-color: ${d.css}; }`;t+=`${this._terminalSelector} .${Rf}257 { color: ${yn.opaque(e.background).css}; }${this._terminalSelector} .${Rf}257.xterm-dim { color: ${yn.multiplyOpacity(yn.opaque(e.background),.5).css}; }${this._terminalSelector} .${Cx}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let n=this._rowElements.length;n<=t;n++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(ud),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ud),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,o=this._selectionRenderModel.viewportEndRow,l=this._selectionRenderModel.viewportCappedStartRow,d=this._selectionRenderModel.viewportCappedEndRow,f=this._document.createDocumentFragment();if(n){let m=e[0]>t[0];f.appendChild(this._createSelectionElement(l,m?t[0]:e[0],m?e[0]:t[0],d-l+1))}else{let m=s===l?e[0]:0,p=l===o?t[0]:this._bufferService.cols;f.appendChild(this._createSelectionElement(l,m,p));let b=d-l-1;if(f.appendChild(this._createSelectionElement(l+1,0,this._bufferService.cols,b)),l!==d){let _=o===d?t[0]:this._bufferService.cols;f.appendChild(this._createSelectionElement(d,0,_))}}this._selectionContainer.appendChild(f)}_createSelectionElement(e,t,n,s=1){let o=this._document.createElement("div"),l=t*this.dimensions.css.cell.width,d=this.dimensions.css.cell.width*(n-t);return l+d>this.dimensions.css.canvas.width&&(d=this.dimensions.css.canvas.width-l),o.style.height=`${s*this.dimensions.css.cell.height}px`,o.style.top=`${e*this.dimensions.css.cell.height}px`,o.style.left=`${l}px`,o.style.width=`${d}px`,o}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,s=n.ybase+n.y,o=Math.min(n.x,this._bufferService.cols-1),l=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,d=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let m=e;m<=t;m++){let p=m+n.ydisp,b=this._rowElements[m],_=n.lines.get(p);if(!b||!_)break;b.replaceChildren(...this._rowFactory.createRow(_,p,p===s,d,f,o,l,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${gv}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,s,o,l){n<0&&(e=0),s<0&&(t=0);let d=this._bufferService.rows-1;n=Math.max(Math.min(n,d),0),s=Math.max(Math.min(s,d),0),o=Math.min(o,this._bufferService.cols);let f=this._bufferService.buffer,m=f.ybase+f.y,p=Math.min(f.x,o-1),b=this._optionsService.rawOptions.cursorBlink,_=this._optionsService.rawOptions.cursorStyle,S=this._optionsService.rawOptions.cursorInactiveStyle;for(let w=n;w<=s;++w){let x=w+f.ydisp,R=this._rowElements[w],L=f.lines.get(x);if(!R||!L)break;R.replaceChildren(...this._rowFactory.createRow(L,x,x===m,_,S,p,b,this.dimensions.css.cell.width,this._widthCache,l?w===n?e:0:-1,l?(w===s?t:o)-1:-1))}}};X_=On([Ve(7,jy),Ve(8,nm),Ve(9,Yi),Ve(10,Vi),Ve(11,Fl),Ve(12,Pa),Ve(13,ou)],X_);var Z_=class extends Nt{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new He),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new vO(this._optionsService))}catch{this._measureStrategy=this._register(new gO(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};Z_=On([Ve(2,Yi)],Z_);var _E=class extends Nt{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},gO=class extends _E{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},vO=class extends _E{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},_O=class extends Nt{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new bO(this._window)),this._onDprChange=this._register(new He),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new He),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(Ei.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(vt(this._textarea,"focus",()=>this._isFocused=!0)),this._register(vt(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},bO=class extends Nt{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new eu),this._onDprChange=this._register(new He),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(Cn(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=vt(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},yO=class extends Nt{constructor(){super(),this.linkProviders=[],this._register(Cn(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function $y(e,t,n){let s=n.getBoundingClientRect(),o=e.getComputedStyle(n),l=parseInt(o.getPropertyValue("padding-left")),d=parseInt(o.getPropertyValue("padding-top"));return[t.clientX-s.left-l,t.clientY-s.top-d]}function SO(e,t,n,s,o,l,d,f,m){if(!l)return;let p=$y(e,t,n);if(p)return p[0]=Math.ceil((p[0]+(m?d/2:0))/d),p[1]=Math.ceil(p[1]/f),p[0]=Math.min(Math.max(p[0],1),s+(m?1:0)),p[1]=Math.min(Math.max(p[1],1),o),p}var Q_=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,s,o){return SO(window,e,t,n,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,o)}getMouseReportCoords(e,t){let n=$y(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};Q_=On([Ve(0,za),Ve(1,nm)],Q_);var wO=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},bE={};Aj(bE,{getSafariVersion:()=>CO,isChromeOS:()=>xE,isFirefox:()=>yE,isIpad:()=>kO,isIphone:()=>TO,isLegacyEdge:()=>xO,isLinux:()=>Fy,isMac:()=>Sp,isNode:()=>im,isSafari:()=>SE,isWindows:()=>wE});var im=typeof process<"u"&&"title"in process,gh=im?"node":navigator.userAgent,vh=im?"node":navigator.platform,yE=gh.includes("Firefox"),xO=gh.includes("Edge"),SE=/^((?!chrome|android).)*safari/i.test(gh);function CO(){if(!SE)return 0;let e=gh.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Sp=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(vh),kO=vh==="iPad",TO=vh==="iPhone",wE=["Windows","Win16","Win32","WinCE"].includes(vh),Fy=vh.indexOf("Linux")>=0,xE=/\bCrOS\b/.test(gh),CE=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,n=0,s=e.timeRemaining(),o=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),o=e.timeRemaining(),n*1.5>o){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=o}this.clear()}},EO=class extends CE{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},RO=class extends CE{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},wp=!im&&"requestIdleCallback"in window?RO:EO,NO=class{constructor(){this._queue=new wp}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},J_=class extends Nt{constructor(e,t,n,s,o,l,d,f,m){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=s,this._coreService=o,this._coreBrowserService=f,this._renderer=this._register(new eu),this._pausedResizeTask=new NO,this._observerDisposable=this._register(new eu),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new He),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new He),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new He),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new He),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new wO((p,b)=>this._renderRows(p,b),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new DO(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(Cn(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(d.onResize(()=>this._fullRefresh())),this._register(d.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(l.onDecorationRegistered(()=>this._fullRefresh())),this._register(l.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(d.cols,d.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(d.buffer.y,d.buffer.y,!0))),this._register(m.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(p=>this._registerIntersectionObserver(p,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let n=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=Cn(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};J_=On([Ve(2,Yi),Ve(3,nm),Ve(4,Fl),Ve(5,mh),Ve(6,Vi),Ve(7,Pa),Ve(8,ou)],J_);var DO=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function MO(e,t,n,s){let o=n.buffer.x,l=n.buffer.y;if(!n.buffer.hasScrollback)return jO(o,l,e,t,n,s)+rm(l,t,n,s)+OO(o,l,e,t,n,s);let d;if(l===t)return d=o>e?"D":"C",Yd(Math.abs(o-e),Vd(d,s));d=l>t?"D":"C";let f=Math.abs(l-t),m=LO(l>t?e:o,n)+(f-1)*n.cols+1+AO(l>t?o:e);return Yd(m,Vd(d,s))}function AO(e,t){return e-1}function LO(e,t){return t.cols-e}function jO(e,t,n,s,o,l){return rm(t,s,o,l).length===0?"":Yd(TE(e,t,e,t-Hl(t,o),!1,o).length,Vd("D",l))}function rm(e,t,n,s){let o=e-Hl(e,n),l=t-Hl(t,n),d=Math.abs(o-l)-BO(e,t,n);return Yd(d,Vd(kE(e,t),s))}function OO(e,t,n,s,o,l){let d;rm(t,s,o,l).length>0?d=s-Hl(s,o):d=t;let f=s,m=IO(e,t,n,s,o,l);return Yd(TE(e,d,n,f,m==="C",o).length,Vd(m,l))}function BO(e,t,n){let s=0,o=e-Hl(e,n),l=t-Hl(t,n);for(let d=0;d<Math.abs(o-l);d++){let f=kE(e,t)==="A"?-1:1;n.buffer.lines.get(o+f*d)?.isWrapped&&s++}return s}function Hl(e,t){let n=0,s=t.buffer.lines.get(e),o=s?.isWrapped;for(;o&&e>=0&&e<t.rows;)n++,s=t.buffer.lines.get(--e),o=s?.isWrapped;return n}function IO(e,t,n,s,o,l){let d;return rm(n,s,o,l).length>0?d=s-Hl(s,o):d=t,e<n&&d<=s||e>=n&&d<s?"C":"D"}function kE(e,t){return e>t?"A":"B"}function TE(e,t,n,s,o,l){let d=e,f=t,m="";for(;(d!==n||f!==s)&&f>=0&&f<l.buffer.lines.length;)d+=o?1:-1,o&&d>l.cols-1?(m+=l.buffer.translateBufferLineToString(f,!1,e,d),d=0,e=0,f++):!o&&d<0&&(m+=l.buffer.translateBufferLineToString(f,!1,0,e+1),d=l.cols-1,e=d,f--);return m+l.buffer.translateBufferLineToString(f,!1,e,d)}function Vd(e,t){let n=t?"O":"[";return De.ESC+n+e}function Yd(e,t){e=Math.floor(e);let n="";for(let s=0;s<e;s++)n+=t;return n}var PO=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function kx(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var vv=50,zO=15,HO=50,UO=500,$O=" ",FO=new RegExp($O,"g"),eb=class extends Nt{constructor(e,t,n,s,o,l,d,f,m){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=s,this._coreService=o,this._mouseService=l,this._optionsService=d,this._renderService=f,this._coreBrowserService=m,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Jr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new He),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new He),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new He),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new He),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=p=>this._handleMouseMove(p),this._mouseUpListener=p=>this._handleMouseUp(p),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(p=>this._handleTrim(p)),this._register(this._bufferService.buffers.onBufferActivate(p=>this._handleBufferActivate(p))),this.enable(),this._model=new PO(this._bufferService),this._activeSelectionMode=0,this._register(Cn(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(p=>{p.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let n=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let o=e[0]<t[0]?e[0]:t[0],l=e[0]<t[0]?t[0]:e[0];for(let d=e[1];d<=t[1];d++){let f=n.translateBufferLineToString(d,!0,o,l);s.push(f)}}else{let o=e[1]===t[1]?t[0]:void 0;s.push(n.translateBufferLineToString(e[1],!0,e[0],o));for(let l=e[1]+1;l<=t[1]-1;l++){let d=n.lines.get(l),f=n.translateBufferLineToString(l,!0);d?.isWrapped?s[s.length-1]+=f:s.push(f)}if(e[1]!==t[1]){let l=n.lines.get(t[1]),d=n.translateBufferLineToString(t[1],!0,0,t[0]);l&&l.isWrapped?s[s.length-1]+=d:s.push(d)}}return s.map(o=>o.replace(FO," ")).join(wE?`\r
27
+ `:`
28
+ `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Fy&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!n||!s||!t?!1:this._areCoordsInSelection(t,n,s)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!n||!s?!1:this._areCoordsInSelection([e,t],n,s)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=kx(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=$y(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-vv),vv),t/=vv,t/Math.abs(t)+Math.round(t*(zO-1)))}shouldForceSelection(e){return Sp?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),HO)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Sp&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let s=n.lines.get(this._model.selectionEnd[1]);s&&s.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<UO&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let n=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(n&&n[0]!==void 0&&n[1]!==void 0){let s=MO(n[0]-1,n[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(s,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!n){this._oldHasSelection&&this._fireOnSelectionChange(e,t,n);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(t=>this._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let s=0;t>=s;s++){let o=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:o>1&&t!==s&&(n+=o-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let o=this._bufferService.buffer,l=o.lines.get(e[1]);if(!l)return;let d=o.translateBufferLineToString(e[1],!1),f=this._convertViewportColToCharacterIndex(l,e[0]),m=f,p=e[0]-f,b=0,_=0,S=0,w=0;if(d.charAt(f)===" "){for(;f>0&&d.charAt(f-1)===" ";)f--;for(;m<d.length&&d.charAt(m+1)===" ";)m++}else{let L=e[0],A=e[0];l.getWidth(L)===0&&(b++,L--),l.getWidth(A)===2&&(_++,A++);let W=l.getString(A).length;for(W>1&&(w+=W-1,m+=W-1);L>0&&f>0&&!this._isCharWordSeparator(l.loadCell(L-1,this._workCell));){l.loadCell(L-1,this._workCell);let H=this._workCell.getChars().length;this._workCell.getWidth()===0?(b++,L--):H>1&&(S+=H-1,f-=H-1),f--,L--}for(;A<l.length&&m+1<d.length&&!this._isCharWordSeparator(l.loadCell(A+1,this._workCell));){l.loadCell(A+1,this._workCell);let H=this._workCell.getChars().length;this._workCell.getWidth()===2?(_++,A++):H>1&&(w+=H-1,m+=H-1),m++,A++}}m++;let x=f+p-b+S,R=Math.min(this._bufferService.cols,m-f+b+_-S-w);if(!(!t&&d.slice(f,m).trim()==="")){if(n&&x===0&&l.getCodePoint(0)!==32){let L=o.lines.get(e[1]-1);if(L&&l.isWrapped&&L.getCodePoint(this._bufferService.cols-1)!==32){let A=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(A){let W=this._bufferService.cols-A.start;x-=W,R+=W}}}if(s&&x+R===this._bufferService.cols&&l.getCodePoint(this._bufferService.cols-1)!==32){let L=o.lines.get(e[1]+1);if(L?.isWrapped&&L.getCodePoint(0)!==32){let A=this._getWordAt([0,e[1]+1],!1,!1,!0);A&&(R+=A.length)}}return{start:x,length:R}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=kx(n,this._bufferService.cols)}};eb=On([Ve(3,Vi),Ve(4,Fl),Ve(5,Oy),Ve(6,Yi),Ve(7,za),Ve(8,Pa)],eb);var Tx=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Ex=class{constructor(){this._color=new Tx,this._css=new Tx}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},ai=Object.freeze((()=>{let e=[Rn.toColor("#2e3436"),Rn.toColor("#cc0000"),Rn.toColor("#4e9a06"),Rn.toColor("#c4a000"),Rn.toColor("#3465a4"),Rn.toColor("#75507b"),Rn.toColor("#06989a"),Rn.toColor("#d3d7cf"),Rn.toColor("#555753"),Rn.toColor("#ef2929"),Rn.toColor("#8ae234"),Rn.toColor("#fce94f"),Rn.toColor("#729fcf"),Rn.toColor("#ad7fa8"),Rn.toColor("#34e2e2"),Rn.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let s=t[n/36%6|0],o=t[n/6%6|0],l=t[n%6];e.push({css:ti.toCss(s,o,l),rgba:ti.toRgba(s,o,l)})}for(let n=0;n<24;n++){let s=8+n*10;e.push({css:ti.toCss(s,s,s),rgba:ti.toRgba(s,s,s)})}return e})()),kl=Rn.toColor("#ffffff"),yd=Rn.toColor("#000000"),Rx=Rn.toColor("#ffffff"),Nx=yd,dd={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},WO=kl,tb=class extends Nt{constructor(e){super(),this._optionsService=e,this._contrastCache=new Ex,this._halfContrastCache=new Ex,this._onChangeColors=this._register(new He),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:kl,background:yd,cursor:Rx,cursorAccent:Nx,selectionForeground:void 0,selectionBackgroundTransparent:dd,selectionBackgroundOpaque:yn.blend(yd,dd),selectionInactiveBackgroundTransparent:dd,selectionInactiveBackgroundOpaque:yn.blend(yd,dd),scrollbarSliderBackground:yn.opacity(kl,.2),scrollbarSliderHoverBackground:yn.opacity(kl,.4),scrollbarSliderActiveBackground:yn.opacity(kl,.5),overviewRulerBorder:kl,ansi:ai.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=an(e.foreground,kl),t.background=an(e.background,yd),t.cursor=yn.blend(t.background,an(e.cursor,Rx)),t.cursorAccent=yn.blend(t.background,an(e.cursorAccent,Nx)),t.selectionBackgroundTransparent=an(e.selectionBackground,dd),t.selectionBackgroundOpaque=yn.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=an(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=yn.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?an(e.selectionForeground,wx):void 0,t.selectionForeground===wx&&(t.selectionForeground=void 0),yn.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=yn.opacity(t.selectionBackgroundTransparent,.3)),yn.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=yn.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=an(e.scrollbarSliderBackground,yn.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=an(e.scrollbarSliderHoverBackground,yn.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=an(e.scrollbarSliderActiveBackground,yn.opacity(t.foreground,.5)),t.overviewRulerBorder=an(e.overviewRulerBorder,WO),t.ansi=ai.slice(),t.ansi[0]=an(e.black,ai[0]),t.ansi[1]=an(e.red,ai[1]),t.ansi[2]=an(e.green,ai[2]),t.ansi[3]=an(e.yellow,ai[3]),t.ansi[4]=an(e.blue,ai[4]),t.ansi[5]=an(e.magenta,ai[5]),t.ansi[6]=an(e.cyan,ai[6]),t.ansi[7]=an(e.white,ai[7]),t.ansi[8]=an(e.brightBlack,ai[8]),t.ansi[9]=an(e.brightRed,ai[9]),t.ansi[10]=an(e.brightGreen,ai[10]),t.ansi[11]=an(e.brightYellow,ai[11]),t.ansi[12]=an(e.brightBlue,ai[12]),t.ansi[13]=an(e.brightMagenta,ai[13]),t.ansi[14]=an(e.brightCyan,ai[14]),t.ansi[15]=an(e.brightWhite,ai[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;s<n;s++)t.ansi[s+16]=an(e.extendedAnsi[s],ai[s+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let t=0;t<this._restoreColors.ansi.length;++t)this._colors.ansi[t]=this._restoreColors.ansi[t];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};tb=On([Ve(0,Yi)],tb);function an(e,t){if(e!==void 0)try{return Rn.toColor(e)}catch{}return t}var KO=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},qO=class{constructor(){this._services=new KO,this._services.set(jy,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=zj(e).sort((l,d)=>l.index-d.index),s=[];for(let l of n){let d=this._services.get(l.id);if(!d)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${l.id._id}.`);s.push(d)}let o=n.length>0?n[0].index:t.length;if(t.length!==o)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${o+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},VO={trace:0,debug:1,info:2,warn:3,error:4,off:5},YO="xterm.js: ",nb=class extends Nt{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=VO[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]=="function"&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?"":YO)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};nb=On([Ve(0,Yi)],nb);var Dx=class extends Nt{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new He),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new He),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new He),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=new Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let s=e;s<this._length-t;s++)this._array[this._getCyclicIndex(s)]=this._array[this._getCyclicIndex(s+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let s=this._length-1;s>=e;s--)this._array[this._getCyclicIndex(s+n.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;s<n.length;s++)this._array[this._getCyclicIndex(e+s)]=n[s];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let s=this._length+n.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+n<0)throw new Error("Cannot shift elements in list beyond index 0");if(n>0){for(let o=t-1;o>=0;o--)this.set(e+o+n,this.get(e+o));let s=e+t+n-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s<t;s++)this.set(e+s+n,this.get(e+s))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},Rt=3,ei=Object.freeze(new ph),Df=0,_v=2,Sd=class EE{constructor(t,n,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(t*Rt);let o=n||Jr.fromCharData([0,qT,1,0]);for(let l=0;l<t;++l)this.setCell(l,o);this.length=t}get(t){let n=this._data[t*Rt+0],s=n&2097151;return[this._data[t*Rt+1],n&2097152?this._combined[t]:s?Eo(s):"",n>>22,n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,n){this._data[t*Rt+1]=n[0],n[1].length>1?(this._combined[t]=n[1],this._data[t*Rt+0]=t|2097152|n[2]<<22):this._data[t*Rt+0]=n[1].charCodeAt(0)|n[2]<<22}getWidth(t){return this._data[t*Rt+0]>>22}hasWidth(t){return this._data[t*Rt+0]&12582912}getFg(t){return this._data[t*Rt+1]}getBg(t){return this._data[t*Rt+2]}hasContent(t){return this._data[t*Rt+0]&4194303}getCodePoint(t){let n=this._data[t*Rt+0];return n&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n&2097151}isCombined(t){return this._data[t*Rt+0]&2097152}getString(t){let n=this._data[t*Rt+0];return n&2097152?this._combined[t]:n&2097151?Eo(n&2097151):""}isProtected(t){return this._data[t*Rt+2]&536870912}loadCell(t,n){return Df=t*Rt,n.content=this._data[Df+0],n.fg=this._data[Df+1],n.bg=this._data[Df+2],n.content&2097152&&(n.combinedData=this._combined[t]),n.bg&268435456&&(n.extended=this._extendedAttrs[t]),n}setCell(t,n){n.content&2097152&&(this._combined[t]=n.combinedData),n.bg&268435456&&(this._extendedAttrs[t]=n.extended),this._data[t*Rt+0]=n.content,this._data[t*Rt+1]=n.fg,this._data[t*Rt+2]=n.bg}setCellFromCodepoint(t,n,s,o){o.bg&268435456&&(this._extendedAttrs[t]=o.extended),this._data[t*Rt+0]=n|s<<22,this._data[t*Rt+1]=o.fg,this._data[t*Rt+2]=o.bg}addCodepointToCell(t,n,s){let o=this._data[t*Rt+0];o&2097152?this._combined[t]+=Eo(n):o&2097151?(this._combined[t]=Eo(o&2097151)+Eo(n),o&=-2097152,o|=2097152):o=n|1<<22,s&&(o&=-12582913,o|=s<<22),this._data[t*Rt+0]=o}insertCells(t,n,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),n<this.length-t){let o=new Jr;for(let l=this.length-t-n-1;l>=0;--l)this.setCell(t+n+l,this.loadCell(t+l,o));for(let l=0;l<n;++l)this.setCell(t+l,s)}else for(let o=t;o<this.length;++o)this.setCell(o,s);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(t,n,s){if(t%=this.length,n<this.length-t){let o=new Jr;for(let l=0;l<this.length-t-n;++l)this.setCell(t+l,this.loadCell(t+n+l,o));for(let l=this.length-n;l<this.length;++l)this.setCell(l,s)}else for(let o=t;o<this.length;++o)this.setCell(o,s);t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),this.getWidth(t)===0&&!this.hasContent(t)&&this.setCellFromCodepoint(t,0,1,s)}replaceCells(t,n,s,o=!1){if(o){for(t&&this.getWidth(t-1)===2&&!this.isProtected(t-1)&&this.setCellFromCodepoint(t-1,0,1,s),n<this.length&&this.getWidth(n-1)===2&&!this.isProtected(n)&&this.setCellFromCodepoint(n,0,1,s);t<n&&t<this.length;)this.isProtected(t)||this.setCell(t,s),t++;return}for(t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),n<this.length&&this.getWidth(n-1)===2&&this.setCellFromCodepoint(n,0,1,s);t<n&&t<this.length;)this.setCell(t++,s)}resize(t,n){if(t===this.length)return this._data.length*4*_v<this._data.buffer.byteLength;let s=t*Rt;if(t>this.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let o=new Uint32Array(s);o.set(this._data),this._data=o}for(let o=this.length;o<t;++o)this.setCell(o,n)}else{this._data=this._data.subarray(0,s);let o=Object.keys(this._combined);for(let d=0;d<o.length;d++){let f=parseInt(o[d],10);f>=t&&delete this._combined[f]}let l=Object.keys(this._extendedAttrs);for(let d=0;d<l.length;d++){let f=parseInt(l[d],10);f>=t&&delete this._extendedAttrs[f]}}return this.length=t,s*4*_v<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*_v<this._data.buffer.byteLength){let t=new Uint32Array(this._data.length);return t.set(this._data),this._data=t,1}return 0}fill(t,n=!1){if(n){for(let s=0;s<this.length;++s)this.isProtected(s)||this.setCell(s,t);return}this._combined={},this._extendedAttrs={};for(let s=0;s<this.length;++s)this.setCell(s,t)}copyFrom(t){this.length!==t.length?this._data=new Uint32Array(t._data):this._data.set(t._data),this.length=t.length,this._combined={};for(let n in t._combined)this._combined[n]=t._combined[n];this._extendedAttrs={};for(let n in t._extendedAttrs)this._extendedAttrs[n]=t._extendedAttrs[n];this.isWrapped=t.isWrapped}clone(){let t=new EE(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let n in this._combined)t._combined[n]=this._combined[n];for(let n in this._extendedAttrs)t._extendedAttrs[n]=this._extendedAttrs[n];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Rt+0]&4194303)return t+(this._data[t*Rt+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Rt+0]&4194303||this._data[t*Rt+2]&50331648)return t+(this._data[t*Rt+0]>>22);return 0}copyCellsFrom(t,n,s,o,l){let d=t._data;if(l)for(let m=o-1;m>=0;m--){for(let p=0;p<Rt;p++)this._data[(s+m)*Rt+p]=d[(n+m)*Rt+p];d[(n+m)*Rt+2]&268435456&&(this._extendedAttrs[s+m]=t._extendedAttrs[n+m])}else for(let m=0;m<o;m++){for(let p=0;p<Rt;p++)this._data[(s+m)*Rt+p]=d[(n+m)*Rt+p];d[(n+m)*Rt+2]&268435456&&(this._extendedAttrs[s+m]=t._extendedAttrs[n+m])}let f=Object.keys(t._combined);for(let m=0;m<f.length;m++){let p=parseInt(f[m],10);p>=n&&(this._combined[p-n+s]=t._combined[p])}}translateToString(t,n,s,o){n=n??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),o&&(o.length=0);let l="";for(;n<s;){let d=this._data[n*Rt+0],f=d&2097151,m=d&2097152?this._combined[n]:f?Eo(f):No;if(l+=m,o)for(let p=0;p<m.length;++p)o.push(n);n+=d>>22||1}return o&&o.push(n),l}};function GO(e,t,n,s,o,l){let d=[];for(let f=0;f<e.length-1;f++){let m=f,p=e.get(++m);if(!p.isWrapped)continue;let b=[e.get(f)];for(;m<e.length&&p.isWrapped;)b.push(p),p=e.get(++m);if(!l&&s>=f&&s<m){f+=b.length-1;continue}let _=0,S=Gd(b,_,t),w=1,x=0;for(;w<b.length;){let L=Gd(b,w,t),A=L-x,W=n-S,H=Math.min(A,W);b[_].copyCellsFrom(b[w],x,S,H,!1),S+=H,S===n&&(_++,S=0),x+=H,x===L&&(w++,x=0),S===0&&_!==0&&b[_-1].getWidth(n-1)===2&&(b[_].copyCellsFrom(b[_-1],n-1,S++,1,!1),b[_-1].setCell(n-1,o))}b[_].replaceCells(S,n,o);let R=0;for(let L=b.length-1;L>0&&(L>_||b[L].getTrimmedLength()===0);L--)R++;R>0&&(d.push(f+b.length-R),d.push(R)),f+=b.length-1}return d}function XO(e,t){let n=[],s=0,o=t[s],l=0;for(let d=0;d<e.length;d++)if(o===d){let f=t[++s];e.onDeleteEmitter.fire({index:d-l,amount:f}),d+=f-1,l+=f,o=t[++s]}else n.push(d);return{layout:n,countRemoved:l}}function ZO(e,t){let n=[];for(let s=0;s<t.length;s++)n.push(e.get(t[s]));for(let s=0;s<n.length;s++)e.set(s,n[s]);e.length=t.length}function QO(e,t,n){let s=[],o=e.map((m,p)=>Gd(e,p,t)).reduce((m,p)=>m+p),l=0,d=0,f=0;for(;f<o;){if(o-f<n){s.push(o-f);break}l+=n;let m=Gd(e,d,t);l>m&&(l-=m,d++);let p=e[d].getWidth(l-1)===2;p&&l--;let b=p?n-1:n;s.push(b),f+=b}return s}function Gd(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,o=e[t+1].getWidth(0)===2;return s&&o?n-1:n}var RE=class NE{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=NE._nextId++,this._onDispose=this.register(new He),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),zl(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};RE._nextId=1;var JO=RE,ui={},Tl=ui.B;ui[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};ui.A={"#":"£"};ui.B=void 0;ui[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};ui.C=ui[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ui.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};ui.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};ui.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};ui.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};ui.E=ui[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};ui.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};ui.H=ui[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};ui["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Mx=4294967295,Ax=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=ei.clone(),this.savedCharset=Tl,this.markers=[],this._nullCell=Jr.fromCharData([0,qT,1,0]),this._whitespaceCell=Jr.fromCharData([0,No,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new wp,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Dx(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new _p),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new _p),this._whitespaceCell}getBlankLine(e,t){return new Sd(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Mx?Mx:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=ei);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Dx(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(ei),s=0,o=this._getCorrectBufferLength(t);if(o>this.lines.maxLength&&(this.lines.maxLength=o),this.lines.length>0){if(this._cols<e)for(let d=0;d<this.lines.length;d++)s+=+this.lines.get(d).resize(e,n);let l=0;if(this._rows<t)for(let d=this._rows;d<t;d++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new Sd(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+l+1?(this.ybase--,l++,this.ydisp>0&&this.ydisp--):this.lines.push(new Sd(e,n)));else for(let d=this._rows;d>t;d--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(o<this.lines.maxLength){let d=this.lines.length-o;d>0&&(this.lines.trimStart(d),this.ybase=Math.max(this.ybase-d,0),this.ydisp=Math.max(this.ydisp-d,0),this.savedY=Math.max(this.savedY-d,0)),this.lines.maxLength=o}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),l&&(this.y+=l),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let l=0;l<this.lines.length;l++)s+=+this.lines.get(l).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),s>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,s=GO(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(ei),n);if(s.length>0){let o=XO(this.lines,s);ZO(this.lines,o.layout),this._reflowLargerAdjustViewport(e,t,o.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let s=this.getNullCell(ei),o=n;for(;o-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new Sd(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,s=this.getNullCell(ei),o=[],l=0;for(let d=this.lines.length-1;d>=0;d--){let f=this.lines.get(d);if(!f||!f.isWrapped&&f.getTrimmedLength()<=e)continue;let m=[f];for(;f.isWrapped&&d>0;)f=this.lines.get(--d),m.unshift(f);if(!n){let H=this.ybase+this.y;if(H>=d&&H<d+m.length)continue}let p=m[m.length-1].getTrimmedLength(),b=QO(m,this._cols,e),_=b.length-m.length,S;this.ybase===0&&this.y!==this.lines.length-1?S=Math.max(0,this.y-this.lines.maxLength+_):S=Math.max(0,this.lines.length-this.lines.maxLength+_);let w=[];for(let H=0;H<_;H++){let U=this.getBlankLine(ei,!0);w.push(U)}w.length>0&&(o.push({start:d+m.length+l,newLines:w}),l+=w.length),m.push(...w);let x=b.length-1,R=b[x];R===0&&(x--,R=b[x]);let L=m.length-_-1,A=p;for(;L>=0;){let H=Math.min(A,R);if(m[x]===void 0)break;if(m[x].copyCellsFrom(m[L],A-H,R-H,H,!0),R-=H,R===0&&(x--,R=b[x]),A-=H,A===0){L--;let U=Math.max(L,0);A=Gd(m,U,this._cols)}}for(let H=0;H<m.length;H++)b[H]<e&&m[H].setCell(b[H],s);let W=_-S;for(;W-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+l)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+_,this.ybase+t-1)}if(o.length>0){let d=[],f=[];for(let R=0;R<this.lines.length;R++)f.push(this.lines.get(R));let m=this.lines.length,p=m-1,b=0,_=o[b];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+l);let S=0;for(let R=Math.min(this.lines.maxLength-1,m+l-1);R>=0;R--)if(_&&_.start>p+S){for(let L=_.newLines.length-1;L>=0;L--)this.lines.set(R--,_.newLines[L]);R++,d.push({index:p+1,amount:_.newLines.length}),S+=_.newLines.length,_=o[++b]}else this.lines.set(R,f[p--]);let w=0;for(let R=d.length-1;R>=0;R--)d[R].index+=w,this.lines.onInsertEmitter.fire(d[R]),w+=d[R].amount;let x=Math.max(0,m+l-this.lines.maxLength);x>0&&this.lines.onTrimEmitter.fire(x)}}translateBufferLineToString(e,t,n=0,s){let o=this.lines.get(e);return o?o.translateToString(t,n,s):""}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e!=null?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e==null&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new JO(e);return this.markers.push(t),t.register(this.lines.onTrim(n=>{t.line-=n,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(n=>{t.line>=n.index&&(t.line+=n.amount)})),t.register(this.lines.onDelete(n=>{t.line>=n.index&&t.line<n.index+n.amount&&t.dispose(),t.line>n.index&&(t.line-=n.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},eB=class extends Nt{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new He),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ax(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ax(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},DE=2,ME=1,ib=class extends Nt{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new He),this.onResize=this._onResize.event,this._onScroll=this._register(new He),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,DE),this.rows=Math.max(e.rawOptions.rows||0,ME),this.buffers=this._register(new eB(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=n.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let o=n.ybase+n.scrollTop,l=n.ybase+n.scrollBottom;if(n.scrollTop===0){let d=n.lines.isFull;l===n.lines.length-1?d?n.lines.recycle().copyFrom(s):n.lines.push(s.clone()):n.lines.splice(l+1,0,s.clone()),d?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let d=l-o+1;n.lines.shiftElements(o+1,d-1,-1),n.lines.set(l,s.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let s=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),s!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};ib=On([Ve(0,Yi)],ib);var Ac={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Sp,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},tB=["normal","bold","100","200","300","400","500","600","700","800","900"],nB=class extends Nt{constructor(e){super(),this._onOptionChange=this._register(new He),this.onOptionChange=this._onOptionChange.event;let t={...Ac};for(let n in e)if(n in t)try{let s=e[n];t[n]=this._sanitizeAndValidateOption(n,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(Cn(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=n=>{if(!(n in Ac))throw new Error(`No option with key "${n}"`);return this.rawOptions[n]},t=(n,s)=>{if(!(n in Ac))throw new Error(`No option with key "${n}"`);s=this._sanitizeAndValidateOption(n,s),this.rawOptions[n]!==s&&(this.rawOptions[n]=s,this._onOptionChange.fire(n))};for(let n in this.rawOptions){let s={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Ac[e]),!iB(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ac[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=tB.includes(t)?t:Ac[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function iB(e){return e==="block"||e==="underline"||e==="bar"}function wd(e,t=5){if(typeof e!="object")return e;let n=Array.isArray(e)?[]:{};for(let s in e)n[s]=t<=1?e[s]:e[s]&&wd(e[s],t-1);return n}var Lx=Object.freeze({insertMode:!1}),jx=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),rb=class extends Nt{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new He),this.onData=this._onData.event,this._onUserInput=this._register(new He),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new He),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new He),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=wd(Lx),this.decPrivateModes=wd(jx)}reset(){this.modes=wd(Lx),this.decPrivateModes=wd(jx)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};rb=On([Ve(0,Vi),Ve(1,ZT),Ve(2,Yi)],rb);var Ox={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function bv(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var yv=String.fromCharCode,Bx={DEFAULT:e=>{let t=[bv(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${yv(t[0])}${yv(t[1])}${yv(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${bv(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${bv(e,!0)};${e.x};${e.y}${t}`}},sb=class extends Nt{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new He),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(Ox))this.addProtocol(s,Ox[s]);for(let s of Object.keys(Bx))this.addEncoding(s,Bx[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let s=t/n,o=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(o/=s+0,Math.abs(e.deltaY)<50&&(o*=.3),this._wheelPartialScroll+=o,o=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(o*=this._bufferService.rows),o}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};sb=On([Ve(0,Vi),Ve(1,Fl),Ve(2,Yi)],sb);var Sv=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],rB=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],oi;function sB(e,t){let n=0,s=t.length-1,o;if(e<t[0][0]||e>t[s][1])return!1;for(;s>=n;)if(o=n+s>>1,e>t[o][1])n=o+1;else if(e<t[o][0])s=o-1;else return!0;return!1}var aB=class{constructor(){if(this.version="6",!oi){oi=new Uint8Array(65536),oi.fill(1),oi[0]=0,oi.fill(0,1,32),oi.fill(0,127,160),oi.fill(2,4352,4448),oi[9001]=2,oi[9002]=2,oi.fill(2,11904,42192),oi[12351]=1,oi.fill(2,44032,55204),oi.fill(2,63744,64256),oi.fill(2,65040,65050),oi.fill(2,65072,65136),oi.fill(2,65280,65377),oi.fill(2,65504,65511);for(let e=0;e<Sv.length;++e)oi.fill(0,Sv[e][0],Sv[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?oi[e]:sB(e,rB)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),s=n===0&&t!==0;if(s){let o=Nl.extractWidth(t);o===0?s=!1:o>n&&(n=o)}return Nl.createPropertyValue(0,n,s)}},Nl=class Vf{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new He,this.onChange=this._onChange.event;let t=new aB;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,n,s=!1){return(t&16777215)<<3|(n&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let n=0,s=0,o=t.length;for(let l=0;l<o;++l){let d=t.charCodeAt(l);if(55296<=d&&d<=56319){if(++l>=o)return n+this.wcwidth(d);let p=t.charCodeAt(l);56320<=p&&p<=57343?d=(d-55296)*1024+p-56320+65536:n+=this.wcwidth(p)}let f=this.charProperties(d,s),m=Vf.extractWidth(f);Vf.extractShouldJoin(f)&&(m-=Vf.extractWidth(s)),n+=m,s=f}return n}charProperties(t,n){return this._activeProvider.charProperties(t,n)}},oB=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Ix(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var hd=2147483647,lB=256,AE=class ab{constructor(t=32,n=32){if(this.maxLength=t,this.maxSubParamsLength=n,n>lB)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(n),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new ab;if(!t.length)return n;for(let s=Array.isArray(t[0])?1:0;s<t.length;++s){let o=t[s];if(Array.isArray(o))for(let l=0;l<o.length;++l)n.addSubParam(o[l]);else n.addParam(o)}return n}clone(){let t=new ab(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let t=[];for(let n=0;n<this.length;++n){t.push(this.params[n]);let s=this._subParamsIdx[n]>>8,o=this._subParamsIdx[n]&255;o-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,o))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>hd?hd:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>hd?hd:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let n=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-n>0?this._subParams.subarray(n,s):null}getSubParamsAll(){let t={};for(let n=0;n<this.length;++n){let s=this._subParamsIdx[n]>>8,o=this._subParamsIdx[n]&255;o-s>0&&(t[n]=this._subParams.slice(s,o))}return t}addDigit(t){let n;if(this._rejectDigits||!(n=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,o=s[n-1];s[n-1]=~o?Math.min(o*10+t,hd):t}},fd=[],cB=class{constructor(){this._state=0,this._active=fd,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let s=n.indexOf(t);s!==-1&&n.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=fd}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=fd,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||fd,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,"PUT",tm(e,t,n));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let s=e[t++];if(s===59){this._state=2,this._start();break}if(s<48||57<s){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+s-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let n=!1,s=this._active.length-1,o=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,n=t,o=this._stack.fallThrough,this._stack.paused=!1),!o&&n===!1){for(;s>=0&&(n=this._active[s].end(e),n!==!0);s--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,n;s--}for(;s>=0;s--)if(n=this._active[s].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,n}this._active=fd,this._id=-1,this._state=0}}},Er=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=tm(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(n=>(this._data="",this._hitLimit=!1,n));return this._data="",this._hitLimit=!1,t}},pd=[],uB=class{constructor(){this._handlers=Object.create(null),this._active=pd,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=pd}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let s=n.indexOf(t);s!==-1&&n.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=pd,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||pd,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let n=this._active.length-1;n>=0;n--)this._active[n].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,"PUT",tm(e,t,n));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let n=!1,s=this._active.length-1,o=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,n=t,o=this._stack.fallThrough,this._stack.paused=!1),!o&&n===!1){for(;s>=0&&(n=this._active[s].unhook(e),n!==!0);s--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,n;s--}for(;s>=0;s--)if(n=this._active[s].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,n}this._active=pd,this._ident=0}},xd=new AE;xd.addParam(0);var Px=class{constructor(e){this._handler=e,this._data="",this._params=xd,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():xd,this._data="",this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=tm(e,t,n),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(n=>(this._params=xd,this._data="",this._hitLimit=!1,n));return this._params=xd,this._data="",this._hitLimit=!1,t}},dB=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,s){this.table[t<<8|e]=n<<4|s}addMany(e,t,n,s){for(let o=0;o<e.length;o++)this.table[t<<8|e[o]]=n<<4|s}},Zr=160,hB=(function(){let e=new dB(4095),t=Array.apply(null,Array(256)).map((f,m)=>m),n=(f,m)=>t.slice(f,m),s=n(32,127),o=n(0,24);o.push(25),o.push.apply(o,n(28,32));let l=n(0,14),d;e.setDefault(1,0),e.addMany(s,0,2,0);for(d in l)e.addMany([24,26,153,154],d,3,0),e.addMany(n(128,144),d,3,0),e.addMany(n(144,152),d,3,0),e.add(156,d,0,0),e.add(27,d,11,1),e.add(157,d,4,8),e.addMany([152,158,159],d,0,7),e.add(155,d,11,3),e.add(144,d,11,9);return e.addMany(o,0,3,0),e.addMany(o,1,3,1),e.add(127,1,0,1),e.addMany(o,8,0,8),e.addMany(o,3,3,3),e.add(127,3,0,3),e.addMany(o,4,3,4),e.add(127,4,0,4),e.addMany(o,6,3,6),e.addMany(o,5,3,5),e.add(127,5,0,5),e.addMany(o,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(o,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(o,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(o,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(o,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(o,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(o,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Zr,0,2,0),e.add(Zr,8,5,8),e.add(Zr,6,0,6),e.add(Zr,11,0,11),e.add(Zr,13,13,13),e})(),fB=class extends Nt{constructor(e=hB){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new AE,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,n,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,n)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(Cn(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new cB),this._dcsParser=this._register(new uB),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let o=0;o<e.intermediates.length;++o){let l=e.intermediates.charCodeAt(o);if(32>l||l>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");n<<=8,n|=l}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=s,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let s=this._escHandlers[n];return s.push(t),{dispose:()=>{let o=s.indexOf(t);o!==-1&&s.splice(o,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let s=this._csiHandlers[n];return s.push(t),{dispose:()=>{let o=s.indexOf(t);o!==-1&&s.splice(o,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,s,o){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=s,this._parseStack.chunkPos=o}parse(e,t,n){let s=0,o=0,l=0,d;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,l=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let f=this._parseStack.handlers,m=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&m>-1){for(;m>=0&&(d=f[m](this._params),d!==!0);m--)if(d instanceof Promise)return this._parseStack.handlerPos=m,d}this._parseStack.handlers=[];break;case 4:if(n===!1&&m>-1){for(;m>=0&&(d=f[m](),d!==!0);m--)if(d instanceof Promise)return this._parseStack.handlerPos=m,d}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],d=this._dcsParser.unhook(s!==24&&s!==26,n),d)return d;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],d=this._oscParser.end(s!==24&&s!==26,n),d)return d;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,l=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let f=l;f<t;++f){switch(s=e[f],o=this._transitions.table[this.currentState<<8|(s<160?s:Zr)],o>>4){case 2:for(let S=f+1;;++S){if(S>=t||(s=e[S])<32||s>126&&s<Zr){this._printHandler(e,f,S),f=S-1;break}if(++S>=t||(s=e[S])<32||s>126&&s<Zr){this._printHandler(e,f,S),f=S-1;break}if(++S>=t||(s=e[S])<32||s>126&&s<Zr){this._printHandler(e,f,S),f=S-1;break}if(++S>=t||(s=e[S])<32||s>126&&s<Zr){this._printHandler(e,f,S),f=S-1;break}}break;case 3:this._executeHandlers[s]?this._executeHandlers[s]():this._executeHandlerFb(s),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:f,code:s,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let m=this._csiHandlers[this._collect<<8|s],p=m?m.length-1:-1;for(;p>=0&&(d=m[p](this._params),d!==!0);p--)if(d instanceof Promise)return this._preserveStack(3,m,p,o,f),d;p<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++f<t&&(s=e[f])>47&&s<60);f--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let b=this._escHandlers[this._collect<<8|s],_=b?b.length-1:-1;for(;_>=0&&(d=b[_](),d!==!0);_--)if(d instanceof Promise)return this._preserveStack(4,b,_,o,f),d;_<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let S=f+1;;++S)if(S>=t||(s=e[S])===24||s===26||s===27||s>127&&s<Zr){this._dcsParser.put(e,f,S),f=S-1;break}break;case 14:if(d=this._dcsParser.unhook(s!==24&&s!==26),d)return this._preserveStack(6,[],0,o,f),d;s===27&&(o|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let S=f+1;;S++)if(S>=t||(s=e[S])<32||s>127&&s<Zr){this._oscParser.put(e,f,S),f=S-1;break}break;case 6:if(d=this._oscParser.end(s!==24&&s!==26),d)return this._preserveStack(5,[],0,o,f),d;s===27&&(o|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=o&15}}},pB=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,mB=/^[\da-f]+$/;function zx(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf("rgb:")===0){t=t.slice(4);let n=pB.exec(t);if(n){let s=n[1]?15:n[4]?255:n[7]?4095:65535;return[Math.round(parseInt(n[1]||n[4]||n[7]||n[10],16)/s*255),Math.round(parseInt(n[2]||n[5]||n[8]||n[11],16)/s*255),Math.round(parseInt(n[3]||n[6]||n[9]||n[12],16)/s*255)]}}else if(t.indexOf("#")===0&&(t=t.slice(1),mB.exec(t)&&[3,6,9,12].includes(t.length))){let n=t.length/3,s=[0,0,0];for(let o=0;o<3;++o){let l=parseInt(t.slice(n*o,n*o+n),16);s[o]=n===1?l<<4:n===2?l:n===3?l>>4:l>>8}return s}}function wv(e,t){let n=e.toString(16),s=n.length<2?"0"+n:n;switch(t){case 4:return n[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function gB(e,t=16){let[n,s,o]=e;return`rgb:${wv(n,t)}/${wv(s,t)}/${wv(o,t)}`}var vB={"(":0,")":1,"*":2,"+":3,"-":1,".":2},wo=131072,Hx=10;function Ux(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var $x=5e3,Fx=0,_B=class extends Nt{constructor(e,t,n,s,o,l,d,f,m=new fB){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=s,this._optionsService=o,this._oscLinkService=l,this._coreMouseService=d,this._unicodeService=f,this._parser=m,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Ij,this._utf8Decoder=new Pj,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=ei.clone(),this._eraseAttrDataInternal=ei.clone(),this._onRequestBell=this._register(new He),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new He),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new He),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new He),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new He),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new He),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new He),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new He),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new He),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new He),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new He),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new He),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new He),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new ob(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(p=>this._activeBuffer=p.activeBuffer)),this._parser.setCsiHandlerFallback((p,b)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(p),params:b.toArray()})}),this._parser.setEscHandlerFallback(p=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(p)})}),this._parser.setExecuteHandlerFallback(p=>{this._logService.debug("Unknown EXECUTE code: ",{code:p})}),this._parser.setOscHandlerFallback((p,b,_)=>{this._logService.debug("Unknown OSC code: ",{identifier:p,action:b,data:_})}),this._parser.setDcsHandlerFallback((p,b,_)=>{b==="HOOK"&&(_=_.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(p),action:b,payload:_})}),this._parser.setPrintHandler((p,b,_)=>this.print(p,b,_)),this._parser.registerCsiHandler({final:"@"},p=>this.insertChars(p)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},p=>this.scrollLeft(p)),this._parser.registerCsiHandler({final:"A"},p=>this.cursorUp(p)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},p=>this.scrollRight(p)),this._parser.registerCsiHandler({final:"B"},p=>this.cursorDown(p)),this._parser.registerCsiHandler({final:"C"},p=>this.cursorForward(p)),this._parser.registerCsiHandler({final:"D"},p=>this.cursorBackward(p)),this._parser.registerCsiHandler({final:"E"},p=>this.cursorNextLine(p)),this._parser.registerCsiHandler({final:"F"},p=>this.cursorPrecedingLine(p)),this._parser.registerCsiHandler({final:"G"},p=>this.cursorCharAbsolute(p)),this._parser.registerCsiHandler({final:"H"},p=>this.cursorPosition(p)),this._parser.registerCsiHandler({final:"I"},p=>this.cursorForwardTab(p)),this._parser.registerCsiHandler({final:"J"},p=>this.eraseInDisplay(p,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},p=>this.eraseInDisplay(p,!0)),this._parser.registerCsiHandler({final:"K"},p=>this.eraseInLine(p,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},p=>this.eraseInLine(p,!0)),this._parser.registerCsiHandler({final:"L"},p=>this.insertLines(p)),this._parser.registerCsiHandler({final:"M"},p=>this.deleteLines(p)),this._parser.registerCsiHandler({final:"P"},p=>this.deleteChars(p)),this._parser.registerCsiHandler({final:"S"},p=>this.scrollUp(p)),this._parser.registerCsiHandler({final:"T"},p=>this.scrollDown(p)),this._parser.registerCsiHandler({final:"X"},p=>this.eraseChars(p)),this._parser.registerCsiHandler({final:"Z"},p=>this.cursorBackwardTab(p)),this._parser.registerCsiHandler({final:"`"},p=>this.charPosAbsolute(p)),this._parser.registerCsiHandler({final:"a"},p=>this.hPositionRelative(p)),this._parser.registerCsiHandler({final:"b"},p=>this.repeatPrecedingCharacter(p)),this._parser.registerCsiHandler({final:"c"},p=>this.sendDeviceAttributesPrimary(p)),this._parser.registerCsiHandler({prefix:">",final:"c"},p=>this.sendDeviceAttributesSecondary(p)),this._parser.registerCsiHandler({final:"d"},p=>this.linePosAbsolute(p)),this._parser.registerCsiHandler({final:"e"},p=>this.vPositionRelative(p)),this._parser.registerCsiHandler({final:"f"},p=>this.hVPosition(p)),this._parser.registerCsiHandler({final:"g"},p=>this.tabClear(p)),this._parser.registerCsiHandler({final:"h"},p=>this.setMode(p)),this._parser.registerCsiHandler({prefix:"?",final:"h"},p=>this.setModePrivate(p)),this._parser.registerCsiHandler({final:"l"},p=>this.resetMode(p)),this._parser.registerCsiHandler({prefix:"?",final:"l"},p=>this.resetModePrivate(p)),this._parser.registerCsiHandler({final:"m"},p=>this.charAttributes(p)),this._parser.registerCsiHandler({final:"n"},p=>this.deviceStatus(p)),this._parser.registerCsiHandler({prefix:"?",final:"n"},p=>this.deviceStatusPrivate(p)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},p=>this.softReset(p)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},p=>this.setCursorStyle(p)),this._parser.registerCsiHandler({final:"r"},p=>this.setScrollRegion(p)),this._parser.registerCsiHandler({final:"s"},p=>this.saveCursor(p)),this._parser.registerCsiHandler({final:"t"},p=>this.windowOptions(p)),this._parser.registerCsiHandler({final:"u"},p=>this.restoreCursor(p)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},p=>this.insertColumns(p)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},p=>this.deleteColumns(p)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},p=>this.selectProtected(p)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},p=>this.requestMode(p,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},p=>this.requestMode(p,!1)),this._parser.setExecuteHandler(De.BEL,()=>this.bell()),this._parser.setExecuteHandler(De.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(De.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(De.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(De.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(De.BS,()=>this.backspace()),this._parser.setExecuteHandler(De.HT,()=>this.tab()),this._parser.setExecuteHandler(De.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(De.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Kf.IND,()=>this.index()),this._parser.setExecuteHandler(Kf.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Kf.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Er(p=>(this.setTitle(p),this.setIconName(p),!0))),this._parser.registerOscHandler(1,new Er(p=>this.setIconName(p))),this._parser.registerOscHandler(2,new Er(p=>this.setTitle(p))),this._parser.registerOscHandler(4,new Er(p=>this.setOrReportIndexedColor(p))),this._parser.registerOscHandler(8,new Er(p=>this.setHyperlink(p))),this._parser.registerOscHandler(10,new Er(p=>this.setOrReportFgColor(p))),this._parser.registerOscHandler(11,new Er(p=>this.setOrReportBgColor(p))),this._parser.registerOscHandler(12,new Er(p=>this.setOrReportCursorColor(p))),this._parser.registerOscHandler(104,new Er(p=>this.restoreIndexedColor(p))),this._parser.registerOscHandler(110,new Er(p=>this.restoreFgColor(p))),this._parser.registerOscHandler(111,new Er(p=>this.restoreBgColor(p))),this._parser.registerOscHandler(112,new Er(p=>this.restoreCursorColor(p))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let p in ui)this._parser.registerEscHandler({intermediates:"(",final:p},()=>this.selectCharset("("+p)),this._parser.registerEscHandler({intermediates:")",final:p},()=>this.selectCharset(")"+p)),this._parser.registerEscHandler({intermediates:"*",final:p},()=>this.selectCharset("*"+p)),this._parser.registerEscHandler({intermediates:"+",final:p},()=>this.selectCharset("+"+p)),this._parser.registerEscHandler({intermediates:"-",final:p},()=>this.selectCharset("-"+p)),this._parser.registerEscHandler({intermediates:".",final:p},()=>this.selectCharset("."+p)),this._parser.registerEscHandler({intermediates:"/",final:p},()=>this.selectCharset("/"+p));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(p=>(this._logService.error("Parsing error: ",p),p)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Px((p,b)=>this.requestStatusString(p,b)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,n)=>setTimeout(()=>n("#SLOW_TIMEOUT"),$x))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${$x} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,s=this._activeBuffer.x,o=this._activeBuffer.y,l=0,d=this._parseStack.paused;if(d){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;s=this._parseStack.cursorStartX,o=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>wo&&(l=this._parseStack.position+wo)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,p=>String.fromCharCode(p)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(p=>p.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<wo&&(this._parseBuffer=new Uint32Array(Math.min(e.length,wo))),d||this._dirtyRowTracker.clearRange(),e.length>wo)for(let p=l;p<e.length;p+=wo){let b=p+wo<e.length?p+wo:e.length,_=typeof e=="string"?this._stringDecoder.decode(e.substring(p,b),this._parseBuffer):this._utf8Decoder.decode(e.subarray(p,b),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,_))return this._preserveStack(s,o,_,p),this._logSlowResolvingAsync(n),n}else if(!d){let p=typeof e=="string"?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,p))return this._preserveStack(s,o,p,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==s||this._activeBuffer.y!==o)&&this._onCursorMove.fire();let f=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),m=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);m<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(m,this._bufferService.rows-1),end:Math.min(f,this._bufferService.rows-1)})}print(e,t,n){let s,o,l=this._charsetService.charset,d=this._optionsService.rawOptions.screenReaderMode,f=this._bufferService.cols,m=this._coreService.decPrivateModes.wraparound,p=this._coreService.modes.insertMode,b=this._curAttrData,_=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&_.getWidth(this._activeBuffer.x-1)===2&&_.setCellFromCodepoint(this._activeBuffer.x-1,0,1,b);let S=this._parser.precedingJoinState;for(let w=t;w<n;++w){if(s=e[w],s<127&&l){let A=l[String.fromCharCode(s)];A&&(s=A.charCodeAt(0))}let x=this._unicodeService.charProperties(s,S);o=Nl.extractWidth(x);let R=Nl.extractShouldJoin(x),L=R?Nl.extractWidth(S):0;if(S=x,d&&this._onA11yChar.fire(Eo(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+o-L>f){if(m){let A=_,W=this._activeBuffer.x-L;for(this._activeBuffer.x=L,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),_=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),L>0&&_ instanceof Sd&&_.copyCellsFrom(A,W,0,L,!1);W<f;)A.setCellFromCodepoint(W++,0,1,b)}else if(this._activeBuffer.x=f-1,o===2)continue}if(R&&this._activeBuffer.x){let A=_.getWidth(this._activeBuffer.x-1)?1:2;_.addCodepointToCell(this._activeBuffer.x-A,s,o);for(let W=o-L;--W>=0;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,b);continue}if(p&&(_.insertCells(this._activeBuffer.x,o-L,this._activeBuffer.getNullCell(b)),_.getWidth(f-1)===2&&_.setCellFromCodepoint(f-1,0,1,b)),_.setCellFromCodepoint(this._activeBuffer.x++,s,o,b),o>0)for(;--o;)_.setCellFromCodepoint(this._activeBuffer.x++,0,0,b)}this._parser.precedingJoinState=S,this._activeBuffer.x<f&&n-t>0&&_.getWidth(this._activeBuffer.x)===0&&!_.hasContent(this._activeBuffer.x)&&_.setCellFromCodepoint(this._activeBuffer.x,0,1,b),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,n=>Ux(n.params[0],this._optionsService.rawOptions.windowOptions)?t(n):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Px(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Er(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,s=!1,o=!1){let l=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);l.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),o),s&&(l.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let s=this._activeBuffer.lines.length-this._bufferService.rows;s>0&&(this._activeBuffer.lines.trimStart(s),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-s,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-s,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,o=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(o-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,s;for(s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,s=this._bufferService.rows-1+this._activeBuffer.ybase-s;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(ei));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let n=this._activeBuffer.scrollTop;n<=this._activeBuffer.scrollBottom;++n){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n);s.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let n=this._activeBuffer.scrollTop;n<=this._activeBuffer.scrollBottom;++n){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n);s.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let n=this._activeBuffer.scrollTop;n<=this._activeBuffer.scrollBottom;++n){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n);s.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let n=this._activeBuffer.scrollTop;n<=this._activeBuffer.scrollBottom;++n){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+n);s.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),s.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,s=Nl.extractWidth(t),o=this._activeBuffer.x-s,l=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(o),d=new Uint32Array(l.length*n),f=0;for(let p=0;p<l.length;){let b=l.codePointAt(p)||0;d[f++]=b,p+=b>65535?2:1}let m=f;for(let p=1;p<n;++p)d.copyWithin(m,0,f),m+=f;return this.print(d,0,m),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(De.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(De.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(De.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(De.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(De.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,Tl),this._charsetService.setgCharset(1,Tl),this._charsetService.setgCharset(2,Tl),this._charsetService.setgCharset(3,Tl);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){let n;(R=>(R[R.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",R[R.SET=1]="SET",R[R.RESET=2]="RESET",R[R.PERMANENTLY_SET=3]="PERMANENTLY_SET",R[R.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(n||={});let s=this._coreService.decPrivateModes,{activeProtocol:o,activeEncoding:l}=this._coreMouseService,d=this._coreService,{buffers:f,cols:m}=this._bufferService,{active:p,alt:b}=f,_=this._optionsService.rawOptions,S=(R,L)=>(d.triggerDataEvent(`${De.ESC}[${t?"":"?"}${R};${L}$y`),!0),w=R=>R?1:2,x=e.params[0];return t?x===2?S(x,4):x===4?S(x,w(d.modes.insertMode)):x===12?S(x,3):x===20?S(x,w(_.convertEol)):S(x,0):x===1?S(x,w(s.applicationCursorKeys)):x===3?S(x,_.windowOptions.setWinLines?m===80?2:m===132?1:0:0):x===6?S(x,w(s.origin)):x===7?S(x,w(s.wraparound)):x===8?S(x,3):x===9?S(x,w(o==="X10")):x===12?S(x,w(_.cursorBlink)):x===25?S(x,w(!d.isCursorHidden)):x===45?S(x,w(s.reverseWraparound)):x===66?S(x,w(s.applicationKeypad)):x===67?S(x,4):x===1e3?S(x,w(o==="VT200")):x===1002?S(x,w(o==="DRAG")):x===1003?S(x,w(o==="ANY")):x===1004?S(x,w(s.sendFocus)):x===1005?S(x,4):x===1006?S(x,w(l==="SGR")):x===1015?S(x,4):x===1016?S(x,w(l==="SGR_PIXELS")):x===1048?S(x,1):x===47||x===1047||x===1049?S(x,w(p===b)):x===2004?S(x,w(s.bracketedPasteMode)):x===2026?S(x,w(s.synchronizedOutput)):S(x,0)}_updateAttrColor(e,t,n,s,o){return t===2?(e|=50331648,e&=-16777216,e|=ph.fromColorRGB([n,s,o])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let s=[0,0,-1,0,0,0],o=0,l=0;do{if(s[l+o]=e.params[t+l],e.hasSubParams(t+l)){let d=e.getSubParams(t+l),f=0;do s[1]===5&&(o=1),s[l+f+1+o]=d[f];while(++f<d.length&&f+l+1+o<s.length);break}if(s[1]===5&&l+o>=2||s[1]===2&&l+o>=5)break;s[1]&&(o=1)}while(++l+t<e.length&&l+o<s.length);for(let d=2;d<s.length;++d)s[d]===-1&&(s[d]=0);switch(s[0]){case 38:n.fg=this._updateAttrColor(n.fg,s[1],s[3],s[4],s[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,s[1],s[3],s[4],s[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,s[1],s[3],s[4],s[5])}return l}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=ei.fg,e.bg=ei.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,s=this._curAttrData;for(let o=0;o<t;o++)n=e.params[o],n>=30&&n<=37?(s.fg&=-50331904,s.fg|=16777216|n-30):n>=40&&n<=47?(s.bg&=-50331904,s.bg|=16777216|n-40):n>=90&&n<=97?(s.fg&=-50331904,s.fg|=16777216|n-90|8):n>=100&&n<=107?(s.bg&=-50331904,s.bg|=16777216|n-100|8):n===0?this._processSGR0(s):n===1?s.fg|=134217728:n===3?s.bg|=67108864:n===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(o)?e.getSubParams(o)[0]:1,s)):n===5?s.fg|=536870912:n===7?s.fg|=67108864:n===8?s.fg|=1073741824:n===9?s.fg|=2147483648:n===2?s.bg|=134217728:n===21?this._processUnderline(2,s):n===22?(s.fg&=-134217729,s.bg&=-134217729):n===23?s.bg&=-67108865:n===24?(s.fg&=-268435457,this._processUnderline(0,s)):n===25?s.fg&=-536870913:n===27?s.fg&=-67108865:n===28?s.fg&=-1073741825:n===29?s.fg&=2147483647:n===39?(s.fg&=-67108864,s.fg|=ei.fg&16777215):n===49?(s.bg&=-67108864,s.bg|=ei.bg&16777215):n===38||n===48||n===58?o+=this._extractColor(e,o,s):n===53?s.bg|=1073741824:n===55?s.bg&=-1073741825:n===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):n===100?(s.fg&=-67108864,s.fg|=ei.fg&16777215,s.bg&=-67108864,s.bg|=ei.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${De.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${De.ESC}[${t};${n}R`);break}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let t=this._activeBuffer.y+1,n=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${De.ESC}[?${t};${n}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=ei.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let n=t%2===1;this._coreService.decPrivateModes.cursorBlink=n}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Ux(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${De.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Hx&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Hx&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(";");for(;n.length>1;){let s=n.shift(),o=n.shift();if(/^\d+$/.exec(s)){let l=parseInt(s);if(Wx(l))if(o==="?")t.push({type:0,index:l});else{let d=zx(o);d&&t.push({type:1,index:l,color:d})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let n=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(n,s):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(":"),s,o=n.findIndex(l=>l.startsWith("id="));return o!==-1&&(s=n[o].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(";");for(let s=0;s<n.length&&!(t>=this._specialColors.length);++s,++t)if(n[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let o=zx(n[s]);o&&this._onColor.fire([{type:1,index:this._specialColors[t],color:o}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(";");for(let s=0;s<n.length;++s)if(/^\d+$/.exec(n[s])){let o=parseInt(n[s]);Wx(o)&&t.push({type:2,index:o})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,Tl),!0}selectCharset(e){return e.length!==2?(this.selectDefaultCharset(),!0):(e[0]==="/"||this._charsetService.setgCharset(vB[e[0]],ui[e[1]]||Tl),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=ei.clone(),this._eraseAttrDataInternal=ei.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Jr;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(n);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=d=>(this._coreService.triggerDataEvent(`${De.ESC}${d}${De.ESC}\\`),!0),s=this._bufferService.buffer,o=this._optionsService.rawOptions;return n(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[o.cursorStyle]-(o.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},ob=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Fx=e,e=t,t=Fx),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};ob=On([Ve(0,Vi)],ob);function Wx(e){return 0<=e&&e<256}var bB=5e7,Kx=12,yB=50,SB=class extends Nt{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new He),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>bB)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],o=this._action(s,t);if(o){let d=f=>performance.now()-n>=Kx?setTimeout(()=>this._innerWrite(0,f)):this._innerWrite(n,f);o.catch(f=>(queueMicrotask(()=>{throw f}),Promise.resolve(!1))).then(d);return}let l=this._callbacks[this._bufferOffset];if(l&&l(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-n>=Kx)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>yB&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},lb=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let f=t.addMarker(t.ybase+t.y),m={data:e,id:this._nextId++,lines:[f]};return f.onDispose(()=>this._removeMarkerFromLink(m,f)),this._dataByLinkId.set(m.id,m),m.id}let n=e,s=this._getEntryIdKey(n),o=this._entriesWithId.get(s);if(o)return this.addLineToLink(o.id,t.ybase+t.y),o.id;let l=t.addMarker(t.ybase+t.y),d={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[l]};return l.onDispose(()=>this._removeMarkerFromLink(d,l)),this._entriesWithId.set(d.key,d),this._dataByLinkId.set(d.id,d),d.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);n.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(n,s))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};lb=On([Ve(0,Vi)],lb);var qx=!1,wB=class extends Nt{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new eu),this._onBinary=this._register(new He),this.onBinary=this._onBinary.event,this._onData=this._register(new He),this.onData=this._onData.event,this._onLineFeed=this._register(new He),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new He),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new He),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new He),this._instantiationService=new qO,this.optionsService=this._register(new nB(e)),this._instantiationService.setService(Yi,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(ib)),this._instantiationService.setService(Vi,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(nb)),this._instantiationService.setService(ZT,this._logService),this.coreService=this._register(this._instantiationService.createInstance(rb)),this._instantiationService.setService(Fl,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(sb)),this._instantiationService.setService(XT,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Nl)),this._instantiationService.setService($j,this.unicodeService),this._charsetService=this._instantiationService.createInstance(oB),this._instantiationService.setService(Uj,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(lb),this._instantiationService.setService(QT,this._oscLinkService),this._inputHandler=this._register(new _B(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Ei.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Ei.forward(this._bufferService.onResize,this._onResize)),this._register(Ei.forward(this.coreService.onData,this._onData)),this._register(Ei.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new SB((t,n)=>this._inputHandler.parse(t,n))),this._register(Ei.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new He),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!qx&&(this._logService.warn("writeSync is unreliable and will be removed soon."),qx=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,DE),t=Math.max(t,ME),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Ix.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Ix(this._bufferService),!1))),this._windowsWrappingHeuristics.value=Cn(()=>{for(let t of e)t.dispose()})}}},xB={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function CB(e,t,n,s){let o={type:0,cancel:!1,key:void 0},l=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?o.key=De.ESC+"OA":o.key=De.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?o.key=De.ESC+"OD":o.key=De.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?o.key=De.ESC+"OC":o.key=De.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?o.key=De.ESC+"OB":o.key=De.ESC+"[B");break;case 8:o.key=e.ctrlKey?"\b":De.DEL,e.altKey&&(o.key=De.ESC+o.key);break;case 9:if(e.shiftKey){o.key=De.ESC+"[Z";break}o.key=De.HT,o.cancel=!0;break;case 13:o.key=e.altKey?De.ESC+De.CR:De.CR,o.cancel=!0;break;case 27:o.key=De.ESC,e.altKey&&(o.key=De.ESC+De.ESC),o.cancel=!0;break;case 37:if(e.metaKey)break;l?o.key=De.ESC+"[1;"+(l+1)+"D":t?o.key=De.ESC+"OD":o.key=De.ESC+"[D";break;case 39:if(e.metaKey)break;l?o.key=De.ESC+"[1;"+(l+1)+"C":t?o.key=De.ESC+"OC":o.key=De.ESC+"[C";break;case 38:if(e.metaKey)break;l?o.key=De.ESC+"[1;"+(l+1)+"A":t?o.key=De.ESC+"OA":o.key=De.ESC+"[A";break;case 40:if(e.metaKey)break;l?o.key=De.ESC+"[1;"+(l+1)+"B":t?o.key=De.ESC+"OB":o.key=De.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(o.key=De.ESC+"[2~");break;case 46:l?o.key=De.ESC+"[3;"+(l+1)+"~":o.key=De.ESC+"[3~";break;case 36:l?o.key=De.ESC+"[1;"+(l+1)+"H":t?o.key=De.ESC+"OH":o.key=De.ESC+"[H";break;case 35:l?o.key=De.ESC+"[1;"+(l+1)+"F":t?o.key=De.ESC+"OF":o.key=De.ESC+"[F";break;case 33:e.shiftKey?o.type=2:e.ctrlKey?o.key=De.ESC+"[5;"+(l+1)+"~":o.key=De.ESC+"[5~";break;case 34:e.shiftKey?o.type=3:e.ctrlKey?o.key=De.ESC+"[6;"+(l+1)+"~":o.key=De.ESC+"[6~";break;case 112:l?o.key=De.ESC+"[1;"+(l+1)+"P":o.key=De.ESC+"OP";break;case 113:l?o.key=De.ESC+"[1;"+(l+1)+"Q":o.key=De.ESC+"OQ";break;case 114:l?o.key=De.ESC+"[1;"+(l+1)+"R":o.key=De.ESC+"OR";break;case 115:l?o.key=De.ESC+"[1;"+(l+1)+"S":o.key=De.ESC+"OS";break;case 116:l?o.key=De.ESC+"[15;"+(l+1)+"~":o.key=De.ESC+"[15~";break;case 117:l?o.key=De.ESC+"[17;"+(l+1)+"~":o.key=De.ESC+"[17~";break;case 118:l?o.key=De.ESC+"[18;"+(l+1)+"~":o.key=De.ESC+"[18~";break;case 119:l?o.key=De.ESC+"[19;"+(l+1)+"~":o.key=De.ESC+"[19~";break;case 120:l?o.key=De.ESC+"[20;"+(l+1)+"~":o.key=De.ESC+"[20~";break;case 121:l?o.key=De.ESC+"[21;"+(l+1)+"~":o.key=De.ESC+"[21~";break;case 122:l?o.key=De.ESC+"[23;"+(l+1)+"~":o.key=De.ESC+"[23~";break;case 123:l?o.key=De.ESC+"[24;"+(l+1)+"~":o.key=De.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?o.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?o.key=De.NUL:e.keyCode>=51&&e.keyCode<=55?o.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?o.key=De.DEL:e.keyCode===219?o.key=De.ESC:e.keyCode===220?o.key=De.FS:e.keyCode===221&&(o.key=De.GS);else if((!n||s)&&e.altKey&&!e.metaKey){let d=xB[e.keyCode]?.[e.shiftKey?1:0];if(d)o.key=De.ESC+d;else if(e.keyCode>=65&&e.keyCode<=90){let f=e.ctrlKey?e.keyCode-64:e.keyCode+32,m=String.fromCharCode(f);e.shiftKey&&(m=m.toUpperCase()),o.key=De.ESC+m}else if(e.keyCode===32)o.key=De.ESC+(e.ctrlKey?De.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let f=e.code.slice(3,4);e.shiftKey||(f=f.toLowerCase()),o.key=De.ESC+f,o.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(o.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?o.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(o.key=De.US),e.key==="@"&&(o.key=De.NUL));break}return o}var Fn=0,kB=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new wp,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new wp,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((o,l)=>this._getKey(o)-this._getKey(l)),t=0,n=0,s=new Array(this._array.length+this._insertedValues.length);for(let o=0;o<s.length;o++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(s[o]=e[t],t++):s[o]=this._array[n++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Fn=this._search(t),Fn===-1)||this._getKey(this._array[Fn])!==t)return!1;do if(this._array[Fn]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Fn),!0;while(++Fn<this._array.length&&this._getKey(this._array[Fn])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((o,l)=>o-l),t=0,n=new Array(this._array.length-e.length),s=0;for(let o=0;o<this._array.length;o++)e[t]===o?t++:n[s++]=this._array[o];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Fn=this._search(e),!(Fn<0||Fn>=this._array.length)&&this._getKey(this._array[Fn])===e))do yield this._array[Fn];while(++Fn<this._array.length&&this._getKey(this._array[Fn])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Fn=this._search(e),!(Fn<0||Fn>=this._array.length)&&this._getKey(this._array[Fn])===e))do t(this._array[Fn]);while(++Fn<this._array.length&&this._getKey(this._array[Fn])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let s=t+n>>1,o=this._getKey(this._array[s]);if(o>e)n=s-1;else if(o<e)t=s+1;else{for(;s>0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},xv=0,Vx=0,TB=class extends Nt{constructor(){super(),this._decorations=new kB(e=>e?.marker.line),this._onDecorationRegistered=this._register(new He),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new He),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(Cn(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new EB(e);if(t){let n=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),n.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let s=0,o=0;for(let l of this._decorations.getKeyIterator(t))s=l.options.x??0,o=s+(l.options.width??1),e>=s&&e<o&&(!n||(l.options.layer??"bottom")===n)&&(yield l)}forEachDecorationAtCell(e,t,n,s){this._decorations.forEachByKey(t,o=>{xv=o.options.x??0,Vx=xv+(o.options.width??1),e>=xv&&e<Vx&&(!n||(o.options.layer??"bottom")===n)&&s(o)})}},EB=class extends Mo{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new He),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new He),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=Rn.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=Rn.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},RB=1e3,NB=class{constructor(e,t=RB){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t;let s=performance.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let o=s-this._lastRefreshMs,l=this._debounceThresholdMS-o;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},l)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Yx=20,xp=class extends Nt{constructor(e,t,n,s){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let o=this._coreBrowserService.mainDocument;this._accessibilityContainer=o.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=o.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let l=0;l<this._terminal.rows;l++)this._rowElements[l]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[l]);if(this._topBoundaryFocusListener=l=>this._handleBoundaryFocus(l,0),this._bottomBoundaryFocusListener=l=>this._handleBoundaryFocus(l,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=o.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new NB(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(l=>this._handleResize(l.rows))),this._register(this._terminal.onRender(l=>this._refreshRows(l.start,l.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(l=>this._handleChar(l))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
29
+ `))),this._register(this._terminal.onA11yTab(l=>this._handleTab(l))),this._register(this._terminal.onKey(l=>this._handleKey(l.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(vt(o,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Cn(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<Yx+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
30
+ `&&(this._liveRegionLineCount++,this._liveRegionLineCount===Yx+1&&(this._liveRegion.textContent+=R_.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,s=n.lines.length.toString();for(let o=e;o<=t;o++){let l=n.lines.get(n.ydisp+o),d=[],f=l?.translateToString(!0,void 0,void 0,d)||"",m=(n.ydisp+o+1).toString(),p=this._rowElements[o];p&&(f.length===0?(p.textContent=" ",this._rowColumns.set(p,[0,1])):(p.textContent=f,this._rowColumns.set(p,d)),p.setAttribute("aria-posinset",m),p.setAttribute("aria-setsize",s),this._alignRowWidth(p))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let n=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],o=n.getAttribute("aria-posinset"),l=t===0?"1":`${this._terminal.buffer.lines.length}`;if(o===l||e.relatedTarget!==s)return;let d,f;if(t===0?(d=n,f=this._rowElements.pop(),this._rowContainer.removeChild(f)):(d=this._rowElements.shift(),f=n,this._rowContainer.removeChild(d)),d.removeEventListener("focus",this._topBoundaryFocusListener),f.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let m=this._createAccessibilityTreeNode();this._rowElements.unshift(m),this._rowContainer.insertAdjacentElement("afterbegin",m)}else{let m=this._createAccessibilityTreeNode();this._rowElements.push(m),this._rowContainer.appendChild(m)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:s,offset:s.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let o=({node:f,offset:m})=>{let p=f instanceof Text?f.parentNode:f,b=parseInt(p?.getAttribute("aria-posinset"),10)-1;if(isNaN(b))return console.warn("row is invalid. Race condition?"),null;let _=this._rowColumns.get(p);if(!_)return console.warn("columns is null. Race condition?"),null;let S=m<_.length?_[m]:_.slice(-1)[0]+1;return S>=this._terminal.cols&&(++b,S=0),{row:b,column:S}},l=o(t),d=o(n);if(!(!l||!d)){if(l.row>d.row||l.row===d.row&&l.column>=d.column)throw new Error("invalid range");this._terminal.select(l.column,l.row,(d.row-l.row)*this._terminal.cols-l.column+d.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform="";let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let s=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${s/t})`}};xp=On([Ve(1,jy),Ve(2,Pa),Ve(3,za)],xp);var cb=class extends Nt{constructor(e,t,n,s,o){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=s,this._linkProviderService=o,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new He),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new He),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(Cn(()=>{zl(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(vt(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(vt(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(vt(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(vt(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let s=0;s<n.length;s++){let o=n[s];if(o.classList.contains("xterm"))break;if(o.classList.contains("xterm-hover"))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized){this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(s=>{s?.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[s,o]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(s)&&(n=this._checkLinkProviderResult(s,e,n)):o.provideLinks(e.y,l=>{if(this._isMouseOut)return;let d=l?.map(f=>({link:f}));this._activeProviderReplies?.set(s,d),n=this._checkLinkProviderResult(s,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let s=0;s<t.size;s++){let o=t.get(s);if(o)for(let l=0;l<o.length;l++){let d=o[l],f=d.link.range.start.y<e?0:d.link.range.start.x,m=d.link.range.end.y>e?this._bufferService.cols:d.link.range.end.x;for(let p=f;p<=m;p++){if(n.has(p)){o.splice(l--,1);break}n.add(p)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let s=this._activeProviderReplies.get(e),o=!1;for(let l=0;l<e;l++)(!this._activeProviderReplies.has(l)||this._activeProviderReplies.get(l))&&(o=!0);if(!o&&s){let l=s.find(d=>this._linkAtPosition(d.link,t));l&&(n=!0,this._handleNewLink(l))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let l=0;l<this._activeProviderReplies.size;l++){let d=this._activeProviderReplies.get(l)?.find(f=>this._linkAtPosition(f.link,t));if(d){n=!0,this._handleNewLink(d);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&DB(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,zl(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:n=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==n&&(this._currentLink.state.decorations.pointerCursor=n,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",n))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:n=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==n&&(this._currentLink.state.decorations.underline=n,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,n))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(n=>{if(!this._currentLink)return;let s=n.start===0?0:n.start+1+this._bufferService.buffer.ydisp,o=this._bufferService.buffer.ydisp+1+n.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=o&&(this._clearCurrentLink(s,o),this._lastMouseEvent)){let l=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);l&&this._askForLink(l,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,s=this._bufferService.buffer.ydisp,o=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-s-1,n.end.x,n.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(o)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,o=t.y*this._bufferService.cols+t.x;return n<=o&&o<=s}_positionFromMouseEvent(e,t,n){let s=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,s,o){return{x1:e,y1:t,x2:n,y2:s,cols:this._bufferService.cols,fg:o}}};cb=On([Ve(1,Oy),Ve(2,za),Ve(3,Vi),Ve(4,eE)],cb);function DB(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var MB=class extends wB{constructor(e={}){super(e),this._linkifier=this._register(new eu),this.browser=bE,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new eu),this._onCursorMove=this._register(new He),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new He),this.onKey=this._onKey.event,this._onRender=this._register(new He),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new He),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new He),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new He),this.onBell=this._onBell.event,this._onFocus=this._register(new He),this._onBlur=this._register(new He),this._onA11yCharEmitter=this._register(new He),this._onA11yTabEmitter=this._register(new He),this._onWillOpen=this._register(new He),this._setup(),this._decorationService=this._instantiationService.createInstance(TB),this._instantiationService.setService(mh,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(yO),this._instantiationService.setService(eE,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(D_)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(Ei.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Ei.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Ei.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Ei.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(Cn(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let n,s="";switch(t.index){case 256:n="foreground",s="10";break;case 257:n="background",s="11";break;case 258:n="cursor",s="12";break;default:n="ansi",s="4;"+t.index}switch(t.type){case 0:let o=yn.toColorRGB(n==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[n]);this.coreService.triggerDataEvent(`${De.ESC}]${s};${gB(o)}${vE.ST}`);break;case 1:if(n==="ansi")this._themeService.modifyColors(l=>l.ansi[t.index]=ti.toColor(...t.color));else{let l=n;this._themeService.modifyColors(d=>d[l]=ti.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(xp,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(De.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(De.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,o=t.getWidth(n),l=this._renderService.dimensions.css.cell.width*o,d=this.buffer.y*this._renderService.dimensions.css.cell.height,f=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=f+"px",this.textarea.style.top=d+"px",this.textarea.style.width=l+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(vt(this.element,"copy",t=>{this.hasSelection()&&Oj(t,this._selectionService)}));let e=t=>Bj(t,this.textarea,this.coreService,this.optionsService);this._register(vt(this.textarea,"paste",e)),this._register(vt(this.element,"paste",e)),yE?this._register(vt(this.element,"mousedown",t=>{t.button===2&&rx(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(vt(this.element,"contextmenu",t=>{rx(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Fy&&this._register(vt(this.element,"auxclick",t=>{t.button===1&&KT(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(vt(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(vt(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(vt(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(vt(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(vt(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(vt(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(vt(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(vt(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",E_.get()),xE||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(_O,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(Pa,this._coreBrowserService),this._register(vt(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(vt(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Z_,this._document,this._helperContainer),this._instantiationService.setService(nm,this._charSizeService),this._themeService=this._instantiationService.createInstance(tb),this._instantiationService.setService(ou,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(yp),this._instantiationService.setService(JT,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(J_,this.rows,this.screenElement)),this._instantiationService.setService(za,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(Y_,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Q_),this._instantiationService.setService(Oy,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(cb,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(q_,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(eb,this.element,this.screenElement,s)),this._instantiationService.setService(Wj,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(Ei.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(V_,this.screenElement)),this._register(vt(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(xp,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(bp,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(bp,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(X_,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(l){let d=e._mouseService.getMouseReportCoords(l,e.screenElement);if(!d)return!1;let f,m;switch(l.overrideType||l.type){case"mousemove":m=32,l.buttons===void 0?(f=3,l.button!==void 0&&(f=l.button<3?l.button:3)):f=l.buttons&1?0:l.buttons&4?1:l.buttons&2?2:3;break;case"mouseup":m=0,f=l.button<3?l.button:3;break;case"mousedown":m=1,f=l.button<3?l.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(l)===!1)return!1;let p=l.deltaY;if(p===0||e.coreMouseService.consumeWheelEvent(l,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;m=p<0?0:1,f=4;break;default:return!1}return m===void 0||f===void 0||f>4?!1:e.coreMouseService.triggerMouseEvent({col:d.col,row:d.row,x:d.x,y:d.y,button:f,action:m,ctrl:l.ctrlKey,alt:l.altKey,shift:l.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},o={mouseup:l=>(n(l),l.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(l)),wheel:l=>(n(l),this.cancel(l,!0)),mousedrag:l=>{l.buttons&&n(l)},mousemove:l=>{l.buttons||n(l)}};this._register(this.coreMouseService.onProtocolChange(l=>{l?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(l)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),l&8?s.mousemove||(t.addEventListener("mousemove",o.mousemove),s.mousemove=o.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),l&16?s.wheel||(t.addEventListener("wheel",o.wheel,{passive:!1}),s.wheel=o.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),l&2?s.mouseup||(s.mouseup=o.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),l&4?s.mousedrag||(s.mousedrag=o.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(vt(t,"mousedown",l=>{if(l.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(l)))return n(l),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(l)})),this._register(vt(t,"wheel",l=>{if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(l)===!1)return!1;if(!this.buffer.hasScrollback){if(l.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(l,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(l,!0);let d=De.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(l.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(d,!0),this.cancel(l,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){WT(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let n=CB(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let s=this.rows-1;return this.scrollLines(n.type===2?-s:s),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===De.ETX||n.key===De.CR)&&(this.textarea.value=""),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(AB(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(ei));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(De.ESC+"[I"):this.coreService.triggerDataEvent(De.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let t=this._renderService.dimensions.css.canvas.width.toFixed(0),n=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${De.ESC}[4;${n};${t}t`);break;case 1:let s=this._renderService.dimensions.css.cell.width.toFixed(0),o=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${De.ESC}[6;${o};${s}t`);break}}cancel(e,t){if(!(!this.options.cancelEvents&&!t))return e.preventDefault(),e.stopPropagation(),!1}};function AB(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var LB=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},jB=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Jr)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},Gx=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new jB(t)}getNullCell(){return new Jr}},OB=class extends Nt{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new He),this.onBufferChange=this._onBufferChange.event,this._normal=new Gx(this._core.buffers.normal,"normal"),this._alternate=new Gx(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},BB=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,n=>t(n.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(n,s)=>t(n,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},IB=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},PB=["cols","rows"],Os=0,zB=class extends Nt{constructor(e){super(),this._core=this._register(new MB(e)),this._addonManager=this._register(new LB),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],n=(s,o)=>{this._checkReadonlyOptions(s),this._core.options[s]=o};for(let s in this._core.options){let o={get:t.bind(this,s),set:n.bind(this,s)};Object.defineProperty(this._publicOptions,s,o)}}_checkReadonlyOptions(e){if(PB.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new BB(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new IB(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new OB(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
31
+ `,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return E_.get()},set promptLabel(e){E_.set(e)},get tooMuchOutput(){return R_.get()},set tooMuchOutput(e){R_.set(e)}}}_verifyIntegers(...e){for(Os of e)if(Os===1/0||isNaN(Os)||Os%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Os of e)if(Os&&(Os===1/0||isNaN(Os)||Os%1!==0||Os<0))throw new Error("This API only accepts positive integers")}};function sm(e){return e.normalize("NFC").trim().toLowerCase()}function HB(e){const t=sm(e);if(t.length>256)return"Use at most 256 characters.";const n=[...t.replace(/\s/gu,"")].length,s=/[\u1100-\u11ff\u3130-\u318f\ua960-\ua97f\uac00-\ud7ff]/u.test(t)?2:3;return n<s?`Enter at least ${s} non-space characters.`:null}const UB=zt.lazy(()=>Ly(()=>import("./TranscriptMarkdownBody-wSYk8MdN.js"),__vite__mapDeps([2,1])));function LE({entries:e,searchQuery:t,activeEntryIndex:n,activeEntryMode:s,activeSearchMatch:o,fontSize:l}){const d=v.useRef(new Map),f=v.useMemo(()=>{const p=new Map,b=new Array(e.length);for(let _=e.length-1;_>=0;_--){const S=e[_],w=`${S.kind}\0${S.header??""}\0${S.body}`;let x=2166136261,R=5381;for(let W=0;W<w.length;W++)x=Math.imul(x^w.charCodeAt(W),16777619),R=Math.imul(R,33)^w.charCodeAt(W);const L=`${w.length}:${x>>>0}:${R>>>0}`,A=p.get(L)??0;p.set(L,A+1),b[_]=`${L}:${A}`}return b},[e]);v.useEffect(()=>{if(n===null)return;const p=d.current.get(n);if(!p||typeof p.scrollIntoView!="function")return;if(s==="prompt"){p.scrollIntoView({block:"start",inline:"nearest"});return}const b=p.querySelectorAll(".transcript-search-hit");((o?.entryIndex===n?b[o.matchIndexInEntry]:null)??p).scrollIntoView({block:"center",inline:"nearest"})},[n,s,o,t]);let m=-1;return u.jsx("div",{className:"transcript-output transcript-formatted-output",style:{fontSize:l},children:e.map((p,b)=>{const _=p.kind==="user"?++m:null,S=n===b?s==="prompt"?" transcript-entry-prompt-active":" transcript-entry-search-active":"";return u.jsxs("section",{ref:w=>{w?d.current.set(b,w):d.current.delete(b)},className:`transcript-entry transcript-entry-${p.kind}${S}`,"data-transcript-kind":p.kind,"data-transcript-entry-key":f[b],"data-transcript-entry-index":b,..._!==null?{"data-transcript-prompt-position":_}:{},children:[p.header?u.jsx("div",{className:"transcript-entry-header",children:jE(p.header,t)}):null,p.body?u.jsx("div",{className:"transcript-entry-body",children:p.kind==="tool"?u.jsx(Xx,{text:p.body,searchQuery:t}):u.jsx(zt.Suspense,{fallback:u.jsx(Xx,{text:p.body,searchQuery:t}),children:u.jsx(UB,{text:p.body,searchQuery:t})})}):null]},f[b])})})}function Xx({text:e,searchQuery:t}){const n=e.endsWith(`
32
+ `)?e.slice(0,-1).split(`
33
+ `):e.split(`
34
+ `);return u.jsx("pre",{className:"transcript-entry-pre",children:n.map((s,o)=>u.jsx("span",{className:`transcript-line transcript-line-${qB(s,o===0||n[o-1]?.trim()==="")}`,children:jE(s,t)},o))})}function jE(e,t){const n=t.trim();if(!n)return e||" ";const s=e.toLowerCase(),o=n.toLowerCase(),l=[];let d=0,f=s.indexOf(o);for(;f!==-1;){f>d&&l.push(e.slice(d,f));const m=f+n.length;l.push(u.jsx("mark",{className:"transcript-search-hit",children:e.slice(f,m)},`${f}-${m}`)),d=m,f=s.indexOf(o,d)}return d<e.length&&l.push(e.slice(d)),l.length>0?l:e||" "}function $B(e,t){const n=t.trim().toLowerCase();if(!n)return 0;const s=e.toLowerCase();let o=0,l=s.indexOf(n);for(;l!==-1;)o+=1,l=s.indexOf(n,l+n.length);return o}function ub(e){const t=e.endsWith(`
35
+ `)?e.slice(0,-1):e;if(!t)return[];const n=[];let s=null,o="plain",l=[];function d(){const f=FB(l).join(`
36
+ `);(s||f)&&n.push({header:s,body:f,kind:o}),s=null,o="plain",l=[]}for(const f of t.split(`
37
+ `)){const m=WB(f);m?(d(),s=f,o=m):l.push(f)}return d(),n}function FB(e){let t=e.length;for(;t>0&&(e[t-1]??"").trim()==="";)t-=1;return e.slice(0,t)}function WB(e){const t=/^\[[^\]]+\]\s+(.+)$/.exec(e.trimEnd());if(!t)return null;const n=t[1]??"";return n==="User"?"user":n==="Codex"||n==="Claude"?"assistant":n==="System"?"system":/^Tool (?:call(?::|$)|output$)/.test(n)?"tool":null}function KB(e,t){const n=[];for(let s=0;s<e.length;s+=1){const o=e[s];if(!o)continue;const l=o.header?`${o.header}
38
+ ${o.body}`:o.body,d=$B(l,t);for(let f=0;f<d;f+=1)n.push({entryIndex:s,matchIndexInEntry:f})}return n}function qB(e,t){const n=e.trim();if(!n)return"blank";const s=n.replace(/^\[[^\]]+\]\s+/,""),o=/^\[[^\]]+\]\s+/.test(n);return(o||t)&&/^User$/.test(s)?"user":(o||t)&&/^(?:Codex|Claude)$/.test(s)?"assistant":(o||t)&&/^System$/.test(s)?"system":(o||t)&&(/^Tool (?:call(?::|$)|output$)/.test(s)||BE(n))?"tool":/^(?:\$|>|❯|➜)\s+/.test(n)?"command":/^(?:✓|✔|PASS|passed\b|success\b)/i.test(n)?"success":/^(?:✗|✘|FAIL|failed\b|error\b|traceback\b)/i.test(n)?"error":/^\[[^\]]+\]/.test(n)||/^(?:info|debug|warn)\b/i.test(n)?"dim":"plain"}function Ao(e){return e==="codex"?"Codex":"Claude"}function Bc(e,t,n={}){const s=`[nterminal] ${Ao(t)} transcript archive ends here. Live terminal screen continues below.`,o=e.join("").replace(/\r\n/g,`
39
+ `).replace(/\r/g,`
40
+ `).replace(s,"").replace(/\n{3,}/g,`
41
+
42
+ `).trimEnd(),l=Wy(o),d=n.includeTools?l:OE(l);return d?`${d}
43
+ `:""}function Wy(e){return e.replace(/^\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z)\]/gm,(t,n)=>{const s=VB(n);return s?`[${s}]`:t})}function VB(e){const t=new Date(e);if(!Number.isFinite(t.getTime()))return null;const n=t.getFullYear(),s=md(t.getMonth()+1),o=md(t.getDate()),l=md(t.getHours()),d=md(t.getMinutes()),f=md(t.getSeconds());return`${n}-${s}-${o} ${l}:${d}:${f}`}function md(e){return e.toString().padStart(2,"0")}function Cp(e,t){return e.map(n=>t?n:OE(n)).filter(Boolean).map(n=>n.endsWith(`
44
+ `)?n:`${n}
45
+ `).join("")}function OE(e){if(!e)return"";const t=e.split(`
46
+ `),n=[];let s=!1,o=!1,l=!0;for(const d of t){const f=d.trim()==="",m=l?YB(d):null;if(m&&(s=m==="tool",o=!1),BE(d)){o=!0,l=!1;continue}if(o){f?(o=!1,s||n.push(d),l=!0):l=!1;continue}s||n.push(d),l=f}return n.join(`
47
+ `).replace(/\n{3,}/g,`
48
+
49
+ `).trimEnd()}function YB(e){const t=e.replace(/^\[[^\]]+\]\s+/,"");return/^Tool (?:call(?::|$)|output$)/.test(t)?"tool":/^(?:User|Codex|Claude|System)$/.test(t)?"message":null}function BE(e){return/^\[tool (?:call(?::|])|output\])/.test(e.trim())}function Aa(e,t){return e.provider===t.provider&&e.sessionId===t.sessionId}function Zx(e,t){return e===null?t===null:t!==null&&Aa(e,t)}const GB=5e3,XB=200,ZB=1200,QB=4,JB=zt.memo(function({terminalId:t,serverApi:n,source:s,fontSize:o,onClose:l}){const d=v.useRef(null),f=v.useRef(0),m=v.useRef(!1),p=v.useRef(!1),b=v.useRef(null),_=v.useRef(!1),[S,w]=v.useState(null),[x,R]=v.useState(null),[L,A]=v.useState(null),[W,H]=v.useState(()=>new Set),[U,q]=v.useState(!1),[Y,I]=v.useState(!1),[F,de]=v.useState([]),[me,K]=v.useState(null),[te,J]=v.useState(!1),[Q,X]=v.useState(!1),[M,T]=v.useState(!1),[O,re]=v.useState(null),he=S?.find(j=>j.id===L)??null;v.useEffect(()=>{function j(ge){ge.key==="Escape"&&(ge.preventDefault(),ge.stopPropagation(),l())}return document.addEventListener("keydown",j,!0),()=>document.removeEventListener("keydown",j,!0)},[l]);const N=v.useCallback(async()=>{try{const j=await n.getTerminalSubagents(t);if(R(null),w(ge=>ge&&r5(ge,j.subagents)?ge:j.subagents),!_.current){const ge=j.subagents.find(Ae=>Ae.hasTranscript);ge&&(_.current=!0,A(Ae=>Ae??ge.id))}}catch(j){R(j instanceof Error?j.message:"Failed to load subagents."),w(ge=>ge??[])}},[n,t]);v.useEffect(()=>{N();const j=window.setInterval(()=>{document.hidden||N()},GB);function ge(){document.hidden||N()}return document.addEventListener("visibilitychange",ge),()=>{window.clearInterval(j),document.removeEventListener("visibilitychange",ge)}},[N]),v.useEffect(()=>{f.current+=1;const j=f.current;return m.current=!1,p.current=!0,b.current=null,de([]),K(null),J(!1),re(null),L&&V(null,"initial",j),()=>{f.current===j&&(f.current+=1)}},[n,t,L,Y]),v.useLayoutEffect(()=>{const j=d.current;if(!j)return;if(p.current){if(Q||F.length===0)return;p.current=!1;const Ae=()=>{j.scrollTop=j.scrollHeight};Ae(),window.requestAnimationFrame?.(Ae);return}const ge=b.current;ge!==null&&(b.current=null,j.scrollTop+=j.scrollHeight-ge)},[F,Q,Y]);async function V(j,ge,Ae=f.current){const Oe=L;if(!(!Oe||m.current)){m.current=!0,ge==="initial"?X(!0):(T(!0),b.current=d.current?.scrollHeight??null),re(null);try{let z=j,fe=0,Te=0,Ne=[];for(;f.current===Ae;){const Le=await n.getTerminalSubagentTranscriptHistory(t,Oe,{...z?{cursor:z}:{},limit:XB,maxLines:ZB,includeTools:Y});if(f.current!==Ae)return;if(!Le.source){if(Te<1){Te+=1,await new Promise($e=>setTimeout($e,600));continue}re("Subagent transcript is unavailable.");return}const be=Bc(Le.output,Le.source.provider,{includeTools:Y});if(K(Le.cursor),J(!!(Le.hasMore&&Le.cursor)),be&&(Ne=[be,...Ne],Cp(Ne,Y))){de($e=>ge==="older"?[...Ne,...$e]:Ne);return}if(!Le.hasMore||!Le.cursor||fe>=QB){Ne.length>0&&de($e=>ge==="older"?[...Ne,...$e]:Ne);return}z=Le.cursor,fe+=1}}catch(z){if(f.current!==Ae)return;re(z instanceof Error?z.message:"Failed to load subagent transcript.")}finally{f.current===Ae&&(m.current=!1,X(!1),T(!1))}}}function se(){const j=d.current;j&&(j.scrollTop>72||!te||!me||m.current||V(me,"older"))}function Z(j){H(ge=>{const Ae=new Set(ge);return Ae.delete(j)||Ae.add(j),Ae})}function Ee(j){_.current=!0,q(!0),j.id!==L&&A(j.id),ye(j.id)}function ye(j){const ge=n5(S??[],j);ge.length!==0&&H(Ae=>{if(ge.every(z=>Ae.has(z)))return Ae;const Oe=new Set(Ae);for(const z of ge)Oe.add(z);return Oe})}function ze(){f.current+=1;const j=f.current;m.current=!1,p.current=!0,b.current=null,de([]),K(null),J(!1),re(null),V(null,"initial",j)}const Ke=v.useMemo(()=>Cp(F,Y),[F,Y]),Be=v.useMemo(()=>ub(Ke),[Ke]),ve=S===null;v.useEffect(()=>{if(Q||M||!te||!me||m.current)return;const j=d.current;!j||F.length===0||j.scrollHeight<=j.clientHeight+4&&V(me,"older")},[F,te,me,Q,M]);const Fe=S?.filter(j=>j.state==="working").length??0,Ie=v.useMemo(()=>zE(e5(S??[]),W),[S,W]);return u.jsx("div",{className:"security-overlay transcript-overlay subagents-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"subagents-dialog-title",onPointerDown:j=>j.stopPropagation(),onMouseDown:j=>j.stopPropagation(),onClick:j=>{j.stopPropagation(),l()},children:u.jsxs("div",{className:"security-panel transcript-dialog subagents-dialog","data-mobile-view":U?"transcript":"list",onPointerDown:j=>j.stopPropagation(),onMouseDown:j=>j.stopPropagation(),onClick:j=>j.stopPropagation(),children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsxs("div",{className:"transcript-dialog-title",children:[u.jsxs("h2",{id:"subagents-dialog-title",children:["Subagents",S&&S.length>0?u.jsx("span",{className:"subagents-count",children:Fe>0?`${Fe} working · ${S.length} total`:`${S.length} total`}):null]}),u.jsxs("span",{title:s.sessionId,children:[Ao(s.provider)," session ",s.sessionId]})]}),u.jsx("button",{type:"button",className:"security-close","aria-label":"Close subagents dialog",onClick:l,children:"×"})]}),u.jsxs("div",{className:"subagents-body",children:[u.jsxs("aside",{className:"subagents-list","aria-label":"Subagents",children:[ve?u.jsx("div",{className:"subagents-list-status",children:"Loading subagents..."}):null,!ve&&x?u.jsx("div",{className:"subagents-list-status subagents-list-error",children:x}):null,!ve&&!x&&S!==null&&S.length===0?u.jsx("div",{className:"subagents-list-status",children:"No subagents found for this session yet."}):null,Ie.map(j=>{const ge=j.subagent,Ae=W.has(ge.id);return u.jsxs("div",{className:"subagent-row-wrap",style:j.level>0?{paddingLeft:`${Math.min(j.level,4)*14}px`}:void 0,children:[j.nestedCount>0?u.jsxs("button",{type:"button",className:"subagent-expander","aria-expanded":Ae,"aria-label":`${Ae?"Collapse":"Expand"} ${j.nestedCount} nested subagents of ${ge.name}`,title:j.nestedWorkingCount>0?`${j.nestedCount} nested · ${j.nestedWorkingCount} working`:`${j.nestedCount} nested`,onClick:()=>Z(ge.id),children:[u.jsx("span",{"aria-hidden":"true",children:Ae?"▾":"▸"}),u.jsx("span",{className:"subagent-expander-count","data-working":j.nestedWorkingCount>0?"true":"false",children:j.nestedCount})]}):u.jsx("span",{className:"subagent-expander-spacer","aria-hidden":"true"}),u.jsxs("button",{type:"button",className:"subagent-row","data-selected":ge.id===L?"true":"false","data-state":ge.state,disabled:!ge.hasTranscript,title:ge.hasTranscript?void 0:"Transcript file not found for this subagent.",onClick:()=>Ee(ge),children:[u.jsx("span",{className:"subagent-row-dot","data-state":ge.state,"aria-hidden":"true"}),u.jsxs("span",{className:"subagent-row-main",children:[u.jsxs("span",{className:"subagent-row-title",children:[u.jsx("strong",{children:ge.name}),u.jsx("span",{className:"subagent-row-badge","data-kind":ge.kind,children:ge.kind==="cross"?Ao(ge.provider):ge.provider})]}),ge.description?u.jsx("span",{className:"subagent-row-description",children:ge.description}):null,u.jsxs("span",{className:"subagent-row-meta",children:[s5(ge.state),ge.model?` · ${ge.model}`:"",ge.updatedAt?` · ${a5(ge.updatedAt)}`:"",j.nestedCount>0&&!Ae?` · ${j.nestedCount} nested${j.nestedWorkingCount>0?` (${j.nestedWorkingCount} working)`:""}`:""]})]})]})]},ge.id)})]}),u.jsxs("section",{className:"subagents-transcript","aria-label":"Subagent transcript",children:[u.jsxs("div",{className:"subagents-transcript-controls",children:[u.jsx("button",{type:"button",className:"subagents-back","aria-label":"Back to subagent list",onClick:()=>q(!1),children:"‹ List"}),u.jsx("span",{className:"subagents-transcript-name",children:he?he.name:"Select a subagent"}),u.jsxs("label",{className:"auth-checkbox transcript-tool-toggle subagents-tool-toggle",children:[u.jsx("input",{type:"checkbox",checked:Y,onChange:j=>I(j.currentTarget.checked)}),"Show tool output"]}),u.jsx("button",{type:"button",className:"subagents-refresh","aria-label":"Reload subagent transcript",title:"Reload latest entries",disabled:!he,onClick:ze,children:"↻"})]}),he?u.jsx("div",{className:"subagents-transcript-hint",children:i5(he)}):null,u.jsxs("div",{ref:d,className:"transcript-dialog-scroll subagents-transcript-scroll",onScroll:se,children:[M?u.jsx("div",{className:"transcript-dialog-status",children:"Loading older entries..."}):null,!Q&&te?u.jsx("div",{className:"transcript-dialog-hint",children:"Scroll up for older entries"}):null,Ke?u.jsx(LE,{entries:Be,searchQuery:"",activeEntryIndex:null,activeEntryMode:null,activeSearchMatch:null,fontSize:o}):null,Q?u.jsx("div",{className:"transcript-dialog-status",children:"Loading transcript..."}):null,!Q&&he&&!Ke&&!O?te&&me?u.jsxs("div",{className:"transcript-dialog-status",children:[Y?"The latest entries are hidden record types.":"The latest entries contain only hidden tool output."," ",u.jsx("button",{type:"button",onClick:()=>{V(me,"older")},disabled:M,children:"Search earlier entries"})]}):u.jsx("div",{className:"transcript-dialog-status",children:"No transcript entries found."}):null,!he&&!ve&&!Ke?u.jsx("div",{className:"transcript-dialog-status",children:"Select a subagent on the left to view its conversation."}):null,O?u.jsx("div",{className:"transcript-dialog-error",children:O}):null]})]})]})]})})});function e5(e){const t=new Map;for(const s of e)t.set(s.id,{subagent:s,children:[],nestedCount:0,nestedWorkingCount:0});const n=[];for(const s of t.values()){const o=t5(s,t);o?o.children.push(s):n.push(s)}for(const s of n)IE(s);return PE(n),n}function t5(e,t){const n=e.subagent.parentId;if(!n)return null;const s=t.get(n);if(!s||s===e)return null;const o=new Set([e.subagent.id]);for(let l=s;l;){if(o.has(l.subagent.id))return null;o.add(l.subagent.id);const d=l.subagent.parentId;l=d?t.get(d):void 0}return s}function IE(e){let t=0,n=0;for(const s of e.children)IE(s),t+=1+s.nestedCount,n+=(s.subagent.state==="working"?1:0)+s.nestedWorkingCount;e.nestedCount=t,e.nestedWorkingCount=n,PE(e.children)}function PE(e){e.sort((t,n)=>{const s=t.subagent.state==="working"||t.nestedWorkingCount>0?0:1,o=n.subagent.state==="working"||n.nestedWorkingCount>0?0:1;return s!==o?s-o:(n.subagent.updatedAt??"").localeCompare(t.subagent.updatedAt??"")})}function zE(e,t,n=0){const s=[];for(const o of e)s.push({subagent:o.subagent,level:n,nestedCount:o.nestedCount,nestedWorkingCount:o.nestedWorkingCount}),o.children.length>0&&t.has(o.subagent.id)&&s.push(...zE(o.children,t,n+1));return s}function n5(e,t){const n=new Map(e.map(d=>[d.id,d])),s=[],o=new Set([t]);let l=n.get(t)?.parentId??null;for(;l&&!o.has(l);)o.add(l),s.push(l),l=n.get(l)?.parentId??null;return s}function i5(e){return e.kind==="cross"?'"User" entries are the prompt the parent session passed to codex exec, not operator input.':e.provider==="codex"?"Codex forks the parent thread to start a teammate; the inherited history is hidden here. Coordinator instructions are stored encrypted by Codex, so they show as placeholders.":`"User" entries are the parent session's instructions and tool results, not operator input.`}function r5(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const s=e[n],o=t[n];if(s.id!==o.id||s.provider!==o.provider||s.kind!==o.kind||s.name!==o.name||s.description!==o.description||s.model!==o.model||s.spawnDepth!==o.spawnDepth||s.parentId!==o.parentId||s.state!==o.state||s.updatedAt!==o.updatedAt||s.hasTranscript!==o.hasTranscript)return!1}return!0}function s5(e){switch(e){case"working":return"working";case"done":return"done";case"stopped":return"stopped";case"idle":return"idle";default:return"unknown"}}function a5(e){const t=Date.parse(e);if(!Number.isFinite(t))return"";const n=Date.now()-t;if(n<45e3)return"just now";const s=Math.round(n/6e4);if(s<60)return`${s}m ago`;const o=Math.round(s/60);return o<24?`${o}h ago`:`${Math.round(o/24)}d ago`}function o5({options:e,value:t,onSelect:n}){const[s,o]=v.useState(!1),l=v.useRef(null),d=v.useRef(null),f=e.find(m=>m.id===t);return v.useEffect(()=>{if(!s)return;const m=()=>Array.from(l.current?.querySelectorAll('[role="menuitemradio"]')??[]),p=m();(p.find(S=>S.getAttribute("aria-checked")==="true")??p[0])?.focus();function b(S){l.current?.contains(S.target)||o(!1)}function _(S){if(S.key==="Escape")S.preventDefault(),S.stopPropagation(),o(!1),d.current?.focus();else if(["ArrowDown","ArrowUp","Home","End"].includes(S.key)){S.preventDefault(),S.stopPropagation();const w=m(),x=w.findIndex(L=>L===document.activeElement),R=S.key==="Home"?0:S.key==="End"?w.length-1:(x+(S.key==="ArrowDown"?1:-1)+w.length)%w.length;w[R]?.focus()}else S.key==="Tab"&&o(!1)}return document.addEventListener("pointerdown",b,!0),window.addEventListener("keydown",_,!0),()=>{document.removeEventListener("pointerdown",b,!0),window.removeEventListener("keydown",_,!0)}},[s]),u.jsxs("div",{className:"transcript-session-menu",ref:l,children:[u.jsxs("button",{ref:d,type:"button",className:"transcript-session-trigger","aria-label":"Transcript session","aria-haspopup":"menu","aria-expanded":s,onClick:()=>o(!s),children:[u.jsx("span",{children:f?.title??"Choose a session"}),u.jsx(NA,{size:16,"aria-hidden":"true"})]}),s?u.jsx("div",{className:"transcript-session-options",role:"menu","aria-label":"Transcript sessions",children:e.map(m=>u.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t===m.id,tabIndex:-1,onClick:()=>{o(!1),d.current?.focus(),n(m.id)},children:[u.jsx("span",{className:"transcript-session-check",children:t===m.id?u.jsx(Xk,{size:16}):null}),u.jsxs("span",{className:"transcript-session-copy",children:[u.jsx("strong",{children:m.title}),u.jsx("small",{children:m.detail})]})]},m.id))}):null]})}function Ky(e){const t=new Set;return e.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}function db(e){return!e.page||e.page.unchanged?null:{page:{...e.page,records:Ky(e.page.records)},cursor:e.cursor,hasMore:e.hasMore,scrollTop:0,atBottom:!0}}function Qx(e,t){const n=db(t);if(!n||n.page.identity!==e.page.identity||n.page.endOffset!==e.page.startOffset)return null;const s=n.page.snapshot===e.page.snapshot&&n.page.snapshotSize===e.page.snapshotSize&&n.page.snapshotMtime===e.page.snapshotMtime,o=n.page.snapshotSize<e.page.snapshotSize&&n.page.endOffset<=e.page.stableBefore&&n.page.endOffset<=n.page.stableBefore;return!s&&!o?null:{...e,page:{...e.page,startOffset:n.page.startOffset,records:Ky([...n.page.records,...e.page.records])},cursor:n.cursor,hasMore:n.hasMore}}function HE(e,t){return e.identity===t.identity&&(t.snapshotSize>e.snapshotSize||t.snapshotSize===e.snapshotSize&&t.snapshotMtime===e.snapshotMtime)}function UE(e,t){return!HE(e.page,t.page)||t.page.startOffset<=e.page.stableBefore||t.page.startOffset<=e.page.startOffset}function l5(e,t){if(!HE(e.page,t.page)||!UE(e,t))return t;const n=new Set(t.page.records.map(l=>l.id)),s=e.page.records.filter(l=>l.startOffset<t.page.startOffset&&l.endOffset<=t.page.startOffset&&!n.has(l.id)),o=e.page.startOffset<t.page.startOffset;return{...t,page:{...t.page,startOffset:Math.min(e.page.startOffset,t.page.startOffset),records:Ky([...s,...t.page.records])},cursor:o?e.cursor:t.cursor,hasMore:o?e.hasMore:t.hasMore,scrollTop:e.scrollTop,atBottom:e.atBottom,...e.scrollAnchor?{scrollAnchor:e.scrollAnchor}:{}}}const c5=64*1024*1024,u5=1800*1e3;let hb=0,fb=new WeakMap;const Xd=new Map,Zd=new Set;function d5(e){const t=e.page;return 2*(t.identity.length+t.snapshot.length+(e.cursor?.length??0)+t.records.reduce((n,s)=>n+s.id.length+s.block.length,0))}function pb(e){e.owner.delete(e.key),Zd.delete(e),e.snapshot=null,e.bytes=0}function Cv(e){for(const s of Zd)!s.leases&&e-s.closedAt>=u5&&pb(s);let t=0;const n=[];for(const s of Zd)t+=s.bytes,s.leases||n.push(s);n.sort((s,o)=>s.closedAt-o.closedAt);for(const s of n){if(t<=c5)break;t-=s.bytes,pb(s)}for(const[s,o]of Xd)o.size||Xd.delete(s)}function kv(){hb+=1;for(const e of Zd)pb(e);Xd.clear(),fb=new WeakMap}function h5(e,t,n,s){Cv(Date.now());const o=e.transcriptCacheScope;let l=o===void 0?fb.get(e):Xd.get(o);l||(l=new Map,o===void 0?fb.set(e,l):Xd.set(o,l));const d=JSON.stringify([t,n.provider,n.sessionId,s]);let f=l.get(d);f||(f={snapshot:null,bytes:0,leases:0,closedAt:0,owner:l,key:d},l.set(d,f),Zd.add(f));const m=hb,p=f;p.leases+=1;let b=!1;const _=()=>!b&&m===hb;return{get snapshot(){return _()?p.snapshot:null},current:_,write(S){_()&&(p.snapshot=S,p.bytes=d5(S),Cv(Date.now()))},invalidate(){_()&&(p.snapshot=null,p.bytes=0)},release(){b||(b=!0,p.leases-=1,p.leases||(p.closedAt=Date.now()),Cv(Date.now()))}}}function f5(e,t,n){if(!e.length)return null;const s=t.timestamp?Wy(`[${t.timestamp}] ${t.role}`):null;let o=e.length-1;if(s){for(let d=e.length-1;d>=0;d-=1)if(e[d]?.header===s){o=d;break}}const l=KB(e,sm(n)).filter(d=>d.entryIndex===o);return(s&&e[o]?.header===s?l[0]:l.at(-1))??{entryIndex:o,matchIndexInEntry:0}}function p5(e,t,n,s,o,l){const[d,f]=v.useState(null),[m,p]=v.useState(!1),[b,_]=v.useState(null),S=v.useRef(null),w=v.useRef(0);function x(){w.current+=1,S.current?.abort(),S.current=null}function R(){x(),p(!1)}v.useEffect(()=>(x(),f(null),p(!1),_(null),x),[e,t,n.provider,n.sessionId,s,o,l]);async function L(A=!1){const W=HB(l);if(W){_(W);return}x();const H=w.current,U=new AbortController;S.current=U,p(!0),_(null);let q=A?d:null;A||f(null);try{for(let Y=0;Y<4;Y+=1){const I=await e.searchTerminalTranscript(t,{query:sm(l),...q?.cursor?{cursor:q.cursor}:{},...s?{candidateId:s}:{},expectedSessionId:n.sessionId,includeTools:o},U.signal);if(U.signal.aborted||H!==w.current)return;if(!I.source||I.source.provider!==n.provider||I.source.sessionId!==n.sessionId)throw new Error("Transcript source changed or is unavailable. Choose a session again.");const F=new Set(q?.hits.map(K=>K.id)),de=[...q?.hits??[],...I.hits.filter(K=>!F.has(K.id))],me=q?.cursor;if(q={...I,hits:de.slice(-200)},f(q),I.complete||!I.cursor||I.cursor===me||I.hits.length)break}}catch(Y){!U.signal.aborted&&H===w.current&&_(Y instanceof Error?Y.message:"Search failed.")}finally{H===w.current&&p(!1)}}return{result:d,busy:m,error:b,search:L,cancel:R}}class m5{pending=null;accept(t){let n="";for(const s of t)n+=this.acceptChar(s);return n}acceptChar(t){return t===""?this.acceptBackspace():KE.has(t)?this.acceptConsonant(t):qE.has(t)?this.acceptVowel(t):b5(t)&&this.canReplacePendingWith(t)?(this.pending=eC(t),""):this.flushPending()+t}acceptConsonant(t){if(!this.pending)return this.pending={initial:t},"";if(!this.pending.vowel){const o=this.flushPending();return this.pending={initial:t},o}if(!this.pending.final){if(VE.has(t))return this.pending.final=t,"";const o=this.flushPending();return this.pending={initial:t},o}const n=_5.get(`${this.pending.final}${t}`);if(n)return this.pending.final=n,"";const s=this.flushPending();return this.pending={initial:t},s}acceptVowel(t){if(!this.pending)return t;if(!this.pending.vowel)return this.pending.vowel=t,"";if(!this.pending.final){const l=v5.get(`${this.pending.vowel}${t}`);return l?(this.pending.vowel=l,""):this.flushPending()+t}const n=Jx.get(this.pending.final);if(n){this.pending.final=n[0];const l=this.flushPending();return this.pending={initial:n[1],vowel:t},l}const s=this.pending.final,o=tC({initial:this.pending.initial,vowel:this.pending.vowel});return this.pending={initial:s,vowel:t},o}acceptBackspace(){if(!this.pending)return"";if(this.pending.final){const t=Jx.get(this.pending.final);return t?this.pending.final=t[0]:delete this.pending.final,""}return this.pending.vowel?(delete this.pending.vowel,""):(this.pending=null,"")}canReplacePendingWith(t){if(!this.pending?.initial)return!1;const n=eC(t);return n.initial===this.pending.initial&&(!this.pending.vowel||n.vowel===this.pending.vowel)&&(!this.pending.final||n.final===this.pending.final)}flushPending(){if(!this.pending)return"";const t=tC(this.pending);return this.pending=null,t}}const kp=44032,Tp=21,Uc=28,g5=19*Tp*Uc,$E=["ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ","ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"],FE=["ㅏ","ㅐ","ㅑ","ㅒ","ㅓ","ㅔ","ㅕ","ㅖ","ㅗ","ㅘ","ㅙ","ㅚ","ㅛ","ㅜ","ㅝ","ㅞ","ㅟ","ㅠ","ㅡ","ㅢ","ㅣ"],WE=["","ㄱ","ㄲ","ㄳ","ㄴ","ㄵ","ㄶ","ㄷ","ㄹ","ㄺ","ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅁ","ㅂ","ㅄ","ㅅ","ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"],KE=qy($E),qE=qy(FE),VE=qy(WE),v5=new Map([["ㅗㅏ","ㅘ"],["ㅗㅐ","ㅙ"],["ㅗㅣ","ㅚ"],["ㅜㅓ","ㅝ"],["ㅜㅔ","ㅞ"],["ㅜㅣ","ㅟ"],["ㅡㅣ","ㅢ"]]),YE=[["ㄱㅅ","ㄳ"],["ㄴㅈ","ㄵ"],["ㄴㅎ","ㄶ"],["ㄹㄱ","ㄺ"],["ㄹㅁ","ㄻ"],["ㄹㅂ","ㄼ"],["ㄹㅅ","ㄽ"],["ㄹㅌ","ㄾ"],["ㄹㅍ","ㄿ"],["ㄹㅎ","ㅀ"],["ㅂㅅ","ㅄ"]],_5=new Map(YE),Jx=new Map(YE.map(([e,t])=>[t,[e[0],e[1]]]));function qy(e){return new Map(e.map((t,n)=>[t,n]))}function b5(e){const t=e.codePointAt(0);return t!==void 0&&t>=kp&&t<kp+g5}function eC(e){const t=e.codePointAt(0)-kp,n=Math.floor(t/(Tp*Uc)),s=Math.floor(t%(Tp*Uc)/Uc),o=t%Uc,l={initial:$E[n],vowel:FE[s]};return o===0?l:{...l,final:WE[o]}}function tC(e){if(!e.vowel)return e.initial;const t=KE.get(e.initial),n=qE.get(e.vowel),s=e.final?VE.get(e.final):0;return t===void 0||n===void 0||s===void 0?`${e.initial}${e.vowel}${e.final??""}`:String.fromCodePoint(kp+(t*Tp+n)*Uc+s)}class nC{constructor(t=!0){this.mouseEnabled=t}mouseEnabled;state="text";pending="";stringIsOsc=!1;oversizedCsi=!1;mouseProtocol=null;mouseEncodings=new Set;setMouseEnabled(t){if(this.mouseEnabled===t)return"";if(this.mouseEnabled=t,!t)return"\x1B[?9;1000;1002;1003;1005;1006;1015;1016l";const n=[...this.mouseEncodings,...this.mouseProtocol===null?[]:[this.mouseProtocol]];return n.length?`\x1B[?${n.join(";")}h`:""}write(t){if(this.state==="text"&&!/[\x1b\x90\x98\x9b\x9d\x9e\x9f]/.test(t))return t;let n="";for(const s of t){if(this.state==="string-escape"){if(s==="\\"){n+="\x1B\\",this.state="text";continue}n+="",this.pending="\x1B",this.state="escape"}if(this.state==="string"){if(s==="\x1B"){this.state="string-escape";continue}n+=s,(s==="œ"||s===""||s===""||this.stringIsOsc&&s==="\x07")&&(this.state="text");continue}if(s==="\x1B"){n+=this.pending,this.pending=s,this.state="escape",this.oversizedCsi=!1;continue}if(this.state==="escape"){const o=s.charCodeAt(0);if(o===127)continue;if(o<32&&s!==""&&s!==""){n+=s;continue}this.pending+=s,s==="["?this.state="csi":(n+=this.pending,this.pending="",this.stringIsOsc=s==="]",this.state="]PX^_".includes(s)?"string":"text");continue}if(this.state==="csi"){const o=s.charCodeAt(0);if(o===127)continue;if(o<32&&s!==""&&s!==""){n+=s;continue}this.oversizedCsi||(this.pending+=s),o>=64&&o<=126?(this.oversizedCsi||(n+=this.filterModes(this.pending)),this.pending="",this.state="text"):s===""||s===""?(n+=this.pending,this.pending="",this.state="text"):this.pending.length>4096&&(this.pending="",this.oversizedCsi=!0);continue}s==="›"?(this.pending=s,this.state="csi",this.oversizedCsi=!1):(n+=s,"˜žŸ".includes(s)&&(this.stringIsOsc=s==="",this.state="string"))}return n}filterModes(t){const n=/^(\x1b\[|\x9b)\?([0-9;:]*)([hl])$/.exec(t);if(!n)return t;const s=n[3]==="h",o=n[2].split(";").filter(Boolean).filter(l=>{const d=Number(l.split(":")[0]);return[47,1047,1049].includes(d)?!1:[9,1e3,1002,1003].includes(d)?(this.mouseProtocol=s?d:null,this.mouseEnabled||!s):[1005,1006,1015,1016].includes(d)?(s?this.mouseEncodings.add(d):this.mouseEncodings.delete(d),this.mouseEnabled||!s):!0});return o.length>0?`${n[1]}?${o.join(";")}${n[3]}`:""}}function y5(e){return/^(?:\x1b\[<\d+;\d+;\d+[Mm])+$/.test(e)}const GE={interrupt:"",escape:"\x1B",tab:" ",arrowUp:"\x1B[A",arrowDown:"\x1B[B",arrowRight:"\x1B[C",arrowLeft:"\x1B[D"},S5={...GE,tab:"\x1B[Z",arrowUp:"\x1B[1;2A",arrowDown:"\x1B[1;2B",arrowRight:"\x1B[1;2C",arrowLeft:"\x1B[1;2D"};function mb(e,t=!1){return(t?S5:GE)[e]}function w5(e){return/^[a-z]$/i.test(e)?String.fromCharCode(e.toUpperCase().charCodeAt(0)-64):null}const x5=[{key:"interrupt",label:"^C",ariaLabel:"Send Interrupt"},{key:"escape",label:"Esc",ariaLabel:"Send Escape"},{key:"tab",label:"Tab",ariaLabel:"Send Tab"},{key:"arrowLeft",label:"←",ariaLabel:"Send Arrow Left"},{key:"arrowDown",label:"↓",ariaLabel:"Send Arrow Down"},{key:"arrowUp",label:"↑",ariaLabel:"Send Arrow Up"},{key:"arrowRight",label:"→",ariaLabel:"Send Arrow Right"}];function C5({ctrlActive:e,shiftActive:t,onCtrl:n,onShift:s,onStandaloneKey:o,onPreserveFocus:l,onHide:d}){const f=v.useRef(null);function m(p){p.preventDefault(),p.stopPropagation(),l()}return u.jsxs("div",{className:"mobile-terminal-key-bar",role:"toolbar","aria-label":"Mobile terminal keys",onMouseDown:m,onPointerDown:m,children:[u.jsx("button",{type:"button",className:"mobile-terminal-key mobile-terminal-key-ctrl","aria-label":"Arm Control modifier","aria-pressed":e,"data-active":e,onClick:n,children:"Ctrl"}),u.jsx("button",{type:"button",className:"mobile-terminal-key mobile-terminal-key-shift","aria-label":"Toggle Shift modifier",title:"Shift","aria-pressed":t,"data-active":t,onPointerDown:()=>{f.current=!t},onPointerCancel:()=>{f.current=null},onKeyDown:()=>{f.current=null},onClick:()=>{const p=f.current??!t;f.current=null,s(p)},children:u.jsx(CA,{size:16,"aria-hidden":"true"})}),x5.map(p=>{const _=t&&mb(p.key,!0)!==mb(p.key)?p.ariaLabel.replace("Send ","Send Shift + "):p.ariaLabel;return u.jsx("button",{type:"button",className:"mobile-terminal-key","aria-label":_,title:_,onClick:()=>o(p.key),children:p.label},p.key)}),u.jsx("button",{type:"button",className:"mobile-terminal-key mobile-terminal-key-hide","aria-label":"Hide terminal control keys",title:"Hide",onClick:d,children:"×"})]})}const XE="--nterminal-viewport-height",ZE="--nterminal-keyboard-inset-bottom",QE="data-nterminal-keyboard-visible",am="data-nterminal-compose-open",Ep="nterminal:viewport-refresh",k5=120;function T5(e=window){const t=e.document.documentElement,n=e.visualViewport,s=A5(e);function o(){Vy(e)}return o(),n?.addEventListener("resize",o),n?.addEventListener("scroll",o),s?.addEventListener("geometrychange",o),e.addEventListener("resize",o),e.addEventListener(Ep,o),e.addEventListener("orientationchange",o),e.addEventListener("pageshow",o),e.document.addEventListener("visibilitychange",o),()=>{n?.removeEventListener("resize",o),n?.removeEventListener("scroll",o),s?.removeEventListener("geometrychange",o),e.removeEventListener("resize",o),e.removeEventListener(Ep,o),e.removeEventListener("orientationchange",o),e.removeEventListener("pageshow",o),e.document.removeEventListener("visibilitychange",o),t.style.removeProperty(XE),t.style.removeProperty(ZE),t.removeAttribute(QE)}}function Vy(e=window){const t=e.document.documentElement,{keyboardInsetBottom:n,keyboardVisible:s}=gb(e),o=E5(e,s);return o!==null&&iC(t,XE,`${o}px`),iC(t,ZE,`${n}px`),R5(t,QE,String(s)),{viewportHeight:o,keyboardInsetBottom:n,keyboardVisible:s}}function gb(e=window){const t=N5(e);return{keyboardInsetBottom:t,keyboardVisible:t>k5}}function E5(e,t){if((e.document.documentElement.hasAttribute(am)||t)&&Ll(e.innerHeight))return e.innerHeight;const n=e.visualViewport?.height;return Ll(n)?n:Ll(e.innerHeight)?e.innerHeight:null}function Ll(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function iC(e,t,n){e.style.getPropertyValue(t)!==n&&e.style.setProperty(t,n)}function R5(e,t,n){e.getAttribute(t)!==n&&e.setAttribute(t,n)}function N5(e){return Math.max(D5(e),M5(e))}function D5(e){const t=e.visualViewport?.height;if(!Ll(t)||!Ll(e.innerHeight))return 0;const n=typeof e.visualViewport?.offsetTop=="number"?e.visualViewport.offsetTop:0;return Math.max(0,Math.round(e.innerHeight-t-n))}function M5(e){if(!Ll(e.innerHeight))return 0;const n=JE(e)?.boundingRect?.height;return!Ll(n)||n>=e.innerHeight*.8?0:Math.round(n)}function JE(e){return e.navigator.virtualKeyboard}function A5(e){const t=JE(e);return!t||typeof t.addEventListener!="function"||typeof t.removeEventListener!="function"?null:t}const _h=new Map,Qd=new Map,L5=Object.freeze({open:!1,text:""});function j5(e){let t=Qd.get(e);return t||(t=new Set,Qd.set(e,t)),t}function e2(e){const t=Qd.get(e);if(t)for(const n of Array.from(t))n()}function Vc(e){return _h.get(e)??L5}function O5(e,t){const n=j5(e);return n.add(t),()=>{n.delete(t)}}function B5(e,t){const n=Vc(e);n.open!==t&&(_h.set(e,{...n,open:t}),e2(e))}function I5(e,t){const n=Vc(e);n.text!==t&&(_h.set(e,{...n,text:t}),e2(e))}function Mf(e){_h.delete(e),Qd.delete(e)}function rC(){_h.clear(),Qd.clear()}const Ho=new Map,Jd=new Map,Rp=new Map,P5=Object.freeze([]);function eh(e){return Ho.get(e)??P5}function z5(e,t){let n=Jd.get(e);return n||(n=new Set,Jd.set(e,n)),n.add(t),()=>n?.delete(t)}function Tv(e,t){t.length!==0&&(Ho.set(e,[...eh(e),...t]),om(e))}function Ev(e){const t=Rp.get(e)??1;return Rp.set(e,t+1),`attach${t}`}function vb(e){Rp.delete(e)}function gd(e,t,n){const s=eh(e);s.length!==0&&(Ho.set(e,s.map(o=>t.has(o.id)?n(o):o)),om(e))}function Af(e,t){const n=eh(e);n.find(l=>l.id===t)?.cancel?.();const o=n.filter(l=>l.id!==t);o.length!==n.length&&(o.length===0?Ho.delete(e):Ho.set(e,o),om(e))}function t2(e){const t=Ho.get(e);if(t){for(const n of t)n.cancel?.();Ho.delete(e),om(e)}}function Cd(e){t2(e),vb(e),Jd.delete(e)}function sC(){for(const e of Array.from(Ho.keys()))Cd(e);Jd.clear(),Rp.clear()}function om(e){for(const t of Array.from(Jd.get(e)??[]))t()}class H5 extends Error{constructor(t){super(t),this.name="UploadDropError"}}function $c(e){return e?Array.from(e.types??[]).includes("Files")||Gy(e.items).some(n=>n.kind==="file")?!0:o2(e.files).length>0:!1}async function n2(e){const t=Gy(e.items).filter(n=>n.kind==="file");return t.length>0?U5(t):r2(e.files)}function i2(e){const t=Gy(e.items).filter(o=>o.kind==="file").flatMap(o=>{const l=o.getAsFile();return l?[{relativePath:Yy(l),file:l}]:[]}),n=r2(e.files);if(t.length===0)return n;if(n.length===0)return t;const s=[...t];for(const o of n)s.some(l=>K5(l.file,o.file))||s.push(o);return s}async function U5(e){const t=[];for(const n of e){const s=q5(n);if(s){await s2(s,"",t);continue}const o=n.getAsFile();if(o){t.push({relativePath:Yy(o),file:o});continue}throw new H5("Folder upload is not supported by this browser.")}return t}function r2(e){return o2(e).map(t=>({relativePath:Yy(t),file:t}))}async function s2(e,t,n){const s=Y5(t,e.name);if(e.isFile){const d=await $5(e);n.push({relativePath:s,file:d});return}if(!e.isDirectory)return;const o=e.createReader(),l=await F5(o);for(const d of l)await s2(d,s,n)}function $5(e){return new Promise((t,n)=>{e.file(t,s=>n(s))})}async function F5(e){const t=[];for(;;){const n=await W5(e);if(n.length===0)return t;t.push(...n)}}function W5(e){return new Promise((t,n)=>{e.readEntries(t,s=>n(s))})}function Yy(e){const t=e.webkitRelativePath;return a2(typeof t=="string"&&t?t:e.name)}function K5(e,t){return e===t||e.name===t.name&&e.size===t.size&&e.type===t.type}function q5(e){const t=e.webkitGetAsEntry?.();return V5(t)?t:null}function V5(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.isFile=="boolean"&&typeof t.isDirectory=="boolean"}function Y5(e,t){return a2(e?`${e}/${t}`:t)}function a2(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").split("/").filter(Boolean).join("/")}function Gy(e){return e?Array.from(e):[]}function o2(e){return e?Array.from(e):[]}const G5=120,X5="\x1B[200~",Z5="\x1B[201~";function Yf(e,t){const n=t.stripTrailingLineBreaks===!1?e:l2(e),s=J5(n);return s?t.bracketedPasteMode?`${X5}${s}${Z5}`:s:""}function Q5(e){return e==="queue"?" ":"\r"}function l2(e){return e.replace(/(?:\r\n|\r|\n)+$/,"")}function J5(e){return e.replace(/\r\n/g,`
50
+ `).replace(/\r/g,`
51
+ `).replace(/\n/g,"\r")}const e4=420,t4=3e3,aC=650,n4=80,i4=3,r4=10,s4=50*1024*1024,a4=100*1024*1024,o4=2,l4={maxFiles:r4,maxFileBytes:s4,maxBatchBytes:a4},Gf=new Set;let Yc=null;function c4({terminalId:e,onSubmit:t,queueAvailable:n=!1,disabled:s=!1,onUploadAttachments:o,onGetAttachmentLimits:l,onDeleteAttachments:d}){const f=v.useMemo(()=>j=>O5(e,j),[e]),m=v.useMemo(()=>()=>Vc(e),[e]),p=v.useSyncExternalStore(f,m,m),{open:b,text:_}=p,S=v.useMemo(()=>j=>z5(e,j),[e]),w=v.useMemo(()=>()=>eh(e),[e]),x=v.useSyncExternalStore(S,w,w),[R,L]=v.useState(l4),[A,W]=v.useState(!1),H=v.useRef(null),U=v.useRef(null),q=v.useRef(null),Y=v.useRef(null),I=v.useRef(new Map),F=v.useRef(l),de=v.useRef(d),me=v.useRef(null),K=v.useRef({start:0,end:0});F.current=l,de.current=d,v.useEffect(()=>()=>{me.current?.(),me.current=null},[]),v.useEffect(()=>{if(!b||!F.current)return;let j=!0;return F.current().then(ge=>{j&&L(ge)}).catch(()=>{}),()=>{j=!1}},[b,e]),v.useLayoutEffect(()=>{if(!(!b||!Xf()))return v4(e),()=>_4(e)},[b,e]),v.useLayoutEffect(()=>{const j=H.current?.closest(".terminal-pane");if(!j)return;function ge(){j?.removeAttribute("data-compose-open"),j?.style.removeProperty("--compose-drawer-panel-height")}if(!b){ge();return}const Ae=U.current;j.setAttribute("data-compose-open","true");function Oe(){const Ne=Ae?.getBoundingClientRect().height??0;Ne>0&&j?.style.setProperty("--compose-drawer-panel-height",`${Math.ceil(Ne)}px`)}Oe();const z=[window.setTimeout(Oe,0),window.setTimeout(Oe,180),window.setTimeout(Oe,260)],fe=window.requestAnimationFrame?.(Oe)??null,Te=typeof ResizeObserver=="function"&&Ae?new ResizeObserver(Oe):null;return Te&&Ae&&Te.observe(Ae),()=>{for(const Ne of z)window.clearTimeout(Ne);fe!==null&&window.cancelAnimationFrame?.(fe),Te?.disconnect(),ge()}},[b]),v.useEffect(()=>{if(!b){me.current?.(),me.current=null;return}Mv(q.current),ve()},[b]);function te(j){B5(e,j)}function J(j){I5(e,j)}function Q(){g4(H.current),te(!1),cC()}function X(j="send"){const ge=x.filter(Oe=>Oe.status==="uploaded"&&Oe.path);if(s||x.some(Oe=>Oe.status==="uploading"||Oe.status==="failed")||!_&&ge.length===0)return;const Ae=h4(_,x);if(Ae.parts.some(Oe=>Oe.kind==="image"||Oe.value.trim())&&t(Ae,j)){if(J(""),t2(e),vb(e),Xf()){q.current?.blur(),cC();return}window.setTimeout(()=>q.current?.focus(),G5+20)}}async function M(j){if(s||j.length===0)return;const ge=eh(e).filter(be=>be.status!=="failed"),Ae=ge.reduce((be,$e)=>be+$e.file.size,0);let Oe=0,z=ge.length;const fe=[],Te=j.filter((be,$e)=>{const qe=Ae+Oe+be.file.size,je=be.file.size>R.maxFileBytes?`File exceeds the ${lC(R.maxFileBytes)} attachment limit.`:z>=R.maxFiles?`A compose message can include up to ${R.maxFiles} attachments.`:qe>R.maxBatchBytes?`Compose attachments cannot exceed ${lC(R.maxBatchBytes)} in total.`:null;return je?(fe.push({id:Nv($e),reference:Ev(e),file:be.file,relativePath:oC(be.relativePath,be.file.name),status:"failed",error:je}),!1):(z+=1,Oe+=be.file.size,!0)});if(fe.length>0&&Tv(e,fe),Te.length===0)return;const Ne=new Map,Le=Te.map((be,$e)=>{const qe=Nv($e),je=new AbortController;return Ne.set(qe,je),{id:qe,reference:Ev(e),file:be.file,relativePath:oC(be.relativePath,be.file.name),status:"uploading",loaded:0,total:be.file.size,cancel:()=>je.abort()}});Tv(e,Le),Fe(Le.map(be=>be.reference));for(const be of Le)I.current.set(be.id,Ne.get(be.id));await m4(Le,o4,async be=>{const $e=Ne.get(be.id),qe=new Set([be.id]);try{const ht=(await o([{relativePath:be.relativePath,file:be.file}],{signal:$e.signal,onProgress:st=>{gd(e,qe,mt=>({...mt,loaded:st.loaded,total:st.total}))}})).results[0];if($e.signal.aborted){const st=de.current;ht?.status==="uploaded"&&ht.attachmentId&&st&&st([ht.attachmentId]).catch(()=>{});return}gd(e,qe,st=>{const{error:mt,cancel:xt,...on}=st;return ht?.status==="uploaded"&&ht.path?{...on,status:"uploaded",...ht.attachmentId?{attachmentId:ht.attachmentId}:{},path:ht.path,loaded:ht.size??st.file.size,total:ht.size??st.file.size}:{...on,status:"failed",error:ht?.error??"upload_failed"}})}catch(je){const ht=$e.signal.aborted?"Upload canceled.":Dv(je);gd(e,qe,st=>{const{cancel:mt,...xt}=st;return{...xt,status:"failed",error:ht}})}finally{I.current.get(be.id)===$e&&I.current.delete(be.id)}})}function T(j){if(j.status!=="removing"){if(Ie(j.reference),j.status!=="uploaded"&&j.status!=="failed"||!j.attachmentId||!de.current){I.current.delete(j.id),Af(e,j.id);return}re([j])}}function O(){J(""),vb(e);const j=x.filter(ge=>!!(ge.path&&ge.attachmentId));for(const ge of x)j.includes(ge)||(I.current.delete(ge.id),Af(e,ge.id));j.length>0&&re(j)}function re(j){const ge=j.flatMap(Oe=>Oe.attachmentId?[Oe.attachmentId]:[]);if(ge.length===0||!de.current){for(const Oe of j)Af(e,Oe.id);return}const Ae=new Set(j.map(Oe=>Oe.id));gd(e,Ae,Oe=>{const{error:z,...fe}=Oe;return{...fe,status:"removing"}}),de.current(ge).then(()=>{for(const Oe of j)Af(e,Oe.id)}).catch(Oe=>{gd(e,Ae,z=>({...z,status:"failed",error:`Could not remove attachment: ${Dv(Oe)}`}))})}function he(j){const ge=Array.from(j.currentTarget.files??[]).map(Ae=>({relativePath:Ae.name,file:Ae}));j.currentTarget.value="",M(ge)}function N(j){const ge=i2(j.clipboardData);ge.length!==0&&(j.preventDefault(),M(ge))}function V(j){s||!$c(j.dataTransfer)||(j.preventDefault(),j.stopPropagation(),j.dataTransfer.dropEffect="copy",W(!0))}function se(j){s||!$c(j.dataTransfer)||(j.preventDefault(),j.stopPropagation(),W(!0))}function Z(j){if(!$c(j.dataTransfer))return;const ge=j.relatedTarget;ge instanceof Node&&j.currentTarget.contains(ge)||W(!1)}function Ee(j){$c(j.dataTransfer)&&(j.preventDefault(),j.stopPropagation(),W(!1),n2(j.dataTransfer).then(M).catch(ge=>{const Ae={id:Nv(0),reference:Ev(e),file:new File([],"attachment"),relativePath:"attachment",status:"failed",error:Dv(ge)};Tv(e,[Ae])}))}const ye=x.some(j=>j.status==="uploading"),ze=x.some(j=>j.status==="failed"),Ke=x.filter(j=>j.status==="uploaded"&&j.path).length,Be=!s&&!ye&&!ze&&(!!_||Ke>0);function ve(){Xf()&&(me.current?.(),me.current=b4())}function Fe(j){if(j.length===0)return;const ge=j.map(je=>`@${je}`).join(" "),Ae=Vc(e).text,Oe=Math.min(K.current.start,Ae.length),z=Math.min(Math.max(Oe,K.current.end),Ae.length),fe=Ae.slice(0,Oe),Te=Ae.slice(z),Ne=fe&&!/\s$/.test(fe)?" ":"",Le=Te&&!/^\s/.test(Te)?" ":"",be=`${Ne}${ge}${Le}`,$e=`${fe}${be}${Te}`,qe=fe.length+be.length;K.current={start:qe,end:qe},J($e),window.requestAnimationFrame(()=>{const je=q.current;je&&(Mv(je),je.setSelectionRange(qe,qe))})}function Ie(j){const ge=Vc(e).text,Ae=ge.replace(new RegExp(`@${p4(j)}(?![A-Za-z0-9_])`,"g"),"");Ae!==ge&&J(Ae.replace(/[ \t]{2,}/g," "))}return u.jsxs("div",{ref:H,className:"compose-drawer","data-open":b?"true":"false",children:[u.jsxs("button",{type:"button",className:"compose-drawer-handle","aria-label":"Open compose drawer","aria-hidden":b?"true":void 0,tabIndex:b?-1:0,title:"Compose long input — type without per-keystroke latency, send with Cmd/Ctrl+Enter",onClick:()=>te(!0),children:[u.jsx("span",{"aria-hidden":"true",children:"▴"}),u.jsx("span",{children:"compose"}),_||x.length>0?u.jsx("span",{className:"compose-drawer-handle-dot","aria-label":"draft saved"}):null]}),u.jsxs("div",{ref:U,className:"compose-drawer-panel","aria-hidden":b?void 0:"true","data-file-drag-active":A?"true":void 0,onDragEnter:se,onDragOver:V,onDragLeave:Z,onDrop:Ee,children:[A?u.jsx("div",{className:"compose-drawer-drop-overlay","aria-hidden":"true",children:"Drop files to attach"}):null,u.jsxs("button",{type:"button",className:"compose-drawer-header","aria-label":"Collapse compose drawer",tabIndex:b?0:-1,title:"Click to collapse — Esc also closes when focus is in the textarea",onClick:Q,children:[u.jsx("span",{"aria-hidden":"true",children:"▾"}),u.jsx("span",{className:"compose-drawer-title",children:"compose"}),u.jsx("span",{className:"compose-drawer-hint","aria-hidden":"true",children:n?"Cmd/Ctrl+Enter to send · Cmd/Ctrl+Shift+Enter to queue · Esc to close":"Cmd/Ctrl+Enter to send · Enter for newline · Esc to close"}),u.jsx("span",{className:"compose-drawer-close","aria-hidden":"true",children:"×"})]}),u.jsx("textarea",{ref:q,className:"compose-drawer-input","aria-label":"Compose input",tabIndex:b?0:-1,spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",value:_,onChange:j=>{K.current={start:j.target.selectionStart,end:j.target.selectionEnd},J(j.target.value)},onSelect:j=>{K.current={start:j.currentTarget.selectionStart,end:j.currentTarget.selectionEnd}},onPaste:N,onFocus:ve,onKeyDown:j=>{if(j.key==="Enter"&&(j.metaKey||j.ctrlKey)){if(j.preventDefault(),j.shiftKey){n&&X("queue");return}X("send");return}j.key==="Escape"&&(j.preventDefault(),Q())},placeholder:n?"Type a longer command here, then send or queue it.":"Type a longer command here, then Cmd/Ctrl+Enter to send."}),u.jsx("input",{ref:Y,className:"compose-drawer-file-input",type:"file",multiple:!0,tabIndex:-1,onChange:he}),x.length>0?u.jsx("div",{className:"compose-attachments","aria-label":"Compose attachments",children:x.map(j=>u.jsx(u4,{attachment:j,onRemove:()=>T(j)},j.id))}):null,u.jsxs("div",{className:"compose-drawer-actions",children:[u.jsx("button",{type:"button",className:"compose-drawer-attach",tabIndex:b?0:-1,title:"Attach files to this message","aria-label":"Attach files",onClick:()=>Y.current?.click(),disabled:s,children:"+"}),u.jsx("button",{type:"button",className:"compose-drawer-clear",tabIndex:b?0:-1,onClick:()=>{O(),Mv(q.current),ve()},disabled:!_&&x.length===0,children:"Clear"}),n?u.jsx("button",{type:"button",className:"compose-drawer-queue",tabIndex:b?0:-1,title:ze?"Remove failed attachments before sending.":"Queue in Codex with Cmd/Ctrl+Shift+Enter",onClick:()=>X("queue"),disabled:!Be,children:"Queue"}):null,u.jsx("button",{type:"button",className:"compose-drawer-send",tabIndex:b?0:-1,title:ze?"Remove failed attachments before sending.":void 0,onClick:()=>X("send"),disabled:!Be,children:"Send"})]})]})]})}function u4({attachment:e,onRemove:t}){const n=d4(e.file,e.status==="uploaded"||e.status==="uploading"||e.status==="removing"),s=e.file.type.startsWith("image/"),o=e.relativePath.split("/").at(-1)??e.relativePath;return u.jsxs("div",{className:"compose-attachment","data-status":e.status,children:[s&&n?u.jsx("img",{src:n,alt:""}):u.jsx("span",{className:"compose-attachment-file","aria-hidden":"true",children:"file"}),u.jsxs("span",{className:"compose-attachment-reference",title:`Reference @${e.reference}`,children:["@",e.reference]}),u.jsx("span",{className:"compose-attachment-name",title:e.relativePath,children:o}),u.jsx("span",{className:"compose-attachment-state",children:e.status==="uploading"?e.total?`${Math.round((e.loaded??0)/e.total*100)}%`:"Uploading":e.status==="removing"?"Removing":e.status==="uploaded"?"Ready":e.error??"Failed"}),u.jsx("button",{type:"button","aria-label":`Remove ${o}`,title:"Remove attachment",onClick:t,disabled:e.status==="removing",children:"x"})]})}function d4(e,t){const n=v.useMemo(()=>t&&e.type.startsWith("image/")&&typeof URL.createObjectURL=="function"?URL.createObjectURL(e):null,[t,e]);return v.useEffect(()=>()=>{n&&URL.revokeObjectURL(n)},[n]),n}function h4(e,t){const n=new Map(t.map(f=>[f.reference,f])),s=[],o=/@([A-Za-z][A-Za-z0-9_]*)(?![A-Za-z0-9_])/g;let l=0,d;for(;(d=o.exec(e))!==null;){const f=n.get(d[1]);f&&(Rv(s,e.slice(l,d.index)),f.status==="uploaded"&&f.path&&(f4(f)?s.push({kind:"image",path:f.path}):Rv(s,f.path)),l=o.lastIndex)}return Rv(s,e.slice(l)),{parts:s}}function Rv(e,t){if(!t)return;const n=e.at(-1);if(n?.kind==="text"){n.value+=t;return}e.push({kind:"text",value:t})}function f4(e){return e.file.type.startsWith("image/")?!0:/\.(?:avif|bmp|gif|jpe?g|png|webp)$/i.test(e.relativePath)}function p4(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oC(e,t){return e.replace(/\\/g,"/").replace(/^\/+/,"").split("/").filter(Boolean).join("/")||t||"attachment"}function Nv(e){return typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`attachment-${Date.now()}-${e}-${Math.random().toString(16).slice(2)}`}function Dv(e){return e instanceof Error&&e.message?e.message:"Upload failed."}function lC(e){return e%(1024*1024)===0?`${e/(1024*1024)} MB`:e>=1024*1024?`${Math.round(e/(1024*1024)*10)/10} MB`:`${Math.ceil(e/1024)} KB`}async function m4(e,t,n){let s=0;const o=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){const l=s;if(s+=1,l>=e.length)return;await n(e[l])}});await Promise.all(o)}function g4(e){const t=document.activeElement;t instanceof HTMLElement&&(!e||e.contains(t))&&t.blur()}function Mv(e){if(e)try{e.focus({preventScroll:!0})}catch{e.focus()}}function Xf(){return navigator.maxTouchPoints>0?!0:typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}function cC(){if(!Xf())return;const e=Fc;e(),window.requestAnimationFrame?.(e),window.setTimeout(e,120),window.setTimeout(e,320)}function v4(e){Yc!==null&&(window.clearTimeout(Yc),Yc=null),Gf.add(e),document.documentElement.setAttribute(am,"true"),Fc()}function _4(e){if(Gf.delete(e),Gf.size>0||Yc!==null){Fc();return}Yc=window.setTimeout(()=>{if(Yc=null,Gf.size>0){Fc();return}document.documentElement.removeAttribute(am),Fc()},e4),Fc()}function b4(){let e=!1,t=null,n=null,s=null,o=0;const l=Date.now(),d=window.visualViewport,f=y4();function m(){t!==null&&(window.clearTimeout(t),t=null),n!==null&&(window.cancelAnimationFrame?.(n),n=null)}function p(){e||(e=!0,m(),d?.removeEventListener("resize",_),d?.removeEventListener("scroll",_),f?.removeEventListener("geometrychange",_))}function b(S){if(!e){if(S<aC&&typeof window.requestAnimationFrame=="function"){n=window.requestAnimationFrame(_);return}t=window.setTimeout(_,n4)}}function _(){if(e)return;m();const S=Vy(),w=Date.now()-l;if(S.keyboardInsetBottom>0&&S.keyboardInsetBottom===s?o+=1:(o=S.keyboardInsetBottom>0?1:0,s=S.keyboardInsetBottom),w>=t4||w>=aC&&o>=i4){p();return}b(w)}return d?.addEventListener("resize",_),d?.addEventListener("scroll",_),f?.addEventListener("geometrychange",_),_(),p}function Fc(){window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0,Vy()}function y4(){const e=navigator.virtualKeyboard;return!e||typeof e.addEventListener!="function"?null:e}function S4(e,t={}){const n=typeof t=="function"?{onPasteText:t}:t;e.attachCustomKeyEventHandler(d=>{if(C4(d))return d.preventDefault(),d.stopPropagation(),w4(e),!1;if(x4(d)&&n.onInterrupt&&n.shouldInterruptPlainCtrlC?.())return d.preventDefault(),d.stopPropagation(),n.onInterrupt(),!1;if(k4(d)){const f=_b(e);return f?(d.preventDefault(),d.stopPropagation(),bb(f),!1):!0}return T4(d)?(d.stopPropagation(),!1):!0});const s=e.element;if(!s)return{dispose(){e.attachCustomKeyEventHandler(()=>!0)}};const o=d=>{const f=_b(e);if(f){if(d.clipboardData){d.clipboardData.setData("text/plain",f),d.preventDefault();return}d.preventDefault(),bb(f)}},l=d=>{if(n.canPaste?.()===!1){d.preventDefault(),d.stopImmediatePropagation();return}if(n.onPasteFiles&&d.clipboardData){const p=i2(d.clipboardData).map(b=>b.file);if(p.length>0){d.preventDefault(),d.stopImmediatePropagation(),n.onPasteFiles(p);return}}const f=d.clipboardData?.getData("text/plain");if(!f)return;const m=l2(f);d.preventDefault(),d.stopImmediatePropagation(),E4(e,m,n.onPasteText)};return s.addEventListener("copy",o,!0),s.addEventListener("paste",l,!0),{dispose(){s.removeEventListener("copy",o,!0),s.removeEventListener("paste",l,!0),e.attachCustomKeyEventHandler(()=>!0)}}}async function w4(e){const t=_b(e);t&&await bb(t)}function x4(e){return e.type==="keydown"&&e.key.toLowerCase()==="c"&&e.ctrlKey&&!e.altKey&&!e.shiftKey&&!e.metaKey}function C4(e){return e.type!=="keydown"||e.altKey||e.key.toLowerCase()!=="c"?!1:e.metaKey&&!e.ctrlKey&&!e.shiftKey||e.ctrlKey&&e.shiftKey&&!e.metaKey}function k4(e){return e.type!=="keydown"||e.altKey||e.key.toLowerCase()!=="c"?!1:e.ctrlKey&&!e.shiftKey&&!e.metaKey}function T4(e){return e.type!=="keydown"||e.altKey||e.key.toLowerCase()!=="v"?!1:e.metaKey&&!e.ctrlKey&&!e.shiftKey||e.ctrlKey&&e.shiftKey&&!e.metaKey?!0:e.ctrlKey&&!e.shiftKey&&!e.metaKey}function E4(e,t,n){if(t){if(n){n(t);return}e.paste(t)}}function _b(e){return e.hasSelection()?e.getSelection():R4(e.element??null)}function R4(e){if(!e||typeof window.getSelection!="function")return"";const t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount<=0)return"";const n=t.toString();if(!n)return"";for(let s=0;s<t.rangeCount;s+=1){const o=t.getRangeAt(s);if(e.contains(o.commonAncestorContainer))return n}return""}async function bb(e){if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(e);return}catch{}N4(e)}function N4(e){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=document.createElement("textarea");n.value=e,n.setAttribute("readonly","true"),n.style.position="fixed",n.style.left="-9999px",n.style.top="0",n.style.opacity="0",document.body.appendChild(n),n.focus({preventScroll:!0}),n.select();try{typeof document.execCommand=="function"&&document.execCommand("copy")}finally{n.remove(),t?.focus({preventScroll:!0})}}const D4=10,M4=100*1024*1024;class A4{constructor(t){this.options=t}options;jobs=[];job=null;limits=null;notice=null;percent=null;get pending(){return this.jobs.length>0}cancel(t,n=!1){for(const s of this.jobs)s.controller.abort(),s.timer!==null&&clearTimeout(s.timer),s.resolve();this.jobs=[],this.job=null,this.limits=null,this.notice=null,this.percent=null,this.options.onState(t?{uploading:!1,message:t,...n?{error:!0}:{}}:null)}allowInput(t,n=!1){return!this.pending||n?!0:t===""||t===""||t===""||t==="\x1B"?(this.cancel("Image paste canceled."),!0):!/[\r\n\t]/.test(t)}paste(t){if(t.length===0)return Promise.resolve();const n=this.options.getTarget();if(this.job&&this.job.target!==n&&this.cancel(),this.pending||(this.notice=null),!n?.supportsImages)return this.showNotice("Image paste requires an active Codex or Claude pane."),Promise.resolve();const s=t.map(L4);if(s.some(l=>l===null))return this.showNotice("Only image attachments are supported here."),Promise.resolve();const o=this.jobs.flatMap(l=>l.files);return o.length+t.length>D4||[...o,...t].reduce((l,d)=>l+d.size,0)>M4?(this.showNotice("New images were not queued: image paste is limited to 10 pending images and 100 MiB."),Promise.resolve()):new Promise(l=>{this.jobs.push({target:n,files:s,controller:new AbortController,timer:null,resolve:l}),this.publishState(),this.startNext()})}startNext(){if(this.job)return;const t=this.jobs[0];if(!t){this.limits=null,this.publishState();return}this.job=t,this.percent=null,this.publishState(),this.upload(t)}showNotice(t){this.notice=t,this.publishState()}publishState(){const t=this.jobs.reduce((s,o)=>s+o.files.length,0),n=t>0?`Uploading ${t} image${t===1?"":"s"}${this.percent===null?"...":` (${this.percent}%)`}`:"";this.options.onState(n||this.notice?{uploading:t>0,message:[n,this.notice].filter(Boolean).join(" "),...this.notice?{error:!0}:{}}:null)}async upload(t){const{target:n,files:s,controller:o}=t,l=()=>this.job===t&&!o.signal.aborted&&this.options.getTarget()===n,d=[];let f=!1;t.timer=setTimeout(()=>{this.job===t&&this.cancel("Image upload timed out. Pending image pastes were canceled.",!0)},12e4);try{if(!l())return;const m=this.limits??await n.api.getComposeAttachmentLimits(o.signal);if(!l())return;if(this.limits=m,s.length>m.maxFiles||s.some(_=>_.size>m.maxFileBytes)||s.reduce((_,S)=>_+S.size,0)>m.maxBatchBytes)throw new Error("Images exceed the server attachment limits.");const p=await n.api.uploadComposeAttachments({terminalId:n.terminalId,files:s.map(_=>({file:_,relativePath:_.name})),signal:o.signal,onProgress:_=>{l()&&(this.percent=_.percent,this.publishState())}});if(d.push(...p.results.filter(_=>_.status==="uploaded")),!l())return;if(p.results.length!==s.length||d.length!==s.length||d.some(_=>!_.path?.startsWith("/")||/[\x00-\x1f\x7f]/.test(_.path)))throw new Error("Image upload did not complete. No images were pasted.");const b=d.map(_=>Yf(_.path,{bracketedPasteMode:!0})).join("");if(f=this.options.send(b),!f)throw new Error("Images were not pasted because the terminal connection is unavailable.")}catch(m){l()&&this.cancel(`${m instanceof Error?m.message:"Image paste failed."} Pending image pastes were canceled.`,!0)}finally{if(t.timer!==null&&clearTimeout(t.timer),this.job===t&&(this.options.getTarget()!==n?this.cancel():(this.jobs.shift(),this.job=null,t.resolve(),this.startNext())),!f&&d.length>0){const m=d.flatMap(p=>p.attachmentId?[p.attachmentId]:[]);m.length>0&&n.api.deleteComposeAttachments({terminalId:n.terminalId,attachmentIds:m}).catch(()=>{})}}}}function L4(e){if(/\.(?:avif|bmp|gif|jpe?g|png|webp)$/i.test(e.name))return e;const t=/^image\/(avif|bmp|gif|jpeg|png|webp)$/.exec(e.type.toLowerCase())?.[1];if(!t)return null;const n=t==="jpeg"?"jpg":t;return new File([e],`${e.name||"clipboard"}.${n}`,{type:e.type})}const j4=[4,10,11,12];function O4(e,t){const n=[e.parser.registerCsiHandler({final:"c"},s=>uC(s)),e.parser.registerCsiHandler({prefix:">",final:"c"},s=>uC(s)),e.parser.registerCsiHandler({final:"n"},s=>B4(s)),e.parser.registerCsiHandler({prefix:"?",final:"n"},s=>I4(s)),e.parser.registerCsiHandler({final:"t"},s=>P4(s)),e.parser.registerDcsHandler({intermediates:"$",final:"q"},()=>!0),...j4.map(s=>e.parser.registerOscHandler(s,o=>z4(o)))];return{dispose(){for(const s of n)s.dispose()}}}function uC(e){return lm(e)===0}function B4(e){const t=lm(e);return t===5||t===6}function I4(e){return lm(e)===6}function P4(e){const t=lm(e);return t===14||t===16||t===18}function z4(e){return e.split(";").some(t=>t==="?")}function lm(e){const t=e[0];return typeof t=="number"?t:0}const es=new Map,Av=2*1024*1024,H4=1500,dC=25e3,U4=2500,$4=2500,F4=1e3,W4=2e3,K4=3e4,q4=16*1024*1024,yb=256,c2=xM-3e4,V4=3e3,u2=1e4,Y4=3e3,Sb=16*1024*1024,cm=4*1024*1024,Np=25,G4=1e3,X4=3e3,Lv=8,Z4=100,d2=1e3,hC=[2e3,5e3,15e3,6e4];let Q4=0,J4=0,jv=0,Ov=null,Zf=!1,wb=0,Qf=0,Lo=!1,fC=!1,Hd=null,pC=!1,xb=0,th=document.visibilityState!=="hidden";const Dp=new Set;let Gc=null,Ud=0;const eI=new TextEncoder,tI=CI();function nI(e,t,n){rI(),hI(),Zp()&&La(0);let s=es.get(e);s?s.exited&&(s.reconnectEnabled||s.status==="unauthorized")&&n?.status==="running"&&n.id===s.snapshot?.id&&Date.parse(n.updatedAt)>Date.parse(s.snapshot.updatedAt)&&(s.snapshot=n,s.status!=="unauthorized"&&s.reconnectEnabled&&(s.exited=!1,(!s.socket||s.socket.readyState===WebSocket.CLOSED)&&Ul(s))):(s=oI(e),es.set(e,s),Ul(s)),s.listeners.add(t);const o=Symbol(e);queueMicrotask(()=>Zy(s));const l=(m,p)=>pI(s,m,p),d=m=>{m?(s.foregroundAttachments.add(o),Mp(),p2(s)):(s.foregroundAttachments.delete(o),Cb())},f=()=>{s.listeners.delete(t),s.foregroundAttachments.delete(o),Cb()};return{status:s.status,snapshot:s.snapshot,output:s.output.slice(),history:s.history,send:l,setForeground:d,detach:f}}function kd(e){const t=es.get(e);t&&(xI(t),es.delete(e),Cb())}function iI(e){const t=es.get(e);if(!t)return!1;t.exited=!1,t.reconnectEnabled=!0,t.reconnectTimer!==null&&(window.clearTimeout(t.reconnectTimer),t.reconnectTimer=null),$o(t),hs(t),Ws(t),Fo(t),Us(t,"reconnecting"),Wo(t);const n=t.socket;return t.socket=null,Ra(t,"reconnecting"),n&&(n.readyState===WebSocket.OPEN||n.readyState===WebSocket.CONNECTING)&&n.close(),Ul(t),!0}function rI(){if(pC)return;pC=!0;const e=()=>{if(document.visibilityState==="hidden"){th=!1,xb+=1,m2(),f2(),sI();return}Xy(),Ud=Date.now(),Mp()};document.addEventListener("visibilitychange",e),window.addEventListener("pageshow",e),window.addEventListener("online",e),Mp()}function Mp(){Gc!==null||document.visibilityState==="hidden"||!h2()||typeof window.requestAnimationFrame!="function"||(Gc=window.requestAnimationFrame(()=>{if(Gc=null,document.visibilityState==="hidden")return;const e=Date.now(),t=Ud>0?e-Ud:0;if(Ud=e,t>=W4){for(const n of es.values())n.foregroundAttachments.size>0&&!n.exited&&n.reconnectEnabled&&Ba("terminal.connection.foreground_gap",n,{gapMs:t});Xy(void 0,{foregroundOnly:!0})}Mp()}))}function h2(){for(const e of es.values())if(e.foregroundAttachments.size>0)return!0;return!1}function Cb(){h2()||(f2(),Ud=0)}function f2(){Gc!==null&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(Gc),Gc=null}function p2(e){if(document.visibilityState!=="hidden"){if(!th||e?.heartbeatSuspended){Xy(e);return}e&&kb(e)}}function Xy(e,t={}){if(document.visibilityState==="hidden")return;th=!0;const n=++xb;m2();const s=Array.from(es.values()).filter(f=>!f.exited&&f.reconnectEnabled&&f.status!=="unauthorized"),o=s.filter(f=>f===e||f.foregroundAttachments.size>0||gI(f)),l=new Set(o),d=s.filter(f=>!l.has(f));for(const f of o)kb(f);if(!t.foregroundOnly)for(let f=0;f<d.length;f+=Lv){const m=d.slice(f,f+Lv),p=Math.floor(f/Lv)*Z4,b=window.setTimeout(()=>{if(Dp.delete(b),!(n!==xb||!th||document.visibilityState==="hidden"))for(const _ of m)kb(_)},p);Dp.add(b)}}function m2(){for(const e of Dp)window.clearTimeout(e);Dp.clear()}function kb(e){if(e.heartbeatSuspended=!1,e.exited||!e.reconnectEnabled||e.status==="unauthorized")return Promise.resolve("skipped");const t=e.socket;if(!t)return e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null,Ul(e)),Promise.resolve(e.status==="closed"?"skipped":"reconnecting");if(t.readyState!==WebSocket.OPEN)return Promise.resolve(e.status==="closed"?"skipped":"reconnecting");if(e.resumeProbe?.socket===t)return e.resumeProbe.promise;const n=Date.now();if(e.lastResumeProbeSocket===t&&n-e.lastResumeProbeAt<F4)return Promise.resolve("alive");Us(e,"reconnecting"),Wo(e),e.lastResumeProbeSocket=t,e.lastResumeProbeAt=n;const s=`resume-${n.toString(36)}-${(++Q4).toString(36)}`;let o;const l=new Promise(f=>{o=f}),d={socket:t,nonce:s,timeout:0,promise:l,resolve:o};e.resumeProbe=d,jl(e,{type:"resume"}),d.timeout=window.setTimeout(()=>{e.resumeProbe!==d||e.socket!==t||(Ba("terminal.connection.resume_timeout",e,{pendingInputs:jo(e)}),Us(e,"reconnecting"),Oo(e))},U4);try{t.send(JSON.stringify({type:"ping",nonce:s}))}catch{Us(e,"reconnecting"),Oo(e)}return l}function sI(){th=!1;for(const e of es.values())e.heartbeatSuspended=!0,$o(e),hs(e),Ws(e),Fo(e),e.lastResumeProbeSocket=null,e.lastResumeProbeAt=0,Us(e,"skipped"),Wo(e)}function aI(){Lo=!1,Zp()&&La(0);for(const e of es.values()){if(e.status!=="unauthorized")continue;if(e.exited&&e.snapshot?.status!=="running"){e.reconnectEnabled=!0,Ra(e,"closed");continue}e.exited=!1,e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),$o(e),hs(e),Ws(e),Fo(e),Us(e,"reconnecting"),Wo(e);const t=e.socket;e.socket=null,e.reconnectEnabled=!0,Ra(e,"reconnecting"),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),Ul(e)}}function Bv(){for(const e of Array.from(es.keys()))kd(e)}function oI(e){return{url:e,socket:null,status:"connecting",snapshot:null,output:[],history:null,outputBytes:0,pendingOut:[],pendingOutBytes:0,unackedInputs:new Map,unackedInputBytes:0,pendingAckReceipts:new Map,inputAckWatchdog:null,inputAckProbe:null,protocolHandshakeWatchdog:null,inputProtocolMode:"unknown",serverInstanceId:null,pendingNotices:[],outboundFlushTimer:null,outboundFlushDelayMs:Np,outboundStallWatchdog:null,listeners:new Set,foregroundAttachments:new Set,reconnectTimer:null,reconnectEnabled:!0,heartbeat:null,heartbeatTickAt:0,heartbeatSuspended:!1,isAlive:!1,resumeProbe:null,lastResumeProbeSocket:null,lastResumeProbeAt:0,lastUpgradeAuthProbeAt:0,exited:!1}}function Ul(e){if(!e.reconnectEnabled)return;Ra(e,e.socket===null&&e.status!=="reconnecting"?"connecting":"reconnecting");const t=new WebSocket(e.url);e.socket=t,hs(e),Ws(e),Fo(e),e.isAlive=!1,e.inputProtocolMode="unknown",e.lastResumeProbeSocket=null,e.lastResumeProbeAt=0;let n=!1;t.addEventListener("open",()=>{e.socket===t&&(n=!0,e.lastUpgradeAuthProbeAt=0,$o(e),hs(e),Ra(e,"connected"),Uo(e,t),g2(e,t),e.isAlive=!0,mC(e))}),t.addEventListener("message",s=>{if(e.socket!==t)return;const o=typeof s.data=="string"?s.data:"";if(!o)return;let l=null;try{l=JSON.parse(o)}catch{return}if(!l||typeof l.type!="string")return;if(AI(l)){LI(e,t,l.instanceId,l.inputAck,l.inputReceipt===!0),Lo&&(Lo=!1,Zp()&&La(0));return}if(e.inputProtocolMode==="unknown"&&b2(e,t),l.type==="pong"){e.isAlive=!0;const f=e.resumeProbe;f?.socket===t&&f.nonce===l.nonce&&(e.lastResumeProbeAt=Date.now(),jo(e)>0&&Ba("terminal.connection.resume_alive",e,{pendingInputs:jo(e)}),Us(e,"alive"),Uo(e,t),mC(e),$l(e),jl(e,{type:"resume"}));const m=e.inputAckProbe;m?.socket===t&&m.nonce===l.nonce&&(nh(e),Ba("terminal.input.delivery_probe_live_but_unreceived",e,{pendingInputs:jo(e)}),Oo(e));return}if(l.type==="input_ack"){RI(e,t,l);return}if(l.type==="input_received"){NI(e,t,l);return}if(l.type==="error"&&DI(e,l),l.type==="input_ack_confirmed"){OI(e,l);return}const d=cI(e,l);if(jl(e,{type:"message",message:d}),l.type==="snapshot"){for(const f of e.pendingNotices)f.ready=!0;Zy(e)}}),t.addEventListener("close",s=>{if(e.socket===t){if(e.socket=null,e.inputProtocolMode="unknown",$o(e),hs(e),Ws(e),Fo(e),Us(e,"reconnecting"),Wo(e),s.code===1008){e.reconnectEnabled=!1,Ra(e,lI(s.reason)?"unauthorized":"closed");return}if(!n&&s.code===1006){const o=Date.now();(e.lastUpgradeAuthProbeAt===0||o-e.lastUpgradeAuthProbeAt>=K4)&&(e.lastUpgradeAuthProbeAt=o,jl(e,{type:"upgrade_rejected"}))}if(e.exited||!e.reconnectEnabled){Ra(e,"closed");return}Ra(e,"reconnecting"),e.reconnectTimer=window.setTimeout(()=>{e.reconnectTimer=null,Ul(e)},H4)}}),t.addEventListener("error",()=>{})}function mC(e){if(Wo(e),e.heartbeatSuspended||document.visibilityState==="hidden"){e.heartbeatSuspended=!0;return}e.heartbeatTickAt=Date.now(),e.heartbeat=window.setInterval(()=>{const t=e.socket;if(!t||t.readyState!==WebSocket.OPEN)return;const n=Date.now(),s=n-e.heartbeatTickAt>dC*1.5;if(e.heartbeatTickAt=n,!e.isAlive&&!s){t.close();return}e.isAlive=!1,t.send(JSON.stringify({type:"ping",nonce:n.toString(36)}))},dC)}function Wo(e){e.heartbeat!==null&&(window.clearInterval(e.heartbeat),e.heartbeat=null),e.heartbeatTickAt=0}function lI(e){const t=e.trim().toLowerCase();return t==="unauthorized"||t==="session expired"||t==="session revoked"||t==="authentication no longer valid"}function cI(e,t){return t.type==="snapshot"?(e.snapshot=t.terminal,e.history=t.history??null,e.exited=t.terminal.status==="exited",e.output=t.output.slice(),e.outputBytes=e.output.reduce((n,s)=>n+Ia(s),0),gC(e),e.exited&&Jf(e),t):t.type==="output"?(e.output.push(t.data),e.outputBytes+=Ia(t.data),gC(e),t):t.type==="terminal_updated"?(e.snapshot=t.terminal,e.exited=t.terminal.status==="exited",e.exited&&Jf(e),t):(t.type==="exit"&&(e.exited=!0,Jf(e),e.snapshot&&e.snapshot.id===t.terminalId&&(e.snapshot={...e.snapshot,status:"exited",exitCode:t.exitCode})),t)}function gC(e){for(;e.outputBytes>Av&&e.output.length>1;){const t=e.output.shift();e.outputBytes-=Ia(t)}e.outputBytes>Av&&e.output.length===1&&(e.output[0]=II(e.output[0],Av),e.outputBytes=Ia(e.output[0]))}function Ra(e,t){e.status!==t&&(e.status=t,jl(e,{type:"status",status:t}))}function jl(e,t){for(const n of Array.from(e.listeners))n(t)}function jo(e){return e.unackedInputs.size+e.pendingOut.reduce((t,n)=>t+(n.message.type==="input"&&!n.message.messageId?1:0),0)}function uI(e){if(e.snapshot?.id)return e.snapshot.id;for(const t of e.pendingOut)if(t.message.type==="input")return t.message.terminalId;for(const t of e.unackedInputs.values())if(t.message.type==="input")return t.message.terminalId;return null}function dI(e,t,n={}){const s=es.get(e);s&&Ba(`terminal.connection.render_${t}`,s,n)}function Ba(e,t,n={}){Pi(e,{...n,status:t.status,socketState:t.socket?.readyState??null,heartbeatSuspended:t.heartbeatSuspended,resumePending:t.resumeProbe!==null,queuedInputs:jo(t),unacknowledgedInputs:t.unackedInputs.size,terminalId:n.terminalId??uI(t)}),wb+=1,Qf=0,La(d2)}function hI(){if(fC)return;fC=!0;const e=()=>{document.visibilityState==="hidden"||Lo||Zp()&&La(0)};window.addEventListener("online",e),window.addEventListener("pageshow",e),document.addEventListener("visibilitychange",e)}function La(e){if(Zf){Hd=Hd===null?e:Math.min(Hd,e);return}Ov!==null||Lo||document.visibilityState==="hidden"||navigator.onLine===!1||(Ov=window.setTimeout(()=>{Ov=null,fI()},e))}async function fI(){if(Zf||Lo||document.visibilityState==="hidden"||navigator.onLine===!1)return;Zf=!0;const e=wb;try{const t=await NM();if(t.outcome==="auth_blocked"){Lo=!0;return}if(t.outcome==="retryable"){const n=hC[Math.min(Qf,hC.length-1)];Qf+=1,La(n);return}if(Qf=0,t.outcome==="sent"&&t.hasMore){La(0);return}}finally{Zf=!1;const t=Hd;Hd=null,t!==null&&La(t),wb!==e&&!Lo&&La(d2)}}function pI(e,t,n={}){if(e.exited||!e.reconnectEnabled||e.status==="closed"||e.status==="unauthorized")return"rejected";const s=TI(e,t);if(!s)return"rejected";const o=JSON.stringify(s),l=Ia(o);if(l>q4)return"rejected";const d=n.durability!=="live-only"&&s.type!=="restore_screen",f={message:s,encoded:o,bytes:l,sentInstanceId:null,receivedInstanceId:null,firstSentAt:null,lastSentAt:null,receivedAt:null,writeSlowReported:!1,inputState:s.type==="input"?"queued":null,durable:d};if(!EI(e,f))return"rejected";const m=e.socket,p=m?.readyState===WebSocket.OPEN;s.type==="input"&&d&&e.heartbeatSuspended&&document.visibilityState==="visible"&&(Ba("terminal.input.foreground_resume",e,{terminalId:s.terminalId,pendingInputs:jo(e)}),p2(e));const _=s.type!=="ping"&&s.type!=="resize";if(_&&(!p||s.type==="input"&&e.inputProtocolMode==="unknown"||e.resumeProbe!==null||e.heartbeatSuspended||document.visibilityState==="hidden"||e.pendingOut.length>0||(m?.bufferedAmount??0)>cm))return s.type==="redraw"||s.type==="restore_screen"||!d?"rejected":mI(e,s)?(p&&m&&Uo(e,m),"queued"):e.pendingOut.length>=yb||e.pendingOutBytes+l>Sb?"rejected":(e.pendingOut.push(f),e.pendingOutBytes+=l,_C(e,f),p&&m&&Uo(e,m),"queued");if(p){_C(e,f);try{return m.send(o),_2(e,f),"sent"}catch{if(_&&d&&e.pendingOut.length<yb&&e.pendingOutBytes+l<=Sb)return e.pendingOut.push(f),e.pendingOutBytes+=l,m.close(),"queued";Wl(e,f),m.close()}}return"rejected"}function Uo(e,t){if(e.socket!==t||t.readyState!==WebSocket.OPEN||e.resumeProbe||e.heartbeatSuspended||document.visibilityState==="hidden"){hs(e);return}let n=!1;for(;e.pendingOut.length>0;){if(t.bufferedAmount>cm){BI(e,t),_I(e,t);return}const s=e.pendingOut[0];if(s.message.type==="input"&&e.inputProtocolMode==="unknown"){g2(e,t);return}try{t.send(s.encoded),_2(e,s)}catch{t.close();return}e.pendingOut.shift(),e.pendingOutBytes=Math.max(0,e.pendingOutBytes-s.bytes),e.outboundFlushDelayMs=Np,n=!0}e.outboundFlushDelayMs=Np,hs(e),n&&queueMicrotask(()=>{e.pendingOut.length===0&&jl(e,{type:"outbound_flushed"})})}function mI(e,t){const n=e.pendingOut.at(-1);if(!n||!("terminalId"in t)||!("terminalId"in n.message)||n.message.terminalId!==t.terminalId)return!1;let s=null;if(t.type==="resize"&&n.message.type==="resize")s=t;else{if(t.type==="refresh_cwd"&&n.message.type==="refresh_cwd")return!0;if(t.type==="cancel_scrollback"&&n.message.type==="cancel_scrollback")return!0;if(t.type==="scrollback_scroll"&&n.message.type==="scrollback_scroll"){const d=Math.max(-240,Math.min(240,n.message.lines+t.lines));if(d===0)return e.pendingOut.pop(),e.pendingOutBytes=Math.max(0,e.pendingOutBytes-n.bytes),!0;s={...t,lines:d}}}if(!s)return!1;const o=JSON.stringify(s),l=Ia(o);return e.pendingOutBytes+=l-n.bytes,n.message=s,n.encoded=o,n.bytes=l,!0}function $o(e){e.outboundFlushTimer!==null&&(window.clearTimeout(e.outboundFlushTimer),e.outboundFlushTimer=null),e.outboundFlushDelayMs=Np}function hs(e){e.outboundStallWatchdog!==null&&(window.clearTimeout(e.outboundStallWatchdog),e.outboundStallWatchdog=null)}function Ap(e){return e.pendingOut.some(t=>t.message.type==="input")}function gI(e){return Ap(e)||e.unackedInputs.size>0}function vI(e){if(!Ap(e))return;const t=e.pendingOut.filter(n=>n.message.type!=="scrollback_scroll");t.length!==e.pendingOut.length&&(e.pendingOut=t,e.pendingOutBytes=t.reduce((n,s)=>n+s.bytes,0))}function _I(e,t){e.outboundStallWatchdog!==null||!Ap(e)||(e.outboundStallWatchdog=window.setTimeout(()=>{if(e.outboundStallWatchdog=null,e.socket!==t||t.readyState!==WebSocket.OPEN||e.resumeProbe!==null||e.heartbeatSuspended||document.visibilityState==="hidden"||!Ap(e))return;const n=e.inputProtocolMode==="unknown",s=t.bufferedAmount>cm;if(!n&&!s){Uo(e,t);return}vI(e),Oo(e)},X4))}function Ws(e){e.protocolHandshakeWatchdog!==null&&(window.clearTimeout(e.protocolHandshakeWatchdog),e.protocolHandshakeWatchdog=null)}function g2(e,t){e.protocolHandshakeWatchdog!==null||e.inputProtocolMode!=="unknown"||e.unackedInputs.size===0||e.heartbeatSuspended||document.visibilityState==="hidden"||(e.protocolHandshakeWatchdog=window.setTimeout(()=>{e.protocolHandshakeWatchdog=null,!(e.socket!==t||t.readyState!==WebSocket.OPEN||e.inputProtocolMode!=="unknown"||e.resumeProbe!==null||e.heartbeatSuspended||document.visibilityState==="hidden"||e.unackedInputs.size===0)&&Oo(e)},Y4))}function v2(e){e.inputAckWatchdog!==null&&(window.clearTimeout(e.inputAckWatchdog),e.inputAckWatchdog=null)}function nh(e){const t=e.inputAckProbe;t&&(e.inputAckProbe=null,window.clearTimeout(t.timeout))}function Fo(e){v2(e),nh(e)}function $l(e){v2(e),Tb(e,{notifyImmediately:!0});const t=e.socket;if(!t||t.readyState!==WebSocket.OPEN||e.inputProtocolMode!=="receipt-ack"||!e.serverInstanceId||e.heartbeatSuspended||document.visibilityState==="hidden")return;const n=vC(e),s=bI(e),o=SI(e);if(n===null&&s===null&&o===null){nh(e);return}if(e.inputAckProbe)return;const l=n===null?Number.POSITIVE_INFINITY:n+V4,d=Math.max(0,Math.min(l,s??Number.POSITIVE_INFINITY,o??Number.POSITIVE_INFINITY)-Date.now());e.inputAckWatchdog=window.setTimeout(()=>{if(e.inputAckWatchdog=null,e.socket!==t||t.readyState!==WebSocket.OPEN||e.inputProtocolMode!=="receipt-ack"||e.heartbeatSuspended||document.visibilityState==="hidden")return;if(Tb(e,{notifyImmediately:!0})){$l(e);return}if(yI(e),vC(e)===null){$l(e);return}wI(e,t)},d)}function bI(e){let t=null;for(const n of e.unackedInputs.values()){if(n.receivedAt===null||n.writeSlowReported)continue;const s=n.receivedAt+u2;t=t===null?s:Math.min(t,s)}return t}function yI(e){const t=Date.now();for(const n of e.unackedInputs.values())n.receivedAt===null||n.writeSlowReported||t-n.receivedAt<u2||(n.writeSlowReported=!0,Ba("terminal.input.pty_write_slow",e,{terminalId:n.message.type==="input"?n.message.terminalId:null,waitMs:t-n.receivedAt}))}function vC(e){let t=null;for(const n of e.unackedInputs.values())n.sentInstanceId!==e.serverInstanceId||n.receivedInstanceId===e.serverInstanceId||n.lastSentAt===null||(t=t===null?n.lastSentAt:Math.min(t,n.lastSentAt));return t}function SI(e){let t=null;for(const n of e.unackedInputs.values()){if(n.firstSentAt===null)continue;const s=n.firstSentAt+c2;t=t===null?s:Math.min(t,s)}return t}function wI(e,t){if(e.inputAckProbe||e.socket!==t||t.readyState!==WebSocket.OPEN)return;if(t.bufferedAmount>cm){Oo(e);return}const n=`input-ack-${Date.now().toString(36)}-${(++J4).toString(36)}`;Ba("terminal.input.delivery_probe_started",e,{pendingInputs:jo(e)});const s={socket:t,nonce:n,timeout:0};e.inputAckProbe=s,s.timeout=window.setTimeout(()=>{e.inputAckProbe!==s||e.socket!==t||(Ba("terminal.input.delivery_probe_timeout",e,{pendingInputs:jo(e)}),nh(e),Oo(e))},$4);try{t.send(JSON.stringify({type:"ping",nonce:n}))}catch{nh(e),Oo(e)}}function Us(e,t){const n=e.resumeProbe;n&&(e.resumeProbe=null,window.clearTimeout(n.timeout),n.resolve(t))}function Oo(e){if(e.exited||!e.reconnectEnabled)return;e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),$o(e),hs(e),Ws(e),Fo(e),Us(e,"reconnecting"),Wo(e);const t=e.socket;e.socket=null,Ra(e,"reconnecting"),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),Ul(e)}function xI(e){e.reconnectEnabled=!1,e.reconnectTimer!==null&&(window.clearTimeout(e.reconnectTimer),e.reconnectTimer=null),$o(e),hs(e),Ws(e),Fo(e),Us(e,"skipped"),Wo(e);const t=e.socket;e.socket=null,t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),Jf(e),e.listeners.clear()}function CI(){const e=globalThis.crypto?.randomUUID?.();return e||`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function kI(){return jv=(jv+1)%Number.MAX_SAFE_INTEGER,`${tI}-${jv.toString(36)}`.slice(0,Rk)}function TI(e,t){if(t.type!=="input")return t;if(e.inputProtocolMode==="legacy"){const{messageId:s,...o}=t;return o}const n=kI();return n.length===0||n.length>Rk?null:{...t,messageId:n}}function EI(e,t){if(t.message.type!=="input"||e.inputProtocolMode==="legacy")return!0;const n=t.message.messageId;return!!(n&&!e.unackedInputs.has(n)&&e.unackedInputs.size+e.pendingAckReceipts.size<yb&&e.unackedInputBytes+t.bytes<=Sb)}function _C(e,t){t.message.type!=="input"||!t.message.messageId||(e.unackedInputs.set(t.message.messageId,t),e.unackedInputBytes+=t.bytes)}function Wl(e,t){t.message.type!=="input"||!t.message.messageId||e.unackedInputs.get(t.message.messageId)===t&&(e.unackedInputs.delete(t.message.messageId),e.unackedInputBytes=Math.max(0,e.unackedInputBytes-t.bytes))}function RI(e,t,n){const s=e.unackedInputs.get(n.messageId);if(!s||s.message.type!=="input"||s.message.terminalId!==n.terminalId){const l=e.pendingAckReceipts.get(n.messageId);l?.terminalId===n.terminalId&&Eb(e,t,l);return}if(Wl(e,s),$l(e),!Qy(e.inputProtocolMode)||!e.serverInstanceId)return;const o={terminalId:n.terminalId,messageId:n.messageId,instanceId:e.serverInstanceId,encoded:JSON.stringify({type:"input_ack_received",terminalId:n.terminalId,messageId:n.messageId})};e.pendingAckReceipts.set(n.messageId,o),Eb(e,t,o)}function NI(e,t,n){if(e.socket!==t||e.inputProtocolMode!=="receipt-ack"||!e.serverInstanceId)return;const s=e.unackedInputs.get(n.messageId);s?.message.type!=="input"||s.message.terminalId!==n.terminalId||s.sentInstanceId!==e.serverInstanceId||(s.receivedInstanceId=e.serverInstanceId,s.receivedAt=Date.now(),s.writeSlowReported=!1,s.inputState="received",$l(e))}function DI(e,t){if(!t.terminalId||!t.messageId)return;const n=e.unackedInputs.get(t.messageId);n?.message.type==="input"&&n.message.terminalId===t.terminalId&&(Wl(e,n),$l(e))}function _2(e,t){if(t.message.type!=="input"||!t.message.messageId||!Qy(e.inputProtocolMode)||!e.serverInstanceId)return;const n=Date.now();t.sentInstanceId=e.serverInstanceId,t.receivedInstanceId=null,t.receivedAt=null,t.writeSlowReported=!1,t.firstSentAt??=n,t.lastSentAt=n,t.inputState="sent",$l(e)}function MI(e){if(Tb(e),e.unackedInputs.size===0)return;const t=new Set(e.pendingOut.flatMap(s=>s.message.type==="input"&&s.message.messageId?[s.message.messageId]:[])),n=[];for(const s of Array.from(e.unackedInputs.values())){if(!s.durable){Wl(e,s);continue}s.message.type==="input"&&s.message.messageId&&!t.has(s.message.messageId)&&(s.inputState="queued",n.push(s))}n.length!==0&&(e.pendingOut.unshift(...n),e.pendingOutBytes+=n.reduce((s,o)=>s+o.bytes,0))}function Tb(e,t={}){const n=Date.now(),s=new Set;let o=0;for(const[l,d]of e.unackedInputs)d.firstSentAt!==null&&n-d.firstSentAt>=c2&&(s.add(l),d.durable&&(o+=1));if(s.size===0)return!1;e.pendingOut=e.pendingOut.filter(l=>{const d=l.message.type==="input"?l.message.messageId:void 0;return!d||!s.has(d)?!0:(e.pendingOutBytes=Math.max(0,e.pendingOutBytes-l.bytes),!1)});for(const l of s){const d=e.unackedInputs.get(l);d&&Wl(e,d)}return o>0&&(S2(e,{message:`NTerminal did not receive confirmation for ${o} ${o===1?"input":"inputs"} before the safe replay window expired, so it did not send ${o===1?"it":"them"} again.`,ready:t.notifyImmediately===!0}),t.notifyImmediately===!0&&Zy(e)),!0}function AI(e){return e.type==="terminal_protocol"&&typeof e.inputAck=="boolean"&&typeof e.instanceId=="string"&&e.instanceId.length>0&&e.instanceId.length<=128}function LI(e,t,n,s,o){if(e.socket!==t||e.inputProtocolMode!=="unknown")return;if(!s){b2(e,t);return}Ws(e);const l=e.serverInstanceId;e.inputProtocolMode=o?"receipt-ack":"ack",e.serverInstanceId=n,l===n?(MI(e),jI(e,t)):l!==null&&(y2(e),w2(e)),Uo(e,t)}function b2(e,t){if(!(e.socket!==t||e.inputProtocolMode!=="unknown")){e.inputProtocolMode="legacy",Ws(e),e.serverInstanceId=null,y2(e),w2(e);for(const n of e.pendingOut){if(n.message.type!=="input"||!n.message.messageId)continue;Wl(e,n);const{messageId:s,...o}=n.message;n.message=o,n.encoded=JSON.stringify(o);const l=Ia(n.encoded);e.pendingOutBytes+=l-n.bytes,n.bytes=l}Uo(e,t)}}function y2(e){const t=new Set;let n=0;for(const[s,o]of e.unackedInputs)o.sentInstanceId!==null&&(t.add(s),o.durable&&(n+=1));if(t.size!==0){e.pendingOut=e.pendingOut.filter(s=>{const o=s.message.type==="input"?s.message.messageId:void 0;return!o||!t.has(o)?!0:(e.pendingOutBytes=Math.max(0,e.pendingOutBytes-s.bytes),!1)});for(const s of t){const o=e.unackedInputs.get(s);o&&Wl(e,o)}n>0&&S2(e,{message:`The terminal server restarted before ${n} ${n===1?"input was":"inputs were"} acknowledged. NTerminal did not resend ${n===1?"it":"them"} to avoid running input twice.`,ready:!1})}}function S2(e,t){e.pendingNotices.push(t),e.pendingNotices.length>8&&e.pendingNotices.splice(0,e.pendingNotices.length-8)}function Zy(e){if(e.listeners.size===0)return;const t=e.pendingNotices.filter(n=>n.ready);if(t.length!==0){e.pendingNotices=e.pendingNotices.filter(n=>!n.ready);for(const n of t)jl(e,{type:"message",message:{type:"error",message:n.message}})}}function Jf(e){$o(e),hs(e),Ws(e),Fo(e),e.pendingOut.length=0,e.pendingOutBytes=0,e.unackedInputs.clear(),e.unackedInputBytes=0,e.pendingAckReceipts.clear()}function Eb(e,t,n){if(!(e.socket!==t||t.readyState!==WebSocket.OPEN||!Qy(e.inputProtocolMode)||e.serverInstanceId!==n.instanceId))try{t.send(n.encoded)}catch{t.close()}}function Qy(e){return e==="ack"||e==="receipt-ack"}function jI(e,t){for(const n of e.pendingAckReceipts.values())if(Eb(e,t,n),e.socket!==t||t.readyState!==WebSocket.OPEN)return}function OI(e,t){e.pendingAckReceipts.get(t.messageId)?.terminalId===t.terminalId&&e.pendingAckReceipts.delete(t.messageId)}function w2(e){e.pendingAckReceipts.clear()}function BI(e,t){if(e.outboundFlushTimer!==null)return;const n=e.outboundFlushDelayMs;e.outboundFlushDelayMs=Math.min(G4,n*2),e.outboundFlushTimer=window.setTimeout(()=>{e.outboundFlushTimer=null,Uo(e,t)},n)}function Ia(e){return eI.encode(e).byteLength}function II(e,t){if(Ia(e)<=t)return e;let n=0,s=e.length;for(;n<s;){const o=Math.floor((n+s)/2);Ia(e.slice(o))<=t?s=o:n=o+1}return n>0&&n<e.length&&e.charCodeAt(n)>=56320&&e.charCodeAt(n)<=57343&&(n+=1),e.slice(n)}const PI=[0,50,150,350],Iv=[100,300,750],bC=800,zI=[150,500],HI=2,UI=[300,1200,2500],$I=1e3,FI=1e5,WI="",KI=400,Pv=9,qI=9,VI=32,YI=1.42,GI=2,XI=24,ZI=720,QI=60,JI=1260,e6=6,t6=2,yC=[500,1500,3e3,5e3,8e3],SC=15e3,n6=2,i6=1e3,wC="Do not take action. Wait for my next input.",Lp=6e4,r6=Lp+5*6e4,xC=Lp+6e4,s6=40,Lf=240,a6=5e3,jp=new Map,Ic=new Map;function CC({terminal:e,serverApi:t,active:n,visible:s=!0,canClose:o,refreshCwdOnEnter:l=!1,tabId:d,codeServerContext:f,onSelect:m,onClose:p,onExit:b,onSnapshot:_,onAuthClose:S}){const w=v.useSyncExternalStore(kT,g_,()=>Ml),x=v.useSyncExternalStore(TT,v_,()=>Zc),R=v.useSyncExternalStore(DT,S_,()=>!0),L=v.useSyncExternalStore(_d,w_,()=>!0),A=v.useSyncExternalStore(_d,x_,()=>!0),W=v.useSyncExternalStore(_d,y_,()=>Kd),H=v.useSyncExternalStore(ny,Bo,()=>Xc),U=v.useSyncExternalStore(Bd,()=>Id("history.toggle"),()=>"Alt+H"),q=v.useSyncExternalStore(Bd,()=>Id("scrollback.toggle"),()=>"Alt+S"),Y=v.useSyncExternalStore(Bd,()=>Id("subagents.toggle"),()=>"Alt+A"),I=v.useRef(null),F=v.useRef(null),de=v.useRef(null),me=v.useRef(null),K=v.useRef(null),te=v.useRef(e.id),J=v.useRef({onExit:b,onSnapshot:_}),Q=v.useRef(t.createWebSocketUrl),X=v.useRef(S),M=v.useRef(null),T=v.useRef(!1),O=v.useRef(null),re=v.useRef(null),he=v.useRef(!1),N=v.useRef(new Map),V=v.useRef(new Map),se=v.useRef(new Set),Z=v.useRef(null),Ee=v.useRef(!1),ye=v.useRef(null),ze=v.useRef(null),Ke=v.useRef(!1),Be=v.useRef(null),ve=v.useRef(0),Fe=v.useRef(0),Ie=v.useRef([]),j=v.useRef(!1),ge=v.useRef(null),Ae=v.useRef(0),Oe=v.useRef(!1),z=v.useRef(!1),fe=v.useRef(e.scrollbackMode),Te=v.useRef({codex:!1,speed:W}),Ne=v.useRef(null),Le=v.useRef(new nC),be=v.useRef(!1),$e=v.useRef({terminalId:e.id,enabled:!1}),qe=v.useRef([]),je=v.useRef([]),ht=v.useRef(0),st=v.useRef(!1),mt=v.useRef(null),xt=v.useRef(0),on=v.useRef(0),ot=v.useRef(null),Dn=v.useRef(null),Tn=v.useRef(!1),ft=v.useRef(!1),Dt=v.useRef(!1),Mt=v.useRef(null),wi=v.useRef(!1),di=v.useRef(null),xi=v.useRef(null),At=v.useRef(!1),ae=v.useRef(!1),Pe=v.useRef(!1),tt=v.useRef(!1),_t=v.useRef(Number.NEGATIVE_INFINITY),$t=v.useRef(Number.NEGATIVE_INFINITY),en=v.useRef(!1),Ft=v.useRef(!1),mn=v.useRef(new Set),Bn=v.useRef(new Set),Ct=v.useRef(!1),ln=v.useRef(!1),cn=v.useRef(!1),Kn=v.useRef(!1),In=v.useRef(n),rt=v.useRef(s),Tt=v.useRef(l),gn=v.useRef(w),oe=v.useRef(x),ke=v.useRef(!1),Ge=v.useRef(!1),Je=v.useRef(null),Ze=v.useRef(null),tn=v.useRef(0),Sn=v.useRef(0),Gi=v.useRef(e.id),Xt=v.useRef(()=>{}),Xi=v.useRef(null),qn=v.useRef(null),Mn=v.useRef(!1),Ri=v.useRef({key:null,warnedFiveMinutes:!1,warnedOneMinute:!1,sent:!1,skipped:!1}),Zi=v.useRef(0),Wt=v.useRef(null),Ks=v.useRef(0),dr=v.useRef(null),Qi=v.useRef(!1),Ni=v.useRef(null),Yl=v.useRef(0),Ha=v.useRef(!1),qs=v.useRef(!1),hi=v.useRef(null),zi=v.useRef(null),[Vs,ni]=v.useState("connecting"),[Pn,Ys]=v.useState(null),gs=v.useRef(null),Gs=v.useRef(null),Ua=v.useRef(()=>!1),Di=v.useRef(null);Di.current||(Di.current=new A4({getTarget:()=>gs.current,send:k=>Ua.current(k),onState:Ys}));const[Gl,ii]=v.useState(!1),[vs,Ko]=v.useState(null),[Xs,hr]=v.useState(!1),[$a,Zs]=v.useState(null),[_s,Xl]=v.useState(!1),[Zl,qo]=v.useState(!1),[Vo,Hi]=v.useState(!1),[Yo,ts]=v.useState(!1),[Mi,Dr]=v.useState(!1),[pn,Mr]=v.useState(null),[Ar,Fa]=v.useState([]),ns=v.useRef([]),Ai=e.agentCache&&pn&&e.agentCache.source.provider===pn.provider&&e.agentCache.source.sessionId===pn.sessionId?e.agentCache:null,[is,fr]=v.useState(()=>Date.now()),[Lr,rs]=v.useState(!1),[jr,Qs]=v.useState(null),[bs,Js]=v.useState(!1),[ys,Ji]=v.useState(!1),[Ui,un]=v.useState(null),[pr,pt]=v.useState(!1),[Or,Ss]=v.useState(!1),[Wa,mr]=v.useState(null),[ws,ea]=v.useState(null),[Go,Ql]=v.useState(!1),Br=f?.serverKey.trim()||(t.isAgent?"agent":"local"),[cu,ta]=v.useState(()=>av(e.id)),gr=pn?.provider??e.agentStatus?.provider??null,Jl=El(e.currentCommand)||NC(e.currentCommand)&&gr!==null,Xo=e.agentStatus?.sessionId??pn?.sessionId??null,na=gr!==null||El(e.currentCommand),Zo=gr==="claude"||Db(e.currentCommand),vr=gr!==null||El(e.currentCommand),ss=e.capabilities?.tmuxScrollback===!0,fi=ss&&(cu??(vr?A:L)),[Qo,Ka]=v.useState(!1);v.useLayoutEffect(()=>{Ua.current=k=>Hn(k,{liveOnly:!0})==="sent"}),v.useLayoutEffect(()=>(Gs.current=null,gs.current=n&&s&&e.status==="running"?{api:t,terminalId:e.id,supportsImages:Jl}:null,()=>{gs.current=null,Di.current?.cancel()}),[t,e.id,e.pid,e.status,e.currentCommand,Jl,n,s,Vs]),v.useLayoutEffect(()=>{const k=gs.current;if(!k||Xo===null)return;const P=Gs.current;Gs.current=Xo,P!==null&&P!==Xo&&(gs.current={...k},Di.current?.pending&&Di.current.cancel("Image paste canceled because the active session changed."))}),v.useLayoutEffect(()=>{(!n||!s||!Qo||e.status!=="running")&&$i(!1)},[n,s,Qo,e.status]),v.useLayoutEffect(()=>{In.current=n},[n]),v.useLayoutEffect(()=>{rt.current=s},[s]),v.useLayoutEffect(()=>{Tt.current=l},[l]),v.useLayoutEffect(()=>{gn.current=w},[w]),v.useLayoutEffect(()=>{oe.current=x},[x]),v.useLayoutEffect(()=>{ke.current=bs},[bs]),v.useLayoutEffect(()=>{Ge.current=ys},[ys]),v.useLayoutEffect(()=>{Ze.current=pn},[pn]);const as=v.useCallback((k,P={})=>{!k&&P.preserveOnNull||(Zx(Ze.current,k)||(Sn.current+=1),Ze.current=k,Mr(xe=>xe&&k&&xe.provider===k.provider&&xe.sessionId===k.sessionId?xe:k))},[]),ec=v.useCallback(async()=>{const k=await t.getTerminalTranscriptSource(e.id);return Gi.current===e.id&&(ns.current=k.candidates??[],Fa(k.candidates??[])),k.source},[t,e.id]),ia=v.useCallback(()=>{Ji(!1),Js(!0)},[]),Jo=v.useCallback(()=>{Ze.current&&(Js(!1),Ji(!0))},[]),xs=v.useCallback(async(k={})=>{const P=await TC(Br,t,k);return un(P),P},[Br,t]),Ir=v.useCallback((k,P="info")=>{dr.current!==null&&window.clearTimeout(dr.current),ea({id:Ks.current++,message:k,tone:P}),dr.current=window.setTimeout(()=>{ea(null),dr.current=null},3200)},[]),tc=v.useCallback(()=>{if(Qi.current)return;Qi.current=!0;const k=Br,P=f?.serverName.trim()||"Local",xe=f?.tabName.trim()||e.title||"Terminal",Xe=Ni.current,et=Xe?.terminalId===e.id&&Xe.requestedCwd===e.cwd?Xe.instance:Ui?.instances.find(ut=>ut.cwd===e.cwd),ct=et?EC(k,et.id):null,{handle:Ht,ownsPopup:Lt}=o6(ct);Lt&&h6(Ht);const nt=()=>{Lt&&f6(Ht)};Ss(!0),mr(null),(async()=>{let ut=Ui;if(ut?.installed||(ut=await xs({force:!0})),!ut?.installed||ut.supported===!1){nt(),pt(!0);return}return t.openCodeServer({terminalId:e.id,serverName:P,tabName:xe})})().then(ut=>{if(!ut)return;Ni.current={terminalId:e.id,requestedCwd:e.cwd,instance:ut.instance},Rb(Br,ut.status),un(ut.status);const Ut=EC(k,ut.instance.id),hn=x2(Ut);if(hn?.createdAt===ut.instance.createdAt&&c6(hn.handle,ut.instance.url)){eS(hn.handle),Ht!==hn.handle&&nt(),Ir("VS Code is already open. If your browser stayed here, check the existing VS Code tab.");return}const Oi=hn?.handle??(Lt||ct===Ut?Ht:null);if(d6(Oi,Ut,ut.url,ut.instance.createdAt))Ht!==Oi&&nt(),Ir("Opening VS Code...");else{const Fi=u6(Ut,ut.url,ut.instance.createdAt);Ht!==Fi&&nt(),Fi?Ir("Opening VS Code..."):Ir("Your browser blocked the VS Code tab. Allow pop-ups for this site and try again.","warning")}}).catch(async ut=>{nt(),ut instanceof Wn&&ut.message==="code_server_not_installed"&&await xs({force:!0}).catch(()=>{}),pt(!0),mr(jf(ut))}).finally(()=>{Qi.current=!1,Ss(!1)})},[f?.serverName,f?.tabName,Br,Ui,xs,t,Ir,e.cwd,e.id,e.title]);v.useEffect(()=>{let k=!1;return TC(Br,t).then(P=>{k||un(P)}).catch(()=>{}),()=>{k=!0}},[Br,t]),v.useEffect(()=>{if(Ui?.job?.status!=="running")return;const k=window.setInterval(()=>{xs({force:!0}).catch(P=>mr(jf(P)))},1e3);return()=>window.clearInterval(k)},[Ui?.job?.status,xs]),v.useEffect(()=>()=>{dr.current!==null&&window.clearTimeout(dr.current)},[]),v.useLayoutEffect(()=>{Xt.current=ia},[ia]),v.useLayoutEffect(()=>{qn.current=Ai},[Ai]),v.useLayoutEffect(()=>{Mn.current=Lr},[Lr]),v.useLayoutEffect(()=>{Ha.current=na},[na]),v.useLayoutEffect(()=>{qs.current=Zo},[Zo]),v.useLayoutEffect(()=>{const k=$e.current;z.current=fi,be.current=ss,$e.current={terminalId:e.id,enabled:fi},DC(I.current,fi);const P=Le.current.setMouseEnabled(fi);P&&F.current?.write(P),k.terminalId===e.id&&k.enabled&&!fi&&lc(),fi||Hi(!1)},[e.id,fi,ss]),v.useLayoutEffect(()=>{fe.current=e.scrollbackMode,e.scrollbackMode&&Hi(e.scrollbackMode==="copy")},[e.id,e.scrollbackMode]),v.useLayoutEffect(()=>{Te.current={codex:!Db(e.currentCommand)&&(gr==="codex"||Nb(e.currentCommand)),speed:W}},[gr,e.currentCommand,W]),v.useEffect(()=>{ta(av(e.id)),Ae.current=0,Oe.current=!1,Hi(!1),ca()},[e.id]),v.useEffect(()=>_d(()=>{ta(av(e.id))}),[e.id]),v.useEffect(()=>()=>{Tu()},[]),v.useEffect(()=>{K.current?.(s&&e.status==="running"),s&&e.status==="running"?B():ie()},[s,e.id,e.status]),v.useEffect(()=>{s&&n&&e.status==="running"&&$r("auto")},[n,s,e.status]),v.useEffect(()=>{J.current={onExit:b,onSnapshot:_}},[b,_]),v.useLayoutEffect(()=>{Q.current=t.createWebSocketUrl,X.current=S},[t,S]),v.useLayoutEffect(()=>{te.current=e.id,cn.current=!1,ts(!1),$i(!1)},[e.id]),v.useEffect(()=>{let k=!1,P=null,xe=0;const Xe=e.agentStatus?.provider==="codex"||e.agentStatus?.provider==="claude",et=Xe||NC(e.currentCommand),ct=Xe||El(e.currentCommand);function Ht(){P!==null&&(window.clearTimeout(P),P=null)}function Lt(ut){if(k)return;let Ut;if(ut)Ut=SC;else if(xe<yC.length){if(!et)return;Ut=yC[xe++]}else{if(!ct)return;Ut=SC}P=window.setTimeout(()=>{P=null,nt()},Ut)}async function nt(){try{const ut=Ze.current!==null,Ut=await ec();if(k)return;if(Ut){tn.current=0,as(Ut),Lt(!0);return}tn.current+=1;const hn=!!(ut&&et&&tn.current<n6);as(null,{preserveOnNull:hn}),Lt(hn)}catch(ut){if(k)return;Hv(ut)&&as(null),Lt(!1)}}return Gi.current!==e.id&&(ns.current=[],Fa([]),Gi.current=e.id,Sn.current+=1,Ze.current=null,tn.current=0,Mr(null)),e.status!=="running"?(Sn.current+=1,Ze.current=null,tn.current=0,Mr(null),()=>{k=!0,Ht()}):(nt(),()=>{k=!0,Ht()})},[as,ec,t,e.agentStatus?.provider,e.currentCommand,e.id,e.status]),v.useEffect(()=>{const k=g6(e.id,pn),P=Xi.current;P!==null&&k!==null&&P!==k&&(Dn.current=null,Tn.current=!1,ft.current=!1,Ji(!1)),Xi.current=k},[e.id,pn?.provider,pn?.sessionId]),v.useEffect(()=>{if(e.status!=="running"||!pn){rs(!1);return}const k=window.setInterval(()=>{fr(Date.now())},i6);return()=>{window.clearInterval(k)}},[e.status,pn?.provider,pn?.sessionId]),v.useEffect(()=>{const k=m6(Ai);Ri.current.key!==k&&(Ri.current={key:k,warnedFiveMinutes:!1,warnedOneMinute:!1,sent:!1,skipped:!1})},[Ai?.expiresAt,Ai?.source?.provider,Ai?.source?.sessionId]),v.useEffect(()=>{if(!Lr||!Ai||Ai.status!=="ready")return;const k=k2(Ai,is);if(k===null||k<=0)return;const P=Ri.current;!P.warnedFiveMinutes&&k<=r6&&k>xC&&(P.warnedFiveMinutes=!0,zn({tone:"info",message:"Cache keep-alive will be sent in 5m",detail:"Use Skip once or Turn off if you do not want NTerminal to send a short idle prompt."})),!P.warnedOneMinute&&k<=xC&&k>Lp&&(P.warnedOneMinute=!0,zn({tone:"warning",message:"Cache keep-alive will be sent in 1m",detail:"NTerminal will only send it if this pane is idle."})),!P.sent&&!P.skipped&&k<=Lp&&ul()},[Lr,is,Ai,e.activity,e.agentStatus?.state,e.status]),v.useEffect(()=>{function k(P){if(!In.current||!rt.current||P.isComposing||P.key==="Process"||b6(P.target))return;const xe=jT(P);if(xe?.id==="history.toggle"&&(Ze.current||ns.current.length)){P.preventDefault(),P.stopPropagation(),ke.current?Js(!1):Xt.current();return}if(xe?.id==="subagents.toggle"&&Ze.current){P.preventDefault(),P.stopPropagation(),Ge.current?Ji(!1):Jo();return}if(xe?.id==="scrollback.toggle"&&be.current){P.preventDefault(),P.stopPropagation(),Cu();return}}return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[]),v.useEffect(()=>{const k=F.current;k&&(k.options.disableStdin=e.status==="exited"),e.status==="exited"&&ni("closed")},[e.status]),v.useEffect(()=>{const k=F.current;k&&(k.options.fontSize=w,sv(w,oe.current).then(()=>{gn.current===w&&pi()}))},[w]),v.useEffect(()=>{const k=F.current;k&&(k.options.fontFamily=m_(x),sv(gn.current,x).then(()=>{oe.current===x&&pi()}))},[x]),v.useEffect(()=>{const k=F.current;k&&(k.options.theme=kC(H))},[H]),v.useEffect(()=>{const k=I.current;if(!k)return;let P=!1,xe=null,Xe=null,et=null,ct=null,Ht=null,Lt=null,nt=null,ut=null,Ut=null,hn=null,Oi=null;M.current=null,_t.current=Number.NEGATIVE_INFINITY,$t.current=Number.NEGATIVE_INFINITY,en.current=!1,yu(),Ct.current=!1,ln.current=!1,wi.current=!1,bh(),yh(),Ee.current=!1,Ke.current=!1,ve.current=0,Fe.current=0,tl(),j.current=!1;const Fi=gn.current,hl=oe.current,_n=new zB({cursorBlink:!0,convertEol:!1,disableStdin:e.status==="exited",fontFamily:m_(hl),fontSize:Fi,fontWeight:400,fontWeightBold:700,macOptionClickForcesSelection:!0,scrollback:FI,theme:{...kC(Bo())}}),Yn=new Dj;return _n.loadAddon(Yn),Ht=O4(_n),F.current=_n,de.current=Yn,sv(Fi,hl).then(()=>{if(P)return;_n.open(k),DC(k,z.current),Ct.current=!0,ct=_n.onRender(()=>{const Gn=Z.current;Gn!==null&&(Z.current=null,sl("painted",{elapsedMs:Date.now()-Gn}))}),xe=S4(_n,{onPasteText:xh,onPasteFiles:Gn=>{Di.current?.paste(Gn)},canPaste:()=>gs.current!==null,onInterrupt:os,shouldInterruptPlainCtrlC:()=>qs.current}),rt.current&&In.current&&e.status==="running"&&$r("auto"),pi();const ua=()=>{T.current&&du()};k.addEventListener("pointerdown",ua,{capture:!0,passive:!0}),k.addEventListener("keydown",ua,{capture:!0}),Ut=()=>{k.removeEventListener("pointerdown",ua,{capture:!0}),k.removeEventListener("keydown",ua,{capture:!0})},ut=H6(k,{markIntent:la,markKeyboardIntent:mu,setPointerScrollActive:Gn=>{en.current=Gn}}),Lt=V6(k,_n,()=>gn.current*1.2,Pr,Gn=>{_r(Gn)},ji,Es,()=>z.current,xu,yr,Ur),nt=W6(k,_n,Pr,Gn=>{_r(Gn)},ji,Es,()=>z.current,xu);const Ch=new m5;Xe=_n.onData(Gn=>{if(y5(Gn)){Ms(Gn);return}if(cn.current){const Th=w5(Gn);if(Th){Et(!1),Hn(Th);return}}const kh=Ch.accept(Gn);kh&&Hn(kh)}),et=_n.onScroll(Gn=>{if(ae.current||tt.current||Pe.current){Vn();return}if(z.current){if(!Ts()){bu(_n);return}}else if(!gu()){if(!At.current||Yr(_n)){At.current=!1,bu(_n);return}Vn(),Gn<=3&&_r();return}fu(),Yr(_n)&&tr({scrollToBottom:!0}),Pr(),!z.current&&Gn<=3&&_r()}),hn=_n.onResize(()=>{Su(vu(_n))}),Oi=new ResizeObserver(()=>{We()}),Oi.observe(k),ln.current&&(nc(),ln.current=!1,pi()),il()}),()=>{Ds(me.current,{updateUi:!1}),P=!0,Ct.current=!1,ln.current=!1,bh(),yh(),ie(),Be.current!==null&&window.clearTimeout(Be.current),Be.current=null,Ke.current=!1,O.current=null,re.current=null,he.current=!1,Li(),j.current=!1,hu(),Pe.current=!1,st.current=!1,xt.current+=1,on.current+=1,mt.current=null,hi.current=null,zi.current=null,Dt.current=!1,Mt.current=null,ii(!1),Lt?.(),nt?.(),ut?.(),Ut?.(),hn?.dispose(),yu(),en.current=!1,Oi?.disconnect(),xe?.dispose(),Xe?.dispose(),et?.dispose(),ct?.dispose(),Ht?.dispose(),_n.dispose(),F.current=null,de.current=null}},[e.id]),v.useEffect(()=>{const k=Q.current(e.id),P=nI(k,el,e);return me.current=P.send,K.current=P.setForeground,P.setForeground(rt.current&&e.status==="running"),ni(P.status),P.status==="connected"&&pi(),P.snapshot&&(Ee.current=P.snapshot.capabilities?.screenRedraw===!0,J.current.onSnapshot(P.snapshot,{notifyCompletion:!1}),F.current&&(pi(),qa(P.output,P.history),pi())),()=>{Ds(P.send,{updateUi:!1}),P.setForeground(!1),P.detach(),me.current=null,K.current=null}},[e.id,e.status]);function el(k){if(k.type==="resume"){B();return}if(k.type==="status"){ni(k.status),k.status==="unauthorized"&&X.current?.({source:"terminal-ws-1008",terminalId:e.id}),k.status==="connected"&&(pi(),rl());return}if(k.type==="upgrade_rejected"){X.current?.({source:"terminal-ws-upgrade-rejected",terminalId:e.id});return}if(k.type==="outbound_flushed"){Ga(),j.current&&(j.current=!1,uc());return}we(k.message)}function tl(k=[],P=null){qe.current=[],je.current=k.filter(Boolean),ht.current=0,st.current=!1,mt.current=null,Pe.current=!1,xt.current+=1,ot.current=P,Dn.current=null,Tn.current=!1,ft.current=!1,Dt.current=!1,Mt.current=null,ln.current=!1,hi.current=null,zi.current=null,di.current=null,At.current=!1,ii(!1),Ko(null),hr(!1),Zs(null),Xl(!1),qo(!1)}function qa(k=[],P=null){if(Pe.current||st.current){zi.current={output:k,history:P,appendFromLiveOutputIndex:je.current.length};return}tl(k,P),Va()}function er(){if(Pe.current||st.current)return!1;const k=zi.current;if(!k)return!1;const P=je.current.slice(k.appendFromLiveOutputIndex);return zi.current=null,tl([...k.output,...P],k.history),Va(),!0}function Va(){if(!F.current||!Ct.current){ln.current=!0;return}ln.current=!1,nc()}async function nc(){const k=F.current;if(!k)return;const P=oa(k),xe=P?je.current.length:ht.current,Xe=await ra(k,{liveOutputLimit:xe,scrollToBottom:P});F.current===k&&(Vn(),Xe&&(Ke.current=!0,ve.current=0,Ga(),rl()))}function ra(k,P={}){return new Promise(xe=>{Pe.current=!0,st.current=!1;const Xe=xt.current+1;xt.current=Xe;const et=Math.max(0,Math.min(P.liveOutputLimit??je.current.length,je.current.length)),ct=P.historyPages??qe.current,Ht=()=>F.current===k&&xt.current===Xe,Lt=()=>Ht()&&(P.isCurrent?.()??!0),nt=()=>{Ht()&&(Pe.current=!1),xe(!1)},ut=()=>{if(!Lt()){nt();return}try{ht.current=et,P.scrollToBottom&&Rs(k)}finally{if(Pe.current=!1,er()){xe(!1);return}const hn=sa();hn?tr(hn):P.applyDeferredSnapshot!==!1&&Xa(),xe(!0)}};(()=>{if(!Lt()){nt();return}k.clear(),Le.current=new nC(z.current);const hn=[...ct,...je.current.slice(0,et)].filter(Boolean);if(hn.length===0){ut();return}for(let Oi=0;Oi<hn.length;Oi+=1){const Fi=ac(hn[Oi]);Oi===hn.length-1?k.write(Fi,ut):k.write(Fi)}})()})}async function _r(k=0){const P=F.current;if(Dt.current||!P||P.buffer.active.type==="alternate")return;if(aa(P)){Vn();return}const xe=ot.current,Xe=on.current,et=Symbol("history-load"),ct=()=>F.current===P&&on.current===Xe;Mt.current=et,Dt.current=!0,ii(!0);const Ht=P.buffer.active.viewportY;try{let Lt=!!(xe&&!xe.hasMore);if(!Lt)try{const nt=await t.getTerminalHistory(e.id,{beforeLine:xe?.startLine??0,...xe?.snapshotHistorySize!==void 0?{snapshotHistorySize:xe.snapshotHistorySize}:{},...xe?.snapshotHistoryLimit!==void 0?{snapshotHistoryLimit:xe.snapshotHistoryLimit}:{},...xe?.snapshotHistoryToken!==void 0?{snapshotHistoryToken:xe.snapshotHistoryToken}:{},...xe?.snapshotPaneWidth!==void 0?{snapshotPaneWidth:xe.snapshotPaneWidth}:{},limit:$I});if(!ct()||ot.current!==xe)return;const ut=()=>ct()&&ot.current===xe;if(nt.invalidated){ee();return}const Ut=nt.hasMore&&nt.snapshotHistorySize!==void 0&&nt.snapshotPaneWidth!==void 0,hn={startLine:nt.startLine,endLine:nt.endLine,hasMore:Ut,...nt.snapshotHistorySize!==void 0?{snapshotHistorySize:nt.snapshotHistorySize}:{},...nt.snapshotHistoryLimit!==void 0?{snapshotHistoryLimit:nt.snapshotHistoryLimit}:{},...nt.snapshotHistoryToken!==void 0?{snapshotHistoryToken:nt.snapshotHistoryToken}:{},...nt.snapshotPaneWidth!==void 0?{snapshotPaneWidth:nt.snapshotPaneWidth}:{}};if(nt.output.length>0){await E(P,nt.output,Ht,k)&&ut()&&(ot.current=hn);return}if(!ut())return;ot.current=hn,Lt=!Ut}catch(nt){Lt=ct()&&Hv(nt)}if(Lt){if(!ct()||aa(P)){Vn();return}await C(P,Ht,k,ct)}}catch{}finally{Mt.current===et&&(Mt.current=null,Dt.current=!1,ii(!1))}}async function C(k,P,xe,Xe){if(!Xe()||Tn.current||ft.current)return;const et=Ze.current,ct=Sn.current,Ht=Dn.current,Lt=()=>Xe()&&Sn.current===ct&&Zx(et,Ze.current)&&Dn.current===Ht;try{const nt=await t.getTerminalTranscriptHistory(e.id,{...Ht?{cursor:Ht}:{},limit:KI}),ut=nt.output.map(Wy);if(!nt.source||nt.terminalId!==e.id||!Lt())return;if(et&&!Aa(et,nt.source)){Dn.current=null,Tn.current=!1,ft.current=!1,as(nt.source);return}if(ut.length===0){as(nt.source),Dn.current=nt.cursor,ft.current=!nt.hasMore||!nt.cursor;return}await E(k,ut,P,xe,Lt)&&Lt()&&(as(nt.source),Dn.current=nt.cursor,ft.current=!nt.hasMore||!nt.cursor)}catch(nt){Lt()&&Hv(nt)&&(Tn.current=!0)}}async function E(k,P,xe,Xe,et){if(aa(k)||et&&!et())return Vn(),!1;const ct=qe.current,Ht=[...P,...ct],Lt=B6(P),nt=xt.current+1,ut=await ra(k,{liveOutputLimit:ht.current,scrollToBottom:!1,historyPages:Ht,applyDeferredSnapshot:!1,...et?{isCurrent:et}:{}}),Ut=et!==void 0&&!et();return!ut||Ut||F.current!==k?(Ut&&F.current===k&&xt.current===nt&&await ra(k,{liveOutputLimit:ht.current,scrollToBottom:!1,historyPages:ct,applyDeferredSnapshot:!1})&&F.current===k&&(ll(k,xe),At.current=!Yr(k),Pr()),!1):(qe.current=Ht,ll(k,Math.max(0,xe+Lt+Math.min(0,Xe))),At.current=!Yr(k),Pr(),!0)}v.useEffect(()=>{const k=window.visualViewport;function P(){document.visibilityState!=="hidden"?B():ie()}function xe(){B()}function Xe(){B()}function et(){We()}function ct(){Vt()}return document.addEventListener("visibilitychange",P),document.addEventListener("resume",xe),window.addEventListener("pageshow",xe),window.addEventListener("focus",xe),window.addEventListener("online",Xe),window.addEventListener("resize",et),window.addEventListener(Ep,ct),k?.addEventListener("resize",et),k?.addEventListener("scroll",et),()=>{document.removeEventListener("visibilitychange",P),document.removeEventListener("resume",xe),window.removeEventListener("pageshow",xe),window.removeEventListener("focus",xe),window.removeEventListener("online",Xe),window.removeEventListener("resize",et),window.removeEventListener(Ep,ct),k?.removeEventListener("resize",et),k?.removeEventListener("scroll",et)}},[e.id]);function B(){if(document.visibilityState==="hidden"||!rt.current)return;rl(),T.current?du():We();const k=F.current;k&&Ct.current&&Su(vu(k)),Ga()}function ee(){if(ye.current)return;const k=Q.current(e.id);if(ye.current={requestId:z6(),startedAt:Date.now(),snapshotReady:!1,sent:!1},Ql(!0),ca(),Ae.current=0,on.current+=1,wi.current=!0,hi.current=null,ni("reconnecting"),pi(),!iI(k)){ie("Could not reconnect this pane. Try reloading again.");return}ze.current=window.setInterval(le,100)}function ie(k){ye.current=null,ze.current!==null&&window.clearInterval(ze.current),ze.current=null,Ql(!1),k&&Ir(k,"error")}function le(){const k=ye.current;if(!k)return;if(!rt.current||document.visibilityState==="hidden"){ie();return}if(Date.now()-k.startedAt>=15e3){ie("Pane recovery timed out. Check the connection and try again.");return}const P=F.current;k.sent||!k.snapshotReady||!P||!Ct.current||N.current.size>0||Pe.current||hi.current||zi.current||(k.sent=Qa({type:"restore_screen",terminalId:e.id,requestId:k.requestId,cols:P.cols,rows:P.rows},{durability:"live-only"})==="sent")}function we(k){if(k.type==="snapshot"&&k.terminal.id===e.id){Ee.current=k.terminal.capabilities?.screenRedraw===!0;const xe=ye.current;xe&&(k.terminal.capabilities?.screenRestore===!0?(xe.snapshotReady=!0,xe.sent=!1):ie("This server does not support live-screen recovery. Update the server and try again.")),on.current+=1,J.current.onSnapshot(k.terminal,{notifyCompletion:!1});const Xe=wi.current;wi.current=!1;const et=F.current;if(!et)return;if(pi(),Xe){Ue(k.output,k.history??null);return}if(pu(et,k.terminal)){br(k.output,k.history??null),Vn(),pi();return}qa(k.output,k.history??null),pi();return}if(k.type==="restore_screen_result"&&k.terminalId===e.id){if(ye.current?.requestId!==k.requestId)return;k.ok&&(Oe.current=!1,Hi(!1),At.current=!1,Ke.current=!1,Fe.current=Date.now(),tr({force:!0,scrollToBottom:!0}),rl()),ie(k.ok?void 0:"Could not restore the live pane screen. Try reloading again.");return}if(k.type==="redraw_result"&&k.terminalId===e.id){sl("redraw_result",{ok:k.ok});return}if(k.type==="terminal_updated"&&k.terminal.id===e.id){J.current.onSnapshot(k.terminal,{notifyCompletion:!0});const xe=M.current;xe&&(k.terminal.cols!==xe.cols||k.terminal.rows!==xe.rows)&&(T.current=!0);return}if(k.type==="output"&&k.terminalId===e.id){const xe=k.data;if(!xe)return;je.current.push(xe),F.current&&Ct.current?tr({scrollToBottom:!0}):ln.current=!0;return}const P=F.current;if(P){if(k.type==="exit"&&k.terminalId===e.id){J.current.onExit(k.exitCode),ni("closed");return}k.type==="error"&&P.writeln(`\r
52
+ [nterminal] ${k.message}`)}}function Ue(k,P){qa(k,P),pi()}function Ye(k=25){if(document.visibilityState==="hidden"||!rt.current||N.current.has(k))return;const P=window.setTimeout(()=>{N.current.delete(k),!St()&&Za()},k);N.current.set(k,P)}function We(){St()||il()}function St(){const k=Cs();return k&&Bt(k)?(he.current=!0,re.current=k,!0):k&&vn(k)?(he.current=!1,re.current=null,!0):((!k||!k.composeOpen&&!k.keyboardVisible)&&(he.current=!1,re.current=null),!1)}function Vt(){if(!he.current)return;const k=Cs();k&&(k.composeOpen||k.keyboardVisible)||(he.current=!1,re.current=null)}function Bt(k){if(!k.mobileLike||!k.composeOpen&&!k.keyboardVisible)return!1;const P=O.current;return P?ks(k.windowWidth,P.windowWidth)&&ks(k.visualViewportWidth,P.visualViewportWidth)&&ks(k.containerWidth,P.containerWidth):!1}function vn(k){if(!k.mobileLike||k.composeOpen||k.keyboardVisible)return!1;const P=re.current;return!P||!P.composeOpen&&!P.keyboardVisible?!1:ks(k.windowWidth,P.windowWidth)&&ks(k.visualViewportWidth,P.visualViewportWidth)&&ks(k.containerWidth,P.containerWidth)}function Cs(){const k=I.current;if(!k||k.isConnected===!1)return null;const P=k.getBoundingClientRect(),xe=nl(window.innerWidth)??0,Xe=nl(window.visualViewport?.width)??xe,et=nl(P.width)??nl(k.clientWidth)??xe;if(xe<=0||Xe<=0||et<=0)return null;const{keyboardVisible:ct}=gb(),Ht=document.documentElement.hasAttribute(am),Lt=Ya()||ct;return{windowWidth:xe,visualViewportWidth:Xe,containerWidth:et,composeOpen:Ht,keyboardVisible:ct,mobileLike:Lt}}function Ya(){return navigator.maxTouchPoints>0?!0:typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}function ic(){return gb().keyboardVisible?!0:typeof window.matchMedia=="function"?window.matchMedia("(hover: none) and (pointer: coarse)").matches:navigator.maxTouchPoints>0}function nl(k){return typeof k=="number"&&Number.isFinite(k)&&k>0?k:null}function ks(k,P){return Math.abs(k-P)<=HI}function il(){for(const k of PI)Ye(k)}function du(){if(document.visibilityState==="hidden"||!rt.current)return;if(!St()){pi();return}const k=F.current;if(!k||!Ct.current)return;const P={cols:k.cols,rows:k.rows};Ci({type:"resize",terminalId:e.id,cols:P.cols,rows:P.rows})&&(M.current=P,T.current=!1)}function pi(){T.current=!1,M.current=null,il()}function rl(){if(Z.current===null&&rt.current&&document.visibilityState!=="hidden"&&(Z.current=Date.now(),sl("requested")),rc(),se.current.size===0&&typeof window.requestAnimationFrame=="function"){const k=window.requestAnimationFrame(()=>{se.current.delete(k),rc();const P=window.requestAnimationFrame(()=>{se.current.delete(P),rc()});se.current.add(P)});se.current.add(k)}for(const k of Iv){if(V.current.has(k))continue;const P=window.setTimeout(()=>{V.current.delete(k),rc(),k===Iv[Iv.length-1]&&Z.current!==null&&(sl("timeout",{elapsedMs:Date.now()-Z.current}),Z.current=null)},k);V.current.set(k,P)}}function rc(){const k=F.current;if(!(!k||!Ct.current||document.visibilityState==="hidden"||!rt.current||I.current?.isConnected===!1))try{k.refresh(0,Math.max(0,k.rows-1))}catch{}}function bh(){for(const k of N.current.values())window.clearTimeout(k);N.current.clear()}function yh(){Z.current=null;for(const k of V.current.values())window.clearTimeout(k);V.current.clear();for(const k of se.current)window.cancelAnimationFrame(k);se.current.clear()}function sl(k,P={}){const xe=F.current;dI(Q.current(e.id),k,{visible:rt.current,cols:xe?.cols??0,rows:xe?.rows??0,viewportY:xe?.buffer.active.viewportY??0,baseY:xe?.buffer.active.baseY??0,pendingChunks:je.current.length-ht.current,replaying:Pe.current,tmuxScrollback:z.current,userScrolledAway:At.current,...P})}function Ga(){if(ye.current)return;const k=F.current;if(!Ke.current||!Ee.current||!k||!Ct.current||!rt.current||document.visibilityState==="hidden"||Pe.current||st.current||hi.current||zi.current||!oa(k))return;const P=1100-(Date.now()-Fe.current);if(P>0){Be.current===null&&(Be.current=window.setTimeout(()=>{Be.current=null,Ga()},P));return}Qa({type:"redraw",terminalId:e.id},{durability:"live-only"})==="sent"?(Ke.current=!1,Fe.current=Date.now(),sl("redraw_sent")):Be.current===null&&ve.current<4&&(ve.current+=1,Be.current=window.setTimeout(()=>{Be.current=null,Ga()},250))}function Li(){for(const k of Ie.current)window.clearTimeout(k);Ie.current=[]}function Pr(){if(Vn(),!di.current){hr(!1);return}hr(!0),hu(),xi.current=window.setTimeout(()=>{xi.current=null,hr(!1)},1200)}function Vn(){const k=F.current,P=k?I6(k):null;if(di.current=P,Ko(P),qo(!!(k&&P)),Xl(!!(k&&P&&!Yr(k))),P||!k||!Sh()){Zs(null);return}Zs({alternate:k.buffer.active.type==="alternate"})}function Sh(){const k=ot.current;return qe.current.length>0||!!k?.hasMore}function hu(){xi.current!==null&&(window.clearTimeout(xi.current),xi.current=null)}function fu(){const k=F.current;k&&(At.current=!Yr(k),Vn())}function sc(k){mt.current=Uv(mt.current,k)}function pm(k){const P=mt.current;return mt.current=null,Uv(P,k)}function sa(){const k=mt.current;return mt.current=null,k}function tr(k={}){const P=F.current;if(!P||!Ct.current){ln.current=!0;return}if(hi.current&&!Pe.current&&!st.current&&zr(P)){Xa();return}if(Pe.current){sc(k);return}if(st.current){sc(k);return}const xe=pm(k);if(al(P),!xe.force&&!oa(P)){Vn();return}st.current=!0;const Xe=xt.current,et=()=>{if(F.current!==P||xt.current!==Xe)return;if(al(P),!xe.force&&!oa(P)){if(st.current=!1,er())return;Vn();return}const ct=ht.current,Ht=je.current[ct];if(Ht===void 0){if(st.current=!1,er())return;xe.scrollToBottom&&Rs(P),al(P),Vn();const Lt=sa();Lt?tr(Uv(xe,Lt)):(Xa(),Ga());return}P.write(ac(Ht),()=>{F.current!==P||xt.current!==Xe||(ht.current=ct+1,et())})};et()}function aa(k){return hi.current!==null||!zr(k)&&(ol()||st.current||Pe.current)}function pu(k,P){return(P?.agentStatus?.provider==="codex"||P?.agentStatus?.provider==="claude"||Ha.current||El(P?.currentCommand))&&!zr(k)}function oa(k){return z.current||P6(k,At.current)}function zr(k){return z.current||Yr(k)}function la(){_t.current=performance.now()}function mu(){const k=performance.now();_t.current=k,$t.current=k}function gu(){return en.current||performance.now()-_t.current<=bC}function Ts(){return en.current||performance.now()-$t.current<=bC}function vu(k){return oa(k)}function _u(k){Rs(k),At.current=!1,Vn(),(ol()||hi.current)&&tr({scrollToBottom:!0})}function bu(k){Ft.current||(Ft.current=!0,queueMicrotask(()=>{Ft.current=!1,!(F.current!==k||!Ct.current||Pe.current||tt.current||ae.current)&&((z.current?Ts():At.current||gu())||_u(k))}))}function yu(){for(const k of mn.current)window.cancelAnimationFrame(k);mn.current.clear();for(const k of Bn.current)window.clearTimeout(k);Bn.current.clear()}function Su(k){yu();const P=performance.now(),xe=()=>mm(k,P);if(typeof window.requestAnimationFrame=="function"){const Xe=mn.current,et=window.requestAnimationFrame(()=>{Xe.delete(et),xe();const ct=window.requestAnimationFrame(()=>{Xe.delete(ct),xe()});Xe.add(ct)});Xe.add(et)}for(const Xe of zI){const et=window.setTimeout(()=>{Bn.current.delete(et),xe()},Xe);Bn.current.add(et)}}function mm(k,P){const xe=F.current;if(!(!xe||!Ct.current||Pe.current||tt.current)){if(z.current){if(en.current||$t.current>=P)return}else if(!k||en.current||_t.current>=P)return;Yr(xe)&&!At.current&&!ol()&&!hi.current||_u(xe)}}function al(k){z.current&&(Rs(k),At.current=!1)}function ol(){return ht.current<je.current.length}function ac(k){return Le.current.write(k)}function br(k,P){hi.current={output:k,history:P,appendFromLiveOutputIndex:je.current.length}}function Xa(){const k=F.current,P=hi.current;if(!k||!P||!zr(k)||st.current||Pe.current)return;const xe=P.output,Xe=je.current.slice(P.appendFromLiveOutputIndex);hi.current=null,qa([...xe,...Xe],P.history),pi()}function ji(){la(),tt.current=!0}function Es(){fu(),tt.current=!1;const k=F.current;k&&Yr(k)&&tr({scrollToBottom:!0})}function Rs(k){cl(()=>MC(k))&&(At.current=!1)}function ll(k,P){cl(()=>(k.scrollToLine(P),!0))}function cl(k){ae.current=!0;try{return k()}finally{ae.current=!1}}function wu(){const k=F.current;if(!k)return;z.current&&(cc(me.current),Hi(!1)),MC(k),At.current=!1,Vn(),tr({force:!0,scrollToBottom:!0}),$r("scroll-action")}function Ns(k){const P=F.current,xe=I.current;if(!P||!xe)return;const Xe=xe.getBoundingClientRect();if(Xe.height<=0)return;const et=Math.max(0,Math.min(1,(k-Xe.top)/Xe.height)),ct=Math.round(P.buffer.active.baseY*et);ji();try{P.scrollToLine(ct)}finally{Es()}At.current=!Yr(P),Vn(),Pr(),ct<=3&&_r()}function wh(k){k.preventDefault(),k.stopPropagation(),k.currentTarget.setPointerCapture?.(k.pointerId),Ns(k.clientY)}function oc(k){(k.buttons&1)!==0&&(k.preventDefault(),k.stopPropagation(),Ns(k.clientY))}function Za(){const k=F.current,P=de.current;if(!(!k||!P)&&!(document.visibilityState==="hidden"||!rt.current||I.current?.isConnected===!1))try{const xe=oa(k),Xe=Cs();P.fit(),Xe&&(O.current=Xe),xe&&Rs(k),z.current&&!Pe.current&&!st.current&&(al(k),(ol()||hi.current)&&tr({scrollToBottom:!0})),k.refresh(0,Math.max(0,k.rows-1)),Vn(),Su(xe);const et={cols:k.cols,rows:k.rows},ct=M.current;if(ct&&ct.cols===et.cols&&ct.rows===et.rows)return;Ci({type:"resize",terminalId:e.id,cols:et.cols,rows:et.rows})&&(M.current=et)}catch{}}function Qa(k,P){const xe=me.current;return xe?xe(k,P):"rejected"}function Ci(k){return Qa(k)!=="rejected"}function ca(){ge.current!==null&&(window.clearTimeout(ge.current),ge.current=null)}function Hr(){ca();const k=Math.max(-Lf,Math.min(Lf,Ae.current));if(Ae.current=0,k===0)return!1;const P=Qa({type:"scrollback_scroll",terminalId:e.id,lines:k},{durability:"live-only"})==="sent";return P&&(Oe.current=!0,k<0&&Hi(!0)),P}function xu(k){if(!z.current||k===0)return;const P=Ae.current+k;Ae.current=Math.max(-Lf,Math.min(Lf,P)),ge.current===null&&(ge.current=window.setTimeout(()=>{ge.current=null,Hr()},s6))}function lc(){cc(me.current)}function Ds(k=me.current,P={}){const xe=Oe.current;ca(),Ae.current=0,Oe.current=!1,P.updateUi!==!1&&Hi(!1),xe&&k?.({type:"cancel_scrollback",terminalId:e.id})}function cc(k){ca(),Ae.current=0,Oe.current=!1,Hi(!1),k?.({type:"cancel_scrollback",terminalId:e.id})}function Cu(){if(!be.current)return;const k=!z.current;ta(UL(te.current,k)),nr()}function ku(){const k=!Mn.current;Mn.current=k,rs(k),zn({tone:k?"info":"skipped",message:k?"Cache keep-alive enabled":"Cache keep-alive off",...k?{detail:"NTerminal will send a short idle prompt before the estimated cache expires."}:{}})}function Tu(){Wt.current!==null&&(window.clearTimeout(Wt.current),Wt.current=null)}function zn(k,P={}){Tu();const xe=Zi.current+1;Zi.current=xe,Qs({...k,id:xe}),!P.sticky&&(Wt.current=window.setTimeout(()=>{Wt.current=null,Qs(Xe=>Xe?.id===xe?null:Xe)},12e3))}function Ja(){Ri.current.skipped=!0,zn({tone:"skipped",message:"Skipped this cache keep-alive",detail:"The timer will watch the next cache window if keep-alive stays on."})}function eo(){Mn.current=!1,rs(!1),zn({tone:"skipped",message:"Cache keep-alive off"})}async function ul(){const k=Ri.current;if(k.sent||k.skipped)return;const P=dl();if(k.sent=!0,P){zn({tone:"skipped",message:"Skipped cache keep-alive",detail:P});return}if(Hn(`${wC}\r`,{userInitiated:!1})==="rejected"){zn({tone:"skipped",message:"Skipped cache keep-alive",detail:"The terminal connection was unavailable."});return}zn({tone:"success",message:"Cache keep-alive sent",detail:wC})}function dl(){const k=qn.current,P=Ze.current;return Mn.current?e.status!=="running"?"Pane is not running.":!k||k.status!=="ready"||!k.source||!P?"Transcript cache status is unavailable.":k.source.provider!==P.provider||k.source.sessionId!==P.sessionId?"The transcript session changed.":e.agentStatus&&["working","finishing","waiting"].includes(e.agentStatus.state)?`${Ao(P.provider)} has an active turn or is waiting for a response.`:e.activity==="busy"?e.currentCommand?`Pane is busy: ${e.currentCommand}.`:"Pane is busy.":Vc(e.id).text.trim()?"Compose has an unsent draft.":y6(I.current)?"Pane input is focused.":Date.now()-Yl.current<5*6e4?"User input was sent recently.":null:"Keep-alive was turned off."}function nr(){const k=F.current;k&&(Rs(k),Vn())}function Hn(k,P={}){if(Di.current?.allowInput(k,P.textPaste)===!1)return"rejected";Kn.current&&P.userInitiated!==!1&&!P.preserveMobileShift&&k&&k!=="\x1B[I"&&k!=="\x1B[O"&&$i(!1),Hr();const xe=Oe.current;tr({force:!0,scrollToBottom:!0});const Xe=Qa({type:"input",terminalId:e.id,data:k,...xe?{cancelScrollbackMode:!0}:{}},{durability:P.userInitiated===!1||P.liveOnly?"live-only":"durable"});return Xe==="rejected"?(P.userInitiated!==!1&&Ir("Input was not sent because the terminal connection buffer is full or unavailable.","error"),Xe):(P.userInitiated!==!1&&(Yl.current=Date.now()),xe&&(Oe.current=!1,Hi(!1)),O6(k)&&(Xe==="sent"?uc():Xe==="queued"&&(j.current=!0)),Xe)}function Ms(k){if(!z.current||!In.current||!rt.current)return;const P=jL(k,Ne.current??yr()??1);Qa({type:"input",terminalId:e.id,data:P},{durability:"live-only"})==="sent"&&/\x1b\[<(?:0|32|64|65);/.test(k)&&(Oe.current=!0,(fe.current==="tmux"||fe.current==="copy")&&Hi(!0))}function yr(){return fe.current==="application"&&Te.current.codex?Te.current.speed:null}function Ur(k,P){const xe=F.current;if(!(!xe||P===0)){Ne.current=Math.abs(P);try{xe.element?.dispatchEvent(T2(k,Math.sign(P),1))}finally{Ne.current=null}}}function os(){cn.current&&Et(!1),Hn(WI)}function xh(k){const P=Yf(k,{bracketedPasteMode:F.current?.modes.bracketedPasteMode===!0||Di.current?.pending===!0,stripTrailingLineBreaks:!0});P&&Hn(P,{textPaste:!0})}function Eu(k,P){const xe=F.current?.modes.bracketedPasteMode===!0,Xe=gr==="codex"||gr==="claude"||El(e.currentCommand),et=k.parts.map(ct=>ct.kind==="image"&&Xe?Yf(ct.path,{bracketedPasteMode:!0,stripTrailingLineBreaks:!0}):Yf(ct.kind==="image"?ct.path:ct.value,{bracketedPasteMode:xe,stripTrailingLineBreaks:!1})).join("");return et?Hn(`${et}${Q5(P)}`)!=="rejected":!1}function uc(){!Tt.current||!In.current||(Li(),Ie.current=UI.map(k=>{const P=window.setTimeout(()=>{Ie.current=Ie.current.filter(xe=>xe!==P),Tt.current&&In.current&&Ci({type:"refresh_cwd",terminalId:e.id})},k);return P}))}function $r(k="terminal-interaction"){ke.current||ic()&&(k==="auto"||k==="scroll-action")||F.current?.focus()}const ri=v.useCallback(()=>{Js(!1)},[]);function dn(){$i(!1),ts(k=>{const P=!k;return cn.current=P,P}),$r("input-action")}function Et(k){cn.current=k,ts(k)}function $i(k){Kn.current=k,Dr(k)}function ir(k){Et(!1),$i(k),$r("input-action")}function Ru(k){cn.current&&Et(!1);const P=Kn.current&&k!=="interrupt"&&k!=="escape";Hn(mb(k,P),{preserveMobileShift:P}),$r("input-action")}async function ls(k="install"){Ss(!0),mr(null);try{const P=k==="update"?await t.updateCodeServer():await t.installCodeServer();Rb(Br,P.status),un(P.status)}catch(P){mr(jf(P))}finally{Ss(!1)}}return u.jsxs("section",{className:"terminal-pane","data-active":n,"data-tmux-scrollback":fi?"true":"false",onMouseDown:()=>{n||m()},children:[u.jsx(S6,{terminal:e,canClose:o,tabId:d,transcriptSource:pn,hasTranscriptCandidates:Ar.length>0,transcriptShortcutLabel:U,subagentsShortcutLabel:Y,transcriptCacheStatus:Ai,transcriptCacheNow:is,cacheKeepAliveEnabled:Lr,codeServerAvailable:!0,codeServerInstallState:Ui===null?"unknown":Ui.installed?"installed":"missing",codeServerBusy:Or||Ui?.job?.status==="running",codeServerSupported:Ui?.supported!==!1,scrollbackShortcutLabel:q,tmuxScrollbackSupported:ss,tmuxScrollbackEnabled:fi,onToggleCacheKeepAlive:ku,onOpenCodeServer:tc,onToggleTmuxScrollback:Cu,onOpenTranscript:ia,onOpenSubagents:Jo,onReload:ee,reloading:Go,onClose:p}),u.jsx("div",{className:"xterm-container",ref:I}),Pn?u.jsxs("div",{className:"terminal-image-paste-status","data-error":Pn.error?"true":"false",role:"status","aria-live":"polite",children:[u.jsx("span",{children:Pn.message}),u.jsx("button",{type:"button","aria-label":Pn.uploading?"Cancel image paste":"Dismiss image paste message",title:Pn.uploading?"Cancel image paste":"Dismiss",onMouseDown:k=>k.preventDefault(),onClick:()=>{Di.current?.cancel()},children:u.jsx(fp,{size:16,"aria-hidden":"true"})})]}):null,Gl?u.jsx("div",{className:"terminal-history-loader",role:"status","aria-label":"Loading older terminal output",children:u.jsx("span",{"aria-hidden":"true"})}):null,R&&!fi&&vs?u.jsxs("div",{className:"terminal-scroll-progress","data-active":Xs,"aria-hidden":"true",children:[vs.current,"/",vs.total]}):R&&!fi&&$a?u.jsxs("div",{className:"terminal-scroll-progress","data-active":!1,"data-pending":"true","data-buffer":$a.alternate?"alternate":"normal","aria-hidden":"true",children:[$a.alternate?"alt ":"","0/?"]}):null,!fi&&_s||fi&&Vo&&e.scrollbackMode!=="application"?u.jsx("button",{type:"button",className:"terminal-scroll-bottom-button","aria-label":"Scroll terminal to bottom",title:"Scroll to bottom",onPointerDown:k=>k.stopPropagation(),onMouseDown:k=>k.stopPropagation(),onClick:k=>{k.stopPropagation(),wu()},children:"↓"}):null,Zl&&!fi?u.jsx("button",{type:"button",className:"terminal-scroll-handle","aria-label":"Drag terminal scroll handle",title:"Drag to scroll",onPointerDown:wh,onPointerMove:oc,children:u.jsx("span",{"aria-hidden":"true"})}):null,n&&e.status==="running"?Qo?u.jsx(C5,{ctrlActive:Yo,shiftActive:Mi,onCtrl:dn,onShift:ir,onStandaloneKey:Ru,onPreserveFocus:()=>$r("input-action"),onHide:()=>{$i(!1),Ka(!1)}}):u.jsx("button",{type:"button",className:"mobile-terminal-key-toggle","aria-label":"Show terminal control keys",title:"Show Ctrl / Shift / Esc / Tab / arrows",onMouseDown:k=>{k.stopPropagation(),$r("input-action")},onPointerDown:k=>{k.stopPropagation(),$r("input-action")},onClick:()=>Ka(!0),children:"⌨"}):null,u.jsx(c4,{terminalId:e.id,onSubmit:Eu,onUploadAttachments:(k,P)=>t.uploadComposeAttachments({terminalId:e.id,files:k,signal:P.signal,onProgress:P.onProgress}),...typeof t.getComposeAttachmentLimits=="function"?{onGetAttachmentLimits:()=>t.getComposeAttachmentLimits()}:{},...typeof t.deleteComposeAttachments=="function"?{onDeleteAttachments:k=>t.deleteComposeAttachments({terminalId:e.id,attachmentIds:k})}:{},queueAvailable:gr==="codex"||Nb(e.currentCommand),disabled:e.status!=="running"}),u.jsx(k6,{toast:jr,onSendNow:()=>{ul()},onSkipOnce:Ja,onTurnOff:eo,onDismiss:()=>Qs(null)}),bs?u.jsx(T6,{terminalId:e.id,serverApi:t,source:pn,candidates:Ar,rememberedSelection:Je,fontSize:w,onClose:ri},e.id):null,ys&&pn?u.jsx(JB,{terminalId:e.id,serverApi:t,source:pn,fontSize:w,onClose:()=>Ji(!1)}):null,ws?u.jsx(x6,{notice:ws}):null,pr?u.jsx(w6,{status:Ui,busy:Or,error:Wa,onInstall:()=>{ls("install")},onUpdate:()=>{ls("update")},onOpen:tc,onRefresh:()=>{xs({checkLatest:!0}).catch(k=>mr(jf(k)))},onClose:()=>pt(!1)}):null]})}function kC(e){return MN(e)}async function TC(e,t,n={}){const s=n.checkLatest===!0,o=n.force===!0||s,l=Date.now(),d=Ic.get(e);if(!o&&d?.status&&l-d.fetchedAt<=a6)return d.status;if(d?.inflight&&(!s||d.inflightCheckLatest))return d.inflight;let f;return f=t.getCodeServerStatus(s?{checkLatest:!0}:void 0).then(m=>(Rb(e,m),m)).catch(m=>{const p=Ic.get(e);throw p?.inflight===f&&(p.status?Ic.set(e,{status:p.status,fetchedAt:p.fetchedAt}):Ic.delete(e)),m}),Ic.set(e,{...d?.status?{status:d.status,fetchedAt:d.fetchedAt}:{fetchedAt:l},inflight:f,inflightCheckLatest:s}),f}function Rb(e,t){Ic.set(e,{status:t,fetchedAt:Date.now()})}function EC(e,t){return`${e}:${t}`}function Jy(e){return`nterminal-code-server-${e.replace(/[^A-Za-z0-9_-]/g,"")}`}function x2(e){const t=jp.get(e);return t?C2(t.handle)?(jp.delete(e),null):t:null}function o6(e){if(e){const t=x2(e);if(t)return{handle:t.handle,ownsPopup:!1}}try{const t=e?window.open("",Jy(e)):window.open("about:blank","_blank");return{handle:t,ownsPopup:l6(t)}}catch{return{handle:null,ownsPopup:!1}}}function l6(e){try{return!!(e&&!e.closed&&e.location.href==="about:blank")}catch{return!1}}function c6(e,t){try{const n=new URL(e.location.href,window.location.href),s=new URL(t,window.location.href);return n.origin===s.origin&&n.pathname===s.pathname}catch{return!1}}function eS(e){try{e.focus()}catch{}}function u6(e,t,n){let s;try{s=window.open(t,Jy(e))}catch{return null}return s?(jp.set(e,{handle:s,createdAt:n}),eS(s),s):null}function d6(e,t,n,s){if(!e||C2(e))return!1;try{e.name=Jy(t),e.location.href=n,jp.set(t,{handle:e,createdAt:s})}catch{return!1}return eS(e),!0}function h6(e){if(e)try{e.document.title="Opening VS Code...",e.document.body.style.margin="0",e.document.body.style.background="#0a0d10",e.document.body.style.color="#e2e8ee",e.document.body.style.font="13px ui-monospace, SFMono-Regular, Menlo, monospace",e.document.body.textContent="Opening VS Code..."}catch{}}function C2(e){if(!e)return!0;try{return e.closed}catch{return!0}}function f6(e){if(e)try{e.closed||e.close()}catch{}}function zv(e,t,n){const s=p6(e,t),o=RC(s*Math.max(1,n),QI,JI);return{limit:RC(Math.ceil(o/GI),XI,ZI),maxLines:o}}function p6(e,t){const n=e?.clientHeight??0;if(n<=0)return VI;const s=Math.max(10,t*YI);return Math.max(1,Math.floor(n/s))}function RC(e,t,n){return Math.max(t,Math.min(n,Math.floor(e)))}function m6(e){return!e?.source||!e.expiresAt?null:`${e.source.provider}:${e.source.sessionId}:${e.expiresAt}`}function g6(e,t){return t?`${e}:${t.provider}:${t.sessionId}`:null}function k2(e,t){if(!e||e.status!=="ready"||!e.expiresAt)return null;const n=Date.parse(e.expiresAt);return Number.isFinite(n)?n-t:null}function v6(e,t){return!e||e.status!=="ready"||t===null?"unknown":t<=0?"expired":t<=2*6e4?"critical":t<=10*6e4?"warning":"ok"}function _6(e){if(e<=0)return"0m";const t=Math.ceil(e/1e3);if(t<60)return"<1m";const n=Math.ceil(t/60);if(n<60)return`${n}m`;const s=Math.floor(n/60),o=n%60;if(s<24&&o>0)return`${s}h ${o}m`;if(s<24)return`${s}h`;const l=Math.floor(s/24),d=s%24;return d>0?`${l}d ${d}h`:`${l}d`}function b6(e){return e instanceof HTMLElement?!!e.closest(".security-panel:not(.transcript-dialog)"):!1}function jf(e){return e instanceof Wn||e instanceof Error?e.message:"Something went wrong."}function y6(e){const t=document.activeElement;return!e||!(t instanceof HTMLElement)||!e.contains(t)?!1:!!t.closest(".xterm-helper-textarea, .compose-drawer-input")}function S6({terminal:e,canClose:t,tabId:n,transcriptSource:s,hasTranscriptCandidates:o,transcriptShortcutLabel:l,subagentsShortcutLabel:d,transcriptCacheStatus:f,transcriptCacheNow:m,cacheKeepAliveEnabled:p,codeServerAvailable:b,codeServerInstallState:_,codeServerBusy:S,codeServerSupported:w,scrollbackShortcutLabel:x,tmuxScrollbackSupported:R,tmuxScrollbackEnabled:L,onToggleCacheKeepAlive:A,onOpenCodeServer:W,onToggleTmuxScrollback:H,onOpenTranscript:U,onOpenSubagents:q,onReload:Y,reloading:I,onClose:F}){const de=dy({id:`pane-${e.id}`,disabled:!n,...n?{data:{kind:"pane",sourceTabId:n,terminalId:e.id}}:{}}),me={cursor:n?"grab":"default",opacity:de.isDragging?.5:void 0};return u.jsxs("header",{ref:de.setNodeRef,className:"terminal-pane-header",style:me,"data-dragging":de.isDragging,...de.attributes,...de.listeners,children:[u.jsx("span",{className:"terminal-pane-dot","aria-hidden":"true"}),u.jsx("span",{className:"terminal-pane-cwd",title:e.cwd,children:e.cwd}),u.jsx("span",{className:"terminal-pane-spacer"}),b?u.jsx("button",{type:"button",className:"terminal-pane-code","data-state":_,"data-busy":S?"true":"false",disabled:!w||S,title:_==="missing"?"Install code-server add-on":"Open this pane in VS Code","aria-label":_==="missing"?"Install code-server add-on":"Open this pane in VS Code",onPointerDown:K=>K.stopPropagation(),onMouseDown:K=>K.stopPropagation(),onClick:K=>{K.stopPropagation(),W()},children:u.jsx("img",{src:"/brand/vscode.png",width:"13",height:"13",alt:"","aria-hidden":"true",draggable:!1})}):null,s||o?u.jsxs("button",{type:"button",className:"terminal-pane-transcript","data-provider":s?.provider,title:"View transcript history","aria-label":"View transcript history",onPointerDown:K=>K.stopPropagation(),onMouseDown:K=>K.stopPropagation(),onClick:K=>{K.stopPropagation(),U()},children:[u.jsx("span",{className:"pane-button-label-full",children:"View history"}),u.jsx("span",{className:"pane-button-label-short",children:"History"}),u.jsx("kbd",{children:l})]}):null,s?u.jsxs("button",{type:"button",className:"terminal-pane-transcript terminal-pane-subagents","data-provider":s.provider,title:"View subagents launched by this session","aria-label":"View subagents launched by this session",onPointerDown:K=>K.stopPropagation(),onMouseDown:K=>K.stopPropagation(),onClick:K=>{K.stopPropagation(),q()},children:[u.jsx("span",{className:"pane-button-label-full",children:"View agents"}),u.jsx("span",{className:"pane-button-label-short",children:"Agents"}),u.jsx("kbd",{children:d})]}):null,s?u.jsx(C6,{status:f,now:m,keepAliveEnabled:p,onToggle:A}):null,e.status==="exited"?u.jsx("span",{className:"terminal-pane-state terminal-pane-state-exited",children:"exited"}):null,R&&e.status==="running"?u.jsxs("button",{type:"button",className:"terminal-pane-scrollback","data-active":L?"true":"false","aria-pressed":L,"aria-label":`Toggle tmux scrollback (${x})`,title:L?`Native scrolling: application history or tmux scrollback (${x}). Shift-drag selects browser text.`:`Scroll input uses NTerminal scrollback (${x}).`,onPointerDown:K=>K.stopPropagation(),onMouseDown:K=>K.stopPropagation(),onClick:K=>{K.stopPropagation(),H()},children:[L?u.jsxs("svg",{"data-scrollback-icon":"tmux",viewBox:"0 0 16 16",width:"12",height:"12","aria-hidden":"true",focusable:"false",children:[u.jsx("path",{d:"M8 1.75c-2.2 0-4 1.8-4 4v4.5c0 2.2 1.8 4 4 4s4-1.8 4-4v-4.5c0-2.2-1.8-4-4-4Zm0 1.25v2.25",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"}),u.jsx("path",{d:"M6.2 7.15 8 5.35l1.8 1.8M6.2 9.25 8 11.05l1.8-1.8",fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]}):u.jsxs("svg",{"data-scrollback-icon":"nterminal",viewBox:"0 0 16 16",width:"12",height:"12","aria-hidden":"true",focusable:"false",children:[u.jsx("path",{d:"M8 1.75c-2.2 0-4 1.8-4 4v4.5c0 2.2 1.8 4 4 4s4-1.8 4-4v-4.5c0-2.2-1.8-4-4-4Zm0 1.25v3.25",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"}),u.jsx("path",{d:"M5.5 7.7h5",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",opacity:"0.75"})]}),u.jsx("kbd",{children:x})]}):null,e.status==="running"?u.jsx("button",{type:"button",className:"terminal-pane-reload","aria-label":`Reload pane ${e.title}`,title:I?"Restoring live pane output...":"Reload pane output and return to live screen",disabled:I,"aria-busy":I,onPointerDown:K=>K.stopPropagation(),onMouseDown:K=>K.stopPropagation(),onClick:K=>{K.stopPropagation(),Y()},children:u.jsx(Il,{size:12,"aria-hidden":"true"})}):null,t?u.jsx("button",{type:"button",className:"terminal-pane-close","aria-label":`Close pane ${e.title}`,title:"Close pane",onPointerDown:K=>K.stopPropagation(),onMouseDown:K=>K.stopPropagation(),onClick:K=>{K.stopPropagation(),F()},children:"x"}):null]})}function w6({status:e,busy:t,error:n,onInstall:s,onUpdate:o,onOpen:l,onRefresh:d,onClose:f}){const m=e?.job??null,p=m?.status==="running",b=e?.installed===!0,_=e?.supported!==!1,S=e===null&&t,w=e?.updateAvailable===!0,x=b?"VS Code add-on":"Install VS Code add-on";return u.jsx("div",{className:"security-overlay code-server-dialog-backdrop",role:"dialog","aria-modal":"true","aria-label":x,onClick:f,children:u.jsxs("section",{className:"security-panel code-server-dialog",onClick:R=>R.stopPropagation(),children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsxs("div",{children:[u.jsx("h2",{children:x}),u.jsx("p",{children:S?"Checking code-server status...":b?`code-server ${e?.version??""}`:"Optional code-server runtime"})]}),u.jsx("button",{type:"button",className:"security-close","aria-label":"Close VS Code add-on dialog",onClick:f,children:"x"})]}),u.jsxs("div",{className:"code-server-dialog-scroll",children:[u.jsxs("div",{className:"code-server-dialog-body",children:[u.jsxs("p",{children:["NTerminal installs code-server under ",u.jsx("code",{children:e?.installPath??"~/.nterminal/addons/code-server/current"})," and opens it through the authenticated NTerminal proxy."]}),S?u.jsx("p",{className:"code-server-dialog-muted",children:"Checking the local add-on before showing install actions."}):null]}),_?null:u.jsx("p",{className:"code-server-dialog-error",children:e?.unsupportedReason??"This platform is not supported."}),n?u.jsx("p",{className:"code-server-dialog-error",children:n}):null,m?u.jsxs("div",{className:"code-server-progress","data-status":m.status,children:[u.jsxs("div",{className:"code-server-progress-heading",children:[u.jsx("span",{children:m.action}),u.jsx("strong",{children:m.status})]}),u.jsx("pre",{children:m.logs.length>0?m.logs.join(`
53
+ `):"Preparing..."})]}):null]}),u.jsxs("div",{className:"code-server-dialog-actions",children:[u.jsx("button",{type:"button",className:"secondary-button",onClick:d,disabled:t||p||!_,children:"Check"}),b?u.jsxs(u.Fragment,{children:[w?u.jsx("button",{type:"button",className:"secondary-button",onClick:o,disabled:t||p||!_,children:"Update"}):null,u.jsx("button",{type:"button",onClick:l,disabled:t||p,children:"Open"})]}):u.jsx("button",{type:"button",onClick:s,disabled:t||p||!_,children:p?"Installing...":"Install"})]})]})})}function x6({notice:e}){return u.jsx("div",{className:"code-server-notice","data-tone":e.tone,role:"status","aria-live":"polite",children:e.message})}function C6({status:e,now:t,keepAliveEnabled:n,onToggle:s}){const o=k2(e,t),l=v6(e,o),d=o===null?"?":_6(o),f=["Estimated cache remaining time based on session history.",n?"Keep-alive is on.":"Click to keep cache warm before estimated expiry.",e?.confidence==="estimated"?"TTL is estimated for this provider.":null].filter(Boolean).join(" ");return u.jsxs("button",{type:"button",className:"terminal-pane-cache","data-state":l,"data-enabled":n?"true":"false","aria-pressed":n,"aria-label":n?"Disable cache keep-alive":"Enable cache keep-alive",title:f,onPointerDown:m=>m.stopPropagation(),onMouseDown:m=>m.stopPropagation(),onClick:m=>{m.stopPropagation(),s()},children:[u.jsxs("svg",{viewBox:"0 0 16 16",width:"12",height:"12","aria-hidden":"true",focusable:"false",children:[u.jsx("circle",{cx:"8",cy:"8",r:"5.8",fill:"none",stroke:"currentColor",strokeWidth:"1.4"}),u.jsx("path",{d:"M8 4.7v3.55l2.25 1.35",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]}),u.jsx("span",{children:d})]})}function k6({toast:e,onSendNow:t,onSkipOnce:n,onTurnOff:s,onDismiss:o}){if(!e)return null;const l=e.tone==="info"||e.tone==="warning";return u.jsxs("aside",{className:"cache-keepalive-toast","data-tone":e.tone,role:"status","aria-live":"polite",children:[u.jsxs("header",{children:[u.jsx("strong",{children:e.message}),u.jsx("button",{type:"button","aria-label":"Dismiss cache keep-alive alert",onClick:o,children:"x"})]}),e.detail?u.jsx("p",{children:e.detail}):null,l?u.jsxs("div",{className:"cache-keepalive-toast-actions",children:[u.jsx("button",{type:"button",onClick:t,children:"Send now"}),u.jsx("button",{type:"button",onClick:n,children:"Skip once"}),u.jsx("button",{type:"button",onClick:s,children:"Turn off"})]}):null]})}function T6(e){const[t,n]=v.useState(null),[s,o]=v.useState(),[l,d]=v.useState(e.candidates),[f,m]=v.useState(e.source),[p,b]=v.useState(null),[_,S]=v.useState(!0),w=v.useRef(0);async function x(A=!1,W=!1){const H=++w.current;S(!0);try{const U=await e.serverApi.getTerminalTranscriptSource(e.terminalId);if(H!==w.current)return;if(d(U.candidates??[]),m(U.source),W&&!U.source&&e.source){m(e.source),n(e.source),b(null);return}const q=e.rememberedSelection?.current;let Y=!1;if((A||!t)&&q?.terminalId===e.terminalId){const I=U.candidates?.find(F=>F.id===q.candidateId);I?(n({provider:I.provider,sessionId:I.sessionId}),o(I.id),Y=!0):e.rememberedSelection&&(e.rememberedSelection.current=null)}if((A||!t)&&U.source)n(U.source),o(void 0),e.rememberedSelection&&(e.rememberedSelection.current=null);else if((A||!t)&&!Y&&U.candidates?.length===1){const I=U.candidates[0];n({provider:I.provider,sessionId:I.sessionId}),o(I.id)}b(null)}catch(U){if(H!==w.current)return;if(W&&e.source){n(e.source);return}b(U instanceof Error?U.message:"Could not load sessions.")}finally{H===w.current&&S(!1)}}v.useEffect(()=>(x(!1,!0),()=>{w.current+=1}),[]),v.useEffect(()=>{if(t)return;function A(W){W.key==="Escape"&&(W.preventDefault(),W.stopPropagation(),e.onClose())}return document.addEventListener("keydown",A,!0),()=>document.removeEventListener("keydown",A,!0)},[t,e.onClose]);const R=[];t&&R.push({id:s??"__pinned",title:l.find(A=>A.id===s)?.title||`${Ao(t.provider)} · ${t.sessionId}`,detail:l.find(A=>A.id===s)?.cwd||t.sessionId}),f&&(!t||!Aa(f,t))&&R.push({id:"__current",title:`Current session · ${Ao(f.provider)}`,detail:f.sessionId});for(const A of l)t&&Aa(t,A)||f&&Aa(f,A)||R.push({id:A.id,title:A.title||A.sessionId,detail:`${Ao(A.provider)} · ${A.cwd}${A.updatedAt?` · ${new Date(A.updatedAt).toLocaleString()}`:""}`});const L=t&&R.length<=1?null:u.jsxs("div",{className:"transcript-session-picker",children:[R.length>1?u.jsx(o5,{options:R,value:s??(t?"__pinned":void 0),onSelect:A=>{if(w.current+=1,S(!1),A==="__current"&&f){n(f),o(void 0),e.rememberedSelection&&(e.rememberedSelection.current=null);return}const W=l.find(H=>H.id===A);W&&(n({provider:W.provider,sessionId:W.sessionId}),o(W.id),e.rememberedSelection&&(e.rememberedSelection.current={terminalId:e.terminalId,candidateId:W.id}))}}):null,u.jsx("button",{type:"button","aria-label":"Refresh sessions",title:"Refresh sessions",disabled:_,onClick:()=>{x()},children:u.jsx(Il,{size:16})}),p?u.jsx("span",{role:"alert",children:p}):null,!t&&!f&&!_&&!l.length?u.jsx("span",{children:"No sessions available."}):null]});return t?v.createElement(E6,{...e,key:`${t.provider}:${t.sessionId}:${s??""}`,source:t,...s?{candidateId:s}:{},sessionPicker:L,liveSourceChanged:!!(e.source&&!Aa(e.source,t)),onReloadLatest:async()=>{e.rememberedSelection&&(e.rememberedSelection.current=null),n(null),o(void 0),await x(!0)}}):u.jsx("div",{className:"security-overlay transcript-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"transcript-picker-title",onPointerDown:A=>A.stopPropagation(),onMouseDown:A=>A.stopPropagation(),onClick:A=>{A.stopPropagation(),e.onClose()},children:u.jsxs("div",{className:"security-panel transcript-dialog",onClick:A=>A.stopPropagation(),children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsx("h2",{id:"transcript-picker-title",children:"History"}),u.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:e.onClose,children:"×"})]}),L,_?u.jsx("div",{className:"transcript-dialog-status",children:"Loading sessions..."}):null]})})}const E6=zt.memo(function({terminalId:t,serverApi:n,source:s,fontSize:o,onClose:l,onReloadLatest:d,candidateId:f,sessionPicker:m,liveSourceChanged:p}){const b=v.useRef(null),_=v.useRef(null),S=v.useRef(null),w=v.useRef(null),x=v.useRef(!0),R=v.useRef(null),[L,A]=v.useState(!1),W=v.useRef(!1),H=v.useRef(null),U=v.useRef(!1),q=v.useRef(()=>{});q.current=Ct;const Y=v.useRef(0),I=v.useRef(!1),F=v.useRef(!1),de=v.useRef(null),me=v.useRef(null),K=v.useRef(null),[te,J]=v.useState([]),[Q,X]=v.useState(!1),[M,T]=v.useState(""),[O,re]=v.useState(null),[he,N]=v.useState(null),[V,se]=v.useState(!1),[Z,Ee]=v.useState(!1),[ye,ze]=v.useState(-1),[Ke,Be]=v.useState(null),[ve,Fe]=v.useState(null),[Ie,j]=v.useState(!1),[ge,Ae]=v.useState(!0),[Oe,z]=v.useState(!1),[fe,Te]=v.useState(null),[Ne,Le]=v.useState(!1),be=p5(n,t,s,f,Q,M),$e=v.useRef(0),qe=v.useRef(null),je=v.useRef(null);function ht(){if(W.current)return!0;const oe=b.current,ke=window.getSelection();if(!oe||!ke||ke.isCollapsed)return!1;for(let Ge=0;Ge<ke.rangeCount;Ge++)if(ke.getRangeAt(Ge).intersectsNode(oe))return!0;return!1}v.useEffect(()=>{const oe=()=>{ht()||(H.current?H.current.resume():U.current&&(U.current=!1,q.current()))},ke=()=>{W.current=!1,oe()};return document.addEventListener("selectionchange",oe),document.addEventListener("pointerup",ke,!0),document.addEventListener("pointercancel",ke,!0),window.addEventListener("blur",ke),()=>{document.removeEventListener("selectionchange",oe),document.removeEventListener("pointerup",ke,!0),document.removeEventListener("pointercancel",ke,!0),window.removeEventListener("blur",ke),H.current?.cancel()}},[]);function st(oe){return oe?.aborted?Promise.reject(new DOMException("Aborted","AbortError")):ht()?new Promise((ke,Ge)=>{const Je=()=>{oe?.removeEventListener("abort",Ze),H.current?.cancel===Ze&&(H.current=null)},Ze=()=>{Je(),Ge(new DOMException("Aborted","AbortError"))};H.current={resume:()=>{Je(),ke()},cancel:Ze},oe?.addEventListener("abort",Ze,{once:!0})}):Promise.resolve()}v.useEffect(()=>{cn(),re(null),N(null)},[M,Q]),v.useEffect(()=>()=>{$e.current+=1,je.current?.abort()},[]),v.useEffect(()=>{function oe(ke){ke.key==="Escape"&&(ke.preventDefault(),ke.stopPropagation(),l())}return document.addEventListener("keydown",oe,!0),()=>document.removeEventListener("keydown",oe,!0)},[l]),v.useLayoutEffect(()=>{Y.current+=1;const oe=Y.current;I.current=!1,F.current=!0,de.current=null,me.current=null,K.current=null;const ke=h5(n,t,s,Q);return _.current=ke,S.current=ke.snapshot,x.current=!0,R.current=null,A(!1),Fe(null),j(!1),Te(null),Le(!1),re(null),N(null),ze(-1),Be(null),ke.snapshot?(F.current=!1,R.current={top:ke.snapshot.scrollTop,atBottom:ke.snapshot.atBottom,...ke.snapshot.scrollAnchor},$t(ke.snapshot),Ae(!1),en(ke.snapshot,oe)):(J([]),Ae(!0),Ft(null,"initial",oe)),()=>{_t(),ke.release(),_.current===ke&&(_.current=null),Y.current+=1,qe.current?.abort(),I.current=!1}},[n,Q,s.provider,s.sessionId,t]),v.useLayoutEffect(()=>{const oe=b.current;if(!oe)return;const ke=R.current;if(ke&&!ge&&w.current===te){R.current=null;const Je=ke.key?Array.from(oe.querySelectorAll("[data-transcript-entry-key]")).find(Ze=>Ze.dataset.transcriptEntryKey===ke.key):null;oe.scrollTop=ke.atBottom?oe.scrollHeight:Je?oe.scrollTop+Je.getBoundingClientRect().top-oe.getBoundingClientRect().top-(ke.offset??0):ke.top;return}if(F.current){if(ge||te.length===0)return;F.current=!1;const Je=()=>{oe.scrollTop=oe.scrollHeight};Je(),window.requestAnimationFrame?.(Je);return}const Ge=de.current;Ge!==null&&(de.current=null,oe.scrollTop+=oe.scrollHeight-Ge)},[te,ge,Q]);const mt=Ao(s.provider),xt=zt.useMemo(()=>Cp(te,Q),[te,Q]),on=zt.useMemo(()=>ub(xt),[xt]),ot=zt.useMemo(()=>R6(on),[on]),Dn=ot.map(oe=>oe.key).join(""),Tn=Ke?ot.find(oe=>oe.key===Ke)?.entryIndex??null:null,ft=M.trim().length>0,Dt=be.result?.hits.length??0,Mt=be.result?.hits.findIndex(oe=>oe.id===O?.id)??-1,wi=he?.entryIndex??null,di=ft?wi:Tn,xi=ft?wi===null?null:"search":Tn===null?null:"prompt",At=xt?xt.split(`
54
+ `).length-1:0,ae=ot.length>0&&ye>=0&&ye<ot.length?ye:ot.length-1,Pe=Ke??(ae>=0?ot[ae]?.key??null:null),tt=ft?Dt>0?`${Mt+1}/${Dt} ${Dt===1?"match":"matches"} · ${At} ${At===1?"line":"lines"}`:`0 matches · ${At} ${At===1?"line":"lines"}`:ot.length>0?`${ae+1}/${ot.length} prompts · ${At} ${At===1?"line":"lines"}`:`0 prompts · ${At} ${At===1?"line":"lines"}`;v.useEffect(()=>{if(ft){Be(null);return}Ke&&!ot.some(oe=>oe.key===Ke)&&Be(null),ze(oe=>{if(ot.length===0)return K.current=null,-1;const ke=K.current?ot.findIndex(Je=>Je.key===K.current):-1,Ge=ke>=0?ke:oe>=0&&oe<ot.length?oe:ot.length-1;return K.current=ot[Ge]?.key??null,Ge})},[Ke,ft,Dn]),v.useEffect(()=>{const oe=me.current;if(!oe||ot.length===0)return;me.current=null;const ke=oe.anchorKey?ot.findIndex(Je=>Je.key===oe.anchorKey):-1,Ge=ke>0?ke-1:0;rt(Ge)},[Dn]);function _t(){const oe=S.current,ke=b.current;if(!oe||!ke||!x.current)return;const Ge=Array.from(ke.querySelectorAll("[data-transcript-entry-key]")).find(Ze=>Ze.getBoundingClientRect().bottom>ke.getBoundingClientRect().top),Je={...oe,scrollTop:ke.scrollTop,atBottom:ke.scrollHeight-ke.clientHeight-ke.scrollTop<=4,...Ge?{scrollAnchor:{key:Ge.dataset.transcriptEntryKey,offset:Ge.getBoundingClientRect().top-ke.getBoundingClientRect().top}}:{}};S.current=Je,_.current?.write(Je)}function $t(oe){S.current=oe,_.current?.write(oe);const ke=Bc([oe.page.records.map(Je=>Je.block).join(`
55
+
56
+ `)],s.provider,{includeTools:Q}),Ge=ke?[ke]:[];w.current=Ge,J(Ge),Fe(oe.cursor),j(oe.hasMore)}async function en(oe,ke){qe.current?.abort();const Ge=new AbortController;qe.current=Ge,I.current=!0,Ae(!1),z(!1),A(!0),Te(null);let Je=null;try{for(;;){const Xt=await n.getTerminalTranscriptHistory(t,{...zv(b.current,o,Pv),...Je?.cursor?{cursor:Je.cursor}:{ifSnapshot:oe.page.snapshot},includeTools:Q,expectedSessionId:s.sessionId,...f?{candidateId:f}:{}},Ge.signal);if(Y.current!==ke||!_.current?.current())return;if(!Xt.source)throw new Error("Transcript source is temporarily unavailable. Retry loading newest.");if(!Aa(s,Xt.source))throw Le(!0),_.current?.invalidate(),new Error("Transcript session changed. Load newest to refresh.");if(Le(!1),Xt.page?.unchanged)return;if(!Xt.page){if(await st(Ge.signal),Y.current!==ke)return;S.current=null,_.current?.invalidate(),J([Bc(Xt.output,s.provider,{includeTools:Q})]),Fe(Xt.cursor),j(Xt.hasMore);return}if(Je=Je?Qx(Je,Xt):db(Xt),!Je)throw new Error("Transcript changed while loading. Load newest to retry.");if(UE(oe,Je)||!Je.hasMore||!Je.cursor)break;await new Promise(Xi=>window.setTimeout(Xi,0))}if(await st(Ge.signal),Y.current!==ke||!_.current?.current())return;_t();const Ze=b.current,tn=S.current??oe,Sn=l5(tn,Je),Gi=Ze?Array.from(Ze.querySelectorAll("[data-transcript-entry-key]")).find(Xt=>Xt.getBoundingClientRect().bottom>Ze.getBoundingClientRect().top):void 0;R.current={top:Sn.scrollTop,atBottom:Sn.atBottom,...Gi&&Ze&&Sn.page.identity===oe.page.identity?{key:Gi.dataset.transcriptEntryKey,offset:Gi.getBoundingClientRect().top-Ze.getBoundingClientRect().top}:{}},$t(Sn)}catch(Ze){Y.current===ke&&!Ge.signal.aborted&&(Te(Ze instanceof Error?Ze.message:"Could not check the latest history."),Ze instanceof Wn&&Ze.status===409&&(_.current?.invalidate(),Le(!0)))}finally{Y.current===ke&&(I.current=!1,A(!1))}}async function Ft(oe,ke,Ge=Y.current){if(!I.current){I.current=!0,qe.current?.abort(),qe.current=new AbortController,A(!1),Ae(ke==="initial"),z(ke==="older"),ke==="older"&&(de.current=b.current?.scrollHeight??null),Te(null);try{await mn(oe,ke,Ge)}catch(Je){if(Y.current!==Ge)return;Te(Je instanceof Error?Je.message:"Failed to load transcript history."),Je instanceof Wn&&Je.status===409&&Le(!0)}finally{Y.current===Ge&&(I.current=!1,Ae(!1),z(!1))}}}async function mn(oe,ke,Ge){const Je=qe.current?.signal;let Ze=oe,tn=0,Sn=[];const Gi=ke==="initial"&&s.provider!=="claude"?t6:e6;for(;Y.current===Ge;){const Xt=await n.getTerminalTranscriptHistory(t,{...Ze?{cursor:Ze}:{},...zv(b.current,o,ke==="initial"?Pv:qI),includeTools:Q,expectedSessionId:s.sessionId,...f?{candidateId:f}:{}},Je);if(Y.current!==Ge||(ke==="older"&&await st(Je),Y.current!==Ge))return;if(!Xt.source){Te("Transcript source is temporarily unavailable.");return}if(!Aa(s,Xt.source)){_.current?.invalidate(),Le(!0),j(!1);return}const Xi=Bc(Xt.output,s.provider,{includeTools:Q}),qn=Bn(Xt,ke,Sn,Xi);if(Xi&&(Sn=[Xi,...Sn],qn))return;if(!Xt.hasMore||!Xt.cursor||tn>=Gi){Sn.length>0&&J(Mn=>ke==="older"?[...Sn,...Mn]:Sn);return}Ze=Xt.cursor,tn+=1}}function Bn(oe,ke,Ge,Je=Bc(oe.output,s.provider,{includeTools:Q})){if(x.current&&oe.page&&!oe.page.unchanged){const tn=S.current,Sn=ke==="older"&&tn?Qx(tn,oe):db(oe);if(!Sn)throw new Error("Transcript changed while loading. Load newest to retry.");return ke==="older"&&(de.current=b.current?.scrollHeight??null),$t(Sn),!!Je}if(Fe(oe.cursor),j(!!(oe.hasMore&&oe.cursor)),!Je)return!1;const Ze=[Je,...Ge];return Cp(Ze,Q)?(J(tn=>ke==="older"?[...Ze,...tn]:Ze),!0):!1}function Ct(){const oe=b.current;if(oe){if(ht()){U.current=!0;return}U.current=!1,gn(),!(ft||oe.scrollTop>72||!Ie||!ve||I.current)&&Ft(ve,"older")}}function ln(oe){if(Dt===0)return;const ke=Mt>=0?Mt:oe>0?-1:0;In((ke+oe+Dt)%Dt)}function cn(){$e.current+=1,je.current?.abort(),je.current=null,se(!1)}function Kn(){const oe=S.current;x.current||(x.current=!0,qe.current?.abort(),Y.current+=1,I.current=!1,z(!1),de.current=null,oe?(R.current={top:oe.scrollTop,atBottom:oe.atBottom,...oe.scrollAnchor},$t(oe),en(oe,Y.current)):(J([]),Fe(null),j(!1),F.current=!0,Ft(null,"initial")))}async function In(oe){const ke=be.result?.hits[oe];if(!ke)return;_t(),x.current=!1,A(!1);const Ge=++$e.current;je.current?.abort(),qe.current?.abort();const Je=new AbortController;je.current=Je,Y.current+=1,I.current=!1,F.current=!1,de.current=null,Ae(!1),se(!0),z(!1),Te(null),re(ke),N(null);try{const Ze=await n.getTerminalTranscriptHistory(t,{around:ke.cursor,expectedSessionId:s.sessionId,...f?{candidateId:f}:{},includeTools:Q,...zv(b.current,o,Pv)},Je.signal);if(Ge!==$e.current)return;if(!Ze.source||!Aa(s,Ze.source)){Le(!0);return}const tn=Bc(Ze.output,s.provider,{includeTools:Q});J([tn]),N(f5(ub(tn),ke,M)),Fe(Ze.cursor),j(!!(Ze.hasMore&&Ze.cursor)),b.current&&(b.current.scrollTop=0)}catch(Ze){Ge===$e.current&&(Te(Ze instanceof Error?Ze.message:"Could not load search result."),Ze instanceof Wn&&Ze.status===409&&Le(!0))}finally{Ge===$e.current&&se(!1)}}function rt(oe){const ke=ot[oe];ke&&(K.current=ke.key,ze(oe),Be(ke.key))}async function Tt(oe){if(ot.length===0){oe<0&&Ie&&ve&&!I.current&&(me.current={anchorKey:null},await Ft(ve,"older"));return}const Ge=(ye>=0&&ye<ot.length?ye:oe<0?ot.length-1:-1)+oe;if(Ge>=0&&Ge<ot.length){rt(Ge);return}oe<0&&Ge<0&&Ie&&ve&&!I.current&&(me.current={anchorKey:ot[0]?.key??null},await Ft(ve,"older"))}function gn(){if(ft)return;const oe=b.current;if(!oe)return;const Ge=oe.getBoundingClientRect().top+Math.min(140,Math.max(48,oe.clientHeight*.28));let Je=null;for(const Ze of L6(oe)){const tn=j6(Ze);if(tn!==null)if(Ze.getBoundingClientRect().top<=Ge)Je=tn;else break}if(Je!==null){const Ze=ot[Je]?.key??null;K.current=Ze,ze(Je),Ke&&Ke!==Ze&&Be(null)}}return u.jsx("div",{className:"security-overlay transcript-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"transcript-dialog-title",onPointerDown:oe=>oe.stopPropagation(),onMouseDown:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),l()},children:u.jsxs("div",{className:"security-panel transcript-dialog",onPointerDown:oe=>oe.stopPropagation(),onMouseDown:oe=>oe.stopPropagation(),onClick:oe=>oe.stopPropagation(),children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsxs("div",{className:"transcript-dialog-title",children:[u.jsxs("h2",{id:"transcript-dialog-title",children:[mt," JSONL"]}),u.jsx("span",{title:s.sessionId,children:s.sessionId})]}),u.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:l,children:"×"})]}),m,p?u.jsx("div",{className:"transcript-dialog-status",children:"The live pane uses another session. History remains pinned to this session."}):null,u.jsxs("div",{className:"transcript-dialog-controls",children:[u.jsxs("label",{className:"auth-checkbox transcript-tool-toggle",children:[u.jsx("input",{type:"checkbox",checked:Q,onChange:oe=>X(oe.currentTarget.checked)}),"Show tool output"]}),u.jsx("label",{className:"transcript-search",children:u.jsx("input",{type:"search",value:M,"aria-label":"Search JSONL transcript",placeholder:"Search history",onChange:oe=>{be.cancel(),cn(),T(oe.currentTarget.value),oe.currentTarget.value.trim()||Kn()},onKeyDown:oe=>{oe.nativeEvent.isComposing||oe.key==="Enter"&&(oe.preventDefault(),ft?be.result?.query===sm(M)?Dt>0?ln(oe.shiftKey?-1:1):!be.result.complete&&be.result.cursor&&!be.busy&&be.search(!0):be.busy||(cn(),re(null),N(null),be.search()):Tt(oe.shiftKey?-1:1))}})}),u.jsx("button",{type:"button",className:"transcript-prompts-toggle","aria-pressed":Z,"aria-label":"Toggle prompt list",title:"Toggle prompt list",onClick:()=>Ee(oe=>!oe),disabled:ot.length===0,children:u.jsx(jA,{size:16})}),u.jsxs("div",{className:"transcript-search-actions","aria-label":ft?"Search result navigation":"Prompt navigation",children:[u.jsx("button",{type:"button",onClick:()=>ft?ln(-1):void Tt(-1),disabled:ft?Dt===0:ot.length===0&&!Ie,"aria-label":ft?"Previous search match":"Previous user prompt",title:ft?"Previous search match":"Previous user prompt",children:u.jsx(RA,{size:16})}),u.jsx("button",{type:"button",onClick:()=>ft?ln(1):void Tt(1),disabled:ft?Dt===0:ot.length===0,"aria-label":ft?"Next search match":"Next user prompt",title:ft?"Next search match":"Next user prompt",children:u.jsx(kA,{size:16})})]}),u.jsx("span",{className:"transcript-result-count",children:tt}),u.jsx("button",{type:"button",title:L?"Checking latest history...":"Load newest entries","aria-label":"Load newest entries","aria-busy":L,onClick:()=>{be.cancel(),cn(),qe.current?.abort(),Y.current+=1,I.current=!1,z(!1),de.current=null,me.current=null,R.current=null,F.current=!0,re(null),N(null),x.current=!0;const oe=S.current;oe?(F.current=!1,R.current={top:0,atBottom:!0},$t({...oe,atBottom:!0}),en(oe,Y.current)):Ft(null,"initial")},children:u.jsx(Il,{size:16})})]}),ft?u.jsxs("div",{className:"transcript-search-results","aria-label":"Search results","aria-busy":be.busy,children:[u.jsxs("div",{className:"transcript-search-summary",role:"status",children:[be.busy?"Searching...":be.result?`${Dt} ${Dt>=200?"retained results":"results"}${be.result.complete?" · Complete":" · More to scan"} · ${be.result.scannedBytes.toLocaleString()} bytes scanned`:"Search history",be.result&&!be.result.complete&&be.result.cursor?u.jsx("button",{type:"button",disabled:be.busy,onClick:()=>{be.search(!0)},children:"Search more"}):null]}),O&&Mt<0&&be.result?u.jsx("div",{className:"transcript-dialog-status",children:"Selected result is outside the retained result window."}):null,be.error?u.jsx("div",{className:"transcript-dialog-error",role:"alert",children:be.error}):null,be.result?.hits.map((oe,ke)=>u.jsxs("button",{type:"button",className:`transcript-prompt-index-item${O?.id===oe.id?" transcript-prompt-index-item-active":""}`,"aria-current":O?.id===oe.id?"true":void 0,onClick:()=>{In(ke)},children:[u.jsxs("span",{children:[oe.timestamp?new Date(oe.timestamp).toLocaleString():""," · ",oe.role]}),u.jsx("strong",{children:oe.preview.slice(0,500)})]},oe.id))]}):null,Z?u.jsx("div",{className:"transcript-prompt-index","aria-label":"User prompts",children:ot.length>0?ot.map((oe,ke)=>u.jsxs("button",{type:"button",className:Pe===oe.key?"transcript-prompt-index-item transcript-prompt-index-item-active":"transcript-prompt-index-item",onClick:()=>rt(ke),children:[u.jsx("span",{children:oe.timestampLabel}),u.jsx("strong",{children:oe.snippet})]},`${oe.key}:${ke}`)):u.jsx("span",{className:"transcript-prompt-index-empty",children:"No user prompts loaded."})}):null,Ne?u.jsxs("div",{className:"transcript-dialog-status",role:"status",children:["The pinned transcript session changed."," ",u.jsx("button",{type:"button",onClick:()=>{d()},children:"Choose session"})]}):null,fe?u.jsx("div",{className:"transcript-dialog-error",role:"alert",children:fe}):null,V?u.jsx("div",{className:"transcript-dialog-status",role:"status",children:"Loading search result..."}):null,u.jsxs("div",{ref:b,className:"transcript-dialog-scroll","aria-label":"JSONL transcript output",onScroll:Ct,onPointerDownCapture:()=>{W.current=!0},children:[Oe?u.jsx("div",{className:"transcript-dialog-status",children:"Loading older entries..."}):null,!ge&&Ie?u.jsx("div",{className:"transcript-dialog-hint",children:"Scroll up for older entries"}):null,xt?u.jsx(LE,{entries:on,searchQuery:M,activeEntryIndex:di,activeEntryMode:xi,activeSearchMatch:he,fontSize:o}):null,ge?u.jsx("div",{className:"transcript-dialog-status",children:"Loading transcript..."}):null,!Ne&&!ge&&!xt&&!fe?Ie&&ve?u.jsxs("div",{className:"transcript-dialog-status",children:[Q?"The latest entries are hidden record types.":"The latest entries contain only hidden tool output."," ",u.jsx("button",{type:"button",onClick:()=>{Ft(ve,"older")},disabled:Oe,children:"Search earlier entries"})]}):u.jsx("div",{className:"transcript-dialog-status",children:"No transcript entries found."}):null]})]})})});function R6(e){const t=[];for(let o=0;o<e.length;o+=1){const l=e[o];!l||l.kind!=="user"||t.push({contentKey:N6(l),entry:l,entryIndex:o})}const n=new Map,s=new Map;for(let o=t.length-1;o>=0;o-=1){const l=t[o];if(!l)continue;const d=n.get(l.contentKey)??0;n.set(l.contentKey,d+1),s.set(o,JSON.stringify([l.contentKey,d]))}return t.map((o,l)=>({entryIndex:o.entryIndex,key:s.get(l)??JSON.stringify([o.contentKey,0]),snippet:M6(o.entry.body),timestampLabel:A6(o.entry.header)}))}function N6(e){return JSON.stringify([e.header??"",e.body.length,D6(e.body)])}function D6(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function M6(e){return(e.replace(/```[\s\S]*?```/g,"[code]").replace(/\s+/g," ").trim()||"(empty prompt)").slice(0,240)}function A6(e){return e?/^\[([^\]]+)\]/.exec(e)?.[1]??"User":"User"}function L6(e){return Array.from(e.querySelectorAll('[data-transcript-kind="user"][data-transcript-prompt-position]'))}function j6(e){const t=e.dataset.transcriptPromptPosition;if(t===void 0)return null;const n=Number(t);return Number.isInteger(n)&&n>=0?n:null}function O6(e){return e.includes("\r")||e.includes(`
57
+ `)}function Hv(e){return e instanceof Wn&&e.status===404}function El(e){return Nb(e)||Db(e)}function Nb(e){if(!e)return!1;const t=e.replace(/^.*[\\/]/,"").toLowerCase();return t==="codex"||t==="codex.js"||t.startsWith("codex-")}function Db(e){if(!e)return!1;const t=e.replace(/^.*[\\/]/,"").toLowerCase();return t==="claude"||t==="claude.js"||t.startsWith("claude-")}function NC(e){if(El(e))return!0;if(!e)return!1;const t=e.replace(/^.*[\\/]/,"").toLowerCase();return t==="node"||t==="nodejs"}function B6(e){let t=0;for(const n of e){if(!n)continue;const s=n.match(/\r\n|\r|\n/g);t+=s?.length??1}return Math.max(1,t)}function Uv(e,t={}){const n={};return(e?.force||t.force)&&(n.force=!0),(e?.scrollToBottom||t.scrollToBottom)&&(n.scrollToBottom=!0),n}function I6(e){const t=e.buffer.active,n=t.baseY+e.rows;return n<=e.rows?null:{current:Math.max(1,Math.min(n,t.viewportY+1)),total:n}}function DC(e,t){const n=e?.querySelector(".xterm .xterm-viewport");if(n){if(t){n.dataset.nterminalTmuxScrollHidden="true",n.style.setProperty("overflow-y","hidden","important"),n.style.setProperty("scrollbar-color","transparent transparent","important"),n.style.setProperty("scrollbar-width","none","important"),n.style.setProperty("-ms-overflow-style","none");return}n.dataset.nterminalTmuxScrollHidden==="true"&&(delete n.dataset.nterminalTmuxScrollHidden,n.style.removeProperty("overflow-y"),n.style.removeProperty("scrollbar-color"),n.style.removeProperty("scrollbar-width"),n.style.removeProperty("-ms-overflow-style"))}}function Yr(e){return e.buffer.active.viewportY>=Math.max(0,e.buffer.active.baseY-1)}function P6(e,t){return!t||Yr(e)}function MC(e){return Yr(e)?!1:(e.scrollToLine(Math.max(0,e.buffer.active.baseY)),!0)}function z6(){return globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function H6(e,t){const{markIntent:n,markKeyboardIntent:s,setPointerScrollActive:o}=t;let l=null;const d={capture:!0,passive:!0},f=()=>n(),m=()=>{l&&(l.scrolling=!0,n(),o(!0))},p=x=>{if(x.button!==0)return;_(),l={id:x.pointerId,x:x.clientX,y:x.clientY,scrolling:!1};const R=x.target;R instanceof Element&&R.closest(U6)&&m()},b=x=>{if(!(!l||x.pointerId!==l.id)){if((x.buttons&1)===0){_();return}if(l.scrolling){n();return}x.pointerType!=="touch"&&Math.hypot(x.clientX-l.x,x.clientY-l.y)>=$6&&m()}},_=()=>{if(!l)return;const x=l.scrolling;l=null,x&&(n(),o(!1))},S=x=>{l&&x.pointerId===l.id&&_()},w=x=>{F6(x)&&s()};return e.addEventListener("wheel",f,d),e.addEventListener("touchmove",f,d),e.addEventListener("pointerdown",p,d),e.addEventListener("keydown",w,{capture:!0}),window.addEventListener("pointermove",b,d),window.addEventListener("pointerup",S,{capture:!0}),window.addEventListener("pointercancel",S,{capture:!0}),window.addEventListener("blur",_),()=>{window.removeEventListener("blur",_),e.removeEventListener("wheel",f,{capture:!0}),e.removeEventListener("touchmove",f,{capture:!0}),e.removeEventListener("pointerdown",p,{capture:!0}),e.removeEventListener("keydown",w,{capture:!0}),window.removeEventListener("pointermove",b,{capture:!0}),window.removeEventListener("pointerup",S,{capture:!0}),window.removeEventListener("pointercancel",S,{capture:!0}),l=null,o(!1)}}const U6=".xterm-scrollable-element > .scrollbar",$6=4;function F6(e){return!e.shiftKey||e.ctrlKey||e.altKey||e.metaKey?!1:e.key==="PageUp"||e.key==="PageDown"||e.key==="Home"||e.key==="End"}function W6(e,t,n,s,o,l,d,f){const m=p=>{const b=q6(p);if(b!==0){if(d()){if(Mb(t))return;p.cancelable&&p.preventDefault(),p.stopPropagation(),f(b);return}p.cancelable&&p.preventDefault(),p.stopPropagation(),K6(t,b,n,s,o,l)}};return e.addEventListener("wheel",m,{capture:!0,passive:!1}),()=>{e.removeEventListener("wheel",m,{capture:!0})}}function K6(e,t,n,s,o,l){const d=()=>{o();try{e.scrollLines(t)}finally{l()}n(),t<0&&e.buffer.active.viewportY<=3&&s(t)};e.buffer.active.type!=="alternate"&&d()}function q6(e){const n=e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?e.deltaY/24:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?e.deltaY*24:e.deltaY;if(n===0)return 0;const s=n<0?Math.floor(n):Math.ceil(n);return Math.max(-30,Math.min(30,s))}function V6(e,t,n,s,o,l,d,f,m,p,b){let _=null,S=0;const w=new OL,x={passive:!1};function R(W){_=$v(W),S=0,w.reset()}function L(W){const H=$v(W);if(H===null){_=null,S=0,w.reset();return}if(_===null){_=H;return}const U=H.clientY-_.clientY;if(_=H,W.cancelable&&W.preventDefault(),U===0)return;const q=p();if(f()&&Mb(t)&&q!==null){const I=w.consume(-U,n(),q);I!==0&&b(H,I),S=0;return}if(w.reset(),f()&&Mb(t)&&Y6(t,H,-U)){S=0;return}S-=U/n();const Y=S<0?Math.ceil(S):Math.floor(S);if(Y!==0){if(S-=Y,f()){m(Y);return}if(t.buffer.active.type!=="alternate"){l();try{t.scrollLines(Y)}finally{d()}s(),Y<0&&t.buffer.active.viewportY<=3&&o(Y)}}}function A(W){if(w.reset(),W.touches.length>0){_=$v(W);return}_=null,S=0}return e.addEventListener("touchstart",R,x),e.addEventListener("touchmove",L,x),e.addEventListener("touchend",A),e.addEventListener("touchcancel",A),()=>{e.removeEventListener("touchstart",R,x),e.removeEventListener("touchmove",L,x),e.removeEventListener("touchend",A),e.removeEventListener("touchcancel",A)}}function $v(e){if(e.touches.length!==1)return null;const t=e.touches[0];return t?{clientX:t.clientX,clientY:t.clientY}:null}function Mb(e){return e.modes.mouseTrackingMode!=="none"}function Y6(e,t,n){const s=e.element;return s?(s.dispatchEvent(T2(t,n)),!0):!1}function T2(e,t,n=0){const s={bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,deltaX:0,deltaY:t,deltaMode:n};if(typeof WheelEvent=="function")return new WheelEvent("wheel",s);const o=new Event("wheel",s);return Object.defineProperties(o,{clientX:{value:e.clientX},clientY:{value:e.clientY},deltaX:{value:0},deltaY:{value:t},deltaMode:{value:n}}),o}function Ab({node:e,terminals:t,editors:n,api:s,activeTerminalId:o,visible:l=!0,refreshCwdOnEnter:d=!1,tabId:f,codeServerContext:m,dropZoneActive:p=!1,draggingTerminalId:b=null,mobileFocusLeafKey:_=null,path:S=[],totalPanes:w,onSelect:x,onClose:R,onResize:L,onExit:A,onSnapshot:W,onCloseEditor:H,onAuthClose:U}){const q=w??Lb(e);if(S.length===0&&_){const de=jb(e),me=de.some(K=>K.key===_)?_:de[0]?.key;if(de.length>1&&me)return u.jsx("div",{className:"mobile-focused-split",children:de.map(K=>{const te=K.key===me;if(K.type==="editor"){const Q=n[K.editorId];return u.jsx("div",{className:"mobile-focused-pane","data-active":te,"aria-hidden":!te,children:Q?u.jsx(tx,{api:s,editor:Q,canClose:q>1,onClose:()=>H(K.editorId)}):u.jsx("div",{className:"missing-pane",children:"Editor unavailable"})},K.key)}const J=t[K.terminalId];return J?u.jsx("div",{className:"mobile-focused-pane","data-active":te,"aria-hidden":!te,children:u.jsx(CC,{terminal:J,serverApi:s,active:te,visible:l&&te,canClose:q>1,refreshCwdOnEnter:d&&te,tabId:f,codeServerContext:m,onSelect:()=>x(K.terminalId),onClose:()=>R(K.terminalId),onExit:Q=>A(K.terminalId,Q),onSnapshot:W,...U?{onAuthClose:U}:{}})},K.key):u.jsx("div",{className:"mobile-focused-pane","data-active":te,"aria-hidden":!te,children:u.jsx("div",{className:"missing-pane",children:"Terminal unavailable"})},K.key)})})}if(e.type==="pane"){const de=t[e.terminalId];if(!de)return u.jsx("div",{className:"missing-pane",children:"Terminal unavailable"});const me=u.jsx(CC,{terminal:de,serverApi:s,active:e.terminalId===o,visible:l,canClose:q>1,refreshCwdOnEnter:d&&e.terminalId===o,tabId:f,codeServerContext:m,onSelect:()=>x(e.terminalId),onClose:()=>R(e.terminalId),onExit:te=>A(e.terminalId,te),onSnapshot:W,...U?{onAuthClose:U}:{}});return p&&b!==e.terminalId?u.jsxs("div",{className:"pane-drop-host",children:[me,u.jsx(Of,{terminalId:e.terminalId,side:"top"}),u.jsx(Of,{terminalId:e.terminalId,side:"right"}),u.jsx(Of,{terminalId:e.terminalId,side:"bottom"}),u.jsx(Of,{terminalId:e.terminalId,side:"left"})]}):me}if(e.type==="editor"){const de=n[e.editorId];return de?u.jsx(tx,{api:s,editor:de,canClose:q>1,onClose:()=>H(e.editorId)}):u.jsx("div",{className:"missing-pane",children:"Editor unavailable"})}const Y=Math.max(.1,Math.min(.9,e.ratio)),I=1-Y,F=e.direction==="vertical"?{gridTemplateColumns:`minmax(0, ${Y}fr) 1px minmax(0, ${I}fr)`}:{gridTemplateRows:`minmax(0, ${Y}fr) 1px minmax(0, ${I}fr)`};return u.jsxs("div",{className:"split-pane","data-direction":e.direction,style:F,children:[u.jsx("div",{className:"split-cell",children:u.jsx(Ab,{node:e.first,terminals:t,editors:n,api:s,activeTerminalId:o,visible:l,refreshCwdOnEnter:d,tabId:f,codeServerContext:m,dropZoneActive:p,draggingTerminalId:b,mobileFocusLeafKey:_,path:[...S,0],totalPanes:q,onSelect:x,onClose:R,onResize:L,onExit:A,onSnapshot:W,onCloseEditor:H,...U?{onAuthClose:U}:{}})}),u.jsx(G6,{direction:e.direction,path:S,onResize:L}),u.jsx("div",{className:"split-cell",children:u.jsx(Ab,{node:e.second,terminals:t,editors:n,api:s,activeTerminalId:o,visible:l,refreshCwdOnEnter:d,tabId:f,codeServerContext:m,dropZoneActive:p,draggingTerminalId:b,mobileFocusLeafKey:_,path:[...S,1],totalPanes:q,onSelect:x,onClose:R,onResize:L,onExit:A,onSnapshot:W,onCloseEditor:H,...U?{onAuthClose:U}:{}})})]})}function Of({terminalId:e,side:t}){const{setNodeRef:n,isOver:s}=Vp({id:`pane-${e}-${t}`,data:{kind:"pane-zone",terminalId:e,side:t}});return u.jsx("div",{ref:n,className:`pane-drop-zone pane-drop-zone--${t}`,"data-over":s,"aria-hidden":"true"})}function G6({direction:e,path:t,onResize:n}){function s(o){o.preventDefault(),o.stopPropagation();const l=o.currentTarget;l.setPointerCapture?.(o.pointerId),l.classList.add("is-dragging"),document.body.style.cursor=e==="vertical"?"col-resize":"row-resize";const d=l.parentElement;if(!d)return;const f=d.getBoundingClientRect();function m(b){const _=e==="vertical"?(b.clientX-f.left)/f.width:(b.clientY-f.top)/f.height;n(t,Math.min(.9,Math.max(.1,_)))}function p(){window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),l.removeEventListener("lostpointercapture",p),l.classList.remove("is-dragging"),document.body.style.cursor=""}window.addEventListener("pointermove",m),window.addEventListener("pointerup",p),window.addEventListener("pointercancel",p),l.addEventListener("lostpointercapture",p)}return u.jsx("div",{"aria-label":"Resize panes","aria-orientation":e==="vertical"?"vertical":"horizontal",className:"split-divider","data-direction":e,onPointerDown:s,role:"separator",children:u.jsx("span",{className:"split-divider-handle","aria-hidden":"true"})})}function Lb(e){return e.type==="pane"||e.type==="editor"?1:Lb(e.first)+Lb(e.second)}function jb(e){return e.type==="pane"?[{key:X6(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:Z6(e.editorId),type:"editor",editorId:e.editorId}]:[...jb(e.first),...jb(e.second)]}function X6(e){return`terminal:${e}`}function Z6(e){return`editor:${e}`}const um="workspace-default",Q6="NTerminal";function J6(){return{workspaces:[],activeWorkspaceId:null,terminals:{}}}function Pc(e,t){switch(t.type){case"workspace.hydrated":return Op(t.terminals,t.savedTabs,t.savedWorkspaces,t.savedActiveWorkspaceId);case"workspace.created":return eP(e,{id:t.workspaceId,title:t.title,defaultCwd:t.defaultCwd??null});case"workspace.closed":return rP(e,t.workspaceId);case"workspace.selected":return E2(e,t.workspaceId);case"workspace.renamed":return tP(e,t.workspaceId,t.title);case"workspace.defaultCwdChanged":return nP(e,t.workspaceId,t.defaultCwd);case"workspace.reordered":return iP(e,t.sourceWorkspaceId,t.targetWorkspaceId,t.placement);case"terminal.created":return tS(e,t.terminal);case"terminal.split":return aP(e,t.terminal,t.direction);case"terminal.updated":return gP(e,t.terminal);case"terminal.exited":return vP(e,t.terminalId,t.exitCode);case"terminal.closed":return M2(e,t.terminalId);case"terminal.detached":return _P(e,t.terminalId,t.workspaceId);case"terminal.revealed":return sP(e,t.terminalId);case"editor.split":return oP(e,t.editorId,t.title,t.direction);case"editor.closed":return bP(e,t.editorId);case"pane.selected":return D2(e,t.terminalId);case"pane.resized":return mP(e,t.path,t.ratio);case"tab.selected":return cP(e,t.tabId);case"tab.renamed":return pP(e,t.tabId,t.title);case"tab.reordered":return nS(e,t.sourceTabId,t.targetIndex);case"tab.dropped_into_pane":return uP(e,t.sourceTabId,t.sourceTerminalId,t.targetTerminalId,t.side);case"terminal.extracted_to_tab":return R2(e,t.sourceTabId,t.sourceTerminalId,t.targetIndex);case"tab.moved_to_workspace":return N2(e,t.sourceTabId,t.targetWorkspaceId,t.targetIndex);case"terminal.extracted_to_workspace":return dP(e,t.sourceTabId,t.sourceTerminalId,t.targetWorkspaceId,t.targetIndex);case"activePane.closed":return lP(e);default:return e}}function eP(e,t){if(e.workspaces.some(s=>s.id===t.id))return E2(e,t.id);const n={id:t.id,title:t.title,defaultCwd:ms(t.defaultCwd),detachedTerminalIds:[],tabs:[],activeTabId:null};return{...e,workspaces:[...e.workspaces,n],activeWorkspaceId:n.id}}function E2(e,t){return e.workspaces.some(n=>n.id===t)?{...e,activeWorkspaceId:t}:e}function tP(e,t,n){const s=n.trim();if(!s)return e;let o=!1;const l=e.workspaces.map(d=>d.id!==t||d.title===s?d:(o=!0,{...d,title:s}));return o?{...e,workspaces:l}:e}function nP(e,t,n){const s=ms(n);let o=!1;const l=e.workspaces.map(d=>d.id!==t||d.defaultCwd===s?d:(o=!0,{...d,defaultCwd:s}));return o?{...e,workspaces:l}:e}function iP(e,t,n,s){if(t===n)return e;const o=e.workspaces.findIndex(_=>_.id===t),l=e.workspaces.findIndex(_=>_.id===n);if(o<0||l<0)return e;const d=e.workspaces.slice(),[f]=d.splice(o,1);if(!f)return e;const m=d.findIndex(_=>_.id===n);if(m<0)return e;const p=s==="before"?m:m+1,b=d.slice();return b.splice(p,0,f),fP(e.workspaces,b)?e:{...e,workspaces:b}}function rP(e,t){if(e.workspaces.length<=1||!e.workspaces.some(f=>f.id===t))return e;const n=e.workspaces.find(f=>f.id===t),s=new Set(n?$s(n):[]),o={...e.terminals};for(const f of s)delete o[f];const l=e.workspaces.filter(f=>f.id!==t),d=e.activeWorkspaceId===t?l[0]?.id??null:e.activeWorkspaceId;return{workspaces:l,activeWorkspaceId:d,terminals:o}}function tS(e,t){const n=L2(e),s=Kl(n)??hm(),o=H2(t);return{...n,activeWorkspaceId:s.id,terminals:{...n.terminals,[t.id]:t},workspaces:n.workspaces.map(l=>l.id===s.id?{...l,defaultCwd:l.defaultCwd??ms(t.cwd),detachedTerminalIds:l.detachedTerminalIds.filter(d=>d!==t.id),tabs:[...l.tabs,o],activeTabId:o.id}:z2(l,t.id))}}function sP(e,t){if(O2(e,t))return D2(e,t);const n=B2(e,t),s=e.terminals[t];return!n||!s?e:tS({...e,activeWorkspaceId:n.id},s)}function aP(e,t,n){const s=Kl(e),o=s?dm(s):void 0;if(!s||!o)return tS(e,t);const l=o.activeTerminalId,d=ih(o.root,l,{type:"split",direction:n,ratio:.5,first:{type:"pane",terminalId:l},second:{type:"pane",terminalId:t.id}});return{...e,terminals:{...e.terminals,[t.id]:t},workspaces:e.workspaces.map(f=>f.id===s.id?{...f,defaultCwd:f.defaultCwd??ms(t.cwd),detachedTerminalIds:f.detachedTerminalIds.filter(m=>m!==t.id),tabs:f.tabs.map(m=>m.id===o.id?{...m,root:d,activeTerminalId:t.id}:m)}:z2(f,t.id))}}function oP(e,t,n,s){const o=Kl(e),l=o?dm(o):void 0;if(!o||!l)return e;const d=l.activeTerminalId,f=ih(l.root,d,{type:"split",direction:s,ratio:.5,first:{type:"pane",terminalId:d},second:{type:"editor",editorId:t,title:n}});return{...e,workspaces:e.workspaces.map(m=>m.id===o.id?{...m,tabs:m.tabs.map(p=>p.id===l.id?{...p,root:f,activeTerminalId:d}:p)}:m)}}function lP(e){const t=Kl(e),n=t?dm(t):void 0;return n?M2(e,n.activeTerminalId):e}function cP(e,t){const n=Kl(e);return!n||!n.tabs.some(s=>s.id===t)?e:{...e,workspaces:e.workspaces.map(s=>s.id===n.id?{...s,activeTabId:t}:s)}}function nS(e,t,n){const s=e.workspaces.map(o=>{const l=o.tabs.findIndex(b=>b.id===t);if(l<0)return o;const d=o.tabs.slice(),[f]=d.splice(l,1);if(!f)return o;const m=Math.max(0,Math.min(d.length,n)),p=d.slice();return p.splice(m,0,f),hP(o.tabs,p)?o:{...o,tabs:p}});return s.every((o,l)=>o===e.workspaces[l])?e:{...e,workspaces:s}}function uP(e,t,n,s,o){if(n===s||!e.terminals[n]||!e.terminals[s])return e;let l=e.workspaces.map(m=>{const p=m.tabs.findIndex(x=>x.id===t);if(p<0)return m;const b=m.tabs[p];if(!b)return m;const _=tu(b.root,n);if(!_){const x=m.tabs.filter((R,L)=>L!==p);return{...m,tabs:x}}const S={...b,root:_,activeTerminalId:Nn(_)[0]??b.activeTerminalId},w=m.tabs.slice();return w[p]=S,{...m,tabs:w}});const d=o==="left"||o==="right"?"vertical":"horizontal",f=o==="left"||o==="top";return l=l.map(m=>{const p=m.tabs.findIndex(R=>Nn(R.root).includes(s));if(p<0)return m;const b=m.tabs[p];if(!b)return m;const _={type:"pane",terminalId:n},S={type:"split",direction:d,ratio:.5,first:f?_:{type:"pane",terminalId:s},second:f?{type:"pane",terminalId:s}:_},w=ih(b.root,s,S),x=m.tabs.slice();return x[p]={...b,root:w,activeTerminalId:n},{...m,tabs:x,activeTabId:b.id}}),L2({...e,workspaces:l})}function R2(e,t,n,s){let o=-1,l=-1;for(let L=0;L<e.workspaces.length;L+=1){const A=e.workspaces[L].tabs.findIndex(W=>W.id===t);if(A>=0){o=L,l=A;break}}if(o<0)return e;const d=e.workspaces[o],f=d.tabs[l],m=Nn(f.root);if(!m.includes(n))return e;if(m.length===1)return nS(e,t,s);const p=tu(f.root,n);if(!p)return e;const b={...f,root:p,activeTerminalId:Nn(p)[0]??f.activeTerminalId},_=e.terminals[n],S={id:`tab-${Date.now().toString(36)}-${n.slice(0,8)}`,title:_?.title??"",activeTerminalId:n,root:{type:"pane",terminalId:n}},w=d.tabs.slice();w[l]=b;const x=Math.max(0,Math.min(w.length,s));w.splice(x,0,S);const R=e.workspaces.slice();return R[o]={...d,tabs:w,activeTabId:S.id},{...e,workspaces:R}}function N2(e,t,n,s=Number.MAX_SAFE_INTEGER){const o=j2(e.workspaces,t),l=e.workspaces.find(p=>p.id===n);if(!o||!l)return e;if(o.workspace.id===n)return s===Number.MAX_SAFE_INTEGER?e:nS(e,t,s);const d=Nn(o.tab.root),f=d.map(p=>e.terminals[p]).find(Boolean),m=e.workspaces.map(p=>{if(p.id===o.workspace.id)return ql({...p,tabs:p.tabs.filter(b=>b.id!==t)});if(p.id===n){const b=p.tabs.slice(),_=Math.max(0,Math.min(b.length,s));return b.splice(_,0,o.tab),{...p,defaultCwd:p.defaultCwd??ms(f?.cwd),detachedTerminalIds:p.detachedTerminalIds.filter(S=>!d.includes(S)),tabs:b,activeTabId:o.tab.id}}return p});return{...e,workspaces:m,activeWorkspaceId:n}}function dP(e,t,n,s,o=Number.MAX_SAFE_INTEGER){const l=e.workspaces.find(w=>w.id===s),d=j2(e.workspaces,t);if(!l||!d||!e.terminals[n]||!Nn(d.tab.root).includes(n))return e;if(d.workspace.id===s)return R2(e,t,n,o);if(Nn(d.tab.root).length===1)return N2(e,t,s,o);const m=tu(d.tab.root,n);if(!m)return e;const p={...d.tab,root:m,activeTerminalId:Nn(m)[0]??d.tab.activeTerminalId},b=e.terminals[n],_={id:`tab-${Date.now().toString(36)}-${n.slice(0,8)}`,title:b.title??n,activeTerminalId:n,root:{type:"pane",terminalId:n}},S=e.workspaces.map(w=>{if(w.id===d.workspace.id)return ql({...w,tabs:w.tabs.map(x=>x.id===t?p:x)});if(w.id===s){const x=w.tabs.slice(),R=Math.max(0,Math.min(x.length,o));return x.splice(R,0,_),{...w,defaultCwd:w.defaultCwd??ms(b.cwd),detachedTerminalIds:w.detachedTerminalIds.filter(L=>L!==n),tabs:x,activeTabId:_.id}}return w});return{...e,workspaces:S,activeWorkspaceId:s}}function hP(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.id!==t[n]?.id)return!1;return!0}function fP(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.id!==t[n]?.id)return!1;return!0}function pP(e,t,n){const s=n.trim();if(!s)return e;let o=!1;const l=e.workspaces.map(d=>{let f=!1;const m=d.tabs.map(p=>p.id!==t||p.title===s?p:(o=!0,f=!0,{...p,title:s}));return f?{...d,tabs:m}:d});return o?{...e,workspaces:l}:e}function D2(e,t){const n=e.workspaces.find(o=>o.tabs.some(l=>nu(l.root,t))),s=n?.tabs.find(o=>nu(o.root,t));return!n||!s?e:{...e,activeWorkspaceId:n.id,workspaces:e.workspaces.map(o=>o.id===n.id?{...o,activeTabId:s.id,tabs:o.tabs.map(l=>l.id===s.id?{...l,activeTerminalId:t}:l)}:o)}}function mP(e,t,n){const s=Kl(e),o=s?dm(s):void 0;if(!s||!o)return e;const l=zb(o.root,t,F2(n));return l===o.root?e:{...e,workspaces:e.workspaces.map(d=>d.id===s.id?{...d,tabs:d.tabs.map(f=>f.id===o.id?{...f,root:l}:f)}:d)}}function Op(e,t,n,s){const o=Object.fromEntries(e.map(_=>[_.id,_])),l=new Set(e.map(_=>_.id)),d=new Set,f=!!(n&&n.some(_=>U2(_))||t&&t.some(_=>$2(_)));let m=yP(t,n,l,d);m.length===0&&(m=[hm()]);const p=typeof s=="string"&&m.some(_=>_.id===s)?s:m[0]?.id??null,b=p??m[0]?.id??um;for(const _ of e)if(!d.has(_.id)){if(f)m=SP(m,b,_.id,_);else{const S=H2(_);m=xP(m,b,S,_)}d.add(_.id)}return{workspaces:m.map(_=>ql(wP(_,o))),activeWorkspaceId:p,terminals:o}}function Dl(e){return Nn(e.root)}function Bp(e){return Hb(e.root)}function $s(e){return iS([...e.tabs.flatMap(t=>Nn(t.root)),...e.detachedTerminalIds])}function Ro(e){const t=e.workspaces.map(n=>{const s=n.tabs.flatMap(o=>{const l=Ib(o.root);return l?[{...o,root:l}]:[]});return ql({...n,tabs:s})});return{activeWorkspaceId:t.some(n=>n.id===e.activeWorkspaceId)?e.activeWorkspaceId:t[0]?.id??null,workspaces:t}}function gP(e,t){return{...e,terminals:{...e.terminals,[t.id]:t},workspaces:e.workspaces.map(n=>({...n,tabs:n.tabs.map(s=>nu(s.root,t.id)?{...s,title:s.title||t.title}:s)}))}}function vP(e,t,n){const s=e.terminals[t];return s?{...e,terminals:{...e.terminals,[t]:{...s,status:"exited",exitCode:n}}}:e}function M2(e,t){const n={...e.terminals};return delete n[t],A2(e,t,n)}function _P(e,t,n){if(!e.terminals[t])return e;const s=(n&&e.workspaces.some(l=>l.id===n)?n:null)??O2(e,t)?.id??B2(e,t)?.id??e.activeWorkspaceId??e.workspaces[0]?.id??um,o=e.workspaces.find(l=>l.id===s);return!o||!P2(o,t)?e:A2(e,t,{...e.terminals},{detachToWorkspaceId:s})}function A2(e,t,n,s={}){let o=e.workspaces.map(d=>{const f=[];for(const m of d.tabs){const p=tu(m.root,t);if(!p)continue;const b=Nn(p),_=b.includes(m.activeTerminalId)?m.activeTerminalId:b[0];_&&f.push({...m,root:p,activeTerminalId:_})}return ql({...d,detachedTerminalIds:d.detachedTerminalIds.filter(m=>m!==t),tabs:f})});s.detachToWorkspaceId&&n[t]&&(o=o.map(d=>d.id===s.detachToWorkspaceId?I2(d,t,n[t]):d));const l=o.some(d=>d.id===e.activeWorkspaceId);return{workspaces:o,activeWorkspaceId:l?e.activeWorkspaceId:o[0]?.id??null,terminals:n}}function bP(e,t){const n=e.workspaces.map(o=>{const l=[];for(const d of o.tabs){const f=Ob(d.root,t);if(!f)continue;const m=Nn(f),p=m.includes(d.activeTerminalId)?d.activeTerminalId:m[0];p&&l.push({...d,root:f,activeTerminalId:p})}return ql({...o,tabs:l})}),s=n.some(o=>o.id===e.activeWorkspaceId);return{...e,workspaces:n,activeWorkspaceId:s?e.activeWorkspaceId:n[0]?.id??null}}function yP(e,t,n,s){if(t&&t.length>0){const o=[];for(const l of t)U2(l)&&o.push(AC(l,n,s));if(o.length>0)return o}return[AC({...hm(),tabs:e??[]},n,s)]}function AC(e,t,n){const s=[];for(const l of e.tabs){if(!$2(l))continue;const d=Bb(l.root,t);if(!d)continue;const f=Nn(d);for(const p of f)n.add(p);const m=f.includes(l.activeTerminalId)?l.activeTerminalId:f[0];m&&s.push({...l,root:d,activeTerminalId:m})}const o=[];for(const l of e.detachedTerminalIds??[])!t.has(l)||n.has(l)||(n.add(l),o.push(l));return ql({...e,defaultCwd:ms(e.defaultCwd),detachedTerminalIds:o,tabs:s})}function L2(e){return Kl(e)?e:{...e,workspaces:[hm()],activeWorkspaceId:um}}function Kl(e){return e.workspaces.find(t=>t.id===e.activeWorkspaceId)??e.workspaces[0]}function dm(e){return e.tabs.find(t=>t.id===e.activeTabId)??e.tabs[0]}function j2(e,t){for(const n of e){const s=n.tabs.findIndex(o=>o.id===t);if(s>=0)return{workspace:n,tab:n.tabs[s],tabIndex:s}}return null}function O2(e,t){return e.workspaces.find(n=>n.tabs.some(s=>nu(s.root,t)))}function B2(e,t){return e.workspaces.find(n=>n.detachedTerminalIds.includes(t))}function SP(e,t,n,s){return e.map(o=>o.id===t?I2(o,n,s):o)}function I2(e,t,n){return P2(e,t)?{...e,defaultCwd:e.defaultCwd??ms(n?.cwd),detachedTerminalIds:iS([...e.detachedTerminalIds.filter(s=>s!==t),t])}:e}function P2(e,t){return e.detachedTerminalIds.includes(t)||e.detachedTerminalIds.length<Io}function z2(e,t){return e.detachedTerminalIds.includes(t)?{...e,detachedTerminalIds:e.detachedTerminalIds.filter(n=>n!==t)}:e}function wP(e,t){if(e.defaultCwd)return e;const n=$s(e).find(o=>!!t[o]),s=n?ms(t[n]?.cwd):null;return s?{...e,defaultCwd:s}:e}function hm(){return{id:um,title:Q6,defaultCwd:null,detachedTerminalIds:[],tabs:[],activeTabId:null}}function ql(e){const t=e.tabs.some(n=>n.id===e.activeTabId);return{...e,defaultCwd:ms(e.defaultCwd),detachedTerminalIds:iS(e.detachedTerminalIds??[]),activeTabId:t?e.activeTabId:e.tabs[0]?.id??null}}function xP(e,t,n,s){const o=Nn(n.root);return e.map(l=>l.id===t?{...l,defaultCwd:l.defaultCwd??ms(s?.cwd),detachedTerminalIds:l.detachedTerminalIds.filter(d=>!o.includes(d)),tabs:[...l.tabs,n],activeTabId:l.activeTabId??n.id}:l)}function H2(e){return{id:`tab-${e.id}`,title:e.title||e.id,root:{type:"pane",terminalId:e.id},activeTerminalId:e.id}}function ih(e,t,n){return e.type==="pane"?e.terminalId===t?n:e:e.type==="editor"?e:{...e,first:ih(e.first,t,n),second:ih(e.second,t,n)}}function tu(e,t){if(e.type==="pane")return e.terminalId===t?null:e;if(e.type==="editor")return e;const n=tu(e.first,t),s=tu(e.second,t);return n&&s?{...e,first:n,second:s}:n??s}function Ob(e,t){if(e.type==="editor")return e.editorId===t?null:e;if(e.type==="pane")return e;const n=Ob(e.first,t),s=Ob(e.second,t);return n&&s?{...e,first:n,second:s}:n??s}function Bb(e,t){if(e.type==="pane")return t.has(e.terminalId)?e:null;if(e.type==="editor")return null;const n=Bb(e.first,t),s=Bb(e.second,t);return n&&s?{...e,ratio:F2(e.ratio),first:n,second:s}:n??s}function Ib(e){if(e.type==="editor")return null;if(e.type==="pane")return e;const t=Ib(e.first),n=Ib(e.second);return t&&n?{...e,first:t,second:n}:t??n}function U2(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.title=="string"&&(typeof t.activeTabId=="string"||t.activeTabId===null)&&Array.isArray(t.tabs)}function $2(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.title=="string"&&typeof t.activeTerminalId=="string"&&Pb(t.root)}function Pb(e){if(!e||typeof e!="object")return!1;const t=e;return t.type==="pane"?typeof t.terminalId=="string":t.type==="editor"?typeof t.editorId=="string"&&typeof t.title=="string":t.type==="split"?(t.direction==="horizontal"||t.direction==="vertical")&&Pb(t.first)&&Pb(t.second):!1}function zb(e,t,n){if(e.type==="pane"||e.type==="editor")return e;if(t.length===0)return e.ratio===n?e:{...e,ratio:n};const[s,...o]=t;if(s===0){const l=zb(e.first,o,n);return l===e.first?e:{...e,first:l}}if(s===1){const l=zb(e.second,o,n);return l===e.second?e:{...e,second:l}}return e}function F2(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}function ms(e){if(typeof e!="string")return null;const t=e.trim();return t||null}function iS(e){const t=new Set,n=[];for(const s of e)!s||t.has(s)||(t.add(s),n.push(s));return n}function nu(e,t){return e.type==="pane"?e.terminalId===t:e.type==="editor"?!1:nu(e.first,t)||nu(e.second,t)}function Nn(e){return e.type==="pane"?[e.terminalId]:e.type==="editor"?[]:[...Nn(e.first),...Nn(e.second)]}function Hb(e){return e.type==="pane"||e.type==="editor"?1:Hb(e.first)+Hb(e.second)}function Ip(e,t,n=!1){if(!e)return t;const s=e.agentStatus,o=t.agentStatus,l=Date.parse(e.updatedAt),d=Date.parse(t.updatedAt);return e.status===t.status&&s?.source==="hook"&&o?.source==="hook"&&s.epoch&&s.epoch===o.epoch&&s.revision!==void 0&&o.revision!==void 0&&s.revision!==o.revision?o.revision>s.revision?t:e:Number.isFinite(l)&&(!Number.isFinite(d)||d<l)?e:Number.isFinite(d)&&(!Number.isFinite(l)||d>l)?t:e.status!==t.status?e.status==="exited"?e:t:n?e:t}function CP(e,t){const n=[],s=l=>{l.type==="split"?(s(l.first),s(l.second)):l.type==="pane"?n.push({key:`terminal:${l.terminalId}`,terminalId:l.terminalId}):n.push({key:`editor:${l.editorId}`})};s(e);const o=t&&n.length>1?[n.find(l=>l.key===t)??n[0]]:n;return new Set(o.flatMap(l=>l.terminalId===void 0?[]:[l.terminalId]))}const ur=new Map,rh=new Map,sh=new Map,ah=new Map,oh=new Map,Td=new Set;let Na=null,kP=0;const Ub=new Set;let W2=0;function Nr(e){return e??"__local__"}function TP(e){return{agentId:e,generation:++kP,state:J6(),editors:{},loaded:!1,error:null,layoutRevision:null,lastPersistedLayoutJson:null,unreadCompletions:new Set,mutable:{editorIdCounter:0,hydration:{requestId:0,layoutSequence:0,metadataSequence:0,pending:null,mutations:new Map,overflow:!1},saveCoord:{pendingLayoutSave:null,saveTimer:null,persistChain:Promise.resolve(),nextPersistQueued:!1,nextPersistLayout:null,queuedBaseRevision:void 0}}}}function gt(e){const t=Nr(e);let n=ur.get(t);return n||(n=TP(e),ur.set(t,n)),n}function xo(e){return ur.get(Nr(e))??null}function K2(e,t){const n=Nr(e);let s=rh.get(n);return s||(s=new Set,rh.set(n,s)),s.add(t),()=>{s.delete(t)}}function EP(e){const t=Nr(e),n=rh.get(t);if(n)for(const s of Array.from(n))s()}function Vl(e,t,n=!0){const s=ur.get(Nr(e)),o=n&&LC(s)!==LC(t);ur.set(Nr(e),t),EP(e),o&&sS()}function $b(e){return!e||e.status!=="running"?!1:e.agentStatus?e.agentStatus.state==="working"||e.agentStatus.state==="finishing"||e.agentStatus.state==="unknown"&&e.activity==="busy":e.activity==="busy"}function rS(e,t){const n=e.state.workspaces.find(d=>d.id===t);if(!n)return{workingTerminalCount:0,unreadCompletionCount:0};const s=new Set;for(const d of n.tabs)for(const f of Nn(d.root))s.add(f);let o=0,l=0;for(const d of s)$b(e.state.terminals[d])&&(o+=1),e.unreadCompletions.has(d)&&(l+=1);return{workingTerminalCount:o,unreadCompletionCount:l}}function LC(e){return e?e.state.workspaces.map(t=>{const n=rS(e,t.id);return`${t.id}:${n.workingTerminalCount}:${n.unreadCompletionCount}`}).join("|"):""}function q2(e){return!!(e&&e.state.workspaces.some(t=>{const n=rS(e,t.id);return n.workingTerminalCount>0||n.unreadCompletionCount>0}))}function sS(){W2+=1;for(const e of Array.from(Ub))e()}function RP(e){return Ub.add(e),()=>{Ub.delete(e)}}function jC(){return W2}function NP(e,t){return rS(gt(e),t)}const Fb=new Set;function DP(e){return Fb.add(e),()=>{Fb.delete(e)}}function aS(e,t,n=gt(e).state){const s=Na;if(!s||s.agentId!==e||s.generation!==ur.get(Nr(e))?.generation)return!1;const o=n.workspaces.find(d=>d.id===s.workspaceId),l=o?.tabs.find(d=>d.id===s.tabId);return!!(o?.id===n.activeWorkspaceId&&l?.id===o?.activeTabId&&l?.root===s.root&&n.terminals[t]&&s.terminalIds.has(t))}function Bf(e,t=!0){let n=typeof e=="object"&&e!==null?e:null;if(e!==void 0&&!n&&t){const d=ur.get(Nr(e)),f=d?.state.workspaces.find(p=>p.id===d.state.activeWorkspaceId),m=f?.tabs.find(p=>p.id===f.activeTabId);d&&f&&m&&(n={generation:d.generation,agentId:d.agentId,workspaceId:f.id,tabId:m.id,root:m.root,terminalIds:new Set(Nn(m.root))})}if(Na=t&&n?{...n,terminalIds:new Set(Nn(n.root).filter(d=>n.terminalIds.has(d)))}:null,!Na)return;const s=Na.agentId,o=ur.get(Nr(s));if(!o||o.generation!==Na.generation){Na=null;return}const l=new Set([...o.unreadCompletions].filter(d=>!aS(s,d,o.state)));l.size!==o.unreadCompletions.size&&(Vl(s,{...o,unreadCompletions:l}),fm())}function Ed(e,t){const n=gt(e),s=Nr(e);if(t.type==="terminal.updated"){const b=n.state.terminals[t.terminal.id];if(n.mutable.hydration.mutations.get(t.terminal.id)==="delete"||b&&Ip(b,t.terminal)===b&&t.terminal!==b)return}const o=AP(n.state,t);t.type==="workspace.hydrated"&&(sh.delete(s),ah.delete(s),oh.delete(s));const l=Pc(n.state,t);UP(n,t,l);let d=n.unreadCompletions,f=null;if(t.type==="terminal.updated"){const b=n.state.terminals[t.terminal.id],_=WP(s),S=KP(s),w=LP(s);if(t.terminal.agentStatus?.source==="hook"){_.delete(t.terminal.id),S.delete(t.terminal.id),w.delete(t.terminal.id);const x=t.terminal.agentStatus.completion;if(x){const R=`${s}:${x.id}`,L=Td.has(R)||b?.agentStatus?.completion?.id===x.id;Y2(R),!L&&t.notifyCompletion===!0&&(f=IC(l,t.terminal.id,t.terminal.currentCommand??null,x.outcome))}}else if(t.terminal.agentStatus){const x=t.terminal.agentStatus.state,R=t.terminal.agentStatus.sessionId,L=w.get(t.terminal.id),A=!!(b&&(b.currentCommand!==t.terminal.currentCommand||b.agentStatus?.provider!==t.terminal.agentStatus.provider||MP(L,R)));A&&(S.delete(t.terminal.id),_.delete(t.terminal.id),w.delete(t.terminal.id)),R&&w.set(t.terminal.id,R),t.notifyCompletion===!0&&(x==="working"?(S.add(t.terminal.id),_.delete(t.terminal.id)):x==="unknown"&&t.terminal.activity==="busy"&&_.add(t.terminal.id)),!A&&(x==="done"||x==="stopped")&&(S.has(t.terminal.id)||_.has(t.terminal.id))&&(f=IC(l,t.terminal.id,b?.currentCommand??null,x==="stopped"?"stopped":"finished"),S.delete(t.terminal.id),_.delete(t.terminal.id)),x==="idle"&&(S.delete(t.terminal.id),_.delete(t.terminal.id))}else b?.agentStatus&&(S.delete(t.terminal.id),w.delete(t.terminal.id)),_.delete(t.terminal.id);f&&!aS(e,t.terminal.id,l)&&!d.has(t.terminal.id)&&(d=new Set(d),d.add(t.terminal.id)),t.terminal.status==="exited"&&(_.delete(t.terminal.id),S.delete(t.terminal.id),w.delete(t.terminal.id))}if(t.type==="terminal.closed"||t.type==="workspace.closed"){const b=new Set([...d].filter(_=>l.terminals[_]));b.size!==d.size&&(d=b)}const m=l!==n.state,p=d!==n.unreadCompletions;if((m||p)&&Vl(e,{...n,state:l,unreadCompletions:d},o||p),p&&fm(),f)for(const b of Array.from(Fb))b({agentId:e,...f})}function MP(e,t){return e!==void 0&&t!==void 0&&e!==t}function AP(e,t){switch(t.type){case"terminal.updated":return $b(e.terminals[t.terminal.id])!==$b(t.terminal);case"workspace.renamed":case"workspace.defaultCwdChanged":case"workspace.reordered":case"editor.split":case"editor.closed":case"pane.selected":case"pane.resized":case"tab.renamed":case"tab.reordered":return!1;default:return!0}}function LP(e){let t=oh.get(e);return t||(t=new Map,oh.set(e,t)),t}function jP(e,t){for(const n of e.workspaces)for(const s of n.tabs)if(Nn(s.root).includes(t))return{workspace:n,tab:s};return null}const Wb=new Set;function OP(e){return Wb.add(e),()=>{Wb.delete(e)}}function BP(){let e=0;for(const t of ur.values())e+=t.unreadCompletions.size;return e}function fm(){for(const e of Array.from(Wb))e()}function OC(e,t){const n=gt(e);if(t!==n.state){n.mutable.hydration.layoutSequence++;for(const s of new Set([...Object.keys(n.state.terminals),...Object.keys(t.terminals)]))n.state.terminals[s]!==t.terminals[s]&&zc(n,s,t.terminals[s]?t.terminals[s].status==="exited"?"exit":"upsert":"delete");Vl(e,{...n,state:t})}}function IP(e){const t=gt(e),n=t.mutable.hydration,s={generation:t.generation,requestId:++n.requestId,layoutSequence:n.layoutSequence,metadataSequence:n.metadataSequence};return n.pending=s,n.mutations.clear(),n.overflow=!1,s}function lh(e,t){const n=ur.get(Nr(e));return n?.generation===t.generation&&n.mutable.hydration.pending===t}function BC(e,t){if(!lh(e,t))return;const n=gt(e).mutable.hydration;n.pending=null,n.mutations.clear()}function V2(e,t,n){if(!lh(e,t))return null;const s=gt(e),o=s.mutable.hydration;if(o.overflow)throw new Error("Workspace changed too much while loading. Retry loading it.");const l=new Map;if(o.layoutSequence!==t.layoutSequence||o.metadataSequence!==t.metadataSequence)for(const d of s.state.workspaces.flatMap($s)){const f=s.state.terminals[d];f&&l.set(d,f)}for(const d of n){const f=o.mutations.get(d.id);if(f==="delete")continue;const m=s.state.terminals[d.id];l.set(d.id,f==="exit"&&m?m:Ip(m,d,!0))}for(const[d,f]of o.mutations)f==="delete"?l.delete(d):s.state.terminals[d]&&l.set(d,Ip(l.get(d),s.state.terminals[d]));return[...l.values()]}function PP(e,t,n){if(!lh(e,t)||n.length>0)return!1;const s=gt(e).mutable.hydration;return s.layoutSequence===t.layoutSequence&&s.metadataSequence===t.metadataSequence&&s.mutations.size===0}function zP(e,t,n){const s=V2(e,t,n.terminals);if(!s)return null;const o=gt(e),l=o.mutable.hydration,d=l.metadataSequence!==t.metadataSequence,f=l.layoutSequence!==t.layoutSequence||d,m=f?{...o.state,terminals:Object.fromEntries(s.map(_=>[_.id,_]))}:Op(s,n.savedTabs,n.savedWorkspaces,n.savedActiveWorkspaceId),p=HP(m,n.savedWorkspaces??n.persistedLayout?.workspaces),b=d?o.lastPersistedLayoutJson:f?n.persistedLayout?JSON.stringify(n.persistedLayout):o.lastPersistedLayoutJson:JSON.stringify(Ro(p));l.pending=null,l.mutations.clear();for(const _ of s)_.agentStatus?.source==="hook"&&_.agentStatus.completion&&Y2(`${Nr(e)}:${_.agentStatus.completion.id}`);return Vl(e,{...o,state:p,loaded:!0,error:null,layoutRevision:d?o.layoutRevision:n.revision,lastPersistedLayoutJson:b}),{state:p,layoutPreserved:f,metadataPreserved:d}}function HP(e,t=[]){const n=new Set(e.workspaces.flatMap($s)),s=Object.values(e.terminals).filter(_=>!n.has(_.id));if(s.length===0)return e;const o=e.workspaces.find(_=>_.id===e.activeWorkspaceId)??e.workspaces[0];if(!o)throw new Error("Loaded terminals have no workspace. Retry loading the workspace.");const l=new Set(e.workspaces.map(_=>_.id)),d=new Map;for(const _ of t)if(l.has(_.id))for(const S of $s(_))d.has(S)||d.set(S,_.id);const f=e.workspaces.slice(),m=new Set(f.flatMap(_=>_.tabs.map(S=>S.id)));let p=!1;for(const _ of s){const S=f.findIndex(x=>x.id===(d.get(_.id)??o.id)),w=f[S];if(w.detachedTerminalIds.length<Io)f[S]={...w,detachedTerminalIds:[...w.detachedTerminalIds,_.id]};else{if(!w.tabs.some(L=>L.id===w.activeTabId))throw new Error(`This workspace already has ${Io} hidden terminal sessions and no selected tab. Re-open or delete hidden sessions before retrying.`);const x=`hydrated-${_.id}`;let R=x;for(let L=1;m.has(R);L++)R=`${x}-${L}`;m.add(R),f[S]={...w,tabs:[...w.tabs,{id:R,title:_.title||_.id,activeTerminalId:_.id,root:{type:"pane",terminalId:_.id}}]},p=!0}}const b={...e,workspaces:f};if(p&&!Yp(Ro(b)))throw new Error("Loaded terminals exceed the workspace layout limit. Re-open or delete hidden sessions before retrying.");return b}function Y2(e){for(Td.add(e);Td.size>2048;)Td.delete(Td.values().next().value)}function zc(e,t,n){const s=e.mutable.hydration;if(s.pending){if(!s.mutations.has(t)&&s.mutations.size>=4096){s.overflow=!0;return}s.mutations.set(t,n)}}function UP(e,t,n){if(t.type!=="terminal.updated"&&t.type!=="terminal.exited"&&(n.workspaces!==e.state.workspaces||n.activeWorkspaceId!==e.state.activeWorkspaceId)&&e.mutable.hydration.layoutSequence++,t.type==="terminal.updated")t.notifyCompletion===!0&&zc(e,t.terminal.id,t.terminal.status==="exited"?"exit":"upsert");else if(t.type==="terminal.created"||t.type==="terminal.split")zc(e,t.terminal.id,"upsert");else if(t.type==="terminal.exited"&&n.terminals[t.terminalId])zc(e,t.terminalId,"exit");else if(t.type==="terminal.closed")zc(e,t.terminalId,"delete");else if(t.type==="workspace.closed")for(const s of Object.keys(e.state.terminals))n.terminals[s]||zc(e,s,"delete")}function Fv(e,t){const n=gt(e),s=t(n.editors);s!==n.editors&&Vl(e,{...n,editors:s},!1)}function Co(e,t,n){const s=gt(e);s.loaded===t&&s.error===n||Vl(e,{...s,loaded:t,error:n},!1)}function If(e,t,n){const s=gt(e);s.layoutRevision===t&&s.lastPersistedLayoutJson===n||(s.mutable.hydration.metadataSequence++,Vl(e,{...s,layoutRevision:t,lastPersistedLayoutJson:n},!1))}function $P(e){const t=gt(e);return t.mutable.editorIdCounter+=1,t.mutable.editorIdCounter}function FP(e){const t=Nr(e),n=ur.get(t);Na?.agentId===e&&(Na=null),n&&n.mutable.saveCoord.saveTimer!==null&&window.clearTimeout(n.mutable.saveCoord.saveTimer);const s=n?n.unreadCompletions.size>0:!1,o=q2(n);ur.delete(t),rh.delete(t),sh.delete(t),ah.delete(t),oh.delete(t),s&&fm(),o&&sS()}function Wv(){Na=null;let e=!1,t=!1;for(const n of ur.values()){const s=n.mutable.saveCoord.saveTimer;s!==null&&window.clearTimeout(s),n.unreadCompletions.size>0&&(e=!0),q2(n)&&(t=!0)}ur.clear(),rh.clear(),sh.clear(),ah.clear(),oh.clear(),e&&fm(),t&&sS()}function WP(e){let t=sh.get(e);return t||(t=new Set,sh.set(e,t)),t}function KP(e){let t=ah.get(e);return t||(t=new Set,ah.set(e,t)),t}function IC(e,t,n,s){const o=jP(e,t);return{terminalId:t,tabId:o?.tab.id??null,commandName:n,outcome:s}}function qP(e,t,n){const s=Ip(e.terminals[t.id],t,!0);if(s.status!=="running")throw new Error("This terminal is no longer running.");let o=Pc(e,{type:"terminal.updated",terminal:s});if(o.workspaces.some(l=>$s(l).includes(t.id)))o=Pc(o,{type:"terminal.revealed",terminalId:t.id});else{const l=n?.workspaces.find(d=>$s(d).includes(t.id));l&&(o.workspaces.some(d=>d.id===l.id)?o=Pc(o,{type:"workspace.selected",workspaceId:l.id}):o=Pc(o,{type:"workspace.created",workspaceId:l.id,title:l.title,defaultCwd:l.defaultCwd})),o=Pc(o,{type:"terminal.created",terminal:s})}if(!Yp(Ro(o)))throw new Error("This terminal cannot be opened because the workspace layout limit was reached.");return o}function Kb(e,t){let n=!1,s=!1,o=null,l=!1;for(const d of Dl(e)){const f=t[d];if(!f)continue;if(f.status==="exited"){l=!0,n=!0;continue}const m=f.agentStatus?.state,p=m&&m!=="unknown"?["working","finishing"].includes(m)?"busy":"idle":f.activity;p==="busy"?(s=!0,n=!0,!o&&f.currentCommand&&(o=f.currentCommand)):p==="idle"&&(n=!0)}return n?l?{state:"exited",commandName:null}:s?{state:"busy",commandName:o}:{state:"idle",commandName:null}:null}function oS(e){return e?e.state==="busy"?e.commandName?`running: ${e.commandName}`:"running":e.state==="exited"?"exited":"idle":""}function qb(e,t){const n=t[e.activeTerminalId];return e.title||n?.title||e.activeTerminalId}function VP(e,t,n,s){return s?.state==="busy"?s.commandName?`running: ${s.commandName}`:"running":s?.state==="exited"?"exited":t[e.activeTerminalId]?.cwd||`${n} pane${n===1?"":"s"}`}function YP({tabs:e,activeTabId:t,terminals:n,unreadCompletionTabIds:s,favoriteTabIds:o,detachedTerminals:l,onSelectTab:d,onCreateTab:f,onToggleWorkspaces:m,onCloseTerminals:p,onReattachTerminal:b,onDeleteTerminal:_,onSplitVertical:S,onSplitHorizontal:w,onRenameTab:x,onToggleFavorite:R,onOpenFavorites:L,activePaneAvailable:A}){const[W,H]=v.useState(null),[U,q]=v.useState(!1),[Y,I]=v.useState(null),F=v.useRef(null),de=e.findIndex(T=>T.id===t),me=de>=0?e[de]:e[0]??null,K=me?Kb(me,n):null,te=me?Bp(me):0,J=me?qb(me,n):"No tab";v.useEffect(()=>{F.current?.focus(),F.current?.select()},[W?.tabId]),v.useEffect(()=>{if(!U)return;const T=O=>{O.key==="Escape"&&q(!1)};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[U]),v.useEffect(()=>{U&&e.length===0&&q(!1)},[U,e.length]);function Q(T,O){H({tabId:T,title:O})}function X(){if(!W)return;const T=W.title.trim();T&&x(W.tabId,T),H(null)}function M(){return u.jsxs("div",{className:"terminal-pane-actions","aria-label":"Pane actions",children:[u.jsx("button",{type:"button",className:"pane-action-button","aria-label":"Split right",title:`Split right - ${VL()}`,onClick:S,disabled:!A,children:u.jsx("span",{className:"split-icon split-icon-right","aria-hidden":"true"})}),u.jsx("button",{type:"button",className:"pane-action-button","aria-label":"Split down",title:`Split down - ${YL()}`,onClick:w,disabled:!A,children:u.jsx("span",{className:"split-icon split-icon-down","aria-hidden":"true"})})]})}return u.jsxs(u.Fragment,{children:[u.jsxs("nav",{className:"terminal-tabs","aria-label":"Terminal tabs",children:[u.jsx("button",{type:"button",className:"mobile-menu-button","aria-label":"Toggle workspaces",title:"Workspaces",onClick:m,children:u.jsxs("span",{className:"hamburger-lines","aria-hidden":"true",children:[u.jsx("span",{}),u.jsx("span",{}),u.jsx("span",{})]})}),u.jsxs("button",{type:"button",className:"mobile-tab-current-button","aria-label":"Open tab switcher",title:J,onClick:()=>q(!0),disabled:e.length===0,children:[K?u.jsx("span",{className:"terminal-tab-status-dot","data-activity":K.state,"aria-hidden":"true",title:oS(K)}):null,u.jsx("span",{children:J}),u.jsxs("small",{children:[de>=0?de+1:0,"/",e.length||0,te>1?` / ${te}`:""]})]}),u.jsxs("div",{className:"terminal-tab-list",children:[e.map((T,O)=>{const re=Dl(T),he=Bp(T),N=qb(T,n),V=T.id===t,se=W?.tabId===T.id,Z=Kb(T,n),Ee=s?.has(T.id)??!1;return u.jsxs(zt.Fragment,{children:[u.jsx(PC,{index:O}),u.jsx(GP,{tab:T,active:V,editing:se,title:N,paneCount:he,terminalIds:re,canClose:e.length>1,editValue:se?W.title:null,editInputRef:se?F:null,activity:Z,unread:Ee,favorite:o?.has(T.id)??!1,onSelect:()=>d(T.id),onBeginRename:()=>Q(T.id,N),onCloseAll:()=>p(re),onCommitRename:X,onCancelRename:()=>H(null),onRenameChange:ye=>H({tabId:T.id,title:ye}),onToggleFavorite:()=>R?.(T)})]},T.id)}),u.jsx(PC,{index:e.length}),u.jsx("button",{type:"button",className:"tab-add-button","aria-label":"New tab",title:"New tab",onClick:f,children:"+"}),u.jsx("button",{type:"button",className:"tab-favorites-button","aria-label":"Open favorite tabs",title:"Favorite tabs",onClick:()=>L?.(),children:"★"}),(l?.length??0)>0?u.jsx("div",{className:"terminal-detached-pills","aria-label":"Detached terminals",children:(l??[]).map(T=>u.jsx(ZP,{terminal:T,onReattach:()=>b?.(T.id),onDelete:()=>I(T)},T.id))}):null]}),u.jsx("button",{type:"button",className:"mobile-tab-add-button","aria-label":"Create new tab",title:"New tab",onClick:f,children:"+"}),A?M():null]}),U?u.jsx(XP,{tabs:e,activeTabId:t,terminals:n,unreadCompletionTabIds:s,favoriteTabIds:o,detachedTerminals:l,editingTab:W,editInputRef:F,onClose:()=>q(!1),onSelectTab:T=>{d(T),q(!1)},onCreateTab:()=>{f(),q(!1)},onBeginRename:Q,onCloseTerminals:T=>{p(T),q(!1)},onCommitRename:X,onCancelRename:()=>H(null),onRenameChange:(T,O)=>H({tabId:T,title:O}),onToggleFavorite:R,onOpenFavorites:L,onReattachTerminal:T=>{b?.(T),q(!1)},onDeleteTerminal:T=>{I(T),q(!1)}}):null,Y?u.jsx(QP,{terminal:Y,onCancel:()=>I(null),onConfirm:()=>{_?.(Y.id),I(null)}}):null]})}function GP({tab:e,active:t,editing:n,title:s,paneCount:o,canClose:l,editValue:d,editInputRef:f,activity:m,unread:p,favorite:b,onSelect:_,onBeginRename:S,onCloseAll:w,onCommitRename:x,onCancelRename:R,onRenameChange:L,onToggleFavorite:A}){const{attributes:W,listeners:H,setNodeRef:U,transform:q,isDragging:Y}=dy({id:`tab-${e.id}`,data:{kind:"tab",tabId:e.id,terminalId:e.activeTerminalId},disabled:n}),I={transform:Oa.Translate.toString(q),opacity:Y?.4:void 0,zIndex:Y?2:void 0};return u.jsxs("div",{ref:U,className:"terminal-tab","data-active":t,"data-dragging":Y,"data-unread":p?"true":void 0,style:I,...W,...H,children:[m?u.jsx("span",{className:"terminal-tab-status-dot","data-activity":m.state,"aria-hidden":"true",title:oS(m)}):null,n&&f&&d!==null?u.jsxs("form",{className:"terminal-tab-editor",onSubmit:F=>{F.preventDefault(),x()},children:[u.jsx("input",{ref:f,"aria-label":`Rename ${s}`,value:d,onBlur:x,onChange:F=>L(F.target.value),onKeyDown:F=>{if(F.key==="Enter"){F.preventDefault(),x();return}F.key==="Escape"&&(F.preventDefault(),R())}}),u.jsx("small",{children:o})]}):u.jsxs("button",{type:"button",className:"terminal-tab-select","aria-label":`Select ${s}`,title:s,onClick:_,onDoubleClick:F=>{F.preventDefault(),S()},children:[u.jsx("span",{children:s}),u.jsx("small",{title:`${o} pane${o===1?"":"s"}`,children:o})]}),n?null:u.jsx("button",{type:"button",className:"terminal-tab-favorite","aria-label":b?`Remove ${s} from favorites`:`Add ${s} to favorites`,title:b?"Remove from favorites":"Add to favorites",onPointerDown:F=>F.stopPropagation(),onClick:F=>{F.stopPropagation(),A()},children:b?"★":"☆"}),l&&!n?u.jsx("button",{type:"button",className:"icon-button","aria-label":`Close ${s}`,title:`Close ${s}`,onPointerDown:F=>F.stopPropagation(),onClick:F=>{F.stopPropagation(),w()},children:"x"}):null]})}function XP({tabs:e,activeTabId:t,terminals:n,unreadCompletionTabIds:s,favoriteTabIds:o,detachedTerminals:l,editingTab:d,editInputRef:f,onClose:m,onSelectTab:p,onCreateTab:b,onBeginRename:_,onCloseTerminals:S,onCommitRename:w,onCancelRename:x,onRenameChange:R,onToggleFavorite:L,onOpenFavorites:A,onReattachTerminal:W,onDeleteTerminal:H}){const U=v.useRef(null);return v.useEffect(()=>{U.current?.scrollIntoView?.({block:"nearest"})},[t]),u.jsx("div",{className:"mobile-tab-sheet-backdrop",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-tab-sheet-title",onClick:m,children:u.jsxs("section",{className:"mobile-tab-sheet",onClick:q=>q.stopPropagation(),children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("strong",{id:"mobile-tab-sheet-title",children:"Switch Tabs"}),u.jsxs("small",{children:[e.length," open"]})]}),u.jsxs("div",{className:"mobile-tab-sheet-header-actions",children:[u.jsx("button",{type:"button","aria-label":"New tab",title:"New tab",onClick:b,children:"+"}),u.jsx("button",{type:"button","aria-label":"Open favorite tabs",title:"Favorite tabs",onClick:()=>{m(),A?.()},children:"★"}),u.jsx("button",{type:"button","aria-label":"Close tab switcher",title:"Close",onClick:m,children:"×"})]})]}),u.jsxs("div",{className:"mobile-tab-sheet-list",children:[e.map((q,Y)=>{const I=Dl(q),F=Bp(q),de=qb(q,n),me=q.id===t,K=d?.tabId===q.id,te=Kb(q,n),J=s?.has(q.id)??!1,Q=o?.has(q.id)??!1;return u.jsxs("div",{ref:me?U:null,className:"mobile-tab-sheet-row","data-active":me,"data-unread":J?"true":void 0,children:[K&&d?u.jsx("form",{className:"mobile-tab-sheet-editor",onSubmit:X=>{X.preventDefault(),w()},children:u.jsx("input",{ref:f,"aria-label":`Rename ${de}`,value:d.title,onBlur:w,onChange:X=>R(q.id,X.target.value),onKeyDown:X=>{if(X.key==="Enter"){X.preventDefault(),w();return}X.key==="Escape"&&(X.preventDefault(),x())}})}):u.jsxs("button",{type:"button",className:"mobile-tab-sheet-select","aria-label":`Switch to ${de}`,onClick:()=>p(q.id),children:[u.jsx("span",{className:"mobile-tab-sheet-index",children:Y+1}),u.jsxs("span",{className:"mobile-tab-sheet-copy",children:[u.jsx("strong",{children:de}),u.jsx("small",{children:VP(q,n,F,te)})]}),u.jsxs("span",{className:"mobile-tab-sheet-meta",children:[te?u.jsx("span",{className:"terminal-tab-status-dot","data-activity":te.state,"aria-hidden":"true",title:oS(te)}):null,u.jsx("span",{children:F})]})]}),u.jsxs("div",{className:"mobile-tab-sheet-actions",children:[K?u.jsx("button",{type:"button","aria-label":`Done renaming ${de}`,onClick:w,children:"Done"}):u.jsx("button",{type:"button","aria-label":`Rename ${de}`,onClick:()=>_(q.id,de),children:"Rename"}),K?null:u.jsx("button",{type:"button","aria-label":Q?`Remove ${de} from favorites`:`Add ${de} to favorites`,title:Q?"Remove from favorites":"Add to favorites",onClick:()=>L?.(q),children:Q?"★":"☆"}),e.length>1?u.jsx("button",{type:"button",className:"mobile-tab-sheet-close","aria-label":`Close ${de}`,onClick:()=>S(I),children:"×"}):null]})]},q.id)}),(l?.length??0)>0?u.jsxs("div",{className:"mobile-tab-sheet-detached","aria-label":"Detached terminals",children:[u.jsx("span",{children:"Detached"}),(l??[]).map(q=>{const Y=q.title||q.cwd||q.id.slice(0,8);return u.jsxs("div",{className:"mobile-tab-sheet-row mobile-tab-sheet-row-detached",children:[u.jsxs("button",{type:"button",className:"mobile-tab-sheet-select","aria-label":`Re-open ${Y}`,onClick:()=>W(q.id),children:[u.jsx("span",{className:"mobile-tab-sheet-index",children:"+"}),u.jsxs("span",{className:"mobile-tab-sheet-copy",children:[u.jsx("strong",{children:Y}),u.jsx("small",{children:q.cwd})]}),u.jsx("span",{className:"mobile-tab-sheet-type",children:"detached"})]}),u.jsx("div",{className:"mobile-tab-sheet-actions",children:u.jsx("button",{type:"button",className:"mobile-tab-sheet-close","aria-label":`Delete ${Y}`,onClick:()=>H(q),children:"×"})})]},q.id)})]}):null]})]})})}function PC({index:e}){const{setNodeRef:t,isOver:n}=Vp({id:`tab-position-${e}`,data:{kind:"tab-position",index:e}});return u.jsx("div",{ref:t,className:"terminal-tab-drop-slot","data-over":n,"aria-hidden":"true"})}function ZP({terminal:e,onReattach:t,onDelete:n}){const s=e.title||e.cwd||e.id.slice(0,8),o=`${e.title||"Terminal"}
58
+ ${e.cwd}
59
+ (detached — click to re-open, × to delete)`;return u.jsxs("span",{className:"terminal-detached-pill",title:o,children:[u.jsx("button",{type:"button",className:"terminal-detached-pill-open","aria-label":`Re-open ${s}`,onClick:t,children:s}),u.jsx("button",{type:"button",className:"terminal-detached-pill-delete","aria-label":`Delete ${s}`,title:`Delete ${s} — this destroys the underlying shell session.`,onClick:l=>{l.stopPropagation(),n()},children:"×"})]})}function QP({terminal:e,onCancel:t,onConfirm:n}){const s=e.title||e.cwd||e.id.slice(0,8);return u.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"delete-terminal-title",onClick:t,children:u.jsxs("div",{className:"security-panel terminal-delete-dialog",onClick:o=>o.stopPropagation(),children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsx("h2",{id:"delete-terminal-title",children:"Delete Terminal"}),u.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:t,children:"×"})]}),u.jsxs("section",{className:"terminal-delete-dialog-body",children:[u.jsx("p",{children:"Delete this terminal?"}),u.jsx("span",{children:s}),u.jsx("small",{children:"The shell session and scrollback will be destroyed."})]}),u.jsxs("div",{className:"terminal-delete-dialog-actions",children:[u.jsx("button",{type:"button",className:"secondary-button",onClick:t,children:"Cancel"}),u.jsx("button",{type:"button",className:"terminal-delete-confirm",onClick:n,children:"Delete"})]})]})})}const JP="nonce-v1",zC=512,Kv=3e4,qv=1e4;function ez(e){if(e.length>zC||new TextEncoder().encode(e).byteLength>zC)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t;return Object.keys(n).length!==3||!Object.hasOwn(n,"type")||!Object.hasOwn(n,"version")||!Object.hasOwn(n,"nonce")||!["activity.ping","activity.pong"].includes(n.type)||n.version!==1||typeof n.nonce!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(n.nonce)?null:n}catch{return null}}const tz=1024*1024,nz=1e3,iz=5e3,rz=1e3;function sz(e,t,n,s={...typeof document>"u"?{}:{document},...typeof window>"u"?{}:{window}},o){const l=s.now??Date.now,d=s.document,f=s.window;let m=!1,p=!1,b="",_=0,S=0,w=!1,x=d?.visibilityState==="hidden",R,L,A,W,H=0,U=0,q=0,Y,I=l(),F=-1/0;const de=[],me=()=>!w&&d?.visibilityState!=="hidden",K=ve=>!m&&R===ve,te=(ve,Fe)=>!ve.ready&&Fe>=ve.handshakeUntil||ve.pending!==void 0&&Fe>=ve.pending.until,J=()=>{clearTimeout(A),A=void 0},Q=()=>{clearTimeout(W),W=void 0},X=()=>{for(const ve of de.splice(0))ve()},M=ve=>Math.min(3e4,1e3*2**Math.min(ve,5)),T=()=>{m||p||L!==void 0||(L=setTimeout(()=>{L=void 0,ze()},M(H++)))},O=ve=>{p&&(b=ve,S=l()+M(_++));try{o?.(ve)}catch{}},re=(ve,Fe=1e3,Ie="activity reconnect",j=!1,ge=!0)=>{if(R===ve){if(R=void 0,ve.pending=void 0,J(),Q(),ve.socket.onmessage=null,ve.socket.onerror=null,ve.socket.onclose=null,j&&(m=!0,clearTimeout(L),L=void 0,X()),ge)try{ve.socket.close(Fe,Ie)}catch{}j||T()}},he=()=>{A!==void 0||m||!R||!me()||(A=setTimeout(()=>{A=void 0,Z()},nz))},N=ve=>{if(!K(ve)||!ve.ready||!ve.probes||ve.pending||!me())return;if(ve.socket.readyState!==1||ve.socket.bufferedAmount>512){re(ve);return}const Fe=`${ve.generation}-${++q}`;ve.pending={nonce:Fe,until:l()+qv},ve.nextProbeAt=l()+Kv;const Ie={type:"activity.ping",version:1,nonce:Fe};try{ve.socket.send(JSON.stringify(Ie))}catch{re(ve)}},V=(ve=!1)=>{if(m||!me())return;if(I=l(),F=I,p){O(b);return}const Fe=R;Fe&&(Fe.pending=void 0,Fe.ready?Fe.probes?N(Fe):re(Fe):((ve||!Number.isFinite(Fe.handshakeUntil))&&(Fe.handshakeUntil=I+qv),Fe.resumeProbe=!0),he())},se=()=>{const ve=l();return ve>=I&&ve-I<=iz?!1:(Q(),V(!0),!0)},Z=()=>{if(m||!me()||!R)return;se(),I=l();const ve=R;ve&&(te(ve,I)?re(ve):ve.ready&&I>=ve.nextProbeAt&&N(ve),he())},Ee=()=>{if(m||!me()||W!==void 0||!p&&l()>=F&&l()-F<rz)return;const ve=p?Math.min(3e4,Math.max(0,S-l())):0;W=setTimeout(()=>{W=void 0,V()},ve)},ye=()=>{R&&(R.pending=void 0,R.ready||(R.handshakeUntil=1/0)),J(),Q(),F=-1/0},ze=()=>{if(m||p)return;const ve=Y;let Fe;try{const Ae=new URL(e);ve&&Ae.searchParams.set("cursor",ve),Fe=t(Ae.toString())}catch{T();return}const Ie={socket:Fe,generation:++U,ready:!1,probes:!1,handshakeUntil:me()?l()+qv:1/0,nextProbeAt:1/0,pending:void 0,resumeProbe:!1};R=Ie,I=l();let j=ve!==void 0,ge=!1;Fe.onmessage=Ae=>{if(K(Ie)&&(me()&&se(),!!K(Ie))){if(me()&&te(Ie,l())){re(Ie);return}try{if(typeof Ae.data!="string"||Ae.data.length>tz)throw new Error("invalid activity frame");const Oe=JSON.parse(Ae.data);if(Oe?.type==="activity.pong"){const z=ez(Ae.data);if(!Ie.ready||!Ie.probes||!z)throw new Error("invalid activity probe");me()&&Ie.pending?.nonce===z.nonce&&(Ie.pending=void 0,Ie.nextProbeAt=l()+Kv);return}if(Oe?.type==="activity.ready"){if(Ie.ready||Oe.version!==1||!HC(Oe.cursor)||!["snapshot","resume","gap"].includes(Oe.mode)||(Oe.mode==="resume"?!ve:!ge))throw new Error("invalid activity acknowledgement");Y=Oe.cursor,Ie.ready=!0,Ie.probes=Oe.probe===JP,Ie.nextProbeAt=l()+Kv,j=!0,H=0,Ie.resumeProbe&&N(Ie),he();return}if(!oz(Oe)||!j&&!Oe.initial)throw new Error("invalid activity snapshot");if(Oe.initial)ge=!0;else if(!HC(Oe.cursor))throw new Error("activity cursor required");j=!0,n(Oe),(Ie.ready||!ge&&ve)&&(Y=Oe.cursor)}catch{re(Ie,1e3,"invalid activity message",!0)}}},Fe.onerror=()=>{K(Ie)&&(re(Ie),Ie.ready||O("activity handshake failed"))},Fe.onclose=Ae=>{if(!K(Ie))return;const Oe=Ae.code===1008&&az(Ae.reason);Oe&&(p=!0),re(Ie,Ae.code,"",Ae.code===1008&&!Oe,!1),Oe?O(Ae.reason):Ae.code!==1008&&!Ie.ready&&O("activity handshake failed")},he()},Ke=(ve,Fe,Ie)=>{ve?.addEventListener(Fe,Ie),de.push(()=>ve?.removeEventListener(Fe,Ie))};Ke(d,"visibilitychange",()=>{const ve=x;x=d?.visibilityState==="hidden",x?ye():ve&&Ee()}),Ke(d,"freeze",()=>{w=!0,ye()}),Ke(d,"resume",()=>{w=!1,Ee()}),Ke(f,"pagehide",()=>{w=!0,ye()}),Ke(f,"pageshow",ve=>{const Fe=w;w=!1,(Fe||ve.persisted)&&Ee()}),Ke(f,"offline",()=>{F=-1/0}),Ke(f,"online",Ee),ze();const Be=()=>{m=!0,clearTimeout(L),L=void 0,J(),Q(),X(),R&&re(R,1e3,"activity disposed",!0)};return Be.reauthenticate=()=>{m||!p||(Q(),p=!1,b="",_=0,S=0,T())},Be}function az(e){return["unauthorized","session expired","session revoked","authentication no longer valid"].includes(e?.trim().toLowerCase()??"")}function HC(e){return typeof e=="string"&&e.length<=128&&/^[a-f0-9-]+:\d+$/.test(e)}function oz(e){const t=e;return!!t&&t.type==="activity"&&t.version===1&&typeof t.initial=="boolean"&&(t.agentId===null||typeof t.agentId=="string"&&t.agentId.length>0&&t.agentId.length<=256)&&Array.isArray(t.terminals)&&t.terminals.length<=2048&&t.terminals.every(n=>n&&typeof n.id=="string"&&n.id.length>0&&n.id.length<=256&&typeof n.title=="string"&&typeof n.cwd=="string"&&["running","exited"].includes(n.status))}let UC=0,ep;const Vb=new Set;let ch;function lz(e){return Vb.add(e),ch!==void 0&&e(ch),()=>{Vb.delete(e)}}function cz(){ch=void 0,ep?.reauthenticate()}function uz(e=!0){v.useEffect(()=>{if(e){if(UC++===0){const t=new URL("/api/activity/ws",window.location.href);t.protocol=t.protocol==="https:"?"wss:":"ws:",ep=hz(t.toString(),void 0,void 0,n=>{ch=n;for(const s of Vb)s(n)})}return()=>{--UC===0&&(ep?.(),ep=void 0,ch=void 0)}}},[e])}function dz(e){for(const t of e.terminals){const n=gt(e.agentId).state.terminals[t.id];e.initial&&n&&Date.parse(t.updatedAt)<Date.parse(n.updatedAt)||Ed(e.agentId,{type:"terminal.updated",terminal:t,notifyCompletion:!e.initial})}}function hz(e,t=o=>new WebSocket(o),n=dz,s){return sz(e,t,n,void 0,s)}function G2(e,t,n){const s=e.slice();return s.splice(n<0?s.length+n:n,0,s.splice(t,1)[0]),s}function fz(e,t){return e.reduce((n,s,o)=>{const l=t.get(s);return l&&(n[o]=l),n},Array(e.length))}function Pf(e){return e!==null&&e>=0}function pz(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function mz(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const lS=e=>{let{rects:t,activeIndex:n,overIndex:s,index:o}=e;const l=G2(t,s,n),d=t[o],f=l[o];return!f||!d?null:{x:f.left-d.left,y:f.top-d.top,scaleX:f.width/d.width,scaleY:f.height/d.height}},zf={scaleX:1,scaleY:1},gz=e=>{var t;let{activeIndex:n,activeNodeRect:s,index:o,rects:l,overIndex:d}=e;const f=(t=l[n])!=null?t:s;if(!f)return null;if(o===n){const p=l[d];return p?{x:0,y:n<d?p.top+p.height-(f.top+f.height):p.top-f.top,...zf}:null}const m=vz(l,o,n);return o>n&&o<=d?{x:0,y:-f.height-m,...zf}:o<n&&o>=d?{x:0,y:f.height+m,...zf}:{x:0,y:0,...zf}};function vz(e,t,n){const s=e[t],o=e[t-1],l=e[t+1];return s?n<t?o?s.top-(o.top+o.height):l?l.top-(s.top+s.height):0:l?l.top-(s.top+s.height):o?s.top-(o.top+o.height):0:0}const X2="Sortable",Z2=zt.createContext({activeIndex:-1,containerId:X2,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:lS,disabled:{draggable:!1,droppable:!1}});function _z(e){let{children:t,id:n,items:s,strategy:o=lS,disabled:l=!1}=e;const{active:d,dragOverlay:f,droppableRects:m,over:p,measureDroppableContainers:b}=kk(),_=hh(X2,n),S=f.rect!==null,w=v.useMemo(()=>s.map(Y=>typeof Y=="object"&&"id"in Y?Y.id:Y),[s]),x=d!=null,R=d?w.indexOf(d.id):-1,L=p?w.indexOf(p.id):-1,A=v.useRef(w),W=!pz(w,A.current),H=L!==-1&&R===-1||W,U=mz(l);fs(()=>{W&&x&&b(w)},[W,w,x,b]),v.useEffect(()=>{A.current=w},[w]);const q=v.useMemo(()=>({activeIndex:R,containerId:_,disabled:U,disableTransforms:H,items:w,overIndex:L,useDragOverlay:S,sortedRects:fz(w,m),strategy:o}),[R,_,U.draggable,U.droppable,H,w,L,m,S,o]);return zt.createElement(Z2.Provider,{value:q},t)}const bz=e=>{let{id:t,items:n,activeIndex:s,overIndex:o}=e;return G2(n,s,o).indexOf(t)},yz=e=>{let{containerId:t,isSorting:n,wasDragging:s,index:o,items:l,newIndex:d,previousItems:f,previousContainerId:m,transition:p}=e;return!p||!s||f!==l&&o===d?!1:n?!0:d!==o&&t===m},Sz={duration:200,easing:"ease"},Q2="transform",wz=Oa.Transition.toString({property:Q2,duration:0,easing:"linear"}),xz={roleDescription:"sortable"};function Cz(e){let{disabled:t,index:n,node:s,rect:o}=e;const[l,d]=v.useState(null),f=v.useRef(n);return fs(()=>{if(!t&&n!==f.current&&s.current){const m=o.current;if(m){const p=su(s.current,{ignoreTransform:!0}),b={x:m.left-p.left,y:m.top-p.top,scaleX:m.width/p.width,scaleY:m.height/p.height};(b.x||b.y)&&d(b)}}n!==f.current&&(f.current=n)},[t,n,s,o]),v.useEffect(()=>{l&&d(null)},[l]),l}function kz(e){let{animateLayoutChanges:t=yz,attributes:n,disabled:s,data:o,getNewIndex:l=bz,id:d,strategy:f,resizeObserverConfig:m,transition:p=Sz}=e;const{items:b,containerId:_,activeIndex:S,disabled:w,disableTransforms:x,sortedRects:R,overIndex:L,useDragOverlay:A,strategy:W}=v.useContext(Z2),H=Tz(s,w),U=b.indexOf(d),q=v.useMemo(()=>({sortable:{containerId:_,index:U,items:b},...o}),[_,o,U,b]),Y=v.useMemo(()=>b.slice(b.indexOf(d)),[b,d]),{rect:I,node:F,isOver:de,setNodeRef:me}=Vp({id:d,data:q,disabled:H.droppable,resizeObserverConfig:{updateMeasurementsFor:Y,...m}}),{active:K,activatorEvent:te,activeNodeRect:J,attributes:Q,setNodeRef:X,listeners:M,isDragging:T,over:O,setActivatorNodeRef:re,transform:he}=dy({id:d,data:q,attributes:{...xz,...n},disabled:H.draggable}),N=ON(me,X),V=!!K,se=V&&!x&&Pf(S)&&Pf(L),Z=!A&&T,Ee=Z&&se?he:null,ze=se?Ee??(f??W)({rects:R,activeNodeRect:J,activeIndex:S,overIndex:L,index:U}):null,Ke=Pf(S)&&Pf(L)?l({id:d,items:b,activeIndex:S,overIndex:L}):U,Be=K?.id,ve=v.useRef({activeId:Be,items:b,newIndex:Ke,containerId:_}),Fe=b!==ve.current.items,Ie=t({active:K,containerId:_,isDragging:T,isSorting:V,id:d,index:U,items:b,newIndex:ve.current.newIndex,previousItems:ve.current.items,previousContainerId:ve.current.containerId,transition:p,wasDragging:ve.current.activeId!=null}),j=Cz({disabled:!Ie,index:U,node:F,rect:I});return v.useEffect(()=>{V&&ve.current.newIndex!==Ke&&(ve.current.newIndex=Ke),_!==ve.current.containerId&&(ve.current.containerId=_),b!==ve.current.items&&(ve.current.items=b)},[V,Ke,_,b]),v.useEffect(()=>{if(Be===ve.current.activeId)return;if(Be!=null&&ve.current.activeId==null){ve.current.activeId=Be;return}const Ae=setTimeout(()=>{ve.current.activeId=Be},50);return()=>clearTimeout(Ae)},[Be]),{active:K,activeIndex:S,attributes:Q,data:q,rect:I,index:U,newIndex:Ke,items:b,isOver:de,isSorting:V,isDragging:T,listeners:M,node:F,overIndex:L,over:O,setNodeRef:N,setActivatorNodeRef:re,setDroppableNodeRef:me,setDraggableNodeRef:X,transform:j??ze,transition:ge()};function ge(){if(j||Fe&&ve.current.newIndex===U)return wz;if(!(Z&&!Wp(te)||!p)&&(V||Ie))return Oa.Transition.toString({...p,property:Q2})}}function Tz(e,t){var n,s;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(n=e?.draggable)!=null?n:t.draggable,droppable:(s=e?.droppable)!=null?s:t.droppable}}Gt.Down,Gt.Right,Gt.Up,Gt.Left;function Ez({favorites:e,unavailableFavoriteIds:t,busy:n=!1,error:s=null,getRuntimeStatus:o,onClose:l,onOpen:d,onRemove:f,onReorder:m}){const p=v.useRef(null),[b,_]=v.useState(()=>Date.now()),[S,w]=v.useState("grid"),[x,R]=v.useState(null),L=ak(up(ly,{activationConstraint:{distance:6}}),up(cy,{activationConstraint:{delay:180,tolerance:8}})),A=v.useMemo(()=>e.map(ds),[e]),W=v.useMemo(()=>new Map(e.map(I=>[ds(I),o?.(I)??null])),[e,o,b]);v.useEffect(()=>{const I=window.setInterval(()=>_(Date.now()),3e4);return()=>window.clearInterval(I)},[]),v.useEffect(()=>{const I=F=>{if(F.key==="Escape"){F.preventDefault(),F.stopImmediatePropagation(),l();return}const de=F.target;if((de instanceof HTMLInputElement||de instanceof HTMLTextAreaElement)&&p.current?.contains(de)||F.ctrlKey||F.altKey||F.metaKey)return;const me=Number.parseInt(F.key,10)-1;me>=0&&me<Math.min(9,e.length)&&(F.preventDefault(),F.stopImmediatePropagation(),d(e[me]))};return window.addEventListener("keydown",I,!0),()=>window.removeEventListener("keydown",I,!0)},[e,l,d]);const H=I=>{R(null);const F=String(I.active.id),de=I.over?String(I.over.id):null;if(!de||F===de)return;const me=e.find(te=>ds(te)===F),K=e.find(te=>ds(te)===de);me&&K&&m(me,K)},U=I=>R({activeId:String(I.active.id),overId:null}),q=I=>{const F=String(I.active.id),de=I.over?String(I.over.id):null;R(me=>me?.activeId===F&&me.overId===de?me:{activeId:F,overId:de})},Y=x?e.find(I=>ds(I)===x.activeId)??null:null;return u.jsx("div",{className:"favorite-tabs-backdrop",role:"dialog","aria-modal":"true","aria-labelledby":"favorite-tabs-title",onClick:l,children:u.jsxs("section",{ref:p,className:"favorite-tabs-dialog",onClick:I=>I.stopPropagation(),children:[u.jsxs("header",{className:"favorite-tabs-header",children:[u.jsxs("div",{children:[u.jsxs("h2",{id:"favorite-tabs-title",children:["Favorite Tabs ",u.jsx("span",{children:e.length})]}),u.jsx("p",{children:"Press 1–9 to open a favorite"})]}),u.jsxs("div",{className:"favorite-tabs-actions",role:"group","aria-label":"Favorite tab view",children:[u.jsx("button",{type:"button",className:"favorite-tabs-view","aria-label":"Grid view",title:"Grid view","aria-pressed":S==="grid",onClick:()=>w("grid"),children:"▦"}),u.jsx("button",{type:"button",className:"favorite-tabs-view","aria-label":"List view",title:"List view","aria-pressed":S==="list",onClick:()=>w("list"),children:"☷"}),u.jsx("button",{type:"button","aria-label":"Close favorite tabs",title:"Close",onClick:l,children:"×"})]})]}),u.jsxs(Ck,{sensors:L,collisionDetection:eD,onDragStart:U,onDragOver:q,onDragEnd:H,onDragCancel:()=>R(null),children:[u.jsxs("div",{className:"favorite-tabs-list","data-view":S,children:[s?u.jsx("p",{className:"favorite-tabs-error",role:"alert",children:s}):null,e.length===0?u.jsx("p",{className:"favorite-tabs-empty",children:"Star a tab to keep it close."}):u.jsx(_z,{items:A,strategy:S==="grid"?lS:gz,children:e.map((I,F)=>u.jsx(Rz,{favorite:I,index:F,busy:n,unavailable:t?.has(ds(I))??!1,runtimeStatus:W.get(ds(I))??null,now:b,isDropTarget:x?.overId===ds(I)&&x.activeId!==ds(I),onOpen:d,onRemove:f},ds(I)))})]}),u.jsx(lM,{dropAnimation:{duration:120,easing:"cubic-bezier(0.2, 0, 0, 1)"},children:Y?u.jsx(Nz,{favorite:Y}):null})]})]})})}const Rz=v.memo(function({favorite:t,index:n,busy:s,unavailable:o,runtimeStatus:l,now:d,isDropTarget:f,onOpen:m,onRemove:p}){const b=ds(t),{attributes:_,listeners:S,setActivatorNodeRef:w,setNodeRef:x,transform:R,transition:L,isDragging:A}=kz({id:b,disabled:s,transition:{duration:100,easing:"cubic-bezier(0.2, 0, 0, 1)"}}),W={transform:Oa.Transform.toString(R),transition:L,zIndex:A?1:void 0,opacity:A?.16:void 0};return u.jsxs("div",{ref:x,className:"favorite-tab-row","data-dragging":A||void 0,"data-drop-target":f||void 0,style:W,children:[u.jsx("button",{ref:w,type:"button",className:"favorite-tab-drag","aria-label":`Reorder favorite ${n+1}`,title:"Drag to reorder",onClick:H=>H.stopPropagation(),..._,...S,children:"⋮⋮"}),u.jsxs("button",{type:"button",className:"favorite-tab-open",onClick:()=>m(t),disabled:s||o,title:o?"Server is no longer registered":void 0,children:[u.jsx("span",{className:"favorite-tab-index",children:n<9?n+1:"·"}),u.jsxs("span",{className:"favorite-tab-copy",children:[u.jsx("strong",{children:t.tabName}),u.jsx("small",{children:o?"Unavailable server":`${t.serverName} › ${t.workspaceName}${t.cwd?` · ${t.cwd}`:""}`}),l&&!o?u.jsxs("small",{className:`favorite-tab-runtime favorite-tab-runtime--${l.state}`,title:"Last observed terminal status",children:[u.jsx("i",{"aria-hidden":"true"}),Dz(l.state),l.lastActivityAt?` · ${Mz(l.lastActivityAt,d)}`:""]}):null,l?.unread&&!o?u.jsxs("small",{className:"favorite-tab-runtime favorite-tab-runtime--unread",title:"Unread completion",children:[u.jsx("i",{"aria-hidden":"true"}),"Unread"]}):null]}),u.jsxs("span",{className:"favorite-tab-providers","aria-label":t.providers.length?`Contains ${t.providers.join(" and ")}`:void 0,children:[t.providers.map(H=>u.jsx("img",{src:`/brand/${H}.webp`,alt:"","aria-hidden":"true"},H)),u.jsx("em",{children:t.paneCount})]})]}),u.jsx("button",{type:"button",className:"favorite-tab-remove","aria-label":`Remove ${t.tabName} from favorites`,title:"Remove from favorites",disabled:s,onClick:()=>p(t),children:"×"})]})}),Nz=v.memo(function({favorite:t}){return u.jsxs("div",{className:"favorite-tab-drag-preview","aria-hidden":"true",children:[u.jsx("span",{className:"favorite-tab-index",children:"★"}),u.jsxs("span",{className:"favorite-tab-copy",children:[u.jsx("strong",{children:t.tabName}),u.jsxs("small",{children:[t.serverName," › ",t.workspaceName]})]}),u.jsxs("span",{className:"favorite-tab-providers",children:[t.providers.map(n=>u.jsx("img",{src:`/brand/${n}.webp`,alt:""},n)),u.jsx("em",{children:t.paneCount})]})]})});function ds(e){return JSON.stringify([e.serverId,e.workspaceId,e.tabId])}function Dz(e){return e==="working"?"Working":e==="done"?"Done":e==="stopped"?"Stopped":e==="exited"?"Exited":"Idle"}function Mz(e,t){const n=Date.parse(e);if(!Number.isFinite(n))return"recently";const s=Math.max(0,Math.floor((t-n)/1e3));if(s<60)return"now";const o=Math.floor(s/60);if(o<60)return`${o}m ago`;const l=Math.floor(o/60);return l<24?`${l}h ago`:`${Math.floor(l/24)}d ago`}function Az({uploads:e,onDismiss:t,onDismissAll:n,onRetry:s,onCancel:o}){if(e.length===0)return null;const d=e.some(m=>m.status==="failed"||m.status==="partial")?"alert":"status",f=e.filter(m=>m.status==="queued"||m.status==="uploading").length;return u.jsxs("aside",{className:`upload-toast upload-toast-${Iz(e)}`,role:d,"aria-live":d==="alert"?"assertive":"polite",children:[u.jsxs("header",{className:"upload-toast-header",children:[u.jsx("strong",{children:e.length===1?tp(e[0]):`Uploads ${f>0?`(${f} active)`:`(${e.length})`}`}),u.jsx("button",{type:"button","aria-label":"Dismiss upload status",onClick:n,children:"x"})]}),u.jsx("div",{className:"upload-toast-body upload-queue-body",children:e.map(m=>u.jsx(Lz,{upload:m,compact:e.length>1,onDismiss:()=>t(m.id),onRetry:()=>s(m.id),onCancel:()=>o(m.id)},m.id))})]})}function Lz({upload:e,compact:t,onDismiss:n,onRetry:s,onCancel:o}){const l="response"in e?e.response:void 0,d=e.status==="failed"||e.status==="partial",f=e.status==="queued"||e.status==="uploading";return u.jsxs("section",{className:"upload-queue-item","data-status":e.status,"aria-label":tp(e),children:[u.jsxs("div",{className:"upload-queue-item-header",children:[u.jsx("strong",{children:tp(e)}),u.jsxs("div",{className:"upload-queue-actions",children:[f?u.jsx("button",{type:"button",onClick:o,children:"Cancel"}):null,d?u.jsx("button",{type:"button",onClick:s,children:"Retry"}):null,u.jsx("button",{type:"button","aria-label":`Dismiss ${tp(e)}`,onClick:n,children:"x"})]})]}),e.status==="queued"?u.jsx("p",{children:e.message??"Queued"}):null,e.status==="uploading"?u.jsx(jz,{toast:e}):null,l&&"message"in e&&e.message?u.jsx("p",{className:"upload-toast-muted",children:e.message}):null,l?u.jsx(Oz,{response:l,compact:t}):null,e.status==="failed"&&!l&&e.message?u.jsx("p",{children:e.message}):null]})}function jz({toast:e}){const t=e.percent===null?Pz(e.loaded):`${e.percent}%`;return u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"upload-progress-row",children:[u.jsxs("span",{children:[e.fileCount," file",e.fileCount===1?"":"s"]}),u.jsx("span",{children:t})]}),u.jsx("div",{className:"upload-progress-track","aria-hidden":"true",children:u.jsx("span",{style:{width:e.percent===null?"100%":`${e.percent}%`}})})]})}function Oz({response:e,compact:t}){const n=e.results.filter(d=>d.status==="failed"),s=e.results.filter(d=>d.status==="uploaded"),o=t?3:6,l=[...n,...s].slice(0,o);return u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"upload-toast-destination",children:e.destinationCwd}),l.length>0?u.jsx("ul",{className:"upload-result-list",children:l.map((d,f)=>u.jsx(Bz,{result:d},`${d.relativePath}-${f}`))}):null,e.results.length>l.length?u.jsxs("p",{className:"upload-toast-muted",children:["+",e.results.length-l.length," more"]}):null]})}function Bz({result:e}){const t=e.savedRelativePath??e.relativePath,n=e.status==="uploaded"&&e.savedRelativePath!==void 0&&e.savedRelativePath!==e.relativePath;return u.jsxs("li",{"data-status":e.status,children:[u.jsx("span",{className:"upload-result-path",children:t}),n?u.jsx("span",{className:"upload-result-renamed",children:"renamed"}):null,e.status==="failed"&&e.error?u.jsx("span",{className:"upload-result-error",children:e.error}):null]})}function tp(e){if(e.status==="queued")return"Preparing upload";if(e.status==="uploading")return`Uploading ${e.fileCount} file${e.fileCount===1?"":"s"}`;if(e.status==="success"){const t=e.response?.uploaded??e.fileCount;return`Uploaded ${t} file${t===1?"":"s"}`}if(e.status==="partial"){const t=e.response?.uploaded??0,n=(e.response?.uploaded??0)+(e.response?.failed??0)||e.fileCount;return`Uploaded ${t} of ${n} files`}return"Upload failed"}function Iz(e){return e.some(t=>t.status==="failed")?"failed":e.some(t=>t.status==="partial")?"partial":e.some(t=>t.status==="uploading")?"uploading":e.some(t=>t.status==="queued")?"queued":"success"}function Pz(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${Math.round(e/(1024*1024))} MB`}function zz({toast:e,onActivate:t,onDismiss:n}){if(!e)return null;const s=e,o=s.outcome==="stopped"?"stopped":"finished",l=s.commandName?`${s.commandName} ${o}`:`Command ${o}`;function d(m){m.stopPropagation(),n()}function f(m){m.target===m.currentTarget&&(m.key!=="Enter"&&m.key!==" "||(m.preventDefault(),t(s)))}return u.jsxs("aside",{className:"completion-toast",role:"status","aria-live":"polite",tabIndex:0,onClick:()=>t(s),onKeyDown:f,children:[u.jsxs("header",{className:"completion-toast-header",children:[u.jsxs("div",{className:"completion-toast-copy",children:[u.jsx("strong",{children:s.tabTitle}),u.jsx("span",{children:l})]}),u.jsx("button",{type:"button","aria-label":"Dismiss completion alert",onClick:d,onPointerDown:m=>m.stopPropagation(),children:"x"})]}),u.jsx("video",{className:"completion-toast-character",src:s.assetSrc,muted:!0,autoPlay:!0,loop:!0,playsInline:!0,"aria-hidden":"true"})]})}const Hz=Nd(0,0,1,1),Ta=1e-6;function Uz(e){return J2(e).map(t=>t.terminalId)}function J2(e){return Rd(e,Hz).sort(Kz).map((t,n)=>({...t,index:n+1}))}function $z(e,t,n){const s=J2(e),o=s.find(d=>d.terminalId===t);return o?s.filter(d=>d.terminalId!==t).map(d=>Wz(o,d,n)).filter(d=>d!==null).sort(qz)[0]?.entry.terminalId??null:null}function Fz(e,t){return!Number.isInteger(t)||t<1?null:Uz(e)[t-1]??null}function Rd(e,t){if(e.type==="pane")return[{terminalId:e.terminalId,bounds:t}];if(e.type==="editor")return[];const n=Vz(e.ratio);if(e.direction==="vertical"){const o=t.left+(t.right-t.left)*n;return[...Rd(e.first,Nd(t.left,t.top,o,t.bottom)),...Rd(e.second,Nd(o,t.top,t.right,t.bottom))]}const s=t.top+(t.bottom-t.top)*n;return[...Rd(e.first,Nd(t.left,t.top,t.right,s)),...Rd(e.second,Nd(t.left,s,t.right,t.bottom))]}function Wz(e,t,n){const s=e.bounds,o=t.bounds,l=$C(s.left,s.right,o.left,o.right),d=$C(s.top,s.bottom,o.top,o.bottom);switch(n){case"left":return o.centerX>=s.centerX-Ta||d<=Ta?null:{entry:t,primaryDistance:Math.max(0,s.left-o.right),perpendicularDistance:Math.abs(s.centerY-o.centerY),overlap:d};case"right":return o.centerX<=s.centerX+Ta||d<=Ta?null:{entry:t,primaryDistance:Math.max(0,o.left-s.right),perpendicularDistance:Math.abs(s.centerY-o.centerY),overlap:d};case"up":return o.centerY>=s.centerY-Ta||l<=Ta?null:{entry:t,primaryDistance:Math.max(0,s.top-o.bottom),perpendicularDistance:Math.abs(s.centerX-o.centerX),overlap:l};case"down":return o.centerY<=s.centerY+Ta||l<=Ta?null:{entry:t,primaryDistance:Math.max(0,o.top-s.bottom),perpendicularDistance:Math.abs(s.centerX-o.centerX),overlap:l};default:return null}}function Kz(e,t){return Wc(e.bounds.top,t.bounds.top)||Wc(e.bounds.left,t.bounds.left)}function qz(e,t){return Wc(e.primaryDistance,t.primaryDistance)||Wc(e.perpendicularDistance,t.perpendicularDistance)||Wc(t.overlap,e.overlap)||Wc(e.entry.index,t.entry.index)}function Wc(e,t){const n=e-t;return Math.abs(n)<=Ta?0:n}function $C(e,t,n,s){return Math.max(0,Math.min(t,s)-Math.max(e,n))}function Nd(e,t,n,s){return{left:e,top:t,right:n,bottom:s,centerX:e+(n-e)/2,centerY:t+(s-t)/2}}function Vz(e){return Number.isFinite(e)?Math.min(.9,Math.max(.1,e)):.5}const FC="nterminal.terminalWorkspaces.v2",eR="nterminal.sidebarCollapsed.v1",Yz=75,WC=Ek.map(e=>e.url),Gz=Ek[0].url,Xz=6;function Zz({api:e,serverApi:t,activeAgentId:n=null,onSelectServer:s,sessionExpiresAt:o=null,previewMode:l=!1,onLogout:d=async()=>{},onSessionInvalid:f}){uz();const m=v.useMemo(()=>e??Hp(),[e]),p=v.useMemo(()=>t??Is(null),[t]),b=v.useMemo(()=>_8(n),[n]),_=v.useMemo(()=>C=>K2(n,C),[n]),S=v.useMemo(()=>()=>gt(n),[n]),w=v.useSyncExternalStore(_,S,S),x=w.state,R=w.editors,L=!w.loaded,A=w.error,[W,H]=v.useState(!1),[U,q]=v.useState(()=>k8()),[Y,I]=v.useState("servers"),[F,de]=v.useState(!1),[me,K]=v.useState(!1),[te,J]=v.useState([]),[Q,X]=v.useState(!1),[M,T]=v.useState(null),[O,re]=v.useState(null),[he,N]=v.useState(null),V=v.useMemo(()=>Is(he?.agentId??null),[he?.agentId]),se=v.useMemo(()=>Is(O?.agentId??null),[O?.agentId]),Z=v.useSyncExternalStore(rj,X1,X1);v.useSyncExternalStore(Bd,G1,G1);const[Ee,ye]=v.useState(0),[ze,Ke]=v.useState(null),[Be,ve]=v.useState(()=>[null]),[Fe,Ie]=v.useState(()=>({[Zt]:"Local"})),j=v.useRef(new Set),[ge,Ae]=v.useState(0),[Oe,z]=v.useState(()=>[n]),[fe,Te]=v.useState(()=>new Set),[Ne,Le]=v.useState({}),[be,$e]=v.useState(null),qe=v.useRef(0),je=v.useRef(0),[ht,st]=v.useState(null),[mt,xt]=v.useState(null),on=v.useRef(null),ot=v.useRef(0),Dn=v.useRef(null),Tn=v.useRef(null),ft=v.useRef(null),Dt=v.useRef(null),Mt=v.useRef([]),wi=v.useRef(0),di=v.useRef(!1),xi=v.useRef(0),At=v.useRef(0),ae=v.useRef([]),Pe=v.useRef(null),tt=v.useRef(null),_t=v.useRef(null),$t=v.useRef(!0),[en,Ft]=v.useState(0),mn=v.useRef(()=>{});v.useEffect(()=>($t.current=!0,()=>{$t.current=!1}),[]);const[Bn,Ct]=v.useState(null),ln=ak(up(ly,{activationConstraint:{distance:8}}),up(cy,{activationConstraint:{delay:250,tolerance:5}}));v.useEffect(()=>sj(m),[m]);function cn(C){const E=C.active.data.current;if(E){if(E.kind==="tab"&&typeof E.tabId=="string"&&typeof E.terminalId=="string"){Ct({tabId:E.tabId,terminalId:E.terminalId});return}E.kind==="pane"&&typeof E.sourceTabId=="string"&&typeof E.terminalId=="string"&&Ct({tabId:E.sourceTabId,terminalId:E.terminalId})}}function Kn(C){Ct(null);const E=C.active.data.current,B=C.over?.data.current;if(!(!E||!B||typeof E.terminalId!="string")){if(E.kind==="tab"&&typeof E.tabId=="string"){if(B.kind==="tab-position"&&typeof B.index=="number"){pt({type:"tab.reordered",sourceTabId:E.tabId,targetIndex:B.index});return}if(B.kind==="workspace"&&typeof B.workspaceId=="string"){pt({type:"tab.moved_to_workspace",sourceTabId:E.tabId,targetWorkspaceId:B.workspaceId});return}B.kind==="pane-zone"&&typeof B.terminalId=="string"&&(B.side==="top"||B.side==="right"||B.side==="bottom"||B.side==="left")&&pt({type:"tab.dropped_into_pane",sourceTabId:E.tabId,sourceTerminalId:E.terminalId,targetTerminalId:B.terminalId,side:B.side});return}if(E.kind==="pane"&&typeof E.sourceTabId=="string"){if(B.kind==="tab-position"&&typeof B.index=="number"){pt({type:"terminal.extracted_to_tab",sourceTabId:E.sourceTabId,sourceTerminalId:E.terminalId,targetIndex:B.index});return}if(B.kind==="workspace"&&typeof B.workspaceId=="string"){pt({type:"terminal.extracted_to_workspace",sourceTabId:E.sourceTabId,sourceTerminalId:E.terminalId,targetWorkspaceId:B.workspaceId});return}B.kind==="pane-zone"&&typeof B.terminalId=="string"&&(B.side==="top"||B.side==="right"||B.side==="bottom"||B.side==="left")&&pt({type:"tab.dropped_into_pane",sourceTabId:E.sourceTabId,sourceTerminalId:E.terminalId,targetTerminalId:B.terminalId,side:B.side})}}}function In(){Ct(null)}const rt=x.workspaces.find(C=>C.id===x.activeWorkspaceId)??x.workspaces[0],Tt=rt?.tabs.find(C=>C.id===rt.activeTabId)??rt?.tabs[0],gn=Tt?.activeTerminalId??null,oe=gn?x.terminals[gn]:void 0,ke=p8("(max-width: 760px)"),Ge=v.useMemo(()=>Tt?Pp(Tt.root):[],[Tt]),Je=rt&&Tt?Dd(n,rt.id,Tt.id):null,Ze=Tt?tR(Ge,Tt.activeTerminalId,Je?Ne[Je]:void 0):null,tn=ke&&Ge.length>1;v.useLayoutEffect(()=>{qs.current=n;const C=()=>{if(Bf(void 0),document.visibilityState!=="visible"||!w.loaded||Jo()||!rt||!Tt)return;const E=gt(n);E.generation!==w.generation||E.state!==x||Bf({generation:w.generation,agentId:n,workspaceId:rt.id,tabId:Tt.id,root:Tt.root,terminalIds:CP(Tt.root,tn?Ze:null)})};return C(),document.addEventListener("visibilitychange",C),()=>{document.removeEventListener("visibilitychange",C),Bf(void 0)}},[n,x,w.generation,w.loaded,w.error,rt?.id,Tt?.id,Tt?.root,Tt?.activeTerminalId,ke,Ze,en]);const Sn=v.useMemo(()=>(rt?.detachedTerminalIds??[]).flatMap(C=>{const E=x.terminals[C];return E?[E]:[]}),[rt?.detachedTerminalIds,x.terminals]),Gi=v.useMemo(()=>{const C=new Set;for(const E of rt?.tabs??[])Dl(E).some(B=>w.unreadCompletions.has(B))&&C.add(E.id);return C},[rt?.tabs,w.unreadCompletions]);v.useSyncExternalStore(RP,jC,jC);const[Xt,Xi]=v.useState([]),qn=v.useRef([]),Mn=v.useRef(null),[Ri,Zi]=v.useState(null),[Wt,Ks]=v.useState(null),[dr,Qi]=v.useState([]),[Ni,Yl]=v.useState(()=>Bl()),Ha=v.useRef(0),qs=v.useRef(n),hi=v.useRef(WC),zi=v.useRef(Ni),Vs=v.useRef(()=>{});Vs.current=ea,mn.current=ia;const ni=v.useCallback(async()=>{try{const C=await m.listNotificationAssets();Qi(C.assets.filter(E=>E.enabled).map(E=>E.url))}catch{Qi([])}},[m]),Pn=v.useCallback(C=>{for(const E of C)j.current.add(Rl(E.agentId));Ie(E=>{const B={...E};for(const ee of C)B[Rl(ee.agentId)]=ee.label;return Yv(E,B)?E:B})},[]);v.useEffect(()=>{const C=At.current+1;At.current=C;const E=xi.current;m.getFavorites().then(B=>{C!==At.current||E!==xi.current||(Mi(B.favorites,B.revision),pn(B.favorites,n,x))}).catch(()=>{})},[m]),v.useEffect(()=>{pn(Mt.current,n,x)},[n,Fe]),v.useEffect(()=>{z(C=>C.some(E=>li(E,n))?C:[...C,n])},[n]);const Ys=v.useCallback(C=>{const E=gt(C),B=Is(C);for(const ee of Object.keys(E.state.terminals))kd(B.createWebSocketUrl(ee)),Mf(ee),Cd(ee);FP(C),z(ee=>ee.filter(ie=>!li(ie,C))),Te(ee=>{const ie=`${ip(C)}:`;let le=!1;const we=new Set;for(const Ue of ee){if(Ue.startsWith(ie)){le=!0;continue}we.add(Ue)}return le?we:ee}),Le(ee=>{const ie=`${ip(C)}:`;let le=!1;const we={};for(const[Ue,Ye]of Object.entries(ee)){if(Ue.startsWith(ie)){le=!0;continue}we[Ue]=Ye}return le?we:ee})},[]);v.useEffect(()=>{let C=!1;return m.getMainInfo().then(E=>{if(C)return;const B=E.name?.trim()||"Local";j.current.add(Zt),Ie(ee=>{const ie={...ee,[Zt]:B};return Yv(ee,ie)?ee:ie})}).catch(()=>{}),m.listAgents().then(E=>{if(!C){const B=E.agents.map(le=>le.id),ee=PA(E.serverOrder,E.agents);for(const le of E.agents)j.current.add(Rl(le.id));Ie(le=>{const we={[Zt]:le[Zt]??"Local"};for(const Ue of E.agents)we[Ue.id]=Ue.name;return Yv(le,we)?le:we}),n!==null&&!B.includes(n)&&(Ys(n),s?.(null));const ie=Dt.current;ie&&ie.serverId!==Zt&&!B.includes(ie.serverId)&&(Dt.current=null,T(`${ie.serverName} is no longer registered.`),K(!0)),ve(ee)}}).catch(()=>{}),()=>{C=!0}},[n,m,Ys,s,ge]);const gs=v.useCallback(C=>{Ys(C),Ae(E=>E+1),li(C,qs.current)&&s?.(null)},[Ys,s]);v.useEffect(()=>{ve(C=>C.some(E=>li(E,n))?C:[...C,n])},[n]),v.useEffect(()=>{Ke(null)},[n]),v.useEffect(()=>{const C=Dn.current;if(!C)return;if(!li(C.agentId,n)){Dn.current=null;return}if(!w.loaded||x.workspaces.length===0)return;Dn.current=null;const E=C.edge==="first"?x.workspaces[0]:x.workspaces[x.workspaces.length-1];E&&E.id!==x.activeWorkspaceId&&pt({type:"workspace.selected",workspaceId:E.id})},[n,w.loaded,x.activeWorkspaceId,x.workspaces]),v.useEffect(()=>{const C=Tn.current;if(C){if(!li(C.agentId,n)){Tn.current=null;return}w.loaded&&(Tn.current=null,x.workspaces.some(E=>E.id===C.workspaceId)&&pt({type:"workspace.selected",workspaceId:C.workspaceId}))}},[n,w.loaded,x.workspaces]),v.useEffect(()=>{const C=ft.current;if(C){if(!li(C.agentId,n)){ft.current=null;return}w.loaded&&(ft.current=null,w.error||Gl())}},[n,w.error,w.loaded]),v.useEffect(()=>{const C=Dt.current;if(!(!C||!li(C.serverId===Zt?null:C.serverId,n)||!w.loaded)){if(Dt.current=null,w.error){T(`Could not reach ${C.serverName}.`),K(!0);return}Fa(C)}},[n,w.loaded]),v.useEffect(()=>{const C=()=>{const ee=g8();ee&&mn.current(ee)},E=ee=>{const ie=v8(ee.data);ie&&mn.current(ie)},B=ee=>{const ie=Gp(ee.detail);ie&&mn.current(ie)};return C(),window.addEventListener("hashchange",C),window.addEventListener(n_,B),navigator.serviceWorker?.addEventListener?.("message",E),()=>{window.removeEventListener("hashchange",C),window.removeEventListener(n_,B),navigator.serviceWorker?.removeEventListener?.("message",E)}},[]),v.useEffect(()=>{ni()},[ni]),v.useEffect(()=>Ik(()=>Yl(Bl())),[]),v.useEffect(()=>{const C=E=>{Vs.current(E)};return window.addEventListener("keydown",C,!0),()=>window.removeEventListener("keydown",C,!0)},[]),v.useEffect(()=>{hi.current=dr.length>0?dr:WC},[dr]),v.useEffect(()=>{zi.current=Ni},[Ni]),v.useEffect(()=>{if(!w.loaded||!rt||!Tt)return;const C=Dd(n,rt.id,Tt.id);Te(E=>{if(E.has(C))return E;const B=new Set(E);return B.add(C),B})},[n,w.loaded,rt?.id,Tt?.id]),v.useEffect(()=>()=>{tc()},[]),v.useEffect(()=>{const C=sA(m),E=lA(m);return()=>{C(),E()}},[m]),v.useEffect(()=>DP(C=>{const E=gt(C.agentId).state,B=E.workspaces.flatMap(we=>we.tabs).find(we=>we.id===C.tabId),ee=E.terminals[C.terminalId],ie=B?.title?.trim()||ee?.title||C.commandName||"terminal",le=aS(C.agentId,C.terminalId);if(le||JM({agentId:C.agentId,tabTitle:ie,commandName:C.commandName,terminalId:C.terminalId,outcome:C.outcome}),!le&&document.visibilityState==="visible"&&zi.current.enabled){const we=Ha.current+1;Ha.current=we;const Ue=hi.current;Zi({id:we,agentId:C.agentId,terminalId:C.terminalId,tabId:C.tabId,tabTitle:ie,commandName:C.commandName,outcome:C.outcome,assetSrc:Ue[Math.floor(Math.random()*Ue.length)]??Gz})}}),[]),v.useEffect(()=>{if(!Ri||Ni.persistUntilDismissed)return;const C=window.setTimeout(()=>{Zi(E=>E?.id===Ri.id?null:E)},Ni.durationSeconds*1e3);return()=>window.clearTimeout(C)},[Ri,Ni]),v.useEffect(()=>{T8(U),U&&Ua()},[U]),v.useEffect(()=>{let C=!1,E;async function B(){if(!gt(n).loaded){E=IP(n),Co(n,!1,null);try{let ie=null,le=null;try{ie=b8(b)}catch(We){if(!(We instanceof zp))throw We;le=We}const[we,Ue]=await Promise.all([p.listTerminals(),p.getTerminalLayout()]),Ye=tv(we,Ue);if(!C&&lh(n,E)){const We=Ye.layout?Gb(Ye.layout):null;if(!We&&le)throw le;const St=We??ie??{};let Vt=we.terminals;const Bt=V2(n,E,Vt);if(!Bt)return;if(PP(n,E,Bt)){const ic=await p.createTerminal({cols:80,rows:24});Vt=[...Vt,ic.terminal]}if(C)return;const vn=zP(n,E,{terminals:Vt,...St,revision:Ye.revision,persistedLayout:Ye.layout});if(!vn)return;const Cs=Ro(vn.state),Ya=gt(n);(vn.layoutPreserved&&JSON.stringify(Cs)!==Ya.lastPersistedLayoutJson||!vn.metadataPreserved&&!We&&ie)&&el(Cs,{},E.generation)}}catch(ie){!C&&E&&lh(n,E)&&!pr(ie)&&Co(n,!0,Ca(ie))}finally{E&&BC(n,E)}}}return B(),()=>{C=!0,E&&BC(n,E)}},[n,p,Ee]);function Gs(){Co(n,!1,null),ye(C=>C+1)}function Ua(){qe.current+=1,je.current+=1,$e(null)}function Di(C){qe.current+=1,je.current+=1,$e(E=>E&&{...E,cwd:C,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null})}function Gl(){qe.current+=1,je.current+=1;const C=x.workspaces.length+1,E=Ko();$e({mode:"create",workspaceId:null,title:`Workspace ${C}`,cwd:E,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null}),E&&Xs(E)}function ii(C){if(li(C,n)){Gl();return}ft.current={agentId:C},s?.(C)}function vs(C){if(U&&!W)return;const E=x.workspaces.find(ee=>ee.id===C);if(!E)return;qe.current+=1,je.current+=1;const B=E.defaultCwd??oe?.cwd??"";$e({mode:"edit",workspaceId:C,title:E.title,cwd:B,browseRoot:null,browseEntries:[],browseStatus:"idle",submitStatus:"idle",error:null}),B&&Xs(B)}function Ko(){return rt?.defaultCwd??oe?.cwd??""}async function Xs(C){const E=qe.current+1;qe.current=E;const B=C.trim();if($e(ee=>ee&&{...ee,cwd:C,browseStatus:B?"loading":"idle",browseRoot:null,browseEntries:[],error:B?null:"Choose a default working directory."}),!!B)try{const ee=await p.createFileRoot({path:B}),ie=await p.listFiles({rootToken:ee.rootToken,path:""});if(qe.current!==E)return;$e(le=>le&&{...le,cwd:ee.rootPath,browseRoot:{rootToken:ee.rootToken,rootPath:ee.rootPath},browseEntries:ie.entries.filter(we=>we.kind==="directory"),browseStatus:"idle",error:null})}catch(ee){if(qe.current!==E)return;$e(ie=>ie&&{...ie,browseStatus:"idle",error:Ca(ee)})}}async function hr(){const C=be;if(!C)return;const E=C.title.trim(),B=C.cwd.trim();if(!E||!B){$e({...C,submitStatus:"idle",error:E?"Choose a default working directory.":"Workspace name is required."});return}const ee=je.current+1;je.current=ee,$e({...C,submitStatus:"submitting",error:null});try{const ie=await p.createFileRoot({path:B});if(je.current!==ee)return;if(C.mode==="create"){const le=x.workspaces.length+1;pt({type:"workspace.created",workspaceId:`workspace-${Date.now().toString(36)}-${le}`,title:E,defaultCwd:ie.rootPath})}else C.workspaceId&&(pt({type:"workspace.renamed",workspaceId:C.workspaceId,title:E}),pt({type:"workspace.defaultCwdChanged",workspaceId:C.workspaceId,defaultCwd:ie.rootPath}));$e(null)}catch(ie){if(je.current!==ee)return;$e(le=>le&&{...le,submitStatus:"idle",error:Ca(ie)})}}function $a(C){je.current+=1,$e(C)}function Zs(C,E,B){if(C===E)return;const ee=x.workspaces.some(le=>le.id===C),ie=x.workspaces.some(le=>le.id===E);!ee||!ie||pt({type:"workspace.reordered",sourceWorkspaceId:C,targetWorkspaceId:E,placement:B})}function _s(C,E){const B=x.workspaces.findIndex(ie=>ie.id===C),ee=x.workspaces[B+E];B<0||!ee||Zs(C,ee.id,E<0?"before":"after")}function Xl(C,E){E.pointerType==="mouse"&&E.button!==0||(E.preventDefault(),E.stopPropagation(),on.current={sourceId:C,pointerId:E.pointerId,startX:E.clientX,startY:E.clientY,active:!1,targetId:null,placement:"after"},E.currentTarget.setPointerCapture?.(E.pointerId))}function Zl(C){const E=on.current;if(!E||E.pointerId!==C.pointerId)return;const B=Math.hypot(C.clientX-E.startX,C.clientY-E.startY);if(!E.active){if(B<Xz)return;E.active=!0,st(E.sourceId)}const ie=document.elementFromPoint(C.clientX,C.clientY)?.closest("[data-workspace-id]"),le=ie?.dataset.workspaceId??null;if(!ie||!le||le===E.sourceId||!x.workspaces.some(Ye=>Ye.id===le)){E.targetId=null,xt(null);return}const we=ie.getBoundingClientRect(),Ue=C.clientY<we.top+we.height/2?"before":"after";E.targetId=le,E.placement=Ue,xt({workspaceId:le,placement:Ue})}function qo(C){const E=on.current;!E||E.pointerId!==C.pointerId||(C.preventDefault(),C.stopPropagation(),C.currentTarget.releasePointerCapture?.(C.pointerId),on.current=null,st(null),xt(null),E.active&&E.targetId&&Zs(E.sourceId,E.targetId,E.placement))}function Vo(C){const E=on.current;E&&E.pointerId===C.pointerId&&C.currentTarget.releasePointerCapture?.(C.pointerId),on.current=null,st(null),xt(null)}async function Hi(){await un(async()=>{const C=rt?.defaultCwd?{cols:80,rows:24,cwd:rt.defaultCwd}:{cols:80,rows:24},E=await p.createTerminal(C);pt({type:"terminal.created",terminal:E.terminal})})}function Yo(C,E=rt,B=x,ee=n){const ie=B.terminals[C.activeTerminalId],le=Array.from(new Set(Dl(C).flatMap(we=>{const Ue=B.terminals[we]?.agentStatus?.provider;return Ue==="codex"||Ue==="claude"?[Ue]:[]})));return{serverId:ee??Zt,workspaceId:E.id,tabId:C.id,serverName:Fe[Rl(ee)]??(ee===null?"Local":"Server"),workspaceName:E.title,tabName:C.title||ie?.title||"Terminal",cwd:ie?.cwd||E.defaultCwd,paneCount:Bp(C),providers:le}}function ts(C){const E=C.serverId===Zt?null:C.serverId,B=xo(E);if(!B?.loaded||B.error)return null;const ee=B.state,le=ee.workspaces.find(We=>We.tabs.some(St=>St.id===C.tabId))?.tabs.find(We=>We.id===C.tabId);if(!le)return null;const we=Dl(le).flatMap(We=>{const St=ee.terminals[We];return St?[St]:[]});if(we.length===0)return null;const Ue=we.reduce((We,St)=>{const Vt=St.agentCache?.lastCallAt;return Vt&&(!We||Date.parse(Vt)>Date.parse(We))?Vt:We},null),Ye=we.some(We=>B.unreadCompletions.has(We.id));return we.some(We=>We.status==="running"&&(We.agentStatus?.state==="working"||We.agentStatus?.state==="finishing"||!We.agentStatus&&We.activity==="busy"))?{state:"working",lastActivityAt:Ue,unread:Ye}:we.some(We=>We.agentStatus?.state==="stopped")?{state:"stopped",lastActivityAt:Ue,unread:Ye}:we.some(We=>We.agentStatus?.state==="done")?{state:"done",lastActivityAt:Ue,unread:Ye}:we.every(We=>We.status==="exited")?{state:"exited",lastActivityAt:Ue,unread:Ye}:{state:"idle",lastActivityAt:Ue,unread:Ye}}function Mi(C,E){Mt.current=C,wi.current=E,J(C)}function Dr(C){xi.current+=1,ae.current.push(C),!di.current&&(di.current=!0,X(!0),T(null),(async()=>{try{for(;ae.current.length>0;){const E=ae.current.shift();let B=0;for(;B<2;){const ee=E(Mt.current);if(qC(ee,Mt.current))break;Mi(ee,wi.current);try{const ie=await m.saveFavorites({favorites:ee,baseRevision:wi.current});Mi(ie.favorites,ie.revision);break}catch(ie){const le=await m.getFavorites().catch(()=>null);if(le&&Mi(le.favorites,le.revision),ie instanceof Wn&&ie.status===409&&le){B+=1;continue}ae.current=[],T("Could not save favorites. Please try again.");return}}if(B>=2){ae.current=[],T("Favorites changed on another device. Please try again.");return}}}finally{di.current=!1,X(!1)}})())}function pn(C,E,B){const ee=E??Zt,ie=le=>le.map(we=>{if(we.serverId!==ee)return we;const Ue=B.workspaces.find(St=>St.tabs.some(Vt=>Vt.id===we.tabId)),Ye=Ue?.tabs.find(St=>St.id===we.tabId);if(!Ue||!Ye)return we;const We=Yo(Ye,Ue,B,E);return j.current.has(Rl(E))?We:{...We,serverName:we.serverName}});qC(C,ie(C))||Dr(ie)}function Mr(C){const E=n??Zt,B=Mt.current.find(ie=>ie.serverId===E&&ie.tabId===C.id);if(B){const ie=Gr(B);Dr(le=>le.filter(we=>Gr(we)!==ie));return}if(!rt||Mt.current.length>=100)return;const ee=Yo(C);Dr(ie=>ie.length>=100?ie:[...ie,ee])}function Ar(C){const E=C.serverId===Zt?null:C.serverId;if(E!==null&&!Be.some(B=>li(B,E))){T(`${C.serverName} is no longer registered.`);return}if(T(null),K(!1),!li(E,n)){Dt.current=C,s?.(E);return}Fa(C)}async function Fa(C){const E=gt(n).state,B=E.workspaces.find(ie=>ie.tabs.some(le=>le.id===C.tabId));if(B){pt({type:"workspace.selected",workspaceId:B.id}),pt({type:"tab.selected",tabId:C.tabId});return}let ee=E.workspaces.find(ie=>ie.id===C.workspaceId);if(!ee){const ie=`workspace-favorite-${Date.now().toString(36)}`;pt({type:"workspace.created",workspaceId:ie,title:C.workspaceName,defaultCwd:C.cwd}),ee=gt(n).state.workspaces.find(le=>le.id===ie)}ee&&pt({type:"workspace.selected",workspaceId:ee.id}),await un(async()=>{const ie=await p.createTerminal(C.cwd?{cols:80,rows:24,cwd:C.cwd}:{cols:80,rows:24});pt({type:"terminal.created",terminal:ie.terminal});const we=gt(n).state.workspaces.find(Bt=>Bt.tabs.some(vn=>vn.activeTerminalId===ie.terminal.id)),Ue=we?.tabs.find(Bt=>Bt.activeTerminalId===ie.terminal.id);if(!Ue||!we)return;Ue.title!==C.tabName&&pt({type:"tab.renamed",tabId:Ue.id,title:C.tabName});const Ye=gt(n).state,We=Ye.workspaces.find(Bt=>Bt.id===we.id)??we,St=We.tabs.find(Bt=>Bt.id===Ue.id)??Ue,Vt=Yo(St,We,Ye);Dr(Bt=>Bt.map(vn=>vn.serverId===C.serverId&&vn.workspaceId===C.workspaceId&&vn.tabId===C.tabId?Vt:vn))})}async function ns(C){await un(async()=>{const E=gn?{parentTerminalId:gn,cols:80,rows:24}:rt?.defaultCwd?{cols:80,rows:24,cwd:rt.defaultCwd}:{cols:80,rows:24},B=await p.createTerminal(E);pt({type:"terminal.split",terminal:B.terminal,direction:C})})}async function Ai(C){let E=gn,B=Je;const ee=rt?.defaultCwd?.trim();if(!E&&!ee)throw new Error("No active pane is available.");const ie=await p.readFile(C);if(!E&&ee){const Ue=await p.createTerminal({cols:80,rows:24,cwd:ee});E=Ue.terminal.id,pt({type:"terminal.created",terminal:Ue.terminal})}if(E){pt({type:"pane.selected",terminalId:E});const Ue=gt(n).state,Ye=Ue.workspaces.find(St=>St.id===Ue.activeWorkspaceId)??Ue.workspaces[0],We=Ye?.tabs.find(St=>St.id===Ye.activeTabId)??Ye?.tabs[0];B=Ye&&We?Dd(n,Ye.id,We.id):null}const le=`editor-${Date.now().toString(36)}-${$P(n)}`,we=C8(ie.path);Fv(n,Ue=>({...Ue,[le]:{id:le,title:we,rootToken:C.rootToken,path:ie.path,read:ie}})),B&&Le(Ue=>({...Ue,[B]:nR(le)})),pt({type:"editor.split",editorId:le,title:we,direction:"vertical"})}function is(C){Fv(n,E=>{const B={...E};return delete B[C],B}),pt({type:"editor.closed",editorId:C})}function fr(C){Lr([C])}function Lr(C){const E=[...new Set(C)].filter(ee=>x.terminals[ee]);if(E.length===0)return;const B=E.length===1?x.terminals[E[0]]?.title||x.terminals[E[0]]?.cwd||E[0]:`${E.length} panes`;Ke(null),Ks({terminalIds:E,label:B,workspaceId:rt?.id??x.activeWorkspaceId??null})}function rs(C,E){const B=cu(C,E);if(!B)return!1;const ee=C.filter(ie=>!B.detachedTerminalIds.includes(ie));if(B.detachedTerminalIds.length+ee.length>Io)return Ke(S8(B.detachedTerminalIds.length)),!1;Ke(null);for(const ie of C)pt(B.id?{type:"terminal.detached",terminalId:ie,workspaceId:B.id}:{type:"terminal.detached",terminalId:ie});return!0}async function jr(C){await un(async()=>{for(const E of C)await Ji(E),kd(p.createWebSocketUrl(E)),Mf(E),Cd(E),pt({type:"terminal.closed",terminalId:E})})}async function Qs(C){const E=x.workspaces.find(B=>B.id===C);!E||x.workspaces.length<=1||window.confirm(`Delete workspace "${E.title}" and close all terminal sessions inside it? This cannot be undone.`)&&await un(async()=>{const B=$s(E),ee=[];let ie=null;for(const we of B)try{await Ji(we)}catch(Ue){ee.push(Ca(Ue)),Ue instanceof Wn&&Ue.status===401&&!p.isAgent&&(ie=Ue)}finally{kd(p.createWebSocketUrl(we)),Mf(we),Cd(we)}const le=E.tabs.flatMap(we=>Yb(we.root));if(le.length>0){const we=new Set(le);Fv(n,Ue=>{const Ye={...Ue};for(const We of we)delete Ye[We];return Ye})}if(pt({type:"workspace.closed",workspaceId:C}),ie)throw ie;if(ee.length>0)throw new Error(`Workspace was removed, but ${ee.length} terminal session${ee.length===1?"":"s"} may still be running. ${ee[0]}`)})}async function bs(C){await un(async()=>{await Ji(C),kd(p.createWebSocketUrl(C)),Mf(C),Cd(C),pt({type:"terminal.closed",terminalId:C})})}async function Js(C,E){const B=E.trim();if(!B)return;let ee=null;for(const ie of x.workspaces){const le=ie.tabs.find(we=>we.id===C);if(le){ee=le.activeTerminalId;break}}if(pt({type:"tab.renamed",tabId:C,title:B}),!!ee)try{const ie=await p.renameTerminal(ee,B);Or({type:"terminal.updated",terminal:ie.terminal})}catch(ie){Co(n,!0,Ca(ie))}}function ys(C){const E=x.terminals[C];E&&pt({type:"terminal.created",terminal:E})}async function Ji(C){try{await p.closeTerminal(C)}catch(E){if(E instanceof Wn&&E.status===404)return;throw E}}async function Ui(){await un(async()=>{await d()})}async function un(C){Co(n,!0,null);try{await C()}catch(E){if(pr(E))return;Co(n,!0,Ca(E))}}function pr(C){return C instanceof Wn&&C.status===401&&!p.isAgent&&f?(f({source:"workspace-api-401",status:401,activeAgentId:n}),!0):!1}function pt(C){Ed(n,C);const E=gt(n),B=E.state;if(pn(Mt.current,n,B),!E.loaded||B.workspaces.length===0)return;const ee=Ro(B);JSON.stringify(ee)!==E.lastPersistedLayoutJson&&Ir(ee)}function Or(C){Ed(n,C),pn(Mt.current,n,gt(n).state)}function Ss(C,E,B,ee){const ie=Dd(C,E,B);Le(le=>({...le,[ie]:ee}))}function Wa(C){Je&&Le(E=>({...E,[Je]:C}))}function mr(C,E){const B=Kc(C);E?Ss(n,E.workspaceId,E.tabId,B):Wa(B),pt({type:"pane.selected",terminalId:C})}function ws(C){Wa(C.key),C.type==="terminal"&&pt({type:"pane.selected",terminalId:C.terminalId})}function ea(C){if(F||he||Wt||C.isComposing||C.key==="Process"||i8(C.target))return;const E=Jz(C);if(!E)return;if(C.preventDefault(),C.stopPropagation(),E.type==="server.previous"||E.type==="server.next"){Ql(E.type==="server.next"?1:-1);return}if(E.type==="favorites.toggle"){K(!0);return}const B=gt(n).state,ee=B.workspaces.find(we=>we.id===B.activeWorkspaceId)??B.workspaces[0],ie=ee?.tabs.find(we=>we.id===ee.activeTabId)??ee?.tabs[0];if(E.type==="split"){if(!ie)return;ns(E.direction);return}if(!ee||!ie)return;if(E.type==="tab.previous"||E.type==="tab.next"){const we=n8(ee.tabs,ie.id,E.type==="tab.next"?1:-1);we&&pt({type:"tab.selected",tabId:we.id});return}if(E.type==="tab.index"){const we=ee.tabs[E.index-1];we&&pt({type:"tab.selected",tabId:we.id});return}const le=e8(ie.root,ie.activeTerminalId,E);le&&mr(le,{workspaceId:ee.id,tabId:ie.id})}function Go(C,E){if(!s||Be.length===0)return;const B=Be.findIndex(we=>li(we,n)),ie=((B===-1?0:B)+C+Be.length)%Be.length,le=Be[ie]??null;li(le,n)||(E&&(Dn.current={agentId:le,edge:E}),s(le))}function Ql(C){const E=gt(n).state,B=E.workspaces;if(B.length===0){Go(C,C===1?"first":"last");return}const ee=B.findIndex(we=>we.id===E.activeWorkspaceId),le=(ee===-1?0:ee)+C;if(le>=0&&le<B.length){pt({type:"workspace.selected",workspaceId:B[le].id});return}Go(C,C===1?"first":"last")}function Br(C,E){if(li(C,n)){pt({type:"workspace.selected",workspaceId:E});return}Tn.current={agentId:C,workspaceId:E},s?.(C)}function cu(C,E){if(E)return x.workspaces.find(B=>B.id===E)??null;for(const B of C){const ee=x.workspaces.find(le=>le.tabs.some(we=>Dl(we).includes(B)));if(ee)return ee;const ie=x.workspaces.find(le=>le.detachedTerminalIds.includes(B));if(ie)return ie}return x.workspaces.find(B=>B.id===x.activeWorkspaceId)??x.workspaces[0]??null}function ta(C){$c(C.dataTransfer)&&(C.preventDefault(),C.dataTransfer.dropEffect="copy")}function gr(C){if(!$c(C.dataTransfer))return;C.preventDefault();const E=w8(gt(n).state),B=ot.current+1;if(ot.current=B,!E){Zo({id:B,status:"failed",fileCount:0,message:"No active running terminal is available for upload."});return}Zo({id:B,status:"queued",fileCount:0,terminalId:E.id,message:"Preparing upload..."}),Jl(B,E.id,C.dataTransfer)}async function Jl(C,E,B){try{const ee=await n2(B);if(ee.length===0)throw new Error("No files were found in the drop.");vr(C,{id:C,status:"queued",fileCount:ee.length,message:"Queued"},{terminalId:E,files:ee})}catch(ee){vr(C,{id:C,status:"failed",fileCount:0,message:Ca(ee)},{terminalId:E})}finally{na()}}async function Xo(C){const E=qn.current.find(le=>le.id===C);if(!E?.terminalId||!E.files||E.files.length===0)return;const B=E.terminalId,ee=E.files,ie=new AbortController;Mn.current=C,vr(C,{id:C,status:"uploading",fileCount:ee.length,loaded:0,total:null,percent:null},{terminalId:B,files:ee,abortController:ie});try{const le=await ZC({terminalId:B,files:ee,signal:ie.signal,onProgress:We=>{vr(C,{id:C,status:"uploading",fileCount:ee.length,loaded:We.loaded,total:We.total,percent:We.percent},{terminalId:B,files:ee,abortController:ie})}}),we=le.failed>0?le.uploaded>0?"partial":"failed":"success",Ue=le.failed>0?x8(le):void 0,Ye={id:C,status:we,fileCount:ee.length,response:le};Ue&&(Ye.message=Ue),vr(C,Ye,{terminalId:B,files:ee})}catch(le){vr(C,{id:C,status:"failed",fileCount:ee.length,message:ie.signal.aborted?"Upload canceled.":Ca(le)},{terminalId:B,files:ee})}finally{Mn.current===C&&(Mn.current=null),na()}}function na(){if(Mn.current!==null)return;const C=qn.current.find(E=>E.status==="queued");C?.terminalId&&C.files&&C.files.length>0&&Xo(C.id)}function Zo(C){ss(E=>[...E,C])}function vr(C,E,B={}){ss(ee=>ee.map(ie=>{if(ie.id!==C)return ie;const le={...E},we=B.terminalId??ie.terminalId,Ue=B.files??ie.files;return we!==void 0&&(le.terminalId=we),Ue!==void 0&&(le.files=Ue),B.abortController!==void 0&&(le.abortController=B.abortController),le}))}function ss(C){const E=C(qn.current);qn.current=E,Xi(E)}function uu(C){qn.current.find(B=>B.id===C)?.abortController?.abort(),Mn.current===C&&(Mn.current=null),ss(B=>B.filter(ee=>ee.id!==C)),na()}function fi(){for(const C of qn.current)C.abortController?.abort();Mn.current=null,ss(()=>[])}function Qo(C){const E=qn.current.find(B=>B.id===C);if(E){if(E.status==="queued"){uu(C);return}E.abortController?.abort()}}function Ka(C){const E=qn.current.find(ee=>ee.id===C);if(!E?.terminalId||!E.files||E.files.length===0)return;const B=as(E);if(B.length===0){vr(C,{id:C,status:"failed",fileCount:E.fileCount,message:"No failed files are available to retry."},{terminalId:E.terminalId,files:E.files});return}vr(C,{id:C,status:"queued",fileCount:B.length,message:"Queued"},{terminalId:E.terminalId,files:B}),na()}function as(C){const E=C.files??[],B="response"in C?C.response:void 0;if(!B)return E;const ee=B.results.filter(we=>we.status==="failed").map(we=>we.relativePath);if(ee.length===0)return[];const ie=new Map;for(const we of E){const Ue=ie.get(we.relativePath)??[];Ue.push(we),ie.set(we.relativePath,Ue)}const le=[];for(const we of ee){const Ye=ie.get(we)?.shift();Ye&&le.push(Ye)}return le}function ec(C){ia({kind:"terminal",agentId:C.agentId,terminalId:C.terminalId}),Zi(null)}function ia(C){if(Pe.current=C,tt.current=null,_t.current=null,Ft(E=>E+1),Bf(void 0),!li(C.agentId,n)){s?s(C.agentId):Pe.current=null;return}}function Jo(){const C=Pe.current;if(!C||!li(C.agentId,n))return!1;if(!w.loaded||document.visibilityState!=="visible")return!0;if(_t.current?.target===C){const ee=_t.current;return ee.generation===w.generation&&(ee.applying||ee.layoutSequence===gt(C.agentId).mutable.hydration.layoutSequence)?!0:(_t.current=null,Pe.current=null,tt.current=null,!1)}if(tt.current?.target!==C||tt.current.generation!==w.generation){if(tt.current={target:C,generation:w.generation},!gt(C.agentId).state.workspaces.some(le=>$s(le).includes(C.terminalId)))return xs(C),!0;pt({type:"terminal.revealed",terminalId:C.terminalId});const ie=Vv(gt(C.agentId).state,C.terminalId);if(ie)return Ss(C.agentId,ie.workspaceId,ie.tabId,Kc(C.terminalId)),Ft(le=>le+1),!0}const E=gt(C.agentId),B=Vv(E.state,C.terminalId);return B&&(x!==E.state||rt?.id!==B.workspaceId||Tt?.id!==B.tabId||tn&&Ze!==Kc(C.terminalId))?!0:(Pe.current=null,tt.current=null,!1)}async function xs(C){const E=gt(C.agentId),B={target:C,generation:E.generation,layoutSequence:E.mutable.hydration.layoutSequence,applying:!1};_t.current=B;let ee=!1;const ie=()=>$t.current&&_t.current===B&&Pe.current===C&&xo(C.agentId)?.generation===B.generation;try{const le=Is(C.agentId),[we,Ue]=await Promise.all([le.listTerminals(),le.getTerminalLayout()]),Ye=tv(we,Ue);if(!ie())return;const We=gt(C.agentId);if(!li(qs.current,C.agentId)||!We.loaded||We.mutable.hydration.layoutSequence!==B.layoutSequence)return;const St=we.terminals.find(Cs=>Cs.id===C.terminalId);if(!St)throw new Error("This terminal is no longer available.");const Vt=qP(We.state,St,Ye.layout);B.applying=!0,OC(C.agentId,Vt);const Bt=Ro(Vt);Ye.revision===We.layoutRevision?Ir(Bt):Lc(Bt,b);const vn=Vv(Vt,C.terminalId);Ss(C.agentId,vn.workspaceId,vn.tabId,Kc(C.terminalId)),tt.current={target:C,generation:B.generation},ee=!0}catch(le){ie()&&!pr(le)&&Co(C.agentId,!0,Ca(le))}finally{ie()&&(_t.current=null,ee||(Pe.current=null,tt.current=null),Ft(le=>le+1))}}function Ir(C){const E=xo(n);if(E?.generation!==w.generation)return;const B=E.mutable.saveCoord;B.pendingLayoutSave=C,Lc(C,b),B.saveTimer!==null&&window.clearTimeout(B.saveTimer),B.saveTimer=window.setTimeout(()=>{B.saveTimer=null;const ee=B.pendingLayoutSave;B.pendingLayoutSave=null,ee&&el(ee,{},E.generation)},Yz)}function tc(){const C=xo(n);if(C?.generation!==w.generation)return;const E=C.mutable.saveCoord;E.saveTimer!==null&&(window.clearTimeout(E.saveTimer),E.saveTimer=null);const B=E.pendingLayoutSave;E.pendingLayoutSave=null,B&&(Lc(B,b),el(B,{},C.generation))}function el(C,E={},B=w.generation){const ee=xo(n);if(ee?.generation!==B)return;const ie=ee.mutable.saveCoord;ie.nextPersistLayout=C,E.baseRevision!==void 0&&(ie.queuedBaseRevision=E.baseRevision),!ie.nextPersistQueued&&(ie.nextPersistQueued=!0,ie.persistChain=ie.persistChain.then(async()=>{if(xo(n)?.generation!==B)return;ie.nextPersistQueued=!1;const le=ie.nextPersistLayout,we=ie.queuedBaseRevision;ie.nextPersistLayout=null,ie.queuedBaseRevision=void 0,le&&await tl(le,we!==void 0?{baseRevision:we}:{},B)}))}async function tl(C,E,B){const ee=xo(n);if(ee?.generation!==B||JSON.stringify(Ro(ee.state))!==JSON.stringify(C))return;const ie=ee.mutable.hydration.layoutSequence,le=()=>xo(n)?.generation===B,we=E.baseRevision??ee.layoutRevision,Ue={layout:C,...typeof we=="number"?{baseRevision:we}:{}};try{const Ye=await p.saveTerminalLayout(Ue);if(!le())return;const We=Ye.layout??C;If(n,Ye.revision,JSON.stringify(We)),Lc(We,b);return}catch(Ye){if(!le())return;if(Ye instanceof Wn&&Ye.status===400&&Ye.message===dM){y8(n,b),Co(n,!0,iR());return}if(Ye instanceof Wn&&Ye.status===409)try{const We=await p.getTerminalLayout();if(!le())return;const St=gt(n).mutable.saveCoord;if(St.nextPersistLayout||St.pendingLayoutSave||gt(n).mutable.hydration.layoutSequence!==ie){const Vt=We.layout?JSON.stringify(We.layout):gt(n).lastPersistedLayoutJson;If(n,We.revision,Vt);return}if(We.layout){const Vt=gt(n).state,Bt=Op(Object.values(Vt.terminals),void 0,We.layout.workspaces,We.layout.activeWorkspaceId),vn=Ro(Bt);OC(n,Bt),If(n,We.revision,JSON.stringify(vn)),Lc(vn,b)}else If(n,We.revision,ee.lastPersistedLayoutJson);return}catch{}le()&&Lc(C,b)}}const qa=E8(o),er=!U||W,Va=er?Y:"servers";function nc(C){const E=C.active?w:gt(C.agentId),B=C.active?x:E.state,ee=C.active?w.loaded:E.loaded,ie=C.active?A:E.error;return u.jsxs("div",{className:`workspace-list-panel${C.active?" workspace-list-panel--active-server":""}`,"aria-label":`${C.label} workspaces`,children:[u.jsxs("div",{className:"workspace-list-header",children:[u.jsx("span",{children:"Workspaces"}),u.jsx("button",{type:"button","aria-label":`New workspace on ${C.label}`,title:"New workspace",onClick:()=>ii(C.agentId),children:"+"})]}),ee?ie?u.jsx("button",{type:"button",className:"workspace-list-placeholder workspace-list-placeholder--error",onClick:()=>s?.(C.agentId),children:ie}):u.jsx("div",{className:"workspace-list-items",children:B.workspaces.map(le=>{const we=C.active&&le.id===rt?.id,Ue=$s(le).length,Ye=NP(C.agentId,le.id),We=l8(Ye),St=C.active&&B.workspaces.length>1,Vt=mt?.workspaceId===le.id&&ht!==le.id?mt.placement:null;return u.jsxs(u8,{workspaceId:le.id,active:we,disabled:!C.active,reorderable:St,dragging:ht===le.id,dropPlacement:Vt,working:Ye.workingTerminalCount>0,unread:Ye.unreadCompletionCount>0,children:[St?u.jsx("button",{type:"button",className:"workspace-list-drag-handle","data-workspace-drag-handle":le.id,title:"Drag to reorder","aria-label":`Reorder ${le.title}`,"aria-grabbed":ht===le.id,onPointerDown:Bt=>Xl(le.id,Bt),onPointerMove:Zl,onPointerUp:qo,onPointerCancel:Vo,onKeyDown:Bt=>{(Bt.key==="ArrowUp"||Bt.key==="ArrowDown")&&(Bt.preventDefault(),Bt.stopPropagation(),_s(le.id,Bt.key==="ArrowUp"?-1:1))},onClick:Bt=>Bt.stopPropagation(),children:"::"}):null,u.jsxs("button",{type:"button",className:"workspace-list-select","aria-current":we?"page":void 0,title:le.defaultCwd??void 0,onClick:()=>Br(C.agentId,le.id),onDoubleClick:()=>{C.active&&vs(le.id)},children:[u.jsxs("span",{className:"workspace-list-title-row",children:[u.jsx("span",{className:"workspace-list-name",children:le.title}),Ye.workingTerminalCount>0||Ye.unreadCompletionCount>0?u.jsxs("span",{className:"workspace-list-attention",title:We,"aria-label":We,children:[Ye.workingTerminalCount>0?u.jsx("span",{className:"workspace-list-working-indicator","aria-hidden":"true"}):null,Ye.unreadCompletionCount>0?u.jsx("span",{className:"workspace-list-unread-count","aria-hidden":"true",children:o8(Ye.unreadCompletionCount)}):null]}):null]}),u.jsxs("small",{children:[le.defaultCwd??"No folder"," · ",Ue," ",Ue===1?"session":"sessions"]})]}),C.active?u.jsxs("div",{className:"workspace-list-actions",children:[u.jsx("button",{type:"button",className:"workspace-list-edit","aria-label":`Edit ${le.title}`,title:"Edit workspace",onClick:()=>vs(le.id),children:"..."}),u.jsx("button",{type:"button",className:"workspace-list-delete","aria-label":`Delete ${le.title}`,title:"Delete workspace",disabled:B.workspaces.length<=1,onClick:()=>{Qs(le.id)},children:"x"})]}):null]},le.id)})}):u.jsx("button",{type:"button",className:"workspace-list-placeholder",onClick:()=>s?.(C.agentId),children:"Open server to load workspaces"})]})}function ra(C,E){re({...C,provider:E})}async function _r(C){if(N(C),!gt(C.agentId).loaded)try{const E=Is(C.agentId),[B,ee]=await Promise.all([E.listTerminals(),E.getTerminalLayout()]),ie=tv(B,ee),le=ie.layout?Gb(ie.layout):null,we=Op(B.terminals,void 0,le?.savedWorkspaces,le?.savedActiveWorkspaceId),Ue=we.workspaces.flatMap(Ye=>Ye.tabs.flatMap(We=>Nn(We.root).flatMap(St=>{const Vt=we.terminals[St];return Vt?[{terminalId:St,cwd:Vt.cwd,label:`${Ye.title} / ${We.title} / ${Vt.title}`}]:[]})));N(Ye=>Ye===C?{...Ye,targets:Ue}:Ye)}catch{N(E=>E===C?{...E,targetError:"Could not retrieve open tabs."}:E)}}return u.jsx(Ck,{sensors:ln,onDragStart:cn,onDragEnd:Kn,onDragCancel:In,children:u.jsxs("main",{className:"terminal-shell","data-collapsed":U,"data-sidebar-open":W,onDragOver:ta,onDrop:gr,children:[u.jsx("button",{type:"button",className:"workspace-backdrop","aria-label":"Close workspaces",onClick:()=>H(!1)}),u.jsxs("aside",{className:"workspace-sidebar",children:[u.jsxs("header",{className:"workspace-brand",children:[u.jsxs("div",{className:"workspace-brand-lockup",children:[er?u.jsx(nk,{height:20}):u.jsx(tk,{size:24}),l&&er?u.jsx("span",{className:"workspace-preview-badge",children:"Preview"}):null]}),u.jsx("button",{type:"button",className:"sidebar-collapse-button","aria-label":U?"Expand sidebar":"Collapse sidebar",title:U?"Expand sidebar":"Collapse sidebar",onClick:()=>q(C=>!C),children:U?">":"<"}),u.jsx("button",{type:"button",className:"sidebar-drawer-close-button","aria-label":"Close workspaces",title:"Close workspaces",onClick:()=>H(!1),children:"x"})]}),u.jsxs("div",{className:`workspace-sidebar-content workspace-sidebar-content--${Va==="files"?"files":"servers"}`,children:[er?u.jsxs("div",{className:"workspace-sidebar-tabs",role:"tablist","aria-label":"Sidebar mode",children:[u.jsx("button",{type:"button",role:"tab","aria-selected":Y==="servers",onClick:()=>{I("servers")},children:"Workspaces"}),u.jsx("button",{type:"button",role:"tab","aria-selected":Y==="files",onClick:()=>{I("files")},children:"Files"})]}):null,Va==="servers"&&er?u.jsx("nav",{className:"workspace-nav","aria-label":"Workspaces",children:u.jsx(U1,{api:m,activeAgentId:n,onSelectServer:s??(()=>{}),onSessionInvalid:f,refreshToken:ge,onServerLabelsChange:Pn,onManageAccounts:ra,onServerInfo:C=>{_r(C)},renderServerChildren:nc})}):null,er?null:u.jsx("nav",{className:"workspace-nav workspace-nav--collapsed","aria-label":"Servers",children:u.jsx(U1,{api:m,activeAgentId:n,onSelectServer:s??(()=>{}),onSessionInvalid:f,refreshToken:ge,onServerLabelsChange:Pn,compact:!0})}),Va==="files"?u.jsx(Sj,{api:p,activeTerminalId:gn,activeTerminalCwd:oe?.cwd??null,workspaceRootPath:gn?null:rt?.defaultCwd??null,onOpenFile:Ai},`${n??"local"}:${rt?.id??"no-workspace"}`):null]}),u.jsxs("div",{className:"workspace-sidebar-footer",children:[er?u.jsx("span",{children:qa}):null,u.jsxs("div",{className:"workspace-sidebar-footer-actions",children:[u.jsxs("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"settings",title:"Settings",onClick:()=>de(!0),children:[u.jsx(VC,{name:"settings"}),Z.hasUpdates?u.jsx("span",{className:"update-pulse-dot","aria-hidden":"true"}):null]}),er?u.jsx("button",{type:"button",className:"workspace-footer-icon-button","aria-label":"logout",title:"Logout",onClick:()=>{Ui()},children:u.jsx(VC,{name:"logout"})}):null]})]})]}),F?u.jsx(mj,{api:m,onClose:()=>de(!1),updateAvailable:Z.hasUpdates,onNotificationAssetsChanged:()=>{ni()},onAgentRemoved:gs}):null,O?u.jsx(dL,{provider:O.provider,serverLabel:O.label,api:se,onClose:()=>re(null)}):null,he&&u.jsx(NL,{api:V,label:he.label,main:he.agentId===null,getRuntimeStatus:ts,favorites:te.filter(C=>C.serverId===(he.agentId??Zt)),targetStatus:he.targetError??(!gt(he.agentId).loaded&&!he.targets?"Loading open tabs...":null),targets:he.targets??gt(he.agentId).state.workspaces.flatMap(C=>C.tabs.flatMap(E=>Nn(E.root).flatMap(B=>{const ee=gt(he.agentId).state.terminals[B];return ee?[{terminalId:B,cwd:ee.cwd,label:`${C.title} / ${E.title} / ${ee.title}`}]:[]}))),onClose:()=>N(null),onFavorite:C=>{N(null),Ar(C)},onTarget:C=>{ia({kind:"terminal",agentId:he.agentId,terminalId:C.terminalId}),N(null)}},he.agentId??Zt),be?u.jsx(r8,{dialog:be,activePaneCwd:oe?.cwd??null,activeWorkspaceCwd:rt?.defaultCwd??null,onChange:$a,onManualCwdChange:Di,onBrowse:Xs,onCancel:Ua,onSubmit:()=>{hr()}}):null,u.jsxs("section",{className:"terminal-main","aria-label":"Terminal workspace","data-mobile-pane-switcher":tn?"true":void 0,children:[u.jsx(YP,{tabs:rt?.tabs??[],activeTabId:rt?.activeTabId??null,terminals:x.terminals,unreadCompletionTabIds:Gi,favoriteTabIds:new Set(te.filter(C=>C.serverId===(n??Zt)).map(C=>C.tabId)),detachedTerminals:Sn,onSelectTab:C=>pt({type:"tab.selected",tabId:C}),onCreateTab:()=>{Hi()},onToggleWorkspaces:()=>H(C=>!C),onCloseTerminals:C=>Lr(C),onReattachTerminal:C=>ys(C),onDeleteTerminal:C=>{bs(C)},onSplitVertical:()=>{ns("vertical")},onSplitHorizontal:()=>{ns("horizontal")},onRenameTab:(C,E)=>{Js(C,E)},onToggleFavorite:Mr,onOpenFavorites:()=>K(!0),activePaneAvailable:!!gn}),me?u.jsx(Ez,{favorites:te,unavailableFavoriteIds:new Set(te.filter(C=>C.serverId!==Zt&&!Be.some(E=>li(E,C.serverId))).map(Gr)),busy:Q,error:M,getRuntimeStatus:ts,onClose:()=>{K(!1),T(null)},onOpen:Ar,onRemove:C=>{Dr(E=>E.filter(B=>Gr(B)!==Gr(C)))},onReorder:(C,E)=>{const B=Gr(C),ee=Gr(E);Dr(ie=>{const le=ie.findIndex(St=>Gr(St)===B),we=ie.findIndex(St=>Gr(St)===ee);if(le<0||we<0||le===we)return ie;const Ue=ie.slice(),[Ye]=Ue.splice(le,1),We=Ue.findIndex(St=>Gr(St)===ee);return Ye&&We>=0&&Ue.splice(We,0,Ye),Ue})}}):null,tn?u.jsx(h8,{targets:Ge,activeLeafKey:Ze,terminals:x.terminals,editors:R,onSelect:ws}):null,A?u.jsxs("div",{className:"workspace-error",role:"alert",children:[u.jsx("span",{children:A}),u.jsxs("div",{className:"workspace-error-actions",children:[u.jsx("button",{type:"button",onClick:Gs,children:"Retry"}),n!==null&&s?u.jsx("button",{type:"button",onClick:()=>s(null),children:"Main server"}):null]})]}):null,u.jsxs("section",{className:"workspace-body","aria-busy":L,children:[L?u.jsx("div",{className:"workspace-placeholder",children:"Opening shell..."}):null,!L&&!Tt?u.jsx(c8,{onCreate:()=>{Hi()}}):null,Oe.map(C=>{const E=li(C,n);return u.jsx(Qz,{agentId:C,serverName:Fe[Rl(C)]??(C===null?"Local":"Server"),active:E,activeServerApi:E?p:void 0,visitedTabKeys:fe,refreshCwdOnEnter:E,draggingTab:E?Bn:null,mobileSplitFocus:ke,mobileFocusedLeafByTabKey:Ne,onSelect:B=>{E&&mr(B)},onClose:B=>{E&&fr(B)},onCloseEditor:B=>{E&&is(B)},onResize:(B,ee)=>{E&&pt({type:"pane.resized",path:B,ratio:ee})},onExit:(B,ee)=>{E?Or({type:"terminal.exited",terminalId:B,exitCode:ee}):Ed(C,{type:"terminal.exited",terminalId:B,exitCode:ee})},onSnapshot:(B,ee)=>{const ie={type:"terminal.updated",terminal:B,notifyCompletion:ee?.notifyCompletion===!0};E?Or(ie):Ed(C,ie)},...f?{onAuthClose:B=>f({...B,source:B?.source??"terminal-ws-1008",activeAgentId:C})}:{}},ip(C))})]}),Wt?u.jsx(d8,{label:Wt.label,count:Wt.terminalIds.length,warning:ze,onCancel:()=>{Ke(null),Ks(null)},onHide:()=>{rs(Wt.terminalIds,Wt.workspaceId)&&Ks(null)},onDelete:()=>{const C=Wt.terminalIds;Ke(null),Ks(null),jr(C)}}):null,u.jsx(zz,{toast:Ri,onActivate:ec,onDismiss:()=>Zi(null)}),u.jsx(Az,{uploads:Xt,onDismiss:uu,onDismissAll:fi,onRetry:Ka,onCancel:Qo})]})]})})}function Qz({agentId:e,serverName:t,active:n,activeServerApi:s,visitedTabKeys:o,refreshCwdOnEnter:l,draggingTab:d,mobileSplitFocus:f,mobileFocusedLeafByTabKey:m,onSelect:p,onClose:b,onCloseEditor:_,onResize:S,onExit:w,onSnapshot:x,onAuthClose:R}){const L=v.useMemo(()=>me=>K2(e,me),[e]),A=v.useMemo(()=>()=>gt(e),[e]),W=v.useSyncExternalStore(L,A,A),H=v.useMemo(()=>Is(e),[e]),U=s??H,q=W.state,Y=q.workspaces.find(me=>me.id===q.activeWorkspaceId)??q.workspaces[0],I=Y?.id??null,de=(Y?.tabs.find(me=>me.id===Y.activeTabId)??Y?.tabs[0])?.id??null;return!W.loaded||q.workspaces.length===0?null:u.jsx("div",{className:"workspace-server-surface","data-active":n,"aria-hidden":!n,children:q.workspaces.flatMap(me=>me.tabs.map(K=>{const te=n&&me.id===I&&K.id===de,J=Dd(e,me.id,K.id),Q=Pp(K.root),X=f&&Q.length>1?tR(Q,K.activeTerminalId,m[J]):null;return!te&&!o.has(J)?null:u.jsx("div",{className:"workspace-tab-surface","data-active":te,"aria-hidden":!te,children:u.jsx(Ab,{node:K.root,terminals:q.terminals,editors:W.editors,api:U,activeTerminalId:K.activeTerminalId,visible:te,refreshCwdOnEnter:te&&l,tabId:K.id,codeServerContext:{serverKey:Rl(e),serverName:t,tabName:K.title||q.terminals[K.activeTerminalId]?.title||"Terminal"},dropZoneActive:te&&d!==null,draggingTerminalId:te?d?.terminalId??null:null,mobileFocusLeafKey:X,onSelect:p,onClose:b,onCloseEditor:_,onResize:S,onExit:w,onSnapshot:x,...R?{onAuthClose:R}:{}})},K.id)}))})}function Jz(e){const t=jT(e);if(t)switch(t.id){case"server.previous":case"server.next":case"tab.previous":case"tab.next":case"favorites.toggle":return{type:t.id};case"tab.index":case"pane.index":return t.index===null?null:{type:t.id,index:t.index};case"split.right":return{type:"split",direction:"vertical"};case"split.down":return{type:"split",direction:"horizontal"};default:return null}if(e.ctrlKey&&e.altKey&&!e.metaKey&&!e.shiftKey){const n=t8(e.key);return n?{type:"pane.direction",direction:n}:null}return null}function e8(e,t,n){switch(n.type){case"pane.direction":return $z(e,t,n.direction);case"pane.index":return Fz(e,n.index);default:return null}}function t8(e){switch(e){case"ArrowLeft":return"left";case"ArrowRight":return"right";case"ArrowUp":return"up";case"ArrowDown":return"down";default:return null}}function n8(e,t,n){if(e.length===0)return null;const s=e.findIndex(l=>l.id===t);return e[((s===-1?0:s)+n+e.length)%e.length]??null}function Pp(e){return e.type==="pane"?[{key:Kc(e.terminalId),type:"terminal",terminalId:e.terminalId}]:e.type==="editor"?[{key:nR(e.editorId),type:"editor",editorId:e.editorId,title:e.title}]:[...Pp(e.first),...Pp(e.second)]}function Yb(e){return e.type==="pane"?[]:e.type==="editor"?[e.editorId]:[...Yb(e.first),...Yb(e.second)]}function tR(e,t,n){if(n&&e.some(o=>o.key===n))return n;const s=t?Kc(t):null;return s&&e.some(o=>o.key===s)?s:e[0]?.key??null}function Kc(e){return`terminal:${e}`}function nR(e){return`editor:${e}`}function i8(e){if(!(e instanceof HTMLElement)||e.closest(".xterm"))return!1;if(e.closest('input, textarea, select, [role="textbox"]'))return!0;const t=e.closest("[contenteditable]");return t instanceof HTMLElement&&t.getAttribute("contenteditable")?.toLowerCase()!=="false"}function r8({dialog:e,activePaneCwd:t,activeWorkspaceCwd:n,onChange:s,onManualCwdChange:o,onBrowse:l,onCancel:d,onSubmit:f}){const m=e.browseRoot?.rootPath??e.cwd,p=e.browseEntries.filter(w=>w.kind==="directory"),b=e.submitStatus==="submitting";function _(w){s(x=>x&&{...x,...w})}function S(w){w&&(_({cwd:w,error:null}),l(w))}return u.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-dialog-title",onClick:d,children:u.jsxs("form",{className:"security-panel workspace-dialog",onClick:w=>w.stopPropagation(),onSubmit:w=>{w.preventDefault(),b||f()},children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsx("h2",{id:"workspace-dialog-title",children:e.mode==="create"?"New Workspace":"Edit Workspace"}),u.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:d,children:"x"})]}),u.jsxs("section",{className:"workspace-dialog-body",children:[u.jsxs("label",{className:"workspace-dialog-field",children:[u.jsx("span",{children:"Name"}),u.jsx("input",{value:e.title,autoFocus:!0,disabled:b,onChange:w=>_({title:w.currentTarget.value,error:null}),placeholder:"Workspace name"})]}),u.jsxs("label",{className:"workspace-dialog-field",children:[u.jsx("span",{children:"Default cwd"}),u.jsxs("div",{className:"workspace-dialog-path-row",children:[u.jsx("input",{value:e.cwd,disabled:b,onChange:w=>o(w.currentTarget.value),placeholder:"/home/user/project"}),u.jsx("button",{type:"button",onClick:()=>{l(e.cwd)},disabled:b||!e.cwd.trim()||e.browseStatus==="loading",children:"Browse"})]})]}),u.jsxs("div",{className:"workspace-dialog-quick-actions",children:[u.jsx("button",{type:"button",onClick:()=>S(t),disabled:b||!t,children:"Use active pane"}),u.jsx("button",{type:"button",onClick:()=>S(n),disabled:b||!n,children:"Use current workspace"})]}),u.jsxs("div",{className:"workspace-dialog-browser","aria-label":"Workspace folder browser","aria-busy":e.browseStatus==="loading",children:[u.jsxs("div",{className:"workspace-dialog-browser-header",children:[u.jsx("span",{title:m,children:m||"No folder selected"}),u.jsx("button",{type:"button",onClick:()=>{l(a8(m))},disabled:b||!m||m==="/"||e.browseStatus==="loading",children:"Up"})]}),e.browseStatus==="loading"?u.jsx("div",{className:"workspace-dialog-empty",children:"Loading..."}):null,e.browseStatus!=="loading"&&p.length===0?u.jsx("div",{className:"workspace-dialog-empty",children:"No folders"}):null,e.browseStatus!=="loading"&&p.length>0?u.jsx("div",{className:"workspace-dialog-folder-list",children:p.map(w=>u.jsxs("button",{type:"button","aria-label":`Choose folder ${w.name}`,disabled:b,onClick:()=>{l(s8(m,w.path))},children:[u.jsx("span",{children:w.name}),u.jsx("small",{children:w.path})]},w.path))}):null]}),e.error?u.jsx("div",{className:"workspace-dialog-error",role:"alert",children:e.error}):null]}),u.jsxs("div",{className:"workspace-dialog-actions",children:[u.jsx("button",{type:"button",className:"secondary-button",onClick:d,children:"Cancel"}),u.jsx("button",{type:"submit",className:"primary-button",disabled:b||e.browseStatus==="loading",children:b?"Saving...":e.mode==="create"?"Create":"Save"})]})]})})}function s8(e,t){return t?t.startsWith("/")?np(t):np(`${e||"/"}/${t}`):np(e)}function a8(e){const t=np(e);if(!t||t==="/")return"/";const n=t.lastIndexOf("/");return n<=0?"/":t.slice(0,n)}function np(e){const t=e.trim();if(!t)return"";const n=t.replace(/\/+/g,"/");return n==="/"?"/":n.endsWith("/")?n.slice(0,-1):n}function o8(e){return e>99?"99+":String(e)}function l8(e){const t=[];return e.workingTerminalCount>0&&t.push(`${e.workingTerminalCount} ${e.workingTerminalCount===1?"pane is":"panes are"} working`),e.unreadCompletionCount>0&&t.push(`${e.unreadCompletionCount} unreviewed completion${e.unreadCompletionCount===1?"":"s"}`),t.join(" · ")}function c8({onCreate:e}){return u.jsxs("div",{className:"empty-workspace",children:[u.jsx("span",{children:"No terminal is open."}),u.jsx("button",{type:"button",onClick:e,children:"New tab"})]})}function u8({workspaceId:e,active:t,disabled:n=!1,reorderable:s=!1,dragging:o=!1,dropPlacement:l=null,working:d=!1,unread:f=!1,children:m}){const{setNodeRef:p,isOver:b}=Vp({id:`workspace-drop:${e}`,data:{kind:"workspace",workspaceId:e},disabled:n}),_=["workspace-list-item",t?"workspace-list-item--active":"",s?"workspace-list-item--reorderable":"",o?"workspace-list-item--dragging":"",d?"workspace-list-item--working":"",f?"workspace-list-item--unread":"",l?"workspace-list-item--drop-target":"",l?`workspace-list-item--drop-${l}`:""].filter(Boolean).join(" ");return u.jsx("div",{ref:p,className:_,"data-workspace-id":e,"data-drop-over":b?"true":void 0,children:m})}function d8({label:e,count:t,warning:n,onCancel:s,onHide:o,onDelete:l}){return u.jsx("div",{className:"security-overlay",role:"dialog","aria-modal":"true","aria-labelledby":"close-terminal-title",onClick:s,children:u.jsxs("div",{className:"security-panel terminal-delete-dialog",onClick:d=>d.stopPropagation(),children:[u.jsxs("header",{className:"security-panel-header",children:[u.jsx("h2",{id:"close-terminal-title",children:"Close Terminal"}),u.jsx("button",{type:"button",className:"security-close","aria-label":"Close",onClick:s,children:"x"})]}),u.jsxs("section",{className:"terminal-delete-dialog-body",children:[u.jsx("p",{children:t===1?"What should happen to this terminal?":`What should happen to these ${t} panes?`}),u.jsx("span",{children:e}),u.jsx("small",{children:"Hide keeps the shell running in this workspace. Delete destroys the underlying session."}),n?u.jsx("div",{className:"terminal-delete-warning",role:"alert",children:n}):null]}),u.jsxs("div",{className:"terminal-delete-dialog-actions",children:[u.jsx("button",{type:"button",className:"secondary-button",onClick:s,children:"Cancel"}),u.jsx("button",{type:"button",className:"secondary-button",onClick:o,children:"Hide"}),u.jsx("button",{type:"button",className:"terminal-delete-confirm",onClick:l,children:"Delete"})]})]})})}function h8({targets:e,activeLeafKey:t,terminals:n,editors:s,onSelect:o}){const[l,d]=v.useState(!1);if(e.length<=1)return null;const f=t?e.findIndex(S=>S.key===t):-1,m=f>=0?f:0,p=e[m]??e[0],b=KC(p,n,s);function _(S){const w=(m+S+e.length)%e.length,x=e[w];x&&o(x)}return u.jsxs("div",{className:"mobile-pane-switcher",role:"group","aria-label":"Pane switcher",children:[u.jsx("button",{type:"button","aria-label":"Previous pane",onClick:()=>_(-1),children:"<"}),u.jsxs("button",{type:"button",className:"mobile-pane-current","aria-label":"Open pane switcher","aria-haspopup":"dialog","aria-expanded":l,title:b,onClick:()=>d(!0),children:["Pane ",m+1,"/",e.length," | ",b]}),u.jsx("button",{type:"button","aria-label":"Next pane",onClick:()=>_(1),children:">"}),l?u.jsx("div",{className:"mobile-pane-sheet-backdrop",onClick:()=>d(!1),children:u.jsxs("section",{className:"mobile-pane-sheet",role:"dialog","aria-modal":"true","aria-label":"Pane switcher",onClick:S=>S.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Panes"}),u.jsx("button",{type:"button","aria-label":"Close pane switcher",onClick:()=>d(!1),children:"x"})]}),u.jsx("div",{className:"mobile-pane-sheet-list",children:e.map((S,w)=>{const x=KC(S,n,s),R=f8(S,n,s),L=S.key===p.key;return u.jsxs("button",{type:"button","data-active":L,onClick:()=>{o(S),d(!1)},children:[u.jsx("span",{className:"mobile-pane-sheet-index",children:w+1}),u.jsxs("span",{className:"mobile-pane-sheet-copy",children:[u.jsx("strong",{children:x}),u.jsx("small",{children:R})]}),u.jsx("span",{className:"mobile-pane-sheet-type",children:S.type})]},S.key)})})]})}):null]})}function KC(e,t,n){if(e.type==="editor")return n[e.editorId]?.title||e.title||e.editorId;const s=t[e.terminalId];return s?.title||s?.cwd||e.terminalId}function f8(e,t,n){if(e.type==="editor"){const l=n[e.editorId];return l?.path?`editor | ${l.path}`:"editor"}const s=t[e.terminalId];return s?`${s.activity==="busy"?`busy${s.currentCommand?`: ${s.currentCommand}`:""}`:s.activity==="idle"?"idle":s.status} | ${s.cwd}`:"terminal"}function p8(e){const[t,n]=v.useState(()=>m8(e));return v.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function"){n(!1);return}const s=window.matchMedia(e),o=()=>n(s.matches);return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):(s.addListener(o),()=>s.removeListener(o))},[e]),t}function m8(e){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches}function g8(){if(typeof window>"u")return null;const e=wM(window.location.hash);if(!e)return null;try{window.history.replaceState(window.history.state,document.title,`${window.location.pathname}${window.location.search}`)}catch{}return e}function v8(e){if(!e||typeof e!="object")return null;const t=e;return t.type!=="nterminal.notificationFocus"?null:Gp(t.focus)}function Vv(e,t){for(const n of e.workspaces)for(const s of n.tabs)if(Nn(s.root).includes(t))return{workspaceId:n.id,tabId:s.id};return null}function li(e,t){return e===t}function Gr(e){return JSON.stringify([e.serverId,e.workspaceId,e.tabId])}function qC(e,t){return e.length!==t.length?!1:e.every((n,s)=>{const o=t[s];return o!==void 0&&Gr(n)===Gr(o)&&n.serverName===o.serverName&&n.workspaceName===o.workspaceName&&n.tabName===o.tabName&&n.cwd===o.cwd&&n.paneCount===o.paneCount&&n.providers.length===o.providers.length&&n.providers.every((l,d)=>l===o.providers[d])})}function ip(e){return e??"__local__"}function Dd(e,t,n){return`${ip(e)}:${t}:${n}`}class zp extends Error{constructor(){super(iR())}}function _8(e){return e?{workspaceKey:`${FC}:${e}`}:{workspaceKey:FC}}function b8(e){const t=localStorage.getItem(e.workspaceKey);if(!t)return null;try{const n=JSON.parse(t);if(Tk(n))throw new zp;const s=Yp(n);return s?Gb(s):null}catch(n){if(n instanceof zp)throw n;return null}}function Gb(e){if(Tk(e))throw new zp;const t=Yp(e);return t?{savedWorkspaces:t.workspaces,savedActiveWorkspaceId:t.activeWorkspaceId}:null}function Lc(e,t){if(e.workspaces.length>0){localStorage.setItem(t.workspaceKey,JSON.stringify(e));return}localStorage.removeItem(t.workspaceKey)}function y8(e,t){const n=gt(e).lastPersistedLayoutJson;if(n){localStorage.setItem(t.workspaceKey,n);return}localStorage.removeItem(t.workspaceKey)}function S8(e){return`This workspace already has ${e} hidden terminal session${e===1?"":"s"}; the limit is ${Io}. Re-open or delete hidden sessions before hiding more.`}function iR(){return`A saved terminal layout has more than ${Io} hidden terminal sessions in one workspace. Re-open or delete hidden sessions, then save the layout again.`}function w8(e){const t=e.workspaces.find(o=>o.id===e.activeWorkspaceId)??e.workspaces[0],n=t?.tabs.find(o=>o.id===t.activeTabId)??t?.tabs[0],s=n?e.terminals[n.activeTerminalId]:void 0;return s?.status==="running"?s:null}function x8(e){return e.results.find(t=>t.status==="failed"&&t.error)?.error}function C8(e){return e.split("/").filter(Boolean).pop()??e}function k8(){try{return localStorage.getItem(eR)==="true"}catch{return!1}}function T8(e){try{localStorage.setItem(eR,e?"true":"false")}catch{}}function Rl(e){return e??Zt}function Yv(e,t){const n=Object.keys(e),s=Object.keys(t);return n.length===s.length&&n.every(o=>e[o]===t[o])}function E8(e){if(!e)return"session · local";const t=Date.parse(e);if(!Number.isFinite(t))return"session · local";const n=t-Date.now();if(n<=0)return"session · expired";const s=Math.max(1,Math.floor(n/6e4));return s<60?`session · ${s}m left`:`session · ${Math.floor(s/60)}h left`}function VC({name:e}){return u.jsxs("svg",{className:"workspace-footer-icon",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[e==="settings"?u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"M4 7h9"}),u.jsx("path",{d:"M17 7h3"}),u.jsx("circle",{cx:"15",cy:"7",r:"2"}),u.jsx("path",{d:"M4 12h3"}),u.jsx("path",{d:"M11 12h9"}),u.jsx("circle",{cx:"9",cy:"12",r:"2"}),u.jsx("path",{d:"M4 17h9"}),u.jsx("path",{d:"M17 17h3"}),u.jsx("circle",{cx:"15",cy:"17",r:"2"})]}):null,e==="logout"?u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"M10 6H6v12h4"}),u.jsx("path",{d:"M13 8l4 4-4 4"}),u.jsx("path",{d:"M8 12h9"})]}):null]})}function Ca(e){return e instanceof Error?e.message:"Request failed"}function R8({api:e,onDone:t}){const[n,s]=v.useState(null),[o,l]=v.useState(null),[d,f]=v.useState(""),[m,p]=v.useState(!1),[b,_]=v.useState(null),[S,w]=v.useState(null);v.useEffect(()=>{let R=!1;return e.setupTotp().then(L=>{R||(s(L.qrDataUrl),l(L.secret))}).catch(L=>{R||w(L instanceof Error?L.message:"Failed to generate QR code")}),()=>{R=!0}},[e]);async function x(R){if(R.preventDefault(),!!o){p(!0),_(null);try{await e.activateTotp({secret:o,otp:d}),t()}catch(L){_(L instanceof Error?L.message:"Verification failed")}finally{p(!1)}}}return S?u.jsx("p",{className:"form-error",children:S}):!n||!o?u.jsx("p",{className:"muted",children:"Generating authenticator setup..."}):u.jsxs("div",{className:"totp-setup",children:[u.jsx("p",{className:"totp-setup-instructions",children:"Scan this QR code with an authenticator app (Google Authenticator, Authy, 1Password, etc.), then enter the 6-digit code to confirm."}),u.jsx("div",{className:"totp-qr-container",children:u.jsx("img",{src:n,alt:"TOTP QR code",width:192,height:192})}),u.jsxs("details",{className:"totp-secret-details",children:[u.jsx("summary",{children:"Can't scan? Enter manually"}),u.jsx("p",{className:"totp-secret-text",children:o})]}),u.jsxs("form",{className:"auth-form",onSubmit:x,children:[u.jsxs("label",{children:["Verification code",u.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:d,onChange:R=>f(R.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),b?u.jsx("p",{className:"form-error",children:b}):null,u.jsx("button",{type:"submit",disabled:m||d.length!==6,children:"Activate 2FA"})]})]})}function N8(e){return{source:Gv(e?.source)||"unknown",...typeof e?.status=="number"?{status:e.status}:{},...e?.activeAgentId!==void 0?{activeAgentId:e.activeAgentId}:{},...e?.terminalId?{terminalId:Gv(e.terminalId)}:{},...e?.detail?{detail:Gv(e.detail)}:{}}}function D8(e){return{invalidationSource:e.source}}function M8(e){Pi("auth.session_invalid.request",rR(e)),!(typeof console>"u"||typeof console.warn!="function")&&(console.warn("[nterminal] session invalid requested",e),fy("session-invalid-request").catch(()=>{}))}function A8(e,t){Pi("auth.session_invalid.result",{...rR(e),authenticated:t}),!(typeof console>"u"||typeof console.warn!="function")&&(console.warn("[nterminal] session invalid check result",{...e,authenticated:t}),fy("session-invalid-result").catch(()=>{}))}function rR(e){return{source:e.source,...typeof e.status=="number"?{status:e.status}:{},...e.activeAgentId!==void 0?{activeAgentId:e.activeAgentId}:{},...e.terminalId?{terminalId:e.terminalId}:{},...e.detail?{detail:e.detail}:{}}}function Gv(e){return e?e.replace(/[^a-zA-Z0-9_.:-]/g,"_").slice(0,96):""}function L8({api:e,serverApi:t,activeAgentId:n=null,onSelectServer:s}){const o=v.useMemo(()=>e??Hp(),[e]),l=v.useMemo(()=>t??Is(null),[t]),[d,f]=v.useState(null),[m,p]=v.useState(null),b=v.useRef(null),_=v.useRef(0),S=v.useRef("loading"),w=v.useCallback(()=>{_.current++,b.current=null},[]);v.useEffect(()=>w,[w]),v.useEffect(()=>{let H=!1;return o.getSession().then(U=>{H||(f(U),p(null))}).catch(U=>{H||(p(Ol(U)),f(null))}),()=>{H=!0}},[o]);const x=I8(d);v.useEffect(()=>{const H=S.current;Pi("auth.view",{view:x,previousView:H,authenticated:d?.authenticated??null,passwordSet:d?.passwordSet??null,totpEnabled:d?.totpEnabled??null,deviceTrusted:d?.deviceTrusted??null,currentIpWhitelisted:d?.currentIpWhitelisted??null}),H==="workspace"&&x!=="workspace"&&(kv(),fy(`auth-left-workspace-${x}`).catch(()=>{})),S.current=x},[d,x]);async function R(){const H=await o.getSession();f(H),p(null)}async function L(){w(),kv(),Bv(),Wv(),rC(),sC(),p(null),f(null);try{await R()}catch(H){p(Ol(H))}}const A=v.useCallback(H=>{const U=N8(H);if(M8(U),b.current)return b.current;const q=_.current,Y=(async()=>{p(null);try{const I=await o.getSession(D8(U));if(q!==_.current)return;if(A8(U,I.authenticated),f(I),I.authenticated){cz(),aI();return}Bv(),Wv(),rC(),sC()}catch(I){q===_.current&&p(Ol(I))}finally{q===_.current&&(b.current=null)}})();return b.current=Y,Y},[o]);if(v.useEffect(()=>{if(x==="workspace")return lz(H=>{A({source:"activity-auth-check",detail:H})})},[x,A]),x==="workspace")return u.jsx(Zz,{api:o,serverApi:l,activeAgentId:n,onSelectServer:s,sessionExpiresAt:d?.expiresAt??null,previewMode:d?.previewMode===!0,onSessionInvalid:H=>{A(H)},onLogout:async()=>{w(),kv(),Bv(),Wv();const H=await o.logout();f(H)}});const W={loading:"Terminal",setup_password:"Set password",setup_totp:"Set up 2FA",login:"Unlock terminal",reauth:"Verify it’s you",workspace:"Terminal"};return u.jsxs("main",{className:"auth-screen",children:[u.jsxs("div",{className:"auth-background","aria-hidden":"true",children:[u.jsx("div",{className:"auth-grid"}),u.jsx("div",{className:"auth-glow"})]}),u.jsxs("section",{className:"auth-panel","aria-busy":x==="loading",children:[u.jsxs("header",{className:"auth-header",children:[u.jsxs("div",{className:"auth-brand",children:[u.jsx(tk,{size:26}),u.jsxs("div",{children:[u.jsx(nk,{height:17}),u.jsx("p",{className:"auth-host",children:"local terminal"})]})]}),u.jsx("h1",{children:W[x]})]}),m?u.jsx("p",{className:"form-error",children:m}):null,x==="loading"?u.jsx("p",{className:"muted",children:"Checking session..."}):null,x==="loading"&&m?u.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{L()},children:"Retry"}):null,x==="setup_password"?u.jsx(j8,{api:o,onSession:H=>{f(H)}}):null,x==="setup_totp"?u.jsx(R8,{api:o,onDone:()=>{R()}}):null,x==="login"?u.jsx(O8,{api:o,session:d,onSession:f,onRefresh:R}):null,x==="reauth"?u.jsx(B8,{api:o,session:d,onSession:f,onFullLogin:()=>f(H=>H&&{...H,deviceTrusted:!1})}):null]})]})}function j8({api:e,onSession:t}){const[n,s]=v.useState(""),[o,l]=v.useState(""),[d,f]=v.useState(!1),[m,p]=v.useState(null);async function b(_){_.preventDefault(),f(!0),p(null);try{if(n!==o){p("Passwords do not match");return}t(await e.setupPassword({password:n}))}catch(S){p(Ol(S))}finally{f(!1)}}return u.jsxs("form",{className:"auth-form",onSubmit:b,children:[u.jsxs("label",{children:["Password",u.jsx("input",{autoFocus:!0,value:n,onChange:_=>s(_.currentTarget.value),type:"password",minLength:8,required:!0})]}),u.jsxs("label",{children:["Confirm password",u.jsx("input",{value:o,onChange:_=>l(_.currentTarget.value),type:"password",minLength:8,required:!0})]}),m?u.jsx("p",{className:"form-error",children:m}):null,u.jsx("button",{type:"submit",disabled:d||n.length<8||o.length<8,children:"Set password"})]})}function O8({api:e,session:t,onSession:n,onRefresh:s}){const[o,l]=v.useState(""),[d,f]=v.useState(""),[m,p]=v.useState(!1),[b,_]=v.useState(!1),[S,w]=v.useState(null),x=t?.totpEnabled??!1,R=t?.currentIpWhitelisted??!1;async function L(A){A.preventDefault(),_(!0),w(null);try{n(await e.login({password:o,...x?{otp:d}:{},rememberNetwork:m}))}catch(W){w(Ol(W))}finally{_(!1)}}return u.jsxs("form",{className:"auth-form",onSubmit:L,children:[u.jsxs("label",{children:["Password",u.jsx("input",{autoFocus:!0,type:"password",value:o,onChange:A=>l(A.currentTarget.value),required:!0})]}),x?u.jsxs("label",{children:["Authenticator code",u.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:d,onChange:A=>f(A.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}):null,R?null:u.jsxs("label",{className:"auth-checkbox",children:[u.jsx("input",{type:"checkbox",checked:m,onChange:A=>p(A.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),S?u.jsx("p",{className:"form-error",children:S}):null,u.jsxs("div",{className:"button-row",children:[u.jsx("button",{type:"submit",disabled:b||o.length===0||x&&d.length!==6,children:"Unlock"}),u.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{s()},disabled:b,children:"Refresh"})]})]})}function B8({api:e,session:t,onSession:n,onFullLogin:s}){const o=t?.currentIpWhitelisted??!1,[l,d]=v.useState(""),[f,m]=v.useState(!1),[p,b]=v.useState(!1),[_,S]=v.useState(!1),[w,x]=v.useState(!1),[R,L]=v.useState(null),A=zt.useCallback(async(H,U)=>{b(!0),L(null);try{n(await e.reauth({...H?{otp:H}:{},rememberNetwork:U}))}catch(q){L(Ol(q))}finally{b(!1)}},[e,n]);v.useEffect(()=>{if(o){let H=!1;S(!0),x(!1),L(null);const U=window.setTimeout(()=>{H||x(!0)},6e3);return e.reauth({rememberNetwork:!1}).then(q=>{H||n(q)}).catch(q=>{H||(L(Ol(q)),x(!0))}).finally(()=>{window.clearTimeout(U),H||S(!1)}),()=>{H=!0,window.clearTimeout(U)}}},[e,o,n]);async function W(H){H.preventDefault(),await A(l,f)}return o&&_&&!w&&!R?u.jsx("p",{className:"muted",children:"Reconnecting from a trusted network…"}):u.jsxs("form",{className:"auth-form",onSubmit:W,children:[o&&w&&!R?u.jsx("p",{className:"muted",children:"Automatic verification is taking longer than expected. You can enter a code or use password login."}):null,u.jsx("p",{className:"muted",children:"This device is remembered. Enter your authenticator code to continue."}),u.jsxs("label",{children:["Authenticator code",u.jsx("input",{autoFocus:!0,type:"text",inputMode:"numeric",pattern:"[0-9]{6}",maxLength:6,value:l,onChange:H=>d(H.currentTarget.value.replace(/\D/g,"")),placeholder:"000000",required:!0})]}),u.jsxs("label",{className:"auth-checkbox",children:[u.jsx("input",{type:"checkbox",checked:f,onChange:H=>m(H.currentTarget.checked)}),"Remember this network (skip 2FA here next time)"]}),R?u.jsx("p",{className:"form-error",children:R}):null,u.jsxs("div",{className:"button-row",children:[u.jsx("button",{type:"submit",disabled:p||l.length!==6,children:"Continue"}),u.jsx("button",{type:"button",className:"secondary-button",onClick:s,disabled:p,children:"Use password instead"})]})]})}function I8(e){return e?e.passwordSet?e.authenticated&&!e.totpEnabled?"setup_totp":e.authenticated?"workspace":e.deviceTrusted&&e.totpEnabled?"reauth":"login":"setup_password":"loading"}function Ol(e){return e instanceof Error?e.message:"Request failed"}const YC="NTerminal",Xb="nterminal.activeAgentId";function P8(){const[e,t]=v.useState(()=>z8()),n=v.useMemo(()=>Hp(),[]),s=v.useMemo(()=>Is(e),[e]);v.useEffect(()=>{const l=()=>{const d=BP();document.title=d>0?`(${d}) ${YC}`:YC};return l(),OP(l)},[]);function o(l){H8(l),t(l)}return u.jsx(L8,{api:n,activeAgentId:e,serverApi:s,onSelectServer:o})}function z8(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Xb);return e&&e.trim()?e:null}catch{return null}}function H8(e){if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Xb,e);return}window.localStorage.removeItem(Xb)}catch{}}const GC=["gesturestart","gesturechange","gestureend"],U8=[".workspace-list",".workspace-nav",".server-list",".terminal-tab-list",".mobile-terminal-key-bar",".upload-toast-body",".file-tree",".file-detail",".file-editor",".file-markdown-preview",".editor-markdown-preview",".settings-content",".settings-nav",".transcript-dialog-scroll",".transcript-filter-group"].join(",");function $8(e=window){if(!W8(e))return()=>{};const t={passive:!1},n=e.document;function s(l){l.cancelable&&l.preventDefault()}function o(l){if(l.defaultPrevented)return;const d=l.touches;!d||d.length===0||(d.length>1||!F8(l.target))&&s(l)}for(const l of GC)n.addEventListener(l,s,t);return n.addEventListener("touchmove",o,t),n.addEventListener("dblclick",s,t),()=>{for(const l of GC)n.removeEventListener(l,s,t);n.removeEventListener("touchmove",o,t),n.removeEventListener("dblclick",s,t)}}function F8(e){return e instanceof Element&&e.closest(U8)!==null}function W8(e){return e.navigator.maxTouchPoints>0?!0:typeof e.matchMedia=="function"&&e.matchMedia("(pointer: coarse)").matches}RM();T5();$8();ty();EN.createRoot(document.getElementById("root")).render(u.jsx(zt.StrictMode,{children:u.jsx(P8,{})}));export{zt as R,_N as g,u as j};