termdock 1.4.134 → 1.4.135
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{ModelPreview-CFATmDMn.js → ModelPreview-DT9Bn9h2.js} +1 -1
- package/dist/client/assets/{abnfDiagram-VRR7QNED-BbyA8ozp.js → abnfDiagram-VRR7QNED-BqrSLPKg.js} +1 -1
- package/dist/client/assets/{arc-CpTVAdlj.js → arc-Dd83pxcL.js} +1 -1
- package/dist/client/assets/{architectureDiagram-ZJ3FMSHR-D8H_GjPS.js → architectureDiagram-ZJ3FMSHR-CsNuQKE3.js} +1 -1
- package/dist/client/assets/{blockDiagram-677ZJIJ3-LDUjP25C.js → blockDiagram-677ZJIJ3-CLR_mE_c.js} +1 -1
- package/dist/client/assets/{c4Diagram-LMCZKHZV-Dqb3edy0.js → c4Diagram-LMCZKHZV-BUpcmsi5.js} +1 -1
- package/dist/client/assets/channel-BA_hCEqV.js +1 -0
- package/dist/client/assets/{chunk-2Q5K7J3B-DJtLmHee.js → chunk-2Q5K7J3B-QQywRieT.js} +1 -1
- package/dist/client/assets/{chunk-32BRIVSS-BG15LwxU.js → chunk-32BRIVSS-DU9a8ckE.js} +1 -1
- package/dist/client/assets/{chunk-5VM5RSS4-DX9c30HP.js → chunk-5VM5RSS4-DqVtE9lh.js} +1 -1
- package/dist/client/assets/{chunk-EX3LRPZG-k77tHt2J.js → chunk-EX3LRPZG-BqPij0fu.js} +1 -1
- package/dist/client/assets/{chunk-JWPE2WC7-CrqhOXW3.js → chunk-JWPE2WC7-haMC8zH8.js} +1 -1
- package/dist/client/assets/{chunk-MOJQB5TN-C9SA_wsQ.js → chunk-MOJQB5TN-BcfZQ_Nn.js} +1 -1
- package/dist/client/assets/{chunk-RYQCIY6F-DAl0B75V.js → chunk-RYQCIY6F-yit0qixk.js} +1 -1
- package/dist/client/assets/{chunk-V7JOEXUC-DEWh_CUK.js → chunk-V7JOEXUC-Bflxzotk.js} +1 -1
- package/dist/client/assets/{chunk-VR4S4FIN-DmgWSqTu.js → chunk-VR4S4FIN-4W2hmPDZ.js} +1 -1
- package/dist/client/assets/{chunk-XXDRQBXY-tLyEVLHM.js → chunk-XXDRQBXY-BzHLdSxE.js} +1 -1
- package/dist/client/assets/classDiagram-OUVF2IWQ-By8ZcMDg.js +1 -0
- package/dist/client/assets/classDiagram-v2-EOCWNBFH-By8ZcMDg.js +1 -0
- package/dist/client/assets/{cose-bilkent-JH36ORCC-D7NNcBEa.js → cose-bilkent-JH36ORCC-CcjCHkoc.js} +1 -1
- package/dist/client/assets/{cynefin-VYW2F7L2-WPf5sAN3.js → cynefin-VYW2F7L2-0gG9Z02e.js} +1 -1
- package/dist/client/assets/{cynefinDiagram-TSTJHNR4-BcJkQPCZ.js → cynefinDiagram-TSTJHNR4-CA4P42gk.js} +1 -1
- package/dist/client/assets/{dagre-VKFMJZFB-Cb-lRK4P.js → dagre-VKFMJZFB-BSXNEIHp.js} +1 -1
- package/dist/client/assets/{diagram-FQU43EPY-DB6W0zgg.js → diagram-FQU43EPY-FNR-L4gD.js} +1 -1
- package/dist/client/assets/{diagram-G47NLZAW-CCLEyGP7.js → diagram-G47NLZAW-CMVH594u.js} +1 -1
- package/dist/client/assets/{diagram-NH7WQ7WH-C6IBg2B3.js → diagram-NH7WQ7WH-DR3Dd1gC.js} +1 -1
- package/dist/client/assets/{diagram-OA4YK3LP-CCJn4LAS.js → diagram-OA4YK3LP-CfzmRJpg.js} +1 -1
- package/dist/client/assets/{diagram-WEI45ONY-6Ey2qBZ7.js → diagram-WEI45ONY-BPa1Z6Kg.js} +1 -1
- package/dist/client/assets/{ebnfDiagram-CCIWWBDH-2fMw77EU.js → ebnfDiagram-CCIWWBDH-fhWCqRkv.js} +1 -1
- package/dist/client/assets/{erDiagram-Q63AITRT-CLLVdktX.js → erDiagram-Q63AITRT-CHSTshrZ.js} +1 -1
- package/dist/client/assets/{flowDiagram-23GEKE2U-dS5xqfIk.js → flowDiagram-23GEKE2U-Cop_JxGl.js} +1 -1
- package/dist/client/assets/{ganttDiagram-NO4QXBWP-CUGJ_uDD.js → ganttDiagram-NO4QXBWP-B4BiczvE.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-IHSO6WYX-DfGdRGft.js → gitGraphDiagram-IHSO6WYX-Cp_6UdIQ.js} +1 -1
- package/dist/client/assets/{index-CgjOcdgV.js → index-ChQVPg1H.js} +5 -5
- package/dist/client/assets/{infoDiagram-FWYZ7A6U-DmWDbahl.js → infoDiagram-FWYZ7A6U-CKaniVj3.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-FXEZZL3T-yVSNrjja.js → ishikawaDiagram-FXEZZL3T-DzQFdFkY.js} +1 -1
- package/dist/client/assets/{journeyDiagram-5HDEW3XC-B5iQpSnc.js → journeyDiagram-5HDEW3XC-BrwR-OSn.js} +1 -1
- package/dist/client/assets/{kanban-definition-HUTT4EX6-CODYQ2tD.js → kanban-definition-HUTT4EX6-CLgKAu-g.js} +1 -1
- package/dist/client/assets/{linear-BW-CWKMG.js → linear-BQbhytDh.js} +1 -1
- package/dist/client/assets/{mermaid.core-26RbK9NE.js → mermaid.core-BCd0z5d0.js} +4 -4
- package/dist/client/assets/{mindmap-definition-LN4V7U3C-CriPfTkg.js → mindmap-definition-LN4V7U3C-DBp5oKiB.js} +1 -1
- package/dist/client/assets/{pegDiagram-2B236MQR-DMhyKW4X.js → pegDiagram-2B236MQR-0Nnv3qsy.js} +1 -1
- package/dist/client/assets/{pieDiagram-ENE6RG2P-CHgzvNfD.js → pieDiagram-ENE6RG2P-ChqeLJJ7.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-ABIIQ3AL-B9GLOwLk.js → quadrantDiagram-ABIIQ3AL-CB3QCKXV.js} +1 -1
- package/dist/client/assets/{railroadDiagram-RFXS5EU6-DYhN8VyR.js → railroadDiagram-RFXS5EU6-Bqw3xxA6.js} +1 -1
- package/dist/client/assets/{requirementDiagram-TGXJPOKE-APhFGIjp.js → requirementDiagram-TGXJPOKE-CcZTOo6S.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-HTMAVEWB-Ca_b20z-.js → sankeyDiagram-HTMAVEWB-YKxEg7pe.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-DBY2YBRQ-DR8JFXz_.js → sequenceDiagram-DBY2YBRQ-BWQ5w-0k.js} +1 -1
- package/dist/client/assets/{sizeCapture-X5ZJPWSS-COd1JT9F.js → sizeCapture-X5ZJPWSS-WDztVwIL.js} +1 -1
- package/dist/client/assets/{stateDiagram-2N3HPSRC-BdmG2XZp.js → stateDiagram-2N3HPSRC-TkxxRUYh.js} +1 -1
- package/dist/client/assets/stateDiagram-v2-6OUMAXLB-Dx08PAaE.js +1 -0
- package/dist/client/assets/{swimlanes-5IMT3BWC-CaiOiI9_.js → swimlanes-5IMT3BWC-BjPfAcvJ.js} +2 -2
- package/dist/client/assets/swimlanesDiagram-G3AALYLV-Bc4bntMJ.js +8 -0
- package/dist/client/assets/{timeline-definition-FHXFAJF6-dXmM2fn1.js → timeline-definition-FHXFAJF6-C2mQ54nf.js} +1 -1
- package/dist/client/assets/{vennDiagram-L72KCM5P-B35qGmUw.js → vennDiagram-L72KCM5P-CYRUoOkA.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-EHGQE667-m0bee3Iw.js → wardleyDiagram-EHGQE667-BpVxfq48.js} +1 -1
- package/dist/client/assets/{xychartDiagram-FW5EYKEG-DuscNL9U.js → xychartDiagram-FW5EYKEG-geKNfLi6.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/client/sw.js +1 -1
- package/package.json +1 -1
- package/runtime-manifest.json +1 -1
- package/dist/client/assets/channel-BSL_0ch_.js +0 -1
- package/dist/client/assets/classDiagram-OUVF2IWQ-_BHIabbP.js +0 -1
- package/dist/client/assets/classDiagram-v2-EOCWNBFH-_BHIabbP.js +0 -1
- package/dist/client/assets/stateDiagram-v2-6OUMAXLB-BhxwFKMp.js +0 -1
- package/dist/client/assets/swimlanesDiagram-G3AALYLV-BXKPMpiM.js +0 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Ca-rq7yX.js","assets/react-XDCjal2T.js","assets/ModelPreview-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Ca-rq7yX.js","assets/react-XDCjal2T.js","assets/ModelPreview-DT9Bn9h2.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/katex-55ZPZeOF.css","assets/mermaid.core-BCd0z5d0.js","assets/purify.es-CC4Brkr_.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{r as Pg,a as __,g as hS}from"./react-XDCjal2T.js";import{b as x,R as M,r as ci,a as L_}from"./dnd-BCFAPC0L.js";import{L as E_,l as I_}from"./terminal-C7X98Amf.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var z1={exports:{}},mf={};var u5;function R_(){if(u5)return mf;u5=1;var e=Pg(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(c,u,f){var p,g={},y=null,v=null;f!==void 0&&(y=""+f),u.key!==void 0&&(y=""+u.key),u.ref!==void 0&&(v=u.ref);for(p in u)r.call(u,p)&&!i.hasOwnProperty(p)&&(g[p]=u[p]);if(c&&c.defaultProps)for(p in u=c.defaultProps,u)g[p]===void 0&&(g[p]=u[p]);return{$$typeof:t,type:c,key:y,ref:v,props:g,_owner:s.current}}return mf.Fragment=n,mf.jsx=a,mf.jsxs=a,mf}var d5;function N_(){return d5||(d5=1,z1.exports=R_()),z1.exports}var o=N_(),Ip={},f5;function M_(){if(f5)return Ip;f5=1;var e=__();return Ip.createRoot=e.createRoot,Ip.hydrateRoot=e.hydrateRoot,Ip}var D_=M_();const j_=hS(D_);function h5(e){return e!==null&&typeof e=="object"&&"constructor"in e&&e.constructor===Object}function _y(e={},t={}){const n=["__proto__","constructor","prototype"];Object.keys(t).filter(r=>n.indexOf(r)<0).forEach(r=>{typeof e[r]>"u"?e[r]=t[r]:h5(t[r])&&h5(e[r])&&Object.keys(t[r]).length>0&&_y(e[r],t[r])})}const pS={body:{},addEventListener(){},removeEventListener(){},activeElement:{blur(){},nodeName:""},querySelector(){return null},querySelectorAll(){return[]},getElementById(){return null},createEvent(){return{initEvent(){}}},createElement(){return{children:[],childNodes:[],style:{},setAttribute(){},getElementsByTagName(){return[]}}},createElementNS(){return{}},importNode(){return null},location:{hash:"",host:"",hostname:"",href:"",origin:"",pathname:"",protocol:"",search:""}};function ld(){const e=typeof document<"u"?document:{};return _y(e,pS),e}const P_={document:pS,navigator:{userAgent:""},location:{hash:"",host:"",hostname:"",href:"",origin:"",pathname:"",protocol:"",search:""},history:{replaceState(){},pushState(){},go(){},back(){}},CustomEvent:function(){return this},addEventListener(){},removeEventListener(){},getComputedStyle(){return{getPropertyValue(){return""}}},Image(){},Date(){},screen:{},setTimeout(){},clearTimeout(){},matchMedia(){return{}},requestAnimationFrame(e){return typeof setTimeout>"u"?(e(),null):setTimeout(e,0)},cancelAnimationFrame(e){typeof setTimeout>"u"||clearTimeout(e)}};function na(){const e=typeof window<"u"?window:{};return _y(e,P_),e}function B_(e=""){return e.trim().split(" ").filter(t=>!!t.trim())}function F_(e){const t=e;Object.keys(t).forEach(n=>{try{t[n]=null}catch{}try{delete t[n]}catch{}})}function mS(e,t=0){return setTimeout(e,t)}function Km(){return Date.now()}function O_(e){const t=na();let n;return t.getComputedStyle&&(n=t.getComputedStyle(e,null)),!n&&e.currentStyle&&(n=e.currentStyle),n||(n=e.style),n}function Q_(e,t="x"){const n=na();let r,s,i;const a=O_(e);return n.WebKitCSSMatrix?(s=a.transform||a.webkitTransform,s.split(",").length>6&&(s=s.split(", ").map(c=>c.replace(",",".")).join(", ")),i=new n.WebKitCSSMatrix(s==="none"?"":s)):(i=a.MozTransform||a.OTransform||a.MsTransform||a.msTransform||a.transform||a.getPropertyValue("transform").replace("translate(","matrix(1, 0, 0, 1,"),r=i.toString().split(",")),t==="x"&&(n.WebKitCSSMatrix?s=i.m41:r.length===16?s=parseFloat(r[12]):s=parseFloat(r[4])),t==="y"&&(n.WebKitCSSMatrix?s=i.m42:r.length===16?s=parseFloat(r[13]):s=parseFloat(r[5])),s||0}function Rp(e){return typeof e=="object"&&e!==null&&e.constructor&&Object.prototype.toString.call(e).slice(8,-1)==="Object"}function $_(e){return typeof window<"u"&&typeof window.HTMLElement<"u"?e instanceof HTMLElement:e&&(e.nodeType===1||e.nodeType===11)}function Qa(...e){const t=Object(e[0]);for(let n=1;n<e.length;n+=1){const r=e[n];if(r!=null&&!$_(r)){const s=Object.keys(Object(r)).filter(i=>i!=="__proto__"&&i!=="constructor"&&i!=="prototype");for(let i=0,a=s.length;i<a;i+=1){const c=s[i],u=Object.getOwnPropertyDescriptor(r,c);u!==void 0&&u.enumerable&&(Rp(t[c])&&Rp(r[c])?r[c].__swiper__?t[c]=r[c]:Qa(t[c],r[c]):!Rp(t[c])&&Rp(r[c])?(t[c]={},r[c].__swiper__?t[c]=r[c]:Qa(t[c],r[c])):t[c]=r[c])}}}return t}function Od(e,t,n){e.style.setProperty(t,n)}function gS({swiper:e,targetPosition:t,side:n}){const r=na(),s=-e.translate;let i=null,a;const c=e.params.speed;e.wrapperEl.style.scrollSnapType="none",r.cancelAnimationFrame(e.cssModeFrameID);const u=t>s?"next":"prev",f=(g,y)=>u==="next"&&g>=y||u==="prev"&&g<=y,p=()=>{a=new Date().getTime(),i===null&&(i=a);const g=Math.max(Math.min((a-i)/c,1),0),y=.5-Math.cos(g*Math.PI)/2;let v=s+y*(t-s);if(f(v,t)&&(v=t),e.wrapperEl.scrollTo({[n]:v}),f(v,t)){e.wrapperEl.style.overflow="hidden",e.wrapperEl.style.scrollSnapType="",setTimeout(()=>{e.wrapperEl.style.overflow="",e.wrapperEl.scrollTo({[n]:v})}),r.cancelAnimationFrame(e.cssModeFrameID);return}e.cssModeFrameID=r.requestAnimationFrame(p)};p()}function Nc(e,t=""){const n=na(),r=[...e.children];return n.HTMLSlotElement&&e instanceof HTMLSlotElement&&r.push(...e.assignedElements()),t?r.filter(s=>s.matches(t)):r}function H_(e,t){const n=[t];for(;n.length>0;){const r=n.shift();if(e===r)return!0;n.push(...r.children,...r.shadowRoot?r.shadowRoot.children:[],...r.assignedElements?r.assignedElements():[])}}function U_(e,t){const n=na();let r=t.contains(e);return!r&&n.HTMLSlotElement&&t instanceof HTMLSlotElement&&(r=[...t.assignedElements()].includes(e),r||(r=H_(e,t))),r}function Ym(e){try{console.warn(e);return}catch{}}function zb(e,t=[]){const n=document.createElement(e);return n.classList.add(...Array.isArray(t)?t:B_(t)),n}function z_(e,t){const n=[];for(;e.previousElementSibling;){const r=e.previousElementSibling;t?r.matches(t)&&n.push(r):n.push(r),e=r}return n}function G_(e,t){const n=[];for(;e.nextElementSibling;){const r=e.nextElementSibling;t?r.matches(t)&&n.push(r):n.push(r),e=r}return n}function cu(e,t){return na().getComputedStyle(e,null).getPropertyValue(t)}function p5(e){let t=e,n;if(t){for(n=0;(t=t.previousSibling)!==null;)t.nodeType===1&&(n+=1);return n}}function W_(e,t){const n=[];let r=e.parentElement;for(;r;)n.push(r),r=r.parentElement;return n}function m5(e,t,n){const r=na();return e[t==="width"?"offsetWidth":"offsetHeight"]+parseFloat(r.getComputedStyle(e,null).getPropertyValue(t==="width"?"margin-right":"margin-top"))+parseFloat(r.getComputedStyle(e,null).getPropertyValue(t==="width"?"margin-left":"margin-bottom"))}function g5(e,t=""){typeof trustedTypes<"u"?e.innerHTML=trustedTypes.createPolicy("html",{createHTML:n=>n}).createHTML(t):e.innerHTML=t}let G1;function V_(){const e=na(),t=ld();return{smoothScroll:t.documentElement&&t.documentElement.style&&"scrollBehavior"in t.documentElement.style,touch:!!("ontouchstart"in e||e.DocumentTouch&&t instanceof e.DocumentTouch)}}function xS(){return G1||(G1=V_()),G1}let W1;function q_({userAgent:e}={}){const t=xS(),n=na(),r=n.navigator.platform,s=e||n.navigator.userAgent,i={ios:!1,android:!1},a=n.screen.width,c=n.screen.height,u=s.match(/(Android);?[\s\/]+([\d.]+)?/);let f=s.match(/(iPad)(?!\1).*OS\s([\d_]+)/);const p=s.match(/(iPod)(.*OS\s([\d_]+))?/),g=!f&&s.match(/(iPhone\sOS|iOS)\s([\d_]+)/),y=r==="Win32";let v=r==="MacIntel";const S=["1024x1366","1366x1024","834x1194","1194x834","834x1112","1112x834","768x1024","1024x768","820x1180","1180x820","810x1080","1080x810"];return!f&&v&&t.touch&&S.indexOf(`${a}x${c}`)>=0&&(f=s.match(/(Version)\/([\d.]+)/),f||(f=[0,1,"13_0_0"]),v=!1),u&&!y&&(i.os="android",i.android=!0),(f||g||p)&&(i.os="ios",i.ios=!0),i}function bS(e={}){return W1||(W1=q_(e)),W1}let V1;function K_(){const e=na(),t=bS();let n=!1;function r(){const c=e.navigator.userAgent.toLowerCase();return c.indexOf("safari")>=0&&c.indexOf("chrome")<0&&c.indexOf("android")<0}if(r()){const c=String(e.navigator.userAgent);if(c.includes("Version/")){const[u,f]=c.split("Version/")[1].split(" ")[0].split(".").map(p=>Number(p));n=u<16||u===16&&f<2}}const s=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(e.navigator.userAgent),i=r(),a=i||s&&t.ios;return{isSafari:n||i,needPerspectiveFix:n,need3dFix:a,isWebView:s}}function yS(){return V1||(V1=K_()),V1}function Y_({swiper:e,on:t,emit:n}){const r=na();let s=null,i=null;const a=()=>{!e||e.destroyed||!e.initialized||(n("beforeResize"),n("resize"))},c=()=>{!e||e.destroyed||!e.initialized||(s=new ResizeObserver(p=>{i=r.requestAnimationFrame(()=>{const{width:g,height:y}=e;let v=g,S=y;p.forEach(({contentBoxSize:T,contentRect:C,target:L})=>{L&&L!==e.el||(v=C?C.width:(T[0]||T).inlineSize,S=C?C.height:(T[0]||T).blockSize)}),(v!==g||S!==y)&&a()})}),s.observe(e.el))},u=()=>{i&&r.cancelAnimationFrame(i),s&&s.unobserve&&e.el&&(s.unobserve(e.el),s=null)},f=()=>{!e||e.destroyed||!e.initialized||n("orientationchange")};t("init",()=>{if(e.params.resizeObserver&&typeof r.ResizeObserver<"u"){c();return}r.addEventListener("resize",a),r.addEventListener("orientationchange",f)}),t("destroy",()=>{u(),r.removeEventListener("resize",a),r.removeEventListener("orientationchange",f)})}function X_({swiper:e,extendParams:t,on:n,emit:r}){const s=[],i=na(),a=(f,p={})=>{const g=i.MutationObserver||i.WebkitMutationObserver,y=new g(v=>{if(e.__preventObserver__)return;if(v.length===1){r("observerUpdate",v[0]);return}const S=function(){r("observerUpdate",v[0])};i.requestAnimationFrame?i.requestAnimationFrame(S):i.setTimeout(S,0)});y.observe(f,{attributes:typeof p.attributes>"u"?!0:p.attributes,childList:e.isElement||(typeof p.childList>"u"?!0:p).childList,characterData:typeof p.characterData>"u"?!0:p.characterData}),s.push(y)},c=()=>{if(e.params.observer){if(e.params.observeParents){const f=W_(e.hostEl);for(let p=0;p<f.length;p+=1)a(f[p])}a(e.hostEl,{childList:e.params.observeSlideChildren}),a(e.wrapperEl,{attributes:!1})}},u=()=>{s.forEach(f=>{f.disconnect()}),s.splice(0,s.length)};t({observer:!1,observeParents:!1,observeSlideChildren:!1}),n("init",c),n("destroy",u)}var Z_={on(e,t,n){const r=this;if(!r.eventsListeners||r.destroyed||typeof t!="function")return r;const s=n?"unshift":"push";return e.split(" ").forEach(i=>{r.eventsListeners[i]||(r.eventsListeners[i]=[]),r.eventsListeners[i][s](t)}),r},once(e,t,n){const r=this;if(!r.eventsListeners||r.destroyed||typeof t!="function")return r;function s(...i){r.off(e,s),s.__emitterProxy&&delete s.__emitterProxy,t.apply(r,i)}return s.__emitterProxy=t,r.on(e,s,n)},onAny(e,t){const n=this;if(!n.eventsListeners||n.destroyed||typeof e!="function")return n;const r=t?"unshift":"push";return n.eventsAnyListeners.indexOf(e)<0&&n.eventsAnyListeners[r](e),n},offAny(e){const t=this;if(!t.eventsListeners||t.destroyed||!t.eventsAnyListeners)return t;const n=t.eventsAnyListeners.indexOf(e);return n>=0&&t.eventsAnyListeners.splice(n,1),t},off(e,t){const n=this;return!n.eventsListeners||n.destroyed||!n.eventsListeners||e.split(" ").forEach(r=>{typeof t>"u"?n.eventsListeners[r]=[]:n.eventsListeners[r]&&n.eventsListeners[r].forEach((s,i)=>{(s===t||s.__emitterProxy&&s.__emitterProxy===t)&&n.eventsListeners[r].splice(i,1)})}),n},emit(...e){const t=this;if(!t.eventsListeners||t.destroyed||!t.eventsListeners)return t;let n,r,s;return typeof e[0]=="string"||Array.isArray(e[0])?(n=e[0],r=e.slice(1,e.length),s=t):(n=e[0].events,r=e[0].data,s=e[0].context||t),r.unshift(s),(Array.isArray(n)?n:n.split(" ")).forEach(a=>{t.eventsAnyListeners&&t.eventsAnyListeners.length&&t.eventsAnyListeners.forEach(c=>{c.apply(s,[a,...r])}),t.eventsListeners&&t.eventsListeners[a]&&t.eventsListeners[a].forEach(c=>{c.apply(s,r)})}),t}};function J_(){const e=this;let t,n;const r=e.el;typeof e.params.width<"u"&&e.params.width!==null?t=e.params.width:t=r.clientWidth,typeof e.params.height<"u"&&e.params.height!==null?n=e.params.height:n=r.clientHeight,!(t===0&&e.isHorizontal()||n===0&&e.isVertical())&&(t=t-parseInt(cu(r,"padding-left")||0,10)-parseInt(cu(r,"padding-right")||0,10),n=n-parseInt(cu(r,"padding-top")||0,10)-parseInt(cu(r,"padding-bottom")||0,10),Number.isNaN(t)&&(t=0),Number.isNaN(n)&&(n=0),Object.assign(e,{width:t,height:n,size:e.isHorizontal()?t:n}))}function eL(){const e=this;function t(K,W){return parseFloat(K.getPropertyValue(e.getDirectionLabel(W))||0)}const n=e.params,{wrapperEl:r,slidesEl:s,rtlTranslate:i,wrongRTL:a}=e,c=e.virtual&&n.virtual.enabled,u=c?e.virtual.slides.length:e.slides.length,f=Nc(s,`.${e.params.slideClass}, swiper-slide`),p=c?e.virtual.slides.length:f.length;let g=[];const y=[],v=[];let S=n.slidesOffsetBefore;typeof S=="function"&&(S=n.slidesOffsetBefore.call(e));let T=n.slidesOffsetAfter;typeof T=="function"&&(T=n.slidesOffsetAfter.call(e));const C=e.snapGrid.length,L=e.slidesGrid.length,E=e.size-S-T;let D=n.spaceBetween,B=-S,F=0,j=0;if(typeof E>"u")return;typeof D=="string"&&D.indexOf("%")>=0?D=parseFloat(D.replace("%",""))/100*E:typeof D=="string"&&(D=parseFloat(D)),e.virtualSize=-D-S-T,f.forEach(K=>{i?K.style.marginLeft="":K.style.marginRight="",K.style.marginBottom="",K.style.marginTop=""}),n.centeredSlides&&n.cssMode&&(Od(r,"--swiper-centered-offset-before",""),Od(r,"--swiper-centered-offset-after","")),n.cssMode&&(Od(r,"--swiper-slides-offset-before",`${S}px`),Od(r,"--swiper-slides-offset-after",`${T}px`));const A=n.grid&&n.grid.rows>1&&e.grid;A?e.grid.initSlides(f):e.grid&&e.grid.unsetSlides();let H;const Q=n.slidesPerView==="auto"&&n.breakpoints&&Object.keys(n.breakpoints).filter(K=>typeof n.breakpoints[K].slidesPerView<"u").length>0;for(let K=0;K<p;K+=1){H=0;const W=f[K];if(!(W&&(A&&e.grid.updateSlide(K,W,f),cu(W,"display")==="none"))){if(c&&n.slidesPerView==="auto")n.virtual.slidesPerViewAutoSlideSize&&(H=n.virtual.slidesPerViewAutoSlideSize),H&&W&&(n.roundLengths&&(H=Math.floor(H)),W.style[e.getDirectionLabel("width")]=`${H}px`);else if(n.slidesPerView==="auto"){Q&&(W.style[e.getDirectionLabel("width")]="");const de=getComputedStyle(W),X=W.style.transform,pe=W.style.webkitTransform;if(X&&(W.style.transform="none"),pe&&(W.style.webkitTransform="none"),n.roundLengths)H=e.isHorizontal()?m5(W,"width"):m5(W,"height");else{const ve=t(de,"width"),Ae=t(de,"padding-left"),ie=t(de,"padding-right"),V=t(de,"margin-left"),z=t(de,"margin-right"),ce=de.getPropertyValue("box-sizing");if(ce&&ce==="border-box")H=ve+V+z;else{const{clientWidth:ge,offsetWidth:he}=W;H=ve+Ae+ie+V+z+(he-ge)}}X&&(W.style.transform=X),pe&&(W.style.webkitTransform=pe),n.roundLengths&&(H=Math.floor(H))}else H=(E-(n.slidesPerView-1)*D)/n.slidesPerView,n.roundLengths&&(H=Math.floor(H)),W&&(W.style[e.getDirectionLabel("width")]=`${H}px`);W&&(W.swiperSlideSize=H),v.push(H),n.centeredSlides?(B=B+H/2+F/2+D,F===0&&K!==0&&(B=B-E/2-D),K===0&&(B=B-E/2-D),Math.abs(B)<1/1e3&&(B=0),n.roundLengths&&(B=Math.floor(B)),j%n.slidesPerGroup===0&&g.push(B),y.push(B)):(n.roundLengths&&(B=Math.floor(B)),(j-Math.min(e.params.slidesPerGroupSkip,j))%e.params.slidesPerGroup===0&&g.push(B),y.push(B),B=B+H+D),e.virtualSize+=H+D,F=H,j+=1}}if(e.virtualSize=Math.max(e.virtualSize,E)+T,i&&a&&(n.effect==="slide"||n.effect==="coverflow")&&(r.style.width=`${e.virtualSize+D}px`),n.setWrapperSize&&(r.style[e.getDirectionLabel("width")]=`${e.virtualSize+D}px`),A&&e.grid.updateWrapperSize(H,g),!n.centeredSlides){const K=n.slidesPerView!=="auto"&&n.slidesPerView%1!==0,W=n.snapToSlideEdge&&!n.loop&&(n.slidesPerView==="auto"||K);let de=g.length;if(W){let pe;if(n.slidesPerView==="auto"){pe=1;let ve=0;for(let Ae=v.length-1;Ae>=0&&(ve+=v[Ae]+(Ae<v.length-1?D:0),ve<=E);Ae-=1)pe=v.length-Ae}else pe=Math.floor(n.slidesPerView);de=Math.max(p-pe,0)}const X=[];for(let pe=0;pe<g.length;pe+=1){let ve=g[pe];n.roundLengths&&(ve=Math.floor(ve)),W?pe<=de&&X.push(ve):g[pe]<=e.virtualSize-E&&X.push(ve)}g=X,Math.floor(e.virtualSize-E)-Math.floor(g[g.length-1])>1&&(W||g.push(e.virtualSize-E))}if(c&&n.loop){const K=v[0]+D;if(n.slidesPerGroup>1){const W=Math.ceil((e.virtual.slidesBefore+e.virtual.slidesAfter)/n.slidesPerGroup),de=K*n.slidesPerGroup;for(let X=0;X<W;X+=1)g.push(g[g.length-1]+de)}for(let W=0;W<e.virtual.slidesBefore+e.virtual.slidesAfter;W+=1)n.slidesPerGroup===1&&g.push(g[g.length-1]+K),y.push(y[y.length-1]+K),e.virtualSize+=K}if(g.length===0&&(g=[0]),D!==0){const K=e.isHorizontal()&&i?"marginLeft":e.getDirectionLabel("marginRight");f.filter((W,de)=>!n.cssMode||n.loop?!0:de!==f.length-1).forEach(W=>{W.style[K]=`${D}px`})}if(n.centeredSlides&&n.centeredSlidesBounds){let K=0;v.forEach(de=>{K+=de+(D||0)}),K-=D;const W=K>E?K-E:0;g=g.map(de=>de<=0?-S:de>W?W+T:de)}if(n.centerInsufficientSlides){let K=0;if(v.forEach(W=>{K+=W+(D||0)}),K-=D,K<E){const W=(E-K)/2;g.forEach((de,X)=>{g[X]=de-W}),y.forEach((de,X)=>{y[X]=de+W})}}if(Object.assign(e,{slides:f,snapGrid:g,slidesGrid:y,slidesSizesGrid:v}),n.centeredSlides&&n.cssMode&&!n.centeredSlidesBounds){Od(r,"--swiper-centered-offset-before",`${-g[0]}px`),Od(r,"--swiper-centered-offset-after",`${e.size/2-v[v.length-1]/2}px`);const K=-e.snapGrid[0],W=-e.slidesGrid[0];e.snapGrid=e.snapGrid.map(de=>de+K),e.slidesGrid=e.slidesGrid.map(de=>de+W)}if(p!==u&&e.emit("slidesLengthChange"),g.length!==C&&(e.params.watchOverflow&&e.checkOverflow(),e.emit("snapGridLengthChange")),y.length!==L&&e.emit("slidesGridLengthChange"),n.watchSlidesProgress&&e.updateSlidesOffset(),e.emit("slidesUpdated"),!c&&!n.cssMode&&(n.effect==="slide"||n.effect==="fade")){const K=`${n.containerModifierClass}backface-hidden`,W=e.el.classList.contains(K);p<=n.maxBackfaceHiddenSlides?W||e.el.classList.add(K):W&&e.el.classList.remove(K)}}function tL(e){const t=this,n=[],r=t.virtual&&t.params.virtual.enabled;let s=0,i;typeof e=="number"?t.setTransition(e):e===!0&&t.setTransition(t.params.speed);const a=c=>r?t.slides[t.getSlideIndexByData(c)]:t.slides[c];if(t.params.slidesPerView!=="auto"&&t.params.slidesPerView>1)if(t.params.centeredSlides)(t.visibleSlides||[]).forEach(c=>{n.push(c)});else for(i=0;i<Math.ceil(t.params.slidesPerView);i+=1){const c=t.activeIndex+i;if(c>t.slides.length&&!r)break;n.push(a(c))}else n.push(a(t.activeIndex));for(i=0;i<n.length;i+=1)if(typeof n[i]<"u"){const c=n[i].offsetHeight;s=c>s?c:s}(s||s===0)&&(t.wrapperEl.style.height=`${s}px`)}function nL(){const e=this,t=e.slides,n=e.isElement?e.isHorizontal()?e.wrapperEl.offsetLeft:e.wrapperEl.offsetTop:0;for(let r=0;r<t.length;r+=1)t[r].swiperSlideOffset=(e.isHorizontal()?t[r].offsetLeft:t[r].offsetTop)-n-e.cssOverflowAdjustment()}const x5=(e,t,n)=>{t&&!e.classList.contains(n)?e.classList.add(n):!t&&e.classList.contains(n)&&e.classList.remove(n)};function rL(e=this&&this.translate||0){const t=this,n=t.params,{slides:r,rtlTranslate:s,snapGrid:i}=t;if(r.length===0)return;typeof r[0].swiperSlideOffset>"u"&&t.updateSlidesOffset();let a=-e;s&&(a=e),t.visibleSlidesIndexes=[],t.visibleSlides=[];let c=n.spaceBetween;typeof c=="string"&&c.indexOf("%")>=0?c=parseFloat(c.replace("%",""))/100*t.size:typeof c=="string"&&(c=parseFloat(c));for(let u=0;u<r.length;u+=1){const f=r[u];let p=f.swiperSlideOffset;n.cssMode&&n.centeredSlides&&(p-=r[0].swiperSlideOffset);const g=(a+(n.centeredSlides?t.minTranslate():0)-p)/(f.swiperSlideSize+c),y=(a-i[0]+(n.centeredSlides?t.minTranslate():0)-p)/(f.swiperSlideSize+c),v=-(a-p),S=v+t.slidesSizesGrid[u],T=v>=0&&v<=t.size-t.slidesSizesGrid[u],C=v>=0&&v<t.size-1||S>1&&S<=t.size||v<=0&&S>=t.size;C&&(t.visibleSlides.push(f),t.visibleSlidesIndexes.push(u)),x5(f,C,n.slideVisibleClass),x5(f,T,n.slideFullyVisibleClass),f.progress=s?-g:g,f.originalProgress=s?-y:y}}function sL(e){const t=this;if(typeof e>"u"){const p=t.rtlTranslate?-1:1;e=t&&t.translate&&t.translate*p||0}const n=t.params,r=t.maxTranslate()-t.minTranslate();let{progress:s,isBeginning:i,isEnd:a,progressLoop:c}=t;const u=i,f=a;if(r===0)s=0,i=!0,a=!0;else{s=(e-t.minTranslate())/r;const p=Math.abs(e-t.minTranslate())<1,g=Math.abs(e-t.maxTranslate())<1;i=p||s<=0,a=g||s>=1,p&&(s=0),g&&(s=1)}if(n.loop){const p=t.getSlideIndexByData(0),g=t.getSlideIndexByData(t.slides.length-1),y=t.slidesGrid[p],v=t.slidesGrid[g],S=t.slidesGrid[t.slidesGrid.length-1],T=Math.abs(e);T>=y?c=(T-y)/S:c=(T+S-v)/S,c>1&&(c-=1)}Object.assign(t,{progress:s,progressLoop:c,isBeginning:i,isEnd:a}),(n.watchSlidesProgress||n.centeredSlides&&n.autoHeight)&&t.updateSlidesProgress(e),i&&!u&&t.emit("reachBeginning toEdge"),a&&!f&&t.emit("reachEnd toEdge"),(u&&!i||f&&!a)&&t.emit("fromEdge"),t.emit("progress",s)}const q1=(e,t,n)=>{t&&!e.classList.contains(n)?e.classList.add(n):!t&&e.classList.contains(n)&&e.classList.remove(n)};function iL(){const e=this,{slides:t,params:n,slidesEl:r,activeIndex:s}=e,i=e.virtual&&n.virtual.enabled,a=e.grid&&n.grid&&n.grid.rows>1,c=g=>Nc(r,`.${n.slideClass}${g}, swiper-slide${g}`)[0];let u,f,p;if(i)if(n.loop){let g=s-e.virtual.slidesBefore;g<0&&(g=e.virtual.slides.length+g),g>=e.virtual.slides.length&&(g-=e.virtual.slides.length),u=c(`[data-swiper-slide-index="${g}"]`)}else u=c(`[data-swiper-slide-index="${s}"]`);else a?(u=t.find(g=>g.column===s),p=t.find(g=>g.column===s+1),f=t.find(g=>g.column===s-1)):u=t[s];u&&(a||(p=G_(u,`.${n.slideClass}, swiper-slide`)[0],n.loop&&!p&&(p=t[0]),f=z_(u,`.${n.slideClass}, swiper-slide`)[0],n.loop&&!f===0&&(f=t[t.length-1]))),t.forEach(g=>{q1(g,g===u,n.slideActiveClass),q1(g,g===p,n.slideNextClass),q1(g,g===f,n.slidePrevClass)}),e.emitSlidesClasses()}const Am=(e,t)=>{if(!e||e.destroyed||!e.params)return;const n=()=>e.isElement?"swiper-slide":`.${e.params.slideClass}`,r=t.closest(n());if(r){let s=r.querySelector(`.${e.params.lazyPreloaderClass}`);!s&&e.isElement&&(r.shadowRoot?s=r.shadowRoot.querySelector(`.${e.params.lazyPreloaderClass}`):requestAnimationFrame(()=>{r.shadowRoot&&(s=r.shadowRoot.querySelector(`.${e.params.lazyPreloaderClass}`),s&&!s.lazyPreloaderManaged&&s.remove())})),s&&!s.lazyPreloaderManaged&&s.remove()}},K1=(e,t)=>{if(!e.slides[t])return;const n=e.slides[t].querySelector('[loading="lazy"]');n&&n.removeAttribute("loading")},Gb=e=>{if(!e||e.destroyed||!e.params)return;let t=e.params.lazyPreloadPrevNext;const n=e.slides.length;if(!n||!t||t<0)return;t=Math.min(t,n);const r=e.params.slidesPerView==="auto"?e.slidesPerViewDynamic():Math.ceil(e.params.slidesPerView),s=e.activeIndex;if(e.params.grid&&e.params.grid.rows>1){const a=s,c=[a-t];c.push(...Array.from({length:t}).map((u,f)=>a+r+f)),e.slides.forEach((u,f)=>{c.includes(u.column)&&K1(e,f)});return}const i=s+r-1;if(e.params.rewind||e.params.loop)for(let a=s-t;a<=i+t;a+=1){const c=(a%n+n)%n;(c<s||c>i)&&K1(e,c)}else for(let a=Math.max(s-t,0);a<=Math.min(i+t,n-1);a+=1)a!==s&&(a>i||a<s)&&K1(e,a)};function oL(e){const{slidesGrid:t,params:n}=e,r=e.rtlTranslate?e.translate:-e.translate;let s;for(let i=0;i<t.length;i+=1)typeof t[i+1]<"u"?r>=t[i]&&r<t[i+1]-(t[i+1]-t[i])/2?s=i:r>=t[i]&&r<t[i+1]&&(s=i+1):r>=t[i]&&(s=i);return n.normalizeSlideIndex&&(s<0||typeof s>"u")&&(s=0),s}function aL(e){const t=this,n=t.rtlTranslate?t.translate:-t.translate,{snapGrid:r,params:s,activeIndex:i,realIndex:a,snapIndex:c}=t;let u=e,f;const p=v=>{let S=v-t.virtual.slidesBefore;return S<0&&(S=t.virtual.slides.length+S),S>=t.virtual.slides.length&&(S-=t.virtual.slides.length),S};if(typeof u>"u"&&(u=oL(t)),r.indexOf(n)>=0)f=r.indexOf(n);else{const v=Math.min(s.slidesPerGroupSkip,u);f=v+Math.floor((u-v)/s.slidesPerGroup)}if(f>=r.length&&(f=r.length-1),u===i&&!t.params.loop){f!==c&&(t.snapIndex=f,t.emit("snapIndexChange"));return}if(u===i&&t.params.loop&&t.virtual&&t.params.virtual.enabled){t.realIndex=p(u);return}const g=t.grid&&s.grid&&s.grid.rows>1;let y;if(t.virtual&&s.virtual.enabled)s.loop?y=p(u):y=u;else if(g){const v=t.slides.find(T=>T.column===u);let S=parseInt(v.getAttribute("data-swiper-slide-index"),10);Number.isNaN(S)&&(S=Math.max(t.slides.indexOf(v),0)),y=Math.floor(S/s.grid.rows)}else if(t.slides[u]){const v=t.slides[u].getAttribute("data-swiper-slide-index");v?y=parseInt(v,10):y=u}else y=u;Object.assign(t,{previousSnapIndex:c,snapIndex:f,previousRealIndex:a,realIndex:y,previousIndex:i,activeIndex:u}),t.initialized&&Gb(t),t.emit("activeIndexChange"),t.emit("snapIndexChange"),(t.initialized||t.params.runCallbacksOnInit)&&(a!==y&&t.emit("realIndexChange"),t.emit("slideChange"))}function lL(e,t){const n=this,r=n.params;let s=e.closest(`.${r.slideClass}, swiper-slide`);!s&&n.isElement&&t&&t.length>1&&t.includes(e)&&[...t.slice(t.indexOf(e)+1,t.length)].forEach(c=>{!s&&c.matches&&c.matches(`.${r.slideClass}, swiper-slide`)&&(s=c)});let i=!1,a;if(s){for(let c=0;c<n.slides.length;c+=1)if(n.slides[c]===s){i=!0,a=c;break}}if(s&&i)n.clickedSlide=s,n.virtual&&n.params.virtual.enabled?n.clickedIndex=parseInt(s.getAttribute("data-swiper-slide-index"),10):n.clickedIndex=a;else{n.clickedSlide=void 0,n.clickedIndex=void 0;return}r.slideToClickedSlide&&n.clickedIndex!==void 0&&n.clickedIndex!==n.activeIndex&&n.slideToClickedSlide()}var cL={updateSize:J_,updateSlides:eL,updateAutoHeight:tL,updateSlidesOffset:nL,updateSlidesProgress:rL,updateProgress:sL,updateSlidesClasses:iL,updateActiveIndex:aL,updateClickedSlide:lL};function uL(e=this.isHorizontal()?"x":"y"){const t=this,{params:n,rtlTranslate:r,translate:s,wrapperEl:i}=t;if(n.virtualTranslate)return r?-s:s;if(n.cssMode)return s;let a=Q_(i,e);return a+=t.cssOverflowAdjustment(),r&&(a=-a),a||0}function dL(e,t){const n=this,{rtlTranslate:r,params:s,wrapperEl:i,progress:a}=n;let c=0,u=0;const f=0;n.isHorizontal()?c=r?-e:e:u=e,s.roundLengths&&(c=Math.floor(c),u=Math.floor(u)),n.previousTranslate=n.translate,n.translate=n.isHorizontal()?c:u,s.cssMode?i[n.isHorizontal()?"scrollLeft":"scrollTop"]=n.isHorizontal()?-c:-u:s.virtualTranslate||(n.isHorizontal()?c-=n.cssOverflowAdjustment():u-=n.cssOverflowAdjustment(),i.style.transform=`translate3d(${c}px, ${u}px, ${f}px)`);let p;const g=n.maxTranslate()-n.minTranslate();g===0?p=0:p=(e-n.minTranslate())/g,p!==a&&n.updateProgress(e),n.emit("setTranslate",n.translate,t)}function fL(){return-this.snapGrid[0]}function hL(){return-this.snapGrid[this.snapGrid.length-1]}function pL(e=0,t=this.params.speed,n=!0,r=!0,s){const i=this,{params:a,wrapperEl:c}=i;if(i.animating&&a.preventInteractionOnTransition)return!1;const u=i.minTranslate(),f=i.maxTranslate();let p;if(r&&e>u?p=u:r&&e<f?p=f:p=e,i.updateProgress(p),a.cssMode){const g=i.isHorizontal();if(t===0)c[g?"scrollLeft":"scrollTop"]=-p;else{if(!i.support.smoothScroll)return gS({swiper:i,targetPosition:-p,side:g?"left":"top"}),!0;c.scrollTo({[g?"left":"top"]:-p,behavior:"smooth"})}return!0}return t===0?(i.setTransition(0),i.setTranslate(p),n&&(i.emit("beforeTransitionStart",t,s),i.emit("transitionEnd"))):(i.setTransition(t),i.setTranslate(p),n&&(i.emit("beforeTransitionStart",t,s),i.emit("transitionStart")),i.animating||(i.animating=!0,i.onTranslateToWrapperTransitionEnd||(i.onTranslateToWrapperTransitionEnd=function(y){!i||i.destroyed||y.target===this&&(i.wrapperEl.removeEventListener("transitionend",i.onTranslateToWrapperTransitionEnd),i.onTranslateToWrapperTransitionEnd=null,delete i.onTranslateToWrapperTransitionEnd,i.animating=!1,n&&i.emit("transitionEnd"))}),i.wrapperEl.addEventListener("transitionend",i.onTranslateToWrapperTransitionEnd))),!0}var mL={getTranslate:uL,setTranslate:dL,minTranslate:fL,maxTranslate:hL,translateTo:pL};function gL(e,t){const n=this;n.params.cssMode||(n.wrapperEl.style.transitionDuration=`${e}ms`,n.wrapperEl.style.transitionDelay=e===0?"0ms":""),n.emit("setTransition",e,t)}function vS({swiper:e,runCallbacks:t,direction:n,step:r}){const{activeIndex:s,previousIndex:i}=e;let a=n;a||(s>i?a="next":s<i?a="prev":a="reset"),e.emit(`transition${r}`),t&&a==="reset"?e.emit(`slideResetTransition${r}`):t&&s!==i&&(e.emit(`slideChangeTransition${r}`),a==="next"?e.emit(`slideNextTransition${r}`):e.emit(`slidePrevTransition${r}`))}function xL(e=!0,t){const n=this,{params:r}=n;r.cssMode||(r.autoHeight&&n.updateAutoHeight(),vS({swiper:n,runCallbacks:e,direction:t,step:"Start"}))}function bL(e=!0,t){const n=this,{params:r}=n;n.animating=!1,!r.cssMode&&(n.setTransition(0),vS({swiper:n,runCallbacks:e,direction:t,step:"End"}))}var yL={setTransition:gL,transitionStart:xL,transitionEnd:bL};function vL(e=0,t,n=!0,r,s){typeof e=="string"&&(e=parseInt(e,10));const i=this;let a=e;a<0&&(a=0);const{params:c,snapGrid:u,slidesGrid:f,previousIndex:p,activeIndex:g,rtlTranslate:y,wrapperEl:v,enabled:S}=i;if(!S&&!r&&!s||i.destroyed||i.animating&&c.preventInteractionOnTransition)return!1;typeof t>"u"&&(t=i.params.speed);const T=Math.min(i.params.slidesPerGroupSkip,a);let C=T+Math.floor((a-T)/i.params.slidesPerGroup);C>=u.length&&(C=u.length-1);const L=-u[C];if(c.normalizeSlideIndex)for(let A=0;A<f.length;A+=1){const H=-Math.floor(L*100),Q=Math.floor(f[A]*100),K=Math.floor(f[A+1]*100);typeof f[A+1]<"u"?H>=Q&&H<K-(K-Q)/2?a=A:H>=Q&&H<K&&(a=A+1):H>=Q&&(a=A)}if(i.initialized&&a!==g&&(!i.allowSlideNext&&(y?L>i.translate&&L>i.minTranslate():L<i.translate&&L<i.minTranslate())||!i.allowSlidePrev&&L>i.translate&&L>i.maxTranslate()&&(g||0)!==a))return!1;a!==(p||0)&&n&&i.emit("beforeSlideChangeStart"),i.updateProgress(L);let E;a>g?E="next":a<g?E="prev":E="reset";const D=i.virtual&&i.params.virtual.enabled;if(!(D&&s)&&(y&&-L===i.translate||!y&&L===i.translate))return i.updateActiveIndex(a),c.autoHeight&&i.updateAutoHeight(),i.updateSlidesClasses(),c.effect!=="slide"&&i.setTranslate(L),E!=="reset"&&(i.transitionStart(n,E),i.transitionEnd(n,E)),!1;if(c.cssMode){const A=i.isHorizontal(),H=y?L:-L;if(t===0)D&&(i.wrapperEl.style.scrollSnapType="none",i._immediateVirtual=!0),D&&!i._cssModeVirtualInitialSet&&i.params.initialSlide>0?(i._cssModeVirtualInitialSet=!0,requestAnimationFrame(()=>{v[A?"scrollLeft":"scrollTop"]=H})):v[A?"scrollLeft":"scrollTop"]=H,D&&requestAnimationFrame(()=>{i.wrapperEl.style.scrollSnapType="",i._immediateVirtual=!1});else{if(!i.support.smoothScroll)return gS({swiper:i,targetPosition:H,side:A?"left":"top"}),!0;v.scrollTo({[A?"left":"top"]:H,behavior:"smooth"})}return!0}const j=yS().isSafari;return D&&!s&&j&&i.isElement&&i.virtual.update(!1,!1,a),i.setTransition(t),i.setTranslate(L),i.updateActiveIndex(a),i.updateSlidesClasses(),i.emit("beforeTransitionStart",t,r),i.transitionStart(n,E),t===0?i.transitionEnd(n,E):i.animating||(i.animating=!0,i.onSlideToWrapperTransitionEnd||(i.onSlideToWrapperTransitionEnd=function(H){!i||i.destroyed||H.target===this&&(i.wrapperEl.removeEventListener("transitionend",i.onSlideToWrapperTransitionEnd),i.onSlideToWrapperTransitionEnd=null,delete i.onSlideToWrapperTransitionEnd,i.transitionEnd(n,E))}),i.wrapperEl.addEventListener("transitionend",i.onSlideToWrapperTransitionEnd)),!0}function wL(e=0,t,n=!0,r){typeof e=="string"&&(e=parseInt(e,10));const s=this;if(s.destroyed)return;typeof t>"u"&&(t=s.params.speed);const i=s.grid&&s.params.grid&&s.params.grid.rows>1;let a=e;if(s.params.loop)if(s.virtual&&s.params.virtual.enabled)a=a+s.virtual.slidesBefore;else{let c;if(i){const T=a*s.params.grid.rows;c=s.slides.find(C=>C.getAttribute("data-swiper-slide-index")*1===T).column}else c=s.getSlideIndexByData(a);const u=i?Math.ceil(s.slides.length/s.params.grid.rows):s.slides.length,{centeredSlides:f,slidesOffsetBefore:p,slidesOffsetAfter:g}=s.params,y=f||!!p||!!g;let v=s.params.slidesPerView;v==="auto"?v=s.slidesPerViewDynamic():(v=Math.ceil(parseFloat(s.params.slidesPerView,10)),y&&v%2===0&&(v=v+1));let S=u-c<v;if(y&&(S=S||c<Math.ceil(v/2)),r&&y&&s.params.slidesPerView!=="auto"&&!i&&(S=!1),S){const T=y?c<s.activeIndex?"prev":"next":c-s.activeIndex-1<s.params.slidesPerView?"next":"prev";s.loopFix({direction:T,slideTo:!0,activeSlideIndex:T==="next"?c+1:c-u+1,slideRealIndex:T==="next"?s.realIndex:void 0})}if(i){const T=a*s.params.grid.rows;a=s.slides.find(C=>C.getAttribute("data-swiper-slide-index")*1===T).column}else a=s.getSlideIndexByData(a)}return requestAnimationFrame(()=>{s.slideTo(a,t,n,r)}),s}function SL(e,t=!0,n){const r=this,{enabled:s,params:i,animating:a}=r;if(!s||r.destroyed)return r;typeof e>"u"&&(e=r.params.speed);let c=i.slidesPerGroup;i.slidesPerView==="auto"&&i.slidesPerGroup===1&&i.slidesPerGroupAuto&&(c=Math.max(r.slidesPerViewDynamic("current",!0),1));const u=r.activeIndex<i.slidesPerGroupSkip?1:c,f=r.virtual&&i.virtual.enabled;if(i.loop){if(a&&!f&&i.loopPreventsSliding)return!1;if(r.loopFix({direction:"next"}),r._clientLeft=r.wrapperEl.clientLeft,r.activeIndex===r.slides.length-1&&i.cssMode)return requestAnimationFrame(()=>{r.slideTo(r.activeIndex+u,e,t,n)}),!0}return i.rewind&&r.isEnd?r.slideTo(0,e,t,n):r.slideTo(r.activeIndex+u,e,t,n)}function AL(e,t=!0,n){const r=this,{params:s,snapGrid:i,slidesGrid:a,rtlTranslate:c,enabled:u,animating:f}=r;if(!u||r.destroyed)return r;typeof e>"u"&&(e=r.params.speed);const p=r.virtual&&s.virtual.enabled;if(s.loop){if(f&&!p&&s.loopPreventsSliding)return!1;r.loopFix({direction:"prev"}),r._clientLeft=r.wrapperEl.clientLeft}const g=c?r.translate:-r.translate;function y(E){return E<0?-Math.floor(Math.abs(E)):Math.floor(E)}const v=y(g),S=i.map(E=>y(E)),T=s.freeMode&&s.freeMode.enabled;let C=i[S.indexOf(v)-1];if(typeof C>"u"&&(s.cssMode||T)){let E;i.forEach((D,B)=>{v>=D&&(E=B)}),typeof E<"u"&&(C=T?i[E]:i[E>0?E-1:E])}let L=0;if(typeof C<"u"&&(L=a.indexOf(C),L<0&&(L=r.activeIndex-1),s.slidesPerView==="auto"&&s.slidesPerGroup===1&&s.slidesPerGroupAuto&&(L=L-r.slidesPerViewDynamic("previous",!0)+1,L=Math.max(L,0))),s.rewind&&r.isBeginning){const E=r.params.virtual&&r.params.virtual.enabled&&r.virtual?r.virtual.slides.length-1:r.slides.length-1;return r.slideTo(E,e,t,n)}else if(s.loop&&r.activeIndex===0&&s.cssMode)return requestAnimationFrame(()=>{r.slideTo(L,e,t,n)}),!0;return r.slideTo(L,e,t,n)}function TL(e,t=!0,n){const r=this;if(!r.destroyed)return typeof e>"u"&&(e=r.params.speed),r.slideTo(r.activeIndex,e,t,n)}function CL(e,t=!0,n,r=.5){const s=this;if(s.destroyed)return;typeof e>"u"&&(e=s.params.speed);let i=s.activeIndex;const a=Math.min(s.params.slidesPerGroupSkip,i),c=a+Math.floor((i-a)/s.params.slidesPerGroup),u=s.rtlTranslate?s.translate:-s.translate;if(u>=s.snapGrid[c]){const f=s.snapGrid[c],p=s.snapGrid[c+1];u-f>(p-f)*r&&(i+=s.params.slidesPerGroup)}else{const f=s.snapGrid[c-1],p=s.snapGrid[c];u-f<=(p-f)*r&&(i-=s.params.slidesPerGroup)}return i=Math.max(i,0),i=Math.min(i,s.slidesGrid.length-1),s.slideTo(i,e,t,n)}function kL(){const e=this;if(e.destroyed)return;const{params:t,slidesEl:n}=e,r=t.slidesPerView==="auto"?e.slidesPerViewDynamic():t.slidesPerView;let s=e.getSlideIndexWhenGrid(e.clickedIndex),i;const a=e.isElement?"swiper-slide":`.${t.slideClass}`,c=e.grid&&e.params.grid&&e.params.grid.rows>1;if(t.loop){if(e.animating)return;i=parseInt(e.clickedSlide.getAttribute("data-swiper-slide-index"),10),t.centeredSlides?e.slideToLoop(i):s>(c?(e.slides.length-r)/2-(e.params.grid.rows-1):e.slides.length-r)?(e.loopFix(),s=e.getSlideIndex(Nc(n,`${a}[data-swiper-slide-index="${i}"]`)[0]),mS(()=>{e.slideTo(s)})):e.slideTo(s)}else e.slideTo(s)}var _L={slideTo:vL,slideToLoop:wL,slideNext:SL,slidePrev:AL,slideReset:TL,slideToClosest:CL,slideToClickedSlide:kL};function LL(e,t){const n=this,{params:r,slidesEl:s}=n;if(!r.loop||n.virtual&&n.params.virtual.enabled)return;const i=()=>{Nc(s,`.${r.slideClass}, swiper-slide`).forEach((S,T)=>{S.setAttribute("data-swiper-slide-index",T)})},a=()=>{const v=Nc(s,`.${r.slideBlankClass}`);v.forEach(S=>{S.remove()}),v.length>0&&(n.recalcSlides(),n.updateSlides())},c=n.grid&&r.grid&&r.grid.rows>1;r.loopAddBlankSlides&&(r.slidesPerGroup>1||c)&&a();const u=r.slidesPerGroup*(c?r.grid.rows:1),f=n.slides.length%u!==0,p=c&&n.slides.length%r.grid.rows!==0,g=v=>{for(let S=0;S<v;S+=1){const T=n.isElement?zb("swiper-slide",[r.slideBlankClass]):zb("div",[r.slideClass,r.slideBlankClass]);n.slidesEl.append(T)}};if(f){if(r.loopAddBlankSlides){const v=u-n.slides.length%u;g(v),n.recalcSlides(),n.updateSlides()}else Ym("Swiper Loop Warning: The number of slides is not even to slidesPerGroup, loop mode may not function properly. You need to add more slides (or make duplicates, or empty slides)");i()}else if(p){if(r.loopAddBlankSlides){const v=r.grid.rows-n.slides.length%r.grid.rows;g(v),n.recalcSlides(),n.updateSlides()}else Ym("Swiper Loop Warning: The number of slides is not even to grid.rows, loop mode may not function properly. You need to add more slides (or make duplicates, or empty slides)");i()}else i();const y=r.centeredSlides||!!r.slidesOffsetBefore||!!r.slidesOffsetAfter;n.loopFix({slideRealIndex:e,direction:y?void 0:"next",initial:t})}function EL({slideRealIndex:e,slideTo:t=!0,direction:n,setTranslate:r,activeSlideIndex:s,initial:i,byController:a,byMousewheel:c}={}){const u=this;if(!u.params.loop)return;u.emit("beforeLoopFix");const{slides:f,allowSlidePrev:p,allowSlideNext:g,slidesEl:y,params:v}=u,{centeredSlides:S,slidesOffsetBefore:T,slidesOffsetAfter:C,initialSlide:L}=v,E=S||!!T||!!C;if(u.allowSlidePrev=!0,u.allowSlideNext=!0,u.virtual&&v.virtual.enabled){t&&(!E&&u.snapIndex===0?u.slideTo(u.virtual.slides.length,0,!1,!0):E&&u.snapIndex<v.slidesPerView?u.slideTo(u.virtual.slides.length+u.snapIndex,0,!1,!0):u.snapIndex===u.snapGrid.length-1&&u.slideTo(u.virtual.slidesBefore,0,!1,!0)),u.allowSlidePrev=p,u.allowSlideNext=g,u.emit("loopFix");return}let D=v.slidesPerView;D==="auto"?D=u.slidesPerViewDynamic():(D=Math.ceil(parseFloat(v.slidesPerView,10)),E&&D%2===0&&(D=D+1));const B=v.slidesPerGroupAuto?D:v.slidesPerGroup;let F=E?Math.max(B,Math.ceil(D/2)):B;F%B!==0&&(F+=B-F%B),F+=v.loopAdditionalSlides,u.loopedSlides=F;const j=u.grid&&v.grid&&v.grid.rows>1;f.length<D+F||u.params.effect==="cards"&&f.length<D+F*2?Ym("Swiper Loop Warning: The number of slides is not enough for loop mode, it will be disabled or not function properly. You need to add more slides (or make duplicates) or lower the values of slidesPerView and slidesPerGroup parameters"):j&&v.grid.fill==="row"&&Ym("Swiper Loop Warning: Loop mode is not compatible with grid.fill = `row`");const A=[],H=[],Q=j?Math.ceil(f.length/v.grid.rows):f.length,K=i&&Q-L<D&&!E;let W=K?L:u.activeIndex;typeof s>"u"?s=u.getSlideIndex(f.find(V=>V.classList.contains(v.slideActiveClass))):W=s;const de=n==="next"||!n,X=n==="prev"||!n;let pe=0,ve=0;const ie=(j?f[s].column:s)+(E&&typeof r>"u"?-D/2+.5:0);if(ie<F){pe=Math.max(F-ie,B);for(let V=0;V<F-ie;V+=1){const z=V-Math.floor(V/Q)*Q;if(j){const ce=Q-z-1;for(let ge=f.length-1;ge>=0;ge-=1)f[ge].column===ce&&A.push(ge)}else A.push(Q-z-1)}}else if(ie+D>Q-F){ve=Math.max(ie-(Q-F*2),B),K&&(ve=Math.max(ve,D-Q+L+1));for(let V=0;V<ve;V+=1){const z=V-Math.floor(V/Q)*Q;j?f.forEach((ce,ge)=>{ce.column===z&&H.push(ge)}):H.push(z)}}if(u.__preventObserver__=!0,requestAnimationFrame(()=>{u.__preventObserver__=!1}),u.params.effect==="cards"&&f.length<D+F*2&&(H.includes(s)&&H.splice(H.indexOf(s),1),A.includes(s)&&A.splice(A.indexOf(s),1)),X&&A.forEach(V=>{f[V].swiperLoopMoveDOM=!0,y.prepend(f[V]),f[V].swiperLoopMoveDOM=!1}),de&&H.forEach(V=>{f[V].swiperLoopMoveDOM=!0,y.append(f[V]),f[V].swiperLoopMoveDOM=!1}),u.recalcSlides(),v.slidesPerView==="auto"?u.updateSlides():j&&(A.length>0&&X||H.length>0&&de)&&u.slides.forEach((V,z)=>{u.grid.updateSlide(z,V,u.slides)}),v.watchSlidesProgress&&u.updateSlidesOffset(),t){if(A.length>0&&X){if(typeof e>"u"){const V=u.slidesGrid[W],ce=u.slidesGrid[W+pe]-V;c?u.setTranslate(u.translate-ce):(u.slideTo(W+Math.ceil(pe),0,!1,!0),r&&(u.touchEventsData.startTranslate=u.touchEventsData.startTranslate-ce,u.touchEventsData.currentTranslate=u.touchEventsData.currentTranslate-ce))}else if(r){const V=j?A.length/v.grid.rows:A.length;u.slideTo(u.activeIndex+V,0,!1,!0),u.touchEventsData.currentTranslate=u.translate}}else if(H.length>0&&de)if(typeof e>"u"){const V=u.slidesGrid[W],ce=u.slidesGrid[W-ve]-V;c?u.setTranslate(u.translate-ce):(u.slideTo(W-ve,0,!1,!0),r&&(u.touchEventsData.startTranslate=u.touchEventsData.startTranslate-ce,u.touchEventsData.currentTranslate=u.touchEventsData.currentTranslate-ce))}else{const V=j?H.length/v.grid.rows:H.length;u.slideTo(u.activeIndex-V,0,!1,!0)}}if(u.allowSlidePrev=p,u.allowSlideNext=g,u.controller&&u.controller.control&&!a){const V={slideRealIndex:e,direction:n,setTranslate:r,activeSlideIndex:s,byController:!0};Array.isArray(u.controller.control)?u.controller.control.forEach(z=>{!z.destroyed&&z.params.loop&&z.loopFix({...V,slideTo:z.params.slidesPerView===v.slidesPerView?t:!1})}):u.controller.control instanceof u.constructor&&u.controller.control.params.loop&&u.controller.control.loopFix({...V,slideTo:u.controller.control.params.slidesPerView===v.slidesPerView?t:!1})}u.emit("loopFix")}function IL(){const e=this,{params:t,slidesEl:n}=e;if(!t.loop||!n||e.virtual&&e.params.virtual.enabled)return;e.recalcSlides();const r=[];e.slides.forEach(s=>{const i=typeof s.swiperSlideIndex>"u"?s.getAttribute("data-swiper-slide-index")*1:s.swiperSlideIndex;r[i]=s}),e.slides.forEach(s=>{s.removeAttribute("data-swiper-slide-index")}),r.forEach(s=>{n.append(s)}),e.recalcSlides(),e.slideTo(e.realIndex,0)}var RL={loopCreate:LL,loopFix:EL,loopDestroy:IL};function NL(e){const t=this;if(!t.params.simulateTouch||t.params.watchOverflow&&t.isLocked||t.params.cssMode)return;const n=t.params.touchEventsTarget==="container"?t.el:t.wrapperEl;t.isElement&&(t.__preventObserver__=!0),n.style.cursor="move",n.style.cursor=e?"grabbing":"grab",t.isElement&&requestAnimationFrame(()=>{t.__preventObserver__=!1})}function ML(){const e=this;e.params.watchOverflow&&e.isLocked||e.params.cssMode||(e.isElement&&(e.__preventObserver__=!0),e[e.params.touchEventsTarget==="container"?"el":"wrapperEl"].style.cursor="",e.isElement&&requestAnimationFrame(()=>{e.__preventObserver__=!1}))}var DL={setGrabCursor:NL,unsetGrabCursor:ML};function jL(e,t=this){function n(r){if(!r||r===ld()||r===na())return null;r.assignedSlot&&(r=r.assignedSlot);const s=r.closest(e);return!s&&!r.getRootNode?null:s||n(r.getRootNode().host)}return n(t)}function b5(e,t,n){const r=na(),{params:s}=e,i=s.edgeSwipeDetection,a=s.edgeSwipeThreshold;return i&&(n<=a||n>=r.innerWidth-a)?i==="prevent"?(t.preventDefault(),!0):!1:!0}function PL(e){const t=this;if(t.destroyed)return;const n=ld();let r=e;r.originalEvent&&(r=r.originalEvent);const s=t.touchEventsData;if(r.type==="pointerdown"){if(s.pointerId!==null&&s.pointerId!==r.pointerId)return;s.pointerId=r.pointerId}else r.type==="touchstart"&&r.targetTouches.length===1&&(s.touchId=r.targetTouches[0].identifier);if(r.type==="touchstart"){b5(t,r,r.targetTouches[0].pageX);return}const{params:i,touches:a,enabled:c}=t;if(!c||!i.simulateTouch&&r.pointerType==="mouse"||t.animating&&i.preventInteractionOnTransition)return;!t.animating&&i.cssMode&&i.loop&&t.loopFix();let u=r.target;if(i.touchEventsTarget==="wrapper"&&!U_(u,t.wrapperEl)||"which"in r&&r.which===3||"button"in r&&r.button>0||s.isTouched&&s.isMoved)return;const f=!!i.noSwipingClass&&i.noSwipingClass!=="",p=r.composedPath?r.composedPath():r.path;f&&r.target&&r.target.shadowRoot&&p&&(u=p[0]);const g=i.noSwipingSelector?i.noSwipingSelector:`.${i.noSwipingClass}`,y=!!(r.target&&r.target.shadowRoot);if(i.noSwiping&&(y?jL(g,u):u.closest(g))){t.allowClick=!0;return}if(i.swipeHandler&&!u.closest(i.swipeHandler))return;a.currentX=r.pageX,a.currentY=r.pageY;const v=a.currentX,S=a.currentY;if(!b5(t,r,v))return;Object.assign(s,{isTouched:!0,isMoved:!1,allowTouchCallbacks:!0,isScrolling:void 0,startMoving:void 0}),a.startX=v,a.startY=S,s.touchStartTime=Km(),t.allowClick=!0,t.updateSize(),t.swipeDirection=void 0,i.threshold>0&&(s.allowThresholdMove=!1);let T=!0;u.matches(s.focusableElements)&&(T=!1,u.nodeName==="SELECT"&&(s.isTouched=!1)),n.activeElement&&n.activeElement.matches(s.focusableElements)&&n.activeElement!==u&&(r.pointerType==="mouse"||r.pointerType!=="mouse"&&!u.matches(s.focusableElements))&&n.activeElement.blur();const C=T&&t.allowTouchMove&&i.touchStartPreventDefault;(i.touchStartForcePreventDefault||C)&&!u.isContentEditable&&r.preventDefault(),i.freeMode&&i.freeMode.enabled&&t.freeMode&&t.animating&&!i.cssMode&&t.freeMode.onTouchStart(),t.emit("touchStart",r)}function BL(e){const t=ld(),n=this;if(n.destroyed)return;const r=n.touchEventsData,{params:s,touches:i,rtlTranslate:a,enabled:c}=n;if(!c||!s.simulateTouch&&e.pointerType==="mouse")return;let u=e;if(u.originalEvent&&(u=u.originalEvent),u.type==="pointermove"&&(r.touchId!==null||u.pointerId!==r.pointerId))return;let f;if(u.type==="touchmove"){if(f=[...u.changedTouches].find(F=>F.identifier===r.touchId),!f||f.identifier!==r.touchId)return}else f=u;if(!r.isTouched){r.startMoving&&r.isScrolling&&n.emit("touchMoveOpposite",u);return}const p=f.pageX,g=f.pageY;if(u.preventedByNestedSwiper){i.startX=p,i.startY=g;return}if(!n.allowTouchMove){u.target.matches(r.focusableElements)||(n.allowClick=!1),r.isTouched&&(Object.assign(i,{startX:p,startY:g,currentX:p,currentY:g}),r.touchStartTime=Km());return}if(s.touchReleaseOnEdges&&!s.loop)if(n.isVertical()){if(g<i.startY&&n.translate<=n.maxTranslate()||g>i.startY&&n.translate>=n.minTranslate()){r.isTouched=!1,r.isMoved=!1;return}}else{if(a&&(p>i.startX&&-n.translate<=n.maxTranslate()||p<i.startX&&-n.translate>=n.minTranslate()))return;if(!a&&(p<i.startX&&n.translate<=n.maxTranslate()||p>i.startX&&n.translate>=n.minTranslate()))return}if(t.activeElement&&t.activeElement.matches(r.focusableElements)&&t.activeElement!==u.target&&u.pointerType!=="mouse"&&t.activeElement.blur(),t.activeElement&&u.target===t.activeElement&&u.target.matches(r.focusableElements)){r.isMoved=!0,n.allowClick=!1;return}r.allowTouchCallbacks&&n.emit("touchMove",u),i.previousX=i.currentX,i.previousY=i.currentY,i.currentX=p,i.currentY=g;const y=i.currentX-i.startX,v=i.currentY-i.startY;if(n.params.threshold&&Math.sqrt(y**2+v**2)<n.params.threshold)return;if(typeof r.isScrolling>"u"){let F;n.isHorizontal()&&i.currentY===i.startY||n.isVertical()&&i.currentX===i.startX?r.isScrolling=!1:y*y+v*v>=25&&(F=Math.atan2(Math.abs(v),Math.abs(y))*180/Math.PI,r.isScrolling=n.isHorizontal()?F>s.touchAngle:90-F>s.touchAngle)}if(r.isScrolling&&n.emit("touchMoveOpposite",u),typeof r.startMoving>"u"&&(i.currentX!==i.startX||i.currentY!==i.startY)&&(r.startMoving=!0),r.isScrolling||u.type==="touchmove"&&r.preventTouchMoveFromPointerMove){r.isTouched=!1;return}if(!r.startMoving)return;n.allowClick=!1,!s.cssMode&&u.cancelable&&u.preventDefault(),s.touchMoveStopPropagation&&!s.nested&&u.stopPropagation();let S=n.isHorizontal()?y:v,T=n.isHorizontal()?i.currentX-i.previousX:i.currentY-i.previousY;s.oneWayMovement&&(S=Math.abs(S)*(a?1:-1),T=Math.abs(T)*(a?1:-1)),i.diff=S,S*=s.touchRatio,a&&(S=-S,T=-T);const C=n.touchesDirection;n.swipeDirection=S>0?"prev":"next",n.touchesDirection=T>0?"prev":"next";const L=n.params.loop&&!s.cssMode,E=n.touchesDirection==="next"&&n.allowSlideNext||n.touchesDirection==="prev"&&n.allowSlidePrev;if(!r.isMoved){if(L&&E&&n.loopFix({direction:n.swipeDirection}),r.startTranslate=n.getTranslate(),n.setTransition(0),n.animating){const F=new window.CustomEvent("transitionend",{bubbles:!0,cancelable:!0,detail:{bySwiperTouchMove:!0}});n.wrapperEl.dispatchEvent(F)}r.allowMomentumBounce=!1,s.grabCursor&&(n.allowSlideNext===!0||n.allowSlidePrev===!0)&&n.setGrabCursor(!0),n.emit("sliderFirstMove",u)}if(new Date().getTime(),s._loopSwapReset!==!1&&r.isMoved&&r.allowThresholdMove&&C!==n.touchesDirection&&L&&E&&Math.abs(S)>=1){Object.assign(i,{startX:p,startY:g,currentX:p,currentY:g,startTranslate:r.currentTranslate}),r.loopSwapReset=!0,r.startTranslate=r.currentTranslate;return}n.emit("sliderMove",u),r.isMoved=!0,r.currentTranslate=S+r.startTranslate;let D=!0,B=s.resistanceRatio;if(s.touchReleaseOnEdges&&(B=0),S>0?(L&&E&&r.allowThresholdMove&&r.currentTranslate>(s.centeredSlides?n.minTranslate()-n.slidesSizesGrid[n.activeIndex+1]-(s.slidesPerView!=="auto"&&n.slides.length-s.slidesPerView>=2?n.slidesSizesGrid[n.activeIndex+1]+n.params.spaceBetween:0)-n.params.spaceBetween:n.minTranslate())&&n.loopFix({direction:"prev",setTranslate:!0,activeSlideIndex:0}),r.currentTranslate>n.minTranslate()&&(D=!1,s.resistance&&(r.currentTranslate=n.minTranslate()-1+(-n.minTranslate()+r.startTranslate+S)**B))):S<0&&(L&&E&&r.allowThresholdMove&&r.currentTranslate<(s.centeredSlides?n.maxTranslate()+n.slidesSizesGrid[n.slidesSizesGrid.length-1]+n.params.spaceBetween+(s.slidesPerView!=="auto"&&n.slides.length-s.slidesPerView>=2?n.slidesSizesGrid[n.slidesSizesGrid.length-1]+n.params.spaceBetween:0):n.maxTranslate())&&n.loopFix({direction:"next",setTranslate:!0,activeSlideIndex:n.slides.length-(s.slidesPerView==="auto"?n.slidesPerViewDynamic():Math.ceil(parseFloat(s.slidesPerView,10)))}),r.currentTranslate<n.maxTranslate()&&(D=!1,s.resistance&&(r.currentTranslate=n.maxTranslate()+1-(n.maxTranslate()-r.startTranslate-S)**B))),D&&(u.preventedByNestedSwiper=!0),!n.allowSlideNext&&n.swipeDirection==="next"&&r.currentTranslate<r.startTranslate&&(r.currentTranslate=r.startTranslate),!n.allowSlidePrev&&n.swipeDirection==="prev"&&r.currentTranslate>r.startTranslate&&(r.currentTranslate=r.startTranslate),!n.allowSlidePrev&&!n.allowSlideNext&&(r.currentTranslate=r.startTranslate),s.threshold>0)if(Math.abs(S)>s.threshold||r.allowThresholdMove){if(!r.allowThresholdMove){r.allowThresholdMove=!0,i.startX=i.currentX,i.startY=i.currentY,r.currentTranslate=r.startTranslate,i.diff=n.isHorizontal()?i.currentX-i.startX:i.currentY-i.startY;return}}else{r.currentTranslate=r.startTranslate;return}!s.followFinger||s.cssMode||((s.freeMode&&s.freeMode.enabled&&n.freeMode||s.watchSlidesProgress)&&(n.updateActiveIndex(),n.updateSlidesClasses()),s.freeMode&&s.freeMode.enabled&&n.freeMode&&n.freeMode.onTouchMove(),n.updateProgress(r.currentTranslate),n.setTranslate(r.currentTranslate))}function FL(e){const t=this;if(t.destroyed)return;const n=t.touchEventsData;let r=e;r.originalEvent&&(r=r.originalEvent);let s;if(r.type==="touchend"||r.type==="touchcancel"){if(s=[...r.changedTouches].find(F=>F.identifier===n.touchId),!s||s.identifier!==n.touchId)return}else{if(n.touchId!==null||r.pointerId!==n.pointerId)return;s=r}if(["pointercancel","pointerout","pointerleave","contextmenu"].includes(r.type)&&!(["pointercancel","contextmenu"].includes(r.type)&&(t.browser.isSafari||t.browser.isWebView)))return;n.pointerId=null,n.touchId=null;const{params:a,touches:c,rtlTranslate:u,slidesGrid:f,enabled:p}=t;if(!p||!a.simulateTouch&&r.pointerType==="mouse")return;if(n.allowTouchCallbacks&&t.emit("touchEnd",r),n.allowTouchCallbacks=!1,!n.isTouched){n.isMoved&&a.grabCursor&&t.setGrabCursor(!1),n.isMoved=!1,n.startMoving=!1;return}a.grabCursor&&n.isMoved&&n.isTouched&&(t.allowSlideNext===!0||t.allowSlidePrev===!0)&&t.setGrabCursor(!1);const g=Km(),y=g-n.touchStartTime;if(t.allowClick){const F=r.path||r.composedPath&&r.composedPath();t.updateClickedSlide(F&&F[0]||r.target,F),t.emit("tap click",r),y<300&&g-n.lastClickTime<300&&t.emit("doubleTap doubleClick",r)}if(n.lastClickTime=Km(),mS(()=>{t.destroyed||(t.allowClick=!0)}),!n.isTouched||!n.isMoved||!t.swipeDirection||c.diff===0&&!n.loopSwapReset||n.currentTranslate===n.startTranslate&&!n.loopSwapReset){n.isTouched=!1,n.isMoved=!1,n.startMoving=!1;return}n.isTouched=!1,n.isMoved=!1,n.startMoving=!1;let v;if(a.followFinger?v=u?t.translate:-t.translate:v=-n.currentTranslate,a.cssMode)return;if(a.freeMode&&a.freeMode.enabled){t.freeMode.onTouchEnd({currentPos:v});return}const S=v>=-t.maxTranslate()&&!t.params.loop;let T=0,C=t.slidesSizesGrid[0];for(let F=0;F<f.length;F+=F<a.slidesPerGroupSkip?1:a.slidesPerGroup){const j=F<a.slidesPerGroupSkip-1?1:a.slidesPerGroup;typeof f[F+j]<"u"?(S||v>=f[F]&&v<f[F+j])&&(T=F,C=f[F+j]-f[F]):(S||v>=f[F])&&(T=F,C=f[f.length-1]-f[f.length-2])}let L=null,E=null;a.rewind&&(t.isBeginning?E=a.virtual&&a.virtual.enabled&&t.virtual?t.virtual.slides.length-1:t.slides.length-1:t.isEnd&&(L=0));const D=(v-f[T])/C,B=T<a.slidesPerGroupSkip-1?1:a.slidesPerGroup;if(y>a.longSwipesMs){if(!a.longSwipes){t.slideTo(t.activeIndex);return}t.swipeDirection==="next"&&(D>=a.longSwipesRatio?t.slideTo(a.rewind&&t.isEnd?L:T+B):t.slideTo(T)),t.swipeDirection==="prev"&&(D>1-a.longSwipesRatio?t.slideTo(T+B):E!==null&&D<0&&Math.abs(D)>a.longSwipesRatio?t.slideTo(E):t.slideTo(T))}else{if(!a.shortSwipes){t.slideTo(t.activeIndex);return}t.navigation&&(r.target===t.navigation.nextEl||r.target===t.navigation.prevEl)?r.target===t.navigation.nextEl?t.slideTo(T+B):t.slideTo(T):(t.swipeDirection==="next"&&t.slideTo(L!==null?L:T+B),t.swipeDirection==="prev"&&t.slideTo(E!==null?E:T))}}function y5(){const e=this,{params:t,el:n}=e;if(n&&n.offsetWidth===0)return;t.breakpoints&&e.setBreakpoint();const{allowSlideNext:r,allowSlidePrev:s,snapGrid:i}=e,a=e.virtual&&e.params.virtual.enabled;e.allowSlideNext=!0,e.allowSlidePrev=!0,e.updateSize(),e.updateSlides(),e.updateSlidesClasses();const c=a&&t.loop;if((t.slidesPerView==="auto"||t.slidesPerView>1)&&e.isEnd&&!e.isBeginning&&!e.params.centeredSlides&&!c){const u=a?e.virtual.slides:e.slides;e.slideTo(u.length-1,0,!1,!0)}else e.params.loop&&!a?e.slideToLoop(e.realIndex,0,!1,!0):e.slideTo(e.activeIndex,0,!1,!0);e.autoplay&&e.autoplay.running&&e.autoplay.paused&&(clearTimeout(e.autoplay.resizeTimeout),e.autoplay.resizeTimeout=setTimeout(()=>{e.autoplay&&e.autoplay.running&&e.autoplay.paused&&e.autoplay.resume()},500)),e.allowSlidePrev=s,e.allowSlideNext=r,e.params.watchOverflow&&i!==e.snapGrid&&e.checkOverflow()}function OL(e){const t=this;t.destroyed||t.enabled&&(t.allowClick||(t.params.preventClicks&&e.preventDefault(),t.params.preventClicksPropagation&&t.animating&&(e.stopPropagation(),e.stopImmediatePropagation())))}function QL(){const e=this;if(e.destroyed)return;const{wrapperEl:t,rtlTranslate:n,enabled:r}=e;if(!r)return;e.previousTranslate=e.translate,e.isHorizontal()?e.translate=-t.scrollLeft:e.translate=-t.scrollTop,e.translate===0&&(e.translate=0),e.updateActiveIndex(),e.updateSlidesClasses();let s;const i=e.maxTranslate()-e.minTranslate();i===0?s=0:s=(e.translate-e.minTranslate())/i,s!==e.progress&&e.updateProgress(n?-e.translate:e.translate),e.emit("setTranslate",e.translate,!1)}function $L(e){const t=this;t.destroyed||(Am(t,e.target),!(t.params.cssMode||t.params.slidesPerView!=="auto"&&!t.params.autoHeight)&&t.update())}function HL(){const e=this;e.destroyed||e.documentTouchHandlerProceeded||(e.documentTouchHandlerProceeded=!0,e.params.touchReleaseOnEdges&&(e.el.style.touchAction="auto"))}const wS=(e,t)=>{const n=ld(),{params:r,el:s,wrapperEl:i,device:a}=e,c=!!r.nested,u=t==="on"?"addEventListener":"removeEventListener",f=t;!s||typeof s=="string"||(n[u]("touchstart",e.onDocumentTouchStart,{passive:!1,capture:c}),s[u]("touchstart",e.onTouchStart,{passive:!1}),s[u]("pointerdown",e.onTouchStart,{passive:!1}),n[u]("touchmove",e.onTouchMove,{passive:!1,capture:c}),n[u]("pointermove",e.onTouchMove,{passive:!1,capture:c}),n[u]("touchend",e.onTouchEnd,{passive:!0}),n[u]("pointerup",e.onTouchEnd,{passive:!0}),n[u]("pointercancel",e.onTouchEnd,{passive:!0}),n[u]("touchcancel",e.onTouchEnd,{passive:!0}),n[u]("pointerout",e.onTouchEnd,{passive:!0}),n[u]("pointerleave",e.onTouchEnd,{passive:!0}),n[u]("contextmenu",e.onTouchEnd,{passive:!0}),(r.preventClicks||r.preventClicksPropagation)&&s[u]("click",e.onClick,!0),r.cssMode&&i[u]("scroll",e.onScroll),r.updateOnWindowResize?e[f](a.ios||a.android?"resize orientationchange observerUpdate":"resize observerUpdate",y5,!0):e[f]("observerUpdate",y5,!0),s[u]("load",e.onLoad,{capture:!0}))};function UL(){const e=this,{params:t}=e;e.onTouchStart=PL.bind(e),e.onTouchMove=BL.bind(e),e.onTouchEnd=FL.bind(e),e.onDocumentTouchStart=HL.bind(e),t.cssMode&&(e.onScroll=QL.bind(e)),e.onClick=OL.bind(e),e.onLoad=$L.bind(e),wS(e,"on")}function zL(){wS(this,"off")}var GL={attachEvents:UL,detachEvents:zL};const v5=(e,t)=>e.grid&&t.grid&&t.grid.rows>1;function WL(){const e=this,{realIndex:t,initialized:n,params:r,el:s}=e,i=r.breakpoints;if(!i||i&&Object.keys(i).length===0)return;const a=ld(),c=r.breakpointsBase==="window"||!r.breakpointsBase?r.breakpointsBase:"container",u=["window","container"].includes(r.breakpointsBase)||!r.breakpointsBase?e.el:a.querySelector(r.breakpointsBase),f=e.getBreakpoint(i,c,u);if(!f||e.currentBreakpoint===f)return;const g=(f in i?i[f]:void 0)||e.originalParams,y=v5(e,r),v=v5(e,g),S=e.params.grabCursor,T=g.grabCursor,C=r.enabled;y&&!v?(s.classList.remove(`${r.containerModifierClass}grid`,`${r.containerModifierClass}grid-column`),e.emitContainerClasses()):!y&&v&&(s.classList.add(`${r.containerModifierClass}grid`),(g.grid.fill&&g.grid.fill==="column"||!g.grid.fill&&r.grid.fill==="column")&&s.classList.add(`${r.containerModifierClass}grid-column`),e.emitContainerClasses()),S&&!T?e.unsetGrabCursor():!S&&T&&e.setGrabCursor(),["navigation","pagination","scrollbar"].forEach(j=>{if(typeof g[j]>"u")return;const A=r[j]&&r[j].enabled,H=g[j]&&g[j].enabled;A&&!H&&e[j].disable(),!A&&H&&e[j].enable()});const L=g.direction&&g.direction!==r.direction,E=r.loop&&(g.slidesPerView!==r.slidesPerView||L),D=r.loop;L&&n&&e.changeDirection(),Qa(e.params,g);const B=e.params.enabled,F=e.params.loop;Object.assign(e,{allowTouchMove:e.params.allowTouchMove,allowSlideNext:e.params.allowSlideNext,allowSlidePrev:e.params.allowSlidePrev}),C&&!B?e.disable():!C&&B&&e.enable(),e.currentBreakpoint=f,e.emit("_beforeBreakpoint",g),n&&(E?(e.loopDestroy(),e.loopCreate(t),e.updateSlides()):!D&&F?(e.loopCreate(t),e.updateSlides()):D&&!F&&e.loopDestroy()),e.emit("breakpoint",g)}function VL(e,t="window",n){if(!e||t==="container"&&!n)return;let r=!1;const s=na(),i=t==="window"?s.innerHeight:n.clientHeight,a=Object.keys(e).map(c=>{if(typeof c=="string"&&c.indexOf("@")===0){const u=parseFloat(c.substr(1));return{value:i*u,point:c}}return{value:c,point:c}});a.sort((c,u)=>parseInt(c.value,10)-parseInt(u.value,10));for(let c=0;c<a.length;c+=1){const{point:u,value:f}=a[c];t==="window"?s.matchMedia(`(min-width: ${f}px)`).matches&&(r=u):f<=n.clientWidth&&(r=u)}return r||"max"}var qL={setBreakpoint:WL,getBreakpoint:VL};function KL(e,t){const n=[];return e.forEach(r=>{typeof r=="object"?Object.keys(r).forEach(s=>{r[s]&&n.push(t+s)}):typeof r=="string"&&n.push(t+r)}),n}function YL(){const e=this,{classNames:t,params:n,rtl:r,el:s,device:i}=e,a=KL(["initialized",n.direction,{"free-mode":e.params.freeMode&&n.freeMode.enabled},{autoheight:n.autoHeight},{rtl:r},{grid:n.grid&&n.grid.rows>1},{"grid-column":n.grid&&n.grid.rows>1&&n.grid.fill==="column"},{android:i.android},{ios:i.ios},{"css-mode":n.cssMode},{centered:n.cssMode&&n.centeredSlides},{"watch-progress":n.watchSlidesProgress}],n.containerModifierClass);t.push(...a),s.classList.add(...t),e.emitContainerClasses()}function XL(){const e=this,{el:t,classNames:n}=e;!t||typeof t=="string"||(t.classList.remove(...n),e.emitContainerClasses())}var ZL={addClasses:YL,removeClasses:XL};function JL(){const e=this,{isLocked:t,params:n}=e,{slidesOffsetBefore:r}=n;if(r){const s=e.slides.length-1,i=e.slidesGrid[s]+e.slidesSizesGrid[s]+r*2;e.isLocked=e.size>i}else e.isLocked=e.snapGrid.length===1;n.allowSlideNext===!0&&(e.allowSlideNext=!e.isLocked),n.allowSlidePrev===!0&&(e.allowSlidePrev=!e.isLocked),t&&t!==e.isLocked&&(e.isEnd=!1),t!==e.isLocked&&e.emit(e.isLocked?"lock":"unlock")}var eE={checkOverflow:JL},Wb={init:!0,direction:"horizontal",oneWayMovement:!1,swiperElementNodeName:"SWIPER-CONTAINER",touchEventsTarget:"wrapper",initialSlide:0,speed:300,cssMode:!1,updateOnWindowResize:!0,resizeObserver:!0,nested:!1,createElements:!1,eventsPrefix:"swiper",enabled:!0,focusableElements:"input, select, option, textarea, button, video, label",width:null,height:null,preventInteractionOnTransition:!1,userAgent:null,url:null,edgeSwipeDetection:!1,edgeSwipeThreshold:20,autoHeight:!1,setWrapperSize:!1,virtualTranslate:!1,effect:"slide",breakpoints:void 0,breakpointsBase:"window",spaceBetween:0,slidesPerView:1,slidesPerGroup:1,slidesPerGroupSkip:0,slidesPerGroupAuto:!1,centeredSlides:!1,centeredSlidesBounds:!1,slidesOffsetBefore:0,slidesOffsetAfter:0,normalizeSlideIndex:!0,centerInsufficientSlides:!1,snapToSlideEdge:!1,watchOverflow:!0,roundLengths:!1,touchRatio:1,touchAngle:45,simulateTouch:!0,shortSwipes:!0,longSwipes:!0,longSwipesRatio:.5,longSwipesMs:300,followFinger:!0,allowTouchMove:!0,threshold:5,touchMoveStopPropagation:!1,touchStartPreventDefault:!0,touchStartForcePreventDefault:!1,touchReleaseOnEdges:!1,uniqueNavElements:!0,resistance:!0,resistanceRatio:.85,watchSlidesProgress:!1,grabCursor:!1,preventClicks:!0,preventClicksPropagation:!0,slideToClickedSlide:!1,loop:!1,loopAddBlankSlides:!0,loopAdditionalSlides:0,loopPreventsSliding:!0,rewind:!1,allowSlidePrev:!0,allowSlideNext:!0,swipeHandler:null,noSwiping:!0,noSwipingClass:"swiper-no-swiping",noSwipingSelector:null,passiveListeners:!0,maxBackfaceHiddenSlides:10,containerModifierClass:"swiper-",slideClass:"swiper-slide",slideBlankClass:"swiper-slide-blank",slideActiveClass:"swiper-slide-active",slideVisibleClass:"swiper-slide-visible",slideFullyVisibleClass:"swiper-slide-fully-visible",slideNextClass:"swiper-slide-next",slidePrevClass:"swiper-slide-prev",wrapperClass:"swiper-wrapper",lazyPreloaderClass:"swiper-lazy-preloader",lazyPreloadPrevNext:0,runCallbacksOnInit:!0,_emitClasses:!1};function tE(e,t){return function(r={}){const s=Object.keys(r)[0],i=r[s];if(typeof i!="object"||i===null){Qa(t,r);return}if(e[s]===!0&&(e[s]={enabled:!0}),s==="navigation"&&e[s]&&e[s].enabled&&!e[s].prevEl&&!e[s].nextEl&&(e[s].auto=!0),["pagination","scrollbar"].indexOf(s)>=0&&e[s]&&e[s].enabled&&!e[s].el&&(e[s].auto=!0),!(s in e&&"enabled"in i)){Qa(t,r);return}typeof e[s]=="object"&&!("enabled"in e[s])&&(e[s].enabled=!0),e[s]||(e[s]={enabled:!1}),Qa(t,r)}}const Y1={eventsEmitter:Z_,update:cL,translate:mL,transition:yL,slide:_L,loop:RL,grabCursor:DL,events:GL,breakpoints:qL,checkOverflow:eE,classes:ZL},X1={};let Ly=class Ec{constructor(...t){let n,r;t.length===1&&t[0].constructor&&Object.prototype.toString.call(t[0]).slice(8,-1)==="Object"?r=t[0]:[n,r]=t,r||(r={}),r=Qa({},r),n&&!r.el&&(r.el=n);const s=ld();if(r.el&&typeof r.el=="string"&&s.querySelectorAll(r.el).length>1){const u=[];return s.querySelectorAll(r.el).forEach(f=>{const p=Qa({},r,{el:f});u.push(new Ec(p))}),u}const i=this;i.__swiper__=!0,i.support=xS(),i.device=bS({userAgent:r.userAgent}),i.browser=yS(),i.eventsListeners={},i.eventsAnyListeners=[],i.modules=[...i.__modules__],r.modules&&Array.isArray(r.modules)&&r.modules.forEach(u=>{typeof u=="function"&&i.modules.indexOf(u)<0&&i.modules.push(u)});const a={};i.modules.forEach(u=>{u({params:r,swiper:i,extendParams:tE(r,a),on:i.on.bind(i),once:i.once.bind(i),off:i.off.bind(i),emit:i.emit.bind(i)})});const c=Qa({},Wb,a);return i.params=Qa({},c,X1,r),i.originalParams=Qa({},i.params),i.passedParams=Qa({},r),i.params&&i.params.on&&Object.keys(i.params.on).forEach(u=>{i.on(u,i.params.on[u])}),i.params&&i.params.onAny&&i.onAny(i.params.onAny),Object.assign(i,{enabled:i.params.enabled,el:n,classNames:[],slides:[],slidesGrid:[],snapGrid:[],slidesSizesGrid:[],isHorizontal(){return i.params.direction==="horizontal"},isVertical(){return i.params.direction==="vertical"},activeIndex:0,realIndex:0,isBeginning:!0,isEnd:!1,translate:0,previousTranslate:0,progress:0,velocity:0,animating:!1,cssOverflowAdjustment(){return Math.trunc(this.translate/2**23)*2**23},allowSlideNext:i.params.allowSlideNext,allowSlidePrev:i.params.allowSlidePrev,touchEventsData:{isTouched:void 0,isMoved:void 0,allowTouchCallbacks:void 0,touchStartTime:void 0,isScrolling:void 0,currentTranslate:void 0,startTranslate:void 0,allowThresholdMove:void 0,focusableElements:i.params.focusableElements,lastClickTime:0,clickTimeout:void 0,velocities:[],allowMomentumBounce:void 0,startMoving:void 0,pointerId:null,touchId:null},allowClick:!0,allowTouchMove:i.params.allowTouchMove,touches:{startX:0,startY:0,currentX:0,currentY:0,diff:0},imagesToLoad:[],imagesLoaded:0}),i.emit("_swiper"),i.params.init&&i.init(),i}getDirectionLabel(t){return this.isHorizontal()?t:{width:"height","margin-top":"margin-left","margin-bottom ":"margin-right","margin-left":"margin-top","margin-right":"margin-bottom","padding-left":"padding-top","padding-right":"padding-bottom",marginRight:"marginBottom"}[t]}getSlideIndex(t){const{slidesEl:n,params:r}=this,s=Nc(n,`.${r.slideClass}, swiper-slide`),i=p5(s[0]);return p5(t)-i}getSlideIndexByData(t){return this.getSlideIndex(this.slides.find(n=>n.getAttribute("data-swiper-slide-index")*1===t))}getSlideIndexWhenGrid(t){return this.grid&&this.params.grid&&this.params.grid.rows>1&&(this.params.grid.fill==="column"?t=Math.floor(t/this.params.grid.rows):this.params.grid.fill==="row"&&(t=t%Math.ceil(this.slides.length/this.params.grid.rows))),t}recalcSlides(){const t=this,{slidesEl:n,params:r}=t;t.slides=Nc(n,`.${r.slideClass}, swiper-slide`)}enable(){const t=this;t.enabled||(t.enabled=!0,t.params.grabCursor&&t.setGrabCursor(),t.emit("enable"))}disable(){const t=this;t.enabled&&(t.enabled=!1,t.params.grabCursor&&t.unsetGrabCursor(),t.emit("disable"))}setProgress(t,n){const r=this;t=Math.min(Math.max(t,0),1);const s=r.minTranslate(),a=(r.maxTranslate()-s)*t+s;r.translateTo(a,typeof n>"u"?0:n),r.updateActiveIndex(),r.updateSlidesClasses()}emitContainerClasses(){const t=this;if(!t.params._emitClasses||!t.el)return;const n=t.el.className.split(" ").filter(r=>r.indexOf("swiper")===0||r.indexOf(t.params.containerModifierClass)===0);t.emit("_containerClasses",n.join(" "))}getSlideClasses(t){const n=this;return n.destroyed?"":t.className.split(" ").filter(r=>r.indexOf("swiper-slide")===0||r.indexOf(n.params.slideClass)===0).join(" ")}emitSlidesClasses(){const t=this;if(!t.params._emitClasses||!t.el)return;const n=[];t.slides.forEach(r=>{const s=t.getSlideClasses(r);n.push({slideEl:r,classNames:s}),t.emit("_slideClass",r,s)}),t.emit("_slideClasses",n)}slidesPerViewDynamic(t="current",n=!1){const r=this,{params:s,slides:i,slidesGrid:a,slidesSizesGrid:c,size:u,activeIndex:f}=r;let p=1;if(typeof s.slidesPerView=="number")return s.slidesPerView;if(s.centeredSlides){let g=i[f]?Math.ceil(i[f].swiperSlideSize):0,y;for(let v=f+1;v<i.length;v+=1)i[v]&&!y&&(g+=Math.ceil(i[v].swiperSlideSize),p+=1,g>u&&(y=!0));for(let v=f-1;v>=0;v-=1)i[v]&&!y&&(g+=i[v].swiperSlideSize,p+=1,g>u&&(y=!0))}else if(t==="current")for(let g=f+1;g<i.length;g+=1)(n?a[g]+c[g]-a[f]<u:a[g]-a[f]<u)&&(p+=1);else for(let g=f-1;g>=0;g-=1)a[f]-a[g]<u&&(p+=1);return p}update(){const t=this;if(!t||t.destroyed)return;const{snapGrid:n,params:r}=t;r.breakpoints&&t.setBreakpoint(),[...t.el.querySelectorAll('[loading="lazy"]')].forEach(a=>{a.complete&&Am(t,a)}),t.updateSize(),t.updateSlides(),t.updateProgress(),t.updateSlidesClasses();function s(){const a=t.rtlTranslate?t.translate*-1:t.translate,c=Math.min(Math.max(a,t.maxTranslate()),t.minTranslate());t.setTranslate(c),t.updateActiveIndex(),t.updateSlidesClasses()}let i;if(r.freeMode&&r.freeMode.enabled&&!r.cssMode)s(),r.autoHeight&&t.updateAutoHeight();else{if((r.slidesPerView==="auto"||r.slidesPerView>1)&&t.isEnd&&!r.centeredSlides){const a=t.virtual&&r.virtual.enabled?t.virtual.slides:t.slides;i=t.slideTo(a.length-1,0,!1,!0)}else i=t.slideTo(t.activeIndex,0,!1,!0);i||s()}r.watchOverflow&&n!==t.snapGrid&&t.checkOverflow(),t.emit("update")}changeDirection(t,n=!0){const r=this,s=r.params.direction;return t||(t=s==="horizontal"?"vertical":"horizontal"),t===s||t!=="horizontal"&&t!=="vertical"||(r.el.classList.remove(`${r.params.containerModifierClass}${s}`),r.el.classList.add(`${r.params.containerModifierClass}${t}`),r.emitContainerClasses(),r.params.direction=t,r.slides.forEach(i=>{t==="vertical"?i.style.width="":i.style.height=""}),r.emit("changeDirection"),n&&r.update()),r}changeLanguageDirection(t){const n=this;n.rtl&&t==="rtl"||!n.rtl&&t==="ltr"||(n.rtl=t==="rtl",n.rtlTranslate=n.params.direction==="horizontal"&&n.rtl,n.rtl?(n.el.classList.add(`${n.params.containerModifierClass}rtl`),n.el.dir="rtl"):(n.el.classList.remove(`${n.params.containerModifierClass}rtl`),n.el.dir="ltr"),n.update())}mount(t){const n=this;if(n.mounted)return!0;let r=t||n.params.el;if(typeof r=="string"&&(r=document.querySelector(r)),!r)return!1;r.swiper=n,r.parentNode&&r.parentNode.host&&r.parentNode.host.nodeName===n.params.swiperElementNodeName.toUpperCase()&&(n.isElement=!0);const s=()=>`.${(n.params.wrapperClass||"").trim().split(" ").join(".")}`;let a=r&&r.shadowRoot&&r.shadowRoot.querySelector?r.shadowRoot.querySelector(s()):Nc(r,s())[0];return!a&&n.params.createElements&&(a=zb("div",n.params.wrapperClass),r.append(a),Nc(r,`.${n.params.slideClass}`).forEach(c=>{a.append(c)})),Object.assign(n,{el:r,wrapperEl:a,slidesEl:n.isElement&&!r.parentNode.host.slideSlots?r.parentNode.host:a,hostEl:n.isElement?r.parentNode.host:r,mounted:!0,rtl:r.dir.toLowerCase()==="rtl"||cu(r,"direction")==="rtl",rtlTranslate:n.params.direction==="horizontal"&&(r.dir.toLowerCase()==="rtl"||cu(r,"direction")==="rtl"),wrongRTL:cu(a,"display")==="-webkit-box"}),!0}init(t){const n=this;if(n.initialized||n.mount(t)===!1)return n;n.emit("beforeInit"),n.params.breakpoints&&n.setBreakpoint(),n.addClasses(),n.updateSize(),n.updateSlides(),n.params.watchOverflow&&n.checkOverflow(),n.params.grabCursor&&n.enabled&&n.setGrabCursor(),n.params.loop&&n.virtual&&n.params.virtual.enabled?n.slideTo(n.params.initialSlide+n.virtual.slidesBefore,0,n.params.runCallbacksOnInit,!1,!0):n.slideTo(n.params.initialSlide,0,n.params.runCallbacksOnInit,!1,!0),n.params.loop&&n.loopCreate(void 0,!0),n.attachEvents();const s=[...n.el.querySelectorAll('[loading="lazy"]')];return n.isElement&&s.push(...n.hostEl.querySelectorAll('[loading="lazy"]')),s.forEach(i=>{i.complete?Am(n,i):i.addEventListener("load",a=>{Am(n,a.target)})}),Gb(n),n.initialized=!0,Gb(n),n.emit("init"),n.emit("afterInit"),n}destroy(t=!0,n=!0){const r=this,{params:s,el:i,wrapperEl:a,slides:c}=r;return typeof r.params>"u"||r.destroyed||(r.emit("beforeDestroy"),r.initialized=!1,r.detachEvents(),s.loop&&r.loopDestroy(),n&&(r.removeClasses(),i&&typeof i!="string"&&i.removeAttribute("style"),a&&a.removeAttribute("style"),c&&c.length&&c.forEach(u=>{u.classList.remove(s.slideVisibleClass,s.slideFullyVisibleClass,s.slideActiveClass,s.slideNextClass,s.slidePrevClass),u.removeAttribute("style"),u.removeAttribute("data-swiper-slide-index")})),r.emit("destroy"),Object.keys(r.eventsListeners).forEach(u=>{r.off(u)}),t!==!1&&(r.el&&typeof r.el!="string"&&(r.el.swiper=null),F_(r)),r.destroyed=!0),null}static extendDefaults(t){Qa(X1,t)}static get extendedDefaults(){return X1}static get defaults(){return Wb}static installModule(t){Ec.prototype.__modules__||(Ec.prototype.__modules__=[]);const n=Ec.prototype.__modules__;typeof t=="function"&&n.indexOf(t)<0&&n.push(t)}static use(t){return Array.isArray(t)?(t.forEach(n=>Ec.installModule(n)),Ec):(Ec.installModule(t),Ec)}};Object.keys(Y1).forEach(e=>{Object.keys(Y1[e]).forEach(t=>{Ly.prototype[t]=Y1[e][t]})});Ly.use([Y_,X_]);const SS=["eventsPrefix","injectStyles","injectStylesUrls","modules","init","_direction","oneWayMovement","swiperElementNodeName","touchEventsTarget","initialSlide","_speed","cssMode","updateOnWindowResize","resizeObserver","nested","focusableElements","_enabled","_width","_height","preventInteractionOnTransition","userAgent","url","_edgeSwipeDetection","_edgeSwipeThreshold","_freeMode","_autoHeight","setWrapperSize","virtualTranslate","_effect","breakpoints","breakpointsBase","_spaceBetween","_slidesPerView","maxBackfaceHiddenSlides","_grid","_slidesPerGroup","_slidesPerGroupSkip","_slidesPerGroupAuto","_centeredSlides","_centeredSlidesBounds","_slidesOffsetBefore","_slidesOffsetAfter","normalizeSlideIndex","_centerInsufficientSlides","_snapToSlideEdge","_watchOverflow","roundLengths","touchRatio","touchAngle","simulateTouch","_shortSwipes","_longSwipes","longSwipesRatio","longSwipesMs","_followFinger","allowTouchMove","_threshold","touchMoveStopPropagation","touchStartPreventDefault","touchStartForcePreventDefault","touchReleaseOnEdges","uniqueNavElements","_resistance","_resistanceRatio","_watchSlidesProgress","_grabCursor","preventClicks","preventClicksPropagation","_slideToClickedSlide","_loop","loopAdditionalSlides","loopAddBlankSlides","loopPreventsSliding","_rewind","_allowSlidePrev","_allowSlideNext","_swipeHandler","_noSwiping","noSwipingClass","noSwipingSelector","passiveListeners","containerModifierClass","slideClass","slideActiveClass","slideVisibleClass","slideFullyVisibleClass","slideNextClass","slidePrevClass","slideBlankClass","wrapperClass","lazyPreloaderClass","lazyPreloadPrevNext","runCallbacksOnInit","observer","observeParents","observeSlideChildren","a11y","_autoplay","_controller","coverflowEffect","cubeEffect","fadeEffect","flipEffect","creativeEffect","cardsEffect","hashNavigation","history","keyboard","mousewheel","_navigation","_pagination","parallax","_scrollbar","_thumbs","virtual","zoom","control"];function nd(e){return typeof e=="object"&&e!==null&&e.constructor&&Object.prototype.toString.call(e).slice(8,-1)==="Object"&&!e.__swiper__}function m0(e,t){const n=["__proto__","constructor","prototype"];Object.keys(t).filter(r=>n.indexOf(r)<0).forEach(r=>{typeof e[r]>"u"?e[r]=t[r]:nd(t[r])&&nd(e[r])&&Object.keys(t[r]).length>0?t[r].__swiper__?e[r]=t[r]:m0(e[r],t[r]):e[r]=t[r]})}function AS(e={}){return e.navigation&&typeof e.navigation.nextEl>"u"&&typeof e.navigation.prevEl>"u"}function TS(e={}){return e.pagination&&typeof e.pagination.el>"u"}function CS(e={}){return e.scrollbar&&typeof e.scrollbar.el>"u"}function kS(e=""){const t=e.split(" ").map(r=>r.trim()).filter(r=>!!r),n=[];return t.forEach(r=>{n.indexOf(r)<0&&n.push(r)}),n.join(" ")}function nE(e=""){return e?e.includes("swiper-wrapper")?e:`swiper-wrapper ${e}`:"swiper-wrapper"}function rE({swiper:e,slides:t,passedParams:n,changedParams:r,nextEl:s,prevEl:i,scrollbarEl:a,paginationEl:c}){const u=r.filter(H=>H!=="children"&&H!=="direction"&&H!=="wrapperClass"),{params:f,pagination:p,navigation:g,scrollbar:y,virtual:v,thumbs:S}=e;let T,C,L,E,D,B,F,j;r.includes("thumbs")&&n.thumbs&&n.thumbs.swiper&&!n.thumbs.swiper.destroyed&&f.thumbs&&(!f.thumbs.swiper||f.thumbs.swiper.destroyed)&&(T=!0),r.includes("controller")&&n.controller&&n.controller.control&&f.controller&&!f.controller.control&&(C=!0),r.includes("pagination")&&n.pagination&&(n.pagination.el||c)&&(f.pagination||f.pagination===!1)&&p&&!p.el&&(L=!0),r.includes("scrollbar")&&n.scrollbar&&(n.scrollbar.el||a)&&(f.scrollbar||f.scrollbar===!1)&&y&&!y.el&&(E=!0),r.includes("navigation")&&n.navigation&&(n.navigation.prevEl||i)&&(n.navigation.nextEl||s)&&(f.navigation||f.navigation===!1)&&g&&!g.prevEl&&!g.nextEl&&(D=!0);const A=H=>{e[H]&&(e[H].destroy(),H==="navigation"?(e.isElement&&(e[H].prevEl.remove(),e[H].nextEl.remove()),f[H].prevEl=void 0,f[H].nextEl=void 0,e[H].prevEl=void 0,e[H].nextEl=void 0):(e.isElement&&e[H].el.remove(),f[H].el=void 0,e[H].el=void 0))};r.includes("loop")&&e.isElement&&(f.loop&&!n.loop?B=!0:!f.loop&&n.loop?F=!0:j=!0),u.forEach(H=>{if(nd(f[H])&&nd(n[H]))Object.assign(f[H],n[H]),(H==="navigation"||H==="pagination"||H==="scrollbar")&&"enabled"in n[H]&&!n[H].enabled&&A(H);else{const Q=n[H];(Q===!0||Q===!1)&&(H==="navigation"||H==="pagination"||H==="scrollbar")?Q===!1&&A(H):f[H]=n[H]}}),u.includes("controller")&&!C&&e.controller&&e.controller.control&&f.controller&&f.controller.control&&(e.controller.control=f.controller.control),r.includes("children")&&t&&v&&f.virtual.enabled?(v.slides=t,v.update(!0)):r.includes("virtual")&&v&&f.virtual.enabled&&(t&&(v.slides=t),v.update(!0)),r.includes("children")&&t&&f.loop&&(j=!0),T&&S.init()&&S.update(!0),C&&(e.controller.control=f.controller.control),L&&(e.isElement&&(!c||typeof c=="string")&&(c=document.createElement("div"),c.classList.add("swiper-pagination"),c.part.add("pagination"),e.el.appendChild(c)),c&&(f.pagination.el=c),p.init(),p.render(),p.update()),E&&(e.isElement&&(!a||typeof a=="string")&&(a=document.createElement("div"),a.classList.add("swiper-scrollbar"),a.part.add("scrollbar"),e.el.appendChild(a)),a&&(f.scrollbar.el=a),y.init(),y.updateSize(),y.setTranslate()),D&&(e.isElement&&((!s||typeof s=="string")&&(s=document.createElement("div"),s.classList.add("swiper-button-next"),g5(s,e.navigation.arrowSvg),s.part.add("button-next"),e.el.appendChild(s)),(!i||typeof i=="string")&&(i=document.createElement("div"),i.classList.add("swiper-button-prev"),g5(i,e.navigation.arrowSvg),i.part.add("button-prev"),e.el.appendChild(i))),s&&(f.navigation.nextEl=s),i&&(f.navigation.prevEl=i),g.init(),g.update()),r.includes("allowSlideNext")&&(e.allowSlideNext=n.allowSlideNext),r.includes("allowSlidePrev")&&(e.allowSlidePrev=n.allowSlidePrev),r.includes("direction")&&e.changeDirection(n.direction,!1),(B||j)&&e.loopDestroy(),(F||j)&&e.loopCreate(),e.update()}function sE(e={},t=!0){const n={on:{}},r={},s={};m0(n,Wb),n._emitClasses=!0,n.init=!1;const i={},a=SS.map(u=>u.replace(/_/,"")),c=Object.assign({},e);return Object.keys(c).forEach(u=>{typeof e[u]>"u"||(a.indexOf(u)>=0?nd(e[u])?(n[u]={},s[u]={},m0(n[u],e[u]),m0(s[u],e[u])):(n[u]=e[u],s[u]=e[u]):u.search(/on[A-Z]/)===0&&typeof e[u]=="function"?t?r[`${u[2].toLowerCase()}${u.substr(3)}`]=e[u]:n.on[`${u[2].toLowerCase()}${u.substr(3)}`]=e[u]:i[u]=e[u])}),["navigation","pagination","scrollbar"].forEach(u=>{n[u]===!0&&(n[u]={}),n[u]===!1&&delete n[u]}),{params:n,passedParams:s,rest:i,events:r}}function iE({el:e,nextEl:t,prevEl:n,paginationEl:r,scrollbarEl:s,swiper:i},a){AS(a)&&t&&n&&(i.params.navigation.nextEl=t,i.originalParams.navigation.nextEl=t,i.params.navigation.prevEl=n,i.originalParams.navigation.prevEl=n),TS(a)&&r&&(i.params.pagination.el=r,i.originalParams.pagination.el=r),CS(a)&&s&&(i.params.scrollbar.el=s,i.originalParams.scrollbar.el=s),i.init(e)}function oE(e,t,n,r,s){const i=[];if(!t)return i;const a=u=>{i.indexOf(u)<0&&i.push(u)};if(n&&r){const u=r.map(s),f=n.map(s);u.join("")!==f.join("")&&a("children"),r.length!==n.length&&a("children")}return SS.filter(u=>u[0]==="_").map(u=>u.replace(/_/,"")).forEach(u=>{if(u in e&&u in t)if(nd(e[u])&&nd(t[u])){const f=Object.keys(e[u]),p=Object.keys(t[u]);f.length!==p.length?a(u):(f.forEach(g=>{e[u][g]!==t[u][g]&&a(u)}),p.forEach(g=>{e[u][g]!==t[u][g]&&a(u)}))}else e[u]!==t[u]&&a(u)}),i}const aE=e=>{!e||e.destroyed||!e.params.virtual||e.params.virtual&&!e.params.virtual.enabled||(e.updateSlides(),e.updateProgress(),e.updateSlidesClasses(),e.emit("_virtualUpdated"),e.parallax&&e.params.parallax&&e.params.parallax.enabled&&e.parallax.setTranslate())};function Xm(){return Xm=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Xm.apply(this,arguments)}function _S(e){return e.type&&e.type.displayName&&e.type.displayName.includes("SwiperSlide")}function LS(e){const t=[];return M.Children.toArray(e).forEach(n=>{_S(n)?t.push(n):n.props&&n.props.children&&LS(n.props.children).forEach(r=>t.push(r))}),t}function lE(e){const t=[],n={"container-start":[],"container-end":[],"wrapper-start":[],"wrapper-end":[]};return M.Children.toArray(e).forEach(r=>{if(_S(r))t.push(r);else if(r.props&&r.props.slot&&n[r.props.slot])n[r.props.slot].push(r);else if(r.props&&r.props.children){const s=LS(r.props.children);s.length>0?s.forEach(i=>t.push(i)):n["container-end"].push(r)}else n["container-end"].push(r)}),{slides:t,slots:n}}function cE(e,t,n){if(!n)return null;const r=p=>{let g=p;return p<0?g=t.length+p:g>=t.length&&(g=g-t.length),g},s=e.isHorizontal()?{[e.rtlTranslate?"right":"left"]:`${n.offset}px`}:{top:`${n.offset}px`},{from:i,to:a}=n,c=e.params.loop?-t.length:0,u=e.params.loop?t.length*2:t.length,f=[];for(let p=c;p<u;p+=1)p>=i&&p<=a&&f.push(t[r(p)]);return f.map((p,g)=>M.cloneElement(p,{swiper:e,style:s,key:p.props.virtualIndex||p.key||`slide-${g}`}))}function ih(e,t){return typeof window>"u"?x.useEffect(e,t):x.useLayoutEffect(e,t)}const w5=x.createContext(null),uE=x.createContext(null),Qh=x.forwardRef(({className:e,tag:t="div",wrapperTag:n="div",children:r,onSwiper:s,...i}={},a)=>{let c=!1;const[u,f]=x.useState("swiper"),[p,g]=x.useState(null),[y,v]=x.useState(!1),S=x.useRef(!1),T=x.useRef(null),C=x.useRef(null),L=x.useRef(null),E=x.useRef(null),D=x.useRef(null),B=x.useRef(null),F=x.useRef(null),j=x.useRef(null),{params:A,passedParams:H,rest:Q,events:K}=sE(i),{slides:W,slots:de}=lE(r),X=()=>{v(!y)};Object.assign(A.on,{_containerClasses(V,z){f(z)}});const pe=()=>{Object.assign(A.on,K),c=!0;const V={...A};if(delete V.wrapperClass,C.current=new Ly(V),C.current.virtual&&C.current.params.virtual.enabled){C.current.virtual.slides=W;const z={cache:!1,slides:W,renderExternal:g,renderExternalUpdate:!1};m0(C.current.params.virtual,z),m0(C.current.originalParams.virtual,z)}};T.current||pe(),C.current&&C.current.on("_beforeBreakpoint",X);const ve=()=>{c||!K||!C.current||Object.keys(K).forEach(V=>{C.current.on(V,K[V])})},Ae=()=>{!K||!C.current||Object.keys(K).forEach(V=>{C.current.off(V,K[V])})};x.useEffect(()=>()=>{C.current&&C.current.off("_beforeBreakpoint",X)}),x.useEffect(()=>{!S.current&&C.current&&(C.current.emitSlidesClasses(),S.current=!0)}),ih(()=>{if(a&&(a.current=T.current),!!T.current)return C.current.destroyed&&pe(),iE({el:T.current,nextEl:D.current,prevEl:B.current,paginationEl:F.current,scrollbarEl:j.current,swiper:C.current},A),s&&!C.current.destroyed&&s(C.current),()=>{C.current&&!C.current.destroyed&&C.current.destroy(!0,!1)}},[]),ih(()=>{ve();const V=oE(H,L.current,W,E.current,z=>z.key);return L.current=H,E.current=W,V.length&&C.current&&!C.current.destroyed&&rE({swiper:C.current,slides:W,passedParams:H,changedParams:V,nextEl:D.current,prevEl:B.current,scrollbarEl:j.current,paginationEl:F.current}),()=>{Ae()}}),ih(()=>{aE(C.current)},[p]);function ie(){return A.virtual?cE(C.current,W,p):W.map((V,z)=>M.cloneElement(V,{swiper:C.current,swiperSlideIndex:z}))}return M.createElement(t,Xm({ref:T,className:kS(`${u}${e?` ${e}`:""}`)},Q),M.createElement(uE.Provider,{value:C.current},de["container-start"],M.createElement(n,{className:nE(A.wrapperClass)},de["wrapper-start"],ie(),de["wrapper-end"]),AS(A)&&M.createElement(M.Fragment,null,M.createElement("div",{ref:B,className:"swiper-button-prev"}),M.createElement("div",{ref:D,className:"swiper-button-next"})),CS(A)&&M.createElement("div",{ref:j,className:"swiper-scrollbar"}),TS(A)&&M.createElement("div",{ref:F,className:"swiper-pagination"}),de["container-end"]))});Qh.displayName="Swiper";const rd=x.forwardRef(({tag:e="div",children:t,className:n="",swiper:r,zoom:s,lazy:i,virtualIndex:a,swiperSlideIndex:c,...u}={},f)=>{const p=x.useRef(null),[g,y]=x.useState("swiper-slide"),[v,S]=x.useState(!1);function T(D,B,F){B===p.current&&y(F)}ih(()=>{if(typeof c<"u"&&(p.current.swiperSlideIndex=c),f&&(f.current=p.current),!(!p.current||!r)){if(r.destroyed){g!=="swiper-slide"&&y("swiper-slide");return}return r.on("_slideClass",T),()=>{r&&r.off("_slideClass",T)}}}),ih(()=>{r&&p.current&&!r.destroyed&&y(r.getSlideClasses(p.current))},[r]);const C={isActive:g.indexOf("swiper-slide-active")>=0,isVisible:g.indexOf("swiper-slide-visible")>=0,isFullyVisible:g.indexOf("swiper-slide-fully-visible")>=0,isPrev:g.indexOf("swiper-slide-prev")>=0,isNext:g.indexOf("swiper-slide-next")>=0},L=()=>typeof t=="function"?t(C):t,E=()=>{S(!0)};return M.createElement(e,Xm({ref:p,className:kS(`${g}${n?` ${n}`:""}`),"data-swiper-slide-index":a,onLoad:E},u),s&&M.createElement(w5.Provider,{value:C},M.createElement("div",{className:"swiper-zoom-container","data-swiper-zoom":typeof s=="number"?s:void 0},L(),i&&!v&&M.createElement("div",{className:"swiper-lazy-preloader",ref:D=>{D&&(D.lazyPreloaderManaged=!0)}}))),!s&&M.createElement(w5.Provider,{value:C},L(),i&&!v&&M.createElement("div",{className:"swiper-lazy-preloader",ref:D=>{D&&(D.lazyPreloaderManaged=!0)}})))});rd.displayName="SwiperSlide";const ho=[];for(let e=0;e<256;++e)ho.push((e+256).toString(16).slice(1));function dE(e,t=0){return(ho[e[t+0]]+ho[e[t+1]]+ho[e[t+2]]+ho[e[t+3]]+"-"+ho[e[t+4]]+ho[e[t+5]]+"-"+ho[e[t+6]]+ho[e[t+7]]+"-"+ho[e[t+8]]+ho[e[t+9]]+"-"+ho[e[t+10]]+ho[e[t+11]]+ho[e[t+12]]+ho[e[t+13]]+ho[e[t+14]]+ho[e[t+15]]).toLowerCase()}let Z1;const fE=new Uint8Array(16);function hE(){if(!Z1){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Z1=crypto.getRandomValues.bind(crypto)}return Z1(fE)}const pE=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),S5={randomUUID:pE};function mE(e,t,n){e=e||{};const r=e.random??e.rng?.()??hE();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,dE(r)}function gE(e,t,n){return S5.randomUUID&&!e?S5.randomUUID():mE(e)}const xE={},A5=e=>{let t;const n=new Set,r=(p,g)=>{const y=typeof p=="function"?p(t):p;if(!Object.is(y,t)){const v=t;t=g??(typeof y!="object"||y===null)?y:Object.assign({},t,y),n.forEach(S=>S(t,v))}},s=()=>t,u={setState:r,getState:s,getInitialState:()=>f,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{(xE?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},f=t=e(r,s,u);return u},bE=e=>e?A5(e):A5;var J1={exports:{}},ex={},tx={exports:{}},nx={};var T5;function yE(){if(T5)return nx;T5=1;var e=Pg();function t(g,y){return g===y&&(g!==0||1/g===1/y)||g!==g&&y!==y}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,s=e.useEffect,i=e.useLayoutEffect,a=e.useDebugValue;function c(g,y){var v=y(),S=r({inst:{value:v,getSnapshot:y}}),T=S[0].inst,C=S[1];return i(function(){T.value=v,T.getSnapshot=y,u(T)&&C({inst:T})},[g,v,y]),s(function(){return u(T)&&C({inst:T}),g(function(){u(T)&&C({inst:T})})},[g]),a(v),v}function u(g){var y=g.getSnapshot;g=g.value;try{var v=y();return!n(g,v)}catch{return!0}}function f(g,y){return y()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:c;return nx.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,nx}var C5;function vE(){return C5||(C5=1,tx.exports=yE()),tx.exports}var k5;function wE(){if(k5)return ex;k5=1;var e=Pg(),t=vE();function n(f,p){return f===p&&(f!==0||1/f===1/p)||f!==f&&p!==p}var r=typeof Object.is=="function"?Object.is:n,s=t.useSyncExternalStore,i=e.useRef,a=e.useEffect,c=e.useMemo,u=e.useDebugValue;return ex.useSyncExternalStoreWithSelector=function(f,p,g,y,v){var S=i(null);if(S.current===null){var T={hasValue:!1,value:null};S.current=T}else T=S.current;S=c(function(){function L(j){if(!E){if(E=!0,D=j,j=y(j),v!==void 0&&T.hasValue){var A=T.value;if(v(A,j))return B=A}return B=j}if(A=B,r(D,j))return A;var H=y(j);return v!==void 0&&v(A,H)?(D=j,A):(D=j,B=H)}var E=!1,D,B,F=g===void 0?null:g;return[function(){return L(p())},F===null?void 0:function(){return L(F())}]},[p,g,y,v]);var C=s(f,S[0],S[1]);return a(function(){T.hasValue=!0,T.value=C},[C]),u(C),C},ex}var _5;function SE(){return _5||(_5=1,J1.exports=wE()),J1.exports}var AE=SE();const TE=hS(AE),ES={},{useDebugValue:CE}=M,{useSyncExternalStoreWithSelector:kE}=TE;let L5=!1;const _E=e=>e;function LE(e,t=_E,n){(ES?"production":void 0)!=="production"&&n&&!L5&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),L5=!0);const r=kE(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return CE(r),r}const E5=e=>{(ES?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?bE(e):e,n=(r,s)=>LE(t,r,s);return Object.assign(n,t),n},IS=e=>e?E5(e):E5,bh="auth:unauthorized";let Wu=null;class Va extends Error{constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}async function EE(){const e=await fetch("/api/terminal/update");if(!e.ok)throw new Va("Failed to load update state",e.status);return e.json()}async function IE(){const e=await dr(),t=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Va("Failed to check for updates",t.status);return t.json()}async function RE(){const e=await dr(),t=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to restart Termdock"}));throw new Va(n.error||"Failed to restart Termdock",t.status)}return t.json()}async function NE(){const e=await fetch("/api/terminal/quota");if(!e.ok)throw new Va("Failed to fetch quota",e.status);return e.json()}async function ME(){const e=await dr(),t=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Va("Failed to refresh quota",t.status);return t.json()}const wu=8e3,DE=32e3,hc=1e4,g0=45e3,jE=8e3,PE=8e3,BE=15e3,FE=1e4,T0=5e3;let OE=0;const Tm=[];let rx=!1;function eu(e,t={}){if(typeof window>"u")return;const n=JSON.stringify({level:e==="error"||e==="timeout_or_abort"||e==="response_body_timeout"||e==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${e}`,data:{seq:++OE,ts:Date.now(),...t}});Tm.push(n),QE()}async function QE(){if(!rx){rx=!0;try{for(;Tm.length>0;){const e=Tm[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),Tm.shift()}catch{break}}}finally{rx=!1}}}function $E(e,t,n){const r=new AbortController;let s=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},t);const i=()=>r.abort(e?.reason);return e&&(e.aborted?i():e.addEventListener("abort",i,{once:!0})),{signal:r.signal,cleanup:()=>{s&&(clearTimeout(s),s=null),e?.removeEventListener("abort",i)}}}async function _s(e,t,n,r){const{signal:s,cleanup:i}=$E(t?.signal??void 0,n,r);try{return await fetch(e,{...t,signal:s})}catch(a){throw a instanceof DOMException&&a.name==="TimeoutError"?new Error(r):a}finally{i()}}async function RS(e,t,n){let r=null;const s=new Promise((i,a)=>{r=setTimeout(()=>a(new Error(n)),t)});try{return await Promise.race([e.text(),s])}finally{r&&clearTimeout(r)}}async function C0(e,t,n){const r=await RS(e,t,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const e=window.fetch.bind(window);window.fetch=async(...t)=>{const n=await e(...t);if(n.status===401){Wu=null;try{window.dispatchEvent(new CustomEvent(bh))}catch{}}return n}}async function dr(){if(Wu)return Wu;const e=await _s("/api/csrf-token",void 0,jE,"CSRF token request timed out");if(!e.ok)throw new Error("Failed to get CSRF token");const t=await C0(e,T0,"CSRF token response timed out");if(!t.csrfToken)throw new Error("Invalid CSRF token response");return Wu=t.csrfToken,Wu}function NS(){Wu=null}const HE=2e4,I5=8e3,UE=1500,wo=new Map,zE=24,GE=40,WE=40;function VE(e){return e.retryState.retryCount>=2||e.pendingInputs.length>=WE?"congested":e.retryState.retryCount>=1||e.pendingInputs.length>=8?"degraded":"good"}function R5(e){if(e.pendingInputs.length===0||e.ws.readyState!==WebSocket.OPEN)return;const t=e.pendingInputs.splice(0);for(const n of t)try{e.ws.send(JSON.stringify({type:"input",data:n}))}catch{}}function MS(e){if(e.ws.readyState!==WebSocket.OPEN)return;const t=VE(e);if(t==="good"){R5(e);return}if(e.inputFlushTimer)return;const n=t==="congested"?GE:zE;e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,R5(e)},n)}const oh=new Map;function qE(e,t,n,r){const s=oh.get(e);s&&(oh.delete(e),t?s.resolve({success:!0,layout:n}):s.reject(new Error(r||"Tmux action failed")))}function KE(e,t){const r=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${e}/ws`;return t>0?`${r}?since=${t}`:r}const N5=new Map;async function YE(e){const t=await dr(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({cols:e.cols||80,rows:e.rows||24,mode:e.mode||"shell",tmuxSessionName:e.tmuxSessionName,cwd:e.cwd,termType:e.termType})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(r.error||"Failed to create terminal session")}return n.json()}function XE(e,t,n,r={}){const{maxRetries:s=10,initialRetryDelay:i=1e3,maxRetryDelay:a=2e4,connectionTimeout:c=15e3}=r,u={maxRetries:s,initialDelayMs:i,maxDelayMs:a,connectionTimeoutMs:c,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let f=null,p=N5.get(e)??0;N5.delete(e);const g=[];let y=!1,v=null;const S=new WeakSet,T=()=>{u.retryTimeout&&(clearTimeout(u.retryTimeout),u.retryTimeout=null),u.connectionTimeoutId&&(clearTimeout(u.connectionTimeoutId),u.connectionTimeoutId=null),v&&(clearTimeout(v),v=null)},C=F=>{F.heartbeatTimer&&(clearInterval(F.heartbeatTimer),F.heartbeatTimer=null),F.pongTimer&&(clearTimeout(F.pongTimer),F.pongTimer=null),F.inputFlushTimer&&(clearTimeout(F.inputFlushTimer),F.inputFlushTimer=null)},L=F=>{C(F),F.heartbeatTimer=setInterval(()=>{if(F.ws.readyState===WebSocket.OPEN){try{F.ws.send(JSON.stringify({type:"ping"}))}catch{}F.pongTimer&&clearTimeout(F.pongTimer),F.pongTimer=setTimeout(()=>{if(Date.now()-F.lastInboundAt>=I5)try{F.ws.close()}catch{}},I5)}},HE)},E=()=>{if(u.isClosed=!0,T(),f){C(f),wo.delete(e);try{f.ws.close()}catch{}f=null}},D=()=>{if(u.isClosed)return;if(f){S.add(f.ws),C(f);try{f.ws.close()}catch{}}const F=KE(e,p),j=new WebSocket(F);y=!1,u.connectionTimeoutId=setTimeout(()=>{j.readyState!==WebSocket.OPEN&&(y=!0,j.close(),B(new Error("WebSocket connection timeout"),!1))},c);const A={ws:j,onEvent:t,onError:n,reconnectNow:()=>{if(!u.isClosed&&(u.isSuspended=!1,!v)){if(T(),f){S.add(f.ws),C(f);try{f.ws.close()}catch{}}t({type:"reconnecting",attempt:Math.min(u.retryCount+1,s),maxAttempts:s}),u.retryCount=Math.min(u.retryCount+1,s),y=!0,v=setTimeout(()=>{v=null,y=!1,D()},0)}},suspendReconnect:()=>{u.isClosed||(u.isSuspended=!0,u.retryTimeout&&(clearTimeout(u.retryTimeout),u.retryTimeout=null))},retryState:u,lastSeq:p,pendingInputs:g,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};j.onopen=()=>{T(),u.retryCount=0,A.lastInboundAt=Date.now(),A.inboundSequence+=1,L(A),MS(A)},j.onmessage=H=>{A.lastInboundAt=Date.now(),A.inboundSequence+=1;try{const Q=JSON.parse(H.data);if(Q.type==="pong"){A.pongTimer&&(clearTimeout(A.pongTimer),A.pongTimer=null);return}if(Q.type==="tmux-result"&&Q.reqId){qE(Q.reqId,Q.success!==!1,Q.layout,Q.error);return}if(Q.type==="tmux-layout"&&Q.layout){t({type:"tmux-layout",layout:Q.layout});return}if(Q.type==="tmux-screen-sync"&&Array.isArray(Q.chunks)){t({type:"tmux-screen-sync",chunks:Q.chunks.filter(W=>typeof W=="string"),cols:typeof Q.cols=="number"?Q.cols:void 0,rows:typeof Q.rows=="number"?Q.rows:void 0,generation:typeof Q.generation=="number"?Q.generation:void 0});return}if(Q.type==="active-program"){t({type:"active-program",activeProgram:Q.activeProgram,activeProgramRaw:Q.activeProgramRaw,activeProgramSource:Q.activeProgramSource});return}if(Q.type==="cwd"){t({type:"cwd",cwd:Q.cwd});return}if(Q.type==="agent-status"){t({type:"agent-status",agentStatus:Q.agentStatus??null,agentIndicator:Q.agentIndicator??null,agentStatusDetail:Q.agentStatusDetail??null,agent:Q.agent??null,agentMessage:Q.agentMessage??null,agentNativeSessionId:Q.agentNativeSessionId??null,agentResumeRecovered:Q.agentResumeRecovered===!0,agentRich:Q.agentRich===!0,agentActivity:typeof Q.agentActivity=="number"?Q.agentActivity:0,agentCwd:Q.agentCwd??null,reviewed:typeof Q.reviewed=="boolean"?Q.reviewed:null});return}if(Q.type==="git-status"){t({type:"git-status",gitStatus:Q.gitStatus??null});return}if(Q.type==="quota-status"&&Array.isArray(Q.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:Q.providers}));return}if(Q.type==="focus-mode"){t({type:"focus-mode",focusTrackingRequested:Q.focusTrackingRequested===!0});return}if(Q.type==="resize-ack"){t({type:"resize-ack",seq:typeof Q.seq=="number"?Q.seq:void 0,cols:typeof Q.cols=="number"?Q.cols:void 0,rows:typeof Q.rows=="number"?Q.rows:void 0,ok:Q.ok!==!1,error:typeof Q.error=="string"?Q.error:void 0});return}if(Q.type==="pty-size"){t({type:"pty-size",cols:typeof Q.cols=="number"?Q.cols:void 0,rows:typeof Q.rows=="number"?Q.rows:void 0,source:typeof Q.source=="string"?Q.source:void 0});return}if(Q.type==="shell-title"){t({type:"shell-title",title:typeof Q.title=="string"?Q.title:""});return}if(Q.type==="prompt-state"){t({type:"prompt-state",state:Q.state==="running"?"running":"idle",exitCode:typeof Q.exitCode=="number"?Q.exitCode:void 0});return}const K=Q;if(K.type==="connected"){typeof K.replayLastSeq=="number"&&K.replayLastSeq>0&&(p=K.replayLastSeq,A.lastSeq=p),t(K);return}if(K.type==="exit"){E(),t(K);return}t(K),K.type==="data"&&typeof K.seq=="number"&&Number.isFinite(K.seq)&&K.seq>p&&(p=K.seq,A.lastSeq=p)}catch(Q){n?.(Q,!1)}},j.onerror=()=>{S.has(j)||(T(),C(A),y||(y=!0,B(new Error("WebSocket connection error"),!1)))},j.onclose=H=>{if(!S.has(j)&&(T(),C(A),!u.isClosed&&!y)){if(y=!0,H.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:H.code,reason:H.reason,stack:new Error().stack}),B(new Error("Session not found on server"),!0);return}if(H.code===4003||H.code===4401){try{window.dispatchEvent(new CustomEvent(bh))}catch{}B(new Error("Authentication required"),!0);return}B(new Error("WebSocket connection closed"),!1)}},f=A,wo.set(e,f)},B=(F,j)=>{if(!u.isClosed)if(j)n?.(F,!0),E();else{u.retryCount=Math.min(u.retryCount+1,Math.max(1,s));const A=Math.min(i*Math.pow(2,u.retryCount-1),a);if(t({type:"reconnecting",attempt:u.retryCount,maxAttempts:s}),u.isSuspended)return;u.retryTimeout=setTimeout(()=>{u.isClosed||D()},A)}};return D(),E}async function DS(e,t){const n=wo.get(e);if(n){if(n.ws.readyState===WebSocket.OPEN){n.pendingInputs.push(t),MS(n);return}if(n.ws.readyState===WebSocket.CONNECTING){n.pendingInputs.push(t);return}}const r=await dr(),s=await fetch(`/api/terminal/${e}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:t});if(!s.ok){const i=await s.json().catch(()=>({error:"Failed to send input"}));throw new Error(i.error||"Failed to send terminal input")}}function ZE(e,t){const n=wo.get(e);if(!n)return!1;if(n.retryState.isSuspended=!1,n.ws.readyState!==WebSocket.OPEN)return n.reconnectNow(),!0;const r=n.inboundSequence;try{n.ws.send(JSON.stringify({type:"ping"}))}catch{}return setTimeout(()=>{wo.get(e)!==n||n.retryState.isClosed||(n.inboundSequence<=r?n.reconnectNow():t?.())},UE),!0}function JE(e){const t=wo.get(e);return t?(t.reconnectNow(),!0):!1}function M5(){for(const e of wo.values())e.suspendReconnect()}function D5(e,t,n){const r=wo.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:t,reason:n}))}catch{}}function j5(e,t,n){const r=wo.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:t,reason:n}))}catch{}}function P5(e){const t=wo.get(e);if(!(!t||t.ws.readyState!==WebSocket.OPEN))try{t.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function B5(e,t,n){const r=wo.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:t,reason:n}))}catch{}}async function eI(e,t,n,r){const s=wo.get(e);if(s&&s.ws.readyState===WebSocket.OPEN)try{s.ws.send(JSON.stringify({type:"resize",cols:t,rows:n,seq:r}));return}catch{}const i=await dr(),a=await fetch(`/api/terminal/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":i},body:JSON.stringify({cols:t,rows:n,seq:r})});if(!a.ok){const u=await a.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(u.error||"Failed to resize terminal")}const c=await a.json().catch(()=>({success:!0}));if(c?.success===!1||c?.ok===!1)throw new Error(c?.error||"Failed to resize terminal")}async function tI(e,t){const n=wo.get(e);if(n&&n.ws.readyState===WebSocket.OPEN)return t.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...t})),{success:!0}):new Promise((i,a)=>{const c=Math.random().toString(36).substring(7);oh.set(c,{resolve:i,reject:a}),n.ws.send(JSON.stringify({type:"tmux",reqId:c,...t})),setTimeout(()=>{oh.has(c)&&(oh.delete(c),a(new Error("Tmux action timed out")))},3e4)});const r=await dr(),s=await fetch(`/api/terminal/${e}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)});if(!s.ok){const i=await s.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Error(i.error||"Failed to execute tmux action")}return s.json()}async function jS(e){const t=wo.get(e);if(t){t.retryState.isClosed=!0;try{t.ws.close()}catch{}wo.delete(e)}const n=await dr(),r=await fetch(`/api/terminal/${e}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(r.status!==404&&!r.ok){const s=await r.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(s.error||"Failed to close terminal")}}async function nI(e,t){const n=wo.get(e);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}wo.delete(e)}const r=await dr(),s=await fetch(`/api/terminal/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...t.cwd?{cwd:t.cwd}:{},cols:t.cols??80,rows:t.rows??24,mode:t.mode,tmuxSessionName:t.tmuxSessionName})});if(!s.ok){const i=await s.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(i.error||"Failed to restart terminal session")}return s.json()}async function rI(e){const t=await _s(`/api/terminal/${e}/health`,{method:"GET"},PE,"Terminal health check timed out");if(!t.ok){if(t.status===404)return{healthy:!1,sessionId:e};const n=await C0(t,T0,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return C0(t,T0,"Terminal health response timed out")}async function sI(e){const t=await dr(),n=await _s("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)},FE,"Terminal force-kill request timed out");if(!n.ok){const r=await C0(n,T0,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}}async function Vb(){const e=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const t=await e.json();return Array.isArray(t.sessions)?t.sessions:[]}async function qb(){const e=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(t.error||"Failed to get tmux status")}return e.json()}async function PS(e){const t=e.trim();if(!t)throw new Error("tmux session name is required");const n=await dr(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(!r.ok){const i=await r.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(i.error||"Failed to kill tmux session")}const s=await r.json();return{cleanedSessions:Array.isArray(s.cleanedSessions)?s.cleanedSessions:[],alreadyGone:!!s.alreadyGone}}async function iI(){const e=await dr(),t=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":e}}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Va(n.error||"Failed to restore tmux Agent sessions",t.status);return n}async function oI(){const e=await dr(),t=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Va("Failed to dismiss tmux recovery",t.status)}const Np=new Map;function aI(e){return JSON.stringify({preferredFrontendSessionId:e.preferredFrontendSessionId??null,mode:e.mode??null,tmuxSessionName:e.tmuxSessionName??null,cwd:e.cwd??null,termType:e.termType??null,createIfEmpty:e.createIfEmpty===!0,requireExisting:e.requireExisting===!0})}async function lI(){const e=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(t.error||"Failed to load session inventory")}return e.json()}async function BS(e){const t=aI(e),n=Np.get(t);if(n)return n;const r=await dr(),s=_s("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)},BE,"Terminal session open request timed out").then(async i=>{if(!i.ok){const a=await C0(i,T0,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new Va(a.error||"Failed to open session",i.status,typeof a.code=="string"?a.code:void 0)}return C0(i,T0,"Terminal session open response timed out")}).finally(()=>{Np.get(t)===s&&Np.delete(t)});return Np.set(t,s),s}async function Cm(e,t){const n=await dr(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(t)});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to update session"}));throw new Error(s.error||"Failed to update session")}return r.json()}async function cI(e){const t=await dr(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({sessionIds:e})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(r.error||"Failed to reorder sessions")}return n.json()}async function uI(e){const t=await dr(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to remove session"}));throw new Error(r.error||"Failed to remove session")}}async function dI(){const e=await dr(),t=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function F5(){const e=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(t.error||"Failed to load toolbar presets")}return e.json()}async function fI(e){const t=await dr(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save toolbar presets"})),s=new Error(r.error||"Failed to save toolbar presets");throw s.current=r.current,s.code=r.code,s}return n.json()}async function k0(){const e=await fetch("/api/terminal/settings",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load settings"}));throw new Error(t.error||"Failed to load settings")}return e.json()}async function bo(e){const t=await dr(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to update settings"}));throw new Error(r.error||"Failed to update settings")}return n.json()}async function gf(e=!1){const t=await fetch(`/api/terminal/auto-title/catalog${e?"?refresh=1":""}`);if(!t.ok)throw new Error("Failed to discover title models");const n=await t.json();return Array.isArray(n?.namers)?n.namers:[]}async function hI(){const e=await fetch("/api/terminal/context-draft",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(t.error||"Failed to load context draft")}return e.json()}async function pI(e,t){const n=await dr(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:e,origin:t})});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(s.error||"Failed to update context draft")}return r.json()}async function mI(){const e=await fetch("/api/auth/status");if(!e.ok)throw new Error("Failed to query auth status");return e.json()}async function gI(e){const t=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:e})});if(t.ok)return NS(),{ok:!0};const n=await t.json().catch(()=>null);return t.status===429?{ok:!1,rateLimited:!0,retryAfterMs:typeof n?.retryAfterMs=="number"?n.retryAfterMs:void 0,error:n?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,error:n?.error||"Login failed"}}async function xI(){const e=await dr();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":e}}),NS()}async function FS(){const e=await fetch("/api/terminal/agent-launchers");if(!e.ok)throw new Error("Failed to detect agent launchers");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function bI(){const e=await fetch("/api/terminal/agent-hooks");if(!e.ok)throw new Error("Failed to get agent hooks");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function yI(e){const t=await dr(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to install agent hooks");return{summary:r.summary??"Installed",devMode:r.devMode===!0}}async function vI(e){const t=await dr(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class Ey extends Error{constructor(t,n,r){super(t),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function wI(){const e=await fetch("/api/terminal/agent-plugins");if(!e.ok)throw new Error("Failed to get agent plugins");return await e.json()}async function SI(e){const t=await dr(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ey(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function AI(e){const t=await dr(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({source:e})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ey(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function TI(e){const t=await dr(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function CI(e){const t=await dr(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function kI(e){const t=await dr(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function _I(e){const t=await dr(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function LI(e){const t=await dr(),n=await fetch(`/api/terminal/${encodeURIComponent(e)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Va(r.error||"Failed to resume agent session",n.status,typeof r.code=="string"?r.code:void 0);return{command:r.command??""}}async function O5(){const e=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!e.ok)throw new Error("Failed to load Agent resume history");const t=await e.json().catch(()=>({entries:[]}));return Array.isArray(t.entries)?t.entries:[]}async function OS(e){const t=await dr(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Va(r.error||"Failed to prepare Agent session resume",n.status,typeof r.code=="string"?r.code:void 0);return r}async function EI(e){const t=await dr(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function Qd(e){const t=await dr(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(r.error||"Failed to update program rules")}return n.json()}async function II(){const e=await dr(),t=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program rules");return t.json()}async function RI(){const e=await fetch("/api/terminal/program-detection");if(!e.ok)throw new Error("Failed to get program detection config");return e.json()}async function Q5(e){const t=await dr(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function NI(){const e=await dr(),t=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program detection config");return t.json()}const MI={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".bmp":"image/bmp",".ico":"image/x-icon",".svg":"image/svg+xml",".heic":"image/heic",".heif":"image/heif"};function Iy(e){const t=e.lastIndexOf(".");return t<0?null:MI[e.slice(t).toLowerCase()]??null}function Ry(e){return Iy(e)!==null}function QS(e){const t=Iy(e);return t==="image/heic"||t==="image/heif"}const DI={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function $S(e){const t=e.lastIndexOf(".");return t<0?null:DI[e.slice(t).toLowerCase()]??null}function HS(e){return $S(e)!==null}function jI(e){return`/api/terminal/fs/video?path=${encodeURIComponent(e)}&action=view_file`}const PI=[".stl",".glb",".gltf"];function US(e){const t=e.lastIndexOf(".");if(t<0)return null;const n=e.slice(t).toLowerCase();return PI.includes(n)?n:null}function zS(e){return US(e)!==null}function GS(e){const t=e.toLowerCase();return t.endsWith(".kicad_sch")?".kicad_sch":t.endsWith(".kicad_pcb")?".kicad_pcb":null}function BI(e){return GS(e)!==null}function FI(e){return GS(e)===".kicad_pcb"?"pcb-front":"schematic"}const OI=[".html",".htm"];function xf(e){const t=e.lastIndexOf(".");if(t<0)return!1;const n=e.slice(t).toLowerCase();return OI.includes(n)}function QI(e){return`/api/terminal/fs/preview/${e.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const $I={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function Ny(e,t,n,r="list_directory",s,i="name"){const a=new URLSearchParams({path:e});n&&a.set("showHidden","true"),i!=="name"&&a.set("sort",i),a.set("action",r),s&&a.set("requestSlotId",s);const c=await _s(`/api/terminal/fs/list?${a}`,{signal:t},wu,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!c.ok){const u=await c.json().catch(()=>({error:"Failed to list directory"}));throw new Error(u.error||"Failed to list directory")}return c.json()}async function HI(e,t,n,r,s,i="name",a,c={}){const u=new URLSearchParams({path:e,query:t,stream:"true"});s&&u.set("showHidden","true"),i==="content"&&u.set("mode","content"),a&&u.set("requestSlotId",a);for(const S of c.excludePatterns??[])u.append("exclude",S);c.caseSensitive&&u.set("caseSensitive","true"),c.wholeWord&&u.set("wholeWord","true"),c.regex&&u.set("regex","true");const f=await fetch(`/api/terminal/fs/search?${u}`,{signal:r});if(!f.ok||!f.body){const S=await f.json().catch(()=>({error:"Failed to search files"}));throw new Error(S.error||"Failed to search files")}const p=f.body.getReader(),g=new TextDecoder;let y="";const v=S=>{if(!S.trim())return;const T=JSON.parse(S);if(T.type==="meta")n({path:T.path,query:T.query,engine:T.engine,mode:T.mode,limited:T.limited});else if(T.type==="batch")n({entries:T.entries??[]});else if(T.type==="content-batch")n({contentEntries:T.contentEntries??[]});else{if(T.type==="error")throw new Error(T.message||"Search failed");T.type==="done"&&n({total:T.total,truncated:T.truncated,limited:T.limited,engine:T.engine,mode:T.mode,done:!0})}};for(;;){const{value:S,done:T}=await p.read();if(T)break;y+=g.decode(S,{stream:!0});let C=y.indexOf(`
|
|
3
3
|
`);for(;C>=0;)v(y.slice(0,C)),y=y.slice(C+1),C=y.indexOf(`
|
|
4
4
|
`)}y+=g.decode(),v(y)}async function UI(e,t,n){const r=new URLSearchParams;r.set("roots",e.join("|"));const s=await fetch(`/api/terminal/fs/watch?${r}`,{signal:n});if(!s.ok||!s.body){const p=await s.json().catch(()=>({error:"Failed to watch files"}));throw new Error(p.error||"Failed to watch files")}const i=s.body.getReader(),a=new TextDecoder;let c="",u=null;const f=p=>{if(!p.trim())return;const g=JSON.parse(p);if(g.type==="events"&&g.events?.length){t(g.events);const y=g.events.find(v=>v.type==="rescan-required"&&v.reason!=="event-storm"&&v.reason!=="reconnected");y?.reason&&(u=y.reason)}};for(;;){const{value:p,done:g}=await i.read();if(g)break;c+=a.decode(p,{stream:!0});let y=c.indexOf(`
|
|
@@ -75,7 +75,7 @@ ${t.trim()}`:""].filter(Boolean).join(`
|
|
|
75
75
|
`)}async function TO(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{return document.execCommand("copy")}catch{return!1}finally{t.remove()}}function CO({error:e,componentStack:t}){const{t:n}=qn(),[r,s]=M.useState("idle"),i=async()=>{const a=AO(e,t,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});s(await TO(a)?"copied":"failed")};return o.jsx("div",{className:"flex h-full items-center justify-center p-4",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[o.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:o.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e?.message||n("errorBoundary.unexpected")})]}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[o.jsx("button",{type:"button",onClick:()=>{i()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:n("errorBoundary.retry")})]})]})})}let eA=class extends M.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(t){return{hasError:!0,error:t,componentStack:""}}componentDidCatch(t,n){console.error("Terminal error caught by boundary:",t,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:o.jsx(CO,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}};function b2(e,t){return e.label.trim().length>0?e.label:`Key ${t+1}`}const Zf=15;function kO(){return tA.map(e=>e.id)}const tA=[{id:"default",label:"Base",programs:[],includeAlt:!0,rowLayout:[3,3,3],actions:[],showOnDesktop:!1},{id:"opencode",label:"Code",programs:["opencode"],includeAlt:!1,rowLayout:[6],actions:[{id:"opencode-undo",label:"/undo",sequence:"/undo",doubleTapSequence:"/undo||\r"},{id:"opencode-new",label:"/new",sequence:"/new",doubleTapSequence:"/new||\r"},{id:"opencode-models",label:"/models",sequence:"/models",doubleTapSequence:"/models||\r"},{id:"opencode-compact",label:"/compact",sequence:"/compact",doubleTapSequence:"/compact||\r"}],showOnDesktop:!0},{id:"claude",label:"Claude",programs:["claude","claude-code"],includeAlt:!1,rowLayout:[6],actions:[{id:"claude-undo",label:"/undo",sequence:"/undo",doubleTapSequence:"/undo\r"},{id:"claude-clear",label:"/clear",sequence:"/clear",doubleTapSequence:"/clear\r"},{id:"claude-compact",label:"/compact",sequence:"/compact",doubleTapSequence:"/compact\r"}],showOnDesktop:!0},{id:"kimi",label:"Kimi",programs:["kimi","kimi-code"],includeAlt:!1,rowLayout:[6],actions:[{id:"kimi-undo",label:"/undo",sequence:"/undo",doubleTapSequence:"/undo\r"},{id:"kimi-new",label:"/new",sequence:"/new",doubleTapSequence:"/new\r"},{id:"kimi-sessions",label:"/sessions",sequence:"/sessions",doubleTapSequence:"/sessions\r"},{id:"kimi-compact",label:"/compact",sequence:"/compact",doubleTapSequence:"/compact\r"},{id:"kimi-goal",label:"/goal",sequence:"/goal",doubleTapSequence:"/goal\r"}],showOnDesktop:!0},{id:"codex",label:"Codex",programs:["codex"],includeAlt:!1,rowLayout:[6],actions:[{id:"codex-undo",label:"/undo",sequence:"/undo",doubleTapSequence:"/undo\r"},{id:"codex-clear",label:"/clear",sequence:"/clear",doubleTapSequence:"/clear\r"},{id:"codex-model",label:"/model",sequence:"/model",doubleTapSequence:"/model\r"},{id:"codex-compact",label:"/compact",sequence:"/compact",doubleTapSequence:"/compact\r"},{id:"codex-resume",label:"/resume",sequence:"/resume",doubleTapSequence:"/resume\r"}],showOnDesktop:!0},{id:"coco",label:"Coco",programs:["coco"],includeAlt:!1,rowLayout:[6],actions:[{id:"coco-undo",label:"/undo",sequence:"/||undo ",doubleTapSequence:"/||undo ||\r"},{id:"coco-clear",label:"/clear",sequence:"/||clear ",doubleTapSequence:"/||clear ||\r"},{id:"coco-model",label:"/model",sequence:"/||model ",doubleTapSequence:"/||model ||\r"},{id:"coco-resume",label:"/resume",sequence:"/||resume ",doubleTapSequence:"/||resume ||\r"}],showOnDesktop:!0},{id:"traex",label:"TraeX",programs:["traex","traecli"],includeAlt:!1,rowLayout:[6],actions:[{id:"traex-undo",label:"/undo",sequence:"/||undo ",doubleTapSequence:"/||undo ||\r"},{id:"traex-clear",label:"/clear",sequence:"/||clear ",doubleTapSequence:"/||clear ||\r"},{id:"traex-compact",label:"/compact",sequence:"/||compact ",doubleTapSequence:"/||compact ||\r"},{id:"traex-model",label:"/model",sequence:"/||model ",doubleTapSequence:"/||model ||\r"},{id:"traex-resume",label:"/resume",sequence:"/||resume ",doubleTapSequence:"/||resume ||\r"}],showOnDesktop:!0}];function wh(){return tA.map(e=>({...e,programs:[...e.programs],includeAlt:e.includeAlt,rowLayout:[...e.rowLayout],actions:e.actions.map(t=>({...t})),showOnDesktop:e.showOnDesktop}))}function Xy(e){const t=Array.isArray(e)?e.map(n=>Math.min(20,Math.max(2,Math.floor(n)))).filter(n=>Number.isFinite(n)):[];return t.length>0?t:[3,3]}function nA(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t.length>0?t:null}const Zy=/^\/(.+)\/([gimsuy]*)$/;function b3(e){return Zy.test(e.trim())}function ig(e){const t=e.trim().match(Zy);if(!t)return null;try{return new RegExp(t[1]??"",t[2]??"")}catch{return null}}function rA(e){if(typeof e!="string")return null;const t=e.trim();return t?Zy.test(t)?ig(t)?t:null:t.toLowerCase():null}function y3(e){return e.replace(/\\u([0-9a-fA-F]{4})/g,(t,n)=>String.fromCharCode(Number.parseInt(n,16))).replace(/\\r/g,"\r").replace(/\\n/g,`
|
|
76
76
|
`).replace(/\\t/g," ")}const v3="||",_O=120;function LO(e){return e.includes(v3)?e.split(v3).filter(t=>t.length>0):[e]}function h0(e){const t=new Set,n=e.map((s,i)=>{const a=typeof s.id=="string"&&s.id.trim().length>0?s.id.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"):`preset-${i+1}`,c=t.has(a)?`${a}-${i+1}`:a;return t.add(c),{id:c,label:typeof s.label=="string"&&s.label.trim().length>0?s.label.trim():"Preset",programs:Array.isArray(s.programs)?s.programs.map(u=>rA(u)).filter(u=>!!u):[],includeAlt:typeof s.includeAlt=="boolean"?!!s.includeAlt:!1,rowLayout:Xy(s.rowLayout),showOnDesktop:typeof s.showOnDesktop=="boolean"?!!s.showOnDesktop:!1,actions:Array.isArray(s.actions)?s.actions.map((u,f)=>{const p={id:typeof u.id=="string"&&u.id.trim().length>0?u.id:`${c}-action-${f+1}`,label:typeof u.label=="string"?u.label:`Key ${f+1}`,sequence:typeof u.sequence=="string"?u.sequence:""};return typeof u.doubleTapSequence=="string"&&(p.doubleTapSequence=u.doubleTapSequence),p}):[]}}).filter(s=>s.id!=="auto"),r=wh()[0];return r&&!n.some(s=>s.id==="default")&&n.unshift(r),n}function EO(e,t){const n=nA(e);if(!n)return"default";for(const r of t)if(r.id!=="default")for(const s of r.programs){const i=ig(s);if(i){if(i.test(n))return r.id}else if(n.includes(s))return r.id}return"default"}function w3(e,t){return e.find(n=>n.id===t)??e.find(n=>n.id==="default")??wh()[0]}function IO(e){return[{id:"auto",label:"Auto"},...e.map(t=>({id:t.id,label:t.label}))]}function RO(e){return[{id:"auto",label:"Auto"},...e.filter(t=>t.showOnDesktop===!0).map(t=>({id:t.id,label:t.label}))]}function sA(e,t){const n=Xy(t),r=[];let s=0,i=0;for(;s<e.length;){const a=n[Math.min(i,n.length-1)]??3;r.push({columns:a,items:e.slice(s,s+a)}),s+=a,i+=1}return r}const iA=28,oA=({mode:e,presetLabel:t,title:n,ariaLabel:r,disabled:s,onPointerDown:i,buttonRef:a})=>o.jsx("button",{ref:a,type:"button",onPointerDown:i,tabIndex:-1,disabled:s,className:"h-7 w-7 rounded-full bg-surface-2 shadow-sm text-[11px] font-medium active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",title:n,"aria-label":r??n,children:e==="auto"?o.jsx(BD,{size:14}):(t.charAt(0)||"?").toUpperCase()}),NO={esc:"\x1B",enter:"\r",home:"\x1B[H",end:"\x1B[F","ctrl-c":"","ctrl-d":"","ctrl-w":"","ctrl-u":""},qp=8;function MO(e,t){return NO[e]??null}const DO=({visible:e,interactive:t=!0,presentation:n="mobile",activeModifier:r,lockedModifier:s,disabled:i,defaultShowExtended:a=!1,presetLabel:c,presetModeLabel:u,presetMode:f,presetOptions:p,includeAlt:g,presetRowLayout:y,extraActions:v,onKeyPress:S,onTextPress:T,onPastePress:C,onFilePress:L,fileUploadState:E="idle",fileUploadProgress:D=0,longPressMode:B="arrows",copyFeedback:F="idle",onLongPressModeToggle:j,onModifierToggle:A,onPresetSelect:H,onExpandedChange:Q})=>{const{t:K}=qn(),[W,de]=M.useState(a),[X,pe]=M.useState(!1),ve=M.useRef(null),Ae=n==="desktop-actions",ie=Ae||W,[V,z]=M.useState(!1),[ce,ge]=M.useState(null),he=i||!e||!t,Ce=i||!e,xe=M.useRef(null),ae=M.useRef(null),_e=M.useRef(null),Z=M.useRef(null),Ze=M.useRef(null),at=M.useRef(F),He=M.useRef(null),be=M.useRef(0),Be=M.useCallback(ht=>{if(he)return;const $t=ht.target;if(!($t instanceof HTMLElement))return;const ut=$t.closest("button"),Ge=ut?.hasAttribute("data-mobile-native-action")===!0;ut&&!Ge?(ht.preventDefault(),Fl(qp)):ut&&Fl(qp)},[he]),fe=M.useCallback(ht=>{ht.preventDefault()},[]),Ke=M.useCallback(ht=>{const $t=ht.target;he||$t instanceof HTMLElement&&$t.closest("button")&&$t.blur()},[he]);M.useEffect(()=>{de(a)},[a]),M.useEffect(()=>{Ae||Q?.(W)},[Ae,Q,W]),M.useEffect(()=>{he&&(He.current!==null&&(window.clearTimeout(He.current.timer),He.current=null),z(!1),ge(null))},[he]),M.useEffect(()=>{e||(z(!1),ge(null))},[e]),M.useEffect(()=>{if(!V)return;const ht=()=>{const $t=xe.current?.getBoundingClientRect();$t&&ge({left:Math.max(8,$t.left),top:Math.max(8,$t.top-8)})};return ht(),window.addEventListener("resize",ht),window.addEventListener("scroll",ht,!0),()=>{window.removeEventListener("resize",ht),window.removeEventListener("scroll",ht,!0)}},[V]),M.useEffect(()=>{const ht=at.current;if(at.current=F,F==="idle"||F===ht)return;if(Ze.current!==null&&window.clearTimeout(Ze.current),!(typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches))if(F==="copied"){ae.current?.animate?.([{transform:"scale(1)"},{transform:"scale(1.16)",offset:.28},{transform:"scale(0.96)",offset:.62},{transform:"scale(1)"}],{duration:720,easing:"cubic-bezier(0.16, 1, 0.3, 1)"});const ut=[{opacity:0,transform:"scale(0.65)"},{opacity:.75,transform:"scale(0.9)",offset:.18},{opacity:0,transform:"scale(1.65)"}];_e.current?.animate?.(ut,{duration:760,easing:"ease-out"}),Z.current?.animate?.(ut,{duration:760,delay:130,easing:"ease-out"})}else ae.current?.animate?.([{transform:"translateX(0)"},{transform:"translateX(-2px)"},{transform:"translateX(2px)"},{transform:"translateX(0)"}],{duration:280,easing:"ease-out"});Fl(qp),F==="copied"&&(Ze.current=window.setTimeout(()=>{Fl(qp),Ze.current=null},90),B==="copy"&&j?.())},[F,B,j]),M.useEffect(()=>()=>{Ze.current!==null&&window.clearTimeout(Ze.current)},[]);const Ye=M.useCallback((ht,$t)=>{he||(ht.preventDefault(),S($t))},[S,he]),tt=M.useCallback((ht,$t)=>{he||(ht.preventDefault(),A($t))},[A,he]),q=M.useCallback(ht=>{he||(ht.preventDefault(),de($t=>{const ut=!$t;return ut&&(pe(!0),ve.current!==null&&window.clearTimeout(ve.current),ve.current=window.setTimeout(()=>{pe(!1),ve.current=null},350)),ut}))},[he]),ue=M.useCallback(()=>{const ht=typeof performance<"u"?performance.now():Date.now();ht-be.current<350||(be.current=ht,C?.())},[C]),Xe=M.useCallback(ht=>{he||(ht.stopPropagation(),ht.pointerType!=="touch"&&(ht.preventDefault(),ue()))},[he,ue]),Ne=M.useCallback(ht=>{he||(ht.preventDefault(),ht.stopPropagation(),ue())},[he,ue]),ze=M.useCallback(ht=>{he||E==="uploading"||!L||(ht.preventDefault(),ht.stopPropagation(),L())},[E,L,he]),Fe=M.useCallback(ht=>{he||ht.stopPropagation()},[he]),ft=250,ot=M.useCallback(()=>{He.current!==null&&(window.clearTimeout(He.current.timer),He.current=null)},[]);M.useEffect(()=>()=>{ot(),ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null)},[ot]);const Dt=M.useCallback((ht,$t)=>{if(he)return;if(ht.preventDefault(),!$t.doubleTapSequence){T($t.sequence);return}const ut=He.current;if(ut!==null&&ut.actionId===$t.id){window.clearTimeout(ut.timer),He.current=null,T($t.doubleTapSequence);return}ot();const Ge=window.setTimeout(()=>{He.current=null,T($t.sequence)},ft);He.current={actionId:$t.id,timer:Ge}},[ot,T,he]),wt=M.useCallback(ht=>{he||(ht.preventDefault(),ht.stopPropagation(),j?.())},[j,he]),Gt=M.useCallback(ht=>{he||ht.stopPropagation()},[he]),Jt=M.useCallback(ht=>{if(he)return;ht.preventDefault();const $t=ht.currentTarget.getBoundingClientRect();ge({left:Math.max(8,$t.left),top:Math.max(8,$t.top-8)}),z(ut=>!ut)},[he]),ln=M.useCallback((ht,$t)=>{he||(ht.preventDefault(),z(!1),ge(null),H($t))},[H,he]),Hn=v.length>0,we=M.useMemo(()=>{const ht=[{id:"preset",kind:"preset"}];if(!Ae&&g&&ht.push({id:"alt",kind:"alt"}),Hn){const $t=v.map(ut=>({id:ut.id,kind:"text",action:ut}));return ht.concat($t)}return Ae?ht:ht.concat([{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"}])},[v,Hn,g,Ae]),dt=M.useMemo(()=>sA(we,y),[we,y]),xt=`${Ae?"space-y-1":"mt-1 space-y-1"}${X?" pointer-events-none":""}`,Vt=V&&ce?ci.createPortal(o.jsx("div",{className:"fixed z-popover min-w-28 -translate-y-full rounded-2xl bg-surface-elevated p-1.5 shadow-xl border border-border/15",style:{left:ce.left,top:ce.top},children:o.jsx("div",{className:"grid gap-1",children:p.map(ht=>o.jsx("button",{type:"button",onPointerDown:$t=>ln($t,ht.id),tabIndex:-1,disabled:Ce,className:`h-7 rounded-full px-3 text-left text-xs font-medium transition-colors disabled:opacity-50 ${ht.id===f?"bg-primary text-primary-foreground":"bg-surface-2 hover:bg-surface-elevated text-muted-foreground hover:text-foreground"}`,children:ht.label},ht.id))})}),document.body):null;return o.jsxs(o.Fragment,{children:[Vt,o.jsx("div",{"data-mobile-keyboard":"true",className:`z-chrome select-none overflow-hidden app-chrome-bg transition-all duration-150 ease-out px-1 py-0 ${e?Ae?"max-h-24":"max-h-40":"max-h-0"} ${e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"} ${t?"":"[&_button]:pointer-events-none"}`,onMouseDownCapture:Be,onPointerDownCapture:Be,onContextMenuCapture:fe,onFocusCapture:Ke,children:o.jsxs("div",{className:"rounded-2xl bg-surface-elevated p-0.5 space-y-0.5",children:[!Ae&&o.jsxs("div",{"data-mobile-keyboard-primary-row":"true",className:"grid grid-cols-10 gap-1",children:[o.jsx("button",{type:"button",onPointerDown:ht=>Ye(ht,"esc"),tabIndex:-1,disabled:Ce,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"Esc"}),o.jsx("button",{type:"button",onPointerDown:ht=>tt(ht,"ctrl"),tabIndex:-1,disabled:Ce,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${r==="ctrl"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${s==="ctrl"?"ring-2 ring-accent":""}`,children:o.jsx("span",{className:"font-medium",children:s==="ctrl"?"Ctrl*":"Ctrl"})}),o.jsx("button",{type:"button",onPointerDown:ht=>Ye(ht,"ctrl-c"),tabIndex:-1,disabled:Ce,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"C-C"}),o.jsx("button",{type:"button",onPointerDown:ht=>Ye(ht,"ctrl-u"),tabIndex:-1,disabled:Ce,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"C-U"}),o.jsxs("button",{type:"button","data-mobile-native-action":"true",onPointerDown:Fe,onTouchStart:Fe,onClick:ze,tabIndex:-1,disabled:Ce||!L||E==="uploading",title:E==="uploading"?`${K("rightSidebar.uploading")} ${Math.round(D)}%`:K(E==="inserted"?"rightSidebar.inserted":E==="failed"?"rightSidebar.uploadFailed":"rightSidebar.insertLocalFile"),"aria-label":K("rightSidebar.insertLocalFile"),className:`relative h-7 w-full overflow-hidden rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center ${E==="inserted"?"bg-primary/15 text-primary":E==="failed"?"bg-destructive/15 text-destructive":"bg-surface-2"}`,children:[E==="uploading"&&o.jsx("span",{"aria-hidden":"true","data-file-upload-progress":"true",className:"absolute inset-y-0 left-0 bg-primary/25 transition-[width] duration-150 ease-out",style:{width:`${Math.max(0,Math.min(100,D))}%`}}),o.jsx("span",{className:"relative z-10 flex items-center justify-center",children:E==="uploading"?o.jsx(zn,{size:15,className:"animate-spin"}):E==="inserted"?o.jsx(Aa,{size:15}):E==="failed"?o.jsx(Zr,{size:15}):o.jsx(iM,{size:15})}),E!=="idle"&&o.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:E==="uploading"?`${K("rightSidebar.uploading")} ${Math.round(D)}%`:K(E==="inserted"?"rightSidebar.inserted":"rightSidebar.uploadFailed")})]}),o.jsx("button",{type:"button",onPointerDown:()=>T("/"),tabIndex:-1,disabled:Ce,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"/"}),o.jsx("button",{type:"button",onPointerDown:ht=>Ye(ht,"enter"),tabIndex:-1,disabled:Ce,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:o.jsx(a8,{size:16})}),o.jsxs("button",{ref:ae,type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:Gt,onTouchStart:Gt,onClick:wt,tabIndex:-1,disabled:Ce,title:K(F==="copied"?"terminal.copied":F==="failed"?"terminal.copyFailed":B==="copy"?"terminal.longPressSelectsText":"terminal.longPressSendsArrows"),"aria-label":K(B==="copy"?"terminal.switchLongPressToArrows":"terminal.switchLongPressToCopy"),className:`relative isolate h-7 w-full overflow-visible rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-colors keyboard-button-active disabled:opacity-50 flex items-center justify-center ${F==="copied"?"bg-primary/15 text-primary":F==="failed"?"bg-destructive/15 text-destructive":B==="copy"?"bg-primary/15 text-primary":"bg-surface-2"}`,children:[o.jsx("span",{ref:_e,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/70 opacity-0"}),o.jsx("span",{ref:Z,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/40 opacity-0"}),o.jsxs("span",{className:"relative z-10 h-4 w-4","aria-hidden":"true",children:[o.jsx(Aa,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${F==="copied"?"scale-100 rotate-0 opacity-100":"scale-50 -rotate-45 opacity-0"}`}),o.jsx(Zr,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none ${F==="failed"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),o.jsx(o8,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${F==="idle"&&B==="copy"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),o.jsx(GM,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${F==="idle"&&B==="arrows"?"scale-100 rotate-0 opacity-100":"scale-50 rotate-45 opacity-0"}`})]}),F!=="idle"&&o.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:F==="copied"?`${K("terminal.copied")} · ${K("terminal.longPressSendsArrows")}`:`${K("terminal.copyFailed")} · ${K("terminal.longPressSelectsText")}`})]}),o.jsx("button",{type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:Xe,onPointerUp:Fe,onTouchStart:Fe,onTouchEnd:Fe,onClick:Ne,tabIndex:-1,disabled:Ce,title:K("terminal.paste"),"aria-label":K("terminal.paste"),className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:o.jsx(FN,{size:15})}),o.jsx("button",{type:"button",onPointerDown:q,tabIndex:-1,disabled:Ce,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:W?o.jsx(i8,{size:16}):o.jsx(Ta,{size:16})})]}),ie&&o.jsx("div",{className:xt,children:dt.map((ht,$t)=>{const ut=ht.items[0]?.kind==="preset",Ge=Math.max(2,ht.columns),Jn=ut?`${iA}px repeat(${Math.max(1,Ge-1)}, minmax(0, 1fr))`:`repeat(${Ge}, minmax(0, 1fr))`;return o.jsx("div",{className:"relative grid gap-1",style:{gridTemplateColumns:Jn},children:ht.items.map(An=>An.kind==="preset"?o.jsx(oA,{buttonRef:An.id==="preset"?xe:void 0,mode:f,presetLabel:c,title:u,disabled:Ce,onPointerDown:Jt},An.id):An.kind==="alt"?o.jsx("button",{type:"button",onPointerDown:We=>tt(We,"alt"),tabIndex:-1,disabled:Ce,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${r==="alt"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${s==="alt"?"ring-2 ring-accent":""}`,children:o.jsx("span",{className:"font-medium",children:s==="alt"?"Alt*":"Alt"})},An.id):An.kind==="text"?o.jsxs("button",{type:"button",onPointerDown:We=>Dt(We,An.action),tabIndex:-1,disabled:Ce,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm px-1 text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 relative",children:[An.action.label,An.action.doubleTapSequence&&o.jsx("span",{className:"absolute top-0.5 right-1.5 h-1 w-1 rounded-full bg-accent/60"})]},An.id):o.jsx("button",{type:"button",onPointerDown:We=>Ye(We,An.keyName),tabIndex:-1,disabled:Ce,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:An.keyName==="ctrl-d"?"Ctrl-D":An.keyName==="home"?"Home":"End"},An.id))},`row-${$t}`)})})]})})]})},jO=({isMobile:e,isInputFocused:t,isIOS:n,isConnecting:r,connectionError:s,terminalSessionId:i})=>{if(typeof window>"u")return null;const a=window.visualViewport?Math.max(0,Math.round(window.innerHeight-window.visualViewport.height-window.visualViewport.offsetTop)):0;return o.jsxs("div",{className:"px-3 py-2 bg-surface text-foreground text-xs border-b border-border/15",children:[o.jsx("div",{className:"font-bold mb-2",children:"Debug Info"}),o.jsxs("div",{className:"grid grid-cols-2 gap-1 font-mono",children:[o.jsxs("div",{children:["isMobile: ",o.jsx("span",{className:e?"text-accent":"text-destructive",children:String(e)})]}),o.jsxs("div",{children:["touchPoints: ",navigator.maxTouchPoints]}),o.jsxs("div",{children:["innerWidth: ",window.innerWidth]}),o.jsxs("div",{children:["innerHeight: ",window.innerHeight]}),o.jsxs("div",{children:["viewportH:"," ",window.visualViewport?Math.round(window.visualViewport.height):"N/A"]}),o.jsxs("div",{children:["inputFocused: ",String(t)]}),o.jsxs("div",{children:["keyboard~: ",a,"px"]}),o.jsxs("div",{children:["connecting:"," ",o.jsx("span",{className:r?"text-muted-foreground":"text-accent",children:String(r)})]}),o.jsxs("div",{children:["sessionId:"," ",o.jsx("span",{className:i?"text-accent":"text-destructive",children:i?"✓":"✗"})]}),o.jsxs("div",{children:["error:"," ",o.jsx("span",{className:s?"text-destructive":"text-accent",children:s?"Yes":"No"})]}),o.jsxs("div",{children:["isIOS:"," ",o.jsx("span",{className:n?"text-muted-foreground":"text-accent",children:String(n)})]})]}),o.jsx("div",{className:"mt-2 pt-2 border-t border-border/15",children:o.jsx("div",{children:"Tip: Tap the status bar 3 times to toggle debug panel"})})]})},PO=/^Reconnecting/i,BO=({connectionError:e,isFatalError:t,isRestarting:n,isConnecting:r,onHardRestart:s})=>{const{t:i}=qn(),a=!!e&&PO.test(e);return r&&!e||a?o.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2 pointer-events-none",children:o.jsx("span",{className:"text-[11px] text-muted-foreground/60 animate-pulse tracking-wide",children:e||i("connection.reconnecting")})}):e?o.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2",children:o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-destructive/70",children:[o.jsx("span",{children:e}),t&&o.jsx("button",{type:"button",onClick:s,disabled:n,className:"text-[11px] text-destructive/90 hover:text-destructive underline underline-offset-2 transition-colors disabled:opacity-40",children:i("common.retry")})]})}):null};let Jf=[],Mx=!1;function Oa(e,t,n={}){typeof window>"u"||(Jf.push(JSON.stringify({level:e,message:t,data:{ts:Date.now(),...n}})),FO())}async function FO(){if(!Mx){Mx=!0;try{for(;Jf.length>0;){const e=Jf[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),Jf.shift()}catch{Jf=[];break}}}finally{Mx=!1}}}const y2=80,OO=60,QO="termdock:viewport-keyboard-change",v2="termdock:viewport-layout-change",Pc=240,S3=640,A3=360,$O=[50,150,300,500,800,1200],HO=28,UO=72,aA=500;function zO({measuredHeight:e,documentVisible:t,editableFocused:n}){return t&&n&&e>=y2}function w2(){if(typeof document>"u")return!1;const e=document.activeElement;return e instanceof HTMLElement&&e.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}function GO({measuredHeight:e,referenceHeight:t,keyboardOpenAgeMs:n,isIOS:r,isTerminalInputFocused:s}){const i=t-e,a=i>=HO&&i<=UO;return r&&s&&n>=aA&&a?t:e}const og=e=>{const t=typeof e=="number"?e:Number.parseFloat(typeof e=="string"?e:"0");return Number.isFinite(t)&&t>0?Math.round(t):0},lA=(e,t)=>{const n=e.map(og).filter(r=>r>0);return n.find(r=>r>=Pc)??n[0]??t},ch=()=>typeof window>"u"?S3:lA([window.innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,window.visualViewport?.height,window.screen?.availHeight,window.screen?.height],S3),cA=()=>typeof window>"u"?A3:lA([window.innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,window.visualViewport?.width,window.screen?.availWidth,window.screen?.width],A3),Kp=e=>{const t=Number.parseFloat(e||"0");return Number.isFinite(t)?Math.max(0,Math.round(t)):0},S2=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,WO=()=>typeof window>"u"?!1:navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)").matches===!0,uA=()=>{if(typeof window>"u"||!S2()||!WO())return{top:0,right:0,bottom:0,left:0};if(!(ch()>=cA()))return{top:0,right:0,bottom:0,left:0};const t=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(t,n),s=Math.max(t,n);return r>=700?{top:20,right:0,bottom:20,left:0}:s<780?{top:20,right:0,bottom:0,left:0}:{top:s>=852?59:s>=844?47:44,right:0,bottom:34,left:0}};function VO(e="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const t=og(window.visualViewport?.height),n=Math.max(0,Math.round(window.visualViewport?.offsetTop??0)),r=ch(),i=t>=Pc?Math.min(r,t+n):r,a=Math.max(r,i),c=document.documentElement.style;c.setProperty(e,`${Math.max(i,Pc)}px`),c.setProperty("--app-base-vh",`${Math.max(a,Pc)}px`),c.setProperty("--app-visible-vh",`${Math.max(i,Pc)}px`),c.setProperty("--app-vv-offset-top",`${n}px`),c.setProperty("--kb-translate-y","0px"),c.setProperty("--kb-margin-top","0px"),c.setProperty("--kb-height","0px");const u=uA();u.top>0&&c.setProperty("--safe-top-inset",`${u.top}px`),u.right>0&&c.setProperty("--safe-right-inset",`${u.right}px`),u.bottom>0&&c.setProperty("--safe-bottom-inset",`${u.bottom}px`),u.left>0&&c.setProperty("--safe-left-inset",`${u.left}px`)}function qO(e={}){const{cssVarName:t="--app-vh"}=e,n=M.useMemo(()=>od("viewport"),[]),r=M.useCallback(()=>{if(typeof window>"u")return 0;const v=window.visualViewport,S=ch();if(!v)return S;const T=og(v.height);if(T<Pc&&S>=Pc)return S;const C=v.offsetTop,E=T<S-1&&C>0&&C<=96?T+C:T,D=Math.max(0,Math.min(S,E));return D>0?Math.round(D):S},[]),[s,i]=M.useState(r),a=M.useRef([]),c=M.useRef(0),u=M.useRef(0),f=M.useRef(0),p=M.useRef(!1),g=M.useRef(null),y=M.useRef(new Map);return M.useEffect(()=>{if(typeof window>"u")return;let v=null,S=null;const T=new Set,C=(V,z,ce)=>[V,z,ce].sort((ge,he)=>ge-he)[1],L=()=>{if(S?.isConnected)return S;try{return S=document.createElement("div"),S.setAttribute("aria-hidden","true"),S.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(S),S}catch{}return null},E=()=>{let V={top:0,right:0,bottom:0,left:0};try{const ge=L();if(ge){const he=getComputedStyle(ge);V={top:Kp(he.paddingTop),right:Kp(he.paddingRight),bottom:Kp(he.paddingBottom),left:Kp(he.paddingLeft)}}}catch{}const z=uA(),ce={top:Math.max(V.top,z.top),right:Math.max(V.right,z.right),bottom:Math.max(V.bottom,z.bottom),left:Math.max(V.left,z.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${ce.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${ce.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${ce.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${ce.left}px`),ce},D=(V,z,ce,ge)=>{const he=Math.max(z,ce);if(c.current===0){c.current=he,u.current=V,document.documentElement.style.setProperty("--app-base-vh",`${he}px`);return}const Ce=Math.abs(V-u.current),xe=ge<=y2;(Ce>OO||xe)&&(c.current=he,u.current=V,document.documentElement.style.setProperty("--app-base-vh",`${he}px`))},B=(V="event")=>{v=null;const z=r(),ce=Math.round(window.visualViewport?.offsetTop??0),ge=og(window.visualViewport?.height),he=ge>=Pc?ge:z,Ce=ch(),xe=cA(),ae=Math.max(0,he+ce),_e=E(),Z=_e.bottom,Ze=Math.max(0,c.current-ae-Z);D(xe,Ce,ae,Ze);const at=a.current;at.push(z),at.length>3&&at.shift();let He=z;at.length===3&&z<=at[0]&&(He=C(at[0],at[1],at[2])),i(xt=>xt===z?xt:z);const be=Number.parseInt(document.documentElement.style.getPropertyValue(t)||"0",10);document.documentElement.style.setProperty(t,`${He}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${ce}px`);const Be=c.current,fe=Math.min(He,he),Ke=Math.max(0,Math.min(Be,ae)),Ye=Math.max(0,Math.round(Be-Ke-Z)),tt=w2(),q=zO({measuredHeight:Ye,documentVisible:document.visibilityState==="visible",editableFocused:tt}),ue=q,Xe=performance.now();ue&&g.current===null?g.current=Xe:ue||(g.current=null);const Ne=g.current===null?0:Math.max(0,Xe-g.current),ze=xe>Be?"landscape":"portrait",Fe=Math.round(xe/20)*20,ft=`${ze}:${Fe}`,ot=y.current.get(ft)??0,Dt=document.activeElement?.matches('[data-terminal-input-anchor="true"]')===!0,wt=q?GO({measuredHeight:Ye,referenceHeight:ot,keyboardOpenAgeMs:Ne,isIOS:S2(),isTerminalInputFocused:Dt}):0,Gt=wt>=y2;S2()&&Dt&&ue&&Ne>=aA&&Ye>ot&&y.current.set(ft,Ye);const Jt=-wt,ln=wt;document.documentElement.style.setProperty("--kb-translate-y",`${Jt}px`),document.documentElement.style.setProperty("--kb-margin-top",`${ln}px`),document.documentElement.style.setProperty("--kb-height",`${wt}px`),document.documentElement.style.setProperty("--app-visible-vh",`${Ke}px`);const Hn=Math.abs(wt-f.current)>1,we=Gt!==p.current;(Hn||we)&&(f.current=wt,p.current=Gt,document.dispatchEvent(new CustomEvent(QO,{detail:{baseHeight:Be,visibleHeight:Ke,visualViewportHeight:he,offsetTop:ce,keyboardHeight:wt,isOpen:Gt,source:V}}))),(be!==He||ce>0||Hn||we)&&n("sync",{cssVarName:t,innerHeight:Ce,baseHeight:Be,rawViewportHeight:he,offsetTop:ce,visibleHeight:Ke,rawHeight:z,appliedHeight:He,keyboardViewportHeight:fe,measuredKeyboardHeight:Ye,editableFocused:tt,applyKeyboardInset:q,referenceKeyboardHeight:ot,keyboardOpenAgeMs:Math.round(Ne),correctedKeyboardToolbar:wt!==Ye,keyboardHeight:wt,isKeyboardOpen:Gt,safeAreaInsets:_e,filtered:He!==z,source:V}),document.dispatchEvent(new CustomEvent(v2,{detail:{height:He,baseHeight:Be,visibleHeight:Ke,offsetTop:ce,source:V}}))},F=(V="event")=>{(V.includes("visibilitychange")||V.includes("pageshow"))&&n("schedule",{source:V}),v===null&&(v=window.requestAnimationFrame(()=>B(V)))},j=V=>{F(`${V}:now`);for(const z of $O){const ce=window.setTimeout(()=>{T.delete(ce),F(`${V}:${z}ms`)},z);T.add(ce)}};j("mount");const A=()=>F("resize"),H=()=>F("orientationchange"),Q=()=>F("visualViewport.resize"),K=()=>F("visualViewport.scroll"),W=()=>j("focusin"),de=()=>j("focusout"),X=V=>{const z=document.activeElement;z instanceof HTMLElement&&w2()&&z.blur(),g.current=null,f.current=0,p.current=!1,a.current=[];const ce=Math.max(c.current,ch(),Pc),ge=document.documentElement.style;ge.setProperty(t,`${ce}px`),ge.setProperty("--app-visible-vh",`${ce}px`),ge.setProperty("--app-vv-offset-top","0px"),ge.setProperty("--kb-translate-y","0px"),ge.setProperty("--kb-margin-top","0px"),ge.setProperty("--kb-height","0px"),i(he=>he===ce?he:ce),n("keyboard session reset",{source:V,baseHeight:ce})};window.addEventListener("resize",A),window.addEventListener("orientationchange",H),window.visualViewport?.addEventListener("resize",Q),window.visualViewport?.addEventListener("scroll",K),document.addEventListener("focusin",W),document.addEventListener("focusout",de);const pe=V=>{n("resume",{source:V,innerHeight:Math.round(window.innerHeight),visualViewport:window.visualViewport?{width:Math.round(window.visualViewport.width),height:Math.round(window.visualViewport.height),offsetTop:Math.round(window.visualViewport.offsetTop)}:null,hidden:document.hidden}),j(V)},ve=()=>{document.hidden?X("visibilitychange:hidden"):pe("visibilitychange")},Ae=()=>pe("pageshow"),ie=()=>X("pagehide");return document.addEventListener("visibilitychange",ve),window.addEventListener("pageshow",Ae),window.addEventListener("pagehide",ie),()=>{window.removeEventListener("resize",A),window.removeEventListener("orientationchange",H),window.visualViewport?.removeEventListener("resize",Q),window.visualViewport?.removeEventListener("scroll",K),document.removeEventListener("focusin",W),document.removeEventListener("focusout",de),document.removeEventListener("visibilitychange",ve),window.removeEventListener("pageshow",Ae),window.removeEventListener("pagehide",ie),v!==null&&window.cancelAnimationFrame(v),T.forEach(V=>window.clearTimeout(V)),T.clear(),S?.remove()}},[t,n,r]),s}const KO=120,YO=80,XO=400;function T3(){if(typeof window>"u"||document.visibilityState!=="visible"||!w2())return 0;const e=Number.parseFloat(document.documentElement.style.getPropertyValue("--kb-height")||"0");if(Number.isFinite(e)&&e>0)return Math.round(e);const t=window.visualViewport;if(!t)return 0;const n=Number.parseFloat(document.documentElement.style.getPropertyValue("--app-base-vh")||"0")||window.innerHeight,r=Number.parseFloat(document.documentElement.style.getPropertyValue("--safe-bottom-inset")||"0")||0,s=t.height+t.offsetTop;return Math.max(0,Math.round(n-s-r))}function dA(e){const{enabled:t,openThresholdPx:n=KO,closeThresholdPx:r=YO,settleDelayMs:s=XO}=e,i=M.useMemo(()=>od("keyboard"),[]),a=M.useRef(!1),c=M.useRef(null),u=M.useRef(0),[f,p]=M.useState({isOpen:!1,isSettled:!1,keyboardHeight:0});return M.useEffect(()=>{if(typeof window>"u"||!t){a.current=!1,c.current!==null&&(clearTimeout(c.current),c.current=null),p(j=>!j.isOpen&&!j.isSettled&&j.keyboardHeight===0?j:{isOpen:!1,isSettled:!1,keyboardHeight:0});return}let g=null;const y=()=>{g=null;const j=T3();let A=a.current;if(j>=n?A=!0:j<=r&&(A=!1),a.current=A,A){const H=Math.abs(j-u.current);u.current=j,H>10&&(c.current!==null&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,p(Q=>Q.isSettled?Q:{...Q,isSettled:!0})},s))}else c.current!==null&&(clearTimeout(c.current),c.current=null);p(H=>{const Q=A?H.isSettled:!1;return H.isOpen===A&&H.keyboardHeight===j&&H.isSettled===Q?H:(i("sync",{keyboardHeight:j,isOpen:A,isSettled:Q,visualViewport:window.visualViewport?{width:Math.round(window.visualViewport.width),height:Math.round(window.visualViewport.height),offsetTop:Math.round(window.visualViewport.offsetTop)}:null}),{isOpen:A,isSettled:Q,keyboardHeight:j})})},v=(j="event")=>{(j.includes("visibilitychange")||j.includes("pageshow"))&&i("schedule",{source:j}),g===null&&(g=window.requestAnimationFrame(y))};v("mount");const S=()=>v("resize"),T=()=>v("orientationchange"),C=()=>v("visualViewport.resize"),L=()=>v("visualViewport.scroll"),E=()=>v("viewport-keyboard-change");window.addEventListener("resize",S),window.addEventListener("orientationchange",T),window.visualViewport?.addEventListener("resize",C),window.visualViewport?.addEventListener("scroll",L),document.addEventListener("termdock:viewport-keyboard-change",E);const D=j=>{i("resume",{source:j,keyboardHeight:T3(),hidden:document.hidden}),v(`${j}:now`),window.setTimeout(()=>v(`${j}:50ms`),50),window.setTimeout(()=>v(`${j}:200ms`),200)},B=()=>{document.hidden||D("visibilitychange")},F=()=>D("pageshow");return document.addEventListener("visibilitychange",B),window.addEventListener("pageshow",F),()=>{window.removeEventListener("resize",S),window.removeEventListener("orientationchange",T),window.visualViewport?.removeEventListener("resize",C),window.visualViewport?.removeEventListener("scroll",L),document.removeEventListener("termdock:viewport-keyboard-change",E),document.removeEventListener("visibilitychange",B),window.removeEventListener("pageshow",F),g!==null&&window.cancelAnimationFrame(g),c.current!==null&&(clearTimeout(c.current),c.current=null)}},[i,t,n,r,s]),f}const jm=300,ZO=120,JO=250,eQ=6e4;function Dx(e,t){return t?e.find(n=>n.id===t||n.backendSessionId===t)?.id??null:null}function Yp(e){return e.prioritySessionId??e.activeSessionId??e.persistedActiveSessionId??e.firstSessionId}function tQ(e){return e.foregroundSessionId===null||e.sessionId===e.foregroundSessionId||e.foregroundReady}function nQ(e){return e.isMobileLayout?e.visibleSessionIds.has(e.sessionId):e.sessionId===e.foregroundSessionId||e.deferredViewportSessionIds.has(e.sessionId)}function rQ(e){return e.requestToken===0||e.foregroundSessionId===null||e.sessionId===e.foregroundSessionId||e.foregroundCompletedToken===e.requestToken}function sQ(e,t){return e===null||t-e>=JO}function iQ(e){return e.wasPageHidden||e.reason==="bfcache"||e.reason==="online"}function oQ(e){return!e.isActive||e.isStreamReady||e.reconnectStartedAt===null?null:Math.max(0,eQ-(e.now-e.reconnectStartedAt))}function aQ(e,t){const n=new Map;let r=0;for(const s of e)if(!n.has(s)){if(t.has(s)){n.set(s,0);continue}n.set(s,jm+r*ZO),r+=1}return n}const lQ="Session not found on server",jx="Terminal session not found",cQ="STALE_SESSION_RESTORE_REJECTED";function uQ(e){return e?.message===lQ}function C3(e){return e?.code===cQ}function eh(e,t){if(!e||e.startsWith("/"))return e;const n=e.replace(/^\.\//,"");return t?`${t.replace(/\/+$/,"")}/${n}`:n}function Yg(e,t){return eh(e,t).replace(/ /g,"\\ ")}function fA(e,t){return`${Yg(e,t)} `}function A2(e,t){return Yg(e,t)}function dQ(e,t,n){if(!n)return A2(e,t);const r=n.start===n.end?`${n.start}`:`${n.start}-${n.end}`;return`${A2(e,t)}:${r}`}const fQ="/tmp";async function hA(e,t,n){const s=(await t(fQ,[e])).files[0];if(!s?.path)throw new Error("Upload did not return a file path");return n(s.path),s}const hQ=hA;function Ur(e,t){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(e);if(n===null||n==="")return null;const r=JSON.parse(n);return t(r)?r:null}catch{return null}}function $n(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function Px(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch{}}const uh=new Map,dh=new Map,Pm=new Map;function v0(e,t,n){if(typeof window>"u")return;const r=Date.now(),s=Pm.get(e)??0,i=r-s;if(i>=n){Pm.set(e,r),$n(e,t);return}if(dh.set(e,t),uh.has(e))return;const a=n-i,c=setTimeout(()=>{uh.delete(e);const u=dh.get(e);dh.delete(e),Pm.set(e,Date.now()),u!==void 0&&$n(e,u)},a);uh.set(e,c)}function i0(e){const t=uh.get(e);t&&(clearTimeout(t),uh.delete(e));const n=dh.get(e);n!==void 0&&(dh.delete(e),Pm.set(e,Date.now()),$n(e,n))}function pQ(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}const mQ=600,Sh=320,gQ=280,xQ=5;function Bx(e,t,n=0){const r=Math.max(Sh,t-Math.max(0,n)-xQ*(n>0?2:1)-gQ);return Math.min(r,Math.max(Sh,e))}const pA="termdock:right-sidebar:tabs-by-session:v2",mA="termdock:right-sidebar:explorer-roots-by-session:v2",Jy="termdock:right-sidebar:pinned-explorer-roots:v1",gA="termdock:right-sidebar:selected-files-by-session:v2",xA="termdock:right-sidebar:show-hidden-files:v1",T2="termdock:right-sidebar:file-sort-modes:v1",k3="termdock-sidebar-group-by-folder",bA="termdock-sidebar-collapsed-folder-groups",yA="termdock-left-sidebar-pinned",vA="termdock-left-sidebar-width",wA="termdock-right-sidebar-pinned",SA="termdock-right-sidebar-width",ev="termdock:right-sidebar:widths-by-session:v1",AA="termdock-right-sidebar-layout-preference";function bQ(){if(typeof window>"u")return!0;try{const e=window.localStorage.getItem(yA);return e===null?!0:e==="1"}catch{return!0}}function _3(e){if(!(typeof window>"u"))try{window.localStorage.setItem(yA,e?"1":"0")}catch{}}function yQ(){if(typeof window>"u")return 300;try{const e=window.localStorage.getItem(vA);if(!e)return 300;const t=parseInt(e,10);return Number.isFinite(t)&&t>=200&&t<=500?t:300}catch{return 300}}function vQ(e){if(!(typeof window>"u"))try{window.localStorage.setItem(vA,String(e))}catch{}}function wQ(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(wA)==="1"}catch{return!1}}function L3(e){if(!(typeof window>"u"))try{window.localStorage.setItem(wA,e?"1":"0")}catch{}}function Xp(){if(typeof window>"u")return 760;try{const e=window.localStorage.getItem(SA);if(!e)return 760;const t=parseInt(e,10);return Number.isFinite(t)&&t>=Sh?t:760}catch{return 760}}function SQ(e){if(!(typeof window>"u"))try{window.localStorage.setItem(SA,String(e))}catch{}}function AQ(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="number"&&Number.isFinite(t)&&t>=Sh)}function Bm(){return Ur(ev,AQ)??{}}function Fx(e,t){if(!e){SQ(t);return}$n(ev,{...Bm(),[e]:t})}function TQ(){if(typeof window>"u")return"auto";try{const e=window.localStorage.getItem(AA);return e==="narrow"||e==="wide"?e:"auto"}catch{return"auto"}}function CQ(e){if(!(typeof window>"u"))try{window.localStorage.setItem(AA,e)}catch{}}function kQ(e,t,n){return!t||n==="auto"?e<mQ:n==="narrow"}function _Q(){return!0}function E3(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(k3,"1"):window.localStorage.setItem(k3,"0")}catch{}}function LQ(){if(typeof window>"u")return new Set;try{const e=window.localStorage.getItem(bA);if(!e)return new Set;const t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function EQ(e){if(!(typeof window>"u"))try{window.localStorage.setItem(bA,JSON.stringify([...e]))}catch{}}function IQ(e){return e==="git"||e==="files"||e==="diff"}function RQ(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(IQ)}function TA(){return Ur(pA,RQ)??{}}function NQ(e,t){e&&$n(pA,{...TA(),[e]:t})}function MQ(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function DQ(){return Ur(mA,MQ)??{}}function I3(e){$n(mA,e)}function jQ(e){return e!==null&&typeof e=="object"&&typeof e.path=="string"&&(e.kind==="file"||e.kind==="directory")}function PQ(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>Array.isArray(t)&&t.every(n=>typeof n=="string"||jQ(n)))}function CA(e){const t=new Set,n=[];for(const r of e){const s=typeof r=="string"?{path:r,kind:"directory"}:r;!s.path||t.has(s.path)||(t.add(s.path),n.push(s))}return n}function BQ(){const e=Ur(Jy,PQ)??{},t={};for(const[n,r]of Object.entries(e))t[n]=CA(r);return t}function R3(e){$n(Jy,e)}function FQ(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function kA(){return Ur(gA,FQ)??{}}function N3(e,t){if(!e)return;const n={...kA()};t?n[e]=t:delete n[e],$n(gA,n)}function C2(e,t){return t?e?`${e}\0${t}`:t:null}function M3(e,t,n){return n?`split-workspace\0${n}`:C2(e,t)}function OQ(e){return typeof e=="boolean"}function QQ(){return Ur(xA,OQ)??!1}function $Q(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>t==="modified")}function HQ(){return Ur(T2,$Q)??{}}let Df=null;const Ox=new Map;let jf=null;const Qx=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function UQ(e){const t=e.replace(/\/+$/,"")||"/";return t==="/"?"/":t.slice(0,t.lastIndexOf("/"))||"/"}function Pf(e,t){const n=e.replace(/\/+$/,"")||"/";return t===n||t.startsWith(`${n}/`)}function zQ(e,t="name"){return[...e].sort((n,r)=>{if(n.type==="directory"&&r.type!=="directory")return-1;if(n.type!=="directory"&&r.type==="directory")return 1;if(t==="modified"){const s=Date.parse(r.modified??"")-Date.parse(n.modified??"");if(Number.isFinite(s)&&s!==0)return s}return n.name.localeCompare(r.name)})}function GQ(e){return e.entry?{name:e.entry.name,path:e.entry.path,type:e.entry.type,isSymlink:e.entry.isSymlink,modified:e.entry.modified,expanded:!1,loaded:!1,children:e.entry.type==="directory"?[]:void 0}:null}const ct=IS(e=>({leftOpen:!1,rightOpen:!1,leftPinned:bQ(),leftSidebarWidth:yQ(),rightPinned:wQ(),rightSidebarWidth:Xp(),rightSidebarLayoutPreference:TQ(),rightTab:"files",rightSearchOpen:!1,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:DQ(),pinnedExplorerRootsCache:BQ(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:HQ(),fileSortModesHydrated:!1,showHiddenFiles:QQ(),groupByFolder:_Q(),collapsedGroups:LQ(),changedFiles:new Map,fileChangeVersions:new Map,fileWatchEpoch:0,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:null,gitBundleLastLoadedAt:null,gitBundleCacheInfo:null,projectStateCache:new Map,openLeft:()=>e({leftOpen:!0}),closeLeft:()=>e({leftOpen:!1}),toggleLeft:()=>e(t=>({leftOpen:!t.leftOpen,rightOpen:t.leftOpen?t.rightOpen:!1})),toggleLeftPinned:()=>e(t=>{const n=!t.leftPinned;return _3(n),{leftPinned:n,leftOpen:!0}}),setLeftPinned:t=>e(()=>(_3(t),{leftPinned:t})),setLeftSidebarWidth:t=>e(n=>{const r=Math.min(Math.max(t,200),500);return n.leftSidebarWidth===r?n:(vQ(r),{leftSidebarWidth:r})}),toggleRightPinned:()=>e(t=>{const n=!t.rightPinned;return L3(n),{rightPinned:n,rightOpen:!0}}),setRightPinned:t=>e(()=>(L3(t),{rightPinned:t})),setRightSidebarWidth:t=>e(n=>{const r=Math.max(t,Sh);return n.rightSidebarWidth===r?n:(Fx(n.rightSidebarWidthContextKey,r),{rightSidebarWidth:r})}),setRightSidebarLayoutPreference:t=>e(n=>n.rightSidebarLayoutPreference===t?n:(CQ(t),{rightSidebarLayoutPreference:t})),openRight:()=>e({rightOpen:!0}),closeRight:()=>e({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>e(t=>({rightOpen:!t.rightOpen,rightSearchOpen:t.rightOpen?!1:t.rightSearchOpen,leftOpen:t.rightOpen?t.leftOpen:!1})),closeAll:()=>e({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:t=>e(n=>(NQ(n.contextKey,t),{rightTab:t})),openRightSearch:()=>e({rightSearchOpen:!0}),closeRightSearch:()=>e({rightSearchOpen:!1}),setRightSearchOpen:t=>e({rightSearchOpen:t}),setRootPath:(t,n=null,r=null)=>e(s=>{const i=C2(n,t),a=M3(n,t,r);if(s.contextKey===i&&s.rightSidebarWidthContextKey===a)return s;if(s.contextKey===i){const S=Bm();let T=a?S[a]:void 0;return r&&a&&T===void 0&&(T=(i?S[i]:void 0)??s.rightSidebarWidth,Fx(a,T)),{rightSidebarWidthContextKey:a,rightSidebarWidth:T??Xp()}}const c=new Map(s.projectStateCache);s.contextKey&&c.set(s.contextKey,{rightTab:s.rightTab,explorerRoot:s.explorerRoot,expandedPaths:new Set(s.expandedPaths),selectedFilePath:s.selectedFilePath,directoryCache:new Map(s.directoryCache),changedFiles:new Map(s.changedFiles),gitBundleError:s.gitBundleError,gitBundleLastLoadedAt:s.gitBundleLastLoadedAt,gitBundleCacheInfo:s.gitBundleCacheInfo});const u=i?c.get(i):void 0,f=i?TA()[i]:void 0,p=Bm();let g=a?p[a]:void 0;r&&a&&g===void 0&&(g=(i?p[i]:void 0)??Xp(),Fx(a,g));const y=i?s.explorerRootCache[i]:void 0,v=i?kA()[i]:void 0;return{rootPath:t,contextKey:i,rightSidebarWidthContextKey:a,rightSidebarWidth:g??Xp(),rightTab:u?.rightTab??f??"files",explorerRoot:u?.explorerRoot??y??t,expandedPaths:u?new Set(u.expandedPaths):new Set,selectedFilePath:u?.selectedFilePath??v??null,directoryCache:u?new Map(u.directoryCache):new Map,changedFiles:u?new Map(u.changedFiles):new Map,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:u?.gitBundleError??null,gitBundleLastLoadedAt:u?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:u?.gitBundleCacheInfo??null,projectStateCache:c}}),inheritRightSidebarWidthFromSplitWorkspace:(t,n)=>{if(!t||n.length===0)return;const r=Bm(),s=M3(null,null,t);if(!s)return;const i=ct.getState(),a=r[s]??(i.rightSidebarWidthContextKey===s?i.rightSidebarWidth:void 0);if(a===void 0)return;let c=!1;const u={...r};for(const f of n){const p=C2(f.sessionId,f.rootPath);!p||u[p]===a||(u[p]=a,c=!0)}c&&$n(ev,u)},setExplorerRoot:t=>e(n=>{if(n.explorerRoot===t)return n;const r={...n.explorerRootCache};return n.contextKey&&t&&(r[n.contextKey]=t,I3(r)),{explorerRoot:t,explorerRootCache:r}}),resetExplorerToProject:()=>e(t=>{if(t.explorerRoot===t.rootPath)return t;const n={...t.explorerRootCache};return t.contextKey&&t.rootPath&&(n[t.contextKey]=t.rootPath,I3(n)),{explorerRoot:t.rootPath,explorerRootCache:n}}),pinExplorerRoot:(t,n="directory")=>e(r=>{if(!r.rootPath||!t)return r;const s=r.rootPath,i=r.pinnedExplorerRootsCache[r.rootPath]??[];if(i.some(c=>c.path===t))return r;const a={...r.pinnedExplorerRootsCache,[r.rootPath]:[{path:t,kind:n},...i].slice(0,12)};return R3(a),(async()=>{try{await ct.getState().hydratePinnedExplorerRoots();const c=await bo({pinnedExplorerRoot:{rootPath:s,path:t,kind:n,pinned:!0},pinnedExplorerRootsOrigin:Qx});ct.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),unpinExplorerRoot:t=>e(n=>{if(!n.rootPath||!t)return n;const r=n.rootPath,s=n.pinnedExplorerRootsCache[n.rootPath]??[],i=s.find(u=>u.path===t);if(!s.some(u=>u.path===t))return n;const a=s.filter(u=>u.path!==t),c={...n.pinnedExplorerRootsCache};return a.length>0?c[n.rootPath]=a:delete c[n.rootPath],R3(c),(async()=>{try{await ct.getState().hydratePinnedExplorerRoots();const u=await bo({pinnedExplorerRoot:{rootPath:r,path:t,kind:i?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:Qx});ct.getState().syncPinnedExplorerRoots(u.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:c}}),hydratePinnedExplorerRoots:async()=>{if(!ct.getState().pinnedExplorerRootsHydrated)return jf||(jf=(async()=>{const t=ct.getState().pinnedExplorerRootsCache;let r=(await k0()).pinnedExplorerRoots??{};Object.keys(r).length===0&&Object.keys(t).length>0&&(r=(await bo({pinnedExplorerRoots:t,pinnedExplorerRootsOrigin:Qx})).pinnedExplorerRoots??t),ct.getState().syncPinnedExplorerRoots(r)})().finally(()=>{jf=null}),jf)},syncPinnedExplorerRoots:t=>e(()=>{const n={};for(const[r,s]of Object.entries(t)){const i=CA(s);i.length>0&&(n[r]=i.slice(0,12))}return Px(Jy),{pinnedExplorerRootsCache:n,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:t=>e(n=>{const r=new Set(n.expandedPaths);return r.has(t)?r.delete(t):r.add(t),{expandedPaths:r}}),selectFile:t=>e(n=>(N3(n.contextKey,t),{selectedFilePath:t})),toggleShowHiddenFiles:()=>e(t=>{const n=!t.showHiddenFiles;$n(xA,n);const r=new Map(t.projectStateCache);for(const[s,i]of r)r.set(s,{...i,directoryCache:new Map});return{showHiddenFiles:n,directoryCache:new Map,projectStateCache:r}}),toggleGroupByFolder:()=>e(t=>{const n=!t.groupByFolder;return E3(n),{groupByFolder:n}}),setGroupByFolder:t=>e(n=>n.groupByFolder===t?n:(E3(t),{groupByFolder:t})),toggleGroupCollapsed:t=>e(n=>{const r=new Set(n.collapsedGroups);return r.has(t)?r.delete(t):r.add(t),EQ(r),{collapsedGroups:r}}),setDirectoryCache:(t,n)=>e(r=>{const s=new Map(r.directoryCache);return s.set(t,n),{directoryCache:s}}),hydrateFileSortModes:async()=>{if(!ct.getState().fileSortModesHydrated)return Df||(Df=(async()=>{const t=ct.getState().fileSortModes;let r=(await k0()).fileSortModes??{};Object.keys(r).length===0&&Object.keys(t).length>0&&(r=(await bo({fileSortModes:t})).fileSortModes??t),Px(T2),e({fileSortModes:r,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{Df=null}),Df)},setDirectorySortMode:async(t,n)=>{try{await ct.getState().hydrateFileSortModes()}catch{}const r=ct.getState().fileSortModes[t]??"name",s=(Ox.get(t)??0)+1;Ox.set(t,s),e(i=>{const a={...i.fileSortModes};n==="modified"?a[t]=n:delete a[t];const c=new Map(i.directoryCache);return c.delete(t),{fileSortModes:a,fileSortModesHydrated:!0,directoryCache:c}});try{await bo({fileSortMode:{path:t,mode:n}}),Px(T2)}catch{if(Ox.get(t)!==s)return;e(i=>{const a={...i.fileSortModes};r==="modified"?a[t]=r:delete a[t];const c=new Map(i.directoryCache);return c.delete(t),{fileSortModes:a,directoryCache:c}})}},invalidateDirectoryCache:(t,n=!1)=>e(r=>{const s=new Map(r.directoryCache);for(const i of s.keys())(i===t||n&&Pf(t,i))&&s.delete(i);return{directoryCache:s}}),applyFileWatchEvents:t=>e(n=>{if(t.length===0)return n;const r=new Map(n.directoryCache),s=new Map(n.fileChangeVersions);let i=n.selectedFilePath,a=!1,c=!1,u=!1;const f=p=>{s.set(p,(s.get(p)??0)+1),c=!0};for(const p of t){if(p.type==="rescan-required"){for(const C of r.keys())Pf(p.path,C)&&(r.delete(C),a=!0);u=!0,i&&Pf(p.path,i)&&f(i);continue}const g=UQ(p.path),y=r.get(g);if(p.type==="deleted"){if(f(p.path),i&&Pf(p.path,i)&&(i=null,N3(n.rootPath,null)),y){const C=y.filter(L=>L.path!==p.path);C.length!==y.length&&(r.set(g,C),a=!0)}for(const C of r.keys())Pf(p.path,C)&&(r.delete(C),a=!0);continue}f(p.path);const v=GQ(p);if(!v||!y)continue;const S=y.find(C=>C.path===v.path),T=zQ(S?y.map(C=>C.path===v.path?{...C,...v,children:C.children}:C):[...y,v],n.fileSortModes[g]??"name");r.set(g,T),a=!0}return!a&&!c&&!u?n:{directoryCache:a?r:n.directoryCache,selectedFilePath:i,fileChangeVersions:c?s:n.fileChangeVersions,fileWatchEpoch:u?n.fileWatchEpoch+1:n.fileWatchEpoch}}),bumpFileWatchEpoch:()=>e(t=>({fileWatchEpoch:t.fileWatchEpoch+1})),setChangedFiles:t=>e({changedFiles:t}),beginGitBundleLoading:t=>e({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:t}),setGitBundleSlowFor:(t,n)=>e(r=>r.gitBundleLoadingOwner===t?{gitBundleSlow:n}:r),finishGitBundleLoading:t=>e(n=>n.gitBundleLoadingOwner===t?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:n),resetGitBundleLoading:()=>e({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:t=>e({gitBundleError:t}),markGitBundleLoaded:(t=null)=>e({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:t})})),WQ=320,D3="termdock:mobile-keyboard-expanded",j3="termdock:mobile-keyboard-preset-mode",P3="termdock:mobile-long-press-mode";function $x(){return typeof window>"u"?!1:(navigator.maxTouchPoints>0||"ontouchstart"in window)&&window.innerWidth<768}const VQ={retry:{maxRetries:60,initialDelayMs:1e3,maxDelayMs:2e4},connectionTimeoutMs:15e3},qQ=({sessionId:e,mode:t,tmuxSessionName:n=null,terminalSettings:r=Ky(),colorTheme:s="dark",toolbarPresets:i=[],isActive:a=!0,focusRequestToken:c=0,resumeRequestToken:u=0,resumeRequestReason:f="visibility",resumeRequestDelayMs:p=0,forceResumeReconnect:g=!1,initialConnectDelayMs:y=0,initialConnectEnabled:v=!0,resumeRequestEnabled:S=!0,onStreamReadyChange:T,onStreamConnected:C,onViewportReadyChange:L,onKeyboardVisibilityChange:E,suppressKeyboard:D=!1,keyboardPortalTarget:B=null,sharedMobileKeyboardLayout:F=!1,suppressPageFlipRefresh:j=!1,showDebug:A,onStatusChange:H})=>{const{t:Q}=qn(),[K,W]=M.useState(r.fontSize),de=M.useMemo(()=>gO(),[]),X=M.useMemo(()=>od("session"),[]),pe=M.useMemo(()=>od("keyboard"),[]),ve=M.useRef(p);ve.current=p;const Ae=M.useRef(null);M.useEffect(()=>{W(r.fontSize)},[r.fontSize]);const ie=M.useMemo(()=>({...r,fontSize:K}),[r,K]),[V]=M.useState(e||gE()),[z,ce]=M.useState($x),[ge,he]=M.useState(!1),[Ce,xe]=M.useState(!1),[ae,_e]=M.useState(!1),[Z,Ze]=M.useState(()=>typeof document>"u"?!0:!document.hidden),[at,He]=M.useState(()=>typeof document>"u"?!0:document.hasFocus()),[be,Be]=M.useState(!1),{isOpen:fe,keyboardHeight:Ke}=dA({enabled:z&&a}),[Ye,tt]=M.useState(null),[q,ue]=M.useState(null),[Xe,Ne]=M.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(D3)==="true"),[ze,Fe]=M.useState(()=>{if(typeof window>"u")return"auto";const De=window.localStorage.getItem(j3);return De&&De.length>0?De:"auto"}),[ft,ot]=M.useState(()=>typeof window>"u"?"arrows":window.localStorage.getItem(P3)==="copy"?"copy":"arrows"),[Dt,wt]=M.useState("idle"),[Gt,Jt]=M.useState("idle"),[ln,Hn]=M.useState(0),we=ns(De=>De.sessions.get(V)),{setTerminalSession:dt,setConnecting:xt,appendToBuffer:Vt,replaceBuffer:ht,clearTerminalSession:$t,removeTerminalSession:ut,clearBuffer:Ge,setSessionActiveProgram:Jn,setSessionCwd:An,setSessionCopyMode:We,setSessionAgentStatus:En,setSessionShellTitle:Et,setSessionPromptState:yr,clearAgentNeedsReview:Qn}=ns.getState(),Tn=M.useMemo(()=>`wt-${V.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,12)}`,[V]),_r=we?.terminalSessionId??null,mr=we?.mode??"shell",jr=we?.activeProgram??null,Lr=M.useMemo(()=>h0(i),[i]),Se=mr==="tmux",te=we?.bufferChunks??[],Mt=we?.isConnecting??!1,Ee=_r,an=M.useCallback(async De=>{const gt=IF(De,we?.cwd||we?.directory);if(!gt)return;let vt=gt,it="directory";try{vt=(await Ny(gt)).path}catch(Tt){if(!(Tt instanceof Error)||Tt.message!=="Path is not a directory")return;it="file"}try{const Tt=ct.getState();Tt.setRightTab("files"),Tt.openRight(),window.dispatchEvent(new CustomEvent(x2,{detail:{path:vt,kind:it}}))}catch{}},[we?.cwd,we?.directory]),Qt=t??we?.mode??"shell",It=Qt==="tmux"?n??we?.tmuxSessionName??null:null,[en,dn]=M.useState(null),tr=M.useRef(!1),[Oe,mt]=M.useState(!1),[cn,tn]=M.useState(!1),[kn,Cn]=M.useState(null),[Nt,Ln]=M.useState(0),[Kn,un]=M.useState(null),nr=A!==void 0?A:!1,Zt=M.useRef(null),Tr=M.useRef(null),wn=M.useRef(null),Wr=M.useRef(null),rt=M.useRef(null),Bt=M.useRef(!1),$e=M.useRef(null),st=M.useRef([]),qt=M.useRef(0),Ht=M.useRef(!1),bn=M.useRef(null),Ie=M.useRef(null),et=M.useRef(-1),At=M.useRef(null),nn=M.useRef(0),Zn=M.useRef(null),fn=M.useRef(null),mn=M.useRef(0),Kt=M.useRef(a);Kt.current=a;const Yn=M.useRef(z),ir=M.useRef(null),_n=M.useRef(null),wr=M.useRef(null),Jr=M.useRef(null),er=M.useRef(null),fr=M.useRef(null),Nr=M.useRef(null),re=M.useCallback(()=>{Jr.current=null;const De=wr.current;wr.current=null,De&&Et(De.sessionId,De.title)},[Et]),Le=M.useCallback((De,gt)=>{if(wr.current={sessionId:De,title:gt},Jr.current===null){if(typeof window>"u"){re();return}Jr.current=window.requestAnimationFrame(re)}},[re]),Qe=M.useCallback(()=>{Jr.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(Jr.current),Jr.current=null,wr.current=null},[]),je=M.useCallback(async()=>{const De=Qt;return(await BS({preferredFrontendSessionId:V,mode:De,tmuxSessionName:De==="tmux"?It||Tn:void 0,termType:"xterm-256color",requireExisting:!0})).terminalSession},[Qt,It,Tn,V]),bt=M.useRef(!1);M.useEffect(()=>{if(!a){rt.current?.blur(),bt.current=!1;return}if(bt.current||(bt.current=!0,!KB(z,j)))return;const De=rt.current?.getDimensions()??null;let gt=0,vt=0;gt=requestAnimationFrame(()=>{vt=requestAnimationFrame(()=>{rt.current?.requestRefresh("page-flip",{reconcileServerSize:!0,skipScrollToBottom:!0})})});const it=window.setTimeout(()=>{const Tt=rt.current,Gn=Tt?.getDimensions()??null;Tt?.requestRefresh("page-flip",{forceRedraw:K8(De,Gn),reconcileServerSize:!0})},360);return()=>{cancelAnimationFrame(gt),cancelAnimationFrame(vt),window.clearTimeout(it)}},[a,z,j,Ee]),M.useEffect(()=>{Yn.current=z},[z]);const yt=M.useCallback(()=>{Kt.current&&rt.current?.focus()},[]),Ut=M.useCallback(De=>{typeof window>"u"||typeof document>"u"||!Kt.current||Yn.current||document.hidden||(ir.current!==null&&window.clearTimeout(ir.current),ir.current=window.setTimeout(()=>{if(ir.current=null,!Kt.current||Yn.current||document.hidden)return;const gt=document.activeElement,vt=gt?.getAttribute("data-terminal-input-anchor")==="true";if((gt instanceof HTMLInputElement||gt instanceof HTMLTextAreaElement||gt instanceof HTMLSelectElement||gt?.isContentEditable===!0)&&!vt){pe("desktop resume focus skipped: editable active",{reason:De});return}pe("desktop resume focus",{reason:De}),rt.current?.requestRefresh("focus",{force:!0,forceRedraw:!0,skipResizePush:!0,skipScrollToBottom:!0}),rt.current?.focus()},50))},[pe]);M.useEffect(()=>()=>{ir.current!==null&&typeof window<"u"&&window.clearTimeout(ir.current),ir.current=null,_n.current!==null&&typeof window<"u"&&window.clearTimeout(_n.current),_n.current=null,er.current!==null&&typeof window<"u"&&window.clearTimeout(er.current),er.current=null,fr.current!==null&&typeof window<"u"&&window.clearTimeout(fr.current),fr.current=null},[]),M.useEffect(()=>{if(typeof document>"u"||typeof window>"u")return;const De=()=>{_n.current!==null&&window.clearTimeout(_n.current),_n.current=window.setTimeout(()=>{_n.current=null;const gt=document.activeElement,it=!(gt?.getAttribute("data-terminal-input-anchor")==="true")&&!!(gt&&(gt instanceof HTMLInputElement||gt instanceof HTMLTextAreaElement||gt instanceof HTMLSelectElement||gt.isContentEditable));hO({isActive:Kt.current,isMobile:Yn.current,documentVisible:!document.hidden,activeElementIsEditable:it})&&yt()},0)};return document.addEventListener("pointerup",De),()=>{document.removeEventListener("pointerup",De),_n.current!==null&&(window.clearTimeout(_n.current),_n.current=null)}},[yt]);const Yt=M.useCallback(()=>{vr.current=!1,Ln(De=>De+1)},[]),rn=M.useCallback((De,gt)=>{const vt=wn.current,it=Date.now();if(vt&>&&JE(vt)){Ae.current={startedAt:it,strategy:"reconnect",reason:De},Oa("info","PWA_RESUME terminal-start",{frontendSessionId:V,backendSessionId:vt,strategy:"reconnect",reason:De,active:Kt.current});return}if(vt&&ZE(vt,()=>{const Tt=Ae.current;Oa("info","PWA_RESUME terminal-responsive",{frontendSessionId:V,backendSessionId:vt,durationMs:Tt?Date.now()-Tt.startedAt:null,strategy:Tt?.strategy??"probe",reason:Tt?.reason??De}),Ae.current=null,C?.(V)})){Ae.current={startedAt:it,strategy:"probe",reason:De},Oa("info","PWA_RESUME terminal-start",{frontendSessionId:V,backendSessionId:vt,strategy:"probe",reason:De,active:Kt.current}),X("[Terminal] resume probe sent",{reason:De,backendSessionId:vt,active:Kt.current});return}X("[Terminal] resume probe missing connection, restarting ensureSession",{reason:De,backendSessionId:vt,active:Kt.current}),Yt()},[X,C,Yt,V]),pn=M.useCallback((De,gt)=>{const vt=wn.current;vt&&$e.current!==De&&($e.current=De,B5(vt,De,gt),X("[Terminal] flow-control state sent",{backendSessionId:vt,paused:De,reason:gt}))},[X]),Mn=M.useCallback((De,gt)=>{const vt=wn.current;vt&&Zn.current!==De&&(Zn.current=De,D5(vt,De,gt),X("[Terminal] focus state sent",{backendSessionId:vt,focused:De,reason:gt}))},[X]),Vn=M.useCallback((De,gt)=>{const vt=wn.current;vt&&fn.current!==De&&(fn.current=De,j5(vt,De,gt),X("[Terminal] viewing state sent",{backendSessionId:vt,viewing:De,reason:gt}))},[X]),hr=dO({isActive:a,viewportFocused:ae,documentVisible:Z,windowFocused:at,streamReady:be}),xn=fO({isActive:a,documentVisible:Z,windowFocused:at,streamReady:be,isDesktop:Li()!==null}),Pr=M.useRef(hr),Cr=M.useRef(xn);M.useEffect(()=>{Pr.current=hr,Mn(hr,"logical-focus-change")},[hr,Mn,Ee]),M.useEffect(()=>{Cr.current=xn,Vn(xn,"logical-viewing-change")},[xn,Vn,Ee]),M.useEffect(()=>{const De=gt=>{const it=gt.detail;typeof it=="number"&&it>=8&&it<=32&&W(it)};return document.addEventListener("termfontchange",De),()=>document.removeEventListener("termfontchange",De)},[]),M.useEffect(()=>{const De=()=>{const Tt=!document.hidden;Ze(Tt),Tt&&a&&Ut("visibility")},gt=Tt=>{a&&Ut(Tt.persisted?"bfcache":"pageshow")},vt=()=>{He(!0),Ut("window-focus")},it=()=>He(!1);return document.addEventListener("visibilitychange",De),window.addEventListener("pageshow",gt),window.addEventListener("focus",vt),window.addEventListener("blur",it),()=>{document.removeEventListener("visibilitychange",De),window.removeEventListener("pageshow",gt),window.removeEventListener("focus",vt),window.removeEventListener("blur",it)}},[a,Ut]),M.useEffect(()=>{if(!u||!S||!ar.current)return;const De=ve.current,gt=()=>{rt.current?.requestRefresh(f),rn(De>0?"global-resume-background":"global-resume-visible",De<=0&&g)};if(De<=0){gt();return}const vt=window.setTimeout(gt,De);return()=>window.clearTimeout(vt)},[u,f,S,g,rn]);const hn=M.useRef(0);M.useEffect(()=>{if(be){hn.current=0;return}if(!Oe||en==="Authentication required"||en===jx)return;const De=hn.current,gt=Math.min(2e3*Math.pow(2,Math.min(De,4)),3e4),vt=setTimeout(()=>{hn.current+=1,X("[Terminal] fatal self-heal: auto restarting ensureSession",{attempt:hn.current,backendSessionId:wn.current}),dn("Reconnecting..."),mt(!1),Yt()},gt);return()=>clearTimeout(vt)},[en,Oe,be,Nt,X,Yt]),M.useEffect(()=>{if(typeof window>"u"){he(!1);return}const De=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;he(De)},[]),M.useEffect(()=>{(!a||!z)&&xe(!1),a||_e(!1)},[a,z]),M.useEffect(()=>{wn.current=Ee,et.current=-1,Zn.current=null,fn.current=null,$e.current=null},[Ee]),M.useEffect(()=>{T?.(V,be)},[be,T,V]),M.useEffect(()=>{Se||(Ht.current=!1,bn.current=null,Ie.current&&(clearTimeout(Ie.current),Ie.current=null))},[Se]),M.useEffect(()=>{Ee&&rt.current?.requestRefresh("session-key-change",{force:!0})},[Ee]),M.useEffect(()=>{const De=a&&z&&fe;pe("visibility signal",{sessionId:V,isActive:a,isMobile:z,isInputFocused:Ce,isViewportKeyboardOpen:fe,viewportKeyboardHeight:Ke,visible:De}),E?.(V,De)},[E,V,a,z,fe,Ke,pe]),M.useEffect(()=>{a&&c&&c!==nn.current&&(nn.current=c,yt())},[c,yt,a]),M.useEffect(()=>{Wr.current=V},[V]),M.useEffect(()=>{!z&&(Ye!==null||q!==null)&&(tt(null),ue(null),At.current=null)},[z,Ye,q]),M.useEffect(()=>{!Ee&&(Ye!==null||q!==null)&&(tt(null),ue(null),At.current=null)},[Ee,Ye,q]),M.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(D3,Xe?"true":"false")},[Xe]),M.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(j3,ze)},[ze]),M.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(P3,ft)},[ft]),M.useEffect(()=>{ce($x());const De=()=>{ce($x())};return window.addEventListener("resize",De),()=>window.removeEventListener("resize",De)},[]);const Ft=M.useCallback(()=>{mn.current+=1,re(),Qe();const De=Zt.current;Zt.current=null,Tr.current=null,Be(!1),rt.current?.setSessionReady(!1);const gt=wn.current;gt&&B5(gt,!1,"stream-disconnect"),Bt.current=!1,$e.current=null,st.current=[],De?.()},[Qe,re]),gr=M.useCallback(De=>{if(Tr.current===De){X(`[startStream] Skipping - already connected to ${De}`);return}X(`[startStream] Starting stream for frontendSessionId=${V} backendSessionId=${De}`),Cn(null),Ft();const gt=mn.current+1;mn.current=gt;const vt=de.connect(De,{onEvent:it=>{if(mn.current!==gt)return;const Tt=V;if(Tt)switch(it.type){case"connected":{const Gn=Ae.current;Gn&&(Oa("info","PWA_RESUME terminal-connected",{frontendSessionId:Tt,backendSessionId:wn.current,durationMs:Date.now()-Gn.startedAt,strategy:Gn.strategy,reason:Gn.reason}),Ae.current=null),C?.(Tt),(it.runtime||it.ptyBackend)&&X(`[Terminal] connected frontendSessionId=${Tt} backendSessionId=${wn.current} runtime=${it.runtime??"unknown"} pty=${it.ptyBackend??"unknown"} cwd=${it.cwd??"unknown"}`),xt(Tt,!1),dn(null),mt(!1),Cn(null),Be(!0),wn.current&&(D5(wn.current,Pr.current,"stream-connected"),j5(wn.current,Cr.current,"stream-connected")),rt.current?.setSessionReady(!0),$e.current=null,pn(Bt.current,"stream-connected"),it.tuiProgress!==void 0&&ns.getState().setSessionTuiProgress(Tt,it.tuiProgress??null),it.shellTitle!==void 0&&ns.getState().setSessionShellTitle(Tt,it.shellTitle??null),it.promptState!==void 0&&it.promptState!==null&&ns.getState().setSessionPromptState(Tt,it.promptState);const cr=ns.getState().getTerminalSession(Tt);if(cr?.terminalSessionId&&it.mode&&ns.getState().setTerminalSession(Tt,{sessionId:cr.terminalSessionId,cols:80,rows:24,mode:it.mode,tmuxSessionName:it.tmuxSessionName??null,cwd:it.cwd??null}),it.activeProgram!==void 0&&Jn(Tt,it.activeProgram??null,it.activeProgramSource??null,it.activeProgramRaw??null),requestAnimationFrame(()=>{requestAnimationFrame(()=>{rt.current?.requestRefresh("connected",{force:!0,forceRedraw:!0,reconcileServerSize:Kt.current})})}),typeof window<"u"&&Kt.current&&Yn.current&&(window.setTimeout(()=>{rt.current?.requestRefresh("connected",{force:!0,forceRedraw:!0,reconcileServerSize:Kt.current})},120),window.setTimeout(()=>{rt.current?.requestRefresh("connected",{force:!0,forceRedraw:!0,reconcileServerSize:Kt.current})},360)),it.mode!=="tmux"&&(un(null),We(Tt,!1)),X("[Terminal] Connected event received:",{frontendSessionId:Tt,backendSessionId:wn.current,storeHasState:!!cr,storeTerminalId:cr?.terminalSessionId,hasHistoryInStore:!!cr?.history?.length,historyLength:cr?.history?.length??0}),cr?.history&&cr.history.length>0){X(`[Terminal] Restoring ${cr.history.length} history chunks to frontend session ${Tt}`);const Kr=cr.history.reduce((ms,_t)=>ms+_t.length,0),xr=Math.max(300,Math.min(2e3,Math.ceil(Kr/200)));qt.current=Date.now()+xr,cr.history.forEach(ms=>{Vt(Tt,ms,{markActivity:!1})}),ns.getState().setSessionHistory(Tt,[]),X(`[Terminal] History restoration complete for ${Tt}`)}else X(`[Terminal] No history to restore for ${Tt}`);const kr=it.replayChunks;if(kr&&kr.length>0){it.replayOutOfWindow?(X(`[Terminal] Replay out-of-window, clearing buffer before replay (${kr.length} chunks)`),Ge(Tt),rt.current?.clear()):X(`[Terminal] Replay incremental: ${kr.length} chunks`);const Kr=kr.reduce((ms,_t)=>ms+_t.length,0),xr=Math.max(200,Math.min(1500,Math.ceil(Kr/200)));qt.current=Math.max(qt.current,Date.now()+xr);for(const ms of kr)Vt(Tt,ms)}break}case"reconnecting":{Cn(Gn=>Gn??Date.now()),dn("Reconnecting..."),mt(!1);break}case"data":{it.data&&(Bt.current?st.current.push(it.data):Vt(Tt,it.data));break}case"tmux-layout":{un(it.layout??null),it.layout&&We(Tt,it.layout.inCopyMode);break}case"tmux-screen-sync":{const Gn=it.generation??0;if(Gn<et.current)break;et.current=Gn,st.current=[],rt.current?.clear(),ht(Tt,it.chunks??[]),typeof it.cols=="number"&&typeof it.rows=="number"&&rt.current?.notifyServerSize(it.cols,it.rows,"tmux-screen-sync");break}case"active-program":{Jn(Tt,it.activeProgram??null,it.activeProgramSource??null,it.activeProgramRaw??null);break}case"cwd":{An(Tt,it.cwd??null);break}case"agent-status":{En(Tt,{agentStatus:it.agentStatus??null,agentIndicator:it.agentIndicator??null,agentStatusDetail:it.agentStatusDetail??null,agent:it.agent??null,agentMessage:it.agentMessage??null,agentNativeSessionId:it.agentNativeSessionId??null,agentResumeRecovered:it.agentResumeRecovered===!0,agentRich:it.agentRich===!0,agentActivity:it.agentActivity??0,agentCwd:it.agentCwd??null,reviewed:it.reviewed??null});break}case"git-status":{ns.getState().setSessionGitStatus(Tt,it.gitStatus??null);break}case"focus-mode":{X("[Terminal] focus tracking mode",{backendSessionId:wn.current,requested:it.focusTrackingRequested===!0});break}case"pty-size":{typeof it.cols=="number"&&typeof it.rows=="number"&&rt.current?.notifyServerSize(it.cols,it.rows,it.source);break}case"shell-title":{Le(Tt,it.title??null);break}case"prompt-state":{yr(Tt,it.state??"idle",it.exitCode??null);break}case"tui-progress":{ns.getState().setSessionTuiProgress(Tt,it.tuiProgress??null);break}case"exit":{const Gn=typeof it.exitCode=="number"?it.exitCode:null,cr=typeof it.signal=="number"?it.signal:null;Vt(Tt,`\r
|
|
77
77
|
[Process exited${Gn!==null?` with code ${Gn}`:""}${cr!==null?` (signal ${cr})`:""}]\r
|
|
78
|
-
`),$t(Tt),xt(Tt,!1),dn("Terminal session ended"),Be(!1),mt(!1),Cn(null),un(null),We(Tt,!1),Ft();break}}},onError:(it,Tt)=>{if(mn.current!==gt)return;const Gn=V;if(!Gn)return;const cr=Tt&&it.message==="Authentication required",kr=uQ(it),Kr=cr?it.message:kr||Tt?"Reconnecting...":it.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${Tt}):`,Kr),kr&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:wn.current,frontendSessionId:Gn,isActive:a,isMobile:z,fatal:Tt,stack:new Error().stack}),dn(Kr),mt(!!Tt),Tt&&(Cn(null),xt(Gn,!1),Ft(),kr&&(X("[onError] Session lost, auto-recreating"),dn("Reconnecting..."),mt(!1),$t(Gn),Ge(Gn),wn.current=null,vr.current=!1,Yt()))}},VQ);Zt.current=()=>{vt.close(),mn.current===gt&&(Tr.current=null)},Tr.current=De},[Vt,Ge,$t,X,Ft,C,pn,Yt,Le,xt,Jn,En,We,An,yr,de,V]);M.useEffect(()=>{const De=oQ({isActive:a,isStreamReady:be,reconnectStartedAt:kn,now:Date.now()});if(De===null)return;const gt=window.setTimeout(()=>{X("[Terminal] visible reconnect watchdog expired",{backendSessionId:wn.current,reconnectStartedAt:kn}),Ft(),xt(V,!1),dn("Reconnecting..."),mt(!1),Cn(Date.now()),Yt()},De);return()=>window.clearTimeout(gt)},[X,Ft,a,be,kn,Yt,V,xt]);const vr=M.useRef(!1),ar=M.useRef(!1),zr=M.useRef(0);M.useEffect(()=>()=>{zr.current+=1,vr.current=!1,Ft()},[Ft]);const Fn=M.useRef(Qt),pr=M.useRef(It);M.useEffect(()=>{const De=Fn.current,gt=pr.current;Fn.current=Qt,pr.current=It,Wr.current===V&&(De===Qt&>===It||(vr.current=!1,Ft(),Ln(vt=>vt+1)))},[Qt,It,Ft,V]),M.useEffect(()=>{if(Wr.current!==V&&(X(`[useEffect] sessionId changed from ${Wr.current} to ${V}, allowing reinitialization`),vr.current=!1,ar.current=!1),vr.current&&Wr.current===V){X(`[useEffect] Already initialized for sessionId=${V}, skipping`);return}const De=async Gn=>{if(X(`[ensureSession] Starting for sessionId=${V}, runId=${Gn}`),!Wr.current||Wr.current!==V){X(`[ensureSession] SessionId mismatch or stale run (current=${Wr.current}, target=${V}), skipping`);return}if(Gn!==zr.current){X(`[ensureSession] Stale run detected (runId=${Gn}, currentRunId=${zr.current}), skipping`);return}const cr=ns.getState(),kr=cr.getTerminalSession(V),Kr=kr?.mode??Qt;X("[ensureSession] Current state from store:",{terminalSessionId:kr?.terminalSessionId,mode:kr?.mode,tmuxSessionName:kr?.tmuxSessionName,isConnecting:kr?.isConnecting});let xr=kr?.terminalSessionId??null,ms=!xr;if(xr&&Kr!==Qt?(X(`[ensureSession] Store mode mismatch for ${xr}: current=${Kr} desired=${Qt}, will create new session`),ms=!0,cr.clearTerminalSession(V),xr=null):xr&&Qt==="tmux"&&It&&kr?.tmuxSessionName!==It&&(X(`[ensureSession] Store tmux name mismatch for ${xr}: current=${kr?.tmuxSessionName} desired=${It}, will create new session`),ms=!0,cr.clearTerminalSession(V),xr=null),xr&&de.checkHealth&&!Kt.current){X(`[ensureSession] Checking health of existing session ${xr}`);try{const _t=await de.checkHealth(xr);if(X("[ensureSession] Health check result:",_t),!_t.healthy)X(`[ensureSession] Session ${xr} is NOT healthy (healthy=${_t.healthy}), will create new session`),X("[ensureSession] Health check details:",_t),ms=!0,_t.mode&&kr?.terminalSessionId&&cr.setTerminalSession(V,{sessionId:kr.terminalSessionId,cols:80,rows:24,mode:_t.mode,tmuxSessionName:_t.tmuxSessionName??null}),cr.clearTerminalSession(V),X("[ensureSession] Cleared unhealthy session from store");else{X(`[ensureSession] Session ${xr} is healthy, reusing it, cwd=${_t.cwd}, clients=${_t.clients}, lastActivity=${Date.now()-(_t.lastActivity||0)}ms ago`),_t.mode&&kr?.terminalSessionId&&cr.setTerminalSession(V,{sessionId:kr.terminalSessionId,cols:80,rows:24,mode:_t.mode,tmuxSessionName:_t.tmuxSessionName??null}),X(`[ensureSession] Setting terminalIdRef to ${xr} and starting stream`),wn.current=xr,gr(xr),X(`[ensureSession] Successfully reused healthy session ${xr}, returning early`);return}}catch(_t){X(`[ensureSession] Failed to check health of session ${xr}:`,_t),X("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(X(`[ensureSession] Decision: shouldCreateNewSession=${ms}, terminalId=${xr}`),ms){X(`[ensureSession] Creating new session, shouldCreateNewSession=${ms}, runId=${Gn}`),dn(null),mt(!1),cr.setConnecting(V,!0);const Oo=ns.getState().getTerminalSession(V),aa=(Oo?.mode??Qt)===Qt&&(Qt!=="tmux"||!It||Oo?.tmuxSessionName===It);if(Oo?.terminalSessionId&&aa)X(`[ensureSession] Race condition avoided: another instance already created session ${Oo.terminalSessionId}`),cr.setConnecting(V,!1),xr=Oo.terminalSessionId,ms=!1;else try{const as=await je();if(X(`[ensureSession] Opened managed backend session ${as.sessionId}`),Gn!==zr.current){X(`[ensureSession] Stale run after session creation (runId=${Gn}, currentRunId=${zr.current}), leaving ${as.sessionId} for sibling`);return}cr.setTerminalSession(V,as),X(`[ensureSession] Updated store with new session ${as.sessionId}`),xr=as.sessionId}catch(as){if(Gn!==zr.current){X("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(as instanceof Va&&C3(as)){X("[ensureSession] Confirmed missing persisted session:",{sessionId:V,error:as.message}),cr.clearTerminalSession(V),dn(jx),mt(!0),cr.setConnecting(V,!1);return}dn("Reconnecting..."),mt(!0),cr.setConnecting(V,!1);return}}if(Gn!==zr.current){X(`[ensureSession] Stale run before starting stream (runId=${Gn}, currentRunId=${zr.current}), skipping`);return}if(!xr){X(`[ensureSession] No terminalId, terminalId=${xr}`);return}X(`[ensureSession] Starting stream for session ${xr}`),wn.current=xr,gr(xr),X(`[ensureSession] ensureSession completed for sessionId=${V}, terminalId=${xr}`)};let gt=null,vt=null;const it=()=>{vt=null,!(vr.current&&Wr.current===V)&&(X(`[useEffect] Running ensureSession for sessionId=${V}, hasInitialized=${vr.current}`),vr.current=!0,ar.current=!0,gt=++zr.current,De(gt))};if(!v&&!ar.current){X(`[useEffect] Holding background connection until the selected session is ready: ${V}`);return}const Tt=ar.current?0:Math.max(0,y);return Tt>0?(X(`[useEffect] Delaying initial connection for sessionId=${V} by ${Tt}ms`),vt=window.setTimeout(it,Tt)):it(),()=>{vt!==null&&window.clearTimeout(vt),X(`[useEffect] Cleanup for sessionId=${V}, runId=${gt??"pending"}`)}},[V,Nt,gr,Ft,de,X,Qt,It,Tn,y,v]);const lr=M.useCallback(async()=>{if(V&&!cn){tn(!0),dn(null),mt(!1),Cn(null),Ft();try{de.forceKill&&await de.forceKill({sessionId:V})}catch{}ut(V),Ge(V),rt.current?.clear(),await new Promise(De=>setTimeout(De,100));try{xt(V,!0);const De=await je();dt(V,De),wn.current=De.sessionId,gr(De.sessionId)}catch(De){dn(De instanceof Va&&C3(De)?jx:"Reconnecting..."),mt(!0),xt(V,!1)}finally{tn(!1)}}},[V,cn,Ft,de,ut,Ge,xt,dt,gr,je]),Hs=M.useCallback((De,gt)=>{if(!Kt.current||!De)return;const vt=wO(De),it=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(De);if(Se&&it&&(Ht.current=!0),Date.now()<qt.current)return;let Tt=De,Gn=gt?.consumeModifier??!1;if(!gt?.skipModifierTransform&&Ye&&De.length>0){const Kr=De[0];if(Kr.length===1&&/[a-zA-Z]/.test(Kr)){const xr=Kr.toUpperCase();Ye==="ctrl"?(Tt=String.fromCharCode(xr.charCodeAt(0)&31),Gn=!0):Ye==="alt"&&(Tt=`\x1B${De}`,Gn=!0)}Gn||(Ye==="alt"&&(Tt=`\x1B${De}`),Gn=!0)}const cr=wn.current;if(!cr)return;(async()=>{try{if(Se&&!vt&&Ht.current&&de.tmuxAction){Ht.current=!1;try{await de.tmuxAction(cr,{action:"copy-mode",enabled:!1})}catch{}if(SO(Tt))return}await de.sendInput(cr,Tt),Qn(V)}catch(Kr){dn(Kr instanceof Error?Kr.message:"Failed to send input")}})(),Gn&&(q||tt(null),yt())},[Ye,Qn,yt,Se,q,de]);M.useEffect(()=>{const De=gt=>{if(!Kt.current)return;const vt=gt,it=vt.detail?.text;if(!it)return;const Tt=vt.detail?.nonce;if(tr.current){Tt&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Tt,ok:!1}}));return}rt.current?.sendSequence(it,{paste:vt.detail?.paste}),Tt&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Tt,ok:!0}})),pO(Yn.current,vt.detail?.focus!==!1)&&yt()};return window.addEventListener("termdock-insert-reference",De),()=>window.removeEventListener("termdock-insert-reference",De)},[yt]);const Er=M.useCallback((De,gt)=>{const vt=wn.current;if(!vt){pe("xterm resize push skipped: no terminalId",{cols:De,rows:gt});return}pe("xterm resize push",{cols:De,rows:gt}),de.resize({sessionId:vt,cols:De,rows:gt}).catch(it=>{it&&/session not found/i.test(String(it.message||it))&&console.warn("[Terminal] resize 404 session not found",{sessionId:vt,cols:De,rows:gt,stack:new Error().stack})})},[de,pe]),os=M.useCallback(async De=>{const gt=wn.current;if(!(!gt||!de.tmuxAction))try{const vt=await de.tmuxAction(gt,De);vt.layout&&(un(vt.layout),De.action==="switch-session"&&(dt(V,{sessionId:gt,cols:80,rows:24,mode:"tmux",tmuxSessionName:vt.layout.sessionName}),Cm(V,{tmuxSessionName:vt.layout.sessionName}).catch(it=>{console.warn("[Terminal] failed to update inventory after tmux switch",it)})))}catch(vt){dn(vt instanceof Error?vt.message:"Failed to execute tmux action")}},[V,dt,de]);M.useEffect(()=>{if(!Kn||!Ee)return;const gt=Kn.windows.find(vt=>vt.id===Kn.activeWindowId)?.panes.find(vt=>vt.id===Kn.activePaneId);gt&&rt.current?.requestRefresh("tmux-layout",{candidateSize:{cols:gt.width,rows:gt.height},skipScrollToBottom:!0,dedupeKey:`${Ee}:${Kn.sessionId}:${gt.id}:${gt.width}x${gt.height}`})},[Kn,Ee]);const ui=M.useCallback((De,gt=5)=>{const vt=Math.max(1,Math.min(Math.floor(gt)||1,40));Ht.current=!0;const it=bn.current;if(it&&it.direction===De){it.lines+=vt;return}it&&os({action:"scroll",direction:it.direction,lines:it.lines}).finally(()=>{yt()}),bn.current={direction:De,lines:vt},Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{const Tt=bn.current;Tt&&(bn.current=null,os({action:"scroll",direction:Tt.direction,lines:Tt.lines}).finally(()=>{yt()}))},0)},[yt,os]),ra=M.useCallback(De=>{const gt=Date.now(),vt=At.current,it=vt!==null&&vt.modifier===De&>-vt.timestamp<=WQ;if(At.current={modifier:De,timestamp:gt},q===De){ue(null),tt(null);return}if(it){ue(De),tt(De);return}q!==null&&q!==De&&ue(null),tt(Tt=>Tt===De?null:De)},[q]),es=M.useCallback(De=>{if(_e(De&&Kt.current),pe("input focus changed",{focused:De,isActive:Kt.current,isMobile:Yn.current}),!Yn.current||!Kt.current){xe(!1);return}xe(gt=>gt===De?gt:De)},[pe]),Ps=M.useCallback(De=>{if(Bt.current=De,pn(De,"viewport-watermark"),!De&&st.current.length>0){const gt=V;if(gt){const vt=st.current;st.current=[];for(const it of vt)Vt(gt,it)}}},[Vt,pn,V]),Xi=M.useCallback(De=>{Kt.current&&rt.current?.ensureSizeMatches(De)},[]),Ii=M.useRef(null);M.useEffect(()=>{if(!a)return;const De=Ii.current;if(!De)return;const gt=()=>Xi("pointerdown"),vt=()=>Xi("keydown"),it=()=>Xi("touchstart"),Tt=()=>Xi("wheel");return De.addEventListener("pointerdown",gt),De.addEventListener("keydown",vt),De.addEventListener("touchstart",it,{passive:!0}),De.addEventListener("wheel",Tt,{passive:!0}),()=>{De.removeEventListener("pointerdown",gt),De.removeEventListener("keydown",vt),De.removeEventListener("touchstart",it),De.removeEventListener("wheel",Tt)}},[a,Xi]);const qs=M.useCallback(De=>{rt.current=De},[]),Bs=M.useCallback(De=>{L?.(V,De)},[L,V]),So=M.useCallback(De=>{const gt=MO(De);if(!gt)return;const vt=Ye!==null;rt.current?.sendSequence(gt,{consumeModifier:vt})},[Ye]),vi=M.useCallback(De=>{const gt=LO(De);if(gt.length===0)return;const vt=Ye!==null;rt.current?.sendSequence(y3(gt[0]),{consumeModifier:vt});for(let it=1;it<gt.length;it+=1){const Tt=gt[it];window.setTimeout(()=>{rt.current?.sendSequence(y3(Tt))},_O*it)}},[Ye]),ws=M.useCallback(()=>{rt.current?.pasteClipboardText()},[]),Ir=M.useCallback(De=>{fr.current!==null&&(window.clearTimeout(fr.current),fr.current=null),Jt(De),(De==="inserted"||De==="failed")&&(fr.current=window.setTimeout(()=>{fr.current=null,Jt("idle")},1400))},[]),ps=M.useCallback(()=>{Ir("idle"),Hn(0),Nr.current?.click()},[Ir]),qr=M.useCallback(De=>{const gt=De.currentTarget.files?.[0];De.currentTarget.value="",gt&&(Hn(0),Ir("uploading"),hA(gt,(vt,it)=>Kb(vt,it,void 0,Hn),vt=>{if(!Kt.current||tr.current)throw new Error("Terminal unavailable");window.dispatchEvent(new CustomEvent("termdock-insert-reference",{detail:{text:fA(vt,null),focus:!0}}))}).then(()=>Ir("inserted"),()=>Ir("failed")))},[Ir]),Ks=Mt||en!==null;tr.current=Ks;const Ys=M.useRef(jr);Ks||(Ys.current=jr);const Bo=Ks?Ys.current:jr,Dn=M.useMemo(()=>EO(Bo,Lr),[Bo,Lr]),Zi=M.useMemo(()=>w3(Lr,ze),[ze,Lr]),Ls=!z&&ze!=="auto"&&Zi.showOnDesktop!==!0?"auto":ze,di=Ls==="auto"?Dn:Ls,Br=M.useMemo(()=>w3(Lr,di),[di,Lr]),Ji=M.useMemo(()=>Br.actions.filter(De=>De.sequence.trim().length>0).map((De,gt)=>({...De,label:b2(De,gt)})),[Br.actions]),Ca=M.useMemo(()=>nA(jr),[jr]),Es=Br.label,Us=M.useMemo(()=>Ls!=="auto"?`Manual preset: ${Br.label}`:Ca?`Auto preset · ${Br.label} (${Ca})`:"Auto preset",[Ca,Ls,Br.label]),ka=M.useCallback(De=>{Fe(De)},[]),sa=M.useCallback(()=>{ot(De=>De==="copy"?"arrows":"copy"),wt("idle")},[]),eo=M.useCallback(()=>{typeof window>"u"||(er.current!==null&&window.clearTimeout(er.current),er.current=window.setTimeout(()=>{er.current=null,wt("idle")},1200))},[]),zl=M.useCallback(De=>{er.current!==null&&typeof window<"u"&&(window.clearTimeout(er.current),er.current=null),wt(De?"copied":"failed"),eo()},[eo]),Is=M.useCallback(De=>{Ne(De)},[]),zs=M.useMemo(()=>z?IO(Lr):RO(Lr),[z,Lr]),Xs=M.useMemo(()=>cO(s),[s]),Fo=M.useMemo(()=>`terminal::${V}`,[V]);M.useEffect(()=>{H?.({isConnecting:Mt,isRestarting:cn,hasError:!!en,sessionId:Ee})},[Mt,cn,en,Ee,H]);const Ao=!Ee||Mt||cn,ia=M.useCallback((De,gt)=>{if(Ao)return;const vt=Math.max(1,Math.min(Math.floor(gt)||1,40));ui(De,vt)},[ui,Ao]);M.useEffect(()=>{if(!a||!z)return;rt.current?.requestRefresh("resize",{skipScrollToBottom:!fe,force:!0})},[a,z,fe,Ke,V]),M.useEffect(()=>{if(!a||!z)return;const De=gt=>{const vt=gt.detail;rt.current?.requestRefresh("resize",{skipScrollToBottom:vt?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",De),()=>{document.removeEventListener("termdock:viewport-keyboard-change",De)}},[a,z,V]);const oa=!D&&(z||Br.showOnDesktop===!0),To=a,Zs=z&&!F?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,Gs=z&&!F?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,si=o.jsx(DO,{visible:oa,interactive:To,presentation:z?"mobile":"desktop-actions",activeModifier:Ye,lockedModifier:q,disabled:Ao,defaultShowExtended:Xe,presetLabel:Es,presetModeLabel:Us,presetMode:Ls,presetOptions:zs,includeAlt:Br.includeAlt,presetRowLayout:Br.rowLayout,extraActions:Ji,onKeyPress:So,onTextPress:vi,onPastePress:z?ws:void 0,onFilePress:z?ps:void 0,fileUploadState:Gt,fileUploadProgress:ln,longPressMode:ft,copyFeedback:Dt,onLongPressModeToggle:sa,onModifierToggle:ra,onPresetSelect:ka,onExpandedChange:Is}),Co=typeof window<"u"&&(navigator.maxTouchPoints>0||"ontouchstart"in window);return o.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:Zs,children:[o.jsx("input",{ref:Nr,type:"file",className:"hidden",onChange:qr}),nr&&o.jsx(jO,{isMobile:z,isInputFocused:Ce,isIOS:ge,isConnecting:Mt,connectionError:en,terminalSessionId:Ee}),o.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:Xs.background,...Gs},children:[o.jsx("div",{ref:Ii,className:"h-full w-full box-border",children:o.jsx(eA,{fallback:o.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[o.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:o.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),o.jsx("span",{className:"text-sm text-muted-foreground",children:Q("terminal.componentFailed")})]})}),children:o.jsx(oO,{ref:qs,sessionKey:Fo,chunks:te,onInput:Hs,onResize:Er,onFlowControl:Ps,onTmuxScroll:Se?ia:void 0,tmuxScrollSensitivity:.38,onDoubleTap:z?()=>{rt.current?.sendSequence(" ")}:void 0,onInputFocusChange:es,onMobileLongPressCopyResult:zl,onReadyChange:Bs,onDirectoryLinkActivate:an,terminalSettings:ie,theme:Xs,enableTouchScroll:z,mobileLongPressMode:ft,autoFocus:!z&&!Co},Fo)})}),o.jsx(BO,{connectionError:en,isFatalError:Oe,isRestarting:cn,isConnecting:Mt,onHardRestart:lr})]}),B?D?null:ci.createPortal(si,B):si]})},KQ=1e3,YQ=2e4,XQ=9e4,ZQ=5e3,Gr={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let Zp=0,w0=null;function JQ(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function _A(){Gr.idleCloseTimer&&(clearTimeout(Gr.idleCloseTimer),Gr.idleCloseTimer=null)}function e$(){_A(),!(Gr.ws&&Gr.ws.readyState===WebSocket.OPEN)&&(Gr.idleCloseTimer=setTimeout(()=>{Gr.idleCloseTimer=null,Gr.listeners.size===0&&t$()},ZQ))}function t$(){if(Gr.ws){try{Gr.ws.close()}catch{}Gr.ws=null}w0&&(clearInterval(w0),w0=null)}function B3(){if(Gr.reconnectTimer)return;const e=Math.min(KQ*Math.pow(2,Gr.reconnectAttempt),YQ);Gr.reconnectAttempt+=1,Gr.reconnectTimer=setTimeout(()=>{Gr.reconnectTimer=null,LA()},e)}function LA(){const e=JQ();if(!e||Gr.ws&&Gr.ws.readyState===WebSocket.OPEN)return;let t;try{t=new WebSocket(e)}catch{B3();return}Gr.ws=t,t.onopen=()=>{Gr.reconnectAttempt=0,Zp=Date.now(),w0||(w0=setInterval(()=>{if(!(!Gr.ws||Gr.ws.readyState!==WebSocket.OPEN)&&Zp>0&&Date.now()-Zp>XQ)try{Gr.ws.close()}catch{}},3e4),w0.unref?.())},t.onmessage=n=>{Zp=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="update-state"){const a=r.state;if(!a||typeof a.status!="string"||typeof a.currentVersion!="string")return;const c={type:"update-state",state:a};for(const u of Gr.listeners)try{u(c)}catch(f){console.error("[clientStateSync] listener threw:",f)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const a={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const c of Gr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const a={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const c of Gr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const a={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const c of Gr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type!=="client-state"||!r.state)return;const s=r.state,i={type:"client-state",clientState:{sessions:Array.isArray(s.sessions)?s.sessions:[],updatedAt:typeof s.updatedAt=="number"?s.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const a of Gr.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}},t.onclose=()=>{Gr.ws===t&&(Gr.ws=null),Gr.listeners.size>0&&B3()},t.onerror=()=>{}}function Ah(e){return Gr.listeners.add(e),_A(),Gr.ws||LA(),()=>{Gr.listeners.delete(e),Gr.listeners.size===0&&e$()}}function EA(e,t,n){const r=e.findIndex(s=>n(s)===t);return r<0?null:e[r+1]?n(e[r+1]):r>0?n(e[r-1]):null}const Hx="termdock-sessions",k2="termdock-active-session",tv="termdock-sessions-cache";function _2(){try{const e=localStorage.getItem(k2);return e&&e.trim().length>0?e:null}catch{return null}}function Kd(e){try{e?localStorage.setItem(k2,e):localStorage.removeItem(k2)}catch{}}function IA(){if(typeof window>"u")return null;try{const e=localStorage.getItem(tv);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function Bu(e){if(!(typeof window>"u"))try{localStorage.setItem(tv,JSON.stringify(e))}catch{}}function F3(){if(!(typeof window>"u"))try{localStorage.removeItem(tv)}catch{}}function RA(e){return e.map(t=>({...t,mode:t.mode==="tmux"?"tmux":"shell",tmuxSessionName:t.tmuxSessionName??null,customName:t.customName===!0}))}function O3(e){return RA(e.map(t=>({sessionId:t.sessionId,name:t.name,customName:t.customName===!0,backendSessionId:t.backendSessionId,mode:t.mode,tmuxSessionName:t.tmuxSessionName,createdAt:t.createdAt,lastActivity:t.lastActivity}))).map((t,n)=>({...t,activeProgram:e[n]?.activeProgram??null,cwd:e[n]?.cwd??null}))}function Q3(e){return e.map(t=>`${t.sessionId}:${t.name}:${t.customName}:${t.backendSessionId}:${t.mode}:${t.tmuxSessionName}:${t.lastActivity}:${t.activeProgram??""}:${t.cwd??""}`).join("|")}function L2(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function n$(){const e=IA()??[];return{sessions:e,activeSessionId:L2(e,_2())}}function r$(){const e=x.useRef(IA()).current,t=x.useRef(_2()).current,[n,r]=x.useState(e??[]),[s,i]=x.useState(null),[a,c]=x.useState(e&&e.length>0?L2(e,t):t),[u,f]=x.useState(e===null),p=x.useRef(!1),g=x.useRef(null),y=x.useRef(e===null),v=x.useRef(0),S=x.useRef(new Set),T=x.useRef(0);x.useEffect(()=>{y.current=u},[u]),x.useEffect(()=>{g.current=a},[a]);const C=x.useCallback(pe=>{const ve=L2(pe,g.current??_2());return c(Ae=>Ae===ve?Ae:ve),Kd(ve),g.current=ve,ve},[]),L=x.useCallback((pe,ve)=>{const Ae=pe.filter(ie=>!S.current.has(ie.sessionId));r(ie=>Q3(ie)===Q3(Ae)?ie:Ae),Bu(Ae),ve?.reconcileActive&&C(Ae)},[C]),E=x.useCallback((pe,ve)=>{const Ae=S.current.size===0?pe:{...pe,clientSessions:pe.clientSessions.filter(ie=>!S.current.has(ie.sessionId))};i(Ae),L(O3(Ae.clientSessions),ve)},[L]),D=x.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(Hx)?(localStorage.removeItem(Hx),F3(),Kd(null),r([]),c(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),B=x.useCallback(async()=>{if(typeof window>"u")return[];const pe=T.current;try{const ve=await lI(),Ae=O3(ve.clientSessions);return pe!==T.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),Ae.filter(ie=>!S.current.has(ie.sessionId))):(E(ve,{reconcileActive:!0}),Ae.length>0?Ae:D())}catch(ve){console.error("Failed to restore sessions from server:",ve);try{return D()}catch(Ae){console.error("Failed to discard legacy local sessions:",Ae)}}finally{f(!1)}return[]},[E,D]),F=x.useCallback(async pe=>{const ve=++T.current,Ae=await BS(pe);return ve===T.current&&(E(Ae.inventory),c(Ae.session.sessionId),Kd(Ae.session.sessionId)),Ae},[E]),j=x.useCallback(async(pe,ve)=>{++T.current,S.current.add(pe),r(Ae=>{const ie=Ae.filter(ce=>ce.sessionId!==pe),V=ve!=null&&ie.some(ce=>ce.sessionId===ve),z=g.current===pe?V?ve:EA(Ae,pe,ce=>ce.sessionId):g.current;return c(z),Kd(z),Bu(ie),ie});try{await uI(pe)}catch(Ae){console.error("Failed to remove session from inventory:",Ae)}},[]),A=x.useCallback(pe=>{const ve=Date.now();r(Ae=>{const ie=Ae.map(V=>V.sessionId===pe?{...V,lastActivity:ve}:V);return Bu(ie),ie})},[]),H=x.useCallback(pe=>{c(pe),Kd(pe)},[]),Q=x.useCallback(async(pe,ve)=>{const Ae=ve.trim();if(!Ae)return;const ie=++T.current;r(V=>{const z=V.map(ce=>ce.sessionId===pe?{...ce,name:Ae,customName:!0}:ce);return Bu(z),z});try{const V=await Cm(pe,{name:Ae,customName:!0});ie===T.current&&E(V)}catch(V){console.error("Failed to rename session in inventory:",V)}},[E]),K=x.useCallback(async pe=>{const ve=++T.current;r(Ae=>{const ie=Ae.map(V=>V.sessionId===pe?{...V,customName:!1}:V);return Bu(ie),ie});try{const Ae=await Cm(pe,{customName:!1});ve===T.current&&E(Ae)}catch(Ae){console.error("Failed to reset session name in inventory:",Ae)}},[E]),W=x.useCallback(async pe=>{const ve=++T.current;r(Ae=>{const ie=new Map(Ae.map(he=>[he.sessionId,he])),V=pe.map(he=>ie.get(he)).filter(he=>he!==void 0),z=new Set(pe),ce=Ae.filter(he=>!z.has(he.sessionId)),ge=[...V,...ce];return Bu(ge),ge});try{const Ae=await cI(pe);ve===T.current&&E(Ae)}catch(Ae){console.error("Failed to reorder sessions in inventory:",Ae)}},[E]),de=x.useCallback(async()=>{++T.current;for(const pe of n)S.current.add(pe.sessionId);r([]),i(null),c(null),Kd(null),F3(),typeof window<"u"&&localStorage.removeItem(Hx);try{await dI()}catch(pe){console.error("Failed to clear session inventory:",pe)}},[n]),X=x.useCallback(async(pe,ve)=>{const Ae=++T.current;r(ie=>{const V=ie.map(z=>z.sessionId===pe?{...z,backendSessionId:ve}:z);return Bu(V),V});try{const ie=await Cm(pe,{backendSessionId:ve});Ae===T.current&&E(ie)}catch(ie){console.error("Failed to update session backend in inventory:",ie)}},[E]);return x.useEffect(()=>{p.current||(p.current=!0,B())},[B]),x.useEffect(()=>Ah(ve=>{if(ve.type!=="client-state"||y.current)return;const Ae=typeof ve.seq=="number"?ve.seq:null;if(Ae!==null){if(Ae<v.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:Ae,latestSeq:v.current});return}v.current=Ae}if(ve.inventory){E(ve.inventory,{reconcileActive:!0});return}const ie=RA(ve.clientState.sessions||[]);L(ie,{reconcileActive:!0})}),[E,L]),{sessions:n,inventory:s,activeSessionId:a,isLoading:u,openSession:F,removeSession:j,updateSessionActivity:A,setActiveSession:H,updateSessionBackendId:X,renameSession:Q,resetSessionCustomName:K,reorderSessions:W,clearAllSessions:de,restoreSessions:B}}const NA=5*6e4,s$=4,i$=3e4;function o$(e){const t=new Set([...e.currentVisibleSessionIds].filter(a=>e.validSessionIds.has(a))),n=e.idleMs??NA,s=Math.max(t.size,e.maxSessions??s$)-t.size;return s===0||[...e.lastVisitedAtBySessionId].filter(([a,c])=>e.validSessionIds.has(a)&&!t.has(a)&&Number.isFinite(c)&&e.now-c<n).sort((a,c)=>c[1]-a[1]).slice(0,s).map(([a])=>a).forEach(a=>t.add(a)),t}const a$="termdock:startup:";function fh(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${a$}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function l$(e,t){e||ci.flushSync(t)}const E2="horizontal";function Bc(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function MA(e,t){if(!Array.isArray(e)||e.length!==t)return Bc(t);const n=e.map(Number);if(n.some(s=>!Number.isFinite(s)||s<=0))return Bc(t);const r=n.reduce((s,i)=>s+i,0);return r<=0?Bc(t):n.map(s=>s/r)}function c$(e){return e==="horizontal"||e==="vertical"||e==="grid"}function u$(e){if(!Array.isArray(e))return[];const t=new Set,n=new Set,r=[];for(const s of e){if(!s||typeof s!="object")continue;const i=s;if(typeof i.id!="string"||!i.id||n.has(i.id))continue;const a=Array.isArray(i.sessionIds)?i.sessionIds.filter(u=>typeof u=="string"&&!!u&&!t.has(u)):[],c=[...new Set(a)];c.length<2||(c.forEach(u=>t.add(u)),n.add(i.id),r.push({id:i.id,...typeof i.name=="string"&&i.name.trim()?{name:i.name.trim().slice(0,80)}:{},sessionIds:c,layout:c$(i.layout)?i.layout:E2,ratios:MA(i.ratios,c.length)}))}return r}function d$(e,t){const n=new Set(t);return e.flatMap(r=>{const s=r.sessionIds.filter(i=>n.has(i));return s.length<2?[]:[{...r,sessionIds:s,ratios:s.length===r.sessionIds.length?MA(r.ratios,s.length):Bc(s.length)}]})}function Th(e,t){if(t)return e.find(n=>n.sessionIds.includes(t))}function Ux(e,t,n){if(!t||!n||t===n)return e;const r=Th(e,t),s=Th(e,n);if(r&&r.id===s?.id)return e;const i=[...r?.sessionIds??[t],...s?.sessionIds??[n]],a=[...new Set(i)],c={id:r?.id??`split:${t}`,...r?.name?{name:r.name}:{},sessionIds:a,layout:a.length>2&&(!r||r.layout===E2)?"grid":r?.layout??E2,ratios:Bc(a.length)},u=new Set([r?.id,s?.id].filter(Boolean)),f=e.filter(g=>!u.has(g.id)),p=r?Math.max(0,e.findIndex(g=>g.id===r.id)):f.length;return f.splice(Math.min(p,f.length),0,c),f}function f$(e,t){const n=Th(e,t);if(!n||!t)return e;if(n.sessionIds.length<=2)return e.filter(s=>s.id!==n.id);const r=n.sessionIds.filter(s=>s!==t);return e.map(s=>s.id===n.id?{...s,sessionIds:r,ratios:Bc(r.length)}:s)}function h$(e,t){const n=Th(e,t);return n?e.filter(r=>r.id!==n.id):e}function p$(e,t,n){return e.map(r=>{if(r.id!==t)return r;const s=[...new Set(n)],i=new Set(r.sessionIds);return s.length===r.sessionIds.length&&s.every(c=>i.has(c))?{...r,sessionIds:s}:r})}function m$(e,t,n){const r=n.trim().slice(0,80);return e.map(s=>s.id===t?{...s,...r?{name:r}:{name:void 0}}:s)}const I2=320,DA=1,g$=I2+120,x$=48,b$=72,R2="termdock:split-workspaces:v2",jA="termdock:split-workspace:v1",y$=.1,v$=.9,w$=.28,S$=300,A$=8,T$=280,C$=160;function zx(){if(typeof window>"u")return{mobile:!1,landscape:!1};const t=(navigator.maxTouchPoints>0||"ontouchstart"in window)&&Math.min(window.innerWidth,window.innerHeight)<768;return{mobile:t,landscape:t&&window.innerWidth>window.innerHeight}}function k$(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(R2);if(e)return u$(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(jA)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const n=Math.min(v$,Math.max(y$,typeof t.ratio=="number"?t.ratio:.5));return[{id:`split:${t.primaryId}`,sessionIds:[t.primaryId,t.secondaryId],layout:t.direction==="vertical"?"vertical":"horizontal",ratios:[n,1-n]}]}}catch{}return[]}function _$(e,t){const n=new Map(e.map(a=>[a.id,a])),r=new Map;t.forEach(a=>a.sessionIds.forEach(c=>r.set(c,a)));const s=new Set,i=[];for(const a of e){const c=r.get(a.id);if(!c){i.push({key:a.id,sessions:[a]});continue}if(s.has(c.id))continue;s.add(c.id);const u=c.sessionIds.flatMap(f=>{const p=n.get(f);return p?[p]:[]});u.length>=2&&i.push({key:c.id,sessions:u,workspace:c})}return i}function $3(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(n=>n.cancel())}catch{}}function Jp(e,t){const n=ag(e,t);if(n===null)return;const r=e.wrapperEl;$3(e),r&&(r.style.transitionDuration="0ms");try{const s=e;s.setTransition?.(0),s.setTranslate?.(n),$3(e),r&&(r.style.transitionDuration="0ms",r.style.transform=`translate3d(${n}px, 0px, 0px)`)}catch{r&&(r.style.transitionDuration="0ms",r.style.transform=`translate3d(${n}px, 0px, 0px)`)}}function N2(e){try{const t=typeof e.getTranslate=="function"?e.getTranslate():e.translate;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return typeof e.translate=="number"&&Number.isFinite(e.translate)?e.translate:null}}function ag(e,t){const n=e.snapGrid,r=Array.isArray(n)?n[t]:void 0;return typeof r!="number"||!Number.isFinite(r)?null:-r}function L$(e,t){const n=N2(e),r=ag(e,t);return n!==null&&r!==null&&Math.abs(n-r)<=DA}function E$(e){const t=[],n=new Map,r=new Map,s=new Map;for(const i of e){const a=n.get(i.id)??[];if(a.push(i.id),n.set(i.id,a),i.sessionId){const c=r.get(i.sessionId)??[];c.push(i.id),r.set(i.sessionId,c)}if(i.mode==="tmux"&&i.tmuxSessionName){const c=s.get(i.tmuxSessionName)??[];c.push(i.id),s.set(i.tmuxSessionName,c)}}for(const[i,a]of n)a.length>1&&t.push({kind:"frontend",key:i,sessionIds:a});for(const[i,a]of r)a.length>1&&t.push({kind:"backend",key:i,sessionIds:a});for(const[i,a]of s)a.length>1&&t.push({kind:"tmux",key:i,sessionIds:a});return t}function PA(e){const t=new Map;for(const n of e)t.set(n.id,n);return Array.from(t.values())}function BA(e){return{id:e.sessionId,name:e.name,customName:e.customName===!0,sessionId:e.backendSessionId,mode:e.mode==="tmux"||e.mode==="shell"?e.mode:"shell",tmuxSessionName:e.tmuxSessionName??null}}function I$(e,t){const n=PA(e),r=n.findIndex(s=>s.id===t.id);if(r>=0){const s=[...n];return s[r]=t,s}return[...n,t]}function H3(e,t){const n=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=n.get(r.sessionId);return{...BA(r),history:s?.history}})}function U3(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function z3(e){if(!e||typeof e!="object")return"unknown";const t=e;if(typeof t.pointerType=="string"&&t.pointerType)return t.pointerType;if(typeof t.type=="string"){if(t.type.startsWith("touch"))return"touch";if(t.type.startsWith("mouse"))return"mouse";if(t.type.startsWith("pointer"))return"pointer"}return"unknown"}function G3(e){const t=new Map;for(const[n,r]of e)t.set(n,r.cwd??null);return t}function R$(e,t){if(e.size!==t.size)return!1;for(const[n,r]of t)if(e.get(n)!==r)return!1;return!0}function N$(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const n=Date.now().toString(36),r=Math.random().toString(36).slice(2,8);return`wt-${n}${r}`}const M$=({terminalSettings:e=Ky(),colorTheme:t="dark",toolbarPresets:n=[],showDebug:r,terminalFocusAvailable:s=!0,defaultSessionMode:i="shell",defaultTmuxSessionName:a="",connectionPrioritySessionId:c=null,connectionPriorityReady:u=!0,onStatusChange:f,onSessionDataUpdate:p})=>{const{t:g}=qn(),y=x.useMemo(()=>od("session"),[]),v=x.useMemo(()=>od("terminal"),[]),[S,T]=x.useState([]),[C,L]=x.useState(null),[E,D]=x.useState(!0),[B,F]=x.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[j,A]=x.useState(()=>new Set),[H,Q]=x.useState(0),[K,W]=x.useState(()=>new Set),[de,X]=x.useState(()=>new Set),[pe,ve]=x.useState(()=>new Map),Ae=x.useRef(!1),ie=x.useRef(null),V=x.useRef({}),[z,ce]=x.useState(null),[ge,he]=x.useState(()=>k$()),[Ce,xe]=x.useState(!1),[ae,_e]=x.useState(null),[Z,Ze]=x.useState(null),[at,He]=x.useState(null),[be,Be]=x.useState(!1),[fe,Ke]=x.useState(()=>zx().mobile),[Ye,tt]=x.useState(()=>zx().landscape),[q,ue]=x.useState(null),[Xe,Ne]=x.useState(null),ze=x.useRef(s),Fe=x.useRef(!1),ft=x.useRef(null),ot=x.useRef(null),Dt=x.useRef(fe),wt=x.useRef(null),Gt=x.useRef(0),Jt=x.useRef([]),ln=x.useRef(0),Hn=x.useRef(null),we=x.useRef(!1),dt=x.useRef(!0),xt=x.useRef(null),Vt=x.useRef(""),ht=x.useRef(null),$t=x.useRef(0);x.useEffect(()=>{if(typeof window>"u")return;const re=()=>{const Le=zx();Dt.current=Le.mobile,Ke(Le.mobile),tt(Le.landscape)};return re(),window.addEventListener("resize",re),()=>window.removeEventListener("resize",re)},[]);const{sessions:ut,inventory:Ge,activeSessionId:Jn,isLoading:An,openSession:We,setActiveSession:En,removeSession:Et,renameSession:yr,resetSessionCustomName:Qn,reorderSessions:Tn,restoreSessions:_r}=r$(),mr=Ge?.tmuxRecovery??null;x.useEffect(()=>{He(null),Ze(null)},[mr?.id]);const jr=x.useCallback(async()=>{Ze("restore"),He(null);try{const re=await iI();await _r(),re.failed>0&&He(g("tab.tmuxRecoveryPartial",{restored:re.restored,failed:re.failed}))}catch{He(g("tab.tmuxRecoveryFailed"))}finally{Ze(null)}},[_r,g]),Lr=x.useCallback(async()=>{Ze("dismiss"),He(null);try{await oI(),await _r()}catch{He(g("tab.tmuxRecoveryDismissFailed"))}finally{Ze(null)}},[_r,g]),Se=ct(re=>re.groupByFolder),te=ct(re=>re.leftOpen||re.rightOpen),[Mt,Ee]=x.useState(()=>G3(ns.getState().sessions));x.useEffect(()=>ns.subscribe(re=>{const Le=G3(re.sessions);Ee(Qe=>R$(Qe,Le)?Qe:Le)}),[]);const{arranged:an}=x.useMemo(()=>J8(S,re=>Mt.get(re.id)??null,Se,""),[S,Mt,Se]),Qt=x.useRef(an);Qt.current=an;const It=x.useMemo(()=>_$(an,ge),[an,ge]),en=x.useRef(It);en.current=It;const dn=x.useMemo(()=>Th(ge,C),[C,ge]),tr=x.useMemo(()=>{const re=It.find(Le=>Le.sessions.some(Qe=>Qe.id===C));return new Set(re?.sessions.map(Le=>Le.id)??[])},[C,It]);x.useEffect(()=>{if(!fe)return;const re=()=>{const Qe=Date.now(),je=new Set(Jt.current.map(bt=>bt.id));ve(bt=>{const yt=new Map;for(const[Ut,Yt]of bt)je.has(Ut)&&(tr.has(Ut)||Qe-Yt<NA)&&yt.set(Ut,Yt);return tr.forEach(Ut=>yt.set(Ut,Qe)),yt})};re();const Le=window.setInterval(re,i$);return()=>window.clearInterval(Le)},[tr,fe]);const Oe=x.useMemo(()=>fe?o$({currentVisibleSessionIds:tr,lastVisitedAtBySessionId:pe,validSessionIds:new Set(S.map(re=>re.id)),now:Date.now()}):tr,[tr,fe,pe,S]),mt=x.useMemo(()=>Dx(S.map(re=>({id:re.id,backendSessionId:re.sessionId})),c),[c,S]),cn=x.useMemo(()=>U3(ut,Jn),[Jn,ut]),tn=Yp({prioritySessionId:mt,activeSessionId:C,persistedActiveSessionId:cn,firstSessionId:S[0]?.id??null}),kn=x.useMemo(()=>aQ(It.flatMap(re=>re.sessions.map(Le=>Le.id)),tr),[tr,It]),Cn=tn!==null&&j.has(tn),Nt=x.useCallback((re,Le)=>{A(Qe=>{if(Qe.has(re)===Le)return Qe;const bt=new Set(Qe);return Le?bt.add(re):bt.delete(re),bt})},[]),Ln=x.useCallback(re=>{const Le=mt??wt.current;re===Le&&(fh("foreground-stream-connected"),Q(Gt.current))},[mt]),Kn=x.useCallback((re,Le)=>{W(Qe=>{if(Qe.has(re)===Le)return Qe;const je=new Set(Qe);return Le?je.add(re):je.delete(re),je})},[]),un=tn!==null&&K.has(tn);x.useEffect(()=>{un&&fh("foreground-viewport-ready")},[un]),x.useEffect(()=>{if(!un||fe)return;const Le=It.flatMap(Qe=>Qe.sessions.map(je=>je.id)).filter(Qe=>Qe!==tn).map((Qe,je)=>window.setTimeout(()=>{X(bt=>{if(bt.has(Qe))return bt;const yt=new Set(bt);return yt.add(Qe),je===0&&fh("background-viewports-started"),yt})},x$+je*b$));return()=>Le.forEach(Qe=>window.clearTimeout(Qe))},[tn,un,fe,It]),x.useEffect(()=>{typeof window>"u"||(ge.length>0?(window.localStorage.setItem(R2,JSON.stringify(ge)),window.localStorage.removeItem(jA)):window.localStorage.removeItem(R2))},[ge]),x.useEffect(()=>{An||E||ge.length===0||he(re=>d$(re,S.map(Le=>Le.id)))},[An,E,S,ge.length]),x.useEffect(()=>{if(!ae)return;const re=window.setTimeout(()=>_e(null),3200);return()=>window.clearTimeout(re)},[ae]),x.useEffect(()=>()=>ht.current?.(),[]),wt.current=C,Gt.current=B.token,Jt.current=S,Hn.current=Jn,we.current=An,dt.current=E,ze.current=s;const nr=x.useCallback((re=ie.current)=>{const Le=ln.current,Qe=typeof window<"u"?window.visualViewport:null,je=re?N2(re):null,bt=re?ag(re,Le):null;return{sessionsLength:Jt.current.length,workspaceSlidesLength:en.current.length,sessionIds:Jt.current.map(yt=>yt.id),activeSessionId:wt.current,activeSessionIndex:Le,persistedActiveId:Hn.current,isLoading:we.current,isRestoring:dt.current,activeIndex:re?.activeIndex??null,previousIndex:re?.previousIndex??null,animating:re?.animating??null,allowTouchMove:re?.allowTouchMove??null,width:re?.width??null,translate:je,targetTranslate:bt,translateDelta:je!==null&&bt!==null?je-bt:null,snapGridLength:re?.snapGrid?.length??null,targetSnap:re?.snapGrid?.[Le]??null,visualViewport:Qe?{width:Math.round(Qe.width),height:Math.round(Qe.height),offsetTop:Math.round(Qe.offsetTop)}:null}},[]),Zt=x.useCallback((re,Le)=>{y(re,{...nr(),...Le})},[y,nr]);x.useEffect(()=>{An||E||C!==Jn&&En(C)},[C,An,E,Jn,En]);const Tr=x.useMemo(()=>{if(an.length===0||!C)return 0;const re=It.findIndex(Le=>Le.sessions.some(Qe=>Qe.id===C));return re>=0?re:0},[It,C]);ln.current=Tr;const wn=x.useCallback(()=>{ft.current&&(clearTimeout(ft.current),ft.current=null)},[]),Wr=x.useCallback(re=>{wn(),ft.current=setTimeout(()=>{ft.current=null,Fe.current=!1,Zt("[swiper:touch-guard-clear]",{reason:re})},g$)},[wn,Zt]),rt=x.useCallback((re,Le={})=>{const Qe=ie.current,je=ln.current,bt=en.current;if(!Qe||bt.length===0||je<0||je>=bt.length)return;if(Fe.current){Zt("[swiper:sync-skip-touch]",{reason:re});return}if(Qe.animating){Zt("[swiper:sync-skip-animating]",{reason:re});return}const yt=N2(Qe),Ut=ag(Qe,je),Yt=yt!==null&&Ut!==null&&Math.abs(yt-Ut)<=DA,rn=Qe.activeIndex===je;if(Zt("[swiper:sync-check]",{reason:re,activeIndexAligned:rn,translateAligned:Yt,immediate:Le.immediate===!0}),!(rn&&Yt)){if(rn){Jp(Qe,je),Zt("[swiper:sync-forced-active]",{reason:re,translateAligned:Yt,immediate:Le.immediate===!0});return}Le.immediate?(Jp(Qe,je),Qe.slideTo(je,0,!1),Jp(Qe,je)):Qe.slideTo(je,I2,!1),Zt("[swiper:sync-applied]",{reason:re,activeIndexAligned:rn,translateAligned:Yt,immediate:Le.immediate===!0})}},[Zt]);x.useEffect(()=>{const re=Le=>{const Qe=Le;ie.current&&(ie.current.allowTouchMove=!Qe.detail.locked),Zt("[swiper:gesture-lock]",{locked:Qe.detail.locked})};return document.addEventListener("termdock:gesture-lock",re),()=>document.removeEventListener("termdock:gesture-lock",re)},[Zt]),x.useEffect(()=>{if(S.length===0){C!==null&&L(null);return}if(!C){if(!u)return;L(Yp({prioritySessionId:mt,activeSessionId:null,persistedActiveSessionId:cn,firstSessionId:S[0]?.id??null}));return}S.some(Le=>Le.id===C)||L(S[0].id)},[S,C,u,mt,cn]);const Bt=x.useCallback((re,Le)=>{if(Le&&Date.now()<$t.current){V.current[re]=!1;return}V.current[re]=Le,Ne(Qe=>Le?re:Qe===re?null:Qe)},[]),$e=x.useCallback(re=>{if(!Fe.current&&re.activeIndex!==ln.current){Zt("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:re.activeIndex,expectedActiveIndex:ln.current}),requestAnimationFrame(()=>rt("ignored-layout-slide-change",{immediate:!0}));return}const Le=en.current[re.activeIndex],Qe=Le?.sessions.some(yt=>yt.id===C)?C:Le?.sessions[0]?.id;if(Zt("[swiper:slide-change]",{nextSessionId:Qe??null,instanceActiveIndex:re.activeIndex}),!Qe||Qe===C)return;const je=!!C&&V.current[C]===!0,bt=ze.current&&(!Dt.current||je);if(ot.current=Qe,L(Qe),bt){ce({sessionId:Qe,token:Date.now()});return}ce(null)},[S,C,Zt,rt]);x.useEffect(()=>{if(ot.current===C){Zt("[swiper:sync-skip-swiper-driven]",{activeSessionId:C}),ot.current=null;return}rt("active-session-index",{immediate:!0})},[C,Tr,S.length,rt,Zt]),x.useEffect(()=>{const re=ie.current;if(!re)return;const Le=It.length>1&&!te&&!Ce;re.allowTouchMove!==Le&&(re.allowTouchMove=Le,Zt("[swiper:allow-touch-sync]",{nextAllow:Le,sidebarOverlayOpen:te}))},[It.length,Zt,te,Ce]);const st=x.useCallback(re=>{const Le=ie.current;if(!Le)return;const Qe=Le.el;if(Zt("[swiper:layout-before]",{reason:re,scrollLeft:Qe?.scrollLeft??null}),Qe&&(Qe.scrollLeft=0),Le.updateSize(),Le.updateSlides(),Le.updateProgress(),Le.updateSlidesClasses(),Qe&&(Qe.scrollLeft=0),Zt("[swiper:layout-after]",{reason:re,scrollLeft:Qe?.scrollLeft??null}),Fe.current||Le.animating){Zt("[swiper:layout-skip-sync-motion]",{reason:re});return}rt(`layout:${re}`,{immediate:!0}),requestAnimationFrame(()=>{const je=ie.current;je&&(Fe.current||je.animating||Jp(je,ln.current))})},[Zt,rt]);x.useEffect(()=>()=>wn(),[wn]);const qt=It.map(re=>re.key).join("\0");x.useEffect(()=>{requestAnimationFrame(()=>st("group-change"))},[Se,qt,st]),x.useEffect(()=>{let re=null,Le="mount";const Qe=Yt=>{Le=Yt,re===null&&(re=requestAnimationFrame(()=>{re=null,st(`viewport-change:${Le}`)}))},je=()=>Qe("window-resize"),bt=()=>Qe("visual-viewport-resize"),yt=()=>Qe("visual-viewport-scroll"),Ut=Yt=>{Qe(`measured:${Yt.detail?.source??"unknown"}`)};return window.addEventListener("resize",je),window.visualViewport?.addEventListener("resize",bt),window.visualViewport?.addEventListener("scroll",yt),document.addEventListener(v2,Ut),Qe("mount"),()=>{window.removeEventListener("resize",je),window.visualViewport?.removeEventListener("resize",bt),window.visualViewport?.removeEventListener("scroll",yt),document.removeEventListener(v2,Ut),re!==null&&cancelAnimationFrame(re)}},[st]),x.useEffect(()=>{if(typeof document>"u")return;let re=null,Le=null,Qe=document.hidden;const je=pn=>{if(pn!=="online"&&document.hidden)return;const Mn=performance.now();if(!sQ(Le,Mn))return;Le=Mn;const Vn=pn==="bfcache"||pn==="online"?pn:"visibility",hr=iQ({wasPageHidden:Qe,reason:pn});Qe=!1,Oa("info","PWA_RESUME scheduled",{source:pn,forceForegroundReconnect:hr,activeSessionId:wt.current}),F(xn=>({token:xn.token+1,reason:Vn,forceForegroundReconnect:hr})),requestAnimationFrame(()=>st(`resume:${pn}:raf`)),re&&clearTimeout(re),re=setTimeout(()=>{re=null,st(`resume:${pn}:settled`)},320)},bt=()=>{if(document.hidden){Qe=!0,M5();return}je("visibility")},yt=()=>{Qe=!0,M5()},Ut=pn=>{je(pn.persisted?"bfcache":"pageshow")},Yt=()=>je("online"),rn=()=>je("focus");return document.addEventListener("visibilitychange",bt),window.addEventListener("pagehide",yt),window.addEventListener("pageshow",Ut),window.addEventListener("online",Yt),window.addEventListener("focus",rn),()=>{document.removeEventListener("visibilitychange",bt),window.removeEventListener("pagehide",yt),window.removeEventListener("pageshow",Ut),window.removeEventListener("online",Yt),window.removeEventListener("focus",rn),re&&clearTimeout(re)}},[st]),x.useEffect(()=>{const re=E$(S),Le=JSON.stringify(re);re.length>0&&Le!==Vt.current?(Vt.current=Le,console.warn("[session-invariant] duplicate mapping detected",re)):re.length===0&&Vt.current&&(Vt.current=""),p?.({sessions:S.map(Qe=>({id:Qe.id,name:Qe.name,customName:Qe.customName,mode:Qe.mode,tmuxSessionName:Qe.tmuxSessionName})),activeSessionId:C,splitWorkspaces:ge.map(({id:Qe,name:je,sessionIds:bt,layout:yt})=>({id:Qe,...je?{name:je}:{},sessionIds:bt,layout:yt}))})},[S,C,ge,p]),x.useEffect(()=>{if(An||Ae.current)return;Ae.current=!0;const re=Dx(ut.map(yt=>({id:yt.sessionId,backendSessionId:yt.backendSessionId??null})),c),Le=U3(ut,Jn),Qe=Yp({prioritySessionId:u?re:null,activeSessionId:null,persistedActiveSessionId:Le,firstSessionId:ut[0]?.sessionId??null}),je=PA(ut.map(BA));if(y("[Session] Restoring",je.length,"persisted sessions (one-shot)"),Zt("[swiper:restore-start]",{persistedSessionIds:ut.map(yt=>yt.sessionId),nextActiveSessionId:Qe}),je.length>0){const yt=ns.getState();je.forEach(Yt=>{Yt.sessionId&&yt.setTerminalSession(Yt.id,{sessionId:Yt.sessionId,cols:80,rows:24,mode:Yt.mode,tmuxSessionName:Yt.tmuxSessionName,history:Yt.history})}),ut.forEach(Yt=>{Yt.activeProgram!=null&&yt.setSessionActiveProgram(Yt.sessionId,Yt.activeProgram),Yt.cwd!=null&&yt.setSessionCwd(Yt.sessionId,Yt.cwd)}),T(je);const Ut=Qe||je[0]?.id||null;L(Ut),Zt("[swiper:restore-complete]",{restoredSessionIds:je.map(Yt=>Yt.id),nextActiveSessionId:Ut})}(async()=>(je.length===0&&await xt.current?.({createIfEmpty:!0}),D(!1),requestAnimationFrame(()=>rt("restore-finished",{immediate:!0}))))()},[An,ut,Jn,y,Zt,rt,u,c]),x.useEffect(()=>{if(!u||E||S.length===0)return;const re=Dx(S.map(Qe=>({id:Qe.id,backendSessionId:Qe.sessionId})),c),Le=Yp({prioritySessionId:re,activeSessionId:wt.current,persistedActiveSessionId:cn,firstSessionId:S[0]?.id??null});Le&&Le!==wt.current&&L(Le)},[u,c,E,cn,S]);const Ht=x.useRef([]),bn=x.useRef(!1);wt.current=C,x.useEffect(()=>{if(E)return;const re=Ht.current,Le=ut;if(!bn.current){T(rn=>H3(rn,Le)),Ht.current=Le,bn.current=!0;return}const Qe=new Set(re.map(rn=>rn.sessionId)),je=new Set(Le.map(rn=>rn.sessionId)),bt=new Map(re.map(rn=>[rn.sessionId,rn.name]));Ht.current=Le,T(rn=>{const pn=H3(rn,Le);return(!wt.current||!pn.some(Mn=>Mn.id===wt.current))&&L(pn[0]?.id??null),pn});const yt=Le.filter(rn=>!Qe.has(rn.sessionId)),Ut=[...Qe].filter(rn=>!je.has(rn)),Yt=Le.filter(rn=>Qe.has(rn.sessionId)&&bt.get(rn.sessionId)!==rn.name);(yt.length>0||Ut.length>0||Yt.length>0)&&y("[Session] Synced persisted sessions:",{newSessionIds:yt.map(rn=>rn.sessionId),removedSessionIds:Ut,renamedSessionIds:Yt.map(rn=>rn.sessionId),currentSessionIds:Le.map(rn=>rn.sessionId)});for(const rn of Le){if(!rn.backendSessionId)continue;ns.getState().setTerminalSession(rn.sessionId,{sessionId:rn.backendSessionId,cols:80,rows:24,mode:rn.mode,tmuxSessionName:rn.tmuxSessionName})}},[ut,E,y]);const Ie=x.useCallback(async re=>{try{const Le=re?.mode==="tmux"||re?.mode==="shell"?re.mode:i,Qe=(re?.tmuxSessionName||"").trim(),je=a.trim(),bt=Le==="tmux"?Qe||je||N$():null,yt=typeof re?.cwd=="string"?re.cwd:null,Ut=C?ns.getState().sessions.get(C)?.cwd??null:null,Yt=typeof yt=="string"&&yt.trim().length>0?yt:typeof Ut=="string"&&Ut.trim().length>0?Ut:void 0,rn=await We({mode:Le,tmuxSessionName:bt,cwd:Yt,termType:"xterm-256color",createIfEmpty:re?.createIfEmpty===!0}),pn=rn.session,Mn=rn.terminalSession,Vn={id:pn.sessionId,name:pn.name,customName:pn.customName===!0,sessionId:Mn.sessionId,mode:Mn.mode??pn.mode,tmuxSessionName:Mn.tmuxSessionName??pn.tmuxSessionName};T(Pr=>I$(Pr,Vn)),L(Vn.id),ns.getState().setTerminalSession(Vn.id,{sessionId:Mn.sessionId,cols:80,rows:24,mode:Vn.mode,tmuxSessionName:Vn.tmuxSessionName,activeProgram:Mn.activeProgram,activeProgramRaw:Mn.activeProgramRaw,activeProgramSource:Mn.activeProgramSource,cwd:Mn.cwd}),y("[Session] Inventory opened session:",{frontendSessionId:Vn.id,backendSessionId:Mn.sessionId,reused:rn.reused,mode:Vn.mode,tmuxSessionName:Vn.tmuxSessionName});const xn=re?.command?.trim();return xn&&await DS(Mn.sessionId,`${xn}\r`),Vn.id}catch(Le){return console.error("[Session] Failed to create new session:",Le),null}},[i,a,C,We,y]);xt.current=Ie;const et=x.useCallback((re,Le={})=>{const Qe=wt.current,je=!!Qe&&V.current[Qe]===!0;if(L(re),Dt.current&&Le.preserveMobileKeyboard===!1){$t.current=Date.now()+600,Qe&&(V.current[Qe]=!1),Ne(null),ce(null);const bt=document.activeElement;bt instanceof HTMLTextAreaElement&&bt.closest(".terminal-viewport-container")&&bt.blur();return}je&&Dt.current&&Ne(re),ze.current&&(!Dt.current||je)&&ce({sessionId:re,token:Date.now()})},[]),At=x.useCallback(re=>{L(re),xe(!0),_e(null)},[]),nn=x.useCallback(re=>{const Le=wt.current;!Le||Le===re||(he(Qe=>Ux(Qe,Le,re)),xe(!1),et(Le,{preserveMobileKeyboard:!1}))},[et]),Zn=x.useCallback(async()=>{const re=wt.current;if(!re||be)return;Be(!0);const Le=ns.getState().sessions.get(re)?.cwd??void 0,Qe=await Ie({cwd:Le||void 0,mode:i});if(Be(!1),!Qe){_e(g("common.error"));return}he(je=>Ux(je,re,Qe)),xe(!1),et(re,{preserveMobileKeyboard:!1})},[et,i,Ie,be,g]),fn=x.useCallback(re=>{he(Le=>h$(Le,re)),re&&et(re,{preserveMobileKeyboard:!1})},[et]),mn=x.useCallback(re=>{he(Le=>f$(Le,re)),et(re,{preserveMobileKeyboard:!1})},[et]),Kt=x.useCallback((re,Le,Qe,je,bt)=>{re.preventDefault(),re.stopPropagation();const yt=re.currentTarget,Ut=re.pointerId,Yt={x:re.clientX,y:re.clientY};yt.setPointerCapture?.(Ut);const rn=Le.getBoundingClientRect();let pn=!fe,Mn=null;const Vn=xn=>{if(xn.pointerId!==Ut)return;if(!pn){Math.hypot(xn.clientX-Yt.x,xn.clientY-Yt.y)>A$&&Mn!==null&&(window.clearTimeout(Mn),Mn=null);return}xn.preventDefault();const Pr=Qe?(xn.clientY-rn.top)/rn.height:(xn.clientX-rn.left)/rn.width,Cr=Qe?rn.height:rn.width,hn=fe?0:Qe?C$:T$;he(Ft=>Ft.map(gr=>{if(gr.id!==je)return gr;const vr=gr.ratios.length===gr.sessionIds.length?[...gr.ratios]:Bc(gr.sessionIds.length),ar=vr.slice(0,bt).reduce((lr,Hs)=>lr+Hs,0),zr=vr[bt]+vr[bt+1],Fn=hn>0?Math.min(zr/2,hn/Math.max(1,Cr)):Math.min(zr/2,w$),pr=Math.min(zr-Fn,Math.max(Fn,Pr-ar));return vr[bt]=pr,vr[bt+1]=zr-pr,{...gr,ratios:vr}}))},hr=()=>{Mn!==null&&(window.clearTimeout(Mn),Mn=null),window.removeEventListener("pointermove",Vn),window.removeEventListener("pointerup",hr),window.removeEventListener("pointercancel",hr),yt.classList.remove("bg-primary"),fe&&document.dispatchEvent(new CustomEvent("termdock:gesture-lock",{detail:{locked:!1}})),ht.current=null};ht.current?.(),ht.current=hr,window.addEventListener("pointermove",Vn),window.addEventListener("pointerup",hr),window.addEventListener("pointercancel",hr),fe&&(document.dispatchEvent(new CustomEvent("termdock:gesture-lock",{detail:{locked:!0}})),Mn=window.setTimeout(()=>{Mn=null,pn=!0,yt.classList.add("bg-primary"),navigator.vibrate?.(8)},S$))},[fe]),Yn=x.useCallback(re=>{S.find(Qe=>Qe.id===re)&&(L(re),ze.current&&!Dt.current&&ce({sessionId:re,token:Date.now()}),y("[Session] Switched to session:",re))},[S,y]),ir=x.useCallback((re,Le)=>{Le.trim()&&(T(Qe=>Qe.map(je=>je.id===re?{...je,name:Le.trim(),customName:!0}:je)),yr(re,Le.trim()))},[yr]),_n=x.useCallback(re=>{T(Le=>Le.map(Qe=>Qe.id===re?{...Qe,customName:!1}:Qe)),Qn(re)},[Qn]),wr=x.useCallback(re=>{T(Le=>{const Qe=new Map(Le.map(Ut=>[Ut.id,Ut])),je=re.map(Ut=>Qe.get(Ut)).filter(Ut=>Ut!==void 0),bt=new Set(re),yt=Le.filter(Ut=>!bt.has(Ut.id));return[...je,...yt]}),Tn(re),y("[Session] Reordered sessions:",re),requestAnimationFrame(()=>{ie.current?.update()})},[Tn,y]),Jr=x.useCallback(async re=>{const Le=typeof re=="string"?re:re.sessionId,Qe=typeof re=="string"?"auto":re.closeMode??"auto",je=S.find(yt=>yt.id===Le);if(!je)return;const bt=EA(an,Le,yt=>yt.id);try{Qe==="destroy"&&je.mode==="tmux"&&je.tmuxSessionName?(await PS(je.tmuxSessionName),y("[Session] Destroyed tmux session:",{frontendSessionId:je.id,tmuxSessionName:je.tmuxSessionName})):je.sessionId&&(await jS(je.sessionId),y("[Session] Closed backend terminal:",je.sessionId))}catch(yt){console.error("[Session] Failed to close backend terminal:",yt);return}T(yt=>{const Ut=yt.filter(Yt=>Yt.id!==Le);return L(bt),Ut}),Et(Le,bt),delete V.current[Le],y("[Session] Closed session:",{sessionId:Le,closeMode:Qe})},[S,an,Et,y]),er=x.useCallback(re=>{if(!re)return;const Le=S.filter(Qe=>Qe.sessionId===re);if(Le.length!==0){Le.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:re,frontendSessionIds:Le.map(Qe=>Qe.id)}),T(Qe=>{const je=Qe.filter(bt=>bt.sessionId!==re);return je.length!==Qe.length&&!je.some(yt=>yt.id===C)&&L(je.length>0?je[0].id:null),je});for(const Qe of Le)Et(Qe.id),delete V.current[Qe.id];y("[Session] Backend gone, dropped local session(s):",Le.map(Qe=>Qe.id))}},[S,C,Et,y]);x.useEffect(()=>{const re=hn=>{Ie(hn.detail)},Le=hn=>{Yn(hn.detail)},Qe=()=>{const hn=wt.current;!hn||Dt.current||ce({sessionId:hn,token:Date.now()})},je=hn=>{const Ft=hn;Ft.detail&&At(Ft.detail)},bt=hn=>{const Ft=hn.detail;fn(Ft??wt.current??void 0)},yt=hn=>{const Ft=hn.detail;Ft&&mn(Ft)},Ut=hn=>{const Ft=hn.detail,gr=typeof Ft=="string"?Ft:Ft?.layout,vr=typeof Ft=="string"?wt.current:Ft?.sessionId;gr!=="horizontal"&&gr!=="vertical"&&gr!=="grid"||he(ar=>ar.map(zr=>zr.sessionIds.includes(vr??"")?{...zr,layout:gr}:zr))},Yt=hn=>{const gr=hn.detail?.direction;if(gr!=="prev"&&gr!=="next")return;const vr=Qt.current;if(vr.length<=1)return;const ar=wt.current,zr=ar?vr.findIndex(Er=>Er.id===ar):-1,lr=((zr>=0?zr:0)+(gr==="next"?1:-1)+vr.length)%vr.length,Hs=vr[lr]?.id;Hs&&Hs!==ar&&Yn(Hs)},rn=hn=>{Jr(hn.detail)},pn=hn=>{er(hn.detail)},Mn=hn=>{const Ft=hn;!Ft.detail?.sessionId||!Ft.detail?.name||ir(Ft.detail.sessionId,Ft.detail.name)},Vn=hn=>{const Ft=hn;Ft.detail?.sessionId&&_n(Ft.detail.sessionId)},hr=hn=>{const Ft=hn;Ft.detail?.sessionIds&&wr(Ft.detail.sessionIds)},xn=hn=>{const Ft=hn.detail;!Ft?.workspaceId||!Array.isArray(Ft.sessionIds)||he(gr=>p$(gr,Ft.workspaceId,Ft.sessionIds))},Pr=hn=>{const Ft=hn.detail;!Ft?.workspaceId||typeof Ft.name!="string"||he(gr=>m$(gr,Ft.workspaceId,Ft.name))},Cr=hn=>{const Ft=hn.detail;!Ft?.primaryId||!Ft.secondaryId||Ft.primaryId===Ft.secondaryId||(he(gr=>Ux(gr,Ft.primaryId,Ft.secondaryId)),et(Ft.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",re),window.addEventListener("switch-terminal-session",Le),window.addEventListener("focus-active-terminal-session",Qe),window.addEventListener("open-terminal-split-chooser",je),window.addEventListener("close-terminal-split",bt),window.addEventListener("remove-terminal-split-pane",yt),window.addEventListener("set-terminal-split-direction",Ut),window.addEventListener("cycle-terminal-session",Yt),window.addEventListener("close-terminal-session",rn),window.addEventListener("close-terminal-session-by-backend",pn),window.addEventListener("rename-terminal-session",Mn),window.addEventListener("reset-terminal-session-name",Vn),window.addEventListener("reorder-terminal-session",hr),window.addEventListener("reorder-terminal-split-workspace",xn),window.addEventListener("rename-terminal-split-workspace",Pr),window.addEventListener("combine-terminal-split-sessions",Cr),()=>{window.removeEventListener("new-terminal-session",re),window.removeEventListener("switch-terminal-session",Le),window.removeEventListener("focus-active-terminal-session",Qe),window.removeEventListener("open-terminal-split-chooser",je),window.removeEventListener("close-terminal-split",bt),window.removeEventListener("remove-terminal-split-pane",yt),window.removeEventListener("set-terminal-split-direction",Ut),window.removeEventListener("cycle-terminal-session",Yt),window.removeEventListener("close-terminal-session",rn),window.removeEventListener("close-terminal-session-by-backend",pn),window.removeEventListener("rename-terminal-session",Mn),window.removeEventListener("reset-terminal-session-name",Vn),window.removeEventListener("reorder-terminal-session",hr),window.removeEventListener("reorder-terminal-split-workspace",xn),window.removeEventListener("rename-terminal-split-workspace",Pr),window.removeEventListener("combine-terminal-split-sessions",Cr)}},[et,Ie,Yn,At,fn,mn,Jr,er,ir,_n,wr]),x.useEffect(()=>{if(!dn||fe)return;const re=Le=>{if(!(Le.ctrlKey||Le.metaKey)||!Le.shiftKey)return;if(dn.layout==="horizontal"?Le.key==="ArrowLeft"||Le.key==="ArrowRight":dn.layout==="vertical"?Le.key==="ArrowUp"||Le.key==="ArrowDown":Le.key.startsWith("Arrow")){Le.preventDefault(),Le.stopPropagation();const je=dn.sessionIds.indexOf(wt.current??""),bt=Le.key==="ArrowLeft"||Le.key==="ArrowUp"?-1:1,yt=(Math.max(0,je)+bt+dn.sessionIds.length)%dn.sessionIds.length,Ut=dn.sessionIds[yt];if(!Ut)return;et(Ut);return}Le.key==="Backspace"&&(Le.preventDefault(),Le.stopPropagation(),fn(wt.current??void 0))};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[et,dn,fn,fe]);const fr=re=>{const Le=ns.getState().sessions.get(re.id);return Ic(re,Le?.activeProgram??null,Le?.cwd??null,void 0,Le?.shellTitle??null,Le?.promptState??null)},Nr=(re,Le={})=>{const Qe=re.id===C,je=u&&nQ({sessionId:re.id,foregroundSessionId:tn,visibleSessionIds:Oe,deferredViewportSessionIds:de,isMobileLayout:fe}),bt=tQ({sessionId:re.id,foregroundSessionId:tn,foregroundReady:Cn})&&u,yt=rQ({sessionId:re.id,foregroundSessionId:tn,requestToken:B.token,foregroundCompletedToken:H})&&u,Ut=re.id===tn?0:kn.get(re.id)??jm;return o.jsx("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${Le.hidden?"invisible pointer-events-none":""}`,style:Le.containerStyle,"aria-hidden":Le.hidden||void 0,onPointerDown:()=>{Qe||et(re.id)},onWheelCapture:()=>{l$(Qe,()=>et(re.id))},children:o.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:je&&o.jsx(qQ,{sessionId:re.id,mode:re.mode,tmuxSessionName:re.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:n,isActive:Qe,initialConnectEnabled:bt,resumeRequestEnabled:yt,suppressKeyboard:Le.suppressKeyboard,keyboardPortalTarget:Le.keyboardPortalTarget,sharedMobileKeyboardLayout:Le.sharedMobileKeyboardLayout,suppressPageFlipRefresh:Le.suppressPageFlipRefresh,focusRequestToken:z?.sessionId===re.id?z.token:0,resumeRequestToken:B.token,resumeRequestReason:B.reason,forceResumeReconnect:B.forceForegroundReconnect&&re.id===tn,resumeRequestDelayMs:re.id===tn?0:Le.hidden?jm:kn.get(re.id)??jm,initialConnectDelayMs:Ut,onStreamReadyChange:Nt,onStreamConnected:Ln,onViewportReadyChange:Kn,onKeyboardVisibilityChange:Bt,showDebug:r,onStatusChange:Qe?f:void 0})})},re.id)};return o.jsxs("div",{className:"relative h-full flex flex-col",children:[mr&&o.jsx("section",{className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto max-w-lg rounded-2xl border border-warning/30 bg-surface-elevated px-4 py-3.5 shadow-[0_20px_60px_var(--app-shadow-strong)]",role:"alert","aria-live":"assertive",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning",children:o.jsx(Wg,{size:18})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:g("tab.tmuxRecoveryTitle",{count:mr.sessions.length})}),o.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:g("tab.tmuxRecoveryHint")}),o.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:mr.sessions.map(re=>re.name).join(" · ")}),at&&o.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:at}),o.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[o.jsxs("button",{type:"button",disabled:Z!==null,onClick:()=>{jr()},className:"inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-[11px] font-medium text-primary-foreground transition active:opacity-80 disabled:opacity-50",children:[o.jsx(d8,{size:13,className:Z==="restore"?"animate-spin":""}),g(Z==="restore"?"tab.tmuxRecoveryRestoring":"tab.tmuxRecoveryRestoreAll")]}),o.jsx("button",{type:"button",disabled:Z!==null,onClick:()=>{Lr()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-50",children:g("tab.tmuxRecoveryDismiss")})]})]})]})}),o.jsx("div",{className:"flex-1 overflow-hidden",children:o.jsx(Qh,{onSwiper:re=>{ie.current=re,re.allowTouchMove=It.length>1&&!te&&!Ce,Zt("[swiper:on-swiper]",{allowTouchMove:re.allowTouchMove}),requestAnimationFrame(()=>st("on-swiper"))},onSlideChange:$e,onTouchStart:(re,Le)=>{const Qe=z3(Le),je=Qe==="touch"||Qe==="pen"||Qe==="unknown";v("[swipe:touch-start]",{pointerType:Qe,allowed:je}),Zt("[swiper:touch-start]",{pointerType:Qe,allowed:je}),je&&(wn(),Fe.current=!0)},onTouchEnd:(re,Le)=>{const Qe=z3(Le),je=Qe==="touch"||Qe==="pen"||Qe==="unknown";v("[swipe:touch-end]",{pointerType:Qe,allowed:je}),Zt("[swiper:touch-end]",{pointerType:Qe,allowed:je}),je&&Wr("touch-end")},onTransitionEnd:()=>{const re=ie.current;if(Fe.current&&re&&!L$(re,ln.current)){Zt("[swiper:transition-end-deferred]");return}wn(),Fe.current=!1,Zt("[swiper:transition-end]")},initialSlide:Math.max(0,Tr),speed:I2,slidesPerView:1,resistanceRatio:.82,threshold:8,longSwipesRatio:.2,touchAngle:45,touchStartPreventDefault:!1,simulateTouch:!1,noSwiping:!0,noSwipingSelector:"[data-mobile-keyboard='true']",className:"h-full",children:It.map(re=>{const Le=re.workspace,Qe=!!Le&&re.sessions.length>=2,je=fe?Ye?"horizontal":"vertical":Le?.layout??"horizontal",bt=je==="vertical",yt=Le?.ratios.length===re.sessions.length?Le.ratios:Bc(re.sessions.length),Ut=Xe?re.sessions.findIndex(xn=>xn.id===Xe):-1,Yt=fe&&Xe?re.sessions.some(xn=>xn.id===Xe):!1,rn=re.sessions.some(xn=>xn.id===C)?C:re.sessions[0]?.id,pn=yt.flatMap((xn,Pr)=>[Yt&&Pr!==Ut?"0px":`minmax(0, ${xn}fr)`,...Pr<yt.length-1?[Yt?"0px":"1px"]:[]]).join(" "),Mn=Math.ceil(Math.sqrt(re.sessions.length)),Vn=re.sessions.length%Mn,hr={...je==="grid"?{gridTemplateColumns:`repeat(${Mn}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${Math.ceil(re.sessions.length/Mn)}, minmax(0, 1fr))`,gap:"1px"}:bt?{gridTemplateRows:pn}:{gridTemplateColumns:pn},...fe?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:{}};return o.jsx(rd,{className:"h-full",children:Qe?o.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:fe?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[o.jsx("div",{"data-split-container":"true",className:"grid min-h-0 min-w-0 flex-1 overflow-hidden",style:hr,children:re.sessions.map((xn,Pr)=>o.jsxs(M.Fragment,{children:[Nr(xn,{suppressKeyboard:fe&&xn.id!==rn,keyboardPortalTarget:fe?q:null,sharedMobileKeyboardLayout:fe,suppressPageFlipRefresh:!0,hidden:Yt&&Ut!==Pr,containerStyle:je==="grid"&&Vn>0&&Pr===re.sessions.length-1?{gridColumn:`span ${Mn-Vn+1}`}:void 0}),je!=="grid"&&Pr<re.sessions.length-1&&Le&&o.jsx("button",{type:"button",className:`swiper-no-swiping relative z-20 touch-none select-none bg-[var(--border-strong)] transition-colors hover:bg-primary active:bg-primary ${bt?"cursor-row-resize":"cursor-col-resize"} ${Yt?"invisible pointer-events-none":""}`,onPointerDownCapture:Cr=>{const hn=Cr.currentTarget.closest('[data-split-container="true"]');hn instanceof HTMLDivElement&&Kt(Cr,hn,bt,Le.id,Pr)},onDoubleClick:Cr=>{fe||(Cr.preventDefault(),Cr.stopPropagation(),he(hn=>hn.map(Ft=>Ft.id===Le.id?{...Ft,ratios:Bc(Ft.sessionIds.length)}:Ft)))},onContextMenu:Cr=>{fe&&Cr.preventDefault()},"aria-label":g("tab.split"),children:o.jsx("span",{"aria-hidden":"true","data-split-divider-hitarea":"true",className:`absolute ${bt?"inset-x-0":"inset-y-0"}`,style:bt?{top:-12,bottom:-12}:{left:-12,right:-12}})})]},xn.id))}),fe&&o.jsx("div",{ref:ue,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):Nr(re.sessions[0])},re.key)})})}),Ce&&C&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>xe(!1),"aria-label":g("common.close")}),o.jsxs("section",{className:"fixed inset-x-3 bottom-3 z-modal-panel mx-auto max-h-[min(78svh,620px)] max-w-md overflow-hidden rounded-2xl border border-border/20 bg-surface shadow-[0_24px_70px_var(--app-shadow-strong)] sm:bottom-auto sm:top-1/2 sm:-translate-y-1/2",style:{paddingBottom:"var(--safe-bottom-inset)"},role:"dialog","aria-modal":"true","aria-label":g("tab.splitTitle"),children:[o.jsxs("header",{className:"flex items-start gap-3 border-b border-border/20 px-4 py-3.5",children:[o.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:o.jsx(x0,{size:17})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:g("tab.splitTitle")}),o.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:g("tab.splitExistingHint")})]}),o.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",onClick:()=>xe(!1),"aria-label":g("common.close"),children:o.jsx(Zr,{size:16})})]}),o.jsxs("div",{className:"max-h-[calc(min(78svh,620px)-72px)] overflow-y-auto overscroll-contain p-2",children:[o.jsxs("button",{type:"button",disabled:be,onClick:()=>{Zn()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[o.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:o.jsx(Po,{size:17})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:g("tab.splitNew")}),o.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:g("tab.splitNewHint")})]})]}),ge.filter(re=>re.id!==dn?.id).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:g("tab.splitExistingGroups")}),ge.filter(re=>re.id!==dn?.id).map((re,Le)=>{const Qe=re.sessionIds.flatMap(yt=>{const Ut=S.find(Yt=>Yt.id===yt);return Ut?[Ut]:[]});if(Qe.length<2)return null;const je=re.name||`${g("tab.splitWorkspace")} ${Le+1}`,bt=Qe.map(yt=>fr(yt).primary).join(" · ");return o.jsxs("button",{type:"button",onClick:()=>nn(Qe[0].id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[o.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:o.jsx(x0,{size:15})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-foreground",children:je}),o.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:g("tab.splitOccupied")})]}),o.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[g("tab.sessionCount",{count:Qe.length})," · ",bt]})]}),o.jsx(Aa,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},re.id)})]}),o.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:g("tab.splitAvailableSessions")}),S.filter(re=>!ge.some(Le=>Le.sessionIds.includes(re.id))&&re.id!==C).length===0&&ge.filter(re=>re.id!==dn?.id).length===0?o.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:g("tab.splitNoOtherSessions")}):S.filter(re=>!ge.some(Le=>Le.sessionIds.includes(re.id))&&re.id!==C).map(re=>{const Le=Mt.get(re.id)??null,Qe=fr(re);return o.jsxs("button",{type:"button",onClick:()=>nn(re.id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[o.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground",children:Le?o.jsx(bu,{size:15}):o.jsx(x0,{size:15})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:Qe.primary}),o.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:Le?fc(Le)??Le:re.name})]}),o.jsx(Aa,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},re.id)})]})]})]}),ae&&o.jsx("div",{className:"fixed inset-x-3 bottom-4 z-toast mx-auto max-w-md rounded-xl border border-border/20 bg-surface-elevated px-4 py-3 text-center text-[12px] text-foreground shadow-lg",children:ae})]})},D$={sm:"h-4 w-7",md:"h-6 w-10"},j$={sm:"h-3 w-3",md:"h-5 w-5"},P$={sm:"translate-x-3",md:"translate-x-4"};function Rc({checked:e,disabled:t=!1,size:n="md",className:r=""}){return o.jsx("span",{"aria-hidden":"true",className:`inline-flex shrink-0 items-center rounded-full transition ${D$[n]} ${e?"bg-primary":"bg-surface-elevated"} ${t?"opacity-50":""} ${r}`,children:o.jsx("span",{className:`mx-0.5 inline-block rounded-full bg-[var(--background)] shadow transition ${j$[n]} ${e?P$[n]:""}`})})}function Jo(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var B$=typeof Symbol=="function"&&Symbol.observable||"@@observable",W3=B$,V3=()=>Math.random().toString(36).substring(7).split("").join("."),F$={INIT:`@@redux/INIT${V3()}`,REPLACE:`@@redux/REPLACE${V3()}`},q3=F$;function O$(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function FA(e,t,n){if(typeof e!="function")throw new Error(Jo(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Jo(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Jo(1));return n(FA)(e,t)}let r=e,s=t,i=new Map,a=i,c=0,u=!1;function f(){a===i&&(a=new Map,i.forEach((C,L)=>{a.set(L,C)}))}function p(){if(u)throw new Error(Jo(3));return s}function g(C){if(typeof C!="function")throw new Error(Jo(4));if(u)throw new Error(Jo(5));let L=!0;f();const E=c++;return a.set(E,C),function(){if(L){if(u)throw new Error(Jo(6));L=!1,f(),a.delete(E),i=null}}}function y(C){if(!O$(C))throw new Error(Jo(7));if(typeof C.type>"u")throw new Error(Jo(8));if(typeof C.type!="string")throw new Error(Jo(17));if(u)throw new Error(Jo(9));try{u=!0,s=r(s,C)}finally{u=!1}return(i=a).forEach(E=>{E()}),C}function v(C){if(typeof C!="function")throw new Error(Jo(10));r=C,y({type:q3.REPLACE})}function S(){const C=g;return{subscribe(L){if(typeof L!="object"||L===null)throw new Error(Jo(11));function E(){const B=L;B.next&&B.next(p())}return E(),{unsubscribe:C(E)}},[W3](){return this}}}return y({type:q3.INIT}),{dispatch:y,subscribe:g,getState:p,replaceReducer:v,[W3]:S}}function K3(e,t){return function(...n){return t(e.apply(this,n))}}function Y3(e,t){if(typeof e=="function")return K3(e,t);if(typeof e!="object"||e===null)throw new Error(Jo(16));const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=K3(s,t))}return n}function OA(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function Q$(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error(Jo(15))};const a={getState:s.getState,dispatch:(u,...f)=>i(u,...f)},c=e.map(u=>u(a));return i=OA(...c)(s.dispatch),{...s,dispatch:i}}}var Gx={exports:{}},Wx={};var X3;function $$(){if(X3)return Wx;X3=1;var e=Pg();function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,c=e.useDebugValue;return Wx.useSyncExternalStoreWithSelector=function(u,f,p,g,y){var v=s(null);if(v.current===null){var S={hasValue:!1,value:null};v.current=S}else S=v.current;v=a(function(){function C(F){if(!L){if(L=!0,E=F,F=g(F),y!==void 0&&S.hasValue){var j=S.value;if(y(j,F))return D=j}return D=F}if(j=D,n(E,F))return j;var A=g(F);return y!==void 0&&y(j,A)?(E=F,j):(E=F,D=A)}var L=!1,E,D,B=p===void 0?null:p;return[function(){return C(f())},B===null?void 0:function(){return C(B())}]},[f,p,g,y]);var T=r(u,v[0],v[1]);return i(function(){S.hasValue=!0,S.value=T},[T]),c(T),T},Wx}var Z3;function H$(){return Z3||(Z3=1,Gx.exports=$$()),Gx.exports}H$();var U$=x.version.startsWith("19"),z$=Symbol.for(U$?"react.transitional.element":"react.element"),G$=Symbol.for("react.portal"),W$=Symbol.for("react.fragment"),V$=Symbol.for("react.strict_mode"),q$=Symbol.for("react.profiler"),K$=Symbol.for("react.consumer"),Y$=Symbol.for("react.context"),QA=Symbol.for("react.forward_ref"),X$=Symbol.for("react.suspense"),Z$=Symbol.for("react.suspense_list"),nv=Symbol.for("react.memo"),J$=Symbol.for("react.lazy"),eH=QA,tH=nv;function nH(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case z$:switch(e=e.type,e){case W$:case q$:case V$:case X$:case Z$:return e;default:switch(e=e&&e.$$typeof,e){case Y$:case QA:case J$:case nv:return e;case K$:return e;default:return t}}case G$:return t}}}function rH(e){return nH(e)===nv}function sH(e,t,n,r,{areStatesEqual:s,areOwnPropsEqual:i,areStatePropsEqual:a}){let c=!1,u,f,p,g,y;function v(E,D){return u=E,f=D,p=e(u,f),g=t(r,f),y=n(p,g,f),c=!0,y}function S(){return p=e(u,f),t.dependsOnOwnProps&&(g=t(r,f)),y=n(p,g,f),y}function T(){return e.dependsOnOwnProps&&(p=e(u,f)),t.dependsOnOwnProps&&(g=t(r,f)),y=n(p,g,f),y}function C(){const E=e(u,f),D=!a(E,p);return p=E,D&&(y=n(p,g,f)),y}function L(E,D){const B=!i(D,f),F=!s(E,u,D,f);return u=E,f=D,B&&F?S():B?T():F?C():y}return function(D,B){return c?L(D,B):v(D,B)}}function iH(e,{initMapStateToProps:t,initMapDispatchToProps:n,initMergeProps:r,...s}){const i=t(e,s),a=n(e,s),c=r(e,s);return sH(i,a,c,e,s)}function oH(e,t){const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=(...i)=>t(s(...i)))}return n}function M2(e){return function(n){const r=e(n);function s(){return r}return s.dependsOnOwnProps=!1,s}}function J3(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function $A(e,t){return function(r,{displayName:s}){const i=function(c,u){return i.dependsOnOwnProps?i.mapToProps(c,u):i.mapToProps(c,void 0)};return i.dependsOnOwnProps=!0,i.mapToProps=function(c,u){i.mapToProps=e,i.dependsOnOwnProps=J3(e);let f=i(c,u);return typeof f=="function"&&(i.mapToProps=f,i.dependsOnOwnProps=J3(f),f=i(c,u)),f},i}}function rv(e,t){return(n,r)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${r.wrappedComponentName}.`)}}function aH(e){return e&&typeof e=="object"?M2(t=>oH(e,t)):e?typeof e=="function"?$A(e):rv(e,"mapDispatchToProps"):M2(t=>({dispatch:t}))}function lH(e){return e?typeof e=="function"?$A(e):rv(e,"mapStateToProps"):M2(()=>({}))}function cH(e,t,n){return{...n,...e,...t}}function uH(e){return function(n,{displayName:r,areMergedPropsEqual:s}){let i=!1,a;return function(u,f,p){const g=e(u,f,p);return i?s(g,a)||(a=g):(i=!0,a=g),a}}}function dH(e){return e?typeof e=="function"?uH(e):rv(e,"mergeProps"):()=>cH}function fH(e){e()}function hH(){let e=null,t=null;return{clear(){e=null,t=null},notify(){fH(()=>{let n=e;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=e;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const s=t={callback:n,next:null,prev:t};return s.prev?s.prev.next=s:e=s,function(){!r||e===null||(r=!1,s.next?s.next.prev=s.prev:t=s.prev,s.prev?s.prev.next=s.next:e=s.next)}}}}var e6={notify(){},get:()=>[]};function HA(e,t){let n,r=e6,s=0,i=!1;function a(T){p();const C=r.subscribe(T);let L=!1;return()=>{L||(L=!0,C(),g())}}function c(){r.notify()}function u(){S.onStateChange&&S.onStateChange()}function f(){return i}function p(){s++,n||(n=t?t.addNestedSub(u):e.subscribe(u),r=hH())}function g(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=e6)}function y(){i||(i=!0,p())}function v(){i&&(i=!1,g())}const S={addNestedSub:a,notifyNestedSubs:c,handleChangeWrapper:u,isSubscribed:f,trySubscribe:y,tryUnsubscribe:v,getListeners:()=>r};return S}var pH=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",mH=pH(),gH=()=>typeof navigator<"u"&&navigator.product==="ReactNative",xH=gH(),bH=()=>mH||xH?x.useLayoutEffect:x.useEffect,lg=bH();function t6(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Vx(e,t){if(t6(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(t,n[s])||!t6(e[n[s]],t[n[s]]))return!1;return!0}var yH={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},vH={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},wH={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},UA={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},SH={[eH]:wH,[tH]:UA};function n6(e){return rH(e)?UA:SH[e.$$typeof]||yH}var AH=Object.defineProperty,TH=Object.getOwnPropertyNames,r6=Object.getOwnPropertySymbols,CH=Object.getOwnPropertyDescriptor,kH=Object.getPrototypeOf,s6=Object.prototype;function D2(e,t){if(typeof t!="string"){if(s6){const i=kH(t);i&&i!==s6&&D2(e,i)}let n=TH(t);r6&&(n=n.concat(r6(t)));const r=n6(e),s=n6(t);for(let i=0;i<n.length;++i){const a=n[i];if(!vH[a]&&!(s&&s[a])&&!(r&&r[a])){const c=CH(t,a);try{AH(e,a,c)}catch{}}}}return e}var _H=Symbol.for("react-redux-context"),LH=typeof globalThis<"u"?globalThis:{};function EH(){if(!x.createContext)return{};const e=LH[_H]??=new Map;let t=e.get(x.createContext);return t||(t=x.createContext(null),e.set(x.createContext,t)),t}var zA=EH(),IH=[null,null];function RH(e,t,n){lg(()=>e(...t),n)}function NH(e,t,n,r,s,i){e.current=r,n.current=!1,s.current&&(s.current=null,i())}function MH(e,t,n,r,s,i,a,c,u,f,p){if(!e)return()=>{};let g=!1,y=null;const v=()=>{if(g||!c.current)return;const T=t.getState();let C,L;try{C=r(T,s.current)}catch(E){L=E,y=E}L||(y=null),C===i.current?a.current||f():(i.current=C,u.current=C,a.current=!0,p())};return n.onStateChange=v,n.trySubscribe(),v(),()=>{if(g=!0,n.tryUnsubscribe(),n.onStateChange=null,y)throw y}}function DH(e,t){return e===t}function jH(e,t,n,{pure:r,areStatesEqual:s=DH,areOwnPropsEqual:i=Vx,areStatePropsEqual:a=Vx,areMergedPropsEqual:c=Vx,forwardRef:u=!1,context:f=zA}={}){const p=f,g=lH(e),y=aH(t),v=dH(n),S=!!e;return C=>{const L=C.displayName||C.name||"Component",E=`Connect(${L})`,D={shouldHandleStateChanges:S,displayName:E,wrappedComponentName:L,WrappedComponent:C,initMapStateToProps:g,initMapDispatchToProps:y,initMergeProps:v,areStatesEqual:s,areStatePropsEqual:a,areOwnPropsEqual:i,areMergedPropsEqual:c};function B(A){const[H,Q,K]=x.useMemo(()=>{const{reactReduxForwardedRef:Be,...fe}=A;return[A.context,Be,fe]},[A]),W=x.useMemo(()=>{let Be=p;return H?.Consumer,Be},[H,p]),de=x.useContext(W),X=!!A.store&&!!A.store.getState&&!!A.store.dispatch,pe=!!de&&!!de.store,ve=X?A.store:de.store,Ae=pe?de.getServerState:ve.getState,ie=x.useMemo(()=>iH(ve.dispatch,D),[ve]),[V,z]=x.useMemo(()=>{if(!S)return IH;const Be=HA(ve,X?void 0:de.subscription),fe=Be.notifyNestedSubs.bind(Be);return[Be,fe]},[ve,X,de]),ce=x.useMemo(()=>X?de:{...de,subscription:V},[X,de,V]),ge=x.useRef(void 0),he=x.useRef(K),Ce=x.useRef(void 0),xe=x.useRef(!1),ae=x.useRef(!1),_e=x.useRef(void 0);lg(()=>(ae.current=!0,()=>{ae.current=!1}),[]);const Z=x.useMemo(()=>()=>Ce.current&&K===he.current?Ce.current:ie(ve.getState(),K),[ve,K]),Ze=x.useMemo(()=>fe=>V?MH(S,ve,V,ie,he,ge,xe,ae,Ce,z,fe):()=>{},[V]);RH(NH,[he,ge,xe,K,Ce,z]);let at;try{at=x.useSyncExternalStore(Ze,Z,Ae?()=>ie(Ae(),K):Z)}catch(Be){throw _e.current&&(Be.message+=`
|
|
78
|
+
`),$t(Tt),xt(Tt,!1),dn("Terminal session ended"),Be(!1),mt(!1),Cn(null),un(null),We(Tt,!1),Ft();break}}},onError:(it,Tt)=>{if(mn.current!==gt)return;const Gn=V;if(!Gn)return;const cr=Tt&&it.message==="Authentication required",kr=uQ(it),Kr=cr?it.message:kr||Tt?"Reconnecting...":it.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${Tt}):`,Kr),kr&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:wn.current,frontendSessionId:Gn,isActive:a,isMobile:z,fatal:Tt,stack:new Error().stack}),dn(Kr),mt(!!Tt),Tt&&(Cn(null),xt(Gn,!1),Ft(),kr&&(X("[onError] Session lost, auto-recreating"),dn("Reconnecting..."),mt(!1),$t(Gn),Ge(Gn),wn.current=null,vr.current=!1,Yt()))}},VQ);Zt.current=()=>{vt.close(),mn.current===gt&&(Tr.current=null)},Tr.current=De},[Vt,Ge,$t,X,Ft,C,pn,Yt,Le,xt,Jn,En,We,An,yr,de,V]);M.useEffect(()=>{const De=oQ({isActive:a,isStreamReady:be,reconnectStartedAt:kn,now:Date.now()});if(De===null)return;const gt=window.setTimeout(()=>{X("[Terminal] visible reconnect watchdog expired",{backendSessionId:wn.current,reconnectStartedAt:kn}),Ft(),xt(V,!1),dn("Reconnecting..."),mt(!1),Cn(Date.now()),Yt()},De);return()=>window.clearTimeout(gt)},[X,Ft,a,be,kn,Yt,V,xt]);const vr=M.useRef(!1),ar=M.useRef(!1),zr=M.useRef(0);M.useEffect(()=>()=>{zr.current+=1,vr.current=!1,Ft()},[Ft]);const Fn=M.useRef(Qt),pr=M.useRef(It);M.useEffect(()=>{const De=Fn.current,gt=pr.current;Fn.current=Qt,pr.current=It,Wr.current===V&&(De===Qt&>===It||(vr.current=!1,Ft(),Ln(vt=>vt+1)))},[Qt,It,Ft,V]),M.useEffect(()=>{if(Wr.current!==V&&(X(`[useEffect] sessionId changed from ${Wr.current} to ${V}, allowing reinitialization`),vr.current=!1,ar.current=!1),vr.current&&Wr.current===V){X(`[useEffect] Already initialized for sessionId=${V}, skipping`);return}const De=async Gn=>{if(X(`[ensureSession] Starting for sessionId=${V}, runId=${Gn}`),!Wr.current||Wr.current!==V){X(`[ensureSession] SessionId mismatch or stale run (current=${Wr.current}, target=${V}), skipping`);return}if(Gn!==zr.current){X(`[ensureSession] Stale run detected (runId=${Gn}, currentRunId=${zr.current}), skipping`);return}const cr=ns.getState(),kr=cr.getTerminalSession(V),Kr=kr?.mode??Qt;X("[ensureSession] Current state from store:",{terminalSessionId:kr?.terminalSessionId,mode:kr?.mode,tmuxSessionName:kr?.tmuxSessionName,isConnecting:kr?.isConnecting});let xr=kr?.terminalSessionId??null,ms=!xr;if(xr&&Kr!==Qt?(X(`[ensureSession] Store mode mismatch for ${xr}: current=${Kr} desired=${Qt}, will create new session`),ms=!0,cr.clearTerminalSession(V),xr=null):xr&&Qt==="tmux"&&It&&kr?.tmuxSessionName!==It&&(X(`[ensureSession] Store tmux name mismatch for ${xr}: current=${kr?.tmuxSessionName} desired=${It}, will create new session`),ms=!0,cr.clearTerminalSession(V),xr=null),xr&&de.checkHealth&&!Kt.current){X(`[ensureSession] Checking health of existing session ${xr}`);try{const _t=await de.checkHealth(xr);if(X("[ensureSession] Health check result:",_t),!_t.healthy)X(`[ensureSession] Session ${xr} is NOT healthy (healthy=${_t.healthy}), will create new session`),X("[ensureSession] Health check details:",_t),ms=!0,_t.mode&&kr?.terminalSessionId&&cr.setTerminalSession(V,{sessionId:kr.terminalSessionId,cols:80,rows:24,mode:_t.mode,tmuxSessionName:_t.tmuxSessionName??null}),cr.clearTerminalSession(V),X("[ensureSession] Cleared unhealthy session from store");else{X(`[ensureSession] Session ${xr} is healthy, reusing it, cwd=${_t.cwd}, clients=${_t.clients}, lastActivity=${Date.now()-(_t.lastActivity||0)}ms ago`),_t.mode&&kr?.terminalSessionId&&cr.setTerminalSession(V,{sessionId:kr.terminalSessionId,cols:80,rows:24,mode:_t.mode,tmuxSessionName:_t.tmuxSessionName??null}),X(`[ensureSession] Setting terminalIdRef to ${xr} and starting stream`),wn.current=xr,gr(xr),X(`[ensureSession] Successfully reused healthy session ${xr}, returning early`);return}}catch(_t){X(`[ensureSession] Failed to check health of session ${xr}:`,_t),X("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(X(`[ensureSession] Decision: shouldCreateNewSession=${ms}, terminalId=${xr}`),ms){X(`[ensureSession] Creating new session, shouldCreateNewSession=${ms}, runId=${Gn}`),dn(null),mt(!1),cr.setConnecting(V,!0);const Oo=ns.getState().getTerminalSession(V),aa=(Oo?.mode??Qt)===Qt&&(Qt!=="tmux"||!It||Oo?.tmuxSessionName===It);if(Oo?.terminalSessionId&&aa)X(`[ensureSession] Race condition avoided: another instance already created session ${Oo.terminalSessionId}`),cr.setConnecting(V,!1),xr=Oo.terminalSessionId,ms=!1;else try{const as=await je();if(X(`[ensureSession] Opened managed backend session ${as.sessionId}`),Gn!==zr.current){X(`[ensureSession] Stale run after session creation (runId=${Gn}, currentRunId=${zr.current}), leaving ${as.sessionId} for sibling`);return}cr.setTerminalSession(V,as),X(`[ensureSession] Updated store with new session ${as.sessionId}`),xr=as.sessionId}catch(as){if(Gn!==zr.current){X("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(as instanceof Va&&C3(as)){X("[ensureSession] Confirmed missing persisted session:",{sessionId:V,error:as.message}),cr.clearTerminalSession(V),dn(jx),mt(!0),cr.setConnecting(V,!1);return}dn("Reconnecting..."),mt(!0),cr.setConnecting(V,!1);return}}if(Gn!==zr.current){X(`[ensureSession] Stale run before starting stream (runId=${Gn}, currentRunId=${zr.current}), skipping`);return}if(!xr){X(`[ensureSession] No terminalId, terminalId=${xr}`);return}X(`[ensureSession] Starting stream for session ${xr}`),wn.current=xr,gr(xr),X(`[ensureSession] ensureSession completed for sessionId=${V}, terminalId=${xr}`)};let gt=null,vt=null;const it=()=>{vt=null,!(vr.current&&Wr.current===V)&&(X(`[useEffect] Running ensureSession for sessionId=${V}, hasInitialized=${vr.current}`),vr.current=!0,ar.current=!0,gt=++zr.current,De(gt))};if(!v&&!ar.current){X(`[useEffect] Holding background connection until the selected session is ready: ${V}`);return}const Tt=ar.current?0:Math.max(0,y);return Tt>0?(X(`[useEffect] Delaying initial connection for sessionId=${V} by ${Tt}ms`),vt=window.setTimeout(it,Tt)):it(),()=>{vt!==null&&window.clearTimeout(vt),X(`[useEffect] Cleanup for sessionId=${V}, runId=${gt??"pending"}`)}},[V,Nt,gr,Ft,de,X,Qt,It,Tn,y,v]);const lr=M.useCallback(async()=>{if(V&&!cn){tn(!0),dn(null),mt(!1),Cn(null),Ft();try{de.forceKill&&await de.forceKill({sessionId:V})}catch{}ut(V),Ge(V),rt.current?.clear(),await new Promise(De=>setTimeout(De,100));try{xt(V,!0);const De=await je();dt(V,De),wn.current=De.sessionId,gr(De.sessionId)}catch(De){dn(De instanceof Va&&C3(De)?jx:"Reconnecting..."),mt(!0),xt(V,!1)}finally{tn(!1)}}},[V,cn,Ft,de,ut,Ge,xt,dt,gr,je]),Hs=M.useCallback((De,gt)=>{if(!Kt.current||!De)return;const vt=wO(De),it=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(De);if(Se&&it&&(Ht.current=!0),Date.now()<qt.current)return;let Tt=De,Gn=gt?.consumeModifier??!1;if(!gt?.skipModifierTransform&&Ye&&De.length>0){const Kr=De[0];if(Kr.length===1&&/[a-zA-Z]/.test(Kr)){const xr=Kr.toUpperCase();Ye==="ctrl"?(Tt=String.fromCharCode(xr.charCodeAt(0)&31),Gn=!0):Ye==="alt"&&(Tt=`\x1B${De}`,Gn=!0)}Gn||(Ye==="alt"&&(Tt=`\x1B${De}`),Gn=!0)}const cr=wn.current;if(!cr)return;(async()=>{try{if(Se&&!vt&&Ht.current&&de.tmuxAction){Ht.current=!1;try{await de.tmuxAction(cr,{action:"copy-mode",enabled:!1})}catch{}if(SO(Tt))return}await de.sendInput(cr,Tt),Qn(V)}catch(Kr){dn(Kr instanceof Error?Kr.message:"Failed to send input")}})(),Gn&&(q||tt(null),yt())},[Ye,Qn,yt,Se,q,de]);M.useEffect(()=>{const De=gt=>{if(!Kt.current)return;const vt=gt,it=vt.detail?.text;if(!it)return;const Tt=vt.detail?.nonce;if(tr.current){Tt&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Tt,ok:!1}}));return}rt.current?.sendSequence(it,{paste:vt.detail?.paste}),Tt&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:Tt,ok:!0}})),pO(Yn.current,vt.detail?.focus!==!1)&&yt()};return window.addEventListener("termdock-insert-reference",De),()=>window.removeEventListener("termdock-insert-reference",De)},[yt]);const Er=M.useCallback((De,gt)=>{const vt=wn.current;if(!vt){pe("xterm resize push skipped: no terminalId",{cols:De,rows:gt});return}pe("xterm resize push",{cols:De,rows:gt}),de.resize({sessionId:vt,cols:De,rows:gt}).catch(it=>{it&&/session not found/i.test(String(it.message||it))&&console.warn("[Terminal] resize 404 session not found",{sessionId:vt,cols:De,rows:gt,stack:new Error().stack})})},[de,pe]),os=M.useCallback(async De=>{const gt=wn.current;if(!(!gt||!de.tmuxAction))try{const vt=await de.tmuxAction(gt,De);vt.layout&&(un(vt.layout),De.action==="switch-session"&&(dt(V,{sessionId:gt,cols:80,rows:24,mode:"tmux",tmuxSessionName:vt.layout.sessionName}),Cm(V,{tmuxSessionName:vt.layout.sessionName}).catch(it=>{console.warn("[Terminal] failed to update inventory after tmux switch",it)})))}catch(vt){dn(vt instanceof Error?vt.message:"Failed to execute tmux action")}},[V,dt,de]);M.useEffect(()=>{if(!Kn||!Ee)return;const gt=Kn.windows.find(vt=>vt.id===Kn.activeWindowId)?.panes.find(vt=>vt.id===Kn.activePaneId);gt&&rt.current?.requestRefresh("tmux-layout",{candidateSize:{cols:gt.width,rows:gt.height},skipScrollToBottom:!0,dedupeKey:`${Ee}:${Kn.sessionId}:${gt.id}:${gt.width}x${gt.height}`})},[Kn,Ee]);const ui=M.useCallback((De,gt=5)=>{const vt=Math.max(1,Math.min(Math.floor(gt)||1,40));Ht.current=!0;const it=bn.current;if(it&&it.direction===De){it.lines+=vt;return}it&&os({action:"scroll",direction:it.direction,lines:it.lines}).finally(()=>{yt()}),bn.current={direction:De,lines:vt},Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{const Tt=bn.current;Tt&&(bn.current=null,os({action:"scroll",direction:Tt.direction,lines:Tt.lines}).finally(()=>{yt()}))},0)},[yt,os]),ra=M.useCallback(De=>{const gt=Date.now(),vt=At.current,it=vt!==null&&vt.modifier===De&>-vt.timestamp<=WQ;if(At.current={modifier:De,timestamp:gt},q===De){ue(null),tt(null);return}if(it){ue(De),tt(De);return}q!==null&&q!==De&&ue(null),tt(Tt=>Tt===De?null:De)},[q]),es=M.useCallback(De=>{if(_e(De&&Kt.current),pe("input focus changed",{focused:De,isActive:Kt.current,isMobile:Yn.current}),!Yn.current||!Kt.current){xe(!1);return}xe(gt=>gt===De?gt:De)},[pe]),Ps=M.useCallback(De=>{if(Bt.current=De,pn(De,"viewport-watermark"),!De&&st.current.length>0){const gt=V;if(gt){const vt=st.current;st.current=[];for(const it of vt)Vt(gt,it)}}},[Vt,pn,V]),Xi=M.useCallback(De=>{Kt.current&&rt.current?.ensureSizeMatches(De)},[]),Ii=M.useRef(null);M.useEffect(()=>{if(!a)return;const De=Ii.current;if(!De)return;const gt=()=>Xi("pointerdown"),vt=()=>Xi("keydown"),it=()=>Xi("touchstart"),Tt=()=>Xi("wheel");return De.addEventListener("pointerdown",gt),De.addEventListener("keydown",vt),De.addEventListener("touchstart",it,{passive:!0}),De.addEventListener("wheel",Tt,{passive:!0}),()=>{De.removeEventListener("pointerdown",gt),De.removeEventListener("keydown",vt),De.removeEventListener("touchstart",it),De.removeEventListener("wheel",Tt)}},[a,Xi]);const qs=M.useCallback(De=>{rt.current=De},[]),Bs=M.useCallback(De=>{L?.(V,De)},[L,V]),So=M.useCallback(De=>{const gt=MO(De);if(!gt)return;const vt=Ye!==null;rt.current?.sendSequence(gt,{consumeModifier:vt})},[Ye]),vi=M.useCallback(De=>{const gt=LO(De);if(gt.length===0)return;const vt=Ye!==null;rt.current?.sendSequence(y3(gt[0]),{consumeModifier:vt});for(let it=1;it<gt.length;it+=1){const Tt=gt[it];window.setTimeout(()=>{rt.current?.sendSequence(y3(Tt))},_O*it)}},[Ye]),ws=M.useCallback(()=>{rt.current?.pasteClipboardText()},[]),Ir=M.useCallback(De=>{fr.current!==null&&(window.clearTimeout(fr.current),fr.current=null),Jt(De),(De==="inserted"||De==="failed")&&(fr.current=window.setTimeout(()=>{fr.current=null,Jt("idle")},1400))},[]),ps=M.useCallback(()=>{Ir("idle"),Hn(0),Nr.current?.click()},[Ir]),qr=M.useCallback(De=>{const gt=De.currentTarget.files?.[0];De.currentTarget.value="",gt&&(Hn(0),Ir("uploading"),hA(gt,(vt,it)=>Kb(vt,it,void 0,Hn),vt=>{if(!Kt.current||tr.current)throw new Error("Terminal unavailable");window.dispatchEvent(new CustomEvent("termdock-insert-reference",{detail:{text:fA(vt,null),focus:!0}}))}).then(()=>Ir("inserted"),()=>Ir("failed")))},[Ir]),Ks=Mt||en!==null;tr.current=Ks;const Ys=M.useRef(jr);Ks||(Ys.current=jr);const Bo=Ks?Ys.current:jr,Dn=M.useMemo(()=>EO(Bo,Lr),[Bo,Lr]),Zi=M.useMemo(()=>w3(Lr,ze),[ze,Lr]),Ls=!z&&ze!=="auto"&&Zi.showOnDesktop!==!0?"auto":ze,di=Ls==="auto"?Dn:Ls,Br=M.useMemo(()=>w3(Lr,di),[di,Lr]),Ji=M.useMemo(()=>Br.actions.filter(De=>De.sequence.trim().length>0).map((De,gt)=>({...De,label:b2(De,gt)})),[Br.actions]),Ca=M.useMemo(()=>nA(jr),[jr]),Es=Br.label,Us=M.useMemo(()=>Ls!=="auto"?`Manual preset: ${Br.label}`:Ca?`Auto preset · ${Br.label} (${Ca})`:"Auto preset",[Ca,Ls,Br.label]),ka=M.useCallback(De=>{Fe(De)},[]),sa=M.useCallback(()=>{ot(De=>De==="copy"?"arrows":"copy"),wt("idle")},[]),eo=M.useCallback(()=>{typeof window>"u"||(er.current!==null&&window.clearTimeout(er.current),er.current=window.setTimeout(()=>{er.current=null,wt("idle")},1200))},[]),zl=M.useCallback(De=>{er.current!==null&&typeof window<"u"&&(window.clearTimeout(er.current),er.current=null),wt(De?"copied":"failed"),eo()},[eo]),Is=M.useCallback(De=>{Ne(De)},[]),zs=M.useMemo(()=>z?IO(Lr):RO(Lr),[z,Lr]),Xs=M.useMemo(()=>cO(s),[s]),Fo=M.useMemo(()=>`terminal::${V}`,[V]);M.useEffect(()=>{H?.({isConnecting:Mt,isRestarting:cn,hasError:!!en,sessionId:Ee})},[Mt,cn,en,Ee,H]);const Ao=!Ee||Mt||cn,ia=M.useCallback((De,gt)=>{if(Ao)return;const vt=Math.max(1,Math.min(Math.floor(gt)||1,40));ui(De,vt)},[ui,Ao]);M.useEffect(()=>{if(!a||!z)return;rt.current?.requestRefresh("resize",{skipScrollToBottom:!fe,force:!0})},[a,z,fe,Ke,V]),M.useEffect(()=>{if(!a||!z)return;const De=gt=>{const vt=gt.detail;rt.current?.requestRefresh("resize",{skipScrollToBottom:vt?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",De),()=>{document.removeEventListener("termdock:viewport-keyboard-change",De)}},[a,z,V]);const oa=!D&&(z||Br.showOnDesktop===!0),To=a,Zs=z&&!F?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,Gs=z&&!F?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,si=o.jsx(DO,{visible:oa,interactive:To,presentation:z?"mobile":"desktop-actions",activeModifier:Ye,lockedModifier:q,disabled:Ao,defaultShowExtended:Xe,presetLabel:Es,presetModeLabel:Us,presetMode:Ls,presetOptions:zs,includeAlt:Br.includeAlt,presetRowLayout:Br.rowLayout,extraActions:Ji,onKeyPress:So,onTextPress:vi,onPastePress:z?ws:void 0,onFilePress:z?ps:void 0,fileUploadState:Gt,fileUploadProgress:ln,longPressMode:ft,copyFeedback:Dt,onLongPressModeToggle:sa,onModifierToggle:ra,onPresetSelect:ka,onExpandedChange:Is}),Co=typeof window<"u"&&(navigator.maxTouchPoints>0||"ontouchstart"in window);return o.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:Zs,children:[o.jsx("input",{ref:Nr,type:"file",className:"hidden",onChange:qr}),nr&&o.jsx(jO,{isMobile:z,isInputFocused:Ce,isIOS:ge,isConnecting:Mt,connectionError:en,terminalSessionId:Ee}),o.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:Xs.background,...Gs},children:[o.jsx("div",{ref:Ii,className:"h-full w-full box-border",children:o.jsx(eA,{fallback:o.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:o.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[o.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:o.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),o.jsx("span",{className:"text-sm text-muted-foreground",children:Q("terminal.componentFailed")})]})}),children:o.jsx(oO,{ref:qs,sessionKey:Fo,chunks:te,onInput:Hs,onResize:Er,onFlowControl:Ps,onTmuxScroll:Se?ia:void 0,tmuxScrollSensitivity:.38,onDoubleTap:z?()=>{rt.current?.sendSequence(" ")}:void 0,onInputFocusChange:es,onMobileLongPressCopyResult:zl,onReadyChange:Bs,onDirectoryLinkActivate:an,terminalSettings:ie,theme:Xs,enableTouchScroll:z,mobileLongPressMode:ft,autoFocus:!z&&!Co},Fo)})}),o.jsx(BO,{connectionError:en,isFatalError:Oe,isRestarting:cn,isConnecting:Mt,onHardRestart:lr})]}),B?D?null:ci.createPortal(si,B):si]})},KQ=1e3,YQ=2e4,XQ=9e4,ZQ=5e3,Gr={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let Zp=0,w0=null;function JQ(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function _A(){Gr.idleCloseTimer&&(clearTimeout(Gr.idleCloseTimer),Gr.idleCloseTimer=null)}function e$(){_A(),!(Gr.ws&&Gr.ws.readyState===WebSocket.OPEN)&&(Gr.idleCloseTimer=setTimeout(()=>{Gr.idleCloseTimer=null,Gr.listeners.size===0&&t$()},ZQ))}function t$(){if(Gr.ws){try{Gr.ws.close()}catch{}Gr.ws=null}w0&&(clearInterval(w0),w0=null)}function B3(){if(Gr.reconnectTimer)return;const e=Math.min(KQ*Math.pow(2,Gr.reconnectAttempt),YQ);Gr.reconnectAttempt+=1,Gr.reconnectTimer=setTimeout(()=>{Gr.reconnectTimer=null,LA()},e)}function LA(){const e=JQ();if(!e||Gr.ws&&Gr.ws.readyState===WebSocket.OPEN)return;let t;try{t=new WebSocket(e)}catch{B3();return}Gr.ws=t,t.onopen=()=>{Gr.reconnectAttempt=0,Zp=Date.now(),w0||(w0=setInterval(()=>{if(!(!Gr.ws||Gr.ws.readyState!==WebSocket.OPEN)&&Zp>0&&Date.now()-Zp>XQ)try{Gr.ws.close()}catch{}},3e4),w0.unref?.())},t.onmessage=n=>{Zp=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="update-state"){const a=r.state;if(!a||typeof a.status!="string"||typeof a.currentVersion!="string")return;const c={type:"update-state",state:a};for(const u of Gr.listeners)try{u(c)}catch(f){console.error("[clientStateSync] listener threw:",f)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const a={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const c of Gr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const a={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const c of Gr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const a={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const c of Gr.listeners)try{c(a)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(r.type!=="client-state"||!r.state)return;const s=r.state,i={type:"client-state",clientState:{sessions:Array.isArray(s.sessions)?s.sessions:[],updatedAt:typeof s.updatedAt=="number"?s.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const a of Gr.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}},t.onclose=()=>{Gr.ws===t&&(Gr.ws=null),Gr.listeners.size>0&&B3()},t.onerror=()=>{}}function Ah(e){return Gr.listeners.add(e),_A(),Gr.ws||LA(),()=>{Gr.listeners.delete(e),Gr.listeners.size===0&&e$()}}function EA(e,t,n){const r=e.findIndex(s=>n(s)===t);return r<0?null:e[r+1]?n(e[r+1]):r>0?n(e[r-1]):null}const Hx="termdock-sessions",k2="termdock-active-session",tv="termdock-sessions-cache";function _2(){try{const e=localStorage.getItem(k2);return e&&e.trim().length>0?e:null}catch{return null}}function Kd(e){try{e?localStorage.setItem(k2,e):localStorage.removeItem(k2)}catch{}}function IA(){if(typeof window>"u")return null;try{const e=localStorage.getItem(tv);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function Bu(e){if(!(typeof window>"u"))try{localStorage.setItem(tv,JSON.stringify(e))}catch{}}function F3(){if(!(typeof window>"u"))try{localStorage.removeItem(tv)}catch{}}function RA(e){return e.map(t=>({...t,mode:t.mode==="tmux"?"tmux":"shell",tmuxSessionName:t.tmuxSessionName??null,customName:t.customName===!0}))}function O3(e){return RA(e.map(t=>({sessionId:t.sessionId,name:t.name,customName:t.customName===!0,backendSessionId:t.backendSessionId,mode:t.mode,tmuxSessionName:t.tmuxSessionName,createdAt:t.createdAt,lastActivity:t.lastActivity}))).map((t,n)=>({...t,activeProgram:e[n]?.activeProgram??null,cwd:e[n]?.cwd??null}))}function Q3(e){return e.map(t=>`${t.sessionId}:${t.name}:${t.customName}:${t.backendSessionId}:${t.mode}:${t.tmuxSessionName}:${t.lastActivity}:${t.activeProgram??""}:${t.cwd??""}`).join("|")}function L2(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function n$(){const e=IA()??[];return{sessions:e,activeSessionId:L2(e,_2())}}function r$(){const e=x.useRef(IA()).current,t=x.useRef(_2()).current,[n,r]=x.useState(e??[]),[s,i]=x.useState(null),[a,c]=x.useState(e&&e.length>0?L2(e,t):t),[u,f]=x.useState(e===null),p=x.useRef(!1),g=x.useRef(null),y=x.useRef(e===null),v=x.useRef(0),S=x.useRef(new Set),T=x.useRef(0);x.useEffect(()=>{y.current=u},[u]),x.useEffect(()=>{g.current=a},[a]);const C=x.useCallback(pe=>{const ve=L2(pe,g.current??_2());return c(Ae=>Ae===ve?Ae:ve),Kd(ve),g.current=ve,ve},[]),L=x.useCallback((pe,ve)=>{const Ae=pe.filter(ie=>!S.current.has(ie.sessionId));r(ie=>Q3(ie)===Q3(Ae)?ie:Ae),Bu(Ae),ve?.reconcileActive&&C(Ae)},[C]),E=x.useCallback((pe,ve)=>{const Ae=S.current.size===0?pe:{...pe,clientSessions:pe.clientSessions.filter(ie=>!S.current.has(ie.sessionId))};i(Ae),L(O3(Ae.clientSessions),ve)},[L]),D=x.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(Hx)?(localStorage.removeItem(Hx),F3(),Kd(null),r([]),c(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),B=x.useCallback(async()=>{if(typeof window>"u")return[];const pe=T.current;try{const ve=await lI(),Ae=O3(ve.clientSessions);return pe!==T.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),Ae.filter(ie=>!S.current.has(ie.sessionId))):(E(ve,{reconcileActive:!0}),Ae.length>0?Ae:D())}catch(ve){console.error("Failed to restore sessions from server:",ve);try{return D()}catch(Ae){console.error("Failed to discard legacy local sessions:",Ae)}}finally{f(!1)}return[]},[E,D]),F=x.useCallback(async pe=>{const ve=++T.current,Ae=await BS(pe);return ve===T.current&&(E(Ae.inventory),c(Ae.session.sessionId),Kd(Ae.session.sessionId)),Ae},[E]),j=x.useCallback(async(pe,ve)=>{++T.current,S.current.add(pe),r(Ae=>{const ie=Ae.filter(ce=>ce.sessionId!==pe),V=ve!=null&&ie.some(ce=>ce.sessionId===ve),z=g.current===pe?V?ve:EA(Ae,pe,ce=>ce.sessionId):g.current;return c(z),Kd(z),Bu(ie),ie});try{await uI(pe)}catch(Ae){console.error("Failed to remove session from inventory:",Ae)}},[]),A=x.useCallback(pe=>{const ve=Date.now();r(Ae=>{const ie=Ae.map(V=>V.sessionId===pe?{...V,lastActivity:ve}:V);return Bu(ie),ie})},[]),H=x.useCallback(pe=>{c(pe),Kd(pe)},[]),Q=x.useCallback(async(pe,ve)=>{const Ae=ve.trim();if(!Ae)return;const ie=++T.current;r(V=>{const z=V.map(ce=>ce.sessionId===pe?{...ce,name:Ae,customName:!0}:ce);return Bu(z),z});try{const V=await Cm(pe,{name:Ae,customName:!0});ie===T.current&&E(V)}catch(V){console.error("Failed to rename session in inventory:",V)}},[E]),K=x.useCallback(async pe=>{const ve=++T.current;r(Ae=>{const ie=Ae.map(V=>V.sessionId===pe?{...V,customName:!1}:V);return Bu(ie),ie});try{const Ae=await Cm(pe,{customName:!1});ve===T.current&&E(Ae)}catch(Ae){console.error("Failed to reset session name in inventory:",Ae)}},[E]),W=x.useCallback(async pe=>{const ve=++T.current;r(Ae=>{const ie=new Map(Ae.map(he=>[he.sessionId,he])),V=pe.map(he=>ie.get(he)).filter(he=>he!==void 0),z=new Set(pe),ce=Ae.filter(he=>!z.has(he.sessionId)),ge=[...V,...ce];return Bu(ge),ge});try{const Ae=await cI(pe);ve===T.current&&E(Ae)}catch(Ae){console.error("Failed to reorder sessions in inventory:",Ae)}},[E]),de=x.useCallback(async()=>{++T.current;for(const pe of n)S.current.add(pe.sessionId);r([]),i(null),c(null),Kd(null),F3(),typeof window<"u"&&localStorage.removeItem(Hx);try{await dI()}catch(pe){console.error("Failed to clear session inventory:",pe)}},[n]),X=x.useCallback(async(pe,ve)=>{const Ae=++T.current;r(ie=>{const V=ie.map(z=>z.sessionId===pe?{...z,backendSessionId:ve}:z);return Bu(V),V});try{const ie=await Cm(pe,{backendSessionId:ve});Ae===T.current&&E(ie)}catch(ie){console.error("Failed to update session backend in inventory:",ie)}},[E]);return x.useEffect(()=>{p.current||(p.current=!0,B())},[B]),x.useEffect(()=>Ah(ve=>{if(ve.type!=="client-state"||y.current)return;const Ae=typeof ve.seq=="number"?ve.seq:null;if(Ae!==null){if(Ae<v.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:Ae,latestSeq:v.current});return}v.current=Ae}if(ve.inventory){E(ve.inventory,{reconcileActive:!0});return}const ie=RA(ve.clientState.sessions||[]);L(ie,{reconcileActive:!0})}),[E,L]),{sessions:n,inventory:s,activeSessionId:a,isLoading:u,openSession:F,removeSession:j,updateSessionActivity:A,setActiveSession:H,updateSessionBackendId:X,renameSession:Q,resetSessionCustomName:K,reorderSessions:W,clearAllSessions:de,restoreSessions:B}}const NA=5*6e4,s$=4,i$=3e4;function o$(e){const t=new Set([...e.currentVisibleSessionIds].filter(a=>e.validSessionIds.has(a))),n=e.idleMs??NA,s=Math.max(t.size*2,e.maxSessions??s$)-t.size;return s===0||[...e.lastVisitedAtBySessionId].filter(([a,c])=>e.validSessionIds.has(a)&&!t.has(a)&&Number.isFinite(c)&&e.now-c<n).sort((a,c)=>c[1]-a[1]).slice(0,s).map(([a])=>a).forEach(a=>t.add(a)),t}const a$="termdock:startup:";function fh(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${a$}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function l$(e,t){e||ci.flushSync(t)}const E2="horizontal";function Bc(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function MA(e,t){if(!Array.isArray(e)||e.length!==t)return Bc(t);const n=e.map(Number);if(n.some(s=>!Number.isFinite(s)||s<=0))return Bc(t);const r=n.reduce((s,i)=>s+i,0);return r<=0?Bc(t):n.map(s=>s/r)}function c$(e){return e==="horizontal"||e==="vertical"||e==="grid"}function u$(e){if(!Array.isArray(e))return[];const t=new Set,n=new Set,r=[];for(const s of e){if(!s||typeof s!="object")continue;const i=s;if(typeof i.id!="string"||!i.id||n.has(i.id))continue;const a=Array.isArray(i.sessionIds)?i.sessionIds.filter(u=>typeof u=="string"&&!!u&&!t.has(u)):[],c=[...new Set(a)];c.length<2||(c.forEach(u=>t.add(u)),n.add(i.id),r.push({id:i.id,...typeof i.name=="string"&&i.name.trim()?{name:i.name.trim().slice(0,80)}:{},sessionIds:c,layout:c$(i.layout)?i.layout:E2,ratios:MA(i.ratios,c.length)}))}return r}function d$(e,t){const n=new Set(t);return e.flatMap(r=>{const s=r.sessionIds.filter(i=>n.has(i));return s.length<2?[]:[{...r,sessionIds:s,ratios:s.length===r.sessionIds.length?MA(r.ratios,s.length):Bc(s.length)}]})}function Th(e,t){if(t)return e.find(n=>n.sessionIds.includes(t))}function Ux(e,t,n){if(!t||!n||t===n)return e;const r=Th(e,t),s=Th(e,n);if(r&&r.id===s?.id)return e;const i=[...r?.sessionIds??[t],...s?.sessionIds??[n]],a=[...new Set(i)],c={id:r?.id??`split:${t}`,...r?.name?{name:r.name}:{},sessionIds:a,layout:a.length>2&&(!r||r.layout===E2)?"grid":r?.layout??E2,ratios:Bc(a.length)},u=new Set([r?.id,s?.id].filter(Boolean)),f=e.filter(g=>!u.has(g.id)),p=r?Math.max(0,e.findIndex(g=>g.id===r.id)):f.length;return f.splice(Math.min(p,f.length),0,c),f}function f$(e,t){const n=Th(e,t);if(!n||!t)return e;if(n.sessionIds.length<=2)return e.filter(s=>s.id!==n.id);const r=n.sessionIds.filter(s=>s!==t);return e.map(s=>s.id===n.id?{...s,sessionIds:r,ratios:Bc(r.length)}:s)}function h$(e,t){const n=Th(e,t);return n?e.filter(r=>r.id!==n.id):e}function p$(e,t,n){return e.map(r=>{if(r.id!==t)return r;const s=[...new Set(n)],i=new Set(r.sessionIds);return s.length===r.sessionIds.length&&s.every(c=>i.has(c))?{...r,sessionIds:s}:r})}function m$(e,t,n){const r=n.trim().slice(0,80);return e.map(s=>s.id===t?{...s,...r?{name:r}:{name:void 0}}:s)}const I2=320,DA=1,g$=I2+120,x$=48,b$=72,R2="termdock:split-workspaces:v2",jA="termdock:split-workspace:v1",y$=.1,v$=.9,w$=.28,S$=300,A$=8,T$=280,C$=160;function zx(){if(typeof window>"u")return{mobile:!1,landscape:!1};const t=(navigator.maxTouchPoints>0||"ontouchstart"in window)&&Math.min(window.innerWidth,window.innerHeight)<768;return{mobile:t,landscape:t&&window.innerWidth>window.innerHeight}}function k$(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(R2);if(e)return u$(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(jA)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const n=Math.min(v$,Math.max(y$,typeof t.ratio=="number"?t.ratio:.5));return[{id:`split:${t.primaryId}`,sessionIds:[t.primaryId,t.secondaryId],layout:t.direction==="vertical"?"vertical":"horizontal",ratios:[n,1-n]}]}}catch{}return[]}function _$(e,t){const n=new Map(e.map(a=>[a.id,a])),r=new Map;t.forEach(a=>a.sessionIds.forEach(c=>r.set(c,a)));const s=new Set,i=[];for(const a of e){const c=r.get(a.id);if(!c){i.push({key:a.id,sessions:[a]});continue}if(s.has(c.id))continue;s.add(c.id);const u=c.sessionIds.flatMap(f=>{const p=n.get(f);return p?[p]:[]});u.length>=2&&i.push({key:c.id,sessions:u,workspace:c})}return i}function $3(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(n=>n.cancel())}catch{}}function Jp(e,t){const n=ag(e,t);if(n===null)return;const r=e.wrapperEl;$3(e),r&&(r.style.transitionDuration="0ms");try{const s=e;s.setTransition?.(0),s.setTranslate?.(n),$3(e),r&&(r.style.transitionDuration="0ms",r.style.transform=`translate3d(${n}px, 0px, 0px)`)}catch{r&&(r.style.transitionDuration="0ms",r.style.transform=`translate3d(${n}px, 0px, 0px)`)}}function N2(e){try{const t=typeof e.getTranslate=="function"?e.getTranslate():e.translate;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return typeof e.translate=="number"&&Number.isFinite(e.translate)?e.translate:null}}function ag(e,t){const n=e.snapGrid,r=Array.isArray(n)?n[t]:void 0;return typeof r!="number"||!Number.isFinite(r)?null:-r}function L$(e,t){const n=N2(e),r=ag(e,t);return n!==null&&r!==null&&Math.abs(n-r)<=DA}function E$(e){const t=[],n=new Map,r=new Map,s=new Map;for(const i of e){const a=n.get(i.id)??[];if(a.push(i.id),n.set(i.id,a),i.sessionId){const c=r.get(i.sessionId)??[];c.push(i.id),r.set(i.sessionId,c)}if(i.mode==="tmux"&&i.tmuxSessionName){const c=s.get(i.tmuxSessionName)??[];c.push(i.id),s.set(i.tmuxSessionName,c)}}for(const[i,a]of n)a.length>1&&t.push({kind:"frontend",key:i,sessionIds:a});for(const[i,a]of r)a.length>1&&t.push({kind:"backend",key:i,sessionIds:a});for(const[i,a]of s)a.length>1&&t.push({kind:"tmux",key:i,sessionIds:a});return t}function PA(e){const t=new Map;for(const n of e)t.set(n.id,n);return Array.from(t.values())}function BA(e){return{id:e.sessionId,name:e.name,customName:e.customName===!0,sessionId:e.backendSessionId,mode:e.mode==="tmux"||e.mode==="shell"?e.mode:"shell",tmuxSessionName:e.tmuxSessionName??null}}function I$(e,t){const n=PA(e),r=n.findIndex(s=>s.id===t.id);if(r>=0){const s=[...n];return s[r]=t,s}return[...n,t]}function H3(e,t){const n=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=n.get(r.sessionId);return{...BA(r),history:s?.history}})}function U3(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function z3(e){if(!e||typeof e!="object")return"unknown";const t=e;if(typeof t.pointerType=="string"&&t.pointerType)return t.pointerType;if(typeof t.type=="string"){if(t.type.startsWith("touch"))return"touch";if(t.type.startsWith("mouse"))return"mouse";if(t.type.startsWith("pointer"))return"pointer"}return"unknown"}function G3(e){const t=new Map;for(const[n,r]of e)t.set(n,r.cwd??null);return t}function R$(e,t){if(e.size!==t.size)return!1;for(const[n,r]of t)if(e.get(n)!==r)return!1;return!0}function N$(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const n=Date.now().toString(36),r=Math.random().toString(36).slice(2,8);return`wt-${n}${r}`}const M$=({terminalSettings:e=Ky(),colorTheme:t="dark",toolbarPresets:n=[],showDebug:r,terminalFocusAvailable:s=!0,defaultSessionMode:i="shell",defaultTmuxSessionName:a="",connectionPrioritySessionId:c=null,connectionPriorityReady:u=!0,onStatusChange:f,onSessionDataUpdate:p})=>{const{t:g}=qn(),y=x.useMemo(()=>od("session"),[]),v=x.useMemo(()=>od("terminal"),[]),[S,T]=x.useState([]),[C,L]=x.useState(null),[E,D]=x.useState(!0),[B,F]=x.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[j,A]=x.useState(()=>new Set),[H,Q]=x.useState(0),[K,W]=x.useState(()=>new Set),[de,X]=x.useState(()=>new Set),[pe,ve]=x.useState(()=>new Map),Ae=x.useRef(!1),ie=x.useRef(null),V=x.useRef({}),[z,ce]=x.useState(null),[ge,he]=x.useState(()=>k$()),[Ce,xe]=x.useState(!1),[ae,_e]=x.useState(null),[Z,Ze]=x.useState(null),[at,He]=x.useState(null),[be,Be]=x.useState(!1),[fe,Ke]=x.useState(()=>zx().mobile),[Ye,tt]=x.useState(()=>zx().landscape),[q,ue]=x.useState(null),[Xe,Ne]=x.useState(null),ze=x.useRef(s),Fe=x.useRef(!1),ft=x.useRef(null),ot=x.useRef(null),Dt=x.useRef(fe),wt=x.useRef(null),Gt=x.useRef(0),Jt=x.useRef([]),ln=x.useRef(0),Hn=x.useRef(null),we=x.useRef(!1),dt=x.useRef(!0),xt=x.useRef(null),Vt=x.useRef(""),ht=x.useRef(null),$t=x.useRef(0);x.useEffect(()=>{if(typeof window>"u")return;const re=()=>{const Le=zx();Dt.current=Le.mobile,Ke(Le.mobile),tt(Le.landscape)};return re(),window.addEventListener("resize",re),()=>window.removeEventListener("resize",re)},[]);const{sessions:ut,inventory:Ge,activeSessionId:Jn,isLoading:An,openSession:We,setActiveSession:En,removeSession:Et,renameSession:yr,resetSessionCustomName:Qn,reorderSessions:Tn,restoreSessions:_r}=r$(),mr=Ge?.tmuxRecovery??null;x.useEffect(()=>{He(null),Ze(null)},[mr?.id]);const jr=x.useCallback(async()=>{Ze("restore"),He(null);try{const re=await iI();await _r(),re.failed>0&&He(g("tab.tmuxRecoveryPartial",{restored:re.restored,failed:re.failed}))}catch{He(g("tab.tmuxRecoveryFailed"))}finally{Ze(null)}},[_r,g]),Lr=x.useCallback(async()=>{Ze("dismiss"),He(null);try{await oI(),await _r()}catch{He(g("tab.tmuxRecoveryDismissFailed"))}finally{Ze(null)}},[_r,g]),Se=ct(re=>re.groupByFolder),te=ct(re=>re.leftOpen||re.rightOpen),[Mt,Ee]=x.useState(()=>G3(ns.getState().sessions));x.useEffect(()=>ns.subscribe(re=>{const Le=G3(re.sessions);Ee(Qe=>R$(Qe,Le)?Qe:Le)}),[]);const{arranged:an}=x.useMemo(()=>J8(S,re=>Mt.get(re.id)??null,Se,""),[S,Mt,Se]),Qt=x.useRef(an);Qt.current=an;const It=x.useMemo(()=>_$(an,ge),[an,ge]),en=x.useRef(It);en.current=It;const dn=x.useMemo(()=>Th(ge,C),[C,ge]),tr=x.useMemo(()=>{const re=It.find(Le=>Le.sessions.some(Qe=>Qe.id===C));return new Set(re?.sessions.map(Le=>Le.id)??[])},[C,It]);x.useEffect(()=>{if(!fe)return;const re=()=>{const Qe=Date.now(),je=new Set(Jt.current.map(bt=>bt.id));ve(bt=>{const yt=new Map;for(const[Ut,Yt]of bt)je.has(Ut)&&(tr.has(Ut)||Qe-Yt<NA)&&yt.set(Ut,Yt);return tr.forEach(Ut=>yt.set(Ut,Qe)),yt})};re();const Le=window.setInterval(re,i$);return()=>window.clearInterval(Le)},[tr,fe]);const Oe=x.useMemo(()=>fe?o$({currentVisibleSessionIds:tr,lastVisitedAtBySessionId:pe,validSessionIds:new Set(S.map(re=>re.id)),now:Date.now()}):tr,[tr,fe,pe,S]),mt=x.useMemo(()=>Dx(S.map(re=>({id:re.id,backendSessionId:re.sessionId})),c),[c,S]),cn=x.useMemo(()=>U3(ut,Jn),[Jn,ut]),tn=Yp({prioritySessionId:mt,activeSessionId:C,persistedActiveSessionId:cn,firstSessionId:S[0]?.id??null}),kn=x.useMemo(()=>aQ(It.flatMap(re=>re.sessions.map(Le=>Le.id)),tr),[tr,It]),Cn=tn!==null&&j.has(tn),Nt=x.useCallback((re,Le)=>{A(Qe=>{if(Qe.has(re)===Le)return Qe;const bt=new Set(Qe);return Le?bt.add(re):bt.delete(re),bt})},[]),Ln=x.useCallback(re=>{const Le=mt??wt.current;re===Le&&(fh("foreground-stream-connected"),Q(Gt.current))},[mt]),Kn=x.useCallback((re,Le)=>{W(Qe=>{if(Qe.has(re)===Le)return Qe;const je=new Set(Qe);return Le?je.add(re):je.delete(re),je})},[]),un=tn!==null&&K.has(tn);x.useEffect(()=>{un&&fh("foreground-viewport-ready")},[un]),x.useEffect(()=>{if(!un||fe)return;const Le=It.flatMap(Qe=>Qe.sessions.map(je=>je.id)).filter(Qe=>Qe!==tn).map((Qe,je)=>window.setTimeout(()=>{X(bt=>{if(bt.has(Qe))return bt;const yt=new Set(bt);return yt.add(Qe),je===0&&fh("background-viewports-started"),yt})},x$+je*b$));return()=>Le.forEach(Qe=>window.clearTimeout(Qe))},[tn,un,fe,It]),x.useEffect(()=>{typeof window>"u"||(ge.length>0?(window.localStorage.setItem(R2,JSON.stringify(ge)),window.localStorage.removeItem(jA)):window.localStorage.removeItem(R2))},[ge]),x.useEffect(()=>{An||E||ge.length===0||he(re=>d$(re,S.map(Le=>Le.id)))},[An,E,S,ge.length]),x.useEffect(()=>{if(!ae)return;const re=window.setTimeout(()=>_e(null),3200);return()=>window.clearTimeout(re)},[ae]),x.useEffect(()=>()=>ht.current?.(),[]),wt.current=C,Gt.current=B.token,Jt.current=S,Hn.current=Jn,we.current=An,dt.current=E,ze.current=s;const nr=x.useCallback((re=ie.current)=>{const Le=ln.current,Qe=typeof window<"u"?window.visualViewport:null,je=re?N2(re):null,bt=re?ag(re,Le):null;return{sessionsLength:Jt.current.length,workspaceSlidesLength:en.current.length,sessionIds:Jt.current.map(yt=>yt.id),activeSessionId:wt.current,activeSessionIndex:Le,persistedActiveId:Hn.current,isLoading:we.current,isRestoring:dt.current,activeIndex:re?.activeIndex??null,previousIndex:re?.previousIndex??null,animating:re?.animating??null,allowTouchMove:re?.allowTouchMove??null,width:re?.width??null,translate:je,targetTranslate:bt,translateDelta:je!==null&&bt!==null?je-bt:null,snapGridLength:re?.snapGrid?.length??null,targetSnap:re?.snapGrid?.[Le]??null,visualViewport:Qe?{width:Math.round(Qe.width),height:Math.round(Qe.height),offsetTop:Math.round(Qe.offsetTop)}:null}},[]),Zt=x.useCallback((re,Le)=>{y(re,{...nr(),...Le})},[y,nr]);x.useEffect(()=>{An||E||C!==Jn&&En(C)},[C,An,E,Jn,En]);const Tr=x.useMemo(()=>{if(an.length===0||!C)return 0;const re=It.findIndex(Le=>Le.sessions.some(Qe=>Qe.id===C));return re>=0?re:0},[It,C]);ln.current=Tr;const wn=x.useCallback(()=>{ft.current&&(clearTimeout(ft.current),ft.current=null)},[]),Wr=x.useCallback(re=>{wn(),ft.current=setTimeout(()=>{ft.current=null,Fe.current=!1,Zt("[swiper:touch-guard-clear]",{reason:re})},g$)},[wn,Zt]),rt=x.useCallback((re,Le={})=>{const Qe=ie.current,je=ln.current,bt=en.current;if(!Qe||bt.length===0||je<0||je>=bt.length)return;if(Fe.current){Zt("[swiper:sync-skip-touch]",{reason:re});return}if(Qe.animating){Zt("[swiper:sync-skip-animating]",{reason:re});return}const yt=N2(Qe),Ut=ag(Qe,je),Yt=yt!==null&&Ut!==null&&Math.abs(yt-Ut)<=DA,rn=Qe.activeIndex===je;if(Zt("[swiper:sync-check]",{reason:re,activeIndexAligned:rn,translateAligned:Yt,immediate:Le.immediate===!0}),!(rn&&Yt)){if(rn){Jp(Qe,je),Zt("[swiper:sync-forced-active]",{reason:re,translateAligned:Yt,immediate:Le.immediate===!0});return}Le.immediate?(Jp(Qe,je),Qe.slideTo(je,0,!1),Jp(Qe,je)):Qe.slideTo(je,I2,!1),Zt("[swiper:sync-applied]",{reason:re,activeIndexAligned:rn,translateAligned:Yt,immediate:Le.immediate===!0})}},[Zt]);x.useEffect(()=>{const re=Le=>{const Qe=Le;ie.current&&(ie.current.allowTouchMove=!Qe.detail.locked),Zt("[swiper:gesture-lock]",{locked:Qe.detail.locked})};return document.addEventListener("termdock:gesture-lock",re),()=>document.removeEventListener("termdock:gesture-lock",re)},[Zt]),x.useEffect(()=>{if(S.length===0){C!==null&&L(null);return}if(!C){if(!u)return;L(Yp({prioritySessionId:mt,activeSessionId:null,persistedActiveSessionId:cn,firstSessionId:S[0]?.id??null}));return}S.some(Le=>Le.id===C)||L(S[0].id)},[S,C,u,mt,cn]);const Bt=x.useCallback((re,Le)=>{if(Le&&Date.now()<$t.current){V.current[re]=!1;return}V.current[re]=Le,Ne(Qe=>Le?re:Qe===re?null:Qe)},[]),$e=x.useCallback(re=>{if(!Fe.current&&re.activeIndex!==ln.current){Zt("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:re.activeIndex,expectedActiveIndex:ln.current}),requestAnimationFrame(()=>rt("ignored-layout-slide-change",{immediate:!0}));return}const Le=en.current[re.activeIndex],Qe=Le?.sessions.some(yt=>yt.id===C)?C:Le?.sessions[0]?.id;if(Zt("[swiper:slide-change]",{nextSessionId:Qe??null,instanceActiveIndex:re.activeIndex}),!Qe||Qe===C)return;const je=!!C&&V.current[C]===!0,bt=ze.current&&(!Dt.current||je);if(ot.current=Qe,L(Qe),bt){ce({sessionId:Qe,token:Date.now()});return}ce(null)},[S,C,Zt,rt]);x.useEffect(()=>{if(ot.current===C){Zt("[swiper:sync-skip-swiper-driven]",{activeSessionId:C}),ot.current=null;return}rt("active-session-index",{immediate:!0})},[C,Tr,S.length,rt,Zt]),x.useEffect(()=>{const re=ie.current;if(!re)return;const Le=It.length>1&&!te&&!Ce;re.allowTouchMove!==Le&&(re.allowTouchMove=Le,Zt("[swiper:allow-touch-sync]",{nextAllow:Le,sidebarOverlayOpen:te}))},[It.length,Zt,te,Ce]);const st=x.useCallback(re=>{const Le=ie.current;if(!Le)return;const Qe=Le.el;if(Zt("[swiper:layout-before]",{reason:re,scrollLeft:Qe?.scrollLeft??null}),Qe&&(Qe.scrollLeft=0),Le.updateSize(),Le.updateSlides(),Le.updateProgress(),Le.updateSlidesClasses(),Qe&&(Qe.scrollLeft=0),Zt("[swiper:layout-after]",{reason:re,scrollLeft:Qe?.scrollLeft??null}),Fe.current||Le.animating){Zt("[swiper:layout-skip-sync-motion]",{reason:re});return}rt(`layout:${re}`,{immediate:!0}),requestAnimationFrame(()=>{const je=ie.current;je&&(Fe.current||je.animating||Jp(je,ln.current))})},[Zt,rt]);x.useEffect(()=>()=>wn(),[wn]);const qt=It.map(re=>re.key).join("\0");x.useEffect(()=>{requestAnimationFrame(()=>st("group-change"))},[Se,qt,st]),x.useEffect(()=>{let re=null,Le="mount";const Qe=Yt=>{Le=Yt,re===null&&(re=requestAnimationFrame(()=>{re=null,st(`viewport-change:${Le}`)}))},je=()=>Qe("window-resize"),bt=()=>Qe("visual-viewport-resize"),yt=()=>Qe("visual-viewport-scroll"),Ut=Yt=>{Qe(`measured:${Yt.detail?.source??"unknown"}`)};return window.addEventListener("resize",je),window.visualViewport?.addEventListener("resize",bt),window.visualViewport?.addEventListener("scroll",yt),document.addEventListener(v2,Ut),Qe("mount"),()=>{window.removeEventListener("resize",je),window.visualViewport?.removeEventListener("resize",bt),window.visualViewport?.removeEventListener("scroll",yt),document.removeEventListener(v2,Ut),re!==null&&cancelAnimationFrame(re)}},[st]),x.useEffect(()=>{if(typeof document>"u")return;let re=null,Le=null,Qe=document.hidden;const je=pn=>{if(pn!=="online"&&document.hidden)return;const Mn=performance.now();if(!sQ(Le,Mn))return;Le=Mn;const Vn=pn==="bfcache"||pn==="online"?pn:"visibility",hr=iQ({wasPageHidden:Qe,reason:pn});Qe=!1,Oa("info","PWA_RESUME scheduled",{source:pn,forceForegroundReconnect:hr,activeSessionId:wt.current}),F(xn=>({token:xn.token+1,reason:Vn,forceForegroundReconnect:hr})),requestAnimationFrame(()=>st(`resume:${pn}:raf`)),re&&clearTimeout(re),re=setTimeout(()=>{re=null,st(`resume:${pn}:settled`)},320)},bt=()=>{if(document.hidden){Qe=!0,M5();return}je("visibility")},yt=()=>{Qe=!0,M5()},Ut=pn=>{je(pn.persisted?"bfcache":"pageshow")},Yt=()=>je("online"),rn=()=>je("focus");return document.addEventListener("visibilitychange",bt),window.addEventListener("pagehide",yt),window.addEventListener("pageshow",Ut),window.addEventListener("online",Yt),window.addEventListener("focus",rn),()=>{document.removeEventListener("visibilitychange",bt),window.removeEventListener("pagehide",yt),window.removeEventListener("pageshow",Ut),window.removeEventListener("online",Yt),window.removeEventListener("focus",rn),re&&clearTimeout(re)}},[st]),x.useEffect(()=>{const re=E$(S),Le=JSON.stringify(re);re.length>0&&Le!==Vt.current?(Vt.current=Le,console.warn("[session-invariant] duplicate mapping detected",re)):re.length===0&&Vt.current&&(Vt.current=""),p?.({sessions:S.map(Qe=>({id:Qe.id,name:Qe.name,customName:Qe.customName,mode:Qe.mode,tmuxSessionName:Qe.tmuxSessionName})),activeSessionId:C,splitWorkspaces:ge.map(({id:Qe,name:je,sessionIds:bt,layout:yt})=>({id:Qe,...je?{name:je}:{},sessionIds:bt,layout:yt}))})},[S,C,ge,p]),x.useEffect(()=>{if(An||Ae.current)return;Ae.current=!0;const re=Dx(ut.map(yt=>({id:yt.sessionId,backendSessionId:yt.backendSessionId??null})),c),Le=U3(ut,Jn),Qe=Yp({prioritySessionId:u?re:null,activeSessionId:null,persistedActiveSessionId:Le,firstSessionId:ut[0]?.sessionId??null}),je=PA(ut.map(BA));if(y("[Session] Restoring",je.length,"persisted sessions (one-shot)"),Zt("[swiper:restore-start]",{persistedSessionIds:ut.map(yt=>yt.sessionId),nextActiveSessionId:Qe}),je.length>0){const yt=ns.getState();je.forEach(Yt=>{Yt.sessionId&&yt.setTerminalSession(Yt.id,{sessionId:Yt.sessionId,cols:80,rows:24,mode:Yt.mode,tmuxSessionName:Yt.tmuxSessionName,history:Yt.history})}),ut.forEach(Yt=>{Yt.activeProgram!=null&&yt.setSessionActiveProgram(Yt.sessionId,Yt.activeProgram),Yt.cwd!=null&&yt.setSessionCwd(Yt.sessionId,Yt.cwd)}),T(je);const Ut=Qe||je[0]?.id||null;L(Ut),Zt("[swiper:restore-complete]",{restoredSessionIds:je.map(Yt=>Yt.id),nextActiveSessionId:Ut})}(async()=>(je.length===0&&await xt.current?.({createIfEmpty:!0}),D(!1),requestAnimationFrame(()=>rt("restore-finished",{immediate:!0}))))()},[An,ut,Jn,y,Zt,rt,u,c]),x.useEffect(()=>{if(!u||E||S.length===0)return;const re=Dx(S.map(Qe=>({id:Qe.id,backendSessionId:Qe.sessionId})),c),Le=Yp({prioritySessionId:re,activeSessionId:wt.current,persistedActiveSessionId:cn,firstSessionId:S[0]?.id??null});Le&&Le!==wt.current&&L(Le)},[u,c,E,cn,S]);const Ht=x.useRef([]),bn=x.useRef(!1);wt.current=C,x.useEffect(()=>{if(E)return;const re=Ht.current,Le=ut;if(!bn.current){T(rn=>H3(rn,Le)),Ht.current=Le,bn.current=!0;return}const Qe=new Set(re.map(rn=>rn.sessionId)),je=new Set(Le.map(rn=>rn.sessionId)),bt=new Map(re.map(rn=>[rn.sessionId,rn.name]));Ht.current=Le,T(rn=>{const pn=H3(rn,Le);return(!wt.current||!pn.some(Mn=>Mn.id===wt.current))&&L(pn[0]?.id??null),pn});const yt=Le.filter(rn=>!Qe.has(rn.sessionId)),Ut=[...Qe].filter(rn=>!je.has(rn)),Yt=Le.filter(rn=>Qe.has(rn.sessionId)&&bt.get(rn.sessionId)!==rn.name);(yt.length>0||Ut.length>0||Yt.length>0)&&y("[Session] Synced persisted sessions:",{newSessionIds:yt.map(rn=>rn.sessionId),removedSessionIds:Ut,renamedSessionIds:Yt.map(rn=>rn.sessionId),currentSessionIds:Le.map(rn=>rn.sessionId)});for(const rn of Le){if(!rn.backendSessionId)continue;ns.getState().setTerminalSession(rn.sessionId,{sessionId:rn.backendSessionId,cols:80,rows:24,mode:rn.mode,tmuxSessionName:rn.tmuxSessionName})}},[ut,E,y]);const Ie=x.useCallback(async re=>{try{const Le=re?.mode==="tmux"||re?.mode==="shell"?re.mode:i,Qe=(re?.tmuxSessionName||"").trim(),je=a.trim(),bt=Le==="tmux"?Qe||je||N$():null,yt=typeof re?.cwd=="string"?re.cwd:null,Ut=C?ns.getState().sessions.get(C)?.cwd??null:null,Yt=typeof yt=="string"&&yt.trim().length>0?yt:typeof Ut=="string"&&Ut.trim().length>0?Ut:void 0,rn=await We({mode:Le,tmuxSessionName:bt,cwd:Yt,termType:"xterm-256color",createIfEmpty:re?.createIfEmpty===!0}),pn=rn.session,Mn=rn.terminalSession,Vn={id:pn.sessionId,name:pn.name,customName:pn.customName===!0,sessionId:Mn.sessionId,mode:Mn.mode??pn.mode,tmuxSessionName:Mn.tmuxSessionName??pn.tmuxSessionName};T(Pr=>I$(Pr,Vn)),L(Vn.id),ns.getState().setTerminalSession(Vn.id,{sessionId:Mn.sessionId,cols:80,rows:24,mode:Vn.mode,tmuxSessionName:Vn.tmuxSessionName,activeProgram:Mn.activeProgram,activeProgramRaw:Mn.activeProgramRaw,activeProgramSource:Mn.activeProgramSource,cwd:Mn.cwd}),y("[Session] Inventory opened session:",{frontendSessionId:Vn.id,backendSessionId:Mn.sessionId,reused:rn.reused,mode:Vn.mode,tmuxSessionName:Vn.tmuxSessionName});const xn=re?.command?.trim();return xn&&await DS(Mn.sessionId,`${xn}\r`),Vn.id}catch(Le){return console.error("[Session] Failed to create new session:",Le),null}},[i,a,C,We,y]);xt.current=Ie;const et=x.useCallback((re,Le={})=>{const Qe=wt.current,je=!!Qe&&V.current[Qe]===!0;if(L(re),Dt.current&&Le.preserveMobileKeyboard===!1){$t.current=Date.now()+600,Qe&&(V.current[Qe]=!1),Ne(null),ce(null);const bt=document.activeElement;bt instanceof HTMLTextAreaElement&&bt.closest(".terminal-viewport-container")&&bt.blur();return}je&&Dt.current&&Ne(re),ze.current&&(!Dt.current||je)&&ce({sessionId:re,token:Date.now()})},[]),At=x.useCallback(re=>{L(re),xe(!0),_e(null)},[]),nn=x.useCallback(re=>{const Le=wt.current;!Le||Le===re||(he(Qe=>Ux(Qe,Le,re)),xe(!1),et(Le,{preserveMobileKeyboard:!1}))},[et]),Zn=x.useCallback(async()=>{const re=wt.current;if(!re||be)return;Be(!0);const Le=ns.getState().sessions.get(re)?.cwd??void 0,Qe=await Ie({cwd:Le||void 0,mode:i});if(Be(!1),!Qe){_e(g("common.error"));return}he(je=>Ux(je,re,Qe)),xe(!1),et(re,{preserveMobileKeyboard:!1})},[et,i,Ie,be,g]),fn=x.useCallback(re=>{he(Le=>h$(Le,re)),re&&et(re,{preserveMobileKeyboard:!1})},[et]),mn=x.useCallback(re=>{he(Le=>f$(Le,re)),et(re,{preserveMobileKeyboard:!1})},[et]),Kt=x.useCallback((re,Le,Qe,je,bt)=>{re.preventDefault(),re.stopPropagation();const yt=re.currentTarget,Ut=re.pointerId,Yt={x:re.clientX,y:re.clientY};yt.setPointerCapture?.(Ut);const rn=Le.getBoundingClientRect();let pn=!fe,Mn=null;const Vn=xn=>{if(xn.pointerId!==Ut)return;if(!pn){Math.hypot(xn.clientX-Yt.x,xn.clientY-Yt.y)>A$&&Mn!==null&&(window.clearTimeout(Mn),Mn=null);return}xn.preventDefault();const Pr=Qe?(xn.clientY-rn.top)/rn.height:(xn.clientX-rn.left)/rn.width,Cr=Qe?rn.height:rn.width,hn=fe?0:Qe?C$:T$;he(Ft=>Ft.map(gr=>{if(gr.id!==je)return gr;const vr=gr.ratios.length===gr.sessionIds.length?[...gr.ratios]:Bc(gr.sessionIds.length),ar=vr.slice(0,bt).reduce((lr,Hs)=>lr+Hs,0),zr=vr[bt]+vr[bt+1],Fn=hn>0?Math.min(zr/2,hn/Math.max(1,Cr)):Math.min(zr/2,w$),pr=Math.min(zr-Fn,Math.max(Fn,Pr-ar));return vr[bt]=pr,vr[bt+1]=zr-pr,{...gr,ratios:vr}}))},hr=()=>{Mn!==null&&(window.clearTimeout(Mn),Mn=null),window.removeEventListener("pointermove",Vn),window.removeEventListener("pointerup",hr),window.removeEventListener("pointercancel",hr),yt.classList.remove("bg-primary"),fe&&document.dispatchEvent(new CustomEvent("termdock:gesture-lock",{detail:{locked:!1}})),ht.current=null};ht.current?.(),ht.current=hr,window.addEventListener("pointermove",Vn),window.addEventListener("pointerup",hr),window.addEventListener("pointercancel",hr),fe&&(document.dispatchEvent(new CustomEvent("termdock:gesture-lock",{detail:{locked:!0}})),Mn=window.setTimeout(()=>{Mn=null,pn=!0,yt.classList.add("bg-primary"),navigator.vibrate?.(8)},S$))},[fe]),Yn=x.useCallback(re=>{S.find(Qe=>Qe.id===re)&&(L(re),ze.current&&!Dt.current&&ce({sessionId:re,token:Date.now()}),y("[Session] Switched to session:",re))},[S,y]),ir=x.useCallback((re,Le)=>{Le.trim()&&(T(Qe=>Qe.map(je=>je.id===re?{...je,name:Le.trim(),customName:!0}:je)),yr(re,Le.trim()))},[yr]),_n=x.useCallback(re=>{T(Le=>Le.map(Qe=>Qe.id===re?{...Qe,customName:!1}:Qe)),Qn(re)},[Qn]),wr=x.useCallback(re=>{T(Le=>{const Qe=new Map(Le.map(Ut=>[Ut.id,Ut])),je=re.map(Ut=>Qe.get(Ut)).filter(Ut=>Ut!==void 0),bt=new Set(re),yt=Le.filter(Ut=>!bt.has(Ut.id));return[...je,...yt]}),Tn(re),y("[Session] Reordered sessions:",re),requestAnimationFrame(()=>{ie.current?.update()})},[Tn,y]),Jr=x.useCallback(async re=>{const Le=typeof re=="string"?re:re.sessionId,Qe=typeof re=="string"?"auto":re.closeMode??"auto",je=S.find(yt=>yt.id===Le);if(!je)return;const bt=EA(an,Le,yt=>yt.id);try{Qe==="destroy"&&je.mode==="tmux"&&je.tmuxSessionName?(await PS(je.tmuxSessionName),y("[Session] Destroyed tmux session:",{frontendSessionId:je.id,tmuxSessionName:je.tmuxSessionName})):je.sessionId&&(await jS(je.sessionId),y("[Session] Closed backend terminal:",je.sessionId))}catch(yt){console.error("[Session] Failed to close backend terminal:",yt);return}T(yt=>{const Ut=yt.filter(Yt=>Yt.id!==Le);return L(bt),Ut}),Et(Le,bt),delete V.current[Le],y("[Session] Closed session:",{sessionId:Le,closeMode:Qe})},[S,an,Et,y]),er=x.useCallback(re=>{if(!re)return;const Le=S.filter(Qe=>Qe.sessionId===re);if(Le.length!==0){Le.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:re,frontendSessionIds:Le.map(Qe=>Qe.id)}),T(Qe=>{const je=Qe.filter(bt=>bt.sessionId!==re);return je.length!==Qe.length&&!je.some(yt=>yt.id===C)&&L(je.length>0?je[0].id:null),je});for(const Qe of Le)Et(Qe.id),delete V.current[Qe.id];y("[Session] Backend gone, dropped local session(s):",Le.map(Qe=>Qe.id))}},[S,C,Et,y]);x.useEffect(()=>{const re=hn=>{Ie(hn.detail)},Le=hn=>{Yn(hn.detail)},Qe=()=>{const hn=wt.current;!hn||Dt.current||ce({sessionId:hn,token:Date.now()})},je=hn=>{const Ft=hn;Ft.detail&&At(Ft.detail)},bt=hn=>{const Ft=hn.detail;fn(Ft??wt.current??void 0)},yt=hn=>{const Ft=hn.detail;Ft&&mn(Ft)},Ut=hn=>{const Ft=hn.detail,gr=typeof Ft=="string"?Ft:Ft?.layout,vr=typeof Ft=="string"?wt.current:Ft?.sessionId;gr!=="horizontal"&&gr!=="vertical"&&gr!=="grid"||he(ar=>ar.map(zr=>zr.sessionIds.includes(vr??"")?{...zr,layout:gr}:zr))},Yt=hn=>{const gr=hn.detail?.direction;if(gr!=="prev"&&gr!=="next")return;const vr=Qt.current;if(vr.length<=1)return;const ar=wt.current,zr=ar?vr.findIndex(Er=>Er.id===ar):-1,lr=((zr>=0?zr:0)+(gr==="next"?1:-1)+vr.length)%vr.length,Hs=vr[lr]?.id;Hs&&Hs!==ar&&Yn(Hs)},rn=hn=>{Jr(hn.detail)},pn=hn=>{er(hn.detail)},Mn=hn=>{const Ft=hn;!Ft.detail?.sessionId||!Ft.detail?.name||ir(Ft.detail.sessionId,Ft.detail.name)},Vn=hn=>{const Ft=hn;Ft.detail?.sessionId&&_n(Ft.detail.sessionId)},hr=hn=>{const Ft=hn;Ft.detail?.sessionIds&&wr(Ft.detail.sessionIds)},xn=hn=>{const Ft=hn.detail;!Ft?.workspaceId||!Array.isArray(Ft.sessionIds)||he(gr=>p$(gr,Ft.workspaceId,Ft.sessionIds))},Pr=hn=>{const Ft=hn.detail;!Ft?.workspaceId||typeof Ft.name!="string"||he(gr=>m$(gr,Ft.workspaceId,Ft.name))},Cr=hn=>{const Ft=hn.detail;!Ft?.primaryId||!Ft.secondaryId||Ft.primaryId===Ft.secondaryId||(he(gr=>Ux(gr,Ft.primaryId,Ft.secondaryId)),et(Ft.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",re),window.addEventListener("switch-terminal-session",Le),window.addEventListener("focus-active-terminal-session",Qe),window.addEventListener("open-terminal-split-chooser",je),window.addEventListener("close-terminal-split",bt),window.addEventListener("remove-terminal-split-pane",yt),window.addEventListener("set-terminal-split-direction",Ut),window.addEventListener("cycle-terminal-session",Yt),window.addEventListener("close-terminal-session",rn),window.addEventListener("close-terminal-session-by-backend",pn),window.addEventListener("rename-terminal-session",Mn),window.addEventListener("reset-terminal-session-name",Vn),window.addEventListener("reorder-terminal-session",hr),window.addEventListener("reorder-terminal-split-workspace",xn),window.addEventListener("rename-terminal-split-workspace",Pr),window.addEventListener("combine-terminal-split-sessions",Cr),()=>{window.removeEventListener("new-terminal-session",re),window.removeEventListener("switch-terminal-session",Le),window.removeEventListener("focus-active-terminal-session",Qe),window.removeEventListener("open-terminal-split-chooser",je),window.removeEventListener("close-terminal-split",bt),window.removeEventListener("remove-terminal-split-pane",yt),window.removeEventListener("set-terminal-split-direction",Ut),window.removeEventListener("cycle-terminal-session",Yt),window.removeEventListener("close-terminal-session",rn),window.removeEventListener("close-terminal-session-by-backend",pn),window.removeEventListener("rename-terminal-session",Mn),window.removeEventListener("reset-terminal-session-name",Vn),window.removeEventListener("reorder-terminal-session",hr),window.removeEventListener("reorder-terminal-split-workspace",xn),window.removeEventListener("rename-terminal-split-workspace",Pr),window.removeEventListener("combine-terminal-split-sessions",Cr)}},[et,Ie,Yn,At,fn,mn,Jr,er,ir,_n,wr]),x.useEffect(()=>{if(!dn||fe)return;const re=Le=>{if(!(Le.ctrlKey||Le.metaKey)||!Le.shiftKey)return;if(dn.layout==="horizontal"?Le.key==="ArrowLeft"||Le.key==="ArrowRight":dn.layout==="vertical"?Le.key==="ArrowUp"||Le.key==="ArrowDown":Le.key.startsWith("Arrow")){Le.preventDefault(),Le.stopPropagation();const je=dn.sessionIds.indexOf(wt.current??""),bt=Le.key==="ArrowLeft"||Le.key==="ArrowUp"?-1:1,yt=(Math.max(0,je)+bt+dn.sessionIds.length)%dn.sessionIds.length,Ut=dn.sessionIds[yt];if(!Ut)return;et(Ut);return}Le.key==="Backspace"&&(Le.preventDefault(),Le.stopPropagation(),fn(wt.current??void 0))};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[et,dn,fn,fe]);const fr=re=>{const Le=ns.getState().sessions.get(re.id);return Ic(re,Le?.activeProgram??null,Le?.cwd??null,void 0,Le?.shellTitle??null,Le?.promptState??null)},Nr=(re,Le={})=>{const Qe=re.id===C,je=u&&nQ({sessionId:re.id,foregroundSessionId:tn,visibleSessionIds:Oe,deferredViewportSessionIds:de,isMobileLayout:fe}),bt=tQ({sessionId:re.id,foregroundSessionId:tn,foregroundReady:Cn})&&u,yt=rQ({sessionId:re.id,foregroundSessionId:tn,requestToken:B.token,foregroundCompletedToken:H})&&u,Ut=re.id===tn?0:kn.get(re.id)??jm;return o.jsx("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${Le.hidden?"invisible pointer-events-none":""}`,style:Le.containerStyle,"aria-hidden":Le.hidden||void 0,onPointerDown:()=>{Qe||et(re.id)},onWheelCapture:()=>{l$(Qe,()=>et(re.id))},children:o.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:je&&o.jsx(qQ,{sessionId:re.id,mode:re.mode,tmuxSessionName:re.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:n,isActive:Qe,initialConnectEnabled:bt,resumeRequestEnabled:yt,suppressKeyboard:Le.suppressKeyboard,keyboardPortalTarget:Le.keyboardPortalTarget,sharedMobileKeyboardLayout:Le.sharedMobileKeyboardLayout,suppressPageFlipRefresh:Le.suppressPageFlipRefresh,focusRequestToken:z?.sessionId===re.id?z.token:0,resumeRequestToken:B.token,resumeRequestReason:B.reason,forceResumeReconnect:B.forceForegroundReconnect&&re.id===tn,resumeRequestDelayMs:re.id===tn?0:Le.hidden?jm:kn.get(re.id)??jm,initialConnectDelayMs:Ut,onStreamReadyChange:Nt,onStreamConnected:Ln,onViewportReadyChange:Kn,onKeyboardVisibilityChange:Bt,showDebug:r,onStatusChange:Qe?f:void 0})})},re.id)};return o.jsxs("div",{className:"relative h-full flex flex-col",children:[mr&&o.jsx("section",{className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto max-w-lg rounded-2xl border border-warning/30 bg-surface-elevated px-4 py-3.5 shadow-[0_20px_60px_var(--app-shadow-strong)]",role:"alert","aria-live":"assertive",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning",children:o.jsx(Wg,{size:18})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:g("tab.tmuxRecoveryTitle",{count:mr.sessions.length})}),o.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:g("tab.tmuxRecoveryHint")}),o.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:mr.sessions.map(re=>re.name).join(" · ")}),at&&o.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:at}),o.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[o.jsxs("button",{type:"button",disabled:Z!==null,onClick:()=>{jr()},className:"inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-[11px] font-medium text-primary-foreground transition active:opacity-80 disabled:opacity-50",children:[o.jsx(d8,{size:13,className:Z==="restore"?"animate-spin":""}),g(Z==="restore"?"tab.tmuxRecoveryRestoring":"tab.tmuxRecoveryRestoreAll")]}),o.jsx("button",{type:"button",disabled:Z!==null,onClick:()=>{Lr()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-50",children:g("tab.tmuxRecoveryDismiss")})]})]})]})}),o.jsx("div",{className:"flex-1 overflow-hidden",children:o.jsx(Qh,{onSwiper:re=>{ie.current=re,re.allowTouchMove=It.length>1&&!te&&!Ce,Zt("[swiper:on-swiper]",{allowTouchMove:re.allowTouchMove}),requestAnimationFrame(()=>st("on-swiper"))},onSlideChange:$e,onTouchStart:(re,Le)=>{const Qe=z3(Le),je=Qe==="touch"||Qe==="pen"||Qe==="unknown";v("[swipe:touch-start]",{pointerType:Qe,allowed:je}),Zt("[swiper:touch-start]",{pointerType:Qe,allowed:je}),je&&(wn(),Fe.current=!0)},onTouchEnd:(re,Le)=>{const Qe=z3(Le),je=Qe==="touch"||Qe==="pen"||Qe==="unknown";v("[swipe:touch-end]",{pointerType:Qe,allowed:je}),Zt("[swiper:touch-end]",{pointerType:Qe,allowed:je}),je&&Wr("touch-end")},onTransitionEnd:()=>{const re=ie.current;if(Fe.current&&re&&!L$(re,ln.current)){Zt("[swiper:transition-end-deferred]");return}wn(),Fe.current=!1,Zt("[swiper:transition-end]")},initialSlide:Math.max(0,Tr),speed:I2,slidesPerView:1,resistanceRatio:.82,threshold:8,longSwipesRatio:.2,touchAngle:45,touchStartPreventDefault:!1,simulateTouch:!1,noSwiping:!0,noSwipingSelector:"[data-mobile-keyboard='true']",className:"h-full",children:It.map(re=>{const Le=re.workspace,Qe=!!Le&&re.sessions.length>=2,je=fe?Ye?"horizontal":"vertical":Le?.layout??"horizontal",bt=je==="vertical",yt=Le?.ratios.length===re.sessions.length?Le.ratios:Bc(re.sessions.length),Ut=Xe?re.sessions.findIndex(xn=>xn.id===Xe):-1,Yt=fe&&Xe?re.sessions.some(xn=>xn.id===Xe):!1,rn=re.sessions.some(xn=>xn.id===C)?C:re.sessions[0]?.id,pn=yt.flatMap((xn,Pr)=>[Yt&&Pr!==Ut?"0px":`minmax(0, ${xn}fr)`,...Pr<yt.length-1?[Yt?"0px":"1px"]:[]]).join(" "),Mn=Math.ceil(Math.sqrt(re.sessions.length)),Vn=re.sessions.length%Mn,hr={...je==="grid"?{gridTemplateColumns:`repeat(${Mn}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${Math.ceil(re.sessions.length/Mn)}, minmax(0, 1fr))`,gap:"1px"}:bt?{gridTemplateRows:pn}:{gridTemplateColumns:pn},...fe?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:{}};return o.jsx(rd,{className:"h-full",children:Qe?o.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:fe?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[o.jsx("div",{"data-split-container":"true",className:"grid min-h-0 min-w-0 flex-1 overflow-hidden",style:hr,children:re.sessions.map((xn,Pr)=>o.jsxs(M.Fragment,{children:[Nr(xn,{suppressKeyboard:fe&&xn.id!==rn,keyboardPortalTarget:fe?q:null,sharedMobileKeyboardLayout:fe,suppressPageFlipRefresh:!0,hidden:Yt&&Ut!==Pr,containerStyle:je==="grid"&&Vn>0&&Pr===re.sessions.length-1?{gridColumn:`span ${Mn-Vn+1}`}:void 0}),je!=="grid"&&Pr<re.sessions.length-1&&Le&&o.jsx("button",{type:"button",className:`swiper-no-swiping relative z-20 touch-none select-none bg-[var(--border-strong)] transition-colors hover:bg-primary active:bg-primary ${bt?"cursor-row-resize":"cursor-col-resize"} ${Yt?"invisible pointer-events-none":""}`,onPointerDownCapture:Cr=>{const hn=Cr.currentTarget.closest('[data-split-container="true"]');hn instanceof HTMLDivElement&&Kt(Cr,hn,bt,Le.id,Pr)},onDoubleClick:Cr=>{fe||(Cr.preventDefault(),Cr.stopPropagation(),he(hn=>hn.map(Ft=>Ft.id===Le.id?{...Ft,ratios:Bc(Ft.sessionIds.length)}:Ft)))},onContextMenu:Cr=>{fe&&Cr.preventDefault()},"aria-label":g("tab.split"),children:o.jsx("span",{"aria-hidden":"true","data-split-divider-hitarea":"true",className:`absolute ${bt?"inset-x-0":"inset-y-0"}`,style:bt?{top:-12,bottom:-12}:{left:-12,right:-12}})})]},xn.id))}),fe&&o.jsx("div",{ref:ue,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):Nr(re.sessions[0])},re.key)})})}),Ce&&C&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>xe(!1),"aria-label":g("common.close")}),o.jsxs("section",{className:"fixed inset-x-3 bottom-3 z-modal-panel mx-auto max-h-[min(78svh,620px)] max-w-md overflow-hidden rounded-2xl border border-border/20 bg-surface shadow-[0_24px_70px_var(--app-shadow-strong)] sm:bottom-auto sm:top-1/2 sm:-translate-y-1/2",style:{paddingBottom:"var(--safe-bottom-inset)"},role:"dialog","aria-modal":"true","aria-label":g("tab.splitTitle"),children:[o.jsxs("header",{className:"flex items-start gap-3 border-b border-border/20 px-4 py-3.5",children:[o.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:o.jsx(x0,{size:17})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:g("tab.splitTitle")}),o.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:g("tab.splitExistingHint")})]}),o.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",onClick:()=>xe(!1),"aria-label":g("common.close"),children:o.jsx(Zr,{size:16})})]}),o.jsxs("div",{className:"max-h-[calc(min(78svh,620px)-72px)] overflow-y-auto overscroll-contain p-2",children:[o.jsxs("button",{type:"button",disabled:be,onClick:()=>{Zn()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[o.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:o.jsx(Po,{size:17})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:g("tab.splitNew")}),o.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:g("tab.splitNewHint")})]})]}),ge.filter(re=>re.id!==dn?.id).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:g("tab.splitExistingGroups")}),ge.filter(re=>re.id!==dn?.id).map((re,Le)=>{const Qe=re.sessionIds.flatMap(yt=>{const Ut=S.find(Yt=>Yt.id===yt);return Ut?[Ut]:[]});if(Qe.length<2)return null;const je=re.name||`${g("tab.splitWorkspace")} ${Le+1}`,bt=Qe.map(yt=>fr(yt).primary).join(" · ");return o.jsxs("button",{type:"button",onClick:()=>nn(Qe[0].id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[o.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:o.jsx(x0,{size:15})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-foreground",children:je}),o.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:g("tab.splitOccupied")})]}),o.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[g("tab.sessionCount",{count:Qe.length})," · ",bt]})]}),o.jsx(Aa,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},re.id)})]}),o.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:g("tab.splitAvailableSessions")}),S.filter(re=>!ge.some(Le=>Le.sessionIds.includes(re.id))&&re.id!==C).length===0&&ge.filter(re=>re.id!==dn?.id).length===0?o.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:g("tab.splitNoOtherSessions")}):S.filter(re=>!ge.some(Le=>Le.sessionIds.includes(re.id))&&re.id!==C).map(re=>{const Le=Mt.get(re.id)??null,Qe=fr(re);return o.jsxs("button",{type:"button",onClick:()=>nn(re.id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[o.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground",children:Le?o.jsx(bu,{size:15}):o.jsx(x0,{size:15})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:Qe.primary}),o.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:Le?fc(Le)??Le:re.name})]}),o.jsx(Aa,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},re.id)})]})]})]}),ae&&o.jsx("div",{className:"fixed inset-x-3 bottom-4 z-toast mx-auto max-w-md rounded-xl border border-border/20 bg-surface-elevated px-4 py-3 text-center text-[12px] text-foreground shadow-lg",children:ae})]})},D$={sm:"h-4 w-7",md:"h-6 w-10"},j$={sm:"h-3 w-3",md:"h-5 w-5"},P$={sm:"translate-x-3",md:"translate-x-4"};function Rc({checked:e,disabled:t=!1,size:n="md",className:r=""}){return o.jsx("span",{"aria-hidden":"true",className:`inline-flex shrink-0 items-center rounded-full transition ${D$[n]} ${e?"bg-primary":"bg-surface-elevated"} ${t?"opacity-50":""} ${r}`,children:o.jsx("span",{className:`mx-0.5 inline-block rounded-full bg-[var(--background)] shadow transition ${j$[n]} ${e?P$[n]:""}`})})}function Jo(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var B$=typeof Symbol=="function"&&Symbol.observable||"@@observable",W3=B$,V3=()=>Math.random().toString(36).substring(7).split("").join("."),F$={INIT:`@@redux/INIT${V3()}`,REPLACE:`@@redux/REPLACE${V3()}`},q3=F$;function O$(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function FA(e,t,n){if(typeof e!="function")throw new Error(Jo(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Jo(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Jo(1));return n(FA)(e,t)}let r=e,s=t,i=new Map,a=i,c=0,u=!1;function f(){a===i&&(a=new Map,i.forEach((C,L)=>{a.set(L,C)}))}function p(){if(u)throw new Error(Jo(3));return s}function g(C){if(typeof C!="function")throw new Error(Jo(4));if(u)throw new Error(Jo(5));let L=!0;f();const E=c++;return a.set(E,C),function(){if(L){if(u)throw new Error(Jo(6));L=!1,f(),a.delete(E),i=null}}}function y(C){if(!O$(C))throw new Error(Jo(7));if(typeof C.type>"u")throw new Error(Jo(8));if(typeof C.type!="string")throw new Error(Jo(17));if(u)throw new Error(Jo(9));try{u=!0,s=r(s,C)}finally{u=!1}return(i=a).forEach(E=>{E()}),C}function v(C){if(typeof C!="function")throw new Error(Jo(10));r=C,y({type:q3.REPLACE})}function S(){const C=g;return{subscribe(L){if(typeof L!="object"||L===null)throw new Error(Jo(11));function E(){const B=L;B.next&&B.next(p())}return E(),{unsubscribe:C(E)}},[W3](){return this}}}return y({type:q3.INIT}),{dispatch:y,subscribe:g,getState:p,replaceReducer:v,[W3]:S}}function K3(e,t){return function(...n){return t(e.apply(this,n))}}function Y3(e,t){if(typeof e=="function")return K3(e,t);if(typeof e!="object"||e===null)throw new Error(Jo(16));const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=K3(s,t))}return n}function OA(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function Q$(...e){return t=>(n,r)=>{const s=t(n,r);let i=()=>{throw new Error(Jo(15))};const a={getState:s.getState,dispatch:(u,...f)=>i(u,...f)},c=e.map(u=>u(a));return i=OA(...c)(s.dispatch),{...s,dispatch:i}}}var Gx={exports:{}},Wx={};var X3;function $$(){if(X3)return Wx;X3=1;var e=Pg();function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,c=e.useDebugValue;return Wx.useSyncExternalStoreWithSelector=function(u,f,p,g,y){var v=s(null);if(v.current===null){var S={hasValue:!1,value:null};v.current=S}else S=v.current;v=a(function(){function C(F){if(!L){if(L=!0,E=F,F=g(F),y!==void 0&&S.hasValue){var j=S.value;if(y(j,F))return D=j}return D=F}if(j=D,n(E,F))return j;var A=g(F);return y!==void 0&&y(j,A)?(E=F,j):(E=F,D=A)}var L=!1,E,D,B=p===void 0?null:p;return[function(){return C(f())},B===null?void 0:function(){return C(B())}]},[f,p,g,y]);var T=r(u,v[0],v[1]);return i(function(){S.hasValue=!0,S.value=T},[T]),c(T),T},Wx}var Z3;function H$(){return Z3||(Z3=1,Gx.exports=$$()),Gx.exports}H$();var U$=x.version.startsWith("19"),z$=Symbol.for(U$?"react.transitional.element":"react.element"),G$=Symbol.for("react.portal"),W$=Symbol.for("react.fragment"),V$=Symbol.for("react.strict_mode"),q$=Symbol.for("react.profiler"),K$=Symbol.for("react.consumer"),Y$=Symbol.for("react.context"),QA=Symbol.for("react.forward_ref"),X$=Symbol.for("react.suspense"),Z$=Symbol.for("react.suspense_list"),nv=Symbol.for("react.memo"),J$=Symbol.for("react.lazy"),eH=QA,tH=nv;function nH(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case z$:switch(e=e.type,e){case W$:case q$:case V$:case X$:case Z$:return e;default:switch(e=e&&e.$$typeof,e){case Y$:case QA:case J$:case nv:return e;case K$:return e;default:return t}}case G$:return t}}}function rH(e){return nH(e)===nv}function sH(e,t,n,r,{areStatesEqual:s,areOwnPropsEqual:i,areStatePropsEqual:a}){let c=!1,u,f,p,g,y;function v(E,D){return u=E,f=D,p=e(u,f),g=t(r,f),y=n(p,g,f),c=!0,y}function S(){return p=e(u,f),t.dependsOnOwnProps&&(g=t(r,f)),y=n(p,g,f),y}function T(){return e.dependsOnOwnProps&&(p=e(u,f)),t.dependsOnOwnProps&&(g=t(r,f)),y=n(p,g,f),y}function C(){const E=e(u,f),D=!a(E,p);return p=E,D&&(y=n(p,g,f)),y}function L(E,D){const B=!i(D,f),F=!s(E,u,D,f);return u=E,f=D,B&&F?S():B?T():F?C():y}return function(D,B){return c?L(D,B):v(D,B)}}function iH(e,{initMapStateToProps:t,initMapDispatchToProps:n,initMergeProps:r,...s}){const i=t(e,s),a=n(e,s),c=r(e,s);return sH(i,a,c,e,s)}function oH(e,t){const n={};for(const r in e){const s=e[r];typeof s=="function"&&(n[r]=(...i)=>t(s(...i)))}return n}function M2(e){return function(n){const r=e(n);function s(){return r}return s.dependsOnOwnProps=!1,s}}function J3(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function $A(e,t){return function(r,{displayName:s}){const i=function(c,u){return i.dependsOnOwnProps?i.mapToProps(c,u):i.mapToProps(c,void 0)};return i.dependsOnOwnProps=!0,i.mapToProps=function(c,u){i.mapToProps=e,i.dependsOnOwnProps=J3(e);let f=i(c,u);return typeof f=="function"&&(i.mapToProps=f,i.dependsOnOwnProps=J3(f),f=i(c,u)),f},i}}function rv(e,t){return(n,r)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${r.wrappedComponentName}.`)}}function aH(e){return e&&typeof e=="object"?M2(t=>oH(e,t)):e?typeof e=="function"?$A(e):rv(e,"mapDispatchToProps"):M2(t=>({dispatch:t}))}function lH(e){return e?typeof e=="function"?$A(e):rv(e,"mapStateToProps"):M2(()=>({}))}function cH(e,t,n){return{...n,...e,...t}}function uH(e){return function(n,{displayName:r,areMergedPropsEqual:s}){let i=!1,a;return function(u,f,p){const g=e(u,f,p);return i?s(g,a)||(a=g):(i=!0,a=g),a}}}function dH(e){return e?typeof e=="function"?uH(e):rv(e,"mergeProps"):()=>cH}function fH(e){e()}function hH(){let e=null,t=null;return{clear(){e=null,t=null},notify(){fH(()=>{let n=e;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=e;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const s=t={callback:n,next:null,prev:t};return s.prev?s.prev.next=s:e=s,function(){!r||e===null||(r=!1,s.next?s.next.prev=s.prev:t=s.prev,s.prev?s.prev.next=s.next:e=s.next)}}}}var e6={notify(){},get:()=>[]};function HA(e,t){let n,r=e6,s=0,i=!1;function a(T){p();const C=r.subscribe(T);let L=!1;return()=>{L||(L=!0,C(),g())}}function c(){r.notify()}function u(){S.onStateChange&&S.onStateChange()}function f(){return i}function p(){s++,n||(n=t?t.addNestedSub(u):e.subscribe(u),r=hH())}function g(){s--,n&&s===0&&(n(),n=void 0,r.clear(),r=e6)}function y(){i||(i=!0,p())}function v(){i&&(i=!1,g())}const S={addNestedSub:a,notifyNestedSubs:c,handleChangeWrapper:u,isSubscribed:f,trySubscribe:y,tryUnsubscribe:v,getListeners:()=>r};return S}var pH=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",mH=pH(),gH=()=>typeof navigator<"u"&&navigator.product==="ReactNative",xH=gH(),bH=()=>mH||xH?x.useLayoutEffect:x.useEffect,lg=bH();function t6(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Vx(e,t){if(t6(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++)if(!Object.prototype.hasOwnProperty.call(t,n[s])||!t6(e[n[s]],t[n[s]]))return!1;return!0}var yH={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},vH={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},wH={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},UA={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},SH={[eH]:wH,[tH]:UA};function n6(e){return rH(e)?UA:SH[e.$$typeof]||yH}var AH=Object.defineProperty,TH=Object.getOwnPropertyNames,r6=Object.getOwnPropertySymbols,CH=Object.getOwnPropertyDescriptor,kH=Object.getPrototypeOf,s6=Object.prototype;function D2(e,t){if(typeof t!="string"){if(s6){const i=kH(t);i&&i!==s6&&D2(e,i)}let n=TH(t);r6&&(n=n.concat(r6(t)));const r=n6(e),s=n6(t);for(let i=0;i<n.length;++i){const a=n[i];if(!vH[a]&&!(s&&s[a])&&!(r&&r[a])){const c=CH(t,a);try{AH(e,a,c)}catch{}}}}return e}var _H=Symbol.for("react-redux-context"),LH=typeof globalThis<"u"?globalThis:{};function EH(){if(!x.createContext)return{};const e=LH[_H]??=new Map;let t=e.get(x.createContext);return t||(t=x.createContext(null),e.set(x.createContext,t)),t}var zA=EH(),IH=[null,null];function RH(e,t,n){lg(()=>e(...t),n)}function NH(e,t,n,r,s,i){e.current=r,n.current=!1,s.current&&(s.current=null,i())}function MH(e,t,n,r,s,i,a,c,u,f,p){if(!e)return()=>{};let g=!1,y=null;const v=()=>{if(g||!c.current)return;const T=t.getState();let C,L;try{C=r(T,s.current)}catch(E){L=E,y=E}L||(y=null),C===i.current?a.current||f():(i.current=C,u.current=C,a.current=!0,p())};return n.onStateChange=v,n.trySubscribe(),v(),()=>{if(g=!0,n.tryUnsubscribe(),n.onStateChange=null,y)throw y}}function DH(e,t){return e===t}function jH(e,t,n,{pure:r,areStatesEqual:s=DH,areOwnPropsEqual:i=Vx,areStatePropsEqual:a=Vx,areMergedPropsEqual:c=Vx,forwardRef:u=!1,context:f=zA}={}){const p=f,g=lH(e),y=aH(t),v=dH(n),S=!!e;return C=>{const L=C.displayName||C.name||"Component",E=`Connect(${L})`,D={shouldHandleStateChanges:S,displayName:E,wrappedComponentName:L,WrappedComponent:C,initMapStateToProps:g,initMapDispatchToProps:y,initMergeProps:v,areStatesEqual:s,areStatePropsEqual:a,areOwnPropsEqual:i,areMergedPropsEqual:c};function B(A){const[H,Q,K]=x.useMemo(()=>{const{reactReduxForwardedRef:Be,...fe}=A;return[A.context,Be,fe]},[A]),W=x.useMemo(()=>{let Be=p;return H?.Consumer,Be},[H,p]),de=x.useContext(W),X=!!A.store&&!!A.store.getState&&!!A.store.dispatch,pe=!!de&&!!de.store,ve=X?A.store:de.store,Ae=pe?de.getServerState:ve.getState,ie=x.useMemo(()=>iH(ve.dispatch,D),[ve]),[V,z]=x.useMemo(()=>{if(!S)return IH;const Be=HA(ve,X?void 0:de.subscription),fe=Be.notifyNestedSubs.bind(Be);return[Be,fe]},[ve,X,de]),ce=x.useMemo(()=>X?de:{...de,subscription:V},[X,de,V]),ge=x.useRef(void 0),he=x.useRef(K),Ce=x.useRef(void 0),xe=x.useRef(!1),ae=x.useRef(!1),_e=x.useRef(void 0);lg(()=>(ae.current=!0,()=>{ae.current=!1}),[]);const Z=x.useMemo(()=>()=>Ce.current&&K===he.current?Ce.current:ie(ve.getState(),K),[ve,K]),Ze=x.useMemo(()=>fe=>V?MH(S,ve,V,ie,he,ge,xe,ae,Ce,z,fe):()=>{},[V]);RH(NH,[he,ge,xe,K,Ce,z]);let at;try{at=x.useSyncExternalStore(Ze,Z,Ae?()=>ie(Ae(),K):Z)}catch(Be){throw _e.current&&(Be.message+=`
|
|
79
79
|
The error may be correlated with this previous error:
|
|
80
80
|
${_e.current.stack}
|
|
81
81
|
|
|
@@ -179,12 +179,12 @@ ${z.desc}`:""}`,"aria-pressed":C===z.key,onPointerEnter:()=>T(z.key),onPointerLe
|
|
|
179
179
|
|
|
180
180
|
`;return`${e}${r}${n}`}function pee(e,t){const n=e.trim();return n?t?`${n}\r`:/\s$/.test(e)?e:`${n} `:""}const dy="termdock:right-sidebar:html-view-mode-by-file:v1";function mee(e){return e==="preview"||e==="source"}function gC(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(mee)}function xC(e,t){if(!t)return null;const n=e&&!t.startsWith("/")?`${e}/${t}`:t;return e?`${e}::${n}`:n}function m7(e,t){const n=xC(e,t);return n?Ur(dy,gC)?.[n]??"source":"source"}function gee(e,t,n){const r=xC(e,t);if(!r)return;const s=Ur(dy,gC)??{};$n(dy,{...s,[r]:n})}function Ab(e){const t=Number.isFinite(e)&&e>0?Math.floor(e):0,n=Math.floor(t/3600),r=Math.floor(t%3600/60),s=t%60,i=String(r).padStart(2,"0"),a=String(s).padStart(2,"0");return n>0?`${n}:${i}:${a}`:`${i}:${a}`}function xee(e,t,n){return!Number.isFinite(n)||n<=0||!t.width?0:Math.min(1,Math.max(0,(e-t.left)/t.width))*n}const bee=350,yee=12,vee=90;function wee({url:e,onLoadError:t}){const{t:n}=qn(),r=x.useRef(null),s=x.useRef(null),i=x.useRef(null),a=x.useRef(null),c=x.useRef(!1),u=x.useRef(null),f=x.useRef(null),p=x.useRef(0),g=x.useRef(!1),y=x.useRef(!1),v=x.useRef(!1),S=x.useRef(null),T=x.useRef(null),C=x.useRef(!1),L=x.useRef(1),E=x.useRef(!1),[D,B]=x.useState(0),[F,j]=x.useState(0),[A,H]=x.useState(!1),[Q,K]=x.useState(!1),[W,de]=x.useState(null),[X,pe]=x.useState(!1),[ve,Ae]=x.useState(0),[ie,V]=x.useState(!1),[z,ce]=x.useState({width:0,height:0}),ge=x.useCallback(()=>{S.current!==null&&(clearTimeout(S.current),S.current=null)},[]),he=x.useCallback(()=>{if(ge(),T.current=null,!C.current)return!1;const Ne=i.current;return Ne&&(Ne.playbackRate=L.current),C.current=!1,pe(!1),!0},[ge]);x.useEffect(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),f.current!==null&&clearTimeout(f.current),ge();const Ne=i.current;Ne&&C.current&&(Ne.playbackRate=L.current)},[ge]),x.useEffect(()=>{const Ne=s.current;if(!Ne||typeof ResizeObserver>"u")return;const ze=new ResizeObserver(([Fe])=>{Fe&&ce({width:Fe.contentRect.width,height:Fe.contentRect.height})});return ze.observe(Ne),()=>ze.disconnect()},[]),x.useEffect(()=>{const Ne=()=>V(document.fullscreenElement===r.current);return document.addEventListener("fullscreenchange",Ne),()=>document.removeEventListener("fullscreenchange",Ne)},[]);const Ce=x.useCallback((Ne,ze=!1)=>{const Fe=i.current;if(!Fe)return!1;const ft=Number.isFinite(Fe.duration)?Fe.duration:Ne,ot=Math.min(Math.max(Ne,0),ft);if(j(ot),Math.abs(Fe.currentTime-ot)<1/120)return!1;const Dt=Fe.fastSeek;return ze&&typeof Dt=="function"?Dt.call(Fe,ot):Fe.currentTime=ot,!0},[]),xe=x.useCallback(()=>{u.current===null&&(u.current=requestAnimationFrame(()=>{u.current=null;const Ne=i.current;if(!Ne||!g.current||y.current||Ne.seeking)return;const ze=v.current;v.current=!1,y.current=Ce(p.current,!ze)}))},[Ce]),ae=x.useCallback(Ne=>{const ze=a.current,Fe=i.current;if(!ze||!Fe)return;const ft=ze.getBoundingClientRect(),ot=xee(Ne,ft,Fe.duration);p.current=ot,de(ot),v.current=!1,xe(),f.current!==null&&clearTimeout(f.current),f.current=setTimeout(()=>{f.current=null,v.current=!0,xe()},vee)},[xe]),_e=x.useCallback(()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),f.current!==null&&(clearTimeout(f.current),f.current=null),v.current=!1,y.current=!1,Ce(p.current)},[Ce]),Z=x.useCallback(Ne=>{const ze=i.current;if(!(!ze||!Number.isFinite(ze.duration)||ze.duration<=0)){c.current=!ze.paused,ze.pause(),g.current=!0,K(!0);try{Ne.currentTarget.setPointerCapture(Ne.pointerId)}catch{}ae(Ne.clientX)}},[ae]),Ze=x.useCallback(()=>{g.current=!1,_e(),K(!1),de(null);const Ne=i.current;Ne&&c.current&&!Ne.ended&&Ne.play().catch(()=>{}),c.current=!1},[_e]),at=x.useCallback(()=>{const Ne=i.current;if(Ne){if(E.current){E.current=!1;return}Ne.paused?Ne.play().catch(()=>{}):Ne.pause()}},[]),He=x.useCallback(Ne=>{const ze=i.current;!ze||ze.paused||Ne.button!==0||(ge(),T.current={id:Ne.pointerId,x:Ne.clientX,y:Ne.clientY},S.current=setTimeout(()=>{S.current=null,L.current=ze.playbackRate,ze.playbackRate=2,C.current=!0,pe(!0)},bee))},[ge]),be=x.useCallback(Ne=>{const ze=T.current;!ze||ze.id!==Ne.pointerId||C.current||Math.hypot(Ne.clientX-ze.x,Ne.clientY-ze.y)>yee&&(ge(),T.current=null)},[ge]),Be=x.useCallback(()=>{he()&&(E.current=!0)},[he]);x.useEffect(()=>(window.addEventListener("pointerup",Be),window.addEventListener("pointercancel",Be),window.addEventListener("blur",Be),()=>{window.removeEventListener("pointerup",Be),window.removeEventListener("pointercancel",Be),window.removeEventListener("blur",Be)}),[Be]);const fe=x.useCallback(async()=>{const Ne=r.current,ze=i.current;if(!(!Ne||!ze))try{document.fullscreenElement===Ne?await document.exitFullscreen():Ne.requestFullscreen?await Ne.requestFullscreen():ze.webkitEnterFullscreen?.()}catch{ze.webkitEnterFullscreen?.()}},[]),Ke=x.useCallback(()=>Ae(Ne=>(Ne+90)%360),[]),Ye=x.useCallback(Ne=>{const ze=i.current;if(!ze||!Number.isFinite(ze.duration))return;const Fe=Ne.shiftKey?10:5;let ft=null;Ne.key==="ArrowLeft"?ft=ze.currentTime-Fe:Ne.key==="ArrowRight"?ft=ze.currentTime+Fe:Ne.key==="Home"?ft=0:Ne.key==="End"&&(ft=ze.duration),ft!==null&&(Ne.preventDefault(),Ce(ft))},[Ce]),tt=Q&&W!==null?W:F,q=D>0?Math.min(1,Math.max(0,tt/D)):0,Xe=(ve===90||ve===270)&&z.width>0&&z.height>0?{width:`${z.height}px`,height:`${z.width}px`}:{width:"100%",height:"100%"};return o.jsxs("div",{ref:r,className:"flex h-full min-h-0 flex-col overflow-hidden rounded-lg bg-background fullscreen:h-screen fullscreen:w-screen fullscreen:rounded-none","data-testid":"file-preview-video-player","data-rotation":ve,children:[o.jsxs("div",{ref:s,className:"relative min-h-0 flex-1 overflow-hidden bg-background",children:[o.jsx("video",{ref:i,"data-testid":"file-preview-video",className:"absolute left-1/2 top-1/2 max-w-none object-contain transition-transform duration-200",style:{...Xe,transform:`translate(-50%, -50%) rotate(${ve}deg)`},src:e,preload:"auto",playsInline:!0,onClick:at,onPointerDown:He,onPointerMove:be,onPointerUp:Be,onPointerCancel:Be,onContextMenu:Ne=>{C.current&&Ne.preventDefault()},onPlay:()=>H(!0),onPause:()=>H(!1),onTimeUpdate:Ne=>j(Ne.currentTarget.currentTime),onSeeked:Ne=>{const ze=Ne.currentTarget;if(j(ze.currentTime),y.current=!1,!g.current)return;const Fe=ze.requestVideoFrameCallback;typeof Fe=="function"?Fe.call(ze,()=>{g.current&&xe()}):requestAnimationFrame(()=>{g.current&&xe()})},onLoadedMetadata:Ne=>B(Number.isFinite(Ne.currentTarget.duration)?Ne.currentTarget.duration:0),onDurationChange:Ne=>B(Number.isFinite(Ne.currentTarget.duration)?Ne.currentTarget.duration:0),onError:t,children:n("rightSidebar.videoUnsupported")}),X&&o.jsx("div",{className:"pointer-events-none absolute left-1/2 top-3 z-10 -translate-x-1/2 rounded-full bg-surface-elevated px-3 py-1 text-xs font-semibold tabular-nums text-foreground shadow-md",children:n("rightSidebar.videoLongPressSpeed")}),Q&&W!==null&&o.jsx("div",{className:"pointer-events-none absolute bottom-1 z-10 -translate-x-1/2 rounded-md bg-surface-elevated px-2 py-1 text-[11px] font-medium text-foreground shadow-md",style:{left:`${q*100}%`},"data-testid":"file-preview-video-scrub-time",children:Ab(W)})]}),o.jsx("div",{"data-testid":"file-preview-video-controls",className:`shrink-0 border-t border-border/60 bg-background px-2 py-1.5 ${cT}`,[uT]:"",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button",onClick:at,"aria-label":n(A?"rightSidebar.videoPause":"rightSidebar.videoPlay"),title:n(A?"rightSidebar.videoPause":"rightSidebar.videoPlay"),className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-foreground transition hover:bg-surface-elevated active:scale-95","data-testid":"file-preview-video-play",children:A?o.jsx(c8,{size:14}):o.jsx(s2,{size:14})}),o.jsxs("div",{ref:a,role:"slider","aria-label":"Seek","aria-valuemin":0,"aria-valuemax":Math.floor(D),"aria-valuenow":Math.floor(tt),tabIndex:0,className:"group relative h-5 min-w-0 flex-1 cursor-pointer touch-none py-2","data-testid":"file-preview-video-track",onPointerDown:Z,onPointerMove:Ne=>{Q&&ae(Ne.clientX)},onPointerUp:Ze,onPointerCancel:Ze,onKeyDown:Ye,children:[o.jsx("div",{className:"h-1 w-full rounded-full bg-surface-elevated"}),o.jsx("div",{className:"absolute inset-y-0 left-0 my-auto h-1 rounded-full bg-primary",style:{width:`${q*100}%`}}),o.jsx("div",{className:"absolute top-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary shadow",style:{left:`${q*100}%`}})]}),o.jsxs("div",{className:"shrink-0 text-[11px] tabular-nums text-muted-foreground","data-testid":"file-preview-video-time",children:[Ab(tt)," / ",Ab(D)]}),o.jsx("button",{type:"button",onClick:Ke,"aria-label":n("rightSidebar.videoRotate"),title:n("rightSidebar.videoRotate"),className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-foreground transition hover:bg-surface-elevated active:scale-95","data-testid":"file-preview-video-rotate",children:o.jsx(uD,{size:14})}),o.jsx("button",{type:"button",onClick:()=>{fe()},"aria-label":n(ie?"rightSidebar.videoFullscreenExit":"rightSidebar.videoFullscreenEnter"),title:n(ie?"rightSidebar.videoFullscreenExit":"rightSidebar.videoFullscreenEnter"),className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-foreground transition hover:bg-surface-elevated active:scale-95","data-testid":"file-preview-video-fullscreen",children:ie?o.jsx(OM,{size:14}):o.jsx(DM,{size:14})})]})})]})}function See(e){const t=Math.max(0,Math.min(100,e.xPercent)),n=Math.max(0,Math.min(100,e.yPercent));return{...t<=50?{left:`calc(${t}% + 8px)`}:{right:`calc(${100-t}% + 8px)`},...n<=50?{top:`calc(${n}% + 8px)`}:{bottom:`calc(${100-n}% + 8px)`}}}function f1({anchor:e,children:t,disabled:n=!1,onClick:r,title:s}){return o.jsxs("button",{type:"button","data-floating-annotation-button":!0,disabled:n,onClick:i=>{i.stopPropagation(),r()},title:s,style:See(e),className:"absolute z-30 inline-flex h-7 items-center gap-1 rounded-full bg-primary px-3 text-[11px] font-semibold text-primary-foreground shadow-lg ring-1 ring-primary/30 transition hover:bg-primary/90 active:scale-95 disabled:cursor-wait disabled:opacity-50",children:[o.jsx(Ul,{size:11}),t]})}function Aee(e,t,n,r){if(n.width<=0||n.height<=0||r.width<=0||r.height<=0)return null;const s=Math.min(n.width/r.width,n.height/r.height);if(!Number.isFinite(s)||s<=0)return null;const i=r.width*s,a=r.height*s,c=n.left+(n.width-i)/2,u=n.top+(n.height-a)/2,f=e-c,p=t-u;if(f<0||p<0||f>i||p>a)return null;const g=f/i*100,y=p/a*100;return{x:r.x+r.width*g/100,y:r.y+r.height*y/100,xPercent:g,yPercent:y}}function Tee(e,t,n){const r=[`SVG标注: ${e}`,`视图: ${t}`,`SVG坐标: (${n.x.toFixed(2)},${n.y.toFixed(2)}) [viewBox坐标]`,`图片位置: (${n.xPercent.toFixed(1)}%,${n.yPercent.toFixed(1)}%) [相对内容边界左上角]`];return n.nearestText&&r.push(`最近文字: ${n.nearestText}`),`"${r.join(" / ")}"`}function Cee(e){const t=new DOMParser().parseFromString(e,"image/svg+xml"),n=t.documentElement;if(n.nodeName.toLowerCase()!=="svg"||t.querySelector("parsererror"))throw new Error("Invalid SVG document");return t.querySelectorAll("script,foreignObject,iframe,object,embed").forEach(r=>r.remove()),t.querySelectorAll("*").forEach(r=>{for(const s of Array.from(r.attributes)){const i=s.name.toLowerCase(),a=s.value.trim();(i.startsWith("on")||(i==="href"||i.endsWith(":href"))&&a&&!a.startsWith("#"))&&r.removeAttribute(s.name)}}),n.removeAttribute("width"),n.removeAttribute("height"),n.setAttribute("preserveAspectRatio","xMidYMid meet"),new XMLSerializer().serializeToString(n)}function kee(e,t,n){let r=null;for(const s of Array.from(e.querySelectorAll("text"))){const i=(s.textContent??"").replace(/\s+/g," ").trim();if(!i)continue;const a=Number(s.getAttribute("x")),c=Number(s.getAttribute("y"));if(!Number.isFinite(a)||!Number.isFinite(c))continue;const u=Math.hypot(a-t,c-n);(!r||u<r.distance)&&(r={text:i,distance:u})}return r?.text.slice(0,120)}function bC({blobUrl:e,filePath:t,viewLabel:n,onInsertAnnotation:r}){const s=x.useRef(null),i=x.useRef(null),[a,c]=x.useState(null),[u,f]=x.useState(null),[p,g]=x.useState(1),[y,v]=x.useState(!1),[S,T]=x.useState(null),C=x.useRef(new Map),L=x.useRef(null),E=x.useRef(!1),D=x.useRef(null),B=x.useRef(p);B.current=p,x.useEffect(()=>{const ie=new AbortController;return c(null),f(null),T(null),g(1),fetch(e,{signal:ie.signal}).then(V=>V.text()).then(V=>c(Cee(V))).catch(V=>{ie.signal.aborted||f(V instanceof Error?V.message:"SVG preview failed")}),()=>ie.abort()},[e]),x.useEffect(()=>{if(!y)return;const ie=V=>{V.key==="Escape"&&v(!1)};return window.addEventListener("keydown",ie),()=>window.removeEventListener("keydown",ie)},[y]),x.useLayoutEffect(()=>{const ie=i.current,V=ie?.querySelector("[data-svg-document] > svg");if(!ie||!V)return;let z;try{z=V.getBBox()}catch{return}if(!z.width||!z.height)return;const ce=Math.max(2,Math.min(z.width,z.height)*.025);V.setAttribute("viewBox",`${z.x-ce} ${z.y-ce} ${z.width+2*ce} ${z.height+2*ce}`),V.style.width=`${p*100}%`,V.style.height=`${p*100}%`,V.style.minWidth=`${p*100}%`,V.style.minHeight=`${p*100}%`,V.style.display="block"},[a,p]);const F=x.useMemo(()=>S?Tee(t,n,S):null,[t,S,n]),j=ie=>{if(E.current){E.current=!1;return}const V=i.current,z=V?.querySelector("[data-svg-document] > svg"),ce=s.current;if(!V||!z||!ce)return;const ge=z.viewBox.baseVal,he=Aee(ie.clientX,ie.clientY,z.getBoundingClientRect(),ge);if(!he)return;const Ce=ce.getBoundingClientRect();T({...he,nearestText:kee(z,he.x,he.y),stageX:ie.clientX-Ce.left,stageY:ie.clientY-Ce.top,stageXPercent:(ie.clientX-Ce.left)/Ce.width*100,stageYPercent:(ie.clientY-Ce.top)/Ce.height*100})},A=ie=>Math.max(1,Math.min(12,ie)),H=(ie,V)=>{const z=A(V),ce=ie.querySelector("[data-svg-document] > svg");if(!ce)return z;const ge=`${z*100}%`;return ce.style.width=ge,ce.style.height=ge,ce.style.minWidth=ge,ce.style.minHeight=ge,B.current=z,z},Q=(ie,V,z,ce)=>{const ge=B.current,he=ie.getBoundingClientRect(),Ce=z-he.left,xe=ce-he.top,ae=(ie.scrollLeft+Ce)/ge,_e=(ie.scrollTop+xe)/ge,Z=H(ie,V);return ie.scrollLeft=ae*Z-Ce,ie.scrollTop=_e*Z-xe,Z},K=()=>{const ie=Array.from(C.current.values());return ie.length>=2?Math.hypot(ie[0].x-ie[1].x,ie[0].y-ie[1].y):0},W=ie=>{if(ie.pointerType==="mouse"&&ie.button!==0)return;const V=i.current;V&&(C.current.set(ie.pointerId,{x:ie.clientX,y:ie.clientY}),V.setPointerCapture?.(ie.pointerId),C.current.size>=2?(L.current={kind:"pinch",startX:ie.clientX,startY:ie.clientY,startScrollLeft:V.scrollLeft,startScrollTop:V.scrollTop,startDistance:K(),startZoom:B.current,moved:!1},E.current=!0):B.current>1&&(L.current={kind:"pan",startX:ie.clientX,startY:ie.clientY,startScrollLeft:V.scrollLeft,startScrollTop:V.scrollTop,startZoom:B.current,moved:!1}))},de=ie=>{if(!C.current.has(ie.pointerId))return;C.current.set(ie.pointerId,{x:ie.clientX,y:ie.clientY});const V=i.current,z=L.current;if(!(!V||!z)){if(C.current.size>=2&&z.kind==="pinch"){const ce=K();if(!z.startDistance||!ce)return;const ge=A(z.startZoom*ce/z.startDistance);if(Math.abs(ge-B.current)<.01)return;const he=Array.from(C.current.values()),Ce=(he[0].x+he[1].x)/2,xe=(he[0].y+he[1].y)/2;z.moved=!0,E.current=!0,Q(V,ge,Ce,xe),ie.preventDefault();return}if(z.kind==="pan"&&C.current.size===1){const ce=ie.clientX-z.startX,ge=ie.clientY-z.startY;if(!z.moved&&Math.hypot(ce,ge)<6)return;z.moved=!0,E.current=!0,V.scrollLeft=z.startScrollLeft-ce,V.scrollTop=z.startScrollTop-ge,ie.preventDefault()}}},X=ie=>{const V=i.current,z=L.current,ce=C.current.size===1&&!z?.moved;C.current.delete(ie.pointerId);try{V?.releasePointerCapture?.(ie.pointerId)}catch{}if(C.current.size===1&&z?.kind==="pinch"){const Ce=Array.from(C.current.values())[0];L.current=V?{kind:"pan",startX:Ce.x,startY:Ce.y,startScrollLeft:V.scrollLeft,startScrollTop:V.scrollTop,startZoom:B.current,moved:!1}:null;return}if(C.current.size>0||(L.current=null,z?.kind==="pinch"&&g(B.current),!ce||E.current))return;const ge=Date.now(),he=D.current;he&&ge-he.time<350&&Math.hypot(ie.clientX-he.x,ie.clientY-he.y)<24?(D.current=null,E.current=!0,g(Ce=>Ce>1?1:2.5)):D.current={time:ge,x:ie.clientX,y:ie.clientY}},pe=ie=>{if(!ie.ctrlKey&&!ie.metaKey)return;const V=i.current;if(!V)return;ie.preventDefault();const z=Q(V,B.current*Math.exp(-ie.deltaY*.01),ie.clientX,ie.clientY);g(z)},ve=()=>{g(1),B.current=1,i.current&&(i.current.scrollLeft=0,i.current.scrollTop=0)},Ae=o.jsxs("div",{className:y?"fixed inset-0 z-modal-panel flex min-h-0 flex-col bg-surface pt-[env(safe-area-inset-top,0px)]":"flex h-full min-h-0 flex-col bg-surface",children:[o.jsxs("div",{ref:s,className:"relative min-h-0 flex-1",children:[o.jsx("div",{ref:i,role:"button",tabIndex:0,onClick:j,onDoubleClick:ie=>{ie.preventDefault(),g(V=>V>1?1:2.5)},onPointerDown:W,onPointerMove:de,onPointerUp:X,onPointerCancel:X,onWheel:pe,onScroll:()=>T(null),className:"h-full touch-none cursor-crosshair overflow-auto bg-white p-3 text-slate-900",children:u?o.jsx("div",{className:"p-4 text-sm text-destructive",children:u}):a?o.jsx("div",{"data-svg-document":!0,className:"h-full min-h-[240px] w-full",dangerouslySetInnerHTML:{__html:a}}):o.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading SVG…"})}),S&&o.jsx("span",{"data-svg-pick-marker":!0,className:"pointer-events-none absolute z-10 h-4 w-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-primary bg-white shadow-sm",style:{left:S.stageX,top:S.stageY}}),S&&F&&o.jsx(f1,{anchor:{xPercent:S.stageXPercent,yPercent:S.stageYPercent},title:"引用 SVG 标注",onClick:()=>{r?.(F,`svg:${S.x.toFixed(2)}:${S.y.toFixed(2)}`),T(null)},children:"引用 SVG 标注"}),o.jsxs("div",{"data-svg-toolbar":!0,className:"absolute right-2 top-2 z-20 flex gap-1",children:[p>1.001&&o.jsx("button",{type:"button","aria-label":"适合窗口",title:"适合窗口",onClick:ie=>{ie.stopPropagation(),ve()},className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 bg-white/95 text-slate-600 shadow-sm backdrop-blur transition active:scale-95",children:o.jsx(hD,{size:14})}),o.jsx("button",{type:"button","aria-label":y?"退出全屏 SVG":"全屏 SVG",title:y?"退出全屏 SVG":"全屏 SVG",onClick:ie=>{ie.stopPropagation(),v(V=>!V)},className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 bg-white/95 text-slate-600 shadow-sm backdrop-blur transition active:scale-95",children:y?o.jsx(Qy,{size:14}):o.jsx(Oy,{size:14})})]})]}),o.jsx("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-border/15 px-3 py-2",children:o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:S?`SVG (${S.x.toFixed(2)}, ${S.y.toFixed(2)}) · ${S.nearestText??"附近无文字"}`:"点击 SVG 的问题位置生成精确引用"})})]});return y?ci.createPortal(Ae,document.body):Ae}function Wm(e){switch(e){case"schematic":return"原理图第1页";case"pcb-front":return"PCB正面";case"pcb-back":return"PCB背面(镜像)";case"pcb-3d":return"PCB 3D正面"}}function _ee(e,t,n,r){const s=[`电子标注: ${e}`,`视图: ${Wm(t)}`,`图片位置: (${n.xPercent.toFixed(1)}%,${n.yPercent.toFixed(1)}%) [相对渲染图左上角]`];if(r?.available&&r.xMm!==void 0&&r.yMm!==void 0&&(s.push(`PCB坐标: (${r.xMm.toFixed(2)},${r.yMm.toFixed(2)})mm [KiCad板坐标]`),r.layer&&s.push(`显示层: ${r.layer}`),r.nearest)){const i=[r.nearest.net?`网络 ${r.nearest.net}`:null,`对象层 ${r.nearest.layer}`,`距离 ${r.nearest.distanceMm.toFixed(2)}mm`].filter(Boolean).join(",");s.push(`最近对象: ${r.nearest.label}${i?`(${i})`:""}`)}return`"${s.join(" / ")}"`}function Lee({blobUrl:e,filePath:t,view:n,board:r,onViewChange:s,onInsertAnnotation:i,onRefresh:a,interactive3d:c}){const{t:u}=qn(),f=x.useRef(null),p=x.useRef(null),g=x.useRef(null),[y,v]=x.useState(null),[S,T]=x.useState(!1);x.useEffect(()=>(g.current?.abort(),v(null),T(!1),()=>g.current?.abort()),[e,n]);const C=x.useMemo(()=>y?_ee(t,n,y,y.inspection):null,[t,y,n]),L=D=>{const B=f.current,F=p.current;if(!B||!F||!F.naturalWidth||!F.naturalHeight)return;const j=B.getBoundingClientRect(),A=Math.min(j.width/F.naturalWidth,j.height/F.naturalHeight),H=F.naturalWidth*A,Q=F.naturalHeight*A,K=j.left+(j.width-H)/2,W=j.top+(j.height-Q)/2,de=D.clientX-K,X=D.clientY-W;if(de<0||X<0||de>H||X>Q)return;const pe={xPercent:Math.max(0,Math.min(100,de/H*100)),yPercent:Math.max(0,Math.min(100,X/Q*100)),stageXPercent:(D.clientX-j.left)/j.width*100,stageYPercent:(D.clientY-j.top)/j.height*100,inspecting:r&&n!=="pcb-3d"};if(v(pe),g.current?.abort(),!pe.inspecting)return;const ve=new AbortController;g.current=ve,WI(t,n,pe.xPercent,pe.yPercent,ve.signal).then(Ae=>v(ie=>ie===pe?{...ie,inspection:Ae,inspecting:!1}:ie)).catch(()=>{ve.signal.aborted||v(Ae=>Ae===pe?{...Ae,inspection:{available:!1},inspecting:!1}:Ae)})},E=r?["pcb-front","pcb-back","pcb-3d"]:["schematic"];return o.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-surface",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-border/15 px-3 py-2",children:[o.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-x-auto",children:E.map(D=>o.jsx("button",{type:"button",onClick:()=>s(D),className:`h-8 shrink-0 rounded-full px-3 text-xs font-semibold transition active:scale-95 ${D===n?"bg-primary/15 text-primary":"bg-surface-2 text-muted-foreground hover:bg-surface-elevated hover:text-foreground"}`,children:Wm(D)},D))}),o.jsx("button",{type:"button",onClick:a,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",title:u("rightSidebar.edaRefresh"),"aria-label":u("rightSidebar.edaRefresh"),children:o.jsx($s,{size:13})})]}),r&&c?o.jsx("div",{className:n==="pcb-3d"?"flex min-h-0 flex-1 flex-col overflow-hidden":"hidden",children:c}):null,r?n==="pcb-3d"?c?null:o.jsx("div",{className:"min-h-0 flex-1"}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{ref:f,role:"button",tabIndex:0,onClick:L,onKeyDown:D=>{D.key!=="Enter"&&D.key!==" "||(D.preventDefault(),v({xPercent:50,yPercent:50,stageXPercent:50,stageYPercent:50}))},className:"relative min-h-0 flex-1 cursor-crosshair overflow-hidden bg-surface p-3 outline-none",title:u("rightSidebar.edaPickHint"),children:[o.jsx("img",{ref:p,src:e,alt:`${t} ${Wm(n)}`,onLoad:()=>T(!0),className:`pointer-events-none h-full w-full object-contain transition-opacity ${S?"opacity-100":"opacity-0"}`}),y&&o.jsx("span",{className:"pointer-events-none absolute h-4 w-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-primary bg-surface shadow-sm",style:{left:`${y.stageXPercent}%`,top:`${y.stageYPercent}%`}}),y&&C&&o.jsx(f1,{anchor:{xPercent:y.stageXPercent,yPercent:y.stageYPercent},disabled:y.inspecting,title:u("rightSidebar.edaInsertAnnotation"),onClick:()=>{i?.(C,`eda:${n}:${y.xPercent.toFixed(1)}:${y.yPercent.toFixed(1)}`),v(null)},children:u("rightSidebar.edaInsertAnnotation")})]}),o.jsx("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-border/15 px-3 py-2",children:o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:y?y.inspecting?u("rightSidebar.edaInspecting"):y.inspection?.available?u("rightSidebar.edaPickedBoardPosition",{x:y.inspection.xMm?.toFixed(2)??"—",y:y.inspection.yMm?.toFixed(2)??"—",object:y.inspection.nearest?.label??u("rightSidebar.edaNoNearbyObject")}):u("rightSidebar.edaPickedPosition",{x:y.xPercent.toFixed(1),y:y.yPercent.toFixed(1)}):u("rightSidebar.edaPickHint")})})]}):o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:o.jsx(bC,{blobUrl:e,filePath:t,viewLabel:Wm(n),onInsertAnnotation:i})})]})}function Eee(e){const t=[];let n=[],r="",s=!1;for(let i=0;i<e.length;i+=1){const a=e[i];s?a==='"'&&e[i+1]==='"'?(r+='"',i+=1):a==='"'?s=!1:r+=a:a==='"'?s=!0:a===","?(n.push(r),r=""):a===`
|
|
181
181
|
`?(n.push(r.replace(/\r$/,"")),t.push(n),n=[],r=""):r+=a}return(r||n.length>0)&&(n.push(r.replace(/\r$/,"")),t.push(n)),t}function Iee(e,t,n,r,s){const i=t[s]||`第${s+1}列`,a=n[s]??"",c=t.map((u,f)=>`${u||`第${f+1}列`}=${n[f]??""}`).join(";");return`"表格标注: ${e} / 数据行: ${r+1} / 列: ${i} / 值: ${a} / 记录: ${c}"`}function Ree({content:e,filePath:t,onInsertAnnotation:n}){const{t:r}=qn(),s=x.useMemo(()=>Eee(e),[e]),i=s[0]??[],a=s.slice(1),c=x.useRef(null),[u,f]=x.useState(null),p=u?a[u.row]:null,g=u&&p?Iee(t,i,p,u.row+1,u.column):null;return o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-surface",children:[o.jsxs("div",{ref:c,className:"relative min-h-0 flex-1",children:[o.jsx("div",{className:"h-full overflow-auto",children:o.jsxs("table",{className:"min-w-full border-separate border-spacing-0 text-left text-xs",children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{className:"sticky left-0 top-0 z-20 border-b border-r border-border/20 bg-surface-elevated px-2 py-2 text-[10px] font-semibold text-muted-foreground",children:"#"}),i.map((y,v)=>o.jsx("th",{className:"sticky top-0 z-10 min-w-28 border-b border-r border-border/20 bg-surface-elevated px-3 py-2 font-semibold text-foreground",children:y||r("rightSidebar.csvUnnamedColumn",{index:v+1})},`${y}:${v}`))]})}),o.jsx("tbody",{children:a.map((y,v)=>o.jsxs("tr",{className:"hover:bg-surface-2",children:[o.jsx("th",{className:"sticky left-0 z-10 border-b border-r border-border/15 bg-surface px-2 py-2 text-right text-[10px] font-normal text-muted-foreground",children:v+1}),i.map((S,T)=>{const C=u?.row===v&&u.column===T;return o.jsx("td",{className:`border-b border-r border-border/15 p-0 ${C?"bg-primary/15":""}`,children:o.jsx("button",{type:"button",onClick:L=>{const E=c.current?.getBoundingClientRect(),D=L.currentTarget.getBoundingClientRect();if(!E?.width||!E.height)return;const B=L.clientX||D.left+D.width/2,F=L.clientY||D.top+D.height/2;f({row:v,column:T,xPercent:(B-E.left)/E.width*100,yPercent:(F-E.top)/E.height*100})},className:"block h-full min-h-9 w-full whitespace-pre-wrap px-3 py-2 text-left text-foreground outline-none hover:bg-primary/10 focus-visible:bg-primary/10",children:y[T]||" "})},`cell:${v}:${T}`)})]},`row:${v}`))})]})}),u&&g&&o.jsx(f1,{anchor:{xPercent:u.xPercent,yPercent:u.yPercent},title:r("rightSidebar.csvInsertAnnotation"),onClick:()=>{n?.(g,`csv:${t}:${u.row+1}:${u.column+1}`),f(null)},children:r("rightSidebar.csvInsertAnnotation")})]}),o.jsx("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-border/15 px-3 py-2",children:o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:u&&p?r("rightSidebar.csvSelectedCell",{row:u.row+1,column:i[u.column]||u.column+1}):r("rightSidebar.csvPickHint",{rows:a.length,columns:i.length})})})]})}function Zd(e,t){let n=e;for(const r of t){if(!n||typeof n!="object")return;n=n[r]}return n}function Nee(e,t){const n=JSON.parse(e),r=Zd(n,["meta","version"]);if(t)return[{label:"文件性质",value:"KiCad 本机界面状态,不属于电气设计源文件"},{label:"格式版本",value:String(r??"未知")},{label:"活动层编号",value:String(Zd(n,["board","active_layer"])??"未知")},{label:"可见层掩码",value:String(Zd(n,["board","visible_layers"])??"未知")},{label:"Git 集成",value:Zd(n,["git","integration_disabled"])===!0?"已禁用":"未禁用"}];const s=Zd(n,["net_settings","classes"]),i=Array.isArray(s)?s.find(c=>c&&typeof c=="object"&&c.name==="Default"):void 0,a=Zd(n,["board","design_settings","drc_exclusions"]);return[{label:"文件性质",value:"KiCad 工程配置"},{label:"格式版本",value:String(r??"未知")},{label:"网络类数量",value:String(Array.isArray(s)?s.length:0)},{label:"默认间距",value:i?.clearance!==void 0?`${i.clearance} mm`:"未设置"},{label:"默认线宽",value:i?.track_width!==void 0?`${i.track_width} mm`:"未设置"},{label:"默认过孔",value:i?.via_diameter!==void 0?`${i.via_diameter} / ${i.via_drill??"—"} mm(外径/钻孔)`:"未设置"},{label:"DRC 排除项",value:String(Array.isArray(a)?a.length:0)}]}function Mee(e,t){return`"KiCad项目标注: ${e} / 项: ${t.label} / 值: ${t.value}"`}function Dee({content:e,filePath:t,localState:n,onInsertAnnotation:r}){const{t:s}=qn(),i=x.useRef(null),[a,c]=x.useState(null),u=x.useMemo(()=>{try{return{items:Nee(e,n),error:null}}catch(p){return{items:[],error:p instanceof Error?p.message:String(p)}}},[e,n]),f=a===null?null:u.items[a.index];return u.error?o.jsx("pre",{className:"min-h-0 flex-1 overflow-auto whitespace-pre-wrap p-3 font-mono text-xs text-foreground",children:e}):o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-surface",children:[n&&o.jsx("div",{className:"border-b border-[color:var(--warning)]/20 bg-[color:var(--warning)]/5 px-3 py-2 text-xs text-[color:var(--warning)]",children:s("rightSidebar.kicadLocalStateNotice")}),o.jsxs("div",{ref:i,className:"relative min-h-0 flex-1",children:[o.jsxs("div",{className:"h-full overflow-auto px-3 py-2",children:[o.jsx("div",{className:"divide-y divide-border/15",children:u.items.map((p,g)=>o.jsxs("button",{type:"button",onClick:y=>{const v=i.current?.getBoundingClientRect(),S=y.currentTarget.getBoundingClientRect();if(!v?.width||!v.height)return;const T=y.clientX||S.left+S.width/2,C=y.clientY||S.top+S.height/2;c({index:g,xPercent:(T-v.left)/v.width*100,yPercent:(C-v.top)/v.height*100})},className:`grid w-full grid-cols-[minmax(7rem,0.8fr)_minmax(0,1.4fr)] gap-3 px-2 py-3 text-left transition hover:bg-surface-2 ${a?.index===g?"bg-primary/10":""}`,children:[o.jsx("span",{className:"text-xs font-semibold text-muted-foreground",children:p.label}),o.jsx("span",{className:"break-words text-xs text-foreground",children:p.value})]},p.label))}),o.jsxs("details",{className:"mt-3 border-t border-border/15 pt-3",children:[o.jsx("summary",{className:"cursor-pointer text-xs font-semibold text-muted-foreground",children:s("rightSidebar.kicadShowRawJson")}),o.jsx("pre",{className:"mt-2 overflow-auto whitespace-pre p-2 font-mono text-[10px] leading-relaxed text-foreground",children:e})]})]}),f&&a&&o.jsx(f1,{anchor:{xPercent:a.xPercent,yPercent:a.yPercent},title:s("rightSidebar.kicadInsertSetting"),onClick:()=>{r?.(Mee(t,f),`kicad-project:${t}:${f.label}`),c(null)},children:s("rightSidebar.kicadInsertSetting")})]}),o.jsx("div",{className:"flex shrink-0 items-center justify-between gap-3 border-t border-border/15 px-3 py-2",children:o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:f?`${f.label}: ${f.value}`:s("rightSidebar.kicadProjectPickHint")})})]})}const jee=x.forwardRef(function({src:t,title:n,exitFullscreenLabel:r,onFullscreenChange:s},i){const a=x.useRef(null),[c,u]=x.useState(!1),[f,p]=x.useState(!1),g=c||f;x.useEffect(()=>{s?.(g)},[g,s]),x.useEffect(()=>{const S=()=>{u(document.fullscreenElement===a.current)};return document.addEventListener("fullscreenchange",S),()=>document.removeEventListener("fullscreenchange",S)},[]),x.useEffect(()=>{if(!f)return;const S=T=>{T.key==="Escape"&&p(!1)};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[f]);const y=x.useCallback(async()=>{const S=a.current;if(S){if(f){p(!1);return}if(document.fullscreenElement===S){await document.exitFullscreen();return}if(S.requestFullscreen&&document.fullscreenEnabled!==!1)try{await S.requestFullscreen();return}catch{}p(!0)}},[f]);x.useImperativeHandle(i,()=>({toggleFullscreen:y}),[y]);const v=o.jsxs("div",{ref:a,"data-html-preview-frame":!0,className:g?"fixed inset-0 z-modal-panel flex min-h-0 flex-col overflow-hidden bg-surface pt-[env(safe-area-inset-top,0px)] text-foreground":"flex h-full min-h-0 flex-col overflow-hidden bg-surface",children:[g&&o.jsxs("div",{className:"flex h-12 shrink-0 items-center justify-between gap-3 border-b border-border/15 bg-[var(--chrome-bg)] px-3",children:[o.jsx("span",{className:"min-w-0 truncate text-[12px] font-semibold",children:n}),o.jsx("button",{type:"button",onClick:()=>{y()},"aria-label":r,title:`${r} (Esc)`,className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:o.jsx(Qy,{size:15})})]}),o.jsx("iframe",{src:t,title:n,sandbox:"allow-scripts",className:"block min-h-0 w-full flex-1 border-0 bg-white"})]});return f?ci.createPortal(v,document.body):v}),yC="termdock-file-search-match",fy="termdock-file-search-current";function Pee(e){const t=e.metaKey||e.ctrlKey,n=e.key.toLocaleLowerCase();return t&&n==="f"?"open":t&&n==="g"||e.key==="F3"?e.shiftKey?"previous":"next":e.key==="Escape"?"close":null}function Bee(e){return e.parentElement?.closest("[data-markdown-preview-block-start], [data-file-preview-line]")??null}function Fee(e,t){const n=t.trim().toLocaleLowerCase();if(!n)return[];const r=[];let s="",i=null;const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let p=a.nextNode();p;p=a.nextNode()){if(!(p instanceof Text)||!p.data)continue;const g=Bee(p);if(!g)continue;i&&i!==g&&(s+=`
|
|
182
|
-
`);const y=s.length;s+=p.data,r.push({node:p,start:y,end:s.length,group:g}),i=g}const c=s.toLocaleLowerCase(),u=[];let f=0;for(;f<=c.length-n.length;){const p=c.indexOf(n,f);if(p<0)break;const g=p+n.length,y=r.find(S=>S.start<=p&&S.end>p),v=r.find(S=>S.start<g&&S.end>=g);if(y&&v&&y.group===v.group){const S=document.createRange();S.setStart(y.node,p-y.start),S.setEnd(v.node,g-v.start),u.push(S)}f=p+Math.max(n.length,1)}return u}function vC(){return typeof CSS<"u"&&CSS.highlights?CSS.highlights:null}function pm(){const e=vC();e?.delete(yC),e?.delete(fy)}function g7(e,t){const n=vC();if(!n||typeof Highlight>"u")return;n.set(yC,new Highlight(...e));const r=e[t];r?n.set(fy,new Highlight(r)):n.delete(fy)}function x7(e){e?.startContainer.parentElement?.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}function Oee(e){return Array.from(new Set(e.split(/[\n,]/).map(t=>t.trim().replace(/^!+/,"")).filter(Boolean))).slice(0,24)}function Qee(e,t){const n=t.trim();return!n||n==="."?e:/^(?:[/\\]|[A-Za-z]:[/\\])/.test(n)?n.replace(/[\\/]+$/,""):`${e.replace(/[\\/]+$/,"")}/${n.replace(/^\.?[\\/]+/,"").replace(/[\\/]+$/,"")}`}function $ee(e,t){if(t===e)return".";const n=`${e.replace(/[\\/]+$/,"")}/`;return t.startsWith(n)?t.slice(n.length):t}const Hv="termdock:right-sidebar:file-tree-scroll:v1",Uv="termdock:right-sidebar:file-preview-reading-state:v1",rh="termdock:right-sidebar:file-tree-width:v1",wC="termdock:right-sidebar:markdown-view-mode:v1",SC="termdock:right-sidebar:diff-change-list-mode:v1",AC="termdock:right-sidebar:diff-wrap:v1",TC="termdock:diff-viewer:view-type:v1",CC="termdock:right-sidebar:file-search-mode:v1",Tb="termdock:right-sidebar:collapsed-git-repo-groups:v1",b7="termdock:right-sidebar:collapsed-diff-directories:v1",Cb="termdock:right-sidebar:branch-audit-module-open:v1",kC="termdock:right-sidebar:branch-audit-module:v1",Hee=150,_C="termdock:right-sidebar:active-git-repo:v1",y7="termdock:right-sidebar:context-draft-enabled:v1",v7="termdock:right-sidebar:context-draft-collapsed:v1",w7="termdock:right-sidebar:context-draft-auto-collapse:v1",kb="termdock:right-sidebar:context-draft-text:v1",Uee=300,zee=20,Gee=120,Wee=250,Vee=250,qee=120,Kee=700,_b=600,S7=[2e3,5e3,15e3,3e4],Yee=320,Xee=500,Zee=20,Jee=12e3,hy=300,A7=240,ete=560,LC="border-r px-2 py-1.5 sm:px-3 sm:py-2",Eg="max-w-[18rem] whitespace-normal break-words sm:max-w-[27rem]",EC=`${LC} border-b border-border/15 font-semibold last:border-r-0`,IC=`${LC} border-border/10 align-top text-muted-foreground last:border-r-0`,zv="termdock-file-preview-horizontal-scroll",T7=x.lazy(()=>P0(()=>import("./ModelPreview-CFATmDMn.js"),__vite__mapDeps([2,3,1,4]))),RC=`${zv} termdock-md-table-scroll max-w-full overflow-x-auto overflow-y-hidden rounded-lg border border-border/20 bg-surface`;function tte(e,t,n){return e&&!t?"unified":n}const nte=new Set([".md",".markdown",".mdown",".mkdn",".mkd"]);function rte(e){return e==="preview"||e==="source"}function ste(e){return e==="list"||e==="tree"||e==="ai"}function C7(){return Ur(wC,rte)??"preview"}function ite(){return Ur(SC,ste)??"tree"}function sh(e){return typeof e=="boolean"}function ote(e){return typeof e=="string"}function ate(){return Ur(AC,sh)??!0}function lte(e){return e==="unified"||e==="split"}function cte(){return Ur(TC,lte)??"unified"}function ute(e){return e==="name"||e==="content"||e==="regex"}function dte(){return Ur(CC,ute)??"name"}function NC(e){return e.repositories??(e.context?.root?[{id:e.context.root,root:e.context.root,relativeRoot:".",name:Ro(e.context.root)||e.context.root,depth:0,nested:!1,available:e.available,files:e.files,context:e.context,error:e.error}]:[])}function fte(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>t===null||typeof t=="string")}function MC(){return Ur(_C,fte)??{}}function k7(e){if(!e)return;const t=MC();return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0}function Lb(e,t){e&&$n(_C,{...MC(),[e]:t})}function hte(e,t){if(!t)return null;const n=new Set((e.repoFilters??[]).map(r=>r.root));return n.has(t)?t:n.size>0?null:(e.repositories??[]).some(r=>r.root===t)?t:null}function py(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function _7(e){const t=Ur(e,py);return t?new Set(t):new Set}function Eb(e,t){$n(e,[...t])}function pte(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.filePath=="string"&&typeof t.hunkHeader=="string"&&typeof t.hunkIndex=="number"&&typeof t.fingerprint=="string"&&typeof t.additions=="number"&&typeof t.deletions=="number"&&typeof t.diff=="string"&&(t.oldPath===void 0||t.oldPath===null||typeof t.oldPath=="string")&&(t.newPath===void 0||t.newPath===null||typeof t.newPath=="string")&&(t.source===void 0||t.source==="committed"||t.source==="uncommitted"||t.source==="unknown")&&(t.commit===void 0||t.commit===null||typeof t.commit=="string")}function mte(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.available=="boolean"&&(t.repoRoot===void 0||typeof t.repoRoot=="string")&&(t.workspaceRoot===void 0||typeof t.workspaceRoot=="string")&&(t.baseRef===void 0||typeof t.baseRef=="string")&&(t.baseBranch===void 0||typeof t.baseBranch=="string")&&(t.currentBranch===void 0||t.currentBranch===null||typeof t.currentBranch=="string")&&(t.headRef===void 0||t.headRef===null||typeof t.headRef=="string")&&(t.diffFingerprint===void 0||typeof t.diffFingerprint=="string")&&(t.stat===void 0||typeof t.stat=="string")&&(t.files===void 0||py(t.files))&&(t.hunks===void 0||Array.isArray(t.hunks)&&t.hunks.every(pte))&&(t.commits===void 0||py(t.commits))&&(t.commitCount===void 0||typeof t.commitCount=="number")&&(t.diff===void 0||typeof t.diff=="string")&&(t.truncated===void 0||typeof t.truncated=="boolean")&&(t.error===void 0||typeof t.error=="string")}function gte(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.key=="string"&&mte(t.diff)&&typeof t.repoLabel=="string"&&typeof t.createdAt=="number"}function xte(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;const n=t;return Array.isArray(n.selectedRepoRoots)&&n.selectedRepoRoots.every(r=>typeof r=="string")&&!!n.repoTargetBranches&&typeof n.repoTargetBranches=="object"&&!Array.isArray(n.repoTargetBranches)&&Object.values(n.repoTargetBranches).every(r=>typeof r=="string")&&(n.repoBaseBranches===void 0||!!n.repoBaseBranches&&typeof n.repoBaseBranches=="object"&&!Array.isArray(n.repoBaseBranches)&&Object.values(n.repoBaseBranches).every(r=>typeof r=="string"))&&(n.previewEntries===void 0||Array.isArray(n.previewEntries)&&n.previewEntries.every(gte))&&(n.selectedPreviewKey===void 0||n.selectedPreviewKey===null||typeof n.selectedPreviewKey=="string")&&(n.selectedPreviewFileKey===void 0||n.selectedPreviewFileKey===null||typeof n.selectedPreviewFileKey=="string")&&(n.previewDetailOpen===void 0||typeof n.previewDetailOpen=="boolean")&&(n.previewScrollTops===void 0||!!n.previewScrollTops&&typeof n.previewScrollTops=="object"&&!Array.isArray(n.previewScrollTops)&&Object.values(n.previewScrollTops).every(r=>typeof r=="number"))&&(n.previewMobileSlideIndex===void 0||typeof n.previewMobileSlideIndex=="number")&&(n.includeUncommitted===void 0||typeof n.includeUncommitted=="boolean")&&typeof n.updatedAt=="number"})}function L7(){return Ur(kC,xte)??{}}function E7(e){return[e.repoRoot,e.baseRef,e.branchName??"",e.headRef??"",e.diffFingerprint??""].join("\0")}function I7(e){const t=e?.trim()??"",n=t.indexOf("/");return n>=0?t.slice(n+1):t}function DC(e,t){const n=e?.trim(),r=t?.trim();return!n||!r?!1:n===r||I7(n)===I7(r)}function R7(e){const t=e?.branch??null;return[e?.upstream,...e?.remoteBranches??[],...e?.branches??[]].find(r=>r&&!DC(r,t))??""}function my(e,t){const n=Math.max(A7,t-320),r=Math.min(ete,n);return Math.min(r,Math.max(A7,e))}function bte(e){return typeof e=="number"&&Number.isFinite(e)}function yte(e){return my(Ur(rh,bte)??hy,e)}function jC(e){const t=e.split(/[\\/]/).pop()??e,n=t.lastIndexOf(".");return n>=0?t.slice(n).toLowerCase():""}function zf(e){return nte.has(jC(e))}function PC(e){const t=e.trim().replace(/\s+/g,"");return/^-{3,}$/.test(t)||/^\*{3,}$/.test(t)||/^_{3,}$/.test(t)}function gy(e){const t=e.trim();return/^#{1,6}\s+/.test(t)||PC(e)||/^>\s?/.test(t)||/^(```|~~~)/.test(t)||/^(?:[-+*]|\d+[.)])\s+/.test(t)}function vte(e){const t=e.trim();return/^(https?:|mailto:|#|\/|\.\/|\.\.\/)/i.test(t)||!/^[a-z][a-z0-9+.-]*:/i.test(t)&&!/[<>]/.test(t)?t:null}const BC=x.createContext(null);function Vm(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function FC(e){return e.replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1").replace(/[`*_~]/g,"").replace(/<[^>]+>/g,"").trim()}function OC(e){return e.replace(/\s+#+\s*$/,"").trim()}function xy(e,t){const r=FC(e).toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu,"").trim().replace(/\s+/g,"-")||"section",s=t.headingSlugCounts.get(r)??0;return t.headingSlugCounts.set(r,s+1),s===0?r:`${r}-${s}`}function N7(e){return FC(e)||e.trim()}function Ig(e){const t=e.match(/^\s{0,3}\[([^\]]+)\]:\s+(.+?)\s*$/);if(!t)return null;const n=yy(t[2]);return n?{id:Vm(t[1]),definition:{href:n.href,title:n.title}}:null}function wte(e){const t=new Map;for(const n of e){const r=Ig(n);r&&t.set(r.id,r.definition)}return t}function QC(e){return e.trim().toLowerCase()}function $C(e){const t=e.match(/^\s{0,3}\[\^([^\]]+)\]:\s+(.+)\s*$/);return t?{id:QC(t[1]),text:t[2]}:null}function Ste(e){const t=new Map;let n=null;for(const r of e){const s=$C(r);if(s){n=s.id,t.set(s.id,{id:s.id,text:s.text,index:t.size+1});continue}if(n&&/^\s{4,}\S/.test(r)){const i=t.get(n);i&&(i.text=`${i.text} ${r.trim()}`);continue}r.trim()&&(n=null)}return t}function Ate(e){const t=new Set;let n=!1;return e.forEach((r,s)=>{if($C(r)){t.add(s),n=!0;return}if(n&&/^\s{4,}\S/.test(r)){t.add(s);return}r.trim()&&(n=!1)}),t}function Tte(e){const t=[...e];let n=0;const r=e[0]?.trim();if(r==="---"||r==="+++"){for(t[0]="",n=1;n<e.length&&e[n].trim()!==r;)t[n]="",n+=1;n<e.length&&(t[n]="",n+=1)}for(;n<e.length;){const s=e[n].trim();if(s.startsWith("<!--")){if(t[n]="",!s.includes("-->")){for(n+=1;n<e.length&&!e[n].includes("-->");)t[n]="",n+=1;n<e.length&&(t[n]="")}n+=1;continue}n+=1}return t}function HC(e){const t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");return n<=0?n===0?"/":"":t.slice(0,n)}function xh(e){const t=e.split(/[?#]/,1)[0],n=t.startsWith("/"),r=[];for(const i of t.split("/"))if(!(!i||i===".")){if(i===".."){r.length>0&&r.pop();continue}r.push(i)}return`${n?"/":""}${r.join("/")}`||(n?"/":".")}function Cte(e,t,n){const r=e.trim();if(!r||/^(?:https?:|mailto:|javascript:|data:|#)/i.test(r)||/^[a-z][a-z0-9+.-]*:/i.test(r))return null;const s=r.indexOf("#"),i=s>=0?r.slice(0,s):r,a=s>=0?r.slice(s+1):"",c=i.split("?",1)[0];if(!c)return null;let u,f=null;try{u=decodeURIComponent(c),f=a?decodeURIComponent(a):null}catch{return null}const p=n?xh(n):null;let g;if(u.startsWith("/")){const y=p&&(u===p||u.startsWith(`${p}/`));g=xh(p&&!y?`${p}/${u.slice(1)}`:u)}else{if(!t)return null;g=xh(`${HC(t)}/${u}`)}return p&&g!==p&&!g.startsWith(`${p}/`)?null:{path:g,fragment:f,directory:/\/$/.test(c)}}function kte(e,t,n){const r=e.trim();if(!r||/^(?:javascript|data):/i.test(r))return null;if(/^https?:\/\//i.test(r))return r;if(!Ry(r.split(/[?#]/,1)[0]))return null;let s;if(r.startsWith("/")){const i=n&&(r===n||r.startsWith(`${n}/`));s=xh(n&&!i?`${n}/${r.slice(1)}`:r)}else{if(!t)return null;s=xh(`${HC(t)}/${r}`)}return`/api/terminal/fs/blob?path=${encodeURIComponent(s)}`}const by=128,_te=360,Ib=480;function Gv(e){try{return/\.svg(?=$|[?#&])/i.test(decodeURIComponent(e))}catch{return!1}}function Lte(e,t,n,r){if(!t||!n)return null;let s,i;return Gv(e)?(i=Math.min(Math.max(n,by),_te),s=t*i/n):(s=t,i=n),r>0&&s>r&&(i=i*r/s,s=r),i>Ib&&(s=s*Ib/i,i=Ib),{width:Math.max(1,Math.round(s)),height:Math.max(1,Math.round(i))}}function Ete(e){if(!e.startsWith("/api/terminal/fs/blob?"))return null;try{return new URLSearchParams(e.slice(e.indexOf("?"))).get("path")}catch{return null}}function UC(e){const t=Ete(e),n=ct(r=>t?(r.fileChangeVersions.get(t)??0)+r.fileWatchEpoch:0);return t&&n>0?`${e}&v=${n}`:e}function Ite({src:e,alt:t,title:n}){const r=Gv(e),s=UC(e),i=x.useRef(null),[a,c]=x.useState(!1),[u,f]=x.useState(0),[p,g]=x.useState({status:"loading"}),[y,v]=x.useState(null);x.useLayoutEffect(()=>{const C=i.current,L=C?.parentElement?.parentElement??C?.parentElement;if(!L)return;const E=()=>f(L.clientWidth);if(E(),typeof ResizeObserver>"u")return;const D=new ResizeObserver(E);return D.observe(L),()=>D.disconnect()},[]),x.useEffect(()=>{if(a)return;const C=i.current;if(!C||typeof IntersectionObserver>"u"){c(!0);return}const L=new IntersectionObserver(E=>{E.some(D=>D.isIntersecting)&&(c(!0),L.disconnect())},{rootMargin:"400px"});return L.observe(C),()=>L.disconnect()},[a]),x.useEffect(()=>{if(!a)return;const C=new AbortController;let L=null;g({status:"loading"});const E=window.setTimeout(()=>{C.abort(new DOMException("Image fetch timed out","TimeoutError"))},15e3);return fetch(s,{signal:C.signal}).then(async D=>{if(!D.ok)throw new Error(`HTTP ${D.status}`);const B=Number(D.headers.get("X-Image-Width"))||0,F=Number(D.headers.get("X-Image-Height"))||0;return{blob:await D.blob(),width:B,height:F}}).then(({blob:D,width:B,height:F})=>{C.signal.aborted||(L=URL.createObjectURL(D),B>0&&F>0&&v({width:B,height:F}),g({status:"ready",objectUrl:L}))}).catch(()=>{const D=C.signal.reason;C.signal.aborted&&!(D instanceof DOMException&&D.name==="TimeoutError")||g({status:"fallback"})}).finally(()=>{window.clearTimeout(E)}),()=>{window.clearTimeout(E),C.abort(),L&&URL.revokeObjectURL(L)}},[a,s]);const S=Lte(e,y?.width??0,y?.height??0,u),T=S??{width:by*2,height:by};return o.jsx("div",{ref:i,className:"block max-w-full",style:S?{width:S.width,height:S.height}:void 0,children:p.status==="ready"?o.jsx("img",{src:p.objectUrl,alt:t,title:n,decoding:"async",className:`${r?"":"termdock-fade-in "}block max-h-[480px] max-w-full object-contain`,style:S?{width:S.width,height:S.height}:void 0,onLoad:C=>{if(y)return;const L=C.currentTarget;L.naturalWidth>0&&L.naturalHeight>0&&v({width:L.naturalWidth,height:L.naturalHeight})}}):p.status==="fallback"?o.jsx("img",{src:s,alt:t,title:n,loading:"lazy",decoding:"async",className:"block max-h-[480px] max-w-full object-contain",style:S?{width:S.width,height:S.height}:void 0,onLoad:C=>{if(y)return;const L=C.currentTarget;L.naturalWidth>0&&L.naturalHeight>0&&v({width:L.naturalWidth,height:L.naturalHeight})}}):o.jsx("div",{"aria-hidden":!0,className:"flex max-w-full animate-pulse items-center justify-center rounded bg-surface-elevated/60",style:{width:T.width,height:T.height},children:o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:t||"…"})})})}function Rb(e,t,n,r,s){const i=kte(n,s.markdownFilePath,s.rootPath);if(!i)return``;const a=s.images.length;s.images.push({kind:"image",src:i,alt:t,title:r});const c=o.jsx(Ite,{src:i,alt:t,title:r});return s.onImageOpen?o.jsx("button",{type:"button",className:"my-2 block max-w-full overflow-hidden rounded-md border border-border/20 bg-surface-2 text-left transition hover:border-border-strong focus:outline-none focus:ring-2 focus:ring-ring/45",title:r||t||"Open image",onClick:u=>{u.stopPropagation(),s.onImageOpen?.(a)},children:c},e):o.jsx("span",{className:"my-2 block max-w-full overflow-hidden rounded-md border border-border/20 bg-surface-2",children:c},e)}function Nb(e){let t=e,n="";for(;/[.,;:!?)]$/.test(t);)n=`${t.slice(-1)}${n}`,t=t.slice(0,-1);return{linkText:t,suffix:n}}function M7(e){return/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(e)}function yy(e){const t=e.trim(),n=t.match(/^<([^>]+)>(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);if(n)return{href:n[1],title:n[2]??n[3]??n[4]};const r=t.match(/^(\S+)(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);return r?{href:r[1],title:r[2]??r[3]??r[4]}:null}const zC="",Rte=/\\([\\`*{}\[\]#+\-.!_|~>$])/g;function Nte(e){return e.replace(Rte,(t,n)=>`${zC}${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}function D7(e){return e.replace(new RegExp(`${zC}([0-9a-f]{4})`,"g"),(t,n)=>String.fromCharCode(Number.parseInt(n,16))).replace(/\\([()])/g,"$1")}function Mte(e){const t=e.replace(/[\r\n]+/g," ");return/^ .+ $/.test(t)&&/[^ ]/.test(t.slice(1,-1))?t.slice(1,-1):t}const GC={ALLOWED_TAGS:["a","abbr","b","blockquote","br","code","del","details","div","em","i","kbd","li","mark","ol","p","pre","s","span","strong","sub","summary","sup","table","tbody","td","th","thead","tr","u","ul"],ALLOWED_ATTR:["href","title","class","id","colspan","rowspan"],ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!0};let mm=null;function WC(){return mm||(mm=P0(()=>import("./purify.es-CC4Brkr_.js"),[]).then(e=>e.default??e).catch(e=>{throw mm=null,e})),mm}function VC({html:e}){const{t}=qn(),[n,r]=x.useState(null);return x.useEffect(()=>{let s=!1;return r(null),WC().then(i=>{s||r(i.sanitize(e,GC))}).catch(()=>{s||r("")}),()=>{s=!0}},[e]),n===null?o.jsx("div",{className:"py-2 text-xs text-muted-foreground",children:t("rightSidebar.renderingHtml")}):n?o.jsx("div",{className:"text-muted-foreground",dangerouslySetInnerHTML:{__html:n}}):null}function Dte({html:e}){const[t,n]=x.useState(null);return x.useEffect(()=>{let r=!1;return n(null),WC().then(s=>{r||n(s.sanitize(e,GC))}).catch(()=>{r||n("")}),()=>{r=!0}},[e]),t===null?null:t?o.jsx("span",{dangerouslySetInnerHTML:{__html:t}}):e}function qC(e){const t=e.trim().match(/^<(div|section|article|aside|table|p|ul|ol|li|blockquote|pre|figure|figcaption)\b[^>]*>/i);if(!t)return null;const n=t[1].toLowerCase();return{tag:n,selfContained:new RegExp(`</${n}>`,"i").test(e)}}let gm=null;function jte(){return gm||(gm=Promise.all([P0(()=>import("./katex-DnlPpQZa.js"),[]),P0(()=>Promise.resolve({}),__vite__mapDeps([5]))]).then(([e])=>e.default??e).catch(e=>{throw gm=null,e})),gm}function Fh({tex:e,display:t=!1}){const[n,r]=x.useState(null),[s,i]=x.useState(!1);if(x.useEffect(()=>{let c=!1;return r(null),i(!1),jte().then(u=>{c||r(u.renderToString(e,{displayMode:t,throwOnError:!1,trust:!1,strict:"ignore"}))}).catch(()=>{c||i(!0)}),()=>{c=!0}},[t,e]),s)return o.jsx("code",{className:"rounded bg-surface-2 px-1 py-0.5 font-mono text-[0.92em] text-foreground",children:t?`$$${e}$$`:`$${e}$`});if(!n)return o.jsx("span",{className:"text-muted-foreground/70",children:t?"Rendering formula...":e});const a=t?"my-2 overflow-auto rounded-md bg-surface-2 px-3 py-2 text-center":"inline-block align-middle";return o.jsx("span",{className:a,dangerouslySetInnerHTML:{__html:n}})}function Pte(e,t,n){if(/^<br\s*\/?>$/i.test(e))return o.jsx("br",{},t);const r=e.match(/^<(kbd|mark|sub|sup)>(.*?)<\/\1>$/i);if(!r)return/^<(a|abbr|span|b|strong|em|i|u|s|del|code)\b[\s\S]*<\/\1>$/i.test(e)?o.jsx(Dte,{html:e},t):null;const s=r[1].toLowerCase(),i=Ei(r[2],`${t}-${s}`,!0,n);return s==="kbd"?o.jsx("kbd",{className:"rounded border border-border/30 bg-surface-2 px-1.5 py-0.5 font-mono text-[0.85em] text-foreground shadow-sm",children:i},t):s==="mark"?o.jsx("mark",{className:"rounded bg-warning/25 px-0.5 text-foreground",children:i},t):s==="sub"?o.jsx("sub",{children:i},t):o.jsx("sup",{children:i},t)}function Ei(e,t,n=!0,r){const s=Nte(e),i=/(\\\([^)]*\\\)|\$[^$\n]+\$|<br\s*\/?>|<(?:a|abbr|span|b|strong|em|i|u|s|del|code|kbd|mark|sub|sup)\b[\s\S]*?<\/(?:a|abbr|span|b|strong|em|i|u|s|del|code|kbd|mark|sub|sup)>|!?\[[^\]]*\]\((?:<[^>]+>|(?:[^\s()]+|\([^()\s]*\))+)(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\)|!?\[[^\]]+\]\[[^\]]*\]|!?\[[^\]]+\]|\[\^[^\]]+\]|(`+)([\s\S]*?)\2|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|\*[^*\s][^*]*\*|_[^_\s][^_]*_|<https?:\/\/[^>\s]+>|<[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+>|https?:\/\/[^\s<]+|www\.[^\s<]+|[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+)/gi,a=[];let c=0,u;for(;(u=i.exec(s))!==null;){u.index>c&&a.push(D7(s.slice(c,u.index)));const f=u[0],p=`${t}-${u.index}`,g=f.startsWith("<")?Pte(f,p,r):null;if(g)a.push(g);else if(f.startsWith("\\(")&&f.endsWith("\\)"))a.push(o.jsx(Fh,{tex:f.slice(2,-2)},p));else if(f.startsWith("$")&&f.endsWith("$"))a.push(o.jsx(Fh,{tex:f.slice(1,-1)},p));else if(f.startsWith("`")){const y=f.match(/^`+/)?.[0].length??1;a.push(o.jsx("code",{className:`${n?"break-all":"whitespace-nowrap"} rounded bg-surface-2 px-1 py-0.5 font-mono text-[0.92em] text-foreground`,children:Mte(f.slice(y,-y))},p))}else if(f.startsWith("~~"))a.push(o.jsx("del",{className:"text-muted-foreground decoration-border-strong",children:Ei(f.slice(2,-2),`${p}-del`,n,r)},p));else if(f.startsWith("**")||f.startsWith("__"))a.push(o.jsx("strong",{className:"font-semibold text-foreground",children:Ei(f.slice(2,-2),`${p}-strong`,n,r)},p));else if(f.startsWith("*")||f.startsWith("_"))a.push(o.jsx("em",{className:"italic",children:Ei(f.slice(1,-1),`${p}-em`,n,r)},p));else if(f.startsWith("![")){const y=f.match(/^!\[([^\]]*)\]\((.*)\)$/),v=f.match(/^!\[([^\]]+)\]\[([^\]]*)\]$/),S=f.match(/^!\[([^\]]+)\]$/);if(y){const T=yy(y[2]);a.push(T?Rb(p,y[1],T.href,T.title,r):f)}else if(v){const T=v[2]||v[1],C=r.referenceDefinitions.get(Vm(T));a.push(C?Rb(p,v[1],C.href,C.title,r):f)}else if(S){const T=r.referenceDefinitions.get(Vm(S[1]));a.push(T?Rb(p,S[1],T.href,T.title,r):f)}else a.push(f)}else if(f.startsWith("[^")){const y=QC(f.slice(2,-1)),v=r.footnoteDefinitions.get(y);a.push(v?o.jsx("sup",{id:`fnref-${v.id}`,title:v.text,className:"ml-0.5 rounded bg-surface-2 px-1 text-[0.72em] font-semibold text-primary",children:o.jsx("a",{href:`#fn-${v.id}`,className:"text-primary no-underline",children:v.index})},p):f)}else if(f.startsWith("<http")){const y=f.slice(1,-1);a.push(o.jsx("a",{href:y,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p))}else if(f.startsWith("<")&&f.endsWith(">")&&M7(f.slice(1,-1))){const y=f.slice(1,-1);a.push(o.jsx("a",{href:`mailto:${y}`,className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p))}else if(M7(Nb(f).linkText)){const{linkText:y,suffix:v}=Nb(f);a.push(o.jsx("a",{href:`mailto:${y}`,className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p)),v&&a.push(v)}else if(f.startsWith("http")||f.startsWith("www.")){const{linkText:y,suffix:v}=Nb(f),S=y.startsWith("www.")?`https://${y}`:y;a.push(o.jsx("a",{href:S,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p)),v&&a.push(v)}else{const y=f.match(/^\[([^\]]+)\]\((.*)\)$/),v=f.match(/^\[([^\]]+)\]\[([^\]]*)\]$/),S=f.match(/^\[([^\]]+)\]$/),T=v?v[2]||v[1]:S?.[1]??null,C=T?r.referenceDefinitions.get(Vm(T)):null,L=y?yy(y[2]):null,E=L?.href??C?.href??null,D=E?vte(E):null,B=y?.[1]??v?.[1]??S?.[1]??"";a.push(D?o.jsx("a",{href:D,title:L?.title??C?.title,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:Ei(B,`${p}-link`,n,r)},p):f)}c=i.lastIndex}return c<s.length&&a.push(D7(s.slice(c))),a.length>0?a:[e]}function KC(e){return/(?: {2,}|\\)$/.test(e)}function YC(e){return e.replace(/(?: {2,}|\\)$/,"")}function Rg(e){return/^(?: {4}|\t)/.test(e)}function XC(e){return e.startsWith(" ")?e.slice(1):e.replace(/^ {4}/,"")}function ZC(e,t,n){const r=[];return e.forEach((s,i)=>{const a=KC(s);r.push(...Ei(YC(s),`${t}-${i}`,!0,n)),i<e.length-1&&r.push(a?o.jsx("br",{},`${t}-${i}-br`):" ")}),r}function vy(e,t,n){const r=[],s=[];return e.forEach((i,a)=>{s.push(KC(i)),r.push(Ei(YC(i),`${t}-${a}`,!0,n))}),{perLine:r,hardBreaks:s}}function wy(e,t,n,r,s){const i=[];return e.forEach((a,c)=>{const u=n[c]??0,f=!!(s&&u>=s.start&&u<=s.end);i.push(o.jsx("span",{"data-md-ref-start":u,"data-md-ref-end":u,"data-selected":f?"true":void 0,children:a},`${r}-ref-${c}`)),c<e.length-1&&i.push(t[c]?o.jsx("br",{},`${r}-${c}-br`):" ")}),i}function Oh(e){const t=e.trim().replace(/^\|/,"").replace(/\|$/,""),n=[];let r="",s=!1,i=0,a=0;for(let c=0;c<t.length;c+=1){const u=t[c];if(s){r+=u,s=!1;continue}if(u==="\\"){s=!0;continue}if(u==="`"){const f=c;for(;c+1<t.length&&t[c+1]==="`";)c+=1;const p=c-f+1;r+="`".repeat(p),i===0?i=p:i===p&&(i=0);continue}if(i===0&&u==="["?a+=1:i===0&&u==="]"&&a>0&&(a-=1),u==="|"&&i===0&&a===0){n.push(r.trim()),r="";continue}r+=u}return s&&(r+="\\"),n.push(r.trim()),n}function JC(e){return Oh(e).map(t=>/^:-+:$/.test(t)?"center":/^-+:$/.test(t)?"right":/^:-+$/.test(t)?"left":null)}function Ng(e){return e==="center"?"text-center":e==="right"?"text-right":"text-left"}function Mg(e){return/^\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)*\|?$/.test(e.trim())}function Bte(e,t){return e>96||e>44&&t>.35}function Wv(e){return(e.match(/^\s*/)?.[0]??"").replace(/\t/g," ").length}function Vv(e){const t=e.trim().match(/^([-+*]|\d+[.)])\s+(.+)$/);if(!t)return null;const n=/^\d+[.)]$/.test(t[1]);return{ordered:n,start:n?Number.parseInt(t[1],10):void 0,content:t[2]}}function ek(e,t,n,r,s,i=new Set){const a=[],c=[];let u=t;for(;u<e.length;){const f=e[u];if(s&&(Ig(f)||i.has(u))){u+=1;continue}const p=Vv(f),g=Wv(f);if(!p){if(g>n&&c.length>0){([...c].reverse().find(T=>T.indent<g)?.item??c[c.length-1].item).paragraphs.push(f.trim());for(const T of c)T.item.lineEnd=u+1;u+=1;continue}break}if(g<n||g===n&&p.ordered!==r)break;const y={content:p.content,ordered:p.ordered,start:p.start,children:[],paragraphs:[],lineStart:u+1,lineEnd:u+1};for(;c.length>0&&c[c.length-1].indent>=g;)c.pop();const v=c[c.length-1]?.item??null;v?v.children.push(y):a.push(y),c.push({indent:g,item:y});for(const S of c)S.item.lineEnd=u+1;u+=1}return{items:a,nextIndex:u}}function qv(e,t,n,r=0){return e.map((s,i)=>{const a=s.content.match(/^\[([ xX])\]\s+(.+)$/);return{key:`item-${i}`,taskItem:!!a,refStart:s.lineStart+r,refEnd:s.lineEnd+r,content:o.jsxs(o.Fragment,{children:[a?o.jsx("input",{type:"checkbox",checked:a[1].toLowerCase()==="x",readOnly:!0,className:"mr-2 align-[-2px] accent-primary"}):null,Ei(a?.[2]??s.content,`li-${t}-${i}`,!0,n),s.paragraphs.length>0&&o.jsx("div",{className:"mt-1 space-y-1 text-muted-foreground",children:s.paragraphs.map((c,u)=>o.jsx("p",{children:Ei(c,`li-${t}-${i}-p-${u}`,!0,n)},`paragraph-${u}`))})]}),groups:Fte(s.children,`${t}-${i}`,n,r)}})}function Fte(e,t,n,r=0){const s=[];for(const i of e){const a=s[s.length-1];a&&a.ordered===i.ordered?a.items.push(i):s.push({ordered:i.ordered,items:[i]})}return s.map((i,a)=>({ordered:i.ordered,start:i.ordered?i.items[0]?.start:void 0,items:qv(i.items,`${t}-g${a}`,n,r)}))}function Kv(e,t){return e.map(n=>{const r=!!(t&&n.refStart<=t.end&&n.refEnd>=t.start);return o.jsxs("li",{className:n.taskItem?"list-none":void 0,"data-md-ref-start":n.refStart,"data-md-ref-end":n.refEnd,"data-selected":r?"true":void 0,children:[n.content,n.groups.length>0&&Ote(n.groups,t)]},n.key)})}function Ote(e,t){return e.map((n,r)=>{const s=n.ordered?"ol":"ul";return o.jsx(s,{start:n.start,className:`${n.ordered?"list-decimal":"list-disc"} mt-1 space-y-0.5 pl-4 marker:text-muted-foreground/60`,children:Kv(n.items,t)},`nested-${r}`)})}function Qte(e){const t=Array.from(e.footnoteDefinitions.values()).sort((n,r)=>n.index-r.index);return t.length===0?null:o.jsxs("section",{className:"mt-3 border-t border-border/20 pt-2 text-[12px] leading-5 text-muted-foreground",children:[o.jsx("div",{className:"mb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/80",children:e.footnotesLabel}),o.jsx("ol",{className:"list-decimal space-y-1 pl-5",children:t.map(n=>o.jsxs("li",{id:`fn-${n.id}`,children:[Ei(n.text,`footnote-${n.id}`,!0,e)," ",o.jsx("a",{href:`#fnref-${n.id}`,className:"text-primary no-underline","aria-label":e.backToFootnoteLabel(n.index),children:"↩"})]},n.id))})]})}function $te(e,t,n,r){const s=[];let i=0;const a=c=>r?.[c]??c+1;for(;i<e.length;){const c=e[i],u=c.trim();if(!u){i+=1;continue}if(/^<details>\s*$/i.test(u)){const L=i;let E="Details";const D=[];for(i+=1;i<e.length&&!/^<\/details>\s*$/i.test(e[i].trim());){const B=e[i].trim().match(/^<summary>(.*?)<\/summary>\s*$/i);B?E=B[1].trim()||E:D.push(e[i].trimStart()),i+=1}i<e.length&&(i+=1),s.push({kind:"static",node:o.jsxs("details",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface px-3 py-2 text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-foreground",children:Ei(E,`${t}-details-${L}-summary`,!0,n)}),D.length>0&&o.jsx("div",{className:"mt-2 text-sm leading-6",children:ZC(D,`${t}-details-${L}`,n)})]},`${t}-details-${L}`)});continue}const f=qC(c);if(f){const L=[c],E=i;for(i+=1;i<e.length&&!f.selfContained&&!new RegExp(`</${f.tag}>`,"i").test(e[i]);)L.push(e[i]),i+=1;i<e.length&&!f.selfContained&&(L.push(e[i]),i+=1),s.push({kind:"static",node:o.jsx(VC,{html:L.join(`
|
|
182
|
+
`);const y=s.length;s+=p.data,r.push({node:p,start:y,end:s.length,group:g}),i=g}const c=s.toLocaleLowerCase(),u=[];let f=0;for(;f<=c.length-n.length;){const p=c.indexOf(n,f);if(p<0)break;const g=p+n.length,y=r.find(S=>S.start<=p&&S.end>p),v=r.find(S=>S.start<g&&S.end>=g);if(y&&v&&y.group===v.group){const S=document.createRange();S.setStart(y.node,p-y.start),S.setEnd(v.node,g-v.start),u.push(S)}f=p+Math.max(n.length,1)}return u}function vC(){return typeof CSS<"u"&&CSS.highlights?CSS.highlights:null}function pm(){const e=vC();e?.delete(yC),e?.delete(fy)}function g7(e,t){const n=vC();if(!n||typeof Highlight>"u")return;n.set(yC,new Highlight(...e));const r=e[t];r?n.set(fy,new Highlight(r)):n.delete(fy)}function x7(e){e?.startContainer.parentElement?.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}function Oee(e){return Array.from(new Set(e.split(/[\n,]/).map(t=>t.trim().replace(/^!+/,"")).filter(Boolean))).slice(0,24)}function Qee(e,t){const n=t.trim();return!n||n==="."?e:/^(?:[/\\]|[A-Za-z]:[/\\])/.test(n)?n.replace(/[\\/]+$/,""):`${e.replace(/[\\/]+$/,"")}/${n.replace(/^\.?[\\/]+/,"").replace(/[\\/]+$/,"")}`}function $ee(e,t){if(t===e)return".";const n=`${e.replace(/[\\/]+$/,"")}/`;return t.startsWith(n)?t.slice(n.length):t}const Hv="termdock:right-sidebar:file-tree-scroll:v1",Uv="termdock:right-sidebar:file-preview-reading-state:v1",rh="termdock:right-sidebar:file-tree-width:v1",wC="termdock:right-sidebar:markdown-view-mode:v1",SC="termdock:right-sidebar:diff-change-list-mode:v1",AC="termdock:right-sidebar:diff-wrap:v1",TC="termdock:diff-viewer:view-type:v1",CC="termdock:right-sidebar:file-search-mode:v1",Tb="termdock:right-sidebar:collapsed-git-repo-groups:v1",b7="termdock:right-sidebar:collapsed-diff-directories:v1",Cb="termdock:right-sidebar:branch-audit-module-open:v1",kC="termdock:right-sidebar:branch-audit-module:v1",Hee=150,_C="termdock:right-sidebar:active-git-repo:v1",y7="termdock:right-sidebar:context-draft-enabled:v1",v7="termdock:right-sidebar:context-draft-collapsed:v1",w7="termdock:right-sidebar:context-draft-auto-collapse:v1",kb="termdock:right-sidebar:context-draft-text:v1",Uee=300,zee=20,Gee=120,Wee=250,Vee=250,qee=120,Kee=700,_b=600,S7=[2e3,5e3,15e3,3e4],Yee=320,Xee=500,Zee=20,Jee=12e3,hy=300,A7=240,ete=560,LC="border-r px-2 py-1.5 sm:px-3 sm:py-2",Eg="max-w-[18rem] whitespace-normal break-words sm:max-w-[27rem]",EC=`${LC} border-b border-border/15 font-semibold last:border-r-0`,IC=`${LC} border-border/10 align-top text-muted-foreground last:border-r-0`,zv="termdock-file-preview-horizontal-scroll",T7=x.lazy(()=>P0(()=>import("./ModelPreview-DT9Bn9h2.js"),__vite__mapDeps([2,3,1,4]))),RC=`${zv} termdock-md-table-scroll max-w-full overflow-x-auto overflow-y-hidden rounded-lg border border-border/20 bg-surface`;function tte(e,t,n){return e&&!t?"unified":n}const nte=new Set([".md",".markdown",".mdown",".mkdn",".mkd"]);function rte(e){return e==="preview"||e==="source"}function ste(e){return e==="list"||e==="tree"||e==="ai"}function C7(){return Ur(wC,rte)??"preview"}function ite(){return Ur(SC,ste)??"tree"}function sh(e){return typeof e=="boolean"}function ote(e){return typeof e=="string"}function ate(){return Ur(AC,sh)??!0}function lte(e){return e==="unified"||e==="split"}function cte(){return Ur(TC,lte)??"unified"}function ute(e){return e==="name"||e==="content"||e==="regex"}function dte(){return Ur(CC,ute)??"name"}function NC(e){return e.repositories??(e.context?.root?[{id:e.context.root,root:e.context.root,relativeRoot:".",name:Ro(e.context.root)||e.context.root,depth:0,nested:!1,available:e.available,files:e.files,context:e.context,error:e.error}]:[])}function fte(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>t===null||typeof t=="string")}function MC(){return Ur(_C,fte)??{}}function k7(e){if(!e)return;const t=MC();return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0}function Lb(e,t){e&&$n(_C,{...MC(),[e]:t})}function hte(e,t){if(!t)return null;const n=new Set((e.repoFilters??[]).map(r=>r.root));return n.has(t)?t:n.size>0?null:(e.repositories??[]).some(r=>r.root===t)?t:null}function py(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function _7(e){const t=Ur(e,py);return t?new Set(t):new Set}function Eb(e,t){$n(e,[...t])}function pte(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.filePath=="string"&&typeof t.hunkHeader=="string"&&typeof t.hunkIndex=="number"&&typeof t.fingerprint=="string"&&typeof t.additions=="number"&&typeof t.deletions=="number"&&typeof t.diff=="string"&&(t.oldPath===void 0||t.oldPath===null||typeof t.oldPath=="string")&&(t.newPath===void 0||t.newPath===null||typeof t.newPath=="string")&&(t.source===void 0||t.source==="committed"||t.source==="uncommitted"||t.source==="unknown")&&(t.commit===void 0||t.commit===null||typeof t.commit=="string")}function mte(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.available=="boolean"&&(t.repoRoot===void 0||typeof t.repoRoot=="string")&&(t.workspaceRoot===void 0||typeof t.workspaceRoot=="string")&&(t.baseRef===void 0||typeof t.baseRef=="string")&&(t.baseBranch===void 0||typeof t.baseBranch=="string")&&(t.currentBranch===void 0||t.currentBranch===null||typeof t.currentBranch=="string")&&(t.headRef===void 0||t.headRef===null||typeof t.headRef=="string")&&(t.diffFingerprint===void 0||typeof t.diffFingerprint=="string")&&(t.stat===void 0||typeof t.stat=="string")&&(t.files===void 0||py(t.files))&&(t.hunks===void 0||Array.isArray(t.hunks)&&t.hunks.every(pte))&&(t.commits===void 0||py(t.commits))&&(t.commitCount===void 0||typeof t.commitCount=="number")&&(t.diff===void 0||typeof t.diff=="string")&&(t.truncated===void 0||typeof t.truncated=="boolean")&&(t.error===void 0||typeof t.error=="string")}function gte(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.key=="string"&&mte(t.diff)&&typeof t.repoLabel=="string"&&typeof t.createdAt=="number"}function xte(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>{if(!t||typeof t!="object"||Array.isArray(t))return!1;const n=t;return Array.isArray(n.selectedRepoRoots)&&n.selectedRepoRoots.every(r=>typeof r=="string")&&!!n.repoTargetBranches&&typeof n.repoTargetBranches=="object"&&!Array.isArray(n.repoTargetBranches)&&Object.values(n.repoTargetBranches).every(r=>typeof r=="string")&&(n.repoBaseBranches===void 0||!!n.repoBaseBranches&&typeof n.repoBaseBranches=="object"&&!Array.isArray(n.repoBaseBranches)&&Object.values(n.repoBaseBranches).every(r=>typeof r=="string"))&&(n.previewEntries===void 0||Array.isArray(n.previewEntries)&&n.previewEntries.every(gte))&&(n.selectedPreviewKey===void 0||n.selectedPreviewKey===null||typeof n.selectedPreviewKey=="string")&&(n.selectedPreviewFileKey===void 0||n.selectedPreviewFileKey===null||typeof n.selectedPreviewFileKey=="string")&&(n.previewDetailOpen===void 0||typeof n.previewDetailOpen=="boolean")&&(n.previewScrollTops===void 0||!!n.previewScrollTops&&typeof n.previewScrollTops=="object"&&!Array.isArray(n.previewScrollTops)&&Object.values(n.previewScrollTops).every(r=>typeof r=="number"))&&(n.previewMobileSlideIndex===void 0||typeof n.previewMobileSlideIndex=="number")&&(n.includeUncommitted===void 0||typeof n.includeUncommitted=="boolean")&&typeof n.updatedAt=="number"})}function L7(){return Ur(kC,xte)??{}}function E7(e){return[e.repoRoot,e.baseRef,e.branchName??"",e.headRef??"",e.diffFingerprint??""].join("\0")}function I7(e){const t=e?.trim()??"",n=t.indexOf("/");return n>=0?t.slice(n+1):t}function DC(e,t){const n=e?.trim(),r=t?.trim();return!n||!r?!1:n===r||I7(n)===I7(r)}function R7(e){const t=e?.branch??null;return[e?.upstream,...e?.remoteBranches??[],...e?.branches??[]].find(r=>r&&!DC(r,t))??""}function my(e,t){const n=Math.max(A7,t-320),r=Math.min(ete,n);return Math.min(r,Math.max(A7,e))}function bte(e){return typeof e=="number"&&Number.isFinite(e)}function yte(e){return my(Ur(rh,bte)??hy,e)}function jC(e){const t=e.split(/[\\/]/).pop()??e,n=t.lastIndexOf(".");return n>=0?t.slice(n).toLowerCase():""}function zf(e){return nte.has(jC(e))}function PC(e){const t=e.trim().replace(/\s+/g,"");return/^-{3,}$/.test(t)||/^\*{3,}$/.test(t)||/^_{3,}$/.test(t)}function gy(e){const t=e.trim();return/^#{1,6}\s+/.test(t)||PC(e)||/^>\s?/.test(t)||/^(```|~~~)/.test(t)||/^(?:[-+*]|\d+[.)])\s+/.test(t)}function vte(e){const t=e.trim();return/^(https?:|mailto:|#|\/|\.\/|\.\.\/)/i.test(t)||!/^[a-z][a-z0-9+.-]*:/i.test(t)&&!/[<>]/.test(t)?t:null}const BC=x.createContext(null);function Vm(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function FC(e){return e.replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1").replace(/[`*_~]/g,"").replace(/<[^>]+>/g,"").trim()}function OC(e){return e.replace(/\s+#+\s*$/,"").trim()}function xy(e,t){const r=FC(e).toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu,"").trim().replace(/\s+/g,"-")||"section",s=t.headingSlugCounts.get(r)??0;return t.headingSlugCounts.set(r,s+1),s===0?r:`${r}-${s}`}function N7(e){return FC(e)||e.trim()}function Ig(e){const t=e.match(/^\s{0,3}\[([^\]]+)\]:\s+(.+?)\s*$/);if(!t)return null;const n=yy(t[2]);return n?{id:Vm(t[1]),definition:{href:n.href,title:n.title}}:null}function wte(e){const t=new Map;for(const n of e){const r=Ig(n);r&&t.set(r.id,r.definition)}return t}function QC(e){return e.trim().toLowerCase()}function $C(e){const t=e.match(/^\s{0,3}\[\^([^\]]+)\]:\s+(.+)\s*$/);return t?{id:QC(t[1]),text:t[2]}:null}function Ste(e){const t=new Map;let n=null;for(const r of e){const s=$C(r);if(s){n=s.id,t.set(s.id,{id:s.id,text:s.text,index:t.size+1});continue}if(n&&/^\s{4,}\S/.test(r)){const i=t.get(n);i&&(i.text=`${i.text} ${r.trim()}`);continue}r.trim()&&(n=null)}return t}function Ate(e){const t=new Set;let n=!1;return e.forEach((r,s)=>{if($C(r)){t.add(s),n=!0;return}if(n&&/^\s{4,}\S/.test(r)){t.add(s);return}r.trim()&&(n=!1)}),t}function Tte(e){const t=[...e];let n=0;const r=e[0]?.trim();if(r==="---"||r==="+++"){for(t[0]="",n=1;n<e.length&&e[n].trim()!==r;)t[n]="",n+=1;n<e.length&&(t[n]="",n+=1)}for(;n<e.length;){const s=e[n].trim();if(s.startsWith("<!--")){if(t[n]="",!s.includes("-->")){for(n+=1;n<e.length&&!e[n].includes("-->");)t[n]="",n+=1;n<e.length&&(t[n]="")}n+=1;continue}n+=1}return t}function HC(e){const t=e.replace(/\/+$/,""),n=t.lastIndexOf("/");return n<=0?n===0?"/":"":t.slice(0,n)}function xh(e){const t=e.split(/[?#]/,1)[0],n=t.startsWith("/"),r=[];for(const i of t.split("/"))if(!(!i||i===".")){if(i===".."){r.length>0&&r.pop();continue}r.push(i)}return`${n?"/":""}${r.join("/")}`||(n?"/":".")}function Cte(e,t,n){const r=e.trim();if(!r||/^(?:https?:|mailto:|javascript:|data:|#)/i.test(r)||/^[a-z][a-z0-9+.-]*:/i.test(r))return null;const s=r.indexOf("#"),i=s>=0?r.slice(0,s):r,a=s>=0?r.slice(s+1):"",c=i.split("?",1)[0];if(!c)return null;let u,f=null;try{u=decodeURIComponent(c),f=a?decodeURIComponent(a):null}catch{return null}const p=n?xh(n):null;let g;if(u.startsWith("/")){const y=p&&(u===p||u.startsWith(`${p}/`));g=xh(p&&!y?`${p}/${u.slice(1)}`:u)}else{if(!t)return null;g=xh(`${HC(t)}/${u}`)}return p&&g!==p&&!g.startsWith(`${p}/`)?null:{path:g,fragment:f,directory:/\/$/.test(c)}}function kte(e,t,n){const r=e.trim();if(!r||/^(?:javascript|data):/i.test(r))return null;if(/^https?:\/\//i.test(r))return r;if(!Ry(r.split(/[?#]/,1)[0]))return null;let s;if(r.startsWith("/")){const i=n&&(r===n||r.startsWith(`${n}/`));s=xh(n&&!i?`${n}/${r.slice(1)}`:r)}else{if(!t)return null;s=xh(`${HC(t)}/${r}`)}return`/api/terminal/fs/blob?path=${encodeURIComponent(s)}`}const by=128,_te=360,Ib=480;function Gv(e){try{return/\.svg(?=$|[?#&])/i.test(decodeURIComponent(e))}catch{return!1}}function Lte(e,t,n,r){if(!t||!n)return null;let s,i;return Gv(e)?(i=Math.min(Math.max(n,by),_te),s=t*i/n):(s=t,i=n),r>0&&s>r&&(i=i*r/s,s=r),i>Ib&&(s=s*Ib/i,i=Ib),{width:Math.max(1,Math.round(s)),height:Math.max(1,Math.round(i))}}function Ete(e){if(!e.startsWith("/api/terminal/fs/blob?"))return null;try{return new URLSearchParams(e.slice(e.indexOf("?"))).get("path")}catch{return null}}function UC(e){const t=Ete(e),n=ct(r=>t?(r.fileChangeVersions.get(t)??0)+r.fileWatchEpoch:0);return t&&n>0?`${e}&v=${n}`:e}function Ite({src:e,alt:t,title:n}){const r=Gv(e),s=UC(e),i=x.useRef(null),[a,c]=x.useState(!1),[u,f]=x.useState(0),[p,g]=x.useState({status:"loading"}),[y,v]=x.useState(null);x.useLayoutEffect(()=>{const C=i.current,L=C?.parentElement?.parentElement??C?.parentElement;if(!L)return;const E=()=>f(L.clientWidth);if(E(),typeof ResizeObserver>"u")return;const D=new ResizeObserver(E);return D.observe(L),()=>D.disconnect()},[]),x.useEffect(()=>{if(a)return;const C=i.current;if(!C||typeof IntersectionObserver>"u"){c(!0);return}const L=new IntersectionObserver(E=>{E.some(D=>D.isIntersecting)&&(c(!0),L.disconnect())},{rootMargin:"400px"});return L.observe(C),()=>L.disconnect()},[a]),x.useEffect(()=>{if(!a)return;const C=new AbortController;let L=null;g({status:"loading"});const E=window.setTimeout(()=>{C.abort(new DOMException("Image fetch timed out","TimeoutError"))},15e3);return fetch(s,{signal:C.signal}).then(async D=>{if(!D.ok)throw new Error(`HTTP ${D.status}`);const B=Number(D.headers.get("X-Image-Width"))||0,F=Number(D.headers.get("X-Image-Height"))||0;return{blob:await D.blob(),width:B,height:F}}).then(({blob:D,width:B,height:F})=>{C.signal.aborted||(L=URL.createObjectURL(D),B>0&&F>0&&v({width:B,height:F}),g({status:"ready",objectUrl:L}))}).catch(()=>{const D=C.signal.reason;C.signal.aborted&&!(D instanceof DOMException&&D.name==="TimeoutError")||g({status:"fallback"})}).finally(()=>{window.clearTimeout(E)}),()=>{window.clearTimeout(E),C.abort(),L&&URL.revokeObjectURL(L)}},[a,s]);const S=Lte(e,y?.width??0,y?.height??0,u),T=S??{width:by*2,height:by};return o.jsx("div",{ref:i,className:"block max-w-full",style:S?{width:S.width,height:S.height}:void 0,children:p.status==="ready"?o.jsx("img",{src:p.objectUrl,alt:t,title:n,decoding:"async",className:`${r?"":"termdock-fade-in "}block max-h-[480px] max-w-full object-contain`,style:S?{width:S.width,height:S.height}:void 0,onLoad:C=>{if(y)return;const L=C.currentTarget;L.naturalWidth>0&&L.naturalHeight>0&&v({width:L.naturalWidth,height:L.naturalHeight})}}):p.status==="fallback"?o.jsx("img",{src:s,alt:t,title:n,loading:"lazy",decoding:"async",className:"block max-h-[480px] max-w-full object-contain",style:S?{width:S.width,height:S.height}:void 0,onLoad:C=>{if(y)return;const L=C.currentTarget;L.naturalWidth>0&&L.naturalHeight>0&&v({width:L.naturalWidth,height:L.naturalHeight})}}):o.jsx("div",{"aria-hidden":!0,className:"flex max-w-full animate-pulse items-center justify-center rounded bg-surface-elevated/60",style:{width:T.width,height:T.height},children:o.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:t||"…"})})})}function Rb(e,t,n,r,s){const i=kte(n,s.markdownFilePath,s.rootPath);if(!i)return``;const a=s.images.length;s.images.push({kind:"image",src:i,alt:t,title:r});const c=o.jsx(Ite,{src:i,alt:t,title:r});return s.onImageOpen?o.jsx("button",{type:"button",className:"my-2 block max-w-full overflow-hidden rounded-md border border-border/20 bg-surface-2 text-left transition hover:border-border-strong focus:outline-none focus:ring-2 focus:ring-ring/45",title:r||t||"Open image",onClick:u=>{u.stopPropagation(),s.onImageOpen?.(a)},children:c},e):o.jsx("span",{className:"my-2 block max-w-full overflow-hidden rounded-md border border-border/20 bg-surface-2",children:c},e)}function Nb(e){let t=e,n="";for(;/[.,;:!?)]$/.test(t);)n=`${t.slice(-1)}${n}`,t=t.slice(0,-1);return{linkText:t,suffix:n}}function M7(e){return/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(e)}function yy(e){const t=e.trim(),n=t.match(/^<([^>]+)>(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);if(n)return{href:n[1],title:n[2]??n[3]??n[4]};const r=t.match(/^(\S+)(?:\s+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?$/);return r?{href:r[1],title:r[2]??r[3]??r[4]}:null}const zC="",Rte=/\\([\\`*{}\[\]#+\-.!_|~>$])/g;function Nte(e){return e.replace(Rte,(t,n)=>`${zC}${n.charCodeAt(0).toString(16).padStart(4,"0")}`)}function D7(e){return e.replace(new RegExp(`${zC}([0-9a-f]{4})`,"g"),(t,n)=>String.fromCharCode(Number.parseInt(n,16))).replace(/\\([()])/g,"$1")}function Mte(e){const t=e.replace(/[\r\n]+/g," ");return/^ .+ $/.test(t)&&/[^ ]/.test(t.slice(1,-1))?t.slice(1,-1):t}const GC={ALLOWED_TAGS:["a","abbr","b","blockquote","br","code","del","details","div","em","i","kbd","li","mark","ol","p","pre","s","span","strong","sub","summary","sup","table","tbody","td","th","thead","tr","u","ul"],ALLOWED_ATTR:["href","title","class","id","colspan","rowspan"],ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!0};let mm=null;function WC(){return mm||(mm=P0(()=>import("./purify.es-CC4Brkr_.js"),[]).then(e=>e.default??e).catch(e=>{throw mm=null,e})),mm}function VC({html:e}){const{t}=qn(),[n,r]=x.useState(null);return x.useEffect(()=>{let s=!1;return r(null),WC().then(i=>{s||r(i.sanitize(e,GC))}).catch(()=>{s||r("")}),()=>{s=!0}},[e]),n===null?o.jsx("div",{className:"py-2 text-xs text-muted-foreground",children:t("rightSidebar.renderingHtml")}):n?o.jsx("div",{className:"text-muted-foreground",dangerouslySetInnerHTML:{__html:n}}):null}function Dte({html:e}){const[t,n]=x.useState(null);return x.useEffect(()=>{let r=!1;return n(null),WC().then(s=>{r||n(s.sanitize(e,GC))}).catch(()=>{r||n("")}),()=>{r=!0}},[e]),t===null?null:t?o.jsx("span",{dangerouslySetInnerHTML:{__html:t}}):e}function qC(e){const t=e.trim().match(/^<(div|section|article|aside|table|p|ul|ol|li|blockquote|pre|figure|figcaption)\b[^>]*>/i);if(!t)return null;const n=t[1].toLowerCase();return{tag:n,selfContained:new RegExp(`</${n}>`,"i").test(e)}}let gm=null;function jte(){return gm||(gm=Promise.all([P0(()=>import("./katex-DnlPpQZa.js"),[]),P0(()=>Promise.resolve({}),__vite__mapDeps([5]))]).then(([e])=>e.default??e).catch(e=>{throw gm=null,e})),gm}function Fh({tex:e,display:t=!1}){const[n,r]=x.useState(null),[s,i]=x.useState(!1);if(x.useEffect(()=>{let c=!1;return r(null),i(!1),jte().then(u=>{c||r(u.renderToString(e,{displayMode:t,throwOnError:!1,trust:!1,strict:"ignore"}))}).catch(()=>{c||i(!0)}),()=>{c=!0}},[t,e]),s)return o.jsx("code",{className:"rounded bg-surface-2 px-1 py-0.5 font-mono text-[0.92em] text-foreground",children:t?`$$${e}$$`:`$${e}$`});if(!n)return o.jsx("span",{className:"text-muted-foreground/70",children:t?"Rendering formula...":e});const a=t?"my-2 overflow-auto rounded-md bg-surface-2 px-3 py-2 text-center":"inline-block align-middle";return o.jsx("span",{className:a,dangerouslySetInnerHTML:{__html:n}})}function Pte(e,t,n){if(/^<br\s*\/?>$/i.test(e))return o.jsx("br",{},t);const r=e.match(/^<(kbd|mark|sub|sup)>(.*?)<\/\1>$/i);if(!r)return/^<(a|abbr|span|b|strong|em|i|u|s|del|code)\b[\s\S]*<\/\1>$/i.test(e)?o.jsx(Dte,{html:e},t):null;const s=r[1].toLowerCase(),i=Ei(r[2],`${t}-${s}`,!0,n);return s==="kbd"?o.jsx("kbd",{className:"rounded border border-border/30 bg-surface-2 px-1.5 py-0.5 font-mono text-[0.85em] text-foreground shadow-sm",children:i},t):s==="mark"?o.jsx("mark",{className:"rounded bg-warning/25 px-0.5 text-foreground",children:i},t):s==="sub"?o.jsx("sub",{children:i},t):o.jsx("sup",{children:i},t)}function Ei(e,t,n=!0,r){const s=Nte(e),i=/(\\\([^)]*\\\)|\$[^$\n]+\$|<br\s*\/?>|<(?:a|abbr|span|b|strong|em|i|u|s|del|code|kbd|mark|sub|sup)\b[\s\S]*?<\/(?:a|abbr|span|b|strong|em|i|u|s|del|code|kbd|mark|sub|sup)>|!?\[[^\]]*\]\((?:<[^>]+>|(?:[^\s()]+|\([^()\s]*\))+)(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\)|!?\[[^\]]+\]\[[^\]]*\]|!?\[[^\]]+\]|\[\^[^\]]+\]|(`+)([\s\S]*?)\2|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|\*[^*\s][^*]*\*|_[^_\s][^_]*_|<https?:\/\/[^>\s]+>|<[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+>|https?:\/\/[^\s<]+|www\.[^\s<]+|[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+)/gi,a=[];let c=0,u;for(;(u=i.exec(s))!==null;){u.index>c&&a.push(D7(s.slice(c,u.index)));const f=u[0],p=`${t}-${u.index}`,g=f.startsWith("<")?Pte(f,p,r):null;if(g)a.push(g);else if(f.startsWith("\\(")&&f.endsWith("\\)"))a.push(o.jsx(Fh,{tex:f.slice(2,-2)},p));else if(f.startsWith("$")&&f.endsWith("$"))a.push(o.jsx(Fh,{tex:f.slice(1,-1)},p));else if(f.startsWith("`")){const y=f.match(/^`+/)?.[0].length??1;a.push(o.jsx("code",{className:`${n?"break-all":"whitespace-nowrap"} rounded bg-surface-2 px-1 py-0.5 font-mono text-[0.92em] text-foreground`,children:Mte(f.slice(y,-y))},p))}else if(f.startsWith("~~"))a.push(o.jsx("del",{className:"text-muted-foreground decoration-border-strong",children:Ei(f.slice(2,-2),`${p}-del`,n,r)},p));else if(f.startsWith("**")||f.startsWith("__"))a.push(o.jsx("strong",{className:"font-semibold text-foreground",children:Ei(f.slice(2,-2),`${p}-strong`,n,r)},p));else if(f.startsWith("*")||f.startsWith("_"))a.push(o.jsx("em",{className:"italic",children:Ei(f.slice(1,-1),`${p}-em`,n,r)},p));else if(f.startsWith("![")){const y=f.match(/^!\[([^\]]*)\]\((.*)\)$/),v=f.match(/^!\[([^\]]+)\]\[([^\]]*)\]$/),S=f.match(/^!\[([^\]]+)\]$/);if(y){const T=yy(y[2]);a.push(T?Rb(p,y[1],T.href,T.title,r):f)}else if(v){const T=v[2]||v[1],C=r.referenceDefinitions.get(Vm(T));a.push(C?Rb(p,v[1],C.href,C.title,r):f)}else if(S){const T=r.referenceDefinitions.get(Vm(S[1]));a.push(T?Rb(p,S[1],T.href,T.title,r):f)}else a.push(f)}else if(f.startsWith("[^")){const y=QC(f.slice(2,-1)),v=r.footnoteDefinitions.get(y);a.push(v?o.jsx("sup",{id:`fnref-${v.id}`,title:v.text,className:"ml-0.5 rounded bg-surface-2 px-1 text-[0.72em] font-semibold text-primary",children:o.jsx("a",{href:`#fn-${v.id}`,className:"text-primary no-underline",children:v.index})},p):f)}else if(f.startsWith("<http")){const y=f.slice(1,-1);a.push(o.jsx("a",{href:y,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p))}else if(f.startsWith("<")&&f.endsWith(">")&&M7(f.slice(1,-1))){const y=f.slice(1,-1);a.push(o.jsx("a",{href:`mailto:${y}`,className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p))}else if(M7(Nb(f).linkText)){const{linkText:y,suffix:v}=Nb(f);a.push(o.jsx("a",{href:`mailto:${y}`,className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p)),v&&a.push(v)}else if(f.startsWith("http")||f.startsWith("www.")){const{linkText:y,suffix:v}=Nb(f),S=y.startsWith("www.")?`https://${y}`:y;a.push(o.jsx("a",{href:S,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:y},p)),v&&a.push(v)}else{const y=f.match(/^\[([^\]]+)\]\((.*)\)$/),v=f.match(/^\[([^\]]+)\]\[([^\]]*)\]$/),S=f.match(/^\[([^\]]+)\]$/),T=v?v[2]||v[1]:S?.[1]??null,C=T?r.referenceDefinitions.get(Vm(T)):null,L=y?yy(y[2]):null,E=L?.href??C?.href??null,D=E?vte(E):null,B=y?.[1]??v?.[1]??S?.[1]??"";a.push(D?o.jsx("a",{href:D,title:L?.title??C?.title,target:"_blank",rel:"noreferrer",className:`${n?"break-all":"whitespace-nowrap"} text-primary underline decoration-primary/40 underline-offset-2 hover:decoration-primary`,children:Ei(B,`${p}-link`,n,r)},p):f)}c=i.lastIndex}return c<s.length&&a.push(D7(s.slice(c))),a.length>0?a:[e]}function KC(e){return/(?: {2,}|\\)$/.test(e)}function YC(e){return e.replace(/(?: {2,}|\\)$/,"")}function Rg(e){return/^(?: {4}|\t)/.test(e)}function XC(e){return e.startsWith(" ")?e.slice(1):e.replace(/^ {4}/,"")}function ZC(e,t,n){const r=[];return e.forEach((s,i)=>{const a=KC(s);r.push(...Ei(YC(s),`${t}-${i}`,!0,n)),i<e.length-1&&r.push(a?o.jsx("br",{},`${t}-${i}-br`):" ")}),r}function vy(e,t,n){const r=[],s=[];return e.forEach((i,a)=>{s.push(KC(i)),r.push(Ei(YC(i),`${t}-${a}`,!0,n))}),{perLine:r,hardBreaks:s}}function wy(e,t,n,r,s){const i=[];return e.forEach((a,c)=>{const u=n[c]??0,f=!!(s&&u>=s.start&&u<=s.end);i.push(o.jsx("span",{"data-md-ref-start":u,"data-md-ref-end":u,"data-selected":f?"true":void 0,children:a},`${r}-ref-${c}`)),c<e.length-1&&i.push(t[c]?o.jsx("br",{},`${r}-${c}-br`):" ")}),i}function Oh(e){const t=e.trim().replace(/^\|/,"").replace(/\|$/,""),n=[];let r="",s=!1,i=0,a=0;for(let c=0;c<t.length;c+=1){const u=t[c];if(s){r+=u,s=!1;continue}if(u==="\\"){s=!0;continue}if(u==="`"){const f=c;for(;c+1<t.length&&t[c+1]==="`";)c+=1;const p=c-f+1;r+="`".repeat(p),i===0?i=p:i===p&&(i=0);continue}if(i===0&&u==="["?a+=1:i===0&&u==="]"&&a>0&&(a-=1),u==="|"&&i===0&&a===0){n.push(r.trim()),r="";continue}r+=u}return s&&(r+="\\"),n.push(r.trim()),n}function JC(e){return Oh(e).map(t=>/^:-+:$/.test(t)?"center":/^-+:$/.test(t)?"right":/^:-+$/.test(t)?"left":null)}function Ng(e){return e==="center"?"text-center":e==="right"?"text-right":"text-left"}function Mg(e){return/^\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)*\|?$/.test(e.trim())}function Bte(e,t){return e>96||e>44&&t>.35}function Wv(e){return(e.match(/^\s*/)?.[0]??"").replace(/\t/g," ").length}function Vv(e){const t=e.trim().match(/^([-+*]|\d+[.)])\s+(.+)$/);if(!t)return null;const n=/^\d+[.)]$/.test(t[1]);return{ordered:n,start:n?Number.parseInt(t[1],10):void 0,content:t[2]}}function ek(e,t,n,r,s,i=new Set){const a=[],c=[];let u=t;for(;u<e.length;){const f=e[u];if(s&&(Ig(f)||i.has(u))){u+=1;continue}const p=Vv(f),g=Wv(f);if(!p){if(g>n&&c.length>0){([...c].reverse().find(T=>T.indent<g)?.item??c[c.length-1].item).paragraphs.push(f.trim());for(const T of c)T.item.lineEnd=u+1;u+=1;continue}break}if(g<n||g===n&&p.ordered!==r)break;const y={content:p.content,ordered:p.ordered,start:p.start,children:[],paragraphs:[],lineStart:u+1,lineEnd:u+1};for(;c.length>0&&c[c.length-1].indent>=g;)c.pop();const v=c[c.length-1]?.item??null;v?v.children.push(y):a.push(y),c.push({indent:g,item:y});for(const S of c)S.item.lineEnd=u+1;u+=1}return{items:a,nextIndex:u}}function qv(e,t,n,r=0){return e.map((s,i)=>{const a=s.content.match(/^\[([ xX])\]\s+(.+)$/);return{key:`item-${i}`,taskItem:!!a,refStart:s.lineStart+r,refEnd:s.lineEnd+r,content:o.jsxs(o.Fragment,{children:[a?o.jsx("input",{type:"checkbox",checked:a[1].toLowerCase()==="x",readOnly:!0,className:"mr-2 align-[-2px] accent-primary"}):null,Ei(a?.[2]??s.content,`li-${t}-${i}`,!0,n),s.paragraphs.length>0&&o.jsx("div",{className:"mt-1 space-y-1 text-muted-foreground",children:s.paragraphs.map((c,u)=>o.jsx("p",{children:Ei(c,`li-${t}-${i}-p-${u}`,!0,n)},`paragraph-${u}`))})]}),groups:Fte(s.children,`${t}-${i}`,n,r)}})}function Fte(e,t,n,r=0){const s=[];for(const i of e){const a=s[s.length-1];a&&a.ordered===i.ordered?a.items.push(i):s.push({ordered:i.ordered,items:[i]})}return s.map((i,a)=>({ordered:i.ordered,start:i.ordered?i.items[0]?.start:void 0,items:qv(i.items,`${t}-g${a}`,n,r)}))}function Kv(e,t){return e.map(n=>{const r=!!(t&&n.refStart<=t.end&&n.refEnd>=t.start);return o.jsxs("li",{className:n.taskItem?"list-none":void 0,"data-md-ref-start":n.refStart,"data-md-ref-end":n.refEnd,"data-selected":r?"true":void 0,children:[n.content,n.groups.length>0&&Ote(n.groups,t)]},n.key)})}function Ote(e,t){return e.map((n,r)=>{const s=n.ordered?"ol":"ul";return o.jsx(s,{start:n.start,className:`${n.ordered?"list-decimal":"list-disc"} mt-1 space-y-0.5 pl-4 marker:text-muted-foreground/60`,children:Kv(n.items,t)},`nested-${r}`)})}function Qte(e){const t=Array.from(e.footnoteDefinitions.values()).sort((n,r)=>n.index-r.index);return t.length===0?null:o.jsxs("section",{className:"mt-3 border-t border-border/20 pt-2 text-[12px] leading-5 text-muted-foreground",children:[o.jsx("div",{className:"mb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/80",children:e.footnotesLabel}),o.jsx("ol",{className:"list-decimal space-y-1 pl-5",children:t.map(n=>o.jsxs("li",{id:`fn-${n.id}`,children:[Ei(n.text,`footnote-${n.id}`,!0,e)," ",o.jsx("a",{href:`#fnref-${n.id}`,className:"text-primary no-underline","aria-label":e.backToFootnoteLabel(n.index),children:"↩"})]},n.id))})]})}function $te(e,t,n,r){const s=[];let i=0;const a=c=>r?.[c]??c+1;for(;i<e.length;){const c=e[i],u=c.trim();if(!u){i+=1;continue}if(/^<details>\s*$/i.test(u)){const L=i;let E="Details";const D=[];for(i+=1;i<e.length&&!/^<\/details>\s*$/i.test(e[i].trim());){const B=e[i].trim().match(/^<summary>(.*?)<\/summary>\s*$/i);B?E=B[1].trim()||E:D.push(e[i].trimStart()),i+=1}i<e.length&&(i+=1),s.push({kind:"static",node:o.jsxs("details",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface px-3 py-2 text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-foreground",children:Ei(E,`${t}-details-${L}-summary`,!0,n)}),D.length>0&&o.jsx("div",{className:"mt-2 text-sm leading-6",children:ZC(D,`${t}-details-${L}`,n)})]},`${t}-details-${L}`)});continue}const f=qC(c);if(f){const L=[c],E=i;for(i+=1;i<e.length&&!f.selfContained&&!new RegExp(`</${f.tag}>`,"i").test(e[i]);)L.push(e[i]),i+=1;i<e.length&&!f.selfContained&&(L.push(e[i]),i+=1),s.push({kind:"static",node:o.jsx(VC,{html:L.join(`
|
|
183
183
|
`)},`${t}-html-${E}`)});continue}const p=u.match(/^(```|~~~)\s*(.*)$/);if(p){const L=[],E=p[1],D=p[2]?.trim(),B=i;for(i+=1;i<e.length&&!e[i].trim().startsWith(E);)L.push(e[i]),i+=1;i<e.length&&(i+=1),D.toLowerCase()==="mermaid"?s.push({kind:"static",node:o.jsx(nk,{code:L.join(`
|
|
184
184
|
`),blockKey:`${t}-code-${B}`},`${t}-code-${B}`)}):["math","latex","tex"].includes(D.toLowerCase())?s.push({kind:"static",node:o.jsx(Fh,{tex:L.join(`
|
|
185
185
|
`),display:!0},`${t}-code-${B}`)}):s.push({kind:"code",key:`${t}-code-${B}`,code:L.join(`
|
|
186
186
|
`),lang:D,blockKey:`${t}-code-${B}`,codeStartLine:a(B)+1});continue}if(Rg(c)){const L=[],E=i;for(;i<e.length&&(Rg(e[i])||!e[i].trim());)L.push(e[i].trim()?XC(e[i]):""),i+=1;s.push({kind:"code",key:`${t}-indented-code-${E}`,code:L.join(`
|
|
187
|
-
`).replace(/\n+$/,""),lang:"",blockKey:`${t}-indented-code-${E}`,codeStartLine:a(E)});continue}const g=u.match(/^(#{1,6})\s+(.+)$/);if(g){const E=`h${Math.min(6,g[1].length+1)}`,D=OC(g[2]),B=xy(D,n);s.push({kind:"static",node:o.jsx(E,{id:B,className:"scroll-mt-16 font-semibold text-foreground",children:Ei(D,`${t}-heading-${i}`,!0,n)},`${t}-heading-${i}`)}),i+=1;continue}if(i+1<e.length&&c.includes("|")&&Mg(e[i+1])){const L=Oh(c),E=JC(e[i+1]),D=[],B=i;for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim();)D.push(Oh(e[i])),i+=1;s.push({kind:"static",node:o.jsx("div",{className:RC,"data-markdown-table-scroll":!0,children:o.jsxs("table",{className:"w-max min-w-full max-w-none table-auto border-collapse text-left text-[11px] sm:text-xs",children:[o.jsx("thead",{className:"bg-surface-2 text-foreground",children:o.jsx("tr",{children:L.map((F,j)=>o.jsx("th",{className:`${EC} ${Ng(E[j]??null)}`,children:o.jsx("div",{className:Eg,children:Ei(F,`${t}-th-${B}-${j}`,!0,n)})},`h-${j}`))})}),o.jsx("tbody",{children:D.map((F,j)=>o.jsx("tr",{className:"border-t border-border/10",children:L.map((A,H)=>o.jsx("td",{className:`${IC} ${Ng(E[H]??null)}`,children:o.jsx("div",{className:Eg,children:Ei(F[H]??"",`${t}-td-${B}-${j}-${H}`,!0,n)})},`c-${H}`))},`r-${j}`))})]})},`${t}-table-${B}`)});continue}const y=Vv(c);if(y){const L=y.ordered,E=Wv(c),D=y.start,B=i,F=ek(e,i,E,L,!1);i=F.nextIndex,s.push({kind:"list",keyPrefix:`${t}-list-${B}`,ordered:L,start:L?D:void 0,renders:qv(F.items,`${t}-list-${B}`,n,a(0)-1)});continue}const v=[c.trimStart()],S=[a(i)],T=i;for(i+=1;i<e.length&&e[i].trim()&&!gy(e[i])&&!(i+1<e.length&&e[i].includes("|")&&Mg(e[i+1]));)v.push(e[i].trimStart()),S.push(a(i)),i+=1;const C=vy(v,`${t}-p-${T}`,n);s.push({kind:"paragraph",keyPrefix:`${t}-p-${T}`,perLine:C.perLine,hardBreaks:C.hardBreaks,lineNums:S})}return s}function Hte(e,t){return e.map(n=>{switch(n.kind){case"static":return n.node;case"paragraph":return o.jsx("p",{children:wy(n.perLine,n.hardBreaks,n.lineNums,n.keyPrefix,t)},n.keyPrefix);case"list":{const r=n.ordered?"ol":"ul";return o.jsx(r,{start:n.start,className:`${n.ordered?"list-decimal":"list-disc"} space-y-0.5 pl-4 marker:text-muted-foreground/70`,children:Kv(n.renders,t)},n.keyPrefix)}case"code":return o.jsx(Dg,{code:n.code,lang:n.lang,blockKey:n.blockKey,codeStartLine:n.codeStartLine,lineRange:t},n.key)}})}let xm=null,j7=!1;const bm=16,tk=192;function Ute(){return xm||(xm=P0(()=>import("./mermaid.core-
|
|
187
|
+
`).replace(/\n+$/,""),lang:"",blockKey:`${t}-indented-code-${E}`,codeStartLine:a(E)});continue}const g=u.match(/^(#{1,6})\s+(.+)$/);if(g){const E=`h${Math.min(6,g[1].length+1)}`,D=OC(g[2]),B=xy(D,n);s.push({kind:"static",node:o.jsx(E,{id:B,className:"scroll-mt-16 font-semibold text-foreground",children:Ei(D,`${t}-heading-${i}`,!0,n)},`${t}-heading-${i}`)}),i+=1;continue}if(i+1<e.length&&c.includes("|")&&Mg(e[i+1])){const L=Oh(c),E=JC(e[i+1]),D=[],B=i;for(i+=2;i<e.length&&e[i].includes("|")&&e[i].trim();)D.push(Oh(e[i])),i+=1;s.push({kind:"static",node:o.jsx("div",{className:RC,"data-markdown-table-scroll":!0,children:o.jsxs("table",{className:"w-max min-w-full max-w-none table-auto border-collapse text-left text-[11px] sm:text-xs",children:[o.jsx("thead",{className:"bg-surface-2 text-foreground",children:o.jsx("tr",{children:L.map((F,j)=>o.jsx("th",{className:`${EC} ${Ng(E[j]??null)}`,children:o.jsx("div",{className:Eg,children:Ei(F,`${t}-th-${B}-${j}`,!0,n)})},`h-${j}`))})}),o.jsx("tbody",{children:D.map((F,j)=>o.jsx("tr",{className:"border-t border-border/10",children:L.map((A,H)=>o.jsx("td",{className:`${IC} ${Ng(E[H]??null)}`,children:o.jsx("div",{className:Eg,children:Ei(F[H]??"",`${t}-td-${B}-${j}-${H}`,!0,n)})},`c-${H}`))},`r-${j}`))})]})},`${t}-table-${B}`)});continue}const y=Vv(c);if(y){const L=y.ordered,E=Wv(c),D=y.start,B=i,F=ek(e,i,E,L,!1);i=F.nextIndex,s.push({kind:"list",keyPrefix:`${t}-list-${B}`,ordered:L,start:L?D:void 0,renders:qv(F.items,`${t}-list-${B}`,n,a(0)-1)});continue}const v=[c.trimStart()],S=[a(i)],T=i;for(i+=1;i<e.length&&e[i].trim()&&!gy(e[i])&&!(i+1<e.length&&e[i].includes("|")&&Mg(e[i+1]));)v.push(e[i].trimStart()),S.push(a(i)),i+=1;const C=vy(v,`${t}-p-${T}`,n);s.push({kind:"paragraph",keyPrefix:`${t}-p-${T}`,perLine:C.perLine,hardBreaks:C.hardBreaks,lineNums:S})}return s}function Hte(e,t){return e.map(n=>{switch(n.kind){case"static":return n.node;case"paragraph":return o.jsx("p",{children:wy(n.perLine,n.hardBreaks,n.lineNums,n.keyPrefix,t)},n.keyPrefix);case"list":{const r=n.ordered?"ol":"ul";return o.jsx(r,{start:n.start,className:`${n.ordered?"list-decimal":"list-disc"} space-y-0.5 pl-4 marker:text-muted-foreground/70`,children:Kv(n.renders,t)},n.keyPrefix)}case"code":return o.jsx(Dg,{code:n.code,lang:n.lang,blockKey:n.blockKey,codeStartLine:n.codeStartLine,lineRange:t},n.key)}})}let xm=null,j7=!1;const bm=16,tk=192;function Ute(){return xm||(xm=P0(()=>import("./mermaid.core-BCd0z5d0.js").then(e=>e.aJ),__vite__mapDeps([6,1,7])).then(e=>e.default??e).catch(e=>{throw xm=null,e})),xm}function zte(e){j7||(e.initialize({startOnLoad:!1,securityLevel:"strict",theme:"neutral"}),j7=!0)}function Gte(e){const t=e.match(/\sviewBox=(["'])([^"']+)\1/i);if(!t)return e;const[,,n]=t,r=n.trim().split(/[\s,]+/).map(Number),[,,s,i]=r;if(!Number.isFinite(s)||!Number.isFinite(i)||s<=0||i<=0)return e;const a=Math.max(tk,Math.ceil(s)),c=Math.ceil(a/s*i);return e.replace(/<svg\b([^>]*)>/i,(u,f)=>`<svg${f.replace(/\s(?:width|height)=(["']).*?\1/gi,"").replace(/\sstyle=(["']).*?\1/gi,"")} width="${a}" height="${c}">`)}function Wte(e){const t=e?.querySelector("svg");if(!t)return;let n;try{n=t.getBBox()}catch{return}if(!Number.isFinite(n.width)||!Number.isFinite(n.height)||n.width<=0||n.height<=0)return;const r=n.x-bm,s=n.y-bm,i=n.width+bm*2,a=n.height+bm*2,c=Math.max(tk,Math.ceil(i)),u=Math.ceil(c/i*a);t.setAttribute("viewBox",`${r} ${s} ${i} ${a}`),t.setAttribute("width",String(c)),t.setAttribute("height",String(u)),t.removeAttribute("style")}function Vte(e){const t=e.trim().split(/\s+/,1)[0]?.toLowerCase();if(!t)return null;const n=t.replace(/^language-/,"");return S0(`code.${n}`)??n}function nk({code:e,blockKey:t}){const{t:n}=qn(),[r,s]=x.useState(null),[i,a]=x.useState(!1),c=x.useRef(null),u=x.useContext(BC);x.useEffect(()=>{let p=!1;return s(null),a(!1),Ute().then(async g=>{zte(g);const y=`termdock-md-mermaid-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`,{svg:v}=await g.render(y,e);p||s(Gte(v))}).catch(()=>{p||a(!0)}),()=>{p=!0}},[t,e]),x.useLayoutEffect(()=>{r&&Wte(c.current)},[r]);const f=x.useCallback(()=>{const p=c.current?.querySelector("svg")?.outerHTML??r;p&&u?.(p)},[u,r]);return i?o.jsx(Dg,{code:e,lang:"mermaid",blockKey:`${t}-fallback`}):o.jsxs("div",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface shadow-sm",children:[o.jsx("div",{className:"border-b border-border/15 bg-surface-2 px-3 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"mermaid"}),o.jsx("div",{className:"bg-surface p-3",children:r?o.jsx("button",{type:"button",className:"block max-w-full rounded text-left focus:outline-none focus:ring-2 focus:ring-ring/45",title:n("rightSidebar.openMermaidDiagram"),onClick:p=>{p.stopPropagation(),f()},children:o.jsx("span",{ref:c,role:"img","aria-label":n("rightSidebar.mermaidDiagram"),className:"block max-h-[70vh] max-w-full overflow-auto rounded bg-white p-2 text-slate-900 [&_svg]:block [&_svg]:h-auto [&_svg]:max-w-full",dangerouslySetInnerHTML:{__html:r}})}):o.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:n("rightSidebar.renderingDiagram")})})]})}function Dg({code:e,lang:t,blockKey:n,codeStartLine:r,lineRange:s}){const i=Vte(t),[a,c]=x.useState(null);x.useEffect(()=>{if(!i||!XT(e)){c(null);return}let f=!1;return ZT().then(p=>{if(f||!p.registered(i)){f||c(null);return}try{c(JT(p,e,i))}catch{f||c(null)}}).catch(()=>{f||c(null)}),()=>{f=!0}},[n,e,i]);const u=a??(e||" ").split(`
|
|
188
188
|
`).map(f=>[f||" "]);return o.jsxs("div",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface shadow-sm",children:[t&&o.jsx("div",{className:"border-b border-border/15 bg-surface-2 px-3 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:t}),o.jsx("pre",{className:`${zv} termdock-code overflow-auto p-3 text-[11px] leading-relaxed text-foreground`,children:o.jsx("code",{children:u.map((f,p)=>{const g=r!=null?r+p:null,y=!!(s&&g!=null&&g>=s.start&&g<=s.end);return o.jsxs("span",{"data-md-ref-start":g??void 0,"data-md-ref-end":g??void 0,"data-selected":y?"true":void 0,children:[f,p<u.length-1?`
|
|
189
189
|
`:null]},`${n}-line-${p}`)})})})]})}function qte(e,t,n,r,s){e=Tte(e);const i=wte(e),a=Ate(e),c=[],u={markdownFilePath:t,rootPath:n,referenceDefinitions:i,footnoteDefinitions:Ste(e),headingSlugCounts:new Map,images:c,onImageOpen:r,footnotesLabel:s?.footnotes??"Footnotes",backToFootnoteLabel:s?.backToFootnote??(y=>`Back to footnote ${y}`)},f=[];let p=0;for(;p<e.length;){const y=e[p],v=y.trim();if(Ig(y)||a.has(p)){p+=1;continue}if(!v){p+=1;continue}if(/^<details>\s*$/i.test(v)){const j=p;let A="Details";const H=[];for(p+=1;p<e.length&&!/^<\/details>\s*$/i.test(e[p].trim());){const Q=e[p].trim().match(/^<summary>(.*?)<\/summary>\s*$/i);Q?A=Q[1].trim()||A:H.push(e[p].trimStart()),p+=1}p<e.length&&(p+=1),f.push({key:`details-${j}`,startLine:j+1,endLine:p,content:o.jsxs("details",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface px-3 py-2 text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-foreground",children:Ei(A,`details-${j}-summary`,!0,u)}),H.length>0&&o.jsx("div",{className:"mt-2 text-sm leading-6",children:ZC(H,`details-${j}`,u)})]})});continue}const S=qC(y);if(S){const j=[y],A=p;for(p+=1;p<e.length&&!S.selfContained&&!new RegExp(`</${S.tag}>`,"i").test(e[p]);)j.push(e[p]),p+=1;p<e.length&&!S.selfContained&&(j.push(e[p]),p+=1),f.push({key:`html-${A}`,startLine:A+1,endLine:p,content:o.jsx(VC,{html:j.join(`
|
|
190
190
|
`)})});continue}const T=v.match(/^(```|~~~)\s*(.*)$/);if(T){const j=[],A=T[1],H=T[2]?.trim(),Q=p;for(p+=1;p<e.length&&!e[p].trim().startsWith(A);)j.push(e[p]),p+=1;p<e.length&&(p+=1),f.push({key:`code-${Q}`,startLine:Q+1,endLine:p,fineGrained:H.toLowerCase()!=="mermaid"&&!["math","latex","tex"].includes(H.toLowerCase()),content:H.toLowerCase()==="mermaid"?o.jsx(nk,{code:j.join(`
|
|
@@ -628,4 +628,4 @@ new file mode 100644
|
|
|
628
628
|
@@ -0,0 +1,2 @@
|
|
629
629
|
+export const second = true;
|
|
630
630
|
+announce(second);`}};function oS(){if(typeof window>"u")return"kotlin";const t=new URLSearchParams(window.location.search).get("fixture");return t&&t in Ty?t:"kotlin"}function aS(){return typeof window>"u"?"unified":new URLSearchParams(window.location.search).get("view")==="split"?"split":"unified"}function lS(){if(typeof window>"u")return"words";const e=new URLSearchParams(window.location.search).get("inline");return e==="none"||e==="chars"||e==="words"?e:"words"}function cS(){return typeof window>"u"?!0:new URLSearchParams(window.location.search).get("wrap")!=="off"}function are(){const[e,t]=x.useState(()=>oS()),[n,r]=x.useState(()=>aS()),[s,i]=x.useState(()=>dC()),[a,c]=x.useState(()=>lS()),[u,f]=x.useState(()=>cS()),p=Ty[e],g=x.useMemo(()=>Object.entries(Ty),[]),y=n==="split"&&!s?"unified":n;return x.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const v=window.matchMedia($v),S=()=>i(v.matches);return S(),v.addEventListener?.("change",S),()=>v.removeEventListener?.("change",S)},[]),x.useEffect(()=>{if(typeof window>"u")return;let v=window.location.search;const S=()=>{window.location.search!==v&&(v=window.location.search,t(oS()),r(aS()),c(lS()),f(cS()))};window.addEventListener("popstate",S),window.addEventListener("pageshow",S),window.addEventListener("focus",S);const T=window.setInterval(S,250);return()=>{window.removeEventListener("popstate",S),window.removeEventListener("pageshow",S),window.removeEventListener("focus",S),window.clearInterval(T)}},[]),o.jsx("div",{className:"min-h-screen bg-background-subtle text-foreground","data-diff-lab":!0,"data-diff-lab-fixture":e,"data-diff-lab-view":y,"data-diff-lab-requested-view":n,"data-diff-lab-inline":a,"data-diff-lab-wrap":u?"on":"off",children:o.jsxs("div",{className:"mx-auto flex min-h-screen max-w-[1180px] flex-col px-4 py-4",children:[o.jsxs("header",{className:"mb-3 flex flex-wrap items-center justify-between gap-3 border-b border-border/20 pb-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm font-semibold",children:"Diff Lab"}),o.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Fixed fixtures for iterating diff rendering without app auth, PWA state, or live Git data."})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("select",{value:e,onChange:v=>t(v.target.value),"aria-label":"Fixture",className:"h-8 rounded-md border border-border/30 bg-surface px-2 text-xs text-foreground outline-none",children:g.map(([v,S])=>o.jsx("option",{value:v,children:S.label},v))}),o.jsxs("div",{className:"inline-flex h-8 overflow-hidden rounded-full bg-surface-2 p-0.5",children:[o.jsx("button",{type:"button",onClick:()=>r("unified"),"aria-pressed":y==="unified",className:`rounded-full px-3 text-xs font-semibold ${y==="unified"?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:"Unified"}),o.jsx("button",{type:"button",onClick:()=>r("split"),disabled:!s,"aria-pressed":y==="split",className:`rounded-full px-3 text-xs font-semibold ${y==="split"?"bg-surface-elevated text-foreground":"text-muted-foreground"} disabled:cursor-not-allowed disabled:opacity-40`,children:"Split"})]}),o.jsx("div",{className:"inline-flex h-8 overflow-hidden rounded-full bg-surface-2 p-0.5",children:["none","words","chars"].map(v=>o.jsx("button",{type:"button",onClick:()=>c(v),className:`rounded-full px-3 text-xs font-semibold ${a===v?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:v},v))}),o.jsxs("button",{type:"button",onClick:()=>f(v=>!v),className:`h-8 rounded-full px-3 text-xs font-semibold ${u?"bg-primary/15 text-primary":"bg-surface-2 text-muted-foreground"}`,children:["Wrap ",u?"on":"off"]})]})]}),o.jsx("main",{className:"min-h-0 flex-1 overflow-auto rounded-lg border border-border/20 bg-surface",children:o.jsx(fC,{filePath:p.path,repoRoot:"/tmp/termdock-diff-lab",changedFile:{path:p.path,absolutePath:`/tmp/termdock-diff-lab/${p.path}`,repoRoot:"/tmp/termdock-diff-lab",status:"modified",staged:!1,unstaged:!0,untracked:!1,tracked:!0,canStage:!1,canUnstage:!1,canStash:!1,canRestoreWorktree:!1},diffOverride:p.diff,oldSourceOverride:p.oldSource,active:!0,wrap:u,showScrollHint:!u,viewType:y,inlineMode:a})})]})})}const gk=40,Cy="/tmp/termdock-diff-review-lab";function uS(e,t){const n=[`diff --git a/${e} b/${e}`,`--- a/${e}`,`+++ b/${e}`,`@@ -1,${t} +1,${t} @@`];for(let r=0;r<t;r+=1)r%5===0&&n.push(`-const removed_${r} = ${r};`),r%3===0&&n.push(`+const added_${r} = ${r} * 2;`),n.push(` context line ${r} in ${e}`);return n.join(`
|
|
631
|
-
`)}function lre(e,t){return Array.from({length:gk},(n,r)=>{const s=6+r*7%60,i=`src/module${String(r).padStart(2,"0")}/File${r}.ts`,a=`${Cy}/${i}`,c=uS(i,s),u=uS(i,1);return{key:a,path:i,absolutePath:a,status:"modified",repoRoot:Cy,displayName:`File${r}.ts`,displayDir:`src/module${String(r).padStart(2,"0")} · ${s} lines`,diffOverride:!t||e.has(r)?c:u,auditRecords:[]}})}function cre(){const e=x.useMemo(()=>{if(typeof window>"u")return 0;const L=new URLSearchParams(window.location.search).get("delay"),E=L===null?0:Number.parseInt(L,10);return Number.isInteger(E)&&E>0?E:0},[]),t=e>0,[n,r]=x.useState(()=>new Set);x.useEffect(()=>{if(!t)return;const L=Array.from({length:gk},(E,D)=>window.setTimeout(()=>{r(B=>{const F=new Set(B);return F.add(D),F})},e+D*20));return()=>L.forEach(E=>window.clearTimeout(E))},[t,e]);const s=x.useMemo(()=>lre(n,t),[n,t]),i=x.useMemo(()=>[{key:"mock-repo",root:Cy,label:"diff-review-lab",files:s.map(L=>({key:L.key,path:L.path,absolutePath:L.absolutePath,displayName:L.displayName,displayDir:L.displayDir,status:L.status}))}],[s]),a=x.useMemo(()=>{if(typeof window>"u")return null;const L=new URLSearchParams(window.location.search).get("select");if(L===null)return null;const E=Number.parseInt(L,10);return Number.isInteger(E)&&E>=0&&E<s.length?E:null},[s.length]),[c,u]=x.useState(()=>a!==null?s[a].key:null),[f,p]=x.useState(()=>({key:a!==null?s[a].key:null,nonce:a!==null?1:0})),[g,y]=x.useState("list"),[v,S]=x.useState(new Set),[T,C]=x.useState(a!==null?1:0);return o.jsxs("div",{className:"flex h-screen flex-col bg-background text-foreground","data-diff-review-lab":!0,children:[o.jsxs("div",{className:"shrink-0 border-b border-border/20 px-3 py-2 text-xs text-muted-foreground",children:["DiffReview Lab · ",s.length," mock files · selected: ",o.jsx("span",{"data-lab-selected":!0,children:c??"none"})," · slide ",T]}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(kg,{mobile:!0,backLabel:"Back",files:s,groups:i,selectedKey:c,scrollToKey:f.key,scrollToKeyNonce:f.nonce,mode:g,onModeChange:L=>{L!=="ai"&&y(L)},collapsedDirectoryKeys:v,onToggleDirectory:L=>S(E=>{const D=new Set(E);return D.has(L)?D.delete(L):D.add(L),D}),onSelectFile:L=>{u(L.key),p(E=>({key:L.key,nonce:E.nonce+1}))},onMobileSlideChange:C,renderLeading:()=>null,renderStreamBadge:L=>o.jsx("span",{className:"text-[10px] text-muted-foreground",children:L}),wrap:!0,showScrollHint:!1,activePane:!0})})]})}const ure=6e4,Ub="termdock:build-id:v1";let dS=!1;function fS(){dS||(dS=!0,window.setTimeout(()=>{window.location.reload()},80))}function ky(e){e.waiting?.postMessage({type:"SKIP_WAITING"})}async function dre(){if(typeof caches>"u")return;const e=await caches.keys();await Promise.all(e.map(t=>caches.delete(t)))}function fre(e){e.addEventListener("updatefound",()=>{const t=e.installing;t&&t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&ky(e)})})}function hre(){if(typeof window>"u"||!("serviceWorker"in navigator))return;const e="
|
|
631
|
+
`)}function lre(e,t){return Array.from({length:gk},(n,r)=>{const s=6+r*7%60,i=`src/module${String(r).padStart(2,"0")}/File${r}.ts`,a=`${Cy}/${i}`,c=uS(i,s),u=uS(i,1);return{key:a,path:i,absolutePath:a,status:"modified",repoRoot:Cy,displayName:`File${r}.ts`,displayDir:`src/module${String(r).padStart(2,"0")} · ${s} lines`,diffOverride:!t||e.has(r)?c:u,auditRecords:[]}})}function cre(){const e=x.useMemo(()=>{if(typeof window>"u")return 0;const L=new URLSearchParams(window.location.search).get("delay"),E=L===null?0:Number.parseInt(L,10);return Number.isInteger(E)&&E>0?E:0},[]),t=e>0,[n,r]=x.useState(()=>new Set);x.useEffect(()=>{if(!t)return;const L=Array.from({length:gk},(E,D)=>window.setTimeout(()=>{r(B=>{const F=new Set(B);return F.add(D),F})},e+D*20));return()=>L.forEach(E=>window.clearTimeout(E))},[t,e]);const s=x.useMemo(()=>lre(n,t),[n,t]),i=x.useMemo(()=>[{key:"mock-repo",root:Cy,label:"diff-review-lab",files:s.map(L=>({key:L.key,path:L.path,absolutePath:L.absolutePath,displayName:L.displayName,displayDir:L.displayDir,status:L.status}))}],[s]),a=x.useMemo(()=>{if(typeof window>"u")return null;const L=new URLSearchParams(window.location.search).get("select");if(L===null)return null;const E=Number.parseInt(L,10);return Number.isInteger(E)&&E>=0&&E<s.length?E:null},[s.length]),[c,u]=x.useState(()=>a!==null?s[a].key:null),[f,p]=x.useState(()=>({key:a!==null?s[a].key:null,nonce:a!==null?1:0})),[g,y]=x.useState("list"),[v,S]=x.useState(new Set),[T,C]=x.useState(a!==null?1:0);return o.jsxs("div",{className:"flex h-screen flex-col bg-background text-foreground","data-diff-review-lab":!0,children:[o.jsxs("div",{className:"shrink-0 border-b border-border/20 px-3 py-2 text-xs text-muted-foreground",children:["DiffReview Lab · ",s.length," mock files · selected: ",o.jsx("span",{"data-lab-selected":!0,children:c??"none"})," · slide ",T]}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(kg,{mobile:!0,backLabel:"Back",files:s,groups:i,selectedKey:c,scrollToKey:f.key,scrollToKeyNonce:f.nonce,mode:g,onModeChange:L=>{L!=="ai"&&y(L)},collapsedDirectoryKeys:v,onToggleDirectory:L=>S(E=>{const D=new Set(E);return D.has(L)?D.delete(L):D.add(L),D}),onSelectFile:L=>{u(L.key),p(E=>({key:L.key,nonce:E.nonce+1}))},onMobileSlideChange:C,renderLeading:()=>null,renderStreamBadge:L=>o.jsx("span",{className:"text-[10px] text-muted-foreground",children:L}),wrap:!0,showScrollHint:!1,activePane:!0})})]})}const ure=6e4,Ub="termdock:build-id:v1";let dS=!1;function fS(){dS||(dS=!0,window.setTimeout(()=>{window.location.reload()},80))}function ky(e){e.waiting?.postMessage({type:"SKIP_WAITING"})}async function dre(){if(typeof caches>"u")return;const e=await caches.keys();await Promise.all(e.map(t=>caches.delete(t)))}function fre(e){e.addEventListener("updatefound",()=>{const t=e.installing;t&&t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&ky(e)})})}function hre(){if(typeof window>"u"||!("serviceWorker"in navigator))return;const e="1788414804979",t=window.localStorage.getItem(Ub);if(t&&t!==e){dre().finally(()=>{window.localStorage.setItem(Ub,e),fS()});return}t!==e&&window.localStorage.setItem(Ub,e);let n=null;navigator.serviceWorker.addEventListener("controllerchange",fS),window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js",{scope:"/"}).then(r=>{fre(r),ky(r);const s=()=>{document.visibilityState==="visible"&&r.update().then(()=>ky(r)).catch(()=>{})};s(),n=window.setInterval(s,ure),document.addEventListener("visibilitychange",s)}).catch(()=>{})}),window.addEventListener("beforeunload",()=>{n!==null&&window.clearInterval(n)})}VO();hre();try{const e=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(e==="dark"||e==="light")&&(document.documentElement.dataset.theme=e,K9(e))}catch{}function pre(){const{t:e}=qn(),[t,n]=x.useState(null),[r,s]=x.useState(null),i=x.useCallback(async()=>{try{const a=await mI();n(a),s(null)}catch(a){s(a instanceof Error?a.message:"Failed to query auth status")}},[]);return x.useEffect(()=>{i()},[i]),x.useEffect(()=>{const a=()=>{n(c=>c&&{...c,authenticated:!1})};return window.addEventListener(bh,a),()=>window.removeEventListener(bh,a)},[]),t===null?o.jsx("div",{className:"flex w-screen items-center justify-center bg-background text-muted-foreground",style:{height:"var(--app-vh, 100vh)"},children:r?`${e("common.error")}: ${r}`:e("common.loading")}):t.enabled&&!t.authenticated?o.jsx(ire,{onLoginSuccess:i}):o.jsx(rre,{})}j_.createRoot(document.getElementById("root")).render(o.jsx(M.StrictMode,{children:o.jsx(eN,{children:o.jsx(eA,{children:(()=>{const e=new URLSearchParams(window.location.search);return e.get("dag-playground")==="1"?o.jsx(ore,{}):e.get("diff-review-lab")==="1"?o.jsx(cre,{}):e.get("diff-lab")==="1"?o.jsx(are,{}):o.jsx(pre,{})})()})})}));export{DM as M,$s as R,kD as S,P0 as _,OM as a,$M as b,kt as c,o as j,qn as u,gE as v};
|