termdock 1.4.12 → 1.4.13
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/{abnfDiagram-VRR7QNED-BbIU8JGv.js → abnfDiagram-VRR7QNED-BfgoPgyv.js} +1 -1
- package/dist/client/assets/{arc-Dh3O8MZW.js → arc-UER-m9g8.js} +1 -1
- package/dist/client/assets/{architectureDiagram-ZJ3FMSHR-B7pOVktb.js → architectureDiagram-ZJ3FMSHR-DlHbR1tc.js} +1 -1
- package/dist/client/assets/{blockDiagram-677ZJIJ3-XVk4wYBJ.js → blockDiagram-677ZJIJ3-GNgKDUS7.js} +1 -1
- package/dist/client/assets/{c4Diagram-LMCZKHZV-C8i1HVRm.js → c4Diagram-LMCZKHZV-CHrjy153.js} +1 -1
- package/dist/client/assets/channel-Di0C_ZGk.js +1 -0
- package/dist/client/assets/{chunk-2Q5K7J3B-7JAzXJ49.js → chunk-2Q5K7J3B-shHbDWXy.js} +1 -1
- package/dist/client/assets/{chunk-32BRIVSS-CmkLhxLH.js → chunk-32BRIVSS-Kh4nPorF.js} +1 -1
- package/dist/client/assets/{chunk-5VM5RSS4-DnZ9siXP.js → chunk-5VM5RSS4-CVuQQo5Y.js} +1 -1
- package/dist/client/assets/{chunk-EX3LRPZG-CcLKyv-X.js → chunk-EX3LRPZG-12SdwS06.js} +1 -1
- package/dist/client/assets/{chunk-JWPE2WC7-44ZjQWJe.js → chunk-JWPE2WC7-D3ekRdTo.js} +1 -1
- package/dist/client/assets/{chunk-MOJQB5TN-BZBAJPkZ.js → chunk-MOJQB5TN-DP66KHPr.js} +1 -1
- package/dist/client/assets/{chunk-RYQCIY6F-Iq1eyN0S.js → chunk-RYQCIY6F-BzOCbSfd.js} +1 -1
- package/dist/client/assets/{chunk-V7JOEXUC-CKx97yQ6.js → chunk-V7JOEXUC-R-QuFL31.js} +1 -1
- package/dist/client/assets/{chunk-VR4S4FIN-C9kxOsyA.js → chunk-VR4S4FIN-TLgeREs3.js} +1 -1
- package/dist/client/assets/{chunk-XXDRQBXY-Dy0xc7bk.js → chunk-XXDRQBXY-CuqhuA0q.js} +1 -1
- package/dist/client/assets/classDiagram-OUVF2IWQ-DLkVBV0z.js +1 -0
- package/dist/client/assets/classDiagram-v2-EOCWNBFH-DLkVBV0z.js +1 -0
- package/dist/client/assets/{cose-bilkent-JH36ORCC-1gFnVS84.js → cose-bilkent-JH36ORCC-DlX9Sw-L.js} +1 -1
- package/dist/client/assets/{cynefin-VYW2F7L2-B1RIFMo2.js → cynefin-VYW2F7L2-DNvyuZKO.js} +1 -1
- package/dist/client/assets/{cynefinDiagram-TSTJHNR4-BWxqGYYu.js → cynefinDiagram-TSTJHNR4-Dfc_5Bb7.js} +1 -1
- package/dist/client/assets/{dagre-VKFMJZFB-B2xmYm2s.js → dagre-VKFMJZFB-DwbuPXYD.js} +1 -1
- package/dist/client/assets/{diagram-FQU43EPY-BI2_KlO2.js → diagram-FQU43EPY-DUDuGeCQ.js} +1 -1
- package/dist/client/assets/{diagram-G47NLZAW-DNXXLs24.js → diagram-G47NLZAW-C0Fc0mGc.js} +1 -1
- package/dist/client/assets/{diagram-NH7WQ7WH-CIy4PaQt.js → diagram-NH7WQ7WH-BCfUo9RZ.js} +1 -1
- package/dist/client/assets/{diagram-OA4YK3LP-BpDoQSGa.js → diagram-OA4YK3LP-CXw-VBwR.js} +1 -1
- package/dist/client/assets/{diagram-WEI45ONY-DSw7tEuI.js → diagram-WEI45ONY-CptNKDSP.js} +1 -1
- package/dist/client/assets/{ebnfDiagram-CCIWWBDH-wrEZiQtV.js → ebnfDiagram-CCIWWBDH-Bovjdqjo.js} +1 -1
- package/dist/client/assets/{erDiagram-Q63AITRT-yJzMAANX.js → erDiagram-Q63AITRT-e2C-1nQR.js} +1 -1
- package/dist/client/assets/{flowDiagram-23GEKE2U-CVh8NPmy.js → flowDiagram-23GEKE2U-xS0ISsF2.js} +1 -1
- package/dist/client/assets/{ganttDiagram-NO4QXBWP-C3GmQfaH.js → ganttDiagram-NO4QXBWP-DBWO9VsL.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-IHSO6WYX-Dv1PJYCK.js → gitGraphDiagram-IHSO6WYX-D3zgenq3.js} +1 -1
- package/dist/client/assets/{index-CjUBNYk1.js → index-B9dw4S9H.js} +4 -4
- package/dist/client/assets/{infoDiagram-FWYZ7A6U-DEfcVg5C.js → infoDiagram-FWYZ7A6U-U08rPalq.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-FXEZZL3T-BAVB0lif.js → ishikawaDiagram-FXEZZL3T-68jvY2Z0.js} +1 -1
- package/dist/client/assets/{journeyDiagram-5HDEW3XC-D8Ke-nMw.js → journeyDiagram-5HDEW3XC-BGH0t4dB.js} +1 -1
- package/dist/client/assets/{kanban-definition-HUTT4EX6-BmmcDq55.js → kanban-definition-HUTT4EX6-Db5WrLkd.js} +1 -1
- package/dist/client/assets/{linear-DbIT5kSO.js → linear-C285fU9g.js} +1 -1
- package/dist/client/assets/{mermaid.core-ULoZppoN.js → mermaid.core-D2G1KcAK.js} +4 -4
- package/dist/client/assets/{mindmap-definition-LN4V7U3C-BzxXRmm8.js → mindmap-definition-LN4V7U3C-DDbzxu9E.js} +1 -1
- package/dist/client/assets/{pegDiagram-2B236MQR-B_gfCFOs.js → pegDiagram-2B236MQR-DGkn___-.js} +1 -1
- package/dist/client/assets/{pieDiagram-ENE6RG2P-CxVRi6p0.js → pieDiagram-ENE6RG2P-C_JrupdN.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-ABIIQ3AL-CsTuCHFg.js → quadrantDiagram-ABIIQ3AL-BQwkW1O_.js} +1 -1
- package/dist/client/assets/{railroadDiagram-RFXS5EU6-DVJqtQsn.js → railroadDiagram-RFXS5EU6-D07Olsgy.js} +1 -1
- package/dist/client/assets/{requirementDiagram-TGXJPOKE-BgJFldJG.js → requirementDiagram-TGXJPOKE-D-xPpUU0.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-HTMAVEWB-BUupM_QI.js → sankeyDiagram-HTMAVEWB-dTZVW9ct.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-DBY2YBRQ-DmDeMC9s.js → sequenceDiagram-DBY2YBRQ-gsNo6HNW.js} +1 -1
- package/dist/client/assets/{sizeCapture-X5ZJPWSS-BBAvrpSM.js → sizeCapture-X5ZJPWSS-FxvsxCA7.js} +1 -1
- package/dist/client/assets/{stateDiagram-2N3HPSRC-CC6pAJXB.js → stateDiagram-2N3HPSRC-CmThTMPK.js} +1 -1
- package/dist/client/assets/stateDiagram-v2-6OUMAXLB-DgmbpAVj.js +1 -0
- package/dist/client/assets/{swimlanes-5IMT3BWC-CK3ARAQi.js → swimlanes-5IMT3BWC-onkhtrB_.js} +2 -2
- package/dist/client/assets/swimlanesDiagram-G3AALYLV-Dr90KyB6.js +8 -0
- package/dist/client/assets/{timeline-definition-FHXFAJF6-140UJW2c.js → timeline-definition-FHXFAJF6-DQkeeX15.js} +1 -1
- package/dist/client/assets/{vennDiagram-L72KCM5P-DQ5joUye.js → vennDiagram-L72KCM5P-BMHh3ux2.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-EHGQE667-Bfh_vlF5.js → wardleyDiagram-EHGQE667-UoX8zRZt.js} +1 -1
- package/dist/client/assets/{xychartDiagram-FW5EYKEG-DV1un8hW.js → xychartDiagram-FW5EYKEG-BzJTLLcH.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/client/sw.js +1 -1
- package/package.json +1 -1
- package/dist/client/assets/channel-B35HtPNj.js +0 -1
- package/dist/client/assets/classDiagram-OUVF2IWQ-BbQJULsA.js +0 -1
- package/dist/client/assets/classDiagram-v2-EOCWNBFH-BbQJULsA.js +0 -1
- package/dist/client/assets/stateDiagram-v2-6OUMAXLB-BjFMxarX.js +0 -1
- package/dist/client/assets/swimlanesDiagram-G3AALYLV-CwUTuvFM.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/katex-55ZPZeOF.css","assets/mermaid.core-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Ca-rq7yX.js","assets/react-XDCjal2T.js","assets/katex-55ZPZeOF.css","assets/mermaid.core-D2G1KcAK.js","assets/purify.es-CC4Brkr_.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{r as _p,a as ST,g as m6}from"./react-XDCjal2T.js";import{b as A,R as P,r as i0,a as CT}from"./dnd-BCFAPC0L.js";import{L as _T,l as LT}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"]'))n(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"&&n(a)}).observe(document,{childList:!0,subtree:!0});function r(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 n(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();var Fm={exports:{}},U0={};var tb;function kT(){if(tb)return U0;tb=1;var e=_p(),t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=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(u,d,f){var b,g={},y=null,v=null;f!==void 0&&(y=""+f),d.key!==void 0&&(y=""+d.key),d.ref!==void 0&&(v=d.ref);for(b in d)n.call(d,b)&&!i.hasOwnProperty(b)&&(g[b]=d[b]);if(u&&u.defaultProps)for(b in d=u.defaultProps,d)g[b]===void 0&&(g[b]=d[b]);return{$$typeof:t,type:u,key:y,ref:v,props:g,_owner:s.current}}return U0.Fragment=r,U0.jsx=a,U0.jsxs=a,U0}var rb;function ET(){return rb||(rb=1,Fm.exports=kT()),Fm.exports}var c=ET(),jh={},nb;function IT(){if(nb)return jh;nb=1;var e=ST();return jh.createRoot=e.createRoot,jh.hydrateRoot=e.hydrateRoot,jh}var MT=IT();const RT=m6(MT);function sb(e){return e!==null&&typeof e=="object"&&"constructor"in e&&e.constructor===Object}function C2(e={},t={}){const r=["__proto__","constructor","prototype"];Object.keys(t).filter(n=>r.indexOf(n)<0).forEach(n=>{typeof e[n]>"u"?e[n]=t[n]:sb(t[n])&&sb(e[n])&&Object.keys(t[n]).length>0&&C2(e[n],t[n])})}const g6={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 Bc(){const e=typeof document<"u"?document:{};return C2(e,g6),e}const NT={document:g6,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 qi(){const e=typeof window<"u"?window:{};return C2(e,NT),e}function DT(e=""){return e.trim().split(" ").filter(t=>!!t.trim())}function BT(e){const t=e;Object.keys(t).forEach(r=>{try{t[r]=null}catch{}try{delete t[r]}catch{}})}function b6(e,t=0){return setTimeout(e,t)}function Wf(){return Date.now()}function PT(e){const t=qi();let r;return t.getComputedStyle&&(r=t.getComputedStyle(e,null)),!r&&e.currentStyle&&(r=e.currentStyle),r||(r=e.style),r}function jT(e,t="x"){const r=qi();let n,s,i;const a=PT(e);return r.WebKitCSSMatrix?(s=a.transform||a.webkitTransform,s.split(",").length>6&&(s=s.split(", ").map(u=>u.replace(",",".")).join(", ")),i=new r.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,"),n=i.toString().split(",")),t==="x"&&(r.WebKitCSSMatrix?s=i.m41:n.length===16?s=parseFloat(n[12]):s=parseFloat(n[4])),t==="y"&&(r.WebKitCSSMatrix?s=i.m42:n.length===16?s=parseFloat(n[13]):s=parseFloat(n[5])),s||0}function Qh(e){return typeof e=="object"&&e!==null&&e.constructor&&Object.prototype.toString.call(e).slice(8,-1)==="Object"}function QT(e){return typeof window<"u"&&typeof window.HTMLElement<"u"?e instanceof HTMLElement:e&&(e.nodeType===1||e.nodeType===11)}function So(...e){const t=Object(e[0]);for(let r=1;r<e.length;r+=1){const n=e[r];if(n!=null&&!QT(n)){const s=Object.keys(Object(n)).filter(i=>i!=="__proto__"&&i!=="constructor"&&i!=="prototype");for(let i=0,a=s.length;i<a;i+=1){const u=s[i],d=Object.getOwnPropertyDescriptor(n,u);d!==void 0&&d.enumerable&&(Qh(t[u])&&Qh(n[u])?n[u].__swiper__?t[u]=n[u]:So(t[u],n[u]):!Qh(t[u])&&Qh(n[u])?(t[u]={},n[u].__swiper__?t[u]=n[u]:So(t[u],n[u])):t[u]=n[u])}}}return t}function hu(e,t,r){e.style.setProperty(t,r)}function x6({swiper:e,targetPosition:t,side:r}){const n=qi(),s=-e.translate;let i=null,a;const u=e.params.speed;e.wrapperEl.style.scrollSnapType="none",n.cancelAnimationFrame(e.cssModeFrameID);const d=t>s?"next":"prev",f=(g,y)=>d==="next"&&g>=y||d==="prev"&&g<=y,b=()=>{a=new Date().getTime(),i===null&&(i=a);const g=Math.max(Math.min((a-i)/u,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({[r]:v}),f(v,t)){e.wrapperEl.style.overflow="hidden",e.wrapperEl.style.scrollSnapType="",setTimeout(()=>{e.wrapperEl.style.overflow="",e.wrapperEl.scrollTo({[r]:v})}),n.cancelAnimationFrame(e.cssModeFrameID);return}e.cssModeFrameID=n.requestAnimationFrame(b)};b()}function rl(e,t=""){const r=qi(),n=[...e.children];return r.HTMLSlotElement&&e instanceof HTMLSlotElement&&n.push(...e.assignedElements()),t?n.filter(s=>s.matches(t)):n}function FT(e,t){const r=[t];for(;r.length>0;){const n=r.shift();if(e===n)return!0;r.push(...n.children,...n.shadowRoot?n.shadowRoot.children:[],...n.assignedElements?n.assignedElements():[])}}function OT(e,t){const r=qi();let n=t.contains(e);return!n&&r.HTMLSlotElement&&t instanceof HTMLSlotElement&&(n=[...t.assignedElements()].includes(e),n||(n=FT(e,t))),n}function Vf(e){try{console.warn(e);return}catch{}}function g1(e,t=[]){const r=document.createElement(e);return r.classList.add(...Array.isArray(t)?t:DT(t)),r}function $T(e,t){const r=[];for(;e.previousElementSibling;){const n=e.previousElementSibling;t?n.matches(t)&&r.push(n):r.push(n),e=n}return r}function HT(e,t){const r=[];for(;e.nextElementSibling;){const n=e.nextElementSibling;t?n.matches(t)&&r.push(n):r.push(n),e=n}return r}function Ql(e,t){return qi().getComputedStyle(e,null).getPropertyValue(t)}function ib(e){let t=e,r;if(t){for(r=0;(t=t.previousSibling)!==null;)t.nodeType===1&&(r+=1);return r}}function UT(e,t){const r=[];let n=e.parentElement;for(;n;)r.push(n),n=n.parentElement;return r}function ob(e,t,r){const n=qi();return e[t==="width"?"offsetWidth":"offsetHeight"]+parseFloat(n.getComputedStyle(e,null).getPropertyValue(t==="width"?"margin-right":"margin-top"))+parseFloat(n.getComputedStyle(e,null).getPropertyValue(t==="width"?"margin-left":"margin-bottom"))}function ab(e,t=""){typeof trustedTypes<"u"?e.innerHTML=trustedTypes.createPolicy("html",{createHTML:r=>r}).createHTML(t):e.innerHTML=t}let Om;function GT(){const e=qi(),t=Bc();return{smoothScroll:t.documentElement&&t.documentElement.style&&"scrollBehavior"in t.documentElement.style,touch:!!("ontouchstart"in e||e.DocumentTouch&&t instanceof e.DocumentTouch)}}function y6(){return Om||(Om=GT()),Om}let $m;function zT({userAgent:e}={}){const t=y6(),r=qi(),n=r.navigator.platform,s=e||r.navigator.userAgent,i={ios:!1,android:!1},a=r.screen.width,u=r.screen.height,d=s.match(/(Android);?[\s\/]+([\d.]+)?/);let f=s.match(/(iPad)(?!\1).*OS\s([\d_]+)/);const b=s.match(/(iPod)(.*OS\s([\d_]+))?/),g=!f&&s.match(/(iPhone\sOS|iOS)\s([\d_]+)/),y=n==="Win32";let v=n==="MacIntel";const w=["1024x1366","1366x1024","834x1194","1194x834","834x1112","1112x834","768x1024","1024x768","820x1180","1180x820","810x1080","1080x810"];return!f&&v&&t.touch&&w.indexOf(`${a}x${u}`)>=0&&(f=s.match(/(Version)\/([\d.]+)/),f||(f=[0,1,"13_0_0"]),v=!1),d&&!y&&(i.os="android",i.android=!0),(f||g||b)&&(i.os="ios",i.ios=!0),i}function v6(e={}){return $m||($m=zT(e)),$m}let Hm;function WT(){const e=qi(),t=v6();let r=!1;function n(){const u=e.navigator.userAgent.toLowerCase();return u.indexOf("safari")>=0&&u.indexOf("chrome")<0&&u.indexOf("android")<0}if(n()){const u=String(e.navigator.userAgent);if(u.includes("Version/")){const[d,f]=u.split("Version/")[1].split(" ")[0].split(".").map(b=>Number(b));r=d<16||d===16&&f<2}}const s=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(e.navigator.userAgent),i=n(),a=i||s&&t.ios;return{isSafari:r||i,needPerspectiveFix:r,need3dFix:a,isWebView:s}}function w6(){return Hm||(Hm=WT()),Hm}function VT({swiper:e,on:t,emit:r}){const n=qi();let s=null,i=null;const a=()=>{!e||e.destroyed||!e.initialized||(r("beforeResize"),r("resize"))},u=()=>{!e||e.destroyed||!e.initialized||(s=new ResizeObserver(b=>{i=n.requestAnimationFrame(()=>{const{width:g,height:y}=e;let v=g,w=y;b.forEach(({contentBoxSize:T,contentRect:C,target:E})=>{E&&E!==e.el||(v=C?C.width:(T[0]||T).inlineSize,w=C?C.height:(T[0]||T).blockSize)}),(v!==g||w!==y)&&a()})}),s.observe(e.el))},d=()=>{i&&n.cancelAnimationFrame(i),s&&s.unobserve&&e.el&&(s.unobserve(e.el),s=null)},f=()=>{!e||e.destroyed||!e.initialized||r("orientationchange")};t("init",()=>{if(e.params.resizeObserver&&typeof n.ResizeObserver<"u"){u();return}n.addEventListener("resize",a),n.addEventListener("orientationchange",f)}),t("destroy",()=>{d(),n.removeEventListener("resize",a),n.removeEventListener("orientationchange",f)})}function qT({swiper:e,extendParams:t,on:r,emit:n}){const s=[],i=qi(),a=(f,b={})=>{const g=i.MutationObserver||i.WebkitMutationObserver,y=new g(v=>{if(e.__preventObserver__)return;if(v.length===1){n("observerUpdate",v[0]);return}const w=function(){n("observerUpdate",v[0])};i.requestAnimationFrame?i.requestAnimationFrame(w):i.setTimeout(w,0)});y.observe(f,{attributes:typeof b.attributes>"u"?!0:b.attributes,childList:e.isElement||(typeof b.childList>"u"?!0:b).childList,characterData:typeof b.characterData>"u"?!0:b.characterData}),s.push(y)},u=()=>{if(e.params.observer){if(e.params.observeParents){const f=UT(e.hostEl);for(let b=0;b<f.length;b+=1)a(f[b])}a(e.hostEl,{childList:e.params.observeSlideChildren}),a(e.wrapperEl,{attributes:!1})}},d=()=>{s.forEach(f=>{f.disconnect()}),s.splice(0,s.length)};t({observer:!1,observeParents:!1,observeSlideChildren:!1}),r("init",u),r("destroy",d)}var YT={on(e,t,r){const n=this;if(!n.eventsListeners||n.destroyed||typeof t!="function")return n;const s=r?"unshift":"push";return e.split(" ").forEach(i=>{n.eventsListeners[i]||(n.eventsListeners[i]=[]),n.eventsListeners[i][s](t)}),n},once(e,t,r){const n=this;if(!n.eventsListeners||n.destroyed||typeof t!="function")return n;function s(...i){n.off(e,s),s.__emitterProxy&&delete s.__emitterProxy,t.apply(n,i)}return s.__emitterProxy=t,n.on(e,s,r)},onAny(e,t){const r=this;if(!r.eventsListeners||r.destroyed||typeof e!="function")return r;const n=t?"unshift":"push";return r.eventsAnyListeners.indexOf(e)<0&&r.eventsAnyListeners[n](e),r},offAny(e){const t=this;if(!t.eventsListeners||t.destroyed||!t.eventsAnyListeners)return t;const r=t.eventsAnyListeners.indexOf(e);return r>=0&&t.eventsAnyListeners.splice(r,1),t},off(e,t){const r=this;return!r.eventsListeners||r.destroyed||!r.eventsListeners||e.split(" ").forEach(n=>{typeof t>"u"?r.eventsListeners[n]=[]:r.eventsListeners[n]&&r.eventsListeners[n].forEach((s,i)=>{(s===t||s.__emitterProxy&&s.__emitterProxy===t)&&r.eventsListeners[n].splice(i,1)})}),r},emit(...e){const t=this;if(!t.eventsListeners||t.destroyed||!t.eventsListeners)return t;let r,n,s;return typeof e[0]=="string"||Array.isArray(e[0])?(r=e[0],n=e.slice(1,e.length),s=t):(r=e[0].events,n=e[0].data,s=e[0].context||t),n.unshift(s),(Array.isArray(r)?r:r.split(" ")).forEach(a=>{t.eventsAnyListeners&&t.eventsAnyListeners.length&&t.eventsAnyListeners.forEach(u=>{u.apply(s,[a,...n])}),t.eventsListeners&&t.eventsListeners[a]&&t.eventsListeners[a].forEach(u=>{u.apply(s,n)})}),t}};function ZT(){const e=this;let t,r;const n=e.el;typeof e.params.width<"u"&&e.params.width!==null?t=e.params.width:t=n.clientWidth,typeof e.params.height<"u"&&e.params.height!==null?r=e.params.height:r=n.clientHeight,!(t===0&&e.isHorizontal()||r===0&&e.isVertical())&&(t=t-parseInt(Ql(n,"padding-left")||0,10)-parseInt(Ql(n,"padding-right")||0,10),r=r-parseInt(Ql(n,"padding-top")||0,10)-parseInt(Ql(n,"padding-bottom")||0,10),Number.isNaN(t)&&(t=0),Number.isNaN(r)&&(r=0),Object.assign(e,{width:t,height:r,size:e.isHorizontal()?t:r}))}function KT(){const e=this;function t(U,W){return parseFloat(U.getPropertyValue(e.getDirectionLabel(W))||0)}const r=e.params,{wrapperEl:n,slidesEl:s,rtlTranslate:i,wrongRTL:a}=e,u=e.virtual&&r.virtual.enabled,d=u?e.virtual.slides.length:e.slides.length,f=rl(s,`.${e.params.slideClass}, swiper-slide`),b=u?e.virtual.slides.length:f.length;let g=[];const y=[],v=[];let w=r.slidesOffsetBefore;typeof w=="function"&&(w=r.slidesOffsetBefore.call(e));let T=r.slidesOffsetAfter;typeof T=="function"&&(T=r.slidesOffsetAfter.call(e));const C=e.snapGrid.length,E=e.slidesGrid.length,N=e.size-w-T;let D=r.spaceBetween,R=-w,_=0,M=0;if(typeof N>"u")return;typeof D=="string"&&D.indexOf("%")>=0?D=parseFloat(D.replace("%",""))/100*N:typeof D=="string"&&(D=parseFloat(D)),e.virtualSize=-D-w-T,f.forEach(U=>{i?U.style.marginLeft="":U.style.marginRight="",U.style.marginBottom="",U.style.marginTop=""}),r.centeredSlides&&r.cssMode&&(hu(n,"--swiper-centered-offset-before",""),hu(n,"--swiper-centered-offset-after","")),r.cssMode&&(hu(n,"--swiper-slides-offset-before",`${w}px`),hu(n,"--swiper-slides-offset-after",`${T}px`));const O=r.grid&&r.grid.rows>1&&e.grid;O?e.grid.initSlides(f):e.grid&&e.grid.unsetSlides();let H;const G=r.slidesPerView==="auto"&&r.breakpoints&&Object.keys(r.breakpoints).filter(U=>typeof r.breakpoints[U].slidesPerView<"u").length>0;for(let U=0;U<b;U+=1){H=0;const W=f[U];if(!(W&&(O&&e.grid.updateSlide(U,W,f),Ql(W,"display")==="none"))){if(u&&r.slidesPerView==="auto")r.virtual.slidesPerViewAutoSlideSize&&(H=r.virtual.slidesPerViewAutoSlideSize),H&&W&&(r.roundLengths&&(H=Math.floor(H)),W.style[e.getDirectionLabel("width")]=`${H}px`);else if(r.slidesPerView==="auto"){G&&(W.style[e.getDirectionLabel("width")]="");const J=getComputedStyle(W),ee=W.style.transform,ae=W.style.webkitTransform;if(ee&&(W.style.transform="none"),ae&&(W.style.webkitTransform="none"),r.roundLengths)H=e.isHorizontal()?ob(W,"width"):ob(W,"height");else{const Se=t(J,"width"),Le=t(J,"padding-left"),_e=t(J,"padding-right"),se=t(J,"margin-left"),ie=t(J,"margin-right"),fe=J.getPropertyValue("box-sizing");if(fe&&fe==="border-box")H=Se+se+ie;else{const{clientWidth:Qe,offsetWidth:de}=W;H=Se+Le+_e+se+ie+(de-Qe)}}ee&&(W.style.transform=ee),ae&&(W.style.webkitTransform=ae),r.roundLengths&&(H=Math.floor(H))}else H=(N-(r.slidesPerView-1)*D)/r.slidesPerView,r.roundLengths&&(H=Math.floor(H)),W&&(W.style[e.getDirectionLabel("width")]=`${H}px`);W&&(W.swiperSlideSize=H),v.push(H),r.centeredSlides?(R=R+H/2+_/2+D,_===0&&U!==0&&(R=R-N/2-D),U===0&&(R=R-N/2-D),Math.abs(R)<1/1e3&&(R=0),r.roundLengths&&(R=Math.floor(R)),M%r.slidesPerGroup===0&&g.push(R),y.push(R)):(r.roundLengths&&(R=Math.floor(R)),(M-Math.min(e.params.slidesPerGroupSkip,M))%e.params.slidesPerGroup===0&&g.push(R),y.push(R),R=R+H+D),e.virtualSize+=H+D,_=H,M+=1}}if(e.virtualSize=Math.max(e.virtualSize,N)+T,i&&a&&(r.effect==="slide"||r.effect==="coverflow")&&(n.style.width=`${e.virtualSize+D}px`),r.setWrapperSize&&(n.style[e.getDirectionLabel("width")]=`${e.virtualSize+D}px`),O&&e.grid.updateWrapperSize(H,g),!r.centeredSlides){const U=r.slidesPerView!=="auto"&&r.slidesPerView%1!==0,W=r.snapToSlideEdge&&!r.loop&&(r.slidesPerView==="auto"||U);let J=g.length;if(W){let ae;if(r.slidesPerView==="auto"){ae=1;let Se=0;for(let Le=v.length-1;Le>=0&&(Se+=v[Le]+(Le<v.length-1?D:0),Se<=N);Le-=1)ae=v.length-Le}else ae=Math.floor(r.slidesPerView);J=Math.max(b-ae,0)}const ee=[];for(let ae=0;ae<g.length;ae+=1){let Se=g[ae];r.roundLengths&&(Se=Math.floor(Se)),W?ae<=J&&ee.push(Se):g[ae]<=e.virtualSize-N&&ee.push(Se)}g=ee,Math.floor(e.virtualSize-N)-Math.floor(g[g.length-1])>1&&(W||g.push(e.virtualSize-N))}if(u&&r.loop){const U=v[0]+D;if(r.slidesPerGroup>1){const W=Math.ceil((e.virtual.slidesBefore+e.virtual.slidesAfter)/r.slidesPerGroup),J=U*r.slidesPerGroup;for(let ee=0;ee<W;ee+=1)g.push(g[g.length-1]+J)}for(let W=0;W<e.virtual.slidesBefore+e.virtual.slidesAfter;W+=1)r.slidesPerGroup===1&&g.push(g[g.length-1]+U),y.push(y[y.length-1]+U),e.virtualSize+=U}if(g.length===0&&(g=[0]),D!==0){const U=e.isHorizontal()&&i?"marginLeft":e.getDirectionLabel("marginRight");f.filter((W,J)=>!r.cssMode||r.loop?!0:J!==f.length-1).forEach(W=>{W.style[U]=`${D}px`})}if(r.centeredSlides&&r.centeredSlidesBounds){let U=0;v.forEach(J=>{U+=J+(D||0)}),U-=D;const W=U>N?U-N:0;g=g.map(J=>J<=0?-w:J>W?W+T:J)}if(r.centerInsufficientSlides){let U=0;if(v.forEach(W=>{U+=W+(D||0)}),U-=D,U<N){const W=(N-U)/2;g.forEach((J,ee)=>{g[ee]=J-W}),y.forEach((J,ee)=>{y[ee]=J+W})}}if(Object.assign(e,{slides:f,snapGrid:g,slidesGrid:y,slidesSizesGrid:v}),r.centeredSlides&&r.cssMode&&!r.centeredSlidesBounds){hu(n,"--swiper-centered-offset-before",`${-g[0]}px`),hu(n,"--swiper-centered-offset-after",`${e.size/2-v[v.length-1]/2}px`);const U=-e.snapGrid[0],W=-e.slidesGrid[0];e.snapGrid=e.snapGrid.map(J=>J+U),e.slidesGrid=e.slidesGrid.map(J=>J+W)}if(b!==d&&e.emit("slidesLengthChange"),g.length!==C&&(e.params.watchOverflow&&e.checkOverflow(),e.emit("snapGridLengthChange")),y.length!==E&&e.emit("slidesGridLengthChange"),r.watchSlidesProgress&&e.updateSlidesOffset(),e.emit("slidesUpdated"),!u&&!r.cssMode&&(r.effect==="slide"||r.effect==="fade")){const U=`${r.containerModifierClass}backface-hidden`,W=e.el.classList.contains(U);b<=r.maxBackfaceHiddenSlides?W||e.el.classList.add(U):W&&e.el.classList.remove(U)}}function XT(e){const t=this,r=[],n=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=u=>n?t.slides[t.getSlideIndexByData(u)]:t.slides[u];if(t.params.slidesPerView!=="auto"&&t.params.slidesPerView>1)if(t.params.centeredSlides)(t.visibleSlides||[]).forEach(u=>{r.push(u)});else for(i=0;i<Math.ceil(t.params.slidesPerView);i+=1){const u=t.activeIndex+i;if(u>t.slides.length&&!n)break;r.push(a(u))}else r.push(a(t.activeIndex));for(i=0;i<r.length;i+=1)if(typeof r[i]<"u"){const u=r[i].offsetHeight;s=u>s?u:s}(s||s===0)&&(t.wrapperEl.style.height=`${s}px`)}function JT(){const e=this,t=e.slides,r=e.isElement?e.isHorizontal()?e.wrapperEl.offsetLeft:e.wrapperEl.offsetTop:0;for(let n=0;n<t.length;n+=1)t[n].swiperSlideOffset=(e.isHorizontal()?t[n].offsetLeft:t[n].offsetTop)-r-e.cssOverflowAdjustment()}const lb=(e,t,r)=>{t&&!e.classList.contains(r)?e.classList.add(r):!t&&e.classList.contains(r)&&e.classList.remove(r)};function eS(e=this&&this.translate||0){const t=this,r=t.params,{slides:n,rtlTranslate:s,snapGrid:i}=t;if(n.length===0)return;typeof n[0].swiperSlideOffset>"u"&&t.updateSlidesOffset();let a=-e;s&&(a=e),t.visibleSlidesIndexes=[],t.visibleSlides=[];let u=r.spaceBetween;typeof u=="string"&&u.indexOf("%")>=0?u=parseFloat(u.replace("%",""))/100*t.size:typeof u=="string"&&(u=parseFloat(u));for(let d=0;d<n.length;d+=1){const f=n[d];let b=f.swiperSlideOffset;r.cssMode&&r.centeredSlides&&(b-=n[0].swiperSlideOffset);const g=(a+(r.centeredSlides?t.minTranslate():0)-b)/(f.swiperSlideSize+u),y=(a-i[0]+(r.centeredSlides?t.minTranslate():0)-b)/(f.swiperSlideSize+u),v=-(a-b),w=v+t.slidesSizesGrid[d],T=v>=0&&v<=t.size-t.slidesSizesGrid[d],C=v>=0&&v<t.size-1||w>1&&w<=t.size||v<=0&&w>=t.size;C&&(t.visibleSlides.push(f),t.visibleSlidesIndexes.push(d)),lb(f,C,r.slideVisibleClass),lb(f,T,r.slideFullyVisibleClass),f.progress=s?-g:g,f.originalProgress=s?-y:y}}function tS(e){const t=this;if(typeof e>"u"){const b=t.rtlTranslate?-1:1;e=t&&t.translate&&t.translate*b||0}const r=t.params,n=t.maxTranslate()-t.minTranslate();let{progress:s,isBeginning:i,isEnd:a,progressLoop:u}=t;const d=i,f=a;if(n===0)s=0,i=!0,a=!0;else{s=(e-t.minTranslate())/n;const b=Math.abs(e-t.minTranslate())<1,g=Math.abs(e-t.maxTranslate())<1;i=b||s<=0,a=g||s>=1,b&&(s=0),g&&(s=1)}if(r.loop){const b=t.getSlideIndexByData(0),g=t.getSlideIndexByData(t.slides.length-1),y=t.slidesGrid[b],v=t.slidesGrid[g],w=t.slidesGrid[t.slidesGrid.length-1],T=Math.abs(e);T>=y?u=(T-y)/w:u=(T+w-v)/w,u>1&&(u-=1)}Object.assign(t,{progress:s,progressLoop:u,isBeginning:i,isEnd:a}),(r.watchSlidesProgress||r.centeredSlides&&r.autoHeight)&&t.updateSlidesProgress(e),i&&!d&&t.emit("reachBeginning toEdge"),a&&!f&&t.emit("reachEnd toEdge"),(d&&!i||f&&!a)&&t.emit("fromEdge"),t.emit("progress",s)}const Um=(e,t,r)=>{t&&!e.classList.contains(r)?e.classList.add(r):!t&&e.classList.contains(r)&&e.classList.remove(r)};function rS(){const e=this,{slides:t,params:r,slidesEl:n,activeIndex:s}=e,i=e.virtual&&r.virtual.enabled,a=e.grid&&r.grid&&r.grid.rows>1,u=g=>rl(n,`.${r.slideClass}${g}, swiper-slide${g}`)[0];let d,f,b;if(i)if(r.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),d=u(`[data-swiper-slide-index="${g}"]`)}else d=u(`[data-swiper-slide-index="${s}"]`);else a?(d=t.find(g=>g.column===s),b=t.find(g=>g.column===s+1),f=t.find(g=>g.column===s-1)):d=t[s];d&&(a||(b=HT(d,`.${r.slideClass}, swiper-slide`)[0],r.loop&&!b&&(b=t[0]),f=$T(d,`.${r.slideClass}, swiper-slide`)[0],r.loop&&!f===0&&(f=t[t.length-1]))),t.forEach(g=>{Um(g,g===d,r.slideActiveClass),Um(g,g===b,r.slideNextClass),Um(g,g===f,r.slidePrevClass)}),e.emitSlidesClasses()}const Cf=(e,t)=>{if(!e||e.destroyed||!e.params)return;const r=()=>e.isElement?"swiper-slide":`.${e.params.slideClass}`,n=t.closest(r());if(n){let s=n.querySelector(`.${e.params.lazyPreloaderClass}`);!s&&e.isElement&&(n.shadowRoot?s=n.shadowRoot.querySelector(`.${e.params.lazyPreloaderClass}`):requestAnimationFrame(()=>{n.shadowRoot&&(s=n.shadowRoot.querySelector(`.${e.params.lazyPreloaderClass}`),s&&!s.lazyPreloaderManaged&&s.remove())})),s&&!s.lazyPreloaderManaged&&s.remove()}},Gm=(e,t)=>{if(!e.slides[t])return;const r=e.slides[t].querySelector('[loading="lazy"]');r&&r.removeAttribute("loading")},b1=e=>{if(!e||e.destroyed||!e.params)return;let t=e.params.lazyPreloadPrevNext;const r=e.slides.length;if(!r||!t||t<0)return;t=Math.min(t,r);const n=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,u=[a-t];u.push(...Array.from({length:t}).map((d,f)=>a+n+f)),e.slides.forEach((d,f)=>{u.includes(d.column)&&Gm(e,f)});return}const i=s+n-1;if(e.params.rewind||e.params.loop)for(let a=s-t;a<=i+t;a+=1){const u=(a%r+r)%r;(u<s||u>i)&&Gm(e,u)}else for(let a=Math.max(s-t,0);a<=Math.min(i+t,r-1);a+=1)a!==s&&(a>i||a<s)&&Gm(e,a)};function nS(e){const{slidesGrid:t,params:r}=e,n=e.rtlTranslate?e.translate:-e.translate;let s;for(let i=0;i<t.length;i+=1)typeof t[i+1]<"u"?n>=t[i]&&n<t[i+1]-(t[i+1]-t[i])/2?s=i:n>=t[i]&&n<t[i+1]&&(s=i+1):n>=t[i]&&(s=i);return r.normalizeSlideIndex&&(s<0||typeof s>"u")&&(s=0),s}function sS(e){const t=this,r=t.rtlTranslate?t.translate:-t.translate,{snapGrid:n,params:s,activeIndex:i,realIndex:a,snapIndex:u}=t;let d=e,f;const b=v=>{let w=v-t.virtual.slidesBefore;return w<0&&(w=t.virtual.slides.length+w),w>=t.virtual.slides.length&&(w-=t.virtual.slides.length),w};if(typeof d>"u"&&(d=nS(t)),n.indexOf(r)>=0)f=n.indexOf(r);else{const v=Math.min(s.slidesPerGroupSkip,d);f=v+Math.floor((d-v)/s.slidesPerGroup)}if(f>=n.length&&(f=n.length-1),d===i&&!t.params.loop){f!==u&&(t.snapIndex=f,t.emit("snapIndexChange"));return}if(d===i&&t.params.loop&&t.virtual&&t.params.virtual.enabled){t.realIndex=b(d);return}const g=t.grid&&s.grid&&s.grid.rows>1;let y;if(t.virtual&&s.virtual.enabled)s.loop?y=b(d):y=d;else if(g){const v=t.slides.find(T=>T.column===d);let w=parseInt(v.getAttribute("data-swiper-slide-index"),10);Number.isNaN(w)&&(w=Math.max(t.slides.indexOf(v),0)),y=Math.floor(w/s.grid.rows)}else if(t.slides[d]){const v=t.slides[d].getAttribute("data-swiper-slide-index");v?y=parseInt(v,10):y=d}else y=d;Object.assign(t,{previousSnapIndex:u,snapIndex:f,previousRealIndex:a,realIndex:y,previousIndex:i,activeIndex:d}),t.initialized&&b1(t),t.emit("activeIndexChange"),t.emit("snapIndexChange"),(t.initialized||t.params.runCallbacksOnInit)&&(a!==y&&t.emit("realIndexChange"),t.emit("slideChange"))}function iS(e,t){const r=this,n=r.params;let s=e.closest(`.${n.slideClass}, swiper-slide`);!s&&r.isElement&&t&&t.length>1&&t.includes(e)&&[...t.slice(t.indexOf(e)+1,t.length)].forEach(u=>{!s&&u.matches&&u.matches(`.${n.slideClass}, swiper-slide`)&&(s=u)});let i=!1,a;if(s){for(let u=0;u<r.slides.length;u+=1)if(r.slides[u]===s){i=!0,a=u;break}}if(s&&i)r.clickedSlide=s,r.virtual&&r.params.virtual.enabled?r.clickedIndex=parseInt(s.getAttribute("data-swiper-slide-index"),10):r.clickedIndex=a;else{r.clickedSlide=void 0,r.clickedIndex=void 0;return}n.slideToClickedSlide&&r.clickedIndex!==void 0&&r.clickedIndex!==r.activeIndex&&r.slideToClickedSlide()}var oS={updateSize:ZT,updateSlides:KT,updateAutoHeight:XT,updateSlidesOffset:JT,updateSlidesProgress:eS,updateProgress:tS,updateSlidesClasses:rS,updateActiveIndex:sS,updateClickedSlide:iS};function aS(e=this.isHorizontal()?"x":"y"){const t=this,{params:r,rtlTranslate:n,translate:s,wrapperEl:i}=t;if(r.virtualTranslate)return n?-s:s;if(r.cssMode)return s;let a=jT(i,e);return a+=t.cssOverflowAdjustment(),n&&(a=-a),a||0}function lS(e,t){const r=this,{rtlTranslate:n,params:s,wrapperEl:i,progress:a}=r;let u=0,d=0;const f=0;r.isHorizontal()?u=n?-e:e:d=e,s.roundLengths&&(u=Math.floor(u),d=Math.floor(d)),r.previousTranslate=r.translate,r.translate=r.isHorizontal()?u:d,s.cssMode?i[r.isHorizontal()?"scrollLeft":"scrollTop"]=r.isHorizontal()?-u:-d:s.virtualTranslate||(r.isHorizontal()?u-=r.cssOverflowAdjustment():d-=r.cssOverflowAdjustment(),i.style.transform=`translate3d(${u}px, ${d}px, ${f}px)`);let b;const g=r.maxTranslate()-r.minTranslate();g===0?b=0:b=(e-r.minTranslate())/g,b!==a&&r.updateProgress(e),r.emit("setTranslate",r.translate,t)}function cS(){return-this.snapGrid[0]}function uS(){return-this.snapGrid[this.snapGrid.length-1]}function dS(e=0,t=this.params.speed,r=!0,n=!0,s){const i=this,{params:a,wrapperEl:u}=i;if(i.animating&&a.preventInteractionOnTransition)return!1;const d=i.minTranslate(),f=i.maxTranslate();let b;if(n&&e>d?b=d:n&&e<f?b=f:b=e,i.updateProgress(b),a.cssMode){const g=i.isHorizontal();if(t===0)u[g?"scrollLeft":"scrollTop"]=-b;else{if(!i.support.smoothScroll)return x6({swiper:i,targetPosition:-b,side:g?"left":"top"}),!0;u.scrollTo({[g?"left":"top"]:-b,behavior:"smooth"})}return!0}return t===0?(i.setTransition(0),i.setTranslate(b),r&&(i.emit("beforeTransitionStart",t,s),i.emit("transitionEnd"))):(i.setTransition(t),i.setTranslate(b),r&&(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,r&&i.emit("transitionEnd"))}),i.wrapperEl.addEventListener("transitionend",i.onTranslateToWrapperTransitionEnd))),!0}var hS={getTranslate:aS,setTranslate:lS,minTranslate:cS,maxTranslate:uS,translateTo:dS};function fS(e,t){const r=this;r.params.cssMode||(r.wrapperEl.style.transitionDuration=`${e}ms`,r.wrapperEl.style.transitionDelay=e===0?"0ms":""),r.emit("setTransition",e,t)}function A6({swiper:e,runCallbacks:t,direction:r,step:n}){const{activeIndex:s,previousIndex:i}=e;let a=r;a||(s>i?a="next":s<i?a="prev":a="reset"),e.emit(`transition${n}`),t&&a==="reset"?e.emit(`slideResetTransition${n}`):t&&s!==i&&(e.emit(`slideChangeTransition${n}`),a==="next"?e.emit(`slideNextTransition${n}`):e.emit(`slidePrevTransition${n}`))}function pS(e=!0,t){const r=this,{params:n}=r;n.cssMode||(n.autoHeight&&r.updateAutoHeight(),A6({swiper:r,runCallbacks:e,direction:t,step:"Start"}))}function mS(e=!0,t){const r=this,{params:n}=r;r.animating=!1,!n.cssMode&&(r.setTransition(0),A6({swiper:r,runCallbacks:e,direction:t,step:"End"}))}var gS={setTransition:fS,transitionStart:pS,transitionEnd:mS};function bS(e=0,t,r=!0,n,s){typeof e=="string"&&(e=parseInt(e,10));const i=this;let a=e;a<0&&(a=0);const{params:u,snapGrid:d,slidesGrid:f,previousIndex:b,activeIndex:g,rtlTranslate:y,wrapperEl:v,enabled:w}=i;if(!w&&!n&&!s||i.destroyed||i.animating&&u.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>=d.length&&(C=d.length-1);const E=-d[C];if(u.normalizeSlideIndex)for(let O=0;O<f.length;O+=1){const H=-Math.floor(E*100),G=Math.floor(f[O]*100),U=Math.floor(f[O+1]*100);typeof f[O+1]<"u"?H>=G&&H<U-(U-G)/2?a=O:H>=G&&H<U&&(a=O+1):H>=G&&(a=O)}if(i.initialized&&a!==g&&(!i.allowSlideNext&&(y?E>i.translate&&E>i.minTranslate():E<i.translate&&E<i.minTranslate())||!i.allowSlidePrev&&E>i.translate&&E>i.maxTranslate()&&(g||0)!==a))return!1;a!==(b||0)&&r&&i.emit("beforeSlideChangeStart"),i.updateProgress(E);let N;a>g?N="next":a<g?N="prev":N="reset";const D=i.virtual&&i.params.virtual.enabled;if(!(D&&s)&&(y&&-E===i.translate||!y&&E===i.translate))return i.updateActiveIndex(a),u.autoHeight&&i.updateAutoHeight(),i.updateSlidesClasses(),u.effect!=="slide"&&i.setTranslate(E),N!=="reset"&&(i.transitionStart(r,N),i.transitionEnd(r,N)),!1;if(u.cssMode){const O=i.isHorizontal(),H=y?E:-E;if(t===0)D&&(i.wrapperEl.style.scrollSnapType="none",i._immediateVirtual=!0),D&&!i._cssModeVirtualInitialSet&&i.params.initialSlide>0?(i._cssModeVirtualInitialSet=!0,requestAnimationFrame(()=>{v[O?"scrollLeft":"scrollTop"]=H})):v[O?"scrollLeft":"scrollTop"]=H,D&&requestAnimationFrame(()=>{i.wrapperEl.style.scrollSnapType="",i._immediateVirtual=!1});else{if(!i.support.smoothScroll)return x6({swiper:i,targetPosition:H,side:O?"left":"top"}),!0;v.scrollTo({[O?"left":"top"]:H,behavior:"smooth"})}return!0}const M=w6().isSafari;return D&&!s&&M&&i.isElement&&i.virtual.update(!1,!1,a),i.setTransition(t),i.setTranslate(E),i.updateActiveIndex(a),i.updateSlidesClasses(),i.emit("beforeTransitionStart",t,n),i.transitionStart(r,N),t===0?i.transitionEnd(r,N):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(r,N))}),i.wrapperEl.addEventListener("transitionend",i.onSlideToWrapperTransitionEnd)),!0}function xS(e=0,t,r=!0,n){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 u;if(i){const T=a*s.params.grid.rows;u=s.slides.find(C=>C.getAttribute("data-swiper-slide-index")*1===T).column}else u=s.getSlideIndexByData(a);const d=i?Math.ceil(s.slides.length/s.params.grid.rows):s.slides.length,{centeredSlides:f,slidesOffsetBefore:b,slidesOffsetAfter:g}=s.params,y=f||!!b||!!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 w=d-u<v;if(y&&(w=w||u<Math.ceil(v/2)),n&&y&&s.params.slidesPerView!=="auto"&&!i&&(w=!1),w){const T=y?u<s.activeIndex?"prev":"next":u-s.activeIndex-1<s.params.slidesPerView?"next":"prev";s.loopFix({direction:T,slideTo:!0,activeSlideIndex:T==="next"?u+1:u-d+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,r,n)}),s}function yS(e,t=!0,r){const n=this,{enabled:s,params:i,animating:a}=n;if(!s||n.destroyed)return n;typeof e>"u"&&(e=n.params.speed);let u=i.slidesPerGroup;i.slidesPerView==="auto"&&i.slidesPerGroup===1&&i.slidesPerGroupAuto&&(u=Math.max(n.slidesPerViewDynamic("current",!0),1));const d=n.activeIndex<i.slidesPerGroupSkip?1:u,f=n.virtual&&i.virtual.enabled;if(i.loop){if(a&&!f&&i.loopPreventsSliding)return!1;if(n.loopFix({direction:"next"}),n._clientLeft=n.wrapperEl.clientLeft,n.activeIndex===n.slides.length-1&&i.cssMode)return requestAnimationFrame(()=>{n.slideTo(n.activeIndex+d,e,t,r)}),!0}return i.rewind&&n.isEnd?n.slideTo(0,e,t,r):n.slideTo(n.activeIndex+d,e,t,r)}function vS(e,t=!0,r){const n=this,{params:s,snapGrid:i,slidesGrid:a,rtlTranslate:u,enabled:d,animating:f}=n;if(!d||n.destroyed)return n;typeof e>"u"&&(e=n.params.speed);const b=n.virtual&&s.virtual.enabled;if(s.loop){if(f&&!b&&s.loopPreventsSliding)return!1;n.loopFix({direction:"prev"}),n._clientLeft=n.wrapperEl.clientLeft}const g=u?n.translate:-n.translate;function y(N){return N<0?-Math.floor(Math.abs(N)):Math.floor(N)}const v=y(g),w=i.map(N=>y(N)),T=s.freeMode&&s.freeMode.enabled;let C=i[w.indexOf(v)-1];if(typeof C>"u"&&(s.cssMode||T)){let N;i.forEach((D,R)=>{v>=D&&(N=R)}),typeof N<"u"&&(C=T?i[N]:i[N>0?N-1:N])}let E=0;if(typeof C<"u"&&(E=a.indexOf(C),E<0&&(E=n.activeIndex-1),s.slidesPerView==="auto"&&s.slidesPerGroup===1&&s.slidesPerGroupAuto&&(E=E-n.slidesPerViewDynamic("previous",!0)+1,E=Math.max(E,0))),s.rewind&&n.isBeginning){const N=n.params.virtual&&n.params.virtual.enabled&&n.virtual?n.virtual.slides.length-1:n.slides.length-1;return n.slideTo(N,e,t,r)}else if(s.loop&&n.activeIndex===0&&s.cssMode)return requestAnimationFrame(()=>{n.slideTo(E,e,t,r)}),!0;return n.slideTo(E,e,t,r)}function wS(e,t=!0,r){const n=this;if(!n.destroyed)return typeof e>"u"&&(e=n.params.speed),n.slideTo(n.activeIndex,e,t,r)}function AS(e,t=!0,r,n=.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),u=a+Math.floor((i-a)/s.params.slidesPerGroup),d=s.rtlTranslate?s.translate:-s.translate;if(d>=s.snapGrid[u]){const f=s.snapGrid[u],b=s.snapGrid[u+1];d-f>(b-f)*n&&(i+=s.params.slidesPerGroup)}else{const f=s.snapGrid[u-1],b=s.snapGrid[u];d-f<=(b-f)*n&&(i-=s.params.slidesPerGroup)}return i=Math.max(i,0),i=Math.min(i,s.slidesGrid.length-1),s.slideTo(i,e,t,r)}function TS(){const e=this;if(e.destroyed)return;const{params:t,slidesEl:r}=e,n=t.slidesPerView==="auto"?e.slidesPerViewDynamic():t.slidesPerView;let s=e.getSlideIndexWhenGrid(e.clickedIndex),i;const a=e.isElement?"swiper-slide":`.${t.slideClass}`,u=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>(u?(e.slides.length-n)/2-(e.params.grid.rows-1):e.slides.length-n)?(e.loopFix(),s=e.getSlideIndex(rl(r,`${a}[data-swiper-slide-index="${i}"]`)[0]),b6(()=>{e.slideTo(s)})):e.slideTo(s)}else e.slideTo(s)}var SS={slideTo:bS,slideToLoop:xS,slideNext:yS,slidePrev:vS,slideReset:wS,slideToClosest:AS,slideToClickedSlide:TS};function CS(e,t){const r=this,{params:n,slidesEl:s}=r;if(!n.loop||r.virtual&&r.params.virtual.enabled)return;const i=()=>{rl(s,`.${n.slideClass}, swiper-slide`).forEach((w,T)=>{w.setAttribute("data-swiper-slide-index",T)})},a=()=>{const v=rl(s,`.${n.slideBlankClass}`);v.forEach(w=>{w.remove()}),v.length>0&&(r.recalcSlides(),r.updateSlides())},u=r.grid&&n.grid&&n.grid.rows>1;n.loopAddBlankSlides&&(n.slidesPerGroup>1||u)&&a();const d=n.slidesPerGroup*(u?n.grid.rows:1),f=r.slides.length%d!==0,b=u&&r.slides.length%n.grid.rows!==0,g=v=>{for(let w=0;w<v;w+=1){const T=r.isElement?g1("swiper-slide",[n.slideBlankClass]):g1("div",[n.slideClass,n.slideBlankClass]);r.slidesEl.append(T)}};if(f){if(n.loopAddBlankSlides){const v=d-r.slides.length%d;g(v),r.recalcSlides(),r.updateSlides()}else Vf("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(b){if(n.loopAddBlankSlides){const v=n.grid.rows-r.slides.length%n.grid.rows;g(v),r.recalcSlides(),r.updateSlides()}else Vf("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=n.centeredSlides||!!n.slidesOffsetBefore||!!n.slidesOffsetAfter;r.loopFix({slideRealIndex:e,direction:y?void 0:"next",initial:t})}function _S({slideRealIndex:e,slideTo:t=!0,direction:r,setTranslate:n,activeSlideIndex:s,initial:i,byController:a,byMousewheel:u}={}){const d=this;if(!d.params.loop)return;d.emit("beforeLoopFix");const{slides:f,allowSlidePrev:b,allowSlideNext:g,slidesEl:y,params:v}=d,{centeredSlides:w,slidesOffsetBefore:T,slidesOffsetAfter:C,initialSlide:E}=v,N=w||!!T||!!C;if(d.allowSlidePrev=!0,d.allowSlideNext=!0,d.virtual&&v.virtual.enabled){t&&(!N&&d.snapIndex===0?d.slideTo(d.virtual.slides.length,0,!1,!0):N&&d.snapIndex<v.slidesPerView?d.slideTo(d.virtual.slides.length+d.snapIndex,0,!1,!0):d.snapIndex===d.snapGrid.length-1&&d.slideTo(d.virtual.slidesBefore,0,!1,!0)),d.allowSlidePrev=b,d.allowSlideNext=g,d.emit("loopFix");return}let D=v.slidesPerView;D==="auto"?D=d.slidesPerViewDynamic():(D=Math.ceil(parseFloat(v.slidesPerView,10)),N&&D%2===0&&(D=D+1));const R=v.slidesPerGroupAuto?D:v.slidesPerGroup;let _=N?Math.max(R,Math.ceil(D/2)):R;_%R!==0&&(_+=R-_%R),_+=v.loopAdditionalSlides,d.loopedSlides=_;const M=d.grid&&v.grid&&v.grid.rows>1;f.length<D+_||d.params.effect==="cards"&&f.length<D+_*2?Vf("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"):M&&v.grid.fill==="row"&&Vf("Swiper Loop Warning: Loop mode is not compatible with grid.fill = `row`");const O=[],H=[],G=M?Math.ceil(f.length/v.grid.rows):f.length,U=i&&G-E<D&&!N;let W=U?E:d.activeIndex;typeof s>"u"?s=d.getSlideIndex(f.find(se=>se.classList.contains(v.slideActiveClass))):W=s;const J=r==="next"||!r,ee=r==="prev"||!r;let ae=0,Se=0;const _e=(M?f[s].column:s)+(N&&typeof n>"u"?-D/2+.5:0);if(_e<_){ae=Math.max(_-_e,R);for(let se=0;se<_-_e;se+=1){const ie=se-Math.floor(se/G)*G;if(M){const fe=G-ie-1;for(let Qe=f.length-1;Qe>=0;Qe-=1)f[Qe].column===fe&&O.push(Qe)}else O.push(G-ie-1)}}else if(_e+D>G-_){Se=Math.max(_e-(G-_*2),R),U&&(Se=Math.max(Se,D-G+E+1));for(let se=0;se<Se;se+=1){const ie=se-Math.floor(se/G)*G;M?f.forEach((fe,Qe)=>{fe.column===ie&&H.push(Qe)}):H.push(ie)}}if(d.__preventObserver__=!0,requestAnimationFrame(()=>{d.__preventObserver__=!1}),d.params.effect==="cards"&&f.length<D+_*2&&(H.includes(s)&&H.splice(H.indexOf(s),1),O.includes(s)&&O.splice(O.indexOf(s),1)),ee&&O.forEach(se=>{f[se].swiperLoopMoveDOM=!0,y.prepend(f[se]),f[se].swiperLoopMoveDOM=!1}),J&&H.forEach(se=>{f[se].swiperLoopMoveDOM=!0,y.append(f[se]),f[se].swiperLoopMoveDOM=!1}),d.recalcSlides(),v.slidesPerView==="auto"?d.updateSlides():M&&(O.length>0&&ee||H.length>0&&J)&&d.slides.forEach((se,ie)=>{d.grid.updateSlide(ie,se,d.slides)}),v.watchSlidesProgress&&d.updateSlidesOffset(),t){if(O.length>0&&ee){if(typeof e>"u"){const se=d.slidesGrid[W],fe=d.slidesGrid[W+ae]-se;u?d.setTranslate(d.translate-fe):(d.slideTo(W+Math.ceil(ae),0,!1,!0),n&&(d.touchEventsData.startTranslate=d.touchEventsData.startTranslate-fe,d.touchEventsData.currentTranslate=d.touchEventsData.currentTranslate-fe))}else if(n){const se=M?O.length/v.grid.rows:O.length;d.slideTo(d.activeIndex+se,0,!1,!0),d.touchEventsData.currentTranslate=d.translate}}else if(H.length>0&&J)if(typeof e>"u"){const se=d.slidesGrid[W],fe=d.slidesGrid[W-Se]-se;u?d.setTranslate(d.translate-fe):(d.slideTo(W-Se,0,!1,!0),n&&(d.touchEventsData.startTranslate=d.touchEventsData.startTranslate-fe,d.touchEventsData.currentTranslate=d.touchEventsData.currentTranslate-fe))}else{const se=M?H.length/v.grid.rows:H.length;d.slideTo(d.activeIndex-se,0,!1,!0)}}if(d.allowSlidePrev=b,d.allowSlideNext=g,d.controller&&d.controller.control&&!a){const se={slideRealIndex:e,direction:r,setTranslate:n,activeSlideIndex:s,byController:!0};Array.isArray(d.controller.control)?d.controller.control.forEach(ie=>{!ie.destroyed&&ie.params.loop&&ie.loopFix({...se,slideTo:ie.params.slidesPerView===v.slidesPerView?t:!1})}):d.controller.control instanceof d.constructor&&d.controller.control.params.loop&&d.controller.control.loopFix({...se,slideTo:d.controller.control.params.slidesPerView===v.slidesPerView?t:!1})}d.emit("loopFix")}function LS(){const e=this,{params:t,slidesEl:r}=e;if(!t.loop||!r||e.virtual&&e.params.virtual.enabled)return;e.recalcSlides();const n=[];e.slides.forEach(s=>{const i=typeof s.swiperSlideIndex>"u"?s.getAttribute("data-swiper-slide-index")*1:s.swiperSlideIndex;n[i]=s}),e.slides.forEach(s=>{s.removeAttribute("data-swiper-slide-index")}),n.forEach(s=>{r.append(s)}),e.recalcSlides(),e.slideTo(e.realIndex,0)}var kS={loopCreate:CS,loopFix:_S,loopDestroy:LS};function ES(e){const t=this;if(!t.params.simulateTouch||t.params.watchOverflow&&t.isLocked||t.params.cssMode)return;const r=t.params.touchEventsTarget==="container"?t.el:t.wrapperEl;t.isElement&&(t.__preventObserver__=!0),r.style.cursor="move",r.style.cursor=e?"grabbing":"grab",t.isElement&&requestAnimationFrame(()=>{t.__preventObserver__=!1})}function IS(){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 MS={setGrabCursor:ES,unsetGrabCursor:IS};function RS(e,t=this){function r(n){if(!n||n===Bc()||n===qi())return null;n.assignedSlot&&(n=n.assignedSlot);const s=n.closest(e);return!s&&!n.getRootNode?null:s||r(n.getRootNode().host)}return r(t)}function cb(e,t,r){const n=qi(),{params:s}=e,i=s.edgeSwipeDetection,a=s.edgeSwipeThreshold;return i&&(r<=a||r>=n.innerWidth-a)?i==="prevent"?(t.preventDefault(),!0):!1:!0}function NS(e){const t=this;if(t.destroyed)return;const r=Bc();let n=e;n.originalEvent&&(n=n.originalEvent);const s=t.touchEventsData;if(n.type==="pointerdown"){if(s.pointerId!==null&&s.pointerId!==n.pointerId)return;s.pointerId=n.pointerId}else n.type==="touchstart"&&n.targetTouches.length===1&&(s.touchId=n.targetTouches[0].identifier);if(n.type==="touchstart"){cb(t,n,n.targetTouches[0].pageX);return}const{params:i,touches:a,enabled:u}=t;if(!u||!i.simulateTouch&&n.pointerType==="mouse"||t.animating&&i.preventInteractionOnTransition)return;!t.animating&&i.cssMode&&i.loop&&t.loopFix();let d=n.target;if(i.touchEventsTarget==="wrapper"&&!OT(d,t.wrapperEl)||"which"in n&&n.which===3||"button"in n&&n.button>0||s.isTouched&&s.isMoved)return;const f=!!i.noSwipingClass&&i.noSwipingClass!=="",b=n.composedPath?n.composedPath():n.path;f&&n.target&&n.target.shadowRoot&&b&&(d=b[0]);const g=i.noSwipingSelector?i.noSwipingSelector:`.${i.noSwipingClass}`,y=!!(n.target&&n.target.shadowRoot);if(i.noSwiping&&(y?RS(g,d):d.closest(g))){t.allowClick=!0;return}if(i.swipeHandler&&!d.closest(i.swipeHandler))return;a.currentX=n.pageX,a.currentY=n.pageY;const v=a.currentX,w=a.currentY;if(!cb(t,n,v))return;Object.assign(s,{isTouched:!0,isMoved:!1,allowTouchCallbacks:!0,isScrolling:void 0,startMoving:void 0}),a.startX=v,a.startY=w,s.touchStartTime=Wf(),t.allowClick=!0,t.updateSize(),t.swipeDirection=void 0,i.threshold>0&&(s.allowThresholdMove=!1);let T=!0;d.matches(s.focusableElements)&&(T=!1,d.nodeName==="SELECT"&&(s.isTouched=!1)),r.activeElement&&r.activeElement.matches(s.focusableElements)&&r.activeElement!==d&&(n.pointerType==="mouse"||n.pointerType!=="mouse"&&!d.matches(s.focusableElements))&&r.activeElement.blur();const C=T&&t.allowTouchMove&&i.touchStartPreventDefault;(i.touchStartForcePreventDefault||C)&&!d.isContentEditable&&n.preventDefault(),i.freeMode&&i.freeMode.enabled&&t.freeMode&&t.animating&&!i.cssMode&&t.freeMode.onTouchStart(),t.emit("touchStart",n)}function DS(e){const t=Bc(),r=this;if(r.destroyed)return;const n=r.touchEventsData,{params:s,touches:i,rtlTranslate:a,enabled:u}=r;if(!u||!s.simulateTouch&&e.pointerType==="mouse")return;let d=e;if(d.originalEvent&&(d=d.originalEvent),d.type==="pointermove"&&(n.touchId!==null||d.pointerId!==n.pointerId))return;let f;if(d.type==="touchmove"){if(f=[...d.changedTouches].find(_=>_.identifier===n.touchId),!f||f.identifier!==n.touchId)return}else f=d;if(!n.isTouched){n.startMoving&&n.isScrolling&&r.emit("touchMoveOpposite",d);return}const b=f.pageX,g=f.pageY;if(d.preventedByNestedSwiper){i.startX=b,i.startY=g;return}if(!r.allowTouchMove){d.target.matches(n.focusableElements)||(r.allowClick=!1),n.isTouched&&(Object.assign(i,{startX:b,startY:g,currentX:b,currentY:g}),n.touchStartTime=Wf());return}if(s.touchReleaseOnEdges&&!s.loop)if(r.isVertical()){if(g<i.startY&&r.translate<=r.maxTranslate()||g>i.startY&&r.translate>=r.minTranslate()){n.isTouched=!1,n.isMoved=!1;return}}else{if(a&&(b>i.startX&&-r.translate<=r.maxTranslate()||b<i.startX&&-r.translate>=r.minTranslate()))return;if(!a&&(b<i.startX&&r.translate<=r.maxTranslate()||b>i.startX&&r.translate>=r.minTranslate()))return}if(t.activeElement&&t.activeElement.matches(n.focusableElements)&&t.activeElement!==d.target&&d.pointerType!=="mouse"&&t.activeElement.blur(),t.activeElement&&d.target===t.activeElement&&d.target.matches(n.focusableElements)){n.isMoved=!0,r.allowClick=!1;return}n.allowTouchCallbacks&&r.emit("touchMove",d),i.previousX=i.currentX,i.previousY=i.currentY,i.currentX=b,i.currentY=g;const y=i.currentX-i.startX,v=i.currentY-i.startY;if(r.params.threshold&&Math.sqrt(y**2+v**2)<r.params.threshold)return;if(typeof n.isScrolling>"u"){let _;r.isHorizontal()&&i.currentY===i.startY||r.isVertical()&&i.currentX===i.startX?n.isScrolling=!1:y*y+v*v>=25&&(_=Math.atan2(Math.abs(v),Math.abs(y))*180/Math.PI,n.isScrolling=r.isHorizontal()?_>s.touchAngle:90-_>s.touchAngle)}if(n.isScrolling&&r.emit("touchMoveOpposite",d),typeof n.startMoving>"u"&&(i.currentX!==i.startX||i.currentY!==i.startY)&&(n.startMoving=!0),n.isScrolling||d.type==="touchmove"&&n.preventTouchMoveFromPointerMove){n.isTouched=!1;return}if(!n.startMoving)return;r.allowClick=!1,!s.cssMode&&d.cancelable&&d.preventDefault(),s.touchMoveStopPropagation&&!s.nested&&d.stopPropagation();let w=r.isHorizontal()?y:v,T=r.isHorizontal()?i.currentX-i.previousX:i.currentY-i.previousY;s.oneWayMovement&&(w=Math.abs(w)*(a?1:-1),T=Math.abs(T)*(a?1:-1)),i.diff=w,w*=s.touchRatio,a&&(w=-w,T=-T);const C=r.touchesDirection;r.swipeDirection=w>0?"prev":"next",r.touchesDirection=T>0?"prev":"next";const E=r.params.loop&&!s.cssMode,N=r.touchesDirection==="next"&&r.allowSlideNext||r.touchesDirection==="prev"&&r.allowSlidePrev;if(!n.isMoved){if(E&&N&&r.loopFix({direction:r.swipeDirection}),n.startTranslate=r.getTranslate(),r.setTransition(0),r.animating){const _=new window.CustomEvent("transitionend",{bubbles:!0,cancelable:!0,detail:{bySwiperTouchMove:!0}});r.wrapperEl.dispatchEvent(_)}n.allowMomentumBounce=!1,s.grabCursor&&(r.allowSlideNext===!0||r.allowSlidePrev===!0)&&r.setGrabCursor(!0),r.emit("sliderFirstMove",d)}if(new Date().getTime(),s._loopSwapReset!==!1&&n.isMoved&&n.allowThresholdMove&&C!==r.touchesDirection&&E&&N&&Math.abs(w)>=1){Object.assign(i,{startX:b,startY:g,currentX:b,currentY:g,startTranslate:n.currentTranslate}),n.loopSwapReset=!0,n.startTranslate=n.currentTranslate;return}r.emit("sliderMove",d),n.isMoved=!0,n.currentTranslate=w+n.startTranslate;let D=!0,R=s.resistanceRatio;if(s.touchReleaseOnEdges&&(R=0),w>0?(E&&N&&n.allowThresholdMove&&n.currentTranslate>(s.centeredSlides?r.minTranslate()-r.slidesSizesGrid[r.activeIndex+1]-(s.slidesPerView!=="auto"&&r.slides.length-s.slidesPerView>=2?r.slidesSizesGrid[r.activeIndex+1]+r.params.spaceBetween:0)-r.params.spaceBetween:r.minTranslate())&&r.loopFix({direction:"prev",setTranslate:!0,activeSlideIndex:0}),n.currentTranslate>r.minTranslate()&&(D=!1,s.resistance&&(n.currentTranslate=r.minTranslate()-1+(-r.minTranslate()+n.startTranslate+w)**R))):w<0&&(E&&N&&n.allowThresholdMove&&n.currentTranslate<(s.centeredSlides?r.maxTranslate()+r.slidesSizesGrid[r.slidesSizesGrid.length-1]+r.params.spaceBetween+(s.slidesPerView!=="auto"&&r.slides.length-s.slidesPerView>=2?r.slidesSizesGrid[r.slidesSizesGrid.length-1]+r.params.spaceBetween:0):r.maxTranslate())&&r.loopFix({direction:"next",setTranslate:!0,activeSlideIndex:r.slides.length-(s.slidesPerView==="auto"?r.slidesPerViewDynamic():Math.ceil(parseFloat(s.slidesPerView,10)))}),n.currentTranslate<r.maxTranslate()&&(D=!1,s.resistance&&(n.currentTranslate=r.maxTranslate()+1-(r.maxTranslate()-n.startTranslate-w)**R))),D&&(d.preventedByNestedSwiper=!0),!r.allowSlideNext&&r.swipeDirection==="next"&&n.currentTranslate<n.startTranslate&&(n.currentTranslate=n.startTranslate),!r.allowSlidePrev&&r.swipeDirection==="prev"&&n.currentTranslate>n.startTranslate&&(n.currentTranslate=n.startTranslate),!r.allowSlidePrev&&!r.allowSlideNext&&(n.currentTranslate=n.startTranslate),s.threshold>0)if(Math.abs(w)>s.threshold||n.allowThresholdMove){if(!n.allowThresholdMove){n.allowThresholdMove=!0,i.startX=i.currentX,i.startY=i.currentY,n.currentTranslate=n.startTranslate,i.diff=r.isHorizontal()?i.currentX-i.startX:i.currentY-i.startY;return}}else{n.currentTranslate=n.startTranslate;return}!s.followFinger||s.cssMode||((s.freeMode&&s.freeMode.enabled&&r.freeMode||s.watchSlidesProgress)&&(r.updateActiveIndex(),r.updateSlidesClasses()),s.freeMode&&s.freeMode.enabled&&r.freeMode&&r.freeMode.onTouchMove(),r.updateProgress(n.currentTranslate),r.setTranslate(n.currentTranslate))}function BS(e){const t=this;if(t.destroyed)return;const r=t.touchEventsData;let n=e;n.originalEvent&&(n=n.originalEvent);let s;if(n.type==="touchend"||n.type==="touchcancel"){if(s=[...n.changedTouches].find(_=>_.identifier===r.touchId),!s||s.identifier!==r.touchId)return}else{if(r.touchId!==null||n.pointerId!==r.pointerId)return;s=n}if(["pointercancel","pointerout","pointerleave","contextmenu"].includes(n.type)&&!(["pointercancel","contextmenu"].includes(n.type)&&(t.browser.isSafari||t.browser.isWebView)))return;r.pointerId=null,r.touchId=null;const{params:a,touches:u,rtlTranslate:d,slidesGrid:f,enabled:b}=t;if(!b||!a.simulateTouch&&n.pointerType==="mouse")return;if(r.allowTouchCallbacks&&t.emit("touchEnd",n),r.allowTouchCallbacks=!1,!r.isTouched){r.isMoved&&a.grabCursor&&t.setGrabCursor(!1),r.isMoved=!1,r.startMoving=!1;return}a.grabCursor&&r.isMoved&&r.isTouched&&(t.allowSlideNext===!0||t.allowSlidePrev===!0)&&t.setGrabCursor(!1);const g=Wf(),y=g-r.touchStartTime;if(t.allowClick){const _=n.path||n.composedPath&&n.composedPath();t.updateClickedSlide(_&&_[0]||n.target,_),t.emit("tap click",n),y<300&&g-r.lastClickTime<300&&t.emit("doubleTap doubleClick",n)}if(r.lastClickTime=Wf(),b6(()=>{t.destroyed||(t.allowClick=!0)}),!r.isTouched||!r.isMoved||!t.swipeDirection||u.diff===0&&!r.loopSwapReset||r.currentTranslate===r.startTranslate&&!r.loopSwapReset){r.isTouched=!1,r.isMoved=!1,r.startMoving=!1;return}r.isTouched=!1,r.isMoved=!1,r.startMoving=!1;let v;if(a.followFinger?v=d?t.translate:-t.translate:v=-r.currentTranslate,a.cssMode)return;if(a.freeMode&&a.freeMode.enabled){t.freeMode.onTouchEnd({currentPos:v});return}const w=v>=-t.maxTranslate()&&!t.params.loop;let T=0,C=t.slidesSizesGrid[0];for(let _=0;_<f.length;_+=_<a.slidesPerGroupSkip?1:a.slidesPerGroup){const M=_<a.slidesPerGroupSkip-1?1:a.slidesPerGroup;typeof f[_+M]<"u"?(w||v>=f[_]&&v<f[_+M])&&(T=_,C=f[_+M]-f[_]):(w||v>=f[_])&&(T=_,C=f[f.length-1]-f[f.length-2])}let E=null,N=null;a.rewind&&(t.isBeginning?N=a.virtual&&a.virtual.enabled&&t.virtual?t.virtual.slides.length-1:t.slides.length-1:t.isEnd&&(E=0));const D=(v-f[T])/C,R=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?E:T+R):t.slideTo(T)),t.swipeDirection==="prev"&&(D>1-a.longSwipesRatio?t.slideTo(T+R):N!==null&&D<0&&Math.abs(D)>a.longSwipesRatio?t.slideTo(N):t.slideTo(T))}else{if(!a.shortSwipes){t.slideTo(t.activeIndex);return}t.navigation&&(n.target===t.navigation.nextEl||n.target===t.navigation.prevEl)?n.target===t.navigation.nextEl?t.slideTo(T+R):t.slideTo(T):(t.swipeDirection==="next"&&t.slideTo(E!==null?E:T+R),t.swipeDirection==="prev"&&t.slideTo(N!==null?N:T))}}function ub(){const e=this,{params:t,el:r}=e;if(r&&r.offsetWidth===0)return;t.breakpoints&&e.setBreakpoint();const{allowSlideNext:n,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 u=a&&t.loop;if((t.slidesPerView==="auto"||t.slidesPerView>1)&&e.isEnd&&!e.isBeginning&&!e.params.centeredSlides&&!u){const d=a?e.virtual.slides:e.slides;e.slideTo(d.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=n,e.params.watchOverflow&&i!==e.snapGrid&&e.checkOverflow()}function PS(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 jS(){const e=this;if(e.destroyed)return;const{wrapperEl:t,rtlTranslate:r,enabled:n}=e;if(!n)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(r?-e.translate:e.translate),e.emit("setTranslate",e.translate,!1)}function QS(e){const t=this;t.destroyed||(Cf(t,e.target),!(t.params.cssMode||t.params.slidesPerView!=="auto"&&!t.params.autoHeight)&&t.update())}function FS(){const e=this;e.destroyed||e.documentTouchHandlerProceeded||(e.documentTouchHandlerProceeded=!0,e.params.touchReleaseOnEdges&&(e.el.style.touchAction="auto"))}const T6=(e,t)=>{const r=Bc(),{params:n,el:s,wrapperEl:i,device:a}=e,u=!!n.nested,d=t==="on"?"addEventListener":"removeEventListener",f=t;!s||typeof s=="string"||(r[d]("touchstart",e.onDocumentTouchStart,{passive:!1,capture:u}),s[d]("touchstart",e.onTouchStart,{passive:!1}),s[d]("pointerdown",e.onTouchStart,{passive:!1}),r[d]("touchmove",e.onTouchMove,{passive:!1,capture:u}),r[d]("pointermove",e.onTouchMove,{passive:!1,capture:u}),r[d]("touchend",e.onTouchEnd,{passive:!0}),r[d]("pointerup",e.onTouchEnd,{passive:!0}),r[d]("pointercancel",e.onTouchEnd,{passive:!0}),r[d]("touchcancel",e.onTouchEnd,{passive:!0}),r[d]("pointerout",e.onTouchEnd,{passive:!0}),r[d]("pointerleave",e.onTouchEnd,{passive:!0}),r[d]("contextmenu",e.onTouchEnd,{passive:!0}),(n.preventClicks||n.preventClicksPropagation)&&s[d]("click",e.onClick,!0),n.cssMode&&i[d]("scroll",e.onScroll),n.updateOnWindowResize?e[f](a.ios||a.android?"resize orientationchange observerUpdate":"resize observerUpdate",ub,!0):e[f]("observerUpdate",ub,!0),s[d]("load",e.onLoad,{capture:!0}))};function OS(){const e=this,{params:t}=e;e.onTouchStart=NS.bind(e),e.onTouchMove=DS.bind(e),e.onTouchEnd=BS.bind(e),e.onDocumentTouchStart=FS.bind(e),t.cssMode&&(e.onScroll=jS.bind(e)),e.onClick=PS.bind(e),e.onLoad=QS.bind(e),T6(e,"on")}function $S(){T6(this,"off")}var HS={attachEvents:OS,detachEvents:$S};const db=(e,t)=>e.grid&&t.grid&&t.grid.rows>1;function US(){const e=this,{realIndex:t,initialized:r,params:n,el:s}=e,i=n.breakpoints;if(!i||i&&Object.keys(i).length===0)return;const a=Bc(),u=n.breakpointsBase==="window"||!n.breakpointsBase?n.breakpointsBase:"container",d=["window","container"].includes(n.breakpointsBase)||!n.breakpointsBase?e.el:a.querySelector(n.breakpointsBase),f=e.getBreakpoint(i,u,d);if(!f||e.currentBreakpoint===f)return;const g=(f in i?i[f]:void 0)||e.originalParams,y=db(e,n),v=db(e,g),w=e.params.grabCursor,T=g.grabCursor,C=n.enabled;y&&!v?(s.classList.remove(`${n.containerModifierClass}grid`,`${n.containerModifierClass}grid-column`),e.emitContainerClasses()):!y&&v&&(s.classList.add(`${n.containerModifierClass}grid`),(g.grid.fill&&g.grid.fill==="column"||!g.grid.fill&&n.grid.fill==="column")&&s.classList.add(`${n.containerModifierClass}grid-column`),e.emitContainerClasses()),w&&!T?e.unsetGrabCursor():!w&&T&&e.setGrabCursor(),["navigation","pagination","scrollbar"].forEach(M=>{if(typeof g[M]>"u")return;const O=n[M]&&n[M].enabled,H=g[M]&&g[M].enabled;O&&!H&&e[M].disable(),!O&&H&&e[M].enable()});const E=g.direction&&g.direction!==n.direction,N=n.loop&&(g.slidesPerView!==n.slidesPerView||E),D=n.loop;E&&r&&e.changeDirection(),So(e.params,g);const R=e.params.enabled,_=e.params.loop;Object.assign(e,{allowTouchMove:e.params.allowTouchMove,allowSlideNext:e.params.allowSlideNext,allowSlidePrev:e.params.allowSlidePrev}),C&&!R?e.disable():!C&&R&&e.enable(),e.currentBreakpoint=f,e.emit("_beforeBreakpoint",g),r&&(N?(e.loopDestroy(),e.loopCreate(t),e.updateSlides()):!D&&_?(e.loopCreate(t),e.updateSlides()):D&&!_&&e.loopDestroy()),e.emit("breakpoint",g)}function GS(e,t="window",r){if(!e||t==="container"&&!r)return;let n=!1;const s=qi(),i=t==="window"?s.innerHeight:r.clientHeight,a=Object.keys(e).map(u=>{if(typeof u=="string"&&u.indexOf("@")===0){const d=parseFloat(u.substr(1));return{value:i*d,point:u}}return{value:u,point:u}});a.sort((u,d)=>parseInt(u.value,10)-parseInt(d.value,10));for(let u=0;u<a.length;u+=1){const{point:d,value:f}=a[u];t==="window"?s.matchMedia(`(min-width: ${f}px)`).matches&&(n=d):f<=r.clientWidth&&(n=d)}return n||"max"}var zS={setBreakpoint:US,getBreakpoint:GS};function WS(e,t){const r=[];return e.forEach(n=>{typeof n=="object"?Object.keys(n).forEach(s=>{n[s]&&r.push(t+s)}):typeof n=="string"&&r.push(t+n)}),r}function VS(){const e=this,{classNames:t,params:r,rtl:n,el:s,device:i}=e,a=WS(["initialized",r.direction,{"free-mode":e.params.freeMode&&r.freeMode.enabled},{autoheight:r.autoHeight},{rtl:n},{grid:r.grid&&r.grid.rows>1},{"grid-column":r.grid&&r.grid.rows>1&&r.grid.fill==="column"},{android:i.android},{ios:i.ios},{"css-mode":r.cssMode},{centered:r.cssMode&&r.centeredSlides},{"watch-progress":r.watchSlidesProgress}],r.containerModifierClass);t.push(...a),s.classList.add(...t),e.emitContainerClasses()}function qS(){const e=this,{el:t,classNames:r}=e;!t||typeof t=="string"||(t.classList.remove(...r),e.emitContainerClasses())}var YS={addClasses:VS,removeClasses:qS};function ZS(){const e=this,{isLocked:t,params:r}=e,{slidesOffsetBefore:n}=r;if(n){const s=e.slides.length-1,i=e.slidesGrid[s]+e.slidesSizesGrid[s]+n*2;e.isLocked=e.size>i}else e.isLocked=e.snapGrid.length===1;r.allowSlideNext===!0&&(e.allowSlideNext=!e.isLocked),r.allowSlidePrev===!0&&(e.allowSlidePrev=!e.isLocked),t&&t!==e.isLocked&&(e.isEnd=!1),t!==e.isLocked&&e.emit(e.isLocked?"lock":"unlock")}var KS={checkOverflow:ZS},x1={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 XS(e,t){return function(n={}){const s=Object.keys(n)[0],i=n[s];if(typeof i!="object"||i===null){So(t,n);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)){So(t,n);return}typeof e[s]=="object"&&!("enabled"in e[s])&&(e[s].enabled=!0),e[s]||(e[s]={enabled:!1}),So(t,n)}}const zm={eventsEmitter:YT,update:oS,translate:hS,transition:gS,slide:SS,loop:kS,grabCursor:MS,events:HS,breakpoints:zS,checkOverflow:KS,classes:YS},Wm={};let _2=class tl{constructor(...t){let r,n;t.length===1&&t[0].constructor&&Object.prototype.toString.call(t[0]).slice(8,-1)==="Object"?n=t[0]:[r,n]=t,n||(n={}),n=So({},n),r&&!n.el&&(n.el=r);const s=Bc();if(n.el&&typeof n.el=="string"&&s.querySelectorAll(n.el).length>1){const d=[];return s.querySelectorAll(n.el).forEach(f=>{const b=So({},n,{el:f});d.push(new tl(b))}),d}const i=this;i.__swiper__=!0,i.support=y6(),i.device=v6({userAgent:n.userAgent}),i.browser=w6(),i.eventsListeners={},i.eventsAnyListeners=[],i.modules=[...i.__modules__],n.modules&&Array.isArray(n.modules)&&n.modules.forEach(d=>{typeof d=="function"&&i.modules.indexOf(d)<0&&i.modules.push(d)});const a={};i.modules.forEach(d=>{d({params:n,swiper:i,extendParams:XS(n,a),on:i.on.bind(i),once:i.once.bind(i),off:i.off.bind(i),emit:i.emit.bind(i)})});const u=So({},x1,a);return i.params=So({},u,Wm,n),i.originalParams=So({},i.params),i.passedParams=So({},n),i.params&&i.params.on&&Object.keys(i.params.on).forEach(d=>{i.on(d,i.params.on[d])}),i.params&&i.params.onAny&&i.onAny(i.params.onAny),Object.assign(i,{enabled:i.params.enabled,el:r,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:r,params:n}=this,s=rl(r,`.${n.slideClass}, swiper-slide`),i=ib(s[0]);return ib(t)-i}getSlideIndexByData(t){return this.getSlideIndex(this.slides.find(r=>r.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:r,params:n}=t;t.slides=rl(r,`.${n.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,r){const n=this;t=Math.min(Math.max(t,0),1);const s=n.minTranslate(),a=(n.maxTranslate()-s)*t+s;n.translateTo(a,typeof r>"u"?0:r),n.updateActiveIndex(),n.updateSlidesClasses()}emitContainerClasses(){const t=this;if(!t.params._emitClasses||!t.el)return;const r=t.el.className.split(" ").filter(n=>n.indexOf("swiper")===0||n.indexOf(t.params.containerModifierClass)===0);t.emit("_containerClasses",r.join(" "))}getSlideClasses(t){const r=this;return r.destroyed?"":t.className.split(" ").filter(n=>n.indexOf("swiper-slide")===0||n.indexOf(r.params.slideClass)===0).join(" ")}emitSlidesClasses(){const t=this;if(!t.params._emitClasses||!t.el)return;const r=[];t.slides.forEach(n=>{const s=t.getSlideClasses(n);r.push({slideEl:n,classNames:s}),t.emit("_slideClass",n,s)}),t.emit("_slideClasses",r)}slidesPerViewDynamic(t="current",r=!1){const n=this,{params:s,slides:i,slidesGrid:a,slidesSizesGrid:u,size:d,activeIndex:f}=n;let b=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),b+=1,g>d&&(y=!0));for(let v=f-1;v>=0;v-=1)i[v]&&!y&&(g+=i[v].swiperSlideSize,b+=1,g>d&&(y=!0))}else if(t==="current")for(let g=f+1;g<i.length;g+=1)(r?a[g]+u[g]-a[f]<d:a[g]-a[f]<d)&&(b+=1);else for(let g=f-1;g>=0;g-=1)a[f]-a[g]<d&&(b+=1);return b}update(){const t=this;if(!t||t.destroyed)return;const{snapGrid:r,params:n}=t;n.breakpoints&&t.setBreakpoint(),[...t.el.querySelectorAll('[loading="lazy"]')].forEach(a=>{a.complete&&Cf(t,a)}),t.updateSize(),t.updateSlides(),t.updateProgress(),t.updateSlidesClasses();function s(){const a=t.rtlTranslate?t.translate*-1:t.translate,u=Math.min(Math.max(a,t.maxTranslate()),t.minTranslate());t.setTranslate(u),t.updateActiveIndex(),t.updateSlidesClasses()}let i;if(n.freeMode&&n.freeMode.enabled&&!n.cssMode)s(),n.autoHeight&&t.updateAutoHeight();else{if((n.slidesPerView==="auto"||n.slidesPerView>1)&&t.isEnd&&!n.centeredSlides){const a=t.virtual&&n.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()}n.watchOverflow&&r!==t.snapGrid&&t.checkOverflow(),t.emit("update")}changeDirection(t,r=!0){const n=this,s=n.params.direction;return t||(t=s==="horizontal"?"vertical":"horizontal"),t===s||t!=="horizontal"&&t!=="vertical"||(n.el.classList.remove(`${n.params.containerModifierClass}${s}`),n.el.classList.add(`${n.params.containerModifierClass}${t}`),n.emitContainerClasses(),n.params.direction=t,n.slides.forEach(i=>{t==="vertical"?i.style.width="":i.style.height=""}),n.emit("changeDirection"),r&&n.update()),n}changeLanguageDirection(t){const r=this;r.rtl&&t==="rtl"||!r.rtl&&t==="ltr"||(r.rtl=t==="rtl",r.rtlTranslate=r.params.direction==="horizontal"&&r.rtl,r.rtl?(r.el.classList.add(`${r.params.containerModifierClass}rtl`),r.el.dir="rtl"):(r.el.classList.remove(`${r.params.containerModifierClass}rtl`),r.el.dir="ltr"),r.update())}mount(t){const r=this;if(r.mounted)return!0;let n=t||r.params.el;if(typeof n=="string"&&(n=document.querySelector(n)),!n)return!1;n.swiper=r,n.parentNode&&n.parentNode.host&&n.parentNode.host.nodeName===r.params.swiperElementNodeName.toUpperCase()&&(r.isElement=!0);const s=()=>`.${(r.params.wrapperClass||"").trim().split(" ").join(".")}`;let a=n&&n.shadowRoot&&n.shadowRoot.querySelector?n.shadowRoot.querySelector(s()):rl(n,s())[0];return!a&&r.params.createElements&&(a=g1("div",r.params.wrapperClass),n.append(a),rl(n,`.${r.params.slideClass}`).forEach(u=>{a.append(u)})),Object.assign(r,{el:n,wrapperEl:a,slidesEl:r.isElement&&!n.parentNode.host.slideSlots?n.parentNode.host:a,hostEl:r.isElement?n.parentNode.host:n,mounted:!0,rtl:n.dir.toLowerCase()==="rtl"||Ql(n,"direction")==="rtl",rtlTranslate:r.params.direction==="horizontal"&&(n.dir.toLowerCase()==="rtl"||Ql(n,"direction")==="rtl"),wrongRTL:Ql(a,"display")==="-webkit-box"}),!0}init(t){const r=this;if(r.initialized||r.mount(t)===!1)return r;r.emit("beforeInit"),r.params.breakpoints&&r.setBreakpoint(),r.addClasses(),r.updateSize(),r.updateSlides(),r.params.watchOverflow&&r.checkOverflow(),r.params.grabCursor&&r.enabled&&r.setGrabCursor(),r.params.loop&&r.virtual&&r.params.virtual.enabled?r.slideTo(r.params.initialSlide+r.virtual.slidesBefore,0,r.params.runCallbacksOnInit,!1,!0):r.slideTo(r.params.initialSlide,0,r.params.runCallbacksOnInit,!1,!0),r.params.loop&&r.loopCreate(void 0,!0),r.attachEvents();const s=[...r.el.querySelectorAll('[loading="lazy"]')];return r.isElement&&s.push(...r.hostEl.querySelectorAll('[loading="lazy"]')),s.forEach(i=>{i.complete?Cf(r,i):i.addEventListener("load",a=>{Cf(r,a.target)})}),b1(r),r.initialized=!0,b1(r),r.emit("init"),r.emit("afterInit"),r}destroy(t=!0,r=!0){const n=this,{params:s,el:i,wrapperEl:a,slides:u}=n;return typeof n.params>"u"||n.destroyed||(n.emit("beforeDestroy"),n.initialized=!1,n.detachEvents(),s.loop&&n.loopDestroy(),r&&(n.removeClasses(),i&&typeof i!="string"&&i.removeAttribute("style"),a&&a.removeAttribute("style"),u&&u.length&&u.forEach(d=>{d.classList.remove(s.slideVisibleClass,s.slideFullyVisibleClass,s.slideActiveClass,s.slideNextClass,s.slidePrevClass),d.removeAttribute("style"),d.removeAttribute("data-swiper-slide-index")})),n.emit("destroy"),Object.keys(n.eventsListeners).forEach(d=>{n.off(d)}),t!==!1&&(n.el&&typeof n.el!="string"&&(n.el.swiper=null),BT(n)),n.destroyed=!0),null}static extendDefaults(t){So(Wm,t)}static get extendedDefaults(){return Wm}static get defaults(){return x1}static installModule(t){tl.prototype.__modules__||(tl.prototype.__modules__=[]);const r=tl.prototype.__modules__;typeof t=="function"&&r.indexOf(t)<0&&r.push(t)}static use(t){return Array.isArray(t)?(t.forEach(r=>tl.installModule(r)),tl):(tl.installModule(t),tl)}};Object.keys(zm).forEach(e=>{Object.keys(zm[e]).forEach(t=>{_2.prototype[t]=zm[e][t]})});_2.use([VT,qT]);const S6=["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 kc(e){return typeof e=="object"&&e!==null&&e.constructor&&Object.prototype.toString.call(e).slice(8,-1)==="Object"&&!e.__swiper__}function Fu(e,t){const r=["__proto__","constructor","prototype"];Object.keys(t).filter(n=>r.indexOf(n)<0).forEach(n=>{typeof e[n]>"u"?e[n]=t[n]:kc(t[n])&&kc(e[n])&&Object.keys(t[n]).length>0?t[n].__swiper__?e[n]=t[n]:Fu(e[n],t[n]):e[n]=t[n]})}function C6(e={}){return e.navigation&&typeof e.navigation.nextEl>"u"&&typeof e.navigation.prevEl>"u"}function _6(e={}){return e.pagination&&typeof e.pagination.el>"u"}function L6(e={}){return e.scrollbar&&typeof e.scrollbar.el>"u"}function k6(e=""){const t=e.split(" ").map(n=>n.trim()).filter(n=>!!n),r=[];return t.forEach(n=>{r.indexOf(n)<0&&r.push(n)}),r.join(" ")}function JS(e=""){return e?e.includes("swiper-wrapper")?e:`swiper-wrapper ${e}`:"swiper-wrapper"}function eC({swiper:e,slides:t,passedParams:r,changedParams:n,nextEl:s,prevEl:i,scrollbarEl:a,paginationEl:u}){const d=n.filter(H=>H!=="children"&&H!=="direction"&&H!=="wrapperClass"),{params:f,pagination:b,navigation:g,scrollbar:y,virtual:v,thumbs:w}=e;let T,C,E,N,D,R,_,M;n.includes("thumbs")&&r.thumbs&&r.thumbs.swiper&&!r.thumbs.swiper.destroyed&&f.thumbs&&(!f.thumbs.swiper||f.thumbs.swiper.destroyed)&&(T=!0),n.includes("controller")&&r.controller&&r.controller.control&&f.controller&&!f.controller.control&&(C=!0),n.includes("pagination")&&r.pagination&&(r.pagination.el||u)&&(f.pagination||f.pagination===!1)&&b&&!b.el&&(E=!0),n.includes("scrollbar")&&r.scrollbar&&(r.scrollbar.el||a)&&(f.scrollbar||f.scrollbar===!1)&&y&&!y.el&&(N=!0),n.includes("navigation")&&r.navigation&&(r.navigation.prevEl||i)&&(r.navigation.nextEl||s)&&(f.navigation||f.navigation===!1)&&g&&!g.prevEl&&!g.nextEl&&(D=!0);const O=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))};n.includes("loop")&&e.isElement&&(f.loop&&!r.loop?R=!0:!f.loop&&r.loop?_=!0:M=!0),d.forEach(H=>{if(kc(f[H])&&kc(r[H]))Object.assign(f[H],r[H]),(H==="navigation"||H==="pagination"||H==="scrollbar")&&"enabled"in r[H]&&!r[H].enabled&&O(H);else{const G=r[H];(G===!0||G===!1)&&(H==="navigation"||H==="pagination"||H==="scrollbar")?G===!1&&O(H):f[H]=r[H]}}),d.includes("controller")&&!C&&e.controller&&e.controller.control&&f.controller&&f.controller.control&&(e.controller.control=f.controller.control),n.includes("children")&&t&&v&&f.virtual.enabled?(v.slides=t,v.update(!0)):n.includes("virtual")&&v&&f.virtual.enabled&&(t&&(v.slides=t),v.update(!0)),n.includes("children")&&t&&f.loop&&(M=!0),T&&w.init()&&w.update(!0),C&&(e.controller.control=f.controller.control),E&&(e.isElement&&(!u||typeof u=="string")&&(u=document.createElement("div"),u.classList.add("swiper-pagination"),u.part.add("pagination"),e.el.appendChild(u)),u&&(f.pagination.el=u),b.init(),b.render(),b.update()),N&&(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"),ab(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"),ab(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()),n.includes("allowSlideNext")&&(e.allowSlideNext=r.allowSlideNext),n.includes("allowSlidePrev")&&(e.allowSlidePrev=r.allowSlidePrev),n.includes("direction")&&e.changeDirection(r.direction,!1),(R||M)&&e.loopDestroy(),(_||M)&&e.loopCreate(),e.update()}function tC(e={},t=!0){const r={on:{}},n={},s={};Fu(r,x1),r._emitClasses=!0,r.init=!1;const i={},a=S6.map(d=>d.replace(/_/,"")),u=Object.assign({},e);return Object.keys(u).forEach(d=>{typeof e[d]>"u"||(a.indexOf(d)>=0?kc(e[d])?(r[d]={},s[d]={},Fu(r[d],e[d]),Fu(s[d],e[d])):(r[d]=e[d],s[d]=e[d]):d.search(/on[A-Z]/)===0&&typeof e[d]=="function"?t?n[`${d[2].toLowerCase()}${d.substr(3)}`]=e[d]:r.on[`${d[2].toLowerCase()}${d.substr(3)}`]=e[d]:i[d]=e[d])}),["navigation","pagination","scrollbar"].forEach(d=>{r[d]===!0&&(r[d]={}),r[d]===!1&&delete r[d]}),{params:r,passedParams:s,rest:i,events:n}}function rC({el:e,nextEl:t,prevEl:r,paginationEl:n,scrollbarEl:s,swiper:i},a){C6(a)&&t&&r&&(i.params.navigation.nextEl=t,i.originalParams.navigation.nextEl=t,i.params.navigation.prevEl=r,i.originalParams.navigation.prevEl=r),_6(a)&&n&&(i.params.pagination.el=n,i.originalParams.pagination.el=n),L6(a)&&s&&(i.params.scrollbar.el=s,i.originalParams.scrollbar.el=s),i.init(e)}function nC(e,t,r,n,s){const i=[];if(!t)return i;const a=d=>{i.indexOf(d)<0&&i.push(d)};if(r&&n){const d=n.map(s),f=r.map(s);d.join("")!==f.join("")&&a("children"),n.length!==r.length&&a("children")}return S6.filter(d=>d[0]==="_").map(d=>d.replace(/_/,"")).forEach(d=>{if(d in e&&d in t)if(kc(e[d])&&kc(t[d])){const f=Object.keys(e[d]),b=Object.keys(t[d]);f.length!==b.length?a(d):(f.forEach(g=>{e[d][g]!==t[d][g]&&a(d)}),b.forEach(g=>{e[d][g]!==t[d][g]&&a(d)}))}else e[d]!==t[d]&&a(d)}),i}const sC=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 qf(){return qf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},qf.apply(this,arguments)}function E6(e){return e.type&&e.type.displayName&&e.type.displayName.includes("SwiperSlide")}function I6(e){const t=[];return P.Children.toArray(e).forEach(r=>{E6(r)?t.push(r):r.props&&r.props.children&&I6(r.props.children).forEach(n=>t.push(n))}),t}function iC(e){const t=[],r={"container-start":[],"container-end":[],"wrapper-start":[],"wrapper-end":[]};return P.Children.toArray(e).forEach(n=>{if(E6(n))t.push(n);else if(n.props&&n.props.slot&&r[n.props.slot])r[n.props.slot].push(n);else if(n.props&&n.props.children){const s=I6(n.props.children);s.length>0?s.forEach(i=>t.push(i)):r["container-end"].push(n)}else r["container-end"].push(n)}),{slides:t,slots:r}}function oC(e,t,r){if(!r)return null;const n=b=>{let g=b;return b<0?g=t.length+b:g>=t.length&&(g=g-t.length),g},s=e.isHorizontal()?{[e.rtlTranslate?"right":"left"]:`${r.offset}px`}:{top:`${r.offset}px`},{from:i,to:a}=r,u=e.params.loop?-t.length:0,d=e.params.loop?t.length*2:t.length,f=[];for(let b=u;b<d;b+=1)b>=i&&b<=a&&f.push(t[n(b)]);return f.map((b,g)=>P.cloneElement(b,{swiper:e,style:s,key:b.props.virtualIndex||b.key||`slide-${g}`}))}function Ad(e,t){return typeof window>"u"?A.useEffect(e,t):A.useLayoutEffect(e,t)}const hb=A.createContext(null),aC=A.createContext(null),sh=A.forwardRef(({className:e,tag:t="div",wrapperTag:r="div",children:n,onSwiper:s,...i}={},a)=>{let u=!1;const[d,f]=A.useState("swiper"),[b,g]=A.useState(null),[y,v]=A.useState(!1),w=A.useRef(!1),T=A.useRef(null),C=A.useRef(null),E=A.useRef(null),N=A.useRef(null),D=A.useRef(null),R=A.useRef(null),_=A.useRef(null),M=A.useRef(null),{params:O,passedParams:H,rest:G,events:U}=tC(i),{slides:W,slots:J}=iC(n),ee=()=>{v(!y)};Object.assign(O.on,{_containerClasses(se,ie){f(ie)}});const ae=()=>{Object.assign(O.on,U),u=!0;const se={...O};if(delete se.wrapperClass,C.current=new _2(se),C.current.virtual&&C.current.params.virtual.enabled){C.current.virtual.slides=W;const ie={cache:!1,slides:W,renderExternal:g,renderExternalUpdate:!1};Fu(C.current.params.virtual,ie),Fu(C.current.originalParams.virtual,ie)}};T.current||ae(),C.current&&C.current.on("_beforeBreakpoint",ee);const Se=()=>{u||!U||!C.current||Object.keys(U).forEach(se=>{C.current.on(se,U[se])})},Le=()=>{!U||!C.current||Object.keys(U).forEach(se=>{C.current.off(se,U[se])})};A.useEffect(()=>()=>{C.current&&C.current.off("_beforeBreakpoint",ee)}),A.useEffect(()=>{!w.current&&C.current&&(C.current.emitSlidesClasses(),w.current=!0)}),Ad(()=>{if(a&&(a.current=T.current),!!T.current)return C.current.destroyed&&ae(),rC({el:T.current,nextEl:D.current,prevEl:R.current,paginationEl:_.current,scrollbarEl:M.current,swiper:C.current},O),s&&!C.current.destroyed&&s(C.current),()=>{C.current&&!C.current.destroyed&&C.current.destroy(!0,!1)}},[]),Ad(()=>{Se();const se=nC(H,E.current,W,N.current,ie=>ie.key);return E.current=H,N.current=W,se.length&&C.current&&!C.current.destroyed&&eC({swiper:C.current,slides:W,passedParams:H,changedParams:se,nextEl:D.current,prevEl:R.current,scrollbarEl:M.current,paginationEl:_.current}),()=>{Le()}}),Ad(()=>{sC(C.current)},[b]);function _e(){return O.virtual?oC(C.current,W,b):W.map((se,ie)=>P.cloneElement(se,{swiper:C.current,swiperSlideIndex:ie}))}return P.createElement(t,qf({ref:T,className:k6(`${d}${e?` ${e}`:""}`)},G),P.createElement(aC.Provider,{value:C.current},J["container-start"],P.createElement(r,{className:JS(O.wrapperClass)},J["wrapper-start"],_e(),J["wrapper-end"]),C6(O)&&P.createElement(P.Fragment,null,P.createElement("div",{ref:R,className:"swiper-button-prev"}),P.createElement("div",{ref:D,className:"swiper-button-next"})),L6(O)&&P.createElement("div",{ref:M,className:"swiper-scrollbar"}),_6(O)&&P.createElement("div",{ref:_,className:"swiper-pagination"}),J["container-end"]))});sh.displayName="Swiper";const Ec=A.forwardRef(({tag:e="div",children:t,className:r="",swiper:n,zoom:s,lazy:i,virtualIndex:a,swiperSlideIndex:u,...d}={},f)=>{const b=A.useRef(null),[g,y]=A.useState("swiper-slide"),[v,w]=A.useState(!1);function T(D,R,_){R===b.current&&y(_)}Ad(()=>{if(typeof u<"u"&&(b.current.swiperSlideIndex=u),f&&(f.current=b.current),!(!b.current||!n)){if(n.destroyed){g!=="swiper-slide"&&y("swiper-slide");return}return n.on("_slideClass",T),()=>{n&&n.off("_slideClass",T)}}}),Ad(()=>{n&&b.current&&!n.destroyed&&y(n.getSlideClasses(b.current))},[n]);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},E=()=>typeof t=="function"?t(C):t,N=()=>{w(!0)};return P.createElement(e,qf({ref:b,className:k6(`${g}${r?` ${r}`:""}`),"data-swiper-slide-index":a,onLoad:N},d),s&&P.createElement(hb.Provider,{value:C},P.createElement("div",{className:"swiper-zoom-container","data-swiper-zoom":typeof s=="number"?s:void 0},E(),i&&!v&&P.createElement("div",{className:"swiper-lazy-preloader",ref:D=>{D&&(D.lazyPreloaderManaged=!0)}}))),!s&&P.createElement(hb.Provider,{value:C},E(),i&&!v&&P.createElement("div",{className:"swiper-lazy-preloader",ref:D=>{D&&(D.lazyPreloaderManaged=!0)}})))});Ec.displayName="SwiperSlide";const mi=[];for(let e=0;e<256;++e)mi.push((e+256).toString(16).slice(1));function lC(e,t=0){return(mi[e[t+0]]+mi[e[t+1]]+mi[e[t+2]]+mi[e[t+3]]+"-"+mi[e[t+4]]+mi[e[t+5]]+"-"+mi[e[t+6]]+mi[e[t+7]]+"-"+mi[e[t+8]]+mi[e[t+9]]+"-"+mi[e[t+10]]+mi[e[t+11]]+mi[e[t+12]]+mi[e[t+13]]+mi[e[t+14]]+mi[e[t+15]]).toLowerCase()}let Vm;const cC=new Uint8Array(16);function uC(){if(!Vm){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Vm=crypto.getRandomValues.bind(crypto)}return Vm(cC)}const dC=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),fb={randomUUID:dC};function hC(e,t,r){e=e||{};const n=e.random??e.rng?.()??uC();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,lC(n)}function fC(e,t,r){return fb.randomUUID&&!e?fb.randomUUID():hC(e)}const pC={},pb=e=>{let t;const r=new Set,n=(b,g)=>{const y=typeof b=="function"?b(t):b;if(!Object.is(y,t)){const v=t;t=g??(typeof y!="object"||y===null)?y:Object.assign({},t,y),r.forEach(w=>w(t,v))}},s=()=>t,d={setState:n,getState:s,getInitialState:()=>f,subscribe:b=>(r.add(b),()=>r.delete(b)),destroy:()=>{(pC?"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."),r.clear()}},f=t=e(n,s,d);return d},mC=e=>e?pb(e):pb;var qm={exports:{}},Ym={},Zm={exports:{}},Km={};var mb;function gC(){if(mb)return Km;mb=1;var e=_p();function t(g,y){return g===y&&(g!==0||1/g===1/y)||g!==g&&y!==y}var r=typeof Object.is=="function"?Object.is:t,n=e.useState,s=e.useEffect,i=e.useLayoutEffect,a=e.useDebugValue;function u(g,y){var v=y(),w=n({inst:{value:v,getSnapshot:y}}),T=w[0].inst,C=w[1];return i(function(){T.value=v,T.getSnapshot=y,d(T)&&C({inst:T})},[g,v,y]),s(function(){return d(T)&&C({inst:T}),g(function(){d(T)&&C({inst:T})})},[g]),a(v),v}function d(g){var y=g.getSnapshot;g=g.value;try{var v=y();return!r(g,v)}catch{return!0}}function f(g,y){return y()}var b=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:u;return Km.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:b,Km}var gb;function bC(){return gb||(gb=1,Zm.exports=gC()),Zm.exports}var bb;function xC(){if(bb)return Ym;bb=1;var e=_p(),t=bC();function r(f,b){return f===b&&(f!==0||1/f===1/b)||f!==f&&b!==b}var n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,i=e.useRef,a=e.useEffect,u=e.useMemo,d=e.useDebugValue;return Ym.useSyncExternalStoreWithSelector=function(f,b,g,y,v){var w=i(null);if(w.current===null){var T={hasValue:!1,value:null};w.current=T}else T=w.current;w=u(function(){function E(M){if(!N){if(N=!0,D=M,M=y(M),v!==void 0&&T.hasValue){var O=T.value;if(v(O,M))return R=O}return R=M}if(O=R,n(D,M))return O;var H=y(M);return v!==void 0&&v(O,H)?(D=M,O):(D=M,R=H)}var N=!1,D,R,_=g===void 0?null:g;return[function(){return E(b())},_===null?void 0:function(){return E(_())}]},[b,g,y,v]);var C=s(f,w[0],w[1]);return a(function(){T.hasValue=!0,T.value=C},[C]),d(C),C},Ym}var xb;function yC(){return xb||(xb=1,qm.exports=xC()),qm.exports}var vC=yC();const wC=m6(vC),M6={},{useDebugValue:AC}=P,{useSyncExternalStoreWithSelector:TC}=wC;let yb=!1;const SC=e=>e;function CC(e,t=SC,r){(M6?"production":void 0)!=="production"&&r&&!yb&&(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"),yb=!0);const n=TC(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return AC(n),n}const vb=e=>{(M6?"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"?mC(e):e,r=(n,s)=>CC(t,n,s);return Object.assign(r,t),r},R6=e=>e?vb(e):vb,Yf="auth:unauthorized";let Bu=null;class N6 extends Error{constructor(t,r,n){super(t),this.status=r,this.code=n,this.name="TerminalApiError"}status;code}const o0=8e3,Pa=1e4,Ou=45e3;let _C=0;const _f=[];let Xm=!1;function El(e,t={}){if(typeof window>"u")return;const r=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:++_C,ts:Date.now(),...t}});_f.push(r),LC()}async function LC(){if(!Xm){Xm=!0;try{for(;_f.length>0;){const e=_f[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),_f.shift()}catch{break}}}finally{Xm=!1}}}function kC(e,t,r){const n=new AbortController;let s=setTimeout(()=>{n.abort(new DOMException(r,"TimeoutError"))},t);const i=()=>n.abort(e?.reason);return e&&(e.aborted?i():e.addEventListener("abort",i,{once:!0})),{signal:n.signal,cleanup:()=>{s&&(clearTimeout(s),s=null),e?.removeEventListener("abort",i)}}}async function ti(e,t,r,n){const{signal:s,cleanup:i}=kC(t?.signal??void 0,r,n);try{return await fetch(e,{...t,signal:s})}catch(a){throw a instanceof DOMException&&a.name==="TimeoutError"?new Error(n):a}finally{i()}}async function EC(e,t,r){let n=null;const s=new Promise((i,a)=>{n=setTimeout(()=>a(new Error(r)),t)});try{return await Promise.race([e.text(),s])}finally{n&&clearTimeout(n)}}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const e=window.fetch.bind(window);window.fetch=async(...t)=>{const r=await e(...t);if(r.status===401){Bu=null;try{window.dispatchEvent(new CustomEvent(Yf))}catch{}}return r}}async function rn(){if(Bu)return Bu;const e=await fetch("/api/csrf-token");if(!e.ok)throw new Error("Failed to get CSRF token");return Bu=(await e.json()).csrfToken,Bu}function D6(){Bu=null}const IC=2e4,wb=8e3,MC=1500,Io=new Map,RC=24,NC=40,DC=40;function BC(e){return e.retryState.retryCount>=2||e.pendingInputs.length>=DC?"congested":e.retryState.retryCount>=1||e.pendingInputs.length>=8?"degraded":"good"}function Ab(e){if(e.pendingInputs.length===0||e.ws.readyState!==WebSocket.OPEN)return;const t=e.pendingInputs.splice(0);for(const r of t)try{e.ws.send(JSON.stringify({type:"input",data:r}))}catch{}}function B6(e){if(e.ws.readyState!==WebSocket.OPEN)return;const t=BC(e);if(t==="good"){Ab(e);return}if(e.inputFlushTimer)return;const r=t==="congested"?NC:RC;e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,Ab(e)},r)}const Td=new Map;function PC(e,t,r,n){const s=Td.get(e);s&&(Td.delete(e),t?s.resolve({success:!0,layout:r}):s.reject(new Error(n||"Tmux action failed")))}function jC(e,t){const n=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${e}/ws`;return t>0?`${n}?since=${t}`:n}const Tb=new Map;async function QC(e){const t=await rn(),r=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(!r.ok){const n=await r.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(n.error||"Failed to create terminal session")}return r.json()}function FC(e,t,r,n={}){const{maxRetries:s=10,initialRetryDelay:i=1e3,maxRetryDelay:a=2e4,connectionTimeout:u=15e3}=n,d={maxRetries:s,initialDelayMs:i,maxDelayMs:a,connectionTimeoutMs:u,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1};let f=null,b=Tb.get(e)??0;Tb.delete(e);const g=[];let y=!1,v=null;const w=new WeakSet,T=()=>{d.retryTimeout&&(clearTimeout(d.retryTimeout),d.retryTimeout=null),d.connectionTimeoutId&&(clearTimeout(d.connectionTimeoutId),d.connectionTimeoutId=null),v&&(clearTimeout(v),v=null)},C=_=>{_.heartbeatTimer&&(clearInterval(_.heartbeatTimer),_.heartbeatTimer=null),_.pongTimer&&(clearTimeout(_.pongTimer),_.pongTimer=null),_.inputFlushTimer&&(clearTimeout(_.inputFlushTimer),_.inputFlushTimer=null)},E=_=>{C(_),_.heartbeatTimer=setInterval(()=>{if(_.ws.readyState===WebSocket.OPEN){try{_.ws.send(JSON.stringify({type:"ping"}))}catch{}_.pongTimer&&clearTimeout(_.pongTimer),_.pongTimer=setTimeout(()=>{if(Date.now()-_.lastInboundAt>=wb)try{_.ws.close()}catch{}},wb)}},IC)},N=()=>{if(d.isClosed=!0,T(),f){C(f),Io.delete(e);try{f.ws.close()}catch{}f=null}},D=()=>{if(d.isClosed)return;if(f){w.add(f.ws),C(f);try{f.ws.close()}catch{}}const _=jC(e,b),M=new WebSocket(_);y=!1,d.connectionTimeoutId=setTimeout(()=>{M.readyState!==WebSocket.OPEN&&(M.close(),R(new Error("WebSocket connection timeout"),!1))},u);const O={ws:M,onEvent:t,onError:r,reconnectNow:()=>{if(!d.isClosed&&!v){if(T(),f){w.add(f.ws),C(f);try{f.ws.close()}catch{}}t({type:"reconnecting",attempt:Math.min(d.retryCount+1,s),maxAttempts:s}),d.retryCount=Math.min(d.retryCount+1,s),y=!0,v=setTimeout(()=>{v=null,y=!1,D()},0)}},retryState:d,lastSeq:b,pendingInputs:g,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now()};M.onopen=()=>{T(),d.retryCount=0,O.lastInboundAt=Date.now(),E(O),B6(O)},M.onmessage=H=>{O.lastInboundAt=Date.now();try{const G=JSON.parse(H.data);if(G.type==="pong"){O.pongTimer&&(clearTimeout(O.pongTimer),O.pongTimer=null);return}if(G.type==="tmux-result"&&G.reqId){PC(G.reqId,G.success!==!1,G.layout,G.error);return}if(G.type==="tmux-layout"&&G.layout){t({type:"tmux-layout",layout:G.layout});return}if(G.type==="active-program"){t({type:"active-program",activeProgram:G.activeProgram,activeProgramRaw:G.activeProgramRaw,activeProgramSource:G.activeProgramSource});return}if(G.type==="cwd"){t({type:"cwd",cwd:G.cwd});return}if(G.type==="agent-status"){t({type:"agent-status",agentStatus:G.agentStatus??null,agentIndicator:G.agentIndicator??null,agent:G.agent??null,agentMessage:G.agentMessage??null,agentNativeSessionId:G.agentNativeSessionId??null,agentRich:G.agentRich===!0,agentActivity:typeof G.agentActivity=="number"?G.agentActivity:0,agentCwd:G.agentCwd??null,reviewed:typeof G.reviewed=="boolean"?G.reviewed:null});return}if(G.type==="git-status"){t({type:"git-status",gitStatus:G.gitStatus??null});return}if(G.type==="focus-mode"){t({type:"focus-mode",focusTrackingRequested:G.focusTrackingRequested===!0});return}if(G.type==="resize-ack"){t({type:"resize-ack",seq:typeof G.seq=="number"?G.seq:void 0,cols:typeof G.cols=="number"?G.cols:void 0,rows:typeof G.rows=="number"?G.rows:void 0,ok:G.ok!==!1,error:typeof G.error=="string"?G.error:void 0});return}if(G.type==="pty-size"){t({type:"pty-size",cols:typeof G.cols=="number"?G.cols:void 0,rows:typeof G.rows=="number"?G.rows:void 0,source:typeof G.source=="string"?G.source:void 0});return}if(G.type==="shell-title"){t({type:"shell-title",title:typeof G.title=="string"?G.title:""});return}if(G.type==="prompt-state"){t({type:"prompt-state",state:G.state==="running"?"running":"idle",exitCode:typeof G.exitCode=="number"?G.exitCode:void 0});return}const U=G;if(U.type==="connected"){typeof U.replayLastSeq=="number"&&U.replayLastSeq>0&&(b=U.replayLastSeq,O.lastSeq=b),t(U);return}if(U.type==="exit"){N(),t(U);return}t(U),U.type==="data"&&typeof U.seq=="number"&&Number.isFinite(U.seq)&&U.seq>b&&(b=U.seq,O.lastSeq=b)}catch(G){r?.(G,!1)}},M.onerror=()=>{w.has(M)||(T(),C(O),y||(y=!0,R(new Error("WebSocket connection error"),!1)))},M.onclose=H=>{if(!w.has(M)&&(T(),C(O),!d.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}),R(new Error("Session not found on server"),!0);return}if(H.code===4003||H.code===4401){try{window.dispatchEvent(new CustomEvent(Yf))}catch{}R(new Error("Authentication required"),!0);return}R(new Error("WebSocket connection closed"),!1)}},f=O,Io.set(e,f)},R=(_,M)=>{if(!d.isClosed)if(d.retryCount<s&&!M){d.retryCount++;const O=Math.min(i*Math.pow(2,d.retryCount-1),a);t({type:"reconnecting",attempt:d.retryCount,maxAttempts:s}),d.retryTimeout=setTimeout(()=>{d.isClosed||D()},O)}else r?.(_,M||d.retryCount>=s),N()};return D(),N}async function OC(e,t){const r=Io.get(e);if(r){if(r.ws.readyState===WebSocket.OPEN){r.pendingInputs.push(t),B6(r);return}if(r.ws.readyState===WebSocket.CONNECTING){r.pendingInputs.push(t);return}}const n=await rn(),s=await fetch(`/api/terminal/${e}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":n},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 $C(e){const t=Io.get(e);if(!t)return!1;if(t.ws.readyState!==WebSocket.OPEN)return t.reconnectNow(),!0;const r=t.lastInboundAt;try{t.ws.send(JSON.stringify({type:"ping"}))}catch{}return setTimeout(()=>{t.lastInboundAt<=r&&t.reconnectNow()},MC),!0}function HC(e,t,r){const n=Io.get(e);if(!(!n||n.ws.readyState!==WebSocket.OPEN))try{n.ws.send(JSON.stringify({type:"focus",focused:t,reason:r}))}catch{}}function UC(e){const t=Io.get(e);if(!(!t||t.ws.readyState!==WebSocket.OPEN))try{t.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function Sb(e,t,r){const n=Io.get(e);if(!(!n||n.ws.readyState!==WebSocket.OPEN))try{n.ws.send(JSON.stringify({type:"flow-control",paused:t,reason:r}))}catch{}}async function GC(e,t,r,n){const s=Io.get(e);if(s&&s.ws.readyState===WebSocket.OPEN)try{s.ws.send(JSON.stringify({type:"resize",cols:t,rows:r,seq:n}));return}catch{}const i=await rn(),a=await fetch(`/api/terminal/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":i},body:JSON.stringify({cols:t,rows:r,seq:n})});if(!a.ok){const d=await a.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(d.error||"Failed to resize terminal")}const u=await a.json().catch(()=>({success:!0}));if(u?.success===!1||u?.ok===!1)throw new Error(u?.error||"Failed to resize terminal")}async function zC(e,t){const r=Io.get(e);if(r&&r.ws.readyState===WebSocket.OPEN)return t.action==="scroll"?(r.ws.send(JSON.stringify({type:"tmux",...t})),{success:!0}):new Promise((i,a)=>{const u=Math.random().toString(36).substring(7);Td.set(u,{resolve:i,reject:a}),r.ws.send(JSON.stringify({type:"tmux",reqId:u,...t})),setTimeout(()=>{Td.has(u)&&(Td.delete(u),a(new Error("Tmux action timed out")))},3e4)});const n=await rn(),s=await fetch(`/api/terminal/${e}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},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 P6(e){const t=Io.get(e);if(t){t.retryState.isClosed=!0;try{t.ws.close()}catch{}Io.delete(e)}const r=await rn(),n=await fetch(`/api/terminal/${e}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":r}});if(n.status!==404&&!n.ok){const s=await n.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(s.error||"Failed to close terminal")}}async function WC(e,t){const r=Io.get(e);if(r){r.retryState.isClosed=!0;try{r.ws.close()}catch{}Io.delete(e)}const n=await rn(),s=await fetch(`/api/terminal/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},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 VC(e){const t=await fetch(`/api/terminal/${e}/health`,{method:"GET"});if(!t.ok){if(t.status===404)return{healthy:!1,sessionId:e};const r=await t.json().catch(()=>({error:"Failed to check terminal health"}));throw new Error(r.error||"Failed to check terminal health")}return t.json()}async function qC(e){const t=await rn(),r=await fetch("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to force kill terminal"}));throw new Error(n.error||"Failed to force kill terminal")}}async function y1(){const e=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!e.ok){const r=await e.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(r.error||"Failed to list tmux sessions")}const t=await e.json();return Array.isArray(t.sessions)?t.sessions:[]}async function v1(){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 j6(e){const t=e.trim();if(!t)throw new Error("tmux session name is required");const r=await rn(),n=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":r}});if(!n.ok){const i=await n.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(i.error||"Failed to kill tmux session")}const s=await n.json();return{cleanedSessions:Array.isArray(s.cleanedSessions)?s.cleanedSessions:[],alreadyGone:!!s.alreadyGone}}const Fh=new Map;function YC(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 ZC(){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 Q6(e){const t=YC(e),r=Fh.get(t);if(r)return r;const n=await rn(),s=fetch("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(e)}).then(async i=>{if(!i.ok){const a=await i.json().catch(()=>({error:"Failed to open session"}));throw new N6(a.error||"Failed to open session",i.status,typeof a.code=="string"?a.code:void 0)}return i.json()}).finally(()=>{Fh.get(t)===s&&Fh.delete(t)});return Fh.set(t,s),s}async function Lf(e,t){const r=await rn(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)});if(!n.ok){const s=await n.json().catch(()=>({error:"Failed to update session"}));throw new Error(s.error||"Failed to update session")}return n.json()}async function KC(e){const t=await rn(),r=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({sessionIds:e})});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(n.error||"Failed to reorder sessions")}return r.json()}async function XC(e){const t=await rn(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to remove session"}));throw new Error(n.error||"Failed to remove session")}}async function JC(){const e=await rn(),t=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok){const r=await t.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(r.error||"Failed to clear sessions")}}async function Cb(){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 e_(e){const t=await rn(),r=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to save toolbar presets"})),s=new Error(n.error||"Failed to save toolbar presets");throw s.current=n.current,s.code=n.code,s}return r.json()}async function t_(){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 Jm(e){const t=await rn(),r=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to update settings"}));throw new Error(n.error||"Failed to update settings")}return r.json()}async function r_(){const e=await fetch("/api/terminal/settings/activity-reorder",{method:"GET"});return e.ok?(await e.json()).enabled!==!1:!0}async function n_(e){const t=await rn(),r=await fetch("/api/terminal/settings/activity-reorder",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({enabled:e})});return r.ok?(await r.json()).enabled:e}async function s_(){const e=await fetch("/api/auth/status");if(!e.ok)throw new Error("Failed to query auth status");return e.json()}async function i_(e){const t=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:e})});if(t.ok)return D6(),{ok:!0};const r=await t.json().catch(()=>null);return t.status===429?{ok:!1,rateLimited:!0,retryAfterMs:typeof r?.retryAfterMs=="number"?r.retryAfterMs:void 0,error:r?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,error:r?.error||"Login failed"}}async function o_(){const e=await rn();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":e}}),D6()}async function a_(){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 l_(e){const t=await rn(),r=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to install agent hooks");return{summary:n.summary??"Installed",devMode:n.devMode===!0}}async function c_(e){const t=await rn(),r=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to uninstall agent hooks");return n.summary??"Removed"}async function u_(){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 d_(e){const t=await rn(),r=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to create agent plugin");return n}async function h_(e){const t=await rn(),r=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(n.error||"Failed to delete agent plugin")}}async function f_(e){const t=await rn(),r=await fetch(`/api/terminal/${encodeURIComponent(e)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),n=await r.json().catch(()=>({}));if(!r.ok)throw new Error(n.error||"Failed to resume agent session");return{command:n.command??""}}async function fu(e){const t=await rn(),r=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!r.ok){const n=await r.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(n.error||"Failed to update program rules")}return r.json()}async function p_(){const e=await rn(),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 m_(){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 _b(e){const t=await rn(),r=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!r.ok)throw new Error("Failed to save program detection config");return r.json()}async function g_(){const e=await rn(),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 b_={".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"};function F6(e){const t=e.lastIndexOf(".");return t<0?null:b_[e.slice(t).toLowerCase()]??null}function L2(e){return F6(e)!==null}async function O6(e,t,r,n="list_directory",s){const i=new URLSearchParams({path:e});r&&i.set("showHidden","true"),i.set("action",n),s&&i.set("requestSlotId",s);const a=await ti(`/api/terminal/fs/list?${i}`,{signal:t},o0,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!a.ok){const u=await a.json().catch(()=>({error:"Failed to list directory"}));throw new Error(u.error||"Failed to list directory")}return a.json()}async function x_(e,t,r,n,s,i="name",a){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);const d=await fetch(`/api/terminal/fs/search?${u}`,{signal:n});if(!d.ok||!d.body){const v=await d.json().catch(()=>({error:"Failed to search files"}));throw new Error(v.error||"Failed to search files")}const f=d.body.getReader(),b=new TextDecoder;let g="";const y=v=>{if(!v.trim())return;const w=JSON.parse(v);if(w.type==="meta")r({path:w.path,query:w.query,engine:w.engine,mode:w.mode,limited:w.limited});else if(w.type==="batch")r({entries:w.entries??[]});else if(w.type==="content-batch")r({contentEntries:w.contentEntries??[]});else{if(w.type==="error")throw new Error(w.message||"Search failed");w.type==="done"&&r({total:w.total,truncated:w.truncated,limited:w.limited,engine:w.engine,mode:w.mode,done:!0})}};for(;;){const{value:v,done:w}=await f.read();if(w)break;g+=b.decode(v,{stream:!0});let T=g.indexOf(`
|
|
3
3
|
`);for(;T>=0;)y(g.slice(0,T)),g=g.slice(T+1),T=g.indexOf(`
|
|
4
4
|
`)}g+=b.decode(),y(g)}async function y_(e,t,r){const n=new URLSearchParams;n.set("roots",e.join("|"));const s=await fetch(`/api/terminal/fs/watch?${n}`,{signal:r});if(!s.ok||!s.body){const f=await s.json().catch(()=>({error:"Failed to watch files"}));throw new Error(f.error||"Failed to watch files")}const i=s.body.getReader(),a=new TextDecoder;let u="";const d=f=>{if(!f.trim())return;const b=JSON.parse(f);b.type==="events"&&b.events?.length&&t(b.events)};for(;;){const{value:f,done:b}=await i.read();if(b)break;u+=a.decode(f,{stream:!0});let g=u.indexOf(`
|
|
@@ -71,7 +71,7 @@ void main() {
|
|
|
71
71
|
shadow-lg transition-all duration-150 ease-out`,style:{opacity:Me?1:0,transform:Me?"translate(-50%, 0) scale(1)":"translate(-50%, -8px) scale(0.9)"},children:"Tab"}),c.jsx("div",{ref:rr,"aria-hidden":!0,className:"fixed left-1/2 top-6 z-chrome-hint pointer-events-none transition-opacity duration-150 ease-out",style:{opacity:be.visible?1:0,transform:be.visible?"translate(-50%, 0) scale(1)":"translate(-50%, -8px) scale(0.9)"},children:be.visible&&(()=>{const{activeDir:$}=be,V=z=>$===z;return c.jsxs("div",{className:"flex flex-col items-center gap-0.5 rounded-xl bg-[var(--overlay-background)] backdrop-blur-sm shadow-lg px-1.5 py-1.5",children:[c.jsx("div",{className:`w-7 h-7 flex items-center justify-center rounded-lg transition-colors ${V("up")?"bg-[var(--overlay-control-bg)] text-[color:var(--overlay-foreground)]":"text-[rgb(var(--overlay-foreground-rgb)_/_0.34)]"}`,children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M12 19V5M7 11l5-5 5 5"})})}),c.jsxs("div",{className:"flex items-center gap-0.5",children:[c.jsx("div",{className:`w-7 h-7 flex items-center justify-center rounded-lg transition-colors ${V("left")?"bg-[var(--overlay-control-bg)] text-[color:var(--overlay-foreground)]":"text-[rgb(var(--overlay-foreground-rgb)_/_0.34)]"}`,children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M19 12H5M12 19l-7-7 7-7"})})}),c.jsx("div",{className:"w-7 h-7 flex items-center justify-center rounded-lg text-[rgb(var(--overlay-foreground-rgb)_/_0.18)]",children:c.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("circle",{cx:"12",cy:"12",r:"4"})})}),c.jsx("div",{className:`w-7 h-7 flex items-center justify-center rounded-lg transition-colors ${V("right")?"bg-[var(--overlay-control-bg)] text-[color:var(--overlay-foreground)]":"text-[rgb(var(--overlay-foreground-rgb)_/_0.34)]"}`,children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M5 12h14M12 5l7 7-7 7"})})})]}),c.jsx("div",{className:`w-7 h-7 flex items-center justify-center rounded-lg transition-colors ${V("down")?"bg-[var(--overlay-control-bg)] text-[color:var(--overlay-foreground)]":"text-[rgb(var(--overlay-foreground-rgb)_/_0.34)]"}`,children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M12 5v14M19 12l-7 7-7-7"})})})]})})()})]})]})});Ow.displayName="TerminalViewport";const kR=Ow,ER={background:"#1C1B1A",foreground:"#CECDC3",cursor:"#CECDC3",cursorAccent:"#1C1B1A",selectionBackground:"#403E3C",selectionForeground:"#CECDC3",selectionInactiveBackground:"#403E3C50",black:"#6F6E69",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#CECDC3",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#FFFCF0"},IR={background:"#FFFCF0",foreground:"#100F0F",cursor:"#100F0F",cursorAccent:"#FFFCF0",selectionBackground:"#CECDC3",selectionForeground:"#100F0F",selectionInactiveBackground:"#CECDC350",black:"#100F0F",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#575653",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#100F0F"};function MR(e){return e==="light"?IR:ER}const $2=new Set(["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"]);function Ol(e){if(!e)return null;if(e==="/")return"/";const t=e.replace(/\/+$/,"").split("/");return t[t.length-1]||e}function Bf(e,t,r,n=$2,s=null,i=null){if(e.customName)return{primary:e.name,secondary:Ol(r)};if(s){const u=Ol(r),d=s===r||s===u;if(i!=="idle"&&!n.has(s)&&!d)return{primary:s,secondary:u}}if(t&&!n.has(t))return{primary:t,secondary:Ol(r)};const a=Ol(r);return a?{primary:a,secondary:null}:{primary:e.name,secondary:null}}function RR(e,t,r,n=$2,s=null,i=null){return Bf(e,t,r,n,s,i).primary}function H2(e,t,r){const n=[],s=new Map;for(const i of e){const a=t(i),u=a&&a.trim().length>0?a:"";let d=s.get(u);d||(d={key:u,label:u?Ol(u)??u:r,sessions:[]},s.set(u,d),n.push(d)),d.sessions.push(i)}return n.sort((i,a)=>(i.key===""?1:0)-(a.key===""?1:0))}function NR(e){return e&&e.trim().length>0?e:""}function $w(e,t,r){const n=[...e],[s]=n.splice(t,1);return s?(n.splice(r,0,s),n.flatMap(i=>i.sessions.map(a=>a.id))):e.flatMap(i=>i.sessions.map(a=>a.id))}function Hw(e,t,r,n){return e.flatMap(s=>{if(s.key!==t)return s.sessions.map(u=>u.id);const i=s.sessions.map(u=>u.id),[a]=i.splice(r,1);return a===void 0?s.sessions.map(u=>u.id):(i.splice(n,0,a),i)})}function Uw(e,t,r,n){if(!r)return{arranged:e,groups:[]};const s=H2(e,t,n);return{arranged:s.flatMap(a=>a.sessions),groups:s}}function DR(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}const BR=e=>{const t=e?.retry;return{maxRetries:t?.maxRetries??3,initialRetryDelay:t?.initialDelayMs??1e3,maxRetryDelay:t?.maxDelayMs??8e3,connectionTimeout:e?.connectionTimeoutMs??1e4}},PR=()=>({async createSession(e){return QC(e)},connect(e,t,r){const n=FC(e,t.onEvent,t.onError,BR(r));return{close:()=>n()}},async sendInput(e,t){await OC(e,t)},async resize(e){await GC(e.sessionId,e.cols,e.rows,e.seq)},async close(e){await P6(e)},async restartSession(e,t){return WC(e,{cols:t.cols,rows:t.rows,mode:t.mode,tmuxSessionName:t.tmuxSessionName})},async forceKill(e){await qC(e)},async tmuxAction(e,t){return zC(e,t)},async listTmuxSessions(){return y1()},async getTmuxStatus(){return v1()},async checkHealth(e){return VC(e)}}),jR={app:{name:"Termdock"},common:{cancel:"Cancel",close:"Close",save:"Save",reset:"Reset",loading:"Loading…",error:"Error",retry:"Retry",refresh:"Refresh",search:"Search",clear:"Clear",delete:"Delete",on:"On",off:"Off",back:"Back",copy:"Copy",decrease:"Decrease",increase:"Increase"},login:{prompt:"termdock login",placeholder:"Enter password",placeholderBlocked:({s:e})=>`Please wait ${e}s`,submit:"Sign in",invalidPassword:"Incorrect password",failed:"Login failed"},sidebar:{sessions:"Sessions",noSessions:"No open sessions yet.",noMatchingSessions:"No matching sessions.",toggleSearch:"Toggle search",settings:"Settings",filterSessions:"Filter sessions",clearSearch:"Clear search",sortRecent:"Recent activity first",sortRecentTitle:"Sort sessions by latest terminal output. Manual drag order is restored when off.",groupByFolder:"Group by folder",groupByFolderTitle:"Collapse sessions into groups by working directory. Mutually exclusive with drag sorting.",ungrouped:"Other",needsAttention:"Needs attention",closeSession:({name:e})=>`Close ${e}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"tmux not available on server",confirmNewShell:"Create Shell?",confirmNewTmux:"Create Tmux?"},rightSidebar:{workspace:"Workspace",currentProject:"Project",browsingLocation:"Browsing",parentFolder:"Parent folder",backToProjectRoot:"Back to project",refreshFiles:"Refresh current folder",resizeFileTree:"Drag to resize file browser",pinCurrentFolder:"Pin current folder to this project",unpinCurrentFolder:"Unpin current folder",showHiddenFiles:"Show hidden files",hideHiddenFiles:"Hide hidden files",insertCurrentFolder:"Insert current folder reference",insertCurrentFolderShort:"Insert",pinnedFolders:"Pinned",unpinFolder:({name:e})=>`Unpin ${e}`,fileWatchUnavailable:({message:e})=>`File watcher unavailable: ${e}. Click to refresh manually.`,browsingOutsideProject:"Browsing outside current project",browsingOutsideProjectHint:"Git and Changes still use the current project. File references from here are inserted as external paths.",toggleSearch:"Toggle search",refreshGit:"Refresh Git status",close:"Close",filterChanges:"Filter changes or files",searchPlaceholderContent:"Search text in files…",searchModeName:"Name",searchModeContent:"Content",clearSearch:"Clear search",insertGitContext:"Insert current Git context into terminal",copyGitContext:"Copy Git context",insertChangeAuditPrompt:"Explain changes",insertChangeAuditPromptTitle:"Insert the change audit prompt into the current session",changeAuditShort:"Explain changes",changeAuditLoading:"Loading hunk explanations…",changeAuditLoaded:({count:e})=>`${e} hunk explanation${e===1?"":"s"} loaded`,changeAuditLoadedAt:({time:e})=>`Generated ${e}`,changeAuditRegenerate:"Regenerate",changeAuditRefreshStale:"Fill stale",changeAuditRefreshStaleTitle:"Insert a prompt to refresh stale hunk explanations",clearChangeAudit:"Clear",clearChangeAuditTitle:"Clear hunk explanations for the current repository",changeAuditClearFailed:({message:e})=>`Failed to clear hunk explanations: ${e}`,changeAuditScopeAll:"All repositories",changeAuditScopeLabel:"Explain scope",branchAuditTitle:"Branch explanation",branchAuditShort:"Explain branch changes",branchAuditBaseLabel:"Base branch",branchAuditBasePlaceholder:"Base branch, e.g. master",branchAuditBaseSearchPlaceholder:"Search base branch",branchAuditBaseEmpty:"No branch options. Type a branch name directly.",branchAuditGenerate:"Generate",branchAuditRegenerate:"Regenerate",branchAuditGenerateTitle:"Insert a prompt to explain this branch against the base branch",branchAuditViewDiff:"View diff",branchAuditViewDiffTitle:"View target branch changes against the base branch",branchAuditDiffLoading:"Loading branch diff...",branchAuditDiffEmpty:"No changes between this branch and the base branch.",branchAuditMissingBase:({repo:e})=>`${e} has no base branch set`,branchAuditRefreshDiff:"Refresh diff",branchAuditRefreshStale:"Fill stale",branchAuditRefreshStaleTitle:"Insert a prompt to refresh stale branch explanations",branchAuditClearTitle:"Clear current branch explanation",branchAuditClearFailed:({message:e})=>`Failed to clear branch explanation: ${e}`,branchAuditCommitCount:({count:e})=>`${e} commit${e===1?"":"s"}`,branchAuditFileCount:({count:e})=>`${e} file${e===1?"":"s"}`,branchAuditTruncated:"diff truncated",branchAuditCurrent:"Saved explanation",branchAuditStale:"Explanation is stale",branchAuditEmpty:"No branch explanation yet. Generate one to persist it here for later review.",branchAuditView:"View explanations",branchAuditSaved:({count:e})=>`${e} hunk explanation${e===1?"":"s"} saved`,branchAuditGeneratedAt:({time:e})=>`Generated ${e}`,insertPreset:({label:e})=>`Insert: ${e}`,tabChanges:"Changes",tabGit:"Git",tabFiles:"Files",tabPreview:"Preview",inserted:"Inserted",copied:"Copied",selectFilePrompt:"Select a file to preview its contents",backToFileList:"Back to file list",insertLineRef:({lineLabel:e})=>`Insert ${e}`,insertFileRef:"Insert",copyFileRef:"Copy file reference",downloadFile:"Download file",downloadFailed:"Download failed",uploadFile:"Upload file",uploadFiles:"Upload files",dropToUpload:"Drop files to upload",uploading:"Uploading…",uploadSuccess:({count:e})=>`${e} file${e===1?"":"s"} uploaded`,uploadFailed:"Upload failed",binaryPreviewHint:"Binary files cannot be previewed. Use the download button above to save it.",selectedLineHint:({lineLabel:e})=>`Selected ${e} · tap "Insert" below to add to terminal`,multiLineHint:"Multi-line select: tap start line, then end line",loadingImage:"Loading image…",imagePreviewHint:"Pinch or ⌘/Ctrl + scroll to zoom · double-tap to reset",imageLoadFailed:"Failed to load image preview",markdownPreview:"Preview",markdownSource:"Source",markdownPreviewHint:"Markdown preview · switch to Source to select lines",markdownOutline:"Markdown outline",markdownOutlineShort:"Outline",closeMarkdownOutline:"Close outline",changedFromPath:({path:e})=>`from ${e}`,selectedLineFooter:({lineLabel:e})=>`Selected ${e}`,clearSelection:"Clear",allChanges:"All changes",backToChangeList:"Back to list",allRepositories:"All repositories",allRepositoriesShort:"All",repositories:"Repositories",gitRepositorySectionTitle:"Repository",gitRepositoryLabel:"Repository",gitRepositoryPlaceholder:"Select repository",gitRepositorySearchPlaceholder:"Search repositories",gitRepositoryEmpty:"No available repositories",selectRepositoryForGitActions:"Select a repository before running Git actions",selectRepositoryForDiff:"Select a repository or file to view diff",repoChangedCount:({count:e})=>`${e} change${e===1?"":"s"}`,repoStagedCount:({count:e})=>`${e} staged`,noChanges:"No changes",noMatchingChanges:"No matching changes",loadingGitChanges:"Loading Git changes…",loadingGitChangesSlow:"Large repositories can take a few seconds.",refreshingGitChanges:"Refreshing Git changes…",gitChangesLoadFailed:"Unable to load Git changes",retryGitChanges:"Retry",insertThisFile:"Insert this file reference into terminal",viewDiff:"View diff",diffViewMode:"Change file display mode",diffViewModeList:"Flat list",diffViewModeTree:"Folder tree",diffViewModeAi:"AI walkthrough",changeWalkthroughEmpty:"No AI walkthrough yet. Generate explanations to show the overview, flow, and checks here.",gitInfo:"Git context",wrapLongLines:"Wrap long lines",wrapOn:"Wrapped",wrapOff:"Raw",horizontalScrollHint:"Swipe left/right to see the full diff",stageFile:"Stage",stageAll:"Stage all",unstageFile:"Unstage",stashFile:"Stash",stashAll:"Stash all",restoreFile:"Restore",gitQuickActions:"Git Actions",gitUnavailable:"Current directory is not a Git repository",branchSectionTitle:"Current branch",currentBranchLabel:"Branch",switchBranchPlaceholder:"Select branch",switchBranchSearchPlaceholder:"Search local branch",switchNoBranches:"No local branches",switchBranch:"Switch",noStagedChangesShort:"no staged",stagedCount:({count:e})=>`${e} staged`,stagedCountShort:({count:e})=>`${e} staged`,commitSectionTitle:"Commit",commitReadyHint:({count:e})=>`${e} file${e===1?"":"s"} ready`,commitMessagePlaceholder:"Commit message",commitChanges:"Commit",commitNeedsStaged:"Stage changes before committing",recentCommitsTitle:"Recent commits",recentCommitsSearchPlaceholder:"Search commit hash or message",recentCommitsLoadMore:"Load more commits",recentCommitsEmpty:"No commit history",pushSectionTitle:"Remote sync",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"Search remote",pushNoRemotes:"No remotes",pushBranchLabel:"Target",pushBranchPlaceholder:({branch:e})=>`${e}`,pushBranchSearchPlaceholder:"Search branch",pushNoBranches:"No branches",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"current",pushNoUpstream:"No upstream configured",pushUpToDate:"Up to date with remote",pushAheadCount:({count:e})=>`${e} commit${e===1?"":"s"} to push`,pushBehindCount:({count:e})=>`${e} commit${e===1?"":"s"} to pull`,pushDivergedCount:({ahead:e,behind:t})=>`${e} ahead / ${t} behind`,pullChanges:"Pull",pushChanges:"Push",gitActionRunning:"Running…",gitActionFailed:({message:e})=>`Git action failed: ${e}`,confirmRestoreTitle:"Discard changes?",confirmRestoreDescription:({path:e})=>`This will discard unstaged changes in ${e}. Termdock cannot recover them.`,confirmRestorePhrase:"discard changes",confirmRestorePlaceholder:"Type “discard changes” to confirm",confirmStashAllTitle:"Stash all changes?",confirmStashAllDescription:"This moves current working tree changes, including untracked files, into a stash.",confirmAction:"Confirm"},fileTree:{insertRef:"Insert",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"Open",openDirRootTitle:"Use this folder as the current browsing root",openInFileBrowser:"Reveal in Finder",openInFileBrowserTitle:"Open this item in the system file browser",openInFileBrowserFailed:"Failed to open file browser",moreDirActions:"More folder actions",pinDir:"Pin",pinDirTitle:"Pin this folder to the current project",unpinDir:"Pinned",unpinDirTitle:"Unpin this folder",pinFileTitle:"Pin this file to the current project",unpinFileTitle:"Unpin this file",pinFile:"Pin",unpinFile:"Unpin",moreFileActions:"More file actions",noWorkingDir:"No working directory detected.",emptyDir:"Empty directory.",noMatchingFiles:"No matching files.",searching:"Searching files…",searchingWithCount:({count:e})=>`Searching… ${e} found`,searchResults:({count:e})=>`${e} results`,searchTruncatedHint:({count:e})=>`Fallback search scanned a large directory and stopped after ${e} matches. Install ripgrep or refine the query for complete results.`,searchStillRunning:"Search is still running. More results will appear automatically.",showingSearchResults:({shown:e,total:t})=>`Showing ${e} of ${t}`,loadMoreSearchResults:({shown:e,total:t})=>`Show more (${e}/${t})`,contentMatchesCount:({count:e})=>`${e} file${e===1?"":"s"} with matches`,moreMatches:({count:e})=>`+${e} more match${e===1?"":"es"}`,noContentMatches:"No matches found in file contents.",contentSearchNeedsRipgrep:"Content search requires ripgrep (rg). Install it on the server to search inside files.",truncatedHint:"Showing first 1000 entries. Use search or open a smaller folder for better performance.",dropToUploadHere:"Upload here"},diffViewer:{noFileChanges:"No changes in this file.",noUnstagedChanges:"No unstaged changes.",emptyHint:"Make some changes, or pull from a remote.",loading:"Loading diff…",insertAllDiff:"Insert current diff as context",insertFileDiff:"Insert this file's diff",insertHunkDiff:"Insert this hunk",insertHunkShort:"Insert",insertFileShort:"Insert",insertAllShort:"Insert all",auditExplanation:"Change meaning",auditStale:"Explanation stale",auditClear:"Clear explanation",auditGeneratedAt:({time:e})=>`Generated ${e}`,allDiffLabel:"all changes",allChangesLabel:"all changes",workingTree:"Working tree changes",allUnstaged:"All unstaged changes",binaryOrEmpty:"No textual changes to display.",noHunks:"No hunks",hunkOutline:"Hunks",expandHunkRail:"Show hunk list",collapseHunkRail:"Hide hunk list",prevHunk:"Previous hunk",nextHunk:"Next hunk",prevFile:"Previous",nextFile:"Next",expandFile:"Expand file",collapseFile:"Collapse file",expandAll:"Expand all",collapseAll:"Collapse all",collapseHunk:"Collapse hunk",useBracketKeysHint:"Press [ / ] to jump between hunks",unified:"Unified",unifiedMode:"Unified view",split:"Split",splitMode:"Side-by-side view",moreActions:"More actions",view:"View"},settings:{title:"Settings",font:"Font",render:"Render",theme:"Theme",darkTheme:"Dark",lightTheme:"Light",newTab:"New tab",debug:"Debug",noSleep:"No sleep",noSleepUnavailable:"No network — disabled",notifications:"Notify",notificationsTitle:"Notification settings",notificationsHint:"Notify when an AI task finishes while Termdock is hidden.",notificationsPageHint:"Choose which Termdock events can send system notifications. The master switch controls browser permission and delivery; event switches decide what should notify you.",notificationsMaster:"System notifications",notificationsMasterHint:"Allow Termdock to send notifications when it is hidden or running as an installed PWA.",notificationsPermission:"Permission",notificationsTest:"Send test",notificationsAlertStyle:"Alert style",notificationsAlertStyleHint:"Browsers and Android still decide the final heads-up behavior. Termdock can only request quiet/default/sticky notification options.",notificationsStyleNormal:"Default",notificationsStyleNormalHint:"Sound/vibration if allowed",notificationsStyleQuiet:"Quiet",notificationsStyleQuietHint:"Status tray, no sound",notificationsStylePersistent:"Sticky",notificationsStylePersistentHint:"Stay until dismissed",notificationsEvents:"Events",notificationsAiFinished:"AI task finished",notificationsAiFinishedHint:"Notify when an AI agent stops while Termdock is in the background.",notificationsFutureHint:"More notification types can be added here later without changing the top-level settings layout.",notificationsOffSummary:"System notifications disabled",notificationsAiOnSummary:"AI task finished enabled",notificationsNoEventsSummary:"No notification events enabled",notificationsDenied:"Browser notification permission is blocked. Enable it in site settings.",notificationsUnsupported:"Notifications require a secure context and service worker support.",notificationsTestBody:"Notifications are enabled. You will be notified when an AI task finishes in the background.",shell:"Shell",tmux:"Tmux",auto:"Auto",webgl:"WebGL",canvas:"Built-in",tmuxServer:"Tmux server",tmuxUnavailable:"unavailable",noTmuxSessions:"No tmux sessions on the server.",installTmuxHint:"Install tmux on the server to enable.",refresh:"Refresh",attached:"Attached",restorable:"Restorable",attach:"Attach",attaching:"Attaching…",destroy:"Destroy",sessions:({n:e})=>`${e} session${e===1?"":"s"}`,windows:({n:e})=>`${e} window${e===1?"":"s"}`,keyboardToolbar:"Keyboard toolbar",aiAgentDetection:"AI agent detection",signOut:"Sign out",language:"Language",programNamePlaceholder:"Program name (e.g. claude)",patternPlaceholder:"Regex pattern (e.g. Thinking|Generating)",statusPlaceholder:"Status",addProgram:"Add program",addPattern:"Add pattern",resetDefaults:"Reset defaults",invalidRegex:"Invalid regex",removeProgram:"Remove program",removeRule:"Remove rule",keepLabel:"keep",customColor:"Custom color",tabIndicator:"Tab indicator style",toolbarPresets:"Toolbar presets",detectionRules:"Detection rules",agentHooksHint:"With hooks installed, agents report their own status: working (green), waiting for you (amber), turn done (check) — and you get a notification the moment one needs your input. Hooks install globally but only fire inside termdock terminals.",agentHooksInstall:"Install",agentHooksInstalled:"Installed",agentHooksOutdated:"Outdated",agentHooksNotInstalled:"Not installed",agentHooksUninstall:"Uninstall",agentHooksReinstall:"Reinstall",agentHooksDevMode:"Dev mode: hooks point at TS sources and need a built install to fire",agentHooksTarget:"writes to",agentPlugins:"Agent Plugins",agentPluginAdd:"Add Plugin",agentPluginHint:"Define custom agents with their own hooks config. Paste a manifest.json below to register a new agent and optionally install hooks for it.",agentPluginCreate:"Create Plugin",agentPluginDelete:"Delete Plugin",mobileKeyboard:"Mobile keyboard",saving:"Saving…",rulesHint:"Configure regex patterns to detect what an AI tool is doing in a terminal tab. Each rule can choose its label, color, icon style and how long the indicator is kept after output quiets down. When it stops and you haven't viewed the tab yet, the tab keeps a yellow review hint.",programsHelp:"Supports multiple programs in one config. Separate with commas.",programLabelResolution:"Program label resolution",rawCommandMapping:"Raw command mapping",rawCommandMappingHint:"Rules below map the raw command line to the tab display label. User rules run before built-ins.",genericProgramNames:"Generic program names",genericProgramNamesHint:"Trigger ps-based deep detection (e.g. node, python)",wrapperScriptNames:"Wrapper script names",wrapperScriptNamesHint:"CLI wrappers that launch another tool (e.g. aiden, npx)",shellNamesConfig:"Shell names",shellNamesHint:"Filtered out from tab display (e.g. bash, zsh)",addTag:"+ add",customRules:"Custom rules",addRule:"Add rule",localAccess:"Local access",localAccessHint:"Use this LAN URL from your phone after trusting the local CA. Open Mobile setup on your phone to download the CA certificate.",resetAutoName:"Reset auto",onboardingUrl:"Mobile setup",httpsActive:"HTTPS active",httpsInactive:"HTTPS inactive",caMissing:"CA download unavailable"},toolbarPresets:{preview:"Preview",presets:"Presets",label:"Label",new:"New",reset:"Reset",presetLabelPlaceholder:"Preset label",deletePreset:({name:e})=>`Delete preset ${e}`,matchPrograms:"Match programs",typeEnterHint:"Type & Enter",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"Plain names match as case-insensitive substrings. Wrap in /…/flags for regex (tested against the lowercase program name).",altSlot:"Alt modifier slot",altSlotHint:"Reserve one preview slot for the Alt key.",desktopVisibility:"Show on desktop",desktopVisibilityHint:"Desktop shows only this preset’s custom actions, not the basic keyboard shortcuts.",rowLayout:"Row layout",rowLayoutHint:"Buttons per expanded row.",addRow:"Row",rowN:({n:e})=>`Row ${e}`,del:"Del",buttons:"Buttons",buttonsHint:"Tap to edit. Use ↑↓ to reorder.",addButton:"Add button",noCustomButtons:"No custom buttons yet. Add one to override the default toolbar.",moveUp:"Move up",moveDown:"Move down",removeRow:({n:e})=>`Remove row ${e}`,removeAction:({name:e})=>`Remove ${e}`,labelField:"Label",labelPlaceholder:"Label shown on the button",sequence:"Sequence",sequencePlaceholder:"e.g. /undo or \\t or /||undo",sequenceHint:"Double-tap sequence",doubleTap:"Double-tap sequence",doubleTapAdd:"+ Add",doubleTapPlaceholder:"e.g. /undo\\r or /||undo ||\\r",remove:"Remove",noSequence:"No sequence",preset:"Preset",overCapacityHint:"More buttons than slots. Extra rows will use the last row size."},agentRules:{ruleColors:{green:"Green",yellow:"Yellow",red:"Red",blue:"Blue",purple:"Purple",orange:"Orange",gray:"Gray"}},tab:{session:"Session",new:"New session",rename:"Rename",renameHint:"Change the tab display name",renamePlaceholder:"Leave empty to reset to default",copyCwd:"Copy cwd",copyCwdHint:"Copy the current working directory",resumeAgent:"Resume agent session",resumeAgentHint:"Resume the last conversation by its native session id",copied:"Copied",close:"Close session",closeHint:"Remove this tab from the list",longPressTip:"Tip: hold a tab still for a moment to open actions; hold and drag to reorder.",sessionsTitle:"Sessions",explorerTitle:"Explorer"},agent:{aiRunning:"AI running",needsReview:"Needs review",finishedReview:"AI finished — needs review",aiWaiting:"AI waiting",copyMode:"Copy mode",jumpToNext:"Jump to next session needing attention"},connection:{reconnecting:"Reconnecting…"},terminal:{input:"Terminal input",error:"Error",dropFilesToPastePaths:"Drop files to paste paths"},errorBoundary:{title:"Something went wrong",unexpected:"An unexpected error occurred",retry:"Try Again"},error:{type:{network:"Network error",session:"Session error",terminal:"Terminal error",auth:"Authentication error",validation:"Validation error",unknown:"Unknown error"},severity:{low:"Notice: ",medium:"Warning: ",high:"Error: ",critical:"Critical: "},suggestion:{networkCheck:"Check your network connection",networkRetry:"Try reconnecting",networkProxy:"Check proxy settings",networkWait:"Wait for the network to recover",sessionRecreate:"Recreate the session",sessionServer:"Check the server status",sessionCache:"Clear your browser cache",terminalRestart:"Restart the terminal",terminalConfig:"Check the terminal configuration",terminalClear:"Clear the terminal output",authRelogin:"Sign in again",authCredentials:"Check your credentials",authAdmin:"Contact the administrator",validationFormat:"Check the input format",validationParams:"Verify your parameters",validationDocs:"See the documentation",unknownReload:"Reload the page",unknownApp:"Restart the app",unknownSupport:"Contact support"}}},QR={app:{name:"Termdock"},common:{cancel:"取消",close:"关闭",save:"保存",reset:"重置",loading:"加载中…",error:"错误",retry:"重试",refresh:"刷新",search:"搜索",clear:"清除",delete:"删除",on:"开",off:"关",back:"返回",copy:"复制",decrease:"减少",increase:"增加"},login:{prompt:"termdock login",placeholder:"请输入密码",placeholderBlocked:({s:e})=>`请稍候 ${e}s`,submit:"登录",invalidPassword:"密码错误",failed:"登录失败"},sidebar:{sessions:"会话",noSessions:"暂无打开的会话。",noMatchingSessions:"没有匹配的会话。",toggleSearch:"切换搜索",settings:"设置",filterSessions:"过滤会话",clearSearch:"清除搜索",sortRecent:"最近活跃优先",sortRecentTitle:"按最近一次 Terminal 输出排序;关闭后恢复手动拖拽顺序。",groupByFolder:"按文件夹分组",groupByFolderTitle:"按工作目录把会话归组折叠;与拖拽排序互斥。",ungrouped:"其他",needsAttention:"待处理",closeSession:({name:e})=>`关闭 ${e}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"服务端未安装 tmux",confirmNewShell:"创建 Shell?",confirmNewTmux:"创建 Tmux?"},rightSidebar:{workspace:"工作区",currentProject:"项目",browsingLocation:"浏览中",parentFolder:"上一级目录",backToProjectRoot:"回到当前项目",refreshFiles:"刷新当前目录",resizeFileTree:"拖动调整文件目录宽度",pinCurrentFolder:"固定当前目录到这个项目",unpinCurrentFolder:"取消固定当前目录",showHiddenFiles:"显示隐藏文件",hideHiddenFiles:"不显示隐藏文件",insertCurrentFolder:"引用当前目录",insertCurrentFolderShort:"引用",pinnedFolders:"固定",unpinFolder:({name:e})=>`取消固定 ${e}`,fileWatchUnavailable:({message:e})=>`文件监听不可用:${e}。可点击手动刷新。`,browsingOutsideProject:"正在浏览当前项目外目录",browsingOutsideProjectHint:"Git 和改动仍使用当前项目;这里引用的文件会按外部路径插入。",toggleSearch:"切换搜索",refreshGit:"刷新 Git 状态",close:"关闭",filterChanges:"过滤改动或文件",searchPlaceholderContent:"在文件内容中搜索…",searchModeName:"名称",searchModeContent:"内容",clearSearch:"清除搜索",insertGitContext:"把当前 Git 信息插入 Terminal",copyGitContext:"复制 Git 信息",insertChangeAuditPrompt:"解释当前改动",insertChangeAuditPromptTitle:"把更改审计提示词插入当前会话",changeAuditShort:"解释当前改动",changeAuditLoading:"正在加载 hunk 解释…",changeAuditLoaded:({count:e})=>`已加载 ${e} 条 hunk 解释`,changeAuditLoadedAt:({time:e})=>`最近生成 ${e}`,changeAuditRegenerate:"重新生成",changeAuditRefreshStale:"补充失效",changeAuditRefreshStaleTitle:"为已失效的 hunk 解释插入补充生成提示词",clearChangeAudit:"清理",clearChangeAuditTitle:"清理当前仓库的 hunk 解释",changeAuditClearFailed:({message:e})=>`清理 hunk 解释失败:${e}`,changeAuditScopeAll:"全部仓库",changeAuditScopeLabel:"解释范围",branchAuditTitle:"分支解释",branchAuditShort:"解释分支改动",branchAuditBaseLabel:"基线分支",branchAuditBasePlaceholder:"基线分支,例如 master",branchAuditBaseSearchPlaceholder:"搜索基线分支",branchAuditBaseEmpty:"没有可选分支,可直接输入分支名",branchAuditGenerate:"生成解释",branchAuditRegenerate:"重新生成",branchAuditGenerateTitle:"生成当前分支相对于基线分支的解释提示词",branchAuditViewDiff:"查看对比",branchAuditViewDiffTitle:"查看目标分支相对于基线分支的改动",branchAuditDiffLoading:"正在加载分支对比…",branchAuditDiffEmpty:"当前分支相对于基线分支暂无改动。",branchAuditMissingBase:({repo:e})=>`${e} 未设置基线分支`,branchAuditRefreshDiff:"刷新对比",branchAuditRefreshStale:"补充失效",branchAuditRefreshStaleTitle:"为已失效的分支解释插入补充生成提示词",branchAuditClearTitle:"清理当前分支解释",branchAuditClearFailed:({message:e})=>`清理分支解释失败:${e}`,branchAuditCommitCount:({count:e})=>`${e} 个提交`,branchAuditFileCount:({count:e})=>`${e} 个文件`,branchAuditTruncated:"diff 已截断",branchAuditCurrent:"已保存解释",branchAuditStale:"解释已失效",branchAuditEmpty:"暂无分支解释。生成后会持久化保存,可随时回来查看。",branchAuditView:"查看解释",branchAuditSaved:({count:e})=>`已保存 ${e} 条 hunk 解释`,branchAuditGeneratedAt:({time:e})=>`生成于 ${e}`,insertPreset:({label:e})=>`插入:${e}`,tabChanges:"改动",tabGit:"Git",tabFiles:"文件",tabPreview:"预览",inserted:"已插入",copied:"已复制",selectFilePrompt:"选择文件以预览内容",backToFileList:"返回文件列表",insertLineRef:({lineLabel:e})=>`引用${e}`,insertFileRef:"引用",copyFileRef:"复制文件引用",downloadFile:"下载文件",downloadFailed:"下载失败",uploadFile:"上传文件",uploadFiles:"上传文件",dropToUpload:"拖放文件以上传",uploading:"上传中…",uploadSuccess:({count:e})=>`已上传 ${e} 个文件`,uploadFailed:"上传失败",binaryPreviewHint:"二进制文件无法预览,请使用上方下载按钮保存到本地",selectedLineHint:({lineLabel:e})=>`已选 ${e} · 点下方「引用」按钮插入`,multiLineHint:"多行引用:先点起始行,再点结束行",loadingImage:"正在加载图片…",imagePreviewHint:"双指捏合或 ⌘/Ctrl + 滚动缩放 · 双击还原",imageLoadFailed:"图片预览加载失败",markdownPreview:"预览",markdownSource:"源码",markdownPreviewHint:"Markdown 预览 · 切到源码可选择行号",markdownOutline:"Markdown 目录",markdownOutlineShort:"目录",closeMarkdownOutline:"关闭目录",changedFromPath:({path:e})=>`来自 ${e}`,selectedLineFooter:({lineLabel:e})=>`已选 ${e}`,clearSelection:"清除",allChanges:"全部改动",backToChangeList:"返回目录",allRepositories:"全部仓库",allRepositoriesShort:"全部",repositories:"仓库",gitRepositorySectionTitle:"操作仓库",gitRepositoryLabel:"仓库",gitRepositoryPlaceholder:"选择仓库",gitRepositorySearchPlaceholder:"搜索仓库",gitRepositoryEmpty:"没有可操作的仓库",selectRepositoryForGitActions:"请选择一个仓库后再执行 Git 操作",selectRepositoryForDiff:"选择一个仓库或文件查看 diff",repoChangedCount:({count:e})=>`${e} 个改动`,repoStagedCount:({count:e})=>`${e} 已暂存`,noChanges:"没有改动",noMatchingChanges:"没有匹配的改动",loadingGitChanges:"正在加载 Git 改动…",loadingGitChangesSlow:"仓库较大时可能需要几秒。",refreshingGitChanges:"正在刷新 Git 改动…",gitChangesLoadFailed:"无法加载 Git 改动",retryGitChanges:"重试",insertThisFile:"把这个文件引用插入 Terminal",viewDiff:"查看 diff",diffViewMode:"改动文件展示方式",diffViewModeList:"平铺列表",diffViewModeTree:"目录结构",diffViewModeAi:"AI 导览",changeWalkthroughEmpty:"暂无 AI 导览。生成解释后会在这里展示总览、链路和验证点。",gitInfo:"Git 信息",wrapLongLines:"长行换行",wrapOn:"已换行",wrapOff:"原始",horizontalScrollHint:"左右滑动查看完整 diff",stageFile:"暂存",stageAll:"全部暂存",unstageFile:"取消暂存",stashFile:"贮藏",stashAll:"全部贮藏",restoreFile:"丢弃",gitQuickActions:"Git 操作",gitUnavailable:"当前目录不是 Git 仓库",branchSectionTitle:"当前分支",currentBranchLabel:"分支",switchBranchPlaceholder:"选择分支",switchBranchSearchPlaceholder:"搜索本地分支",switchNoBranches:"没有本地分支",switchBranch:"切换",noStagedChangesShort:"无暂存",stagedCount:({count:e})=>`已暂存 ${e}`,stagedCountShort:({count:e})=>`已暂存 ${e}`,commitSectionTitle:"提交",commitReadyHint:({count:e})=>`${e} 个文件已准备提交`,commitMessagePlaceholder:"提交信息",commitChanges:"提交",commitNeedsStaged:"请先暂存要提交的改动",recentCommitsTitle:"近期提交",recentCommitsSearchPlaceholder:"搜索提交 hash 或信息",recentCommitsLoadMore:"加载更多提交",recentCommitsEmpty:"暂无提交历史",pushSectionTitle:"同步远端",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"搜索 Remote",pushNoRemotes:"没有 Remote",pushBranchLabel:"目标分支",pushBranchPlaceholder:({branch:e})=>`${e}`,pushBranchSearchPlaceholder:"搜索分支",pushNoBranches:"没有分支",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"当前",pushNoUpstream:"当前分支未设置 upstream",pushUpToDate:"与远端同步",pushAheadCount:({count:e})=>`领先远端 ${e} 个提交`,pushBehindCount:({count:e})=>`落后远端 ${e} 个提交`,pushDivergedCount:({ahead:e,behind:t})=>`领先 ${e} / 落后 ${t} 个提交`,pullChanges:"拉取",pushChanges:"推送",gitActionRunning:"执行中…",gitActionFailed:({message:e})=>`Git 操作失败:${e}`,confirmRestoreTitle:"确认丢弃改动",confirmRestoreDescription:({path:e})=>`将丢弃 ${e} 的未暂存改动,此操作不可从 Termdock 恢复。`,confirmRestorePhrase:"丢弃改动",confirmRestorePlaceholder:"输入“丢弃改动”确认",confirmStashAllTitle:"确认贮藏全部改动",confirmStashAllDescription:"会把当前工作区改动(包含未跟踪文件)移入贮藏。",confirmAction:"确认"},fileTree:{insertRef:"引用",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"进入",openDirRootTitle:"把这个目录作为当前浏览根目录",openInFileBrowser:"在 Finder 中显示",openInFileBrowserTitle:"在系统文件浏览器中打开这个项目",openInFileBrowserFailed:"打开文件浏览器失败",moreDirActions:"更多目录操作",pinDir:"固定",pinDirTitle:"固定这个目录到当前项目",unpinDir:"已固定",unpinDirTitle:"取消固定这个目录",pinFileTitle:"固定这个文件到当前项目",unpinFileTitle:"取消固定这个文件",pinFile:"固定",unpinFile:"已固定",moreFileActions:"更多文件操作",noWorkingDir:"未检测到工作目录。",emptyDir:"空目录。",noMatchingFiles:"没有匹配的文件。",searching:"正在搜索文件…",searchingWithCount:({count:e})=>`搜索中…已找到 ${e} 项`,searchResults:({count:e})=>`${e} 个结果`,searchTruncatedHint:({count:e})=>`降级搜索已扫描大量目录并在找到 ${e} 项后停止。安装 ripgrep 或输入更精确关键词可获得完整结果。`,searchStillRunning:"搜索仍在进行,更多结果会自动出现。",showingSearchResults:({shown:e,total:t})=>`正在展示 ${e}/${t}`,loadMoreSearchResults:({shown:e,total:t})=>`查看更多(${e}/${t})`,contentMatchesCount:({count:e})=>`${e} 个文件命中`,moreMatches:({count:e})=>`还有 ${e} 处匹配`,noContentMatches:"文件内容中没有匹配。",contentSearchNeedsRipgrep:"内容搜索需要 ripgrep(rg),请在服务端安装后再在文件内搜索。",truncatedHint:"仅展示前 1000 项。使用搜索或打开更小的文件夹以获得更好性能。",dropToUploadHere:"上传到这里"},diffViewer:{noFileChanges:"此文件无改动。",noUnstagedChanges:"没有未暂存的改动。",emptyHint:"做一些改动,或从远程拉取。",loading:"正在加载 diff…",insertAllDiff:"把当前 diff 内容作为上下文插入 Terminal",insertFileDiff:"引用这个文件的 diff",insertHunkDiff:"引用这段 diff hunk",insertHunkShort:"引用",insertFileShort:"引用",insertAllShort:"全部",auditExplanation:"更改意义",auditStale:"解释已失效",auditClear:"清除解释",auditGeneratedAt:({time:e})=>`生成于 ${e}`,allDiffLabel:"全部 diff",allChangesLabel:"全部改动",workingTree:"工作区改动",allUnstaged:"所有未暂存改动",binaryOrEmpty:"没有可显示的文本改动。",noHunks:"没有 hunk",hunkOutline:"Hunk 列表",expandHunkRail:"显示 hunk 列表",collapseHunkRail:"隐藏 hunk 列表",prevHunk:"上一个 hunk",nextHunk:"下一个 hunk",prevFile:"上一个",nextFile:"下一个",expandFile:"展开文件",collapseFile:"折叠文件",expandAll:"全部展开",collapseAll:"全部折叠",collapseHunk:"折叠 hunk",useBracketKeysHint:"按 [ / ] 在 hunk 之间跳转",unified:"统一",unifiedMode:"统一视图",split:"分屏",splitMode:"左右分屏视图",moreActions:"更多操作",view:"视图"},settings:{title:"设置",font:"字体",render:"渲染",theme:"主题",darkTheme:"深色",lightTheme:"浅色",newTab:"新标签",debug:"调试",noSleep:"常亮",noSleepUnavailable:"无网络 — 已禁用",notifications:"通知",notificationsTitle:"通知设置",notificationsHint:"Termdock 在后台时,AI 任务结束后发送系统通知。",notificationsPageHint:"选择哪些 Termdock 事件可以发送系统通知。总开关负责浏览器权限和投递,事件开关决定具体哪些内容提醒你。",notificationsMaster:"系统通知",notificationsMasterHint:"允许 Termdock 在隐藏或作为 PWA 安装运行时发送通知。",notificationsPermission:"权限",notificationsTest:"发送测试",notificationsAlertStyle:"提醒方式",notificationsAlertStyleHint:"最终是否横幅弹出仍由浏览器和 Android 系统决定。Termdock 只能请求静默、默认或持续显示等通知选项。",notificationsStyleNormal:"默认",notificationsStyleNormalHint:"允许时声音/震动",notificationsStyleQuiet:"静默",notificationsStyleQuietHint:"仅状态栏,无声音",notificationsStylePersistent:"持续",notificationsStylePersistentHint:"保留到手动关闭",notificationsEvents:"事件",notificationsAiFinished:"AI 任务结束",notificationsAiFinishedHint:"当 Termdock 在后台时,AI agent 停止后发送通知。",notificationsFutureHint:"后续可以在这里继续增加更多通知类型,不需要改变顶层设置布局。",notificationsOffSummary:"系统通知已关闭",notificationsAiOnSummary:"AI 任务结束通知已开启",notificationsNoEventsSummary:"暂无开启的通知事件",notificationsDenied:"浏览器通知权限已被阻止,请在站点设置中开启。",notificationsUnsupported:"通知需要安全上下文和 Service Worker 支持。",notificationsTestBody:"通知已开启。后台 AI 任务结束后会提醒你。",shell:"Shell",tmux:"Tmux",auto:"自动",webgl:"WebGL",canvas:"内置",tmuxServer:"Tmux 服务",tmuxUnavailable:"不可用",noTmuxSessions:"服务端没有 tmux 会话。",installTmuxHint:"请在服务端安装 tmux 后启用。",refresh:"刷新",attached:"已连接",restorable:"可恢复",attach:"连接",attaching:"连接中…",destroy:"销毁",sessions:({n:e})=>`${e} 个会话`,windows:({n:e})=>`${e} 个窗口`,keyboardToolbar:"键盘工具栏",aiAgentDetection:"AI 代理检测",signOut:"退出登录",language:"语言",programNamePlaceholder:"程序名(如 claude)",patternPlaceholder:"正则表达式(如 Thinking|Generating)",statusPlaceholder:"状态",addProgram:"添加程序",addPattern:"添加规则",resetDefaults:"恢复默认",invalidRegex:"无效的正则",removeProgram:"移除程序",removeRule:"移除规则",keepLabel:"保持",customColor:"自定义颜色",tabIndicator:"标签指示器样式",toolbarPresets:"工具栏预设",detectionRules:"检测规则",agentHooksHint:"安装 hooks 后,agent 会主动上报状态:回合进行中(绿)、等你授权/回答(黄)、回合完成(对勾),并在等待你输入时推送通知。hooks 全局安装但只在 termdock 的终端里生效。",agentHooksInstall:"安装",agentHooksInstalled:"已安装",agentHooksOutdated:"需更新",agentHooksNotInstalled:"未安装",agentHooksUninstall:"卸载",agentHooksReinstall:"重新安装",agentHooksDevMode:"开发模式:hooks 指向 TS 源码,需要构建后的版本才能生效",agentHooksTarget:"写入",agentPlugins:"Agent 插件",agentPluginAdd:"添加插件",agentPluginHint:"自定义 agent 的注册和 hooks 配置。粘贴 manifest.json 来注册新 agent,可选安装 hooks。",agentPluginCreate:"创建插件",agentPluginDelete:"删除插件",mobileKeyboard:"移动键盘",saving:"保存中…",rulesHint:"配置正则表达式来识别 AI 工具在终端标签中的状态。每条规则可独立设置标签、颜色、图标样式以及输出静默后指示器保留的时长。停止后若你未查看该标签,标签会保留一个黄色待查看提示。",programsHelp:"支持在一个配置中匹配多个程序,用英文逗号分隔。",programLabelResolution:"程序名识别",rawCommandMapping:"原始命令映射",rawCommandMappingHint:"以下规则将原始命令行映射为标签显示名。用户规则优先于内置规则。",genericProgramNames:"通用程序名",genericProgramNamesHint:"触发 ps 深度识别(如 node, python)",wrapperScriptNames:"包装脚本名",wrapperScriptNamesHint:"CLI 包装器,启动其他工具(如 aiden, npx)",shellNamesConfig:"Shell 名称",shellNamesHint:"从标签显示中过滤(如 bash, zsh)",addTag:"+ 添加",customRules:"自定义规则",addRule:"添加规则",localAccess:"本地访问",localAccessHint:"手机信任本地 CA 后,可通过这个局域网地址访问。请先在手机上打开「手机引导」地址下载 CA 证书。",resetAutoName:"恢复自动",onboardingUrl:"手机引导",httpsActive:"HTTPS 已启用",httpsInactive:"HTTPS 未启用",caMissing:"未配置 CA 下载"},toolbarPresets:{preview:"预览",presets:"预设",label:"标签",new:"新建",reset:"重置",presetLabelPlaceholder:"预设名称",deletePreset:({name:e})=>`删除预设 ${e}`,matchPrograms:"匹配程序",typeEnterHint:"输入后回车",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"纯字符串按大小写不敏感子串匹配。用 /…/flags 包裹则为正则(针对小写程序名测试)。",altSlot:"Alt 修饰键槽",altSlotHint:"在预览中保留一个 Alt 键槽位。",desktopVisibility:"桌面端显示",desktopVisibilityHint:"桌面端只显示该预设的自定义按钮,不显示基础快捷键。",rowLayout:"行布局",rowLayoutHint:"每行按钮数。",addRow:"行",rowN:({n:e})=>`第 ${e} 行`,del:"删",buttons:"按钮",buttonsHint:"点击编辑,使用 ↑↓ 排序。",addButton:"添加按钮",noCustomButtons:"暂无自定义按钮。添加一个来覆盖默认工具栏。",moveUp:"上移",moveDown:"下移",removeRow:({n:e})=>`移除第 ${e} 行`,removeAction:({name:e})=>`移除 ${e}`,labelField:"标签",labelPlaceholder:"按钮上显示的文本",sequence:"序列",sequencePlaceholder:"例如 /undo 或 \\t 或 /||undo",sequenceHint:"双击序列",doubleTap:"双击序列",doubleTapAdd:"+ 添加",doubleTapPlaceholder:"例如 /undo\\r 或 /||undo ||\\r",remove:"移除",noSequence:"无序列",preset:"预设",overCapacityHint:"按钮数超过槽位,多余按钮将使用最后一行的尺寸。"},agentRules:{ruleColors:{green:"绿",yellow:"黄",red:"红",blue:"蓝",purple:"紫",orange:"橙",gray:"灰"}},tab:{session:"会话",new:"新建会话",rename:"重命名",renameHint:"修改标签的显示名称",renamePlaceholder:"留空则恢复默认名称",copyCwd:"复制当前目录",copyCwdHint:"复制当前工作目录",resumeAgent:"恢复 Agent 会话",resumeAgentHint:"用原生 session id 恢复上次对话",copied:"已复制",close:"关闭会话",closeHint:"从列表移除该标签",longPressTip:"提示:按住标签不动约半秒打开操作菜单,按住并拖动可排序。",sessionsTitle:"会话",explorerTitle:"资源管理器"},agent:{aiRunning:"AI 运行中",needsReview:"需要查看",finishedReview:"AI 已完成 — 需要查看",aiWaiting:"AI 等待中",copyMode:"Copy 模式",jumpToNext:"跳到下一个待处理"},connection:{reconnecting:"正在重连…"},terminal:{input:"终端输入",error:"错误",dropFilesToPastePaths:"拖放文件以输入路径"},errorBoundary:{title:"出现了一些问题",unexpected:"发生意外错误",retry:"重试"},error:{type:{network:"网络连接错误",session:"会话错误",terminal:"终端错误",auth:"认证错误",validation:"验证错误",unknown:"未知错误"},severity:{low:"提示:",medium:"警告:",high:"错误:",critical:"严重错误:"},suggestion:{networkCheck:"检查网络连接",networkRetry:"尝试重新连接",networkProxy:"检查代理设置",networkWait:"等待网络恢复",sessionRecreate:"重新创建会话",sessionServer:"检查服务器状态",sessionCache:"清理浏览器缓存",terminalRestart:"重启终端",terminalConfig:"检查终端配置",terminalClear:"清除终端输出",authRelogin:"重新登录",authCredentials:"检查凭证",authAdmin:"联系管理员",validationFormat:"检查输入格式",validationParams:"验证参数",validationDocs:"参考文档",unknownReload:"刷新页面",unknownApp:"重启应用",unknownSupport:"联系技术支持"}}},FR=["en","zh"],Qd="en",Gw="termdock:locale",kg={en:jR,zh:QR};function OR(e){return typeof e=="string"&&FR.includes(e)}function $R(){if(typeof window>"u")return Qd;try{const t=window.localStorage.getItem(Gw);if(OR(t))return t}catch{}return(window.navigator?.language?.toLowerCase()??"").startsWith("zh")?"zh":Qd}const zw=A.createContext(null);function Ux(e,t){const r=t.split(".");let n=e;for(const s of r)if(n&&typeof n=="object"&&s in n)n=n[s];else return;return n}function Gx(e,t){return typeof e=="function"?e(t??{}):typeof e!="string"?String(e):t?e.replace(/\{(\w+)\}/g,(r,n)=>Object.prototype.hasOwnProperty.call(t,n)?String(t[n]):r):e}function HR({children:e}){const[t,r]=A.useState(()=>$R());A.useEffect(()=>{if(!(typeof window>"u")){try{window.localStorage.setItem(Gw,t)}catch{}document.documentElement.lang=t==="zh"?"zh-CN":"en"}},[t]);const n=A.useCallback(u=>{r(u)},[]),s=kg[t]??kg[Qd],i=A.useCallback((u,d)=>{const f=Ux(s,u);if(f===void 0){const b=Ux(kg[Qd],u);return b===void 0?u:Gx(b,d)}return Gx(f,d)},[s]),a=A.useMemo(()=>({locale:t,setLocale:n,t:i}),[t,n,i]);return c.jsx(zw.Provider,{value:a,children:e})}function Qn(){const e=A.useContext(zw);return e||{locale:Qd,setLocale:()=>{},t:t=>t}}function UR({error:e}){const{t}=Qn();return c.jsx("div",{className:"flex h-full items-center justify-center p-4",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:c.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.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"})})}),c.jsxs("div",{className:"space-y-1",children:[c.jsx("h3",{className:"font-medium text-foreground",children:t("errorBoundary.title")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:e?.message||t("errorBoundary.unexpected")})]}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"mt-2 px-5 py-2.5 bg-primary text-primary-foreground text-sm font-medium rounded-full hover:bg-primary/90 active:scale-[0.97] transition-all shadow-sm",children:t("errorBoundary.retry")})]})})}let Ww=class extends P.Component{state={hasError:!1,error:null};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){console.error("Terminal error caught by boundary:",t,r)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:c.jsx(UR,{error:this.state.error}):this.props.children}};function B1(e,t){return e.label.trim().length>0?e.label:`Key ${t+1}`}const xd=12;function GR(){return Vw.map(e=>e.id)}const Vw=[{id:"default",label:"Base",programs:[],includeAlt:!0,rowLayout:[3,3,3],actions:[],showOnDesktop:!1},{id:"opencode",label:"Code",programs:["opencode"],includeAlt:!1,rowLayout:[4],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:[4],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:"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:[3,3],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:[3,2],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 Fd(){return Vw.map(e=>({...e,programs:[...e.programs],includeAlt:e.includeAlt,rowLayout:[...e.rowLayout],actions:e.actions.map(t=>({...t})),showOnDesktop:e.showOnDesktop}))}function U2(e){const t=Array.isArray(e)?e.map(r=>Math.min(20,Math.max(2,Math.floor(r)))).filter(r=>Number.isFinite(r)):[];return t.length>0?t:[3,3]}function qw(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t.length>0?t:null}const G2=/^\/(.+)\/([gimsuy]*)$/;function zx(e){return G2.test(e.trim())}function Jf(e){const t=e.trim().match(G2);if(!t)return null;try{return new RegExp(t[1]??"",t[2]??"")}catch{return null}}function Yw(e){if(typeof e!="string")return null;const t=e.trim();return t?G2.test(t)?Jf(t)?t:null:t.toLowerCase():null}function Wx(e){return e.replace(/\\u([0-9a-fA-F]{4})/g,(t,r)=>String.fromCharCode(Number.parseInt(r,16))).replace(/\\r/g,"\r").replace(/\\n/g,`
|
|
72
72
|
`).replace(/\\t/g," ")}const Vx="||",zR=120;function WR(e){return e.includes(Vx)?e.split(Vx).filter(t=>t.length>0):[e]}function ju(e){const t=new Set,r=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}`,u=t.has(a)?`${a}-${i+1}`:a;return t.add(u),{id:u,label:typeof s.label=="string"&&s.label.trim().length>0?s.label.trim():"Preset",programs:Array.isArray(s.programs)?s.programs.map(d=>Yw(d)).filter(d=>!!d):[],includeAlt:typeof s.includeAlt=="boolean"?!!s.includeAlt:!1,rowLayout:U2(s.rowLayout),showOnDesktop:typeof s.showOnDesktop=="boolean"?!!s.showOnDesktop:!1,actions:Array.isArray(s.actions)?s.actions.map((d,f)=>{const b={id:typeof d.id=="string"&&d.id.trim().length>0?d.id:`${u}-action-${f+1}`,label:typeof d.label=="string"?d.label:`Key ${f+1}`,sequence:typeof d.sequence=="string"?d.sequence:""};return typeof d.doubleTapSequence=="string"&&(b.doubleTapSequence=d.doubleTapSequence),b}):[]}}).filter(s=>s.id!=="auto"),n=Fd()[0];return n&&!r.some(s=>s.id==="default")&&r.unshift(n),r}function VR(e,t){const r=qw(e);if(!r)return"default";for(const n of t)if(n.id!=="default")for(const s of n.programs){const i=Jf(s);if(i){if(i.test(r))return n.id}else if(r.includes(s))return n.id}return"default"}function qx(e,t){return e.find(r=>r.id===t)??e.find(r=>r.id==="default")??Fd()[0]}function qR(e){return[{id:"auto",label:"Auto"},...e.map(t=>({id:t.id,label:t.label}))]}function YR(e){return[{id:"auto",label:"Auto"},...e.filter(t=>t.showOnDesktop===!0).map(t=>({id:t.id,label:t.label}))]}function Zw(e,t){const r=U2(t),n=[];let s=0,i=0;for(;s<e.length;){const a=r[Math.min(i,r.length-1)]??3;n.push({columns:a,items:e.slice(s,s+a)}),s+=a,i+=1}return n}const Kw=28,Xw=({mode:e,presetLabel:t,title:r,ariaLabel:n,disabled:s,onPointerDown:i,buttonRef:a})=>c.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:r,"aria-label":n??r,children:e==="auto"?c.jsx(Ok,{size:14}):(t.charAt(0)||"?").toUpperCase()}),ZR={esc:"\x1B",enter:"\r",home:"\x1B[H",end:"\x1B[F","ctrl-c":"","ctrl-d":"","ctrl-w":"","ctrl-u":""},Yx=8;function KR(e,t){return ZR[e]??null}const XR=({visible:e,interactive:t=!0,presentation:r="mobile",activeModifier:n,lockedModifier:s,disabled:i,defaultShowExtended:a=!1,presetLabel:u,presetModeLabel:d,presetMode:f,presetOptions:b,includeAlt:g,presetRowLayout:y,extraActions:v,onKeyPress:w,onTextPress:T,onPastePress:C,longPressMode:E="arrows",copyFeedback:N="idle",onLongPressModeToggle:D,onModifierToggle:R,onPresetSelect:_,onExpandedChange:M})=>{const[O,H]=P.useState(a),[G,U]=P.useState(!1),W=P.useRef(null),J=r==="desktop-actions",ee=J||O,[ae,Se]=P.useState(!1),[Le,_e]=P.useState(null),se=i||!e||!t,ie=i||!e,fe=P.useRef(null),Qe=P.useRef(null),de=P.useRef(0),Fe=P.useCallback($e=>{if(se)return;const lt=$e.target;if(!(lt instanceof HTMLElement))return;const $t=lt.closest("button"),Ht=$t?.hasAttribute("data-mobile-copy-button")===!0;$t&&!Ht?($e.preventDefault(),jl(Yx)):$t&&jl(Yx)},[se]),rt=P.useCallback($e=>{$e.preventDefault()},[]),ht=P.useCallback($e=>{const lt=$e.target;se||lt instanceof HTMLElement&<.closest("button")&<.blur()},[se]);P.useEffect(()=>{H(a)},[a]),P.useEffect(()=>{J||M?.(O)},[J,M,O]),P.useEffect(()=>{se&&(Qe.current!==null&&(window.clearTimeout(Qe.current.timer),Qe.current=null),Se(!1),_e(null))},[se]),P.useEffect(()=>{e||(Se(!1),_e(null))},[e]),P.useEffect(()=>{if(!ae)return;const $e=()=>{const lt=fe.current?.getBoundingClientRect();lt&&_e({left:Math.max(8,lt.left),top:Math.max(8,lt.top-8)})};return $e(),window.addEventListener("resize",$e),window.addEventListener("scroll",$e,!0),()=>{window.removeEventListener("resize",$e),window.removeEventListener("scroll",$e,!0)}},[ae]);const Ee=P.useCallback(($e,lt)=>{se||($e.preventDefault(),w(lt))},[w,se]),ce=P.useCallback(($e,lt)=>{se||($e.preventDefault(),R(lt))},[R,se]),je=P.useCallback($e=>{se||($e.preventDefault(),H(lt=>{const $t=!lt;return $t&&(U(!0),W.current!==null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{U(!1),W.current=null},350)),$t}))},[se]),De=P.useCallback(()=>{const $e=typeof performance<"u"?performance.now():Date.now();$e-de.current<350||(de.current=$e,C?.())},[C]),ke=P.useCallback($e=>{se||($e.stopPropagation(),$e.pointerType!=="touch"&&($e.preventDefault(),De()))},[se,De]),ge=P.useCallback($e=>{se||($e.preventDefault(),$e.stopPropagation(),De())},[se,De]),Re=P.useCallback($e=>{se||$e.stopPropagation()},[se]),ct=250,Ae=P.useCallback(()=>{Qe.current!==null&&(window.clearTimeout(Qe.current.timer),Qe.current=null)},[]);P.useEffect(()=>()=>{Ae(),W.current!==null&&(window.clearTimeout(W.current),W.current=null)},[Ae]);const Ve=P.useCallback(($e,lt)=>{if(se)return;if($e.preventDefault(),!lt.doubleTapSequence){T(lt.sequence);return}const $t=Qe.current;if($t!==null&&$t.actionId===lt.id){window.clearTimeout($t.timer),Qe.current=null,T(lt.doubleTapSequence);return}Ae();const Ht=window.setTimeout(()=>{Qe.current=null,T(lt.sequence)},ct);Qe.current={actionId:lt.id,timer:Ht}},[Ae,T,se]),We=P.useCallback($e=>{se||($e.preventDefault(),$e.stopPropagation(),D?.())},[D,se]),he=P.useCallback($e=>{se||$e.stopPropagation()},[se]),Be=P.useCallback($e=>{if(se)return;$e.preventDefault();const lt=$e.currentTarget.getBoundingClientRect();_e({left:Math.max(8,lt.left),top:Math.max(8,lt.top-8)}),Se($t=>!$t)},[se]),Ce=P.useCallback(($e,lt)=>{se||($e.preventDefault(),Se(!1),_e(null),_(lt))},[_,se]),nt=v.length>0,kt=P.useMemo(()=>{const $e=[{id:"preset",kind:"preset"}];return!J&&g&&$e.push({id:"alt",kind:"alt"}),nt?$e.concat(v.map(lt=>({id:lt.id,kind:"text",action:lt}))):J?$e:$e.concat([{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"}])},[v,nt,g,J]),vt=P.useMemo(()=>Zw(kt,y),[kt,y]),wt=`${J?"space-y-1":"mt-1 space-y-1"}${G?" pointer-events-none":""}`,Xe=ae&&Le?i0.createPortal(c.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:Le.left,top:Le.top},children:c.jsx("div",{className:"grid gap-1",children:b.map($e=>c.jsx("button",{type:"button",onPointerDown:lt=>Ce(lt,$e.id),tabIndex:-1,disabled:ie,className:`h-7 rounded-full px-3 text-left text-xs font-medium transition-colors disabled:opacity-50 ${$e.id===f?"bg-primary text-primary-foreground":"bg-surface-2 hover:bg-surface-elevated text-muted-foreground hover:text-foreground"}`,children:$e.label},$e.id))})}),document.body):null;return c.jsxs(c.Fragment,{children:[Xe,c.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?J?"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:Fe,onPointerDownCapture:Fe,onContextMenuCapture:rt,onFocusCapture:ht,children:c.jsxs("div",{className:"rounded-2xl bg-surface-elevated p-0.5 space-y-0.5",children:[!J&&c.jsxs("div",{className:"grid grid-cols-10 gap-1",children:[c.jsx("button",{type:"button",onPointerDown:$e=>Ee($e,"esc"),tabIndex:-1,disabled:ie,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"}),c.jsx("button",{type:"button",onPointerDown:$e=>ce($e,"ctrl"),tabIndex:-1,disabled:ie,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${n==="ctrl"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${s==="ctrl"?"ring-2 ring-accent":""}`,children:c.jsx("span",{className:"font-medium",children:s==="ctrl"?"Ctrl*":"Ctrl"})}),c.jsx("button",{type:"button",onPointerDown:$e=>Ee($e,"ctrl-c"),tabIndex:-1,disabled:ie,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"}),c.jsx("button",{type:"button",onPointerDown:$e=>Ee($e,"ctrl-w"),tabIndex:-1,disabled:ie,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-W"}),c.jsx("button",{type:"button",onPointerDown:$e=>Ee($e,"ctrl-u"),tabIndex:-1,disabled:ie,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"}),c.jsx("button",{type:"button",onPointerDown:()=>T("/"),tabIndex:-1,disabled:ie,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.jsx("button",{type:"button",onPointerDown:$e=>Ee($e,"enter"),tabIndex:-1,disabled:ie,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:c.jsx(EL,{size:16})}),c.jsx("button",{type:"button","data-mobile-copy-button":"true",onPointerDown:he,onTouchStart:he,onClick:We,tabIndex:-1,disabled:ie,title:N==="copied"?"Copied":N==="failed"?"Copy failed":E==="copy"?"Long press selects text":"Long press sends arrows","aria-label":E==="copy"?"Switch long press to arrow keys":"Switch long press to copy selection",className:`h-7 w-full rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center ${N==="copied"?"bg-primary/15 text-primary":N==="failed"?"bg-destructive/15 text-destructive":E==="copy"?"bg-primary/15 text-primary":"bg-surface-2"}`,children:N==="copied"?c.jsx(ew,{size:15}):N==="failed"?c.jsx(Ks,{size:15}):E==="copy"?c.jsx(AL,{size:15}):c.jsx(fk,{size:15})}),c.jsx("button",{type:"button","data-mobile-copy-button":"true",onPointerDown:ke,onPointerUp:Re,onTouchStart:Re,onTouchEnd:Re,onClick:ge,tabIndex:-1,disabled:ie,title:"Paste","aria-label":"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:c.jsx(vL,{size:15})}),c.jsx("button",{type:"button",onPointerDown:je,tabIndex:-1,disabled:ie,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?c.jsx(mL,{size:16}):c.jsx(Vl,{size:16})})]}),ee&&c.jsx("div",{className:wt,children:vt.map(($e,lt)=>{const $t=$e.items[0]?.kind==="preset",Ht=Math.max(2,$e.columns),St=$t?`${Kw}px repeat(${Math.max(1,Ht-1)}, minmax(0, 1fr))`:`repeat(${Ht}, minmax(0, 1fr))`;return c.jsx("div",{className:"relative grid gap-1",style:{gridTemplateColumns:St},children:$e.items.map(ut=>ut.kind==="preset"?c.jsx(Xw,{buttonRef:ut.id==="preset"?fe:void 0,mode:f,presetLabel:u,title:d,disabled:ie,onPointerDown:Be},ut.id):ut.kind==="alt"?c.jsx("button",{type:"button",onPointerDown:Oe=>ce(Oe,"alt"),tabIndex:-1,disabled:ie,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${n==="alt"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${s==="alt"?"ring-2 ring-accent":""}`,children:c.jsx("span",{className:"font-medium",children:s==="alt"?"Alt*":"Alt"})},ut.id):ut.kind==="text"?c.jsxs("button",{type:"button",onPointerDown:Oe=>Ve(Oe,ut.action),tabIndex:-1,disabled:ie,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:[ut.action.label,ut.action.doubleTapSequence&&c.jsx("span",{className:"absolute top-0.5 right-1.5 h-1 w-1 rounded-full bg-accent/60"})]},ut.id):c.jsx("button",{type:"button",onPointerDown:Oe=>Ee(Oe,ut.keyName),tabIndex:-1,disabled:ie,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:ut.keyName==="ctrl-d"?"Ctrl-D":ut.keyName==="home"?"Home":"End"},ut.id))},`row-${lt}`)})})]})})]})},JR=({isMobile:e,isInputFocused:t,isIOS:r,isConnecting:n,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 c.jsxs("div",{className:"px-3 py-2 bg-surface text-foreground text-xs border-b border-border/15",children:[c.jsx("div",{className:"font-bold mb-2",children:"Debug Info"}),c.jsxs("div",{className:"grid grid-cols-2 gap-1 font-mono",children:[c.jsxs("div",{children:["isMobile: ",c.jsx("span",{className:e?"text-accent":"text-destructive",children:String(e)})]}),c.jsxs("div",{children:["touchPoints: ",navigator.maxTouchPoints]}),c.jsxs("div",{children:["innerWidth: ",window.innerWidth]}),c.jsxs("div",{children:["innerHeight: ",window.innerHeight]}),c.jsxs("div",{children:["viewportH:"," ",window.visualViewport?Math.round(window.visualViewport.height):"N/A"]}),c.jsxs("div",{children:["inputFocused: ",String(t)]}),c.jsxs("div",{children:["keyboard~: ",a,"px"]}),c.jsxs("div",{children:["connecting:"," ",c.jsx("span",{className:n?"text-muted-foreground":"text-accent",children:String(n)})]}),c.jsxs("div",{children:["sessionId:"," ",c.jsx("span",{className:i?"text-accent":"text-destructive",children:i?"✓":"✗"})]}),c.jsxs("div",{children:["error:"," ",c.jsx("span",{className:s?"text-destructive":"text-accent",children:s?"Yes":"No"})]}),c.jsxs("div",{children:["isIOS:"," ",c.jsx("span",{className:r?"text-muted-foreground":"text-accent",children:String(r)})]})]}),c.jsx("div",{className:"mt-2 pt-2 border-t border-border/15",children:c.jsx("div",{children:"Tip: Tap the status bar 3 times to toggle debug panel"})})]})},eN=/^Reconnecting/i,tN=({connectionError:e,isFatalError:t,isRestarting:r,isConnecting:n,onHardRestart:s})=>{const{t:i}=Qn(),a=!!e&&!t&&eN.test(e);return n&&!e||a?c.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2 pointer-events-none",children:c.jsx("span",{className:"text-[11px] text-muted-foreground/60 animate-pulse tracking-wide",children:e||i("connection.reconnecting")})}):e?c.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2",children:c.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-destructive/70",children:[c.jsx("span",{children:e}),t&&c.jsx("button",{type:"button",onClick:s,disabled:r,className:"text-[11px] text-destructive/90 hover:text-destructive underline underline-offset-2 transition-colors disabled:opacity-40",children:i("common.retry")})]})}):null},rN=120,nN=80,sN=400;function Zx(){if(typeof window>"u")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 r=Number.parseFloat(document.documentElement.style.getPropertyValue("--app-base-vh")||"0")||window.innerHeight,n=Number.parseFloat(document.documentElement.style.getPropertyValue("--safe-bottom-inset")||"0")||0,s=t.height+t.offsetTop;return Math.max(0,Math.round(r-s-n))}function iN(e){const{enabled:t,openThresholdPx:r=rN,closeThresholdPx:n=nN,settleDelayMs:s=sN}=e,i=P.useMemo(()=>Nc("keyboard"),[]),a=P.useRef(!1),u=P.useRef(null),d=P.useRef(0),[f,b]=P.useState({isOpen:!1,isSettled:!1,keyboardHeight:0});return P.useEffect(()=>{if(typeof window>"u"||!t){a.current=!1,u.current!==null&&(clearTimeout(u.current),u.current=null),b(M=>!M.isOpen&&!M.isSettled&&M.keyboardHeight===0?M:{isOpen:!1,isSettled:!1,keyboardHeight:0});return}let g=null;const y=()=>{g=null;const M=Zx();let O=a.current;if(M>=r?O=!0:M<=n&&(O=!1),a.current=O,O){const H=Math.abs(M-d.current);d.current=M,H>10&&(u.current!==null&&clearTimeout(u.current),u.current=setTimeout(()=>{u.current=null,b(G=>G.isSettled?G:{...G,isSettled:!0})},s))}else u.current!==null&&(clearTimeout(u.current),u.current=null);b(H=>{const G=O?H.isSettled:!1;return H.isOpen===O&&H.keyboardHeight===M&&H.isSettled===G?H:(i("sync",{keyboardHeight:M,isOpen:O,isSettled:G,visualViewport:window.visualViewport?{width:Math.round(window.visualViewport.width),height:Math.round(window.visualViewport.height),offsetTop:Math.round(window.visualViewport.offsetTop)}:null}),{isOpen:O,isSettled:G,keyboardHeight:M})})},v=(M="event")=>{(M.includes("visibilitychange")||M.includes("pageshow"))&&i("schedule",{source:M}),g===null&&(g=window.requestAnimationFrame(y))};v("mount");const w=()=>v("resize"),T=()=>v("orientationchange"),C=()=>v("visualViewport.resize"),E=()=>v("visualViewport.scroll"),N=()=>v("viewport-keyboard-change");window.addEventListener("resize",w),window.addEventListener("orientationchange",T),window.visualViewport?.addEventListener("resize",C),window.visualViewport?.addEventListener("scroll",E),document.addEventListener("termdock:viewport-keyboard-change",N);const D=M=>{i("resume",{source:M,keyboardHeight:Zx(),hidden:document.hidden}),v(`${M}:now`),window.setTimeout(()=>v(`${M}:50ms`),50),window.setTimeout(()=>v(`${M}:200ms`),200)},R=()=>{document.hidden||D("visibilitychange")},_=()=>D("pageshow");return document.addEventListener("visibilitychange",R),window.addEventListener("pageshow",_),()=>{window.removeEventListener("resize",w),window.removeEventListener("orientationchange",T),window.visualViewport?.removeEventListener("resize",C),window.visualViewport?.removeEventListener("scroll",E),document.removeEventListener("termdock:viewport-keyboard-change",N),document.removeEventListener("visibilitychange",R),window.removeEventListener("pageshow",_),g!==null&&window.cancelAnimationFrame(g),u.current!==null&&(clearTimeout(u.current),u.current=null)}},[i,t,r,n,s]),f}const oN=320,Kx="termdock:mobile-keyboard-expanded",Xx="termdock:mobile-keyboard-preset-mode",Jx="termdock:mobile-long-press-mode",aN={retry:{maxRetries:60,initialDelayMs:1e3,maxDelayMs:2e4},connectionTimeoutMs:15e3},lN=({sessionId:e,mode:t,tmuxSessionName:r=null,terminalSettings:n=O2(),colorTheme:s="dark",toolbarPresets:i=[],isActive:a=!0,focusRequestToken:u=0,resumeRequestToken:d=0,resumeRequestReason:f="visibility",onKeyboardVisibilityChange:b,showDebug:g,onStatusChange:y})=>{const[v,w]=P.useState(n.fontSize),T=P.useMemo(()=>PR(),[]),C=P.useMemo(()=>Nc("session"),[]),E=P.useMemo(()=>Nc("keyboard"),[]);P.useEffect(()=>{w(n.fontSize)},[n.fontSize]);const N=P.useMemo(()=>({...n,fontSize:v}),[n,v]),[D]=P.useState(e||fC()),[R,_]=P.useState(!1),[M,O]=P.useState(!1),[H,G]=P.useState(!1),[U,W]=P.useState(!1),[J,ee]=P.useState(()=>typeof document>"u"?!0:!document.hidden),[ae,Se]=P.useState(()=>typeof document>"u"?!0:document.hasFocus()),[Le,_e]=P.useState(!1),{isOpen:se,keyboardHeight:ie}=iN({enabled:R&&a}),[fe,Qe]=P.useState(null),[de,Fe]=P.useState(null),[rt,ht]=P.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Kx)==="true"),[Ee,ce]=P.useState(()=>{if(typeof window>"u")return"auto";const ve=window.localStorage.getItem(Xx);return ve&&ve.length>0?ve:"auto"}),[je,De]=P.useState(()=>typeof window>"u"?"arrows":window.localStorage.getItem(Jx)==="copy"?"copy":"arrows"),[ke,ge]=P.useState("idle"),Re=Vn(),ct=Re.sessions,Ae=Re.setTerminalSession,Ve=Re.setConnecting,We=Re.appendToBuffer,he=Re.clearTerminalSession,Be=Re.removeTerminalSession,Ce=Re.clearBuffer,nt=Re.setSessionActiveProgram,kt=Re.setSessionCwd,vt=Re.setSessionCopyMode,wt=Re.setSessionAgentStatus,Xe=Re.setSessionShellTitle,$e=Re.setSessionPromptState,lt=P.useMemo(()=>{if(D)return ct.get(D)},[ct,D]),$t=P.useMemo(()=>`wt-${D.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,12)}`,[D]),Ht=lt?.terminalSessionId??null,St=lt?.mode??"shell",ut=lt?.activeProgram??null,Oe=P.useMemo(()=>ju(i),[i]),Mt=St==="tmux",it=lt?.bufferChunks??[],Me=lt?.isConnecting??!1,ne=Ht,be=t??lt?.mode??"shell",Te=be==="tmux"?r??lt?.tmuxSessionName??null:null,[ue,ot]=P.useState(null),[xt,Rt]=P.useState(!1),[at,qe]=P.useState(!1),[st,mt]=P.useState(0),[Ze,rr]=P.useState(null),Tt=g!==void 0?g:!1,yr=P.useRef(null),cn=P.useRef(null),Vt=P.useRef(null),le=P.useRef(null),Yt=P.useRef(null),et=P.useRef(!1),Ct=P.useRef(null),Fn=P.useRef([]),On=P.useRef(0),lr=P.useRef(!1),Bt=P.useRef(null),nn=P.useRef(null),qn=P.useRef(null),ri=P.useRef(0),Hr=P.useRef(null),Rr=P.useRef(0),un=P.useRef(a),_n=P.useRef(R),Sr=P.useRef(null),sn=P.useRef(null),Dr=P.useRef(null),on=P.useRef(null),Yn=P.useCallback(()=>{Dr.current=null;const ve=sn.current;sn.current=null,ve&&Xe(ve.sessionId,ve.title)},[Xe]),ts=P.useCallback((ve,Je)=>{if(sn.current={sessionId:ve,title:Je},Dr.current===null){if(typeof window>"u"){Yn();return}Dr.current=window.requestAnimationFrame(Yn)}},[Yn]),Fs=P.useCallback(()=>{Dr.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(Dr.current),Dr.current=null,sn.current=null},[]),ks=P.useCallback(async()=>{const ve=be;return(await Q6({preferredFrontendSessionId:D,mode:ve,tmuxSessionName:ve==="tmux"?Te||$t:void 0,termType:"xterm-256color",requireExisting:!0})).terminalSession},[be,Te,$t,D]);P.useEffect(()=>{un.current=a},[a]);const ni=P.useRef(!1);P.useEffect(()=>{if(!a){Yt.current?.blur(),ni.current=!1;return}if(ni.current)return;ni.current=!0;let ve=0,Je=0;ve=requestAnimationFrame(()=>{Je=requestAnimationFrame(()=>{Yt.current?.requestRefresh("page-flip")})});const ft=window.setTimeout(()=>{Yt.current?.requestRefresh("page-flip")},360);return()=>{cancelAnimationFrame(ve),cancelAnimationFrame(Je),window.clearTimeout(ft)}},[a,ne]),P.useEffect(()=>{_n.current=R},[R]);const dn=P.useCallback(()=>{un.current&&Yt.current?.focus()},[]),Cr=P.useCallback(ve=>{typeof window>"u"||typeof document>"u"||!un.current||_n.current||document.hidden||(Sr.current!==null&&window.clearTimeout(Sr.current),Sr.current=window.setTimeout(()=>{if(Sr.current=null,!un.current||_n.current||document.hidden)return;const Je=document.activeElement,ft=Je?.getAttribute("data-terminal-input-anchor")==="true";if((Je instanceof HTMLInputElement||Je instanceof HTMLTextAreaElement||Je instanceof HTMLSelectElement||Je?.isContentEditable===!0)&&!ft){E("desktop resume focus skipped: editable active",{reason:ve});return}E("desktop resume focus",{reason:ve}),Yt.current?.focus()},50))},[E]);P.useEffect(()=>()=>{Sr.current!==null&&typeof window<"u"&&window.clearTimeout(Sr.current),Sr.current=null,on.current!==null&&typeof window<"u"&&window.clearTimeout(on.current),on.current=null},[]);const cr=P.useCallback(()=>{Fr.current=!1,mt(ve=>ve+1)},[]),Kr=P.useCallback(ve=>{const Je=Vt.current;if(Je&&$C(Je)){C("[Terminal] resume probe sent",{reason:ve,backendSessionId:Je,active:un.current});return}C("[Terminal] resume probe missing connection, restarting ensureSession",{reason:ve,backendSessionId:Je,active:un.current}),cr()},[C,cr]),Br=P.useCallback((ve,Je)=>{const ft=Vt.current;ft&&Ct.current!==ve&&(Ct.current=ve,Sb(ft,ve,Je),C("[Terminal] flow-control state sent",{backendSessionId:ft,paused:ve,reason:Je}))},[C]),Qr=P.useCallback((ve,Je)=>{const ft=Vt.current;ft&&Hr.current!==ve&&(Hr.current=ve,HC(ft,ve,Je),C("[Terminal] focus state sent",{backendSessionId:ft,focused:ve,reason:Je}))},[C]),Os=DR({isActive:a,viewportFocused:U,documentVisible:J,windowFocused:ae,streamReady:Le});P.useEffect(()=>{Qr(Os,"logical-focus-change")},[Os,Qr,ne]),P.useEffect(()=>{const ve=Je=>{const Pe=Je.detail;typeof Pe=="number"&&Pe>=8&&Pe<=32&&w(Pe)};return document.addEventListener("termfontchange",ve),()=>document.removeEventListener("termfontchange",ve)},[]),P.useEffect(()=>{const ve=()=>{const Et=!document.hidden;ee(Et),Et&&a&&Cr("visibility")},Je=Et=>{a&&Cr(Et.persisted?"bfcache":"pageshow")},ft=()=>{Se(!0),Cr("window-focus")},Pe=()=>Se(!1);return document.addEventListener("visibilitychange",ve),window.addEventListener("pageshow",Je),window.addEventListener("focus",ft),window.addEventListener("blur",Pe),()=>{document.removeEventListener("visibilitychange",ve),window.removeEventListener("pageshow",Je),window.removeEventListener("focus",ft),window.removeEventListener("blur",Pe)}},[a,Cr]),P.useEffect(()=>{d&&(Yt.current?.requestRefresh(f),Kr("global-resume"))},[d,f,Kr]);const dr=P.useRef(0);P.useEffect(()=>{if(Le){dr.current=0;return}if(!xt||dr.current>=8)return;const Je=dr.current,ft=Math.min(2e3*Math.pow(2,Je),3e4),Pe=setTimeout(()=>{dr.current+=1,C("[Terminal] fatal self-heal: auto restarting ensureSession",{attempt:dr.current,backendSessionId:Vt.current}),ot("Reconnecting..."),Rt(!1),cr()},ft);return()=>clearTimeout(Pe)},[xt,Le,st,C,cr]),P.useEffect(()=>{if(typeof window>"u"){O(!1);return}const ve=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;O(ve)},[]),P.useEffect(()=>{(!a||!R)&&G(!1),a||W(!1)},[a,R]),P.useEffect(()=>{Vt.current=ne,Hr.current=null,Ct.current=null},[ne]),P.useEffect(()=>{Mt||(lr.current=!1,Bt.current=null,nn.current&&(clearTimeout(nn.current),nn.current=null))},[Mt]),P.useEffect(()=>{ne&&Yt.current?.requestRefresh("session-key-change",{force:!0})},[ne]),P.useEffect(()=>{const ve=a&&R&&se;E("visibility signal",{sessionId:D,isActive:a,isMobile:R,isInputFocused:H,isViewportKeyboardOpen:se,viewportKeyboardHeight:ie,visible:ve}),b?.(D,ve)},[b,D,a,R,se,ie,E]),P.useEffect(()=>{a&&u&&u!==ri.current&&(ri.current=u,dn())},[u,dn,a]),P.useEffect(()=>{le.current=D},[D]),P.useEffect(()=>{!R&&(fe!==null||de!==null)&&(Qe(null),Fe(null),qn.current=null)},[R,fe,de]),P.useEffect(()=>{!ne&&(fe!==null||de!==null)&&(Qe(null),Fe(null),qn.current=null)},[ne,fe,de]),P.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Kx,rt?"true":"false")},[rt]),P.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Xx,Ee)},[Ee]),P.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Jx,je)},[je]),P.useEffect(()=>{const ve=()=>{if(typeof window>"u")return!1;const ft=navigator.maxTouchPoints>0||"ontouchstart"in window,Pe=window.innerWidth<768;return ft&&Pe};_(ve());const Je=()=>{_(ve())};return window.addEventListener("resize",Je),()=>window.removeEventListener("resize",Je)},[]);const gr=P.useCallback(()=>{Rr.current+=1,Yn(),Fs();const ve=yr.current;yr.current=null,cn.current=null,_e(!1),Yt.current?.setSessionReady(!1);const Je=Vt.current;Je&&Sb(Je,!1,"stream-disconnect"),et.current=!1,Ct.current=null,Fn.current=[],ve?.()},[Fs,Yn]),Es=P.useCallback(ve=>{if(cn.current===ve){C(`[startStream] Skipping - already connected to ${ve}`);return}C(`[startStream] Starting stream for frontendSessionId=${D} backendSessionId=${ve}`),gr();const Je=Rr.current+1;Rr.current=Je;const ft=T.connect(ve,{onEvent:Pe=>{if(Rr.current!==Je)return;const Et=D;if(Et)switch(Pe.type){case"connected":{(Pe.runtime||Pe.ptyBackend)&&C(`[Terminal] connected frontendSessionId=${Et} backendSessionId=${Vt.current} runtime=${Pe.runtime??"unknown"} pty=${Pe.ptyBackend??"unknown"} cwd=${Pe.cwd??"unknown"}`),Ve(Et,!1),ot(null),Rt(!1),_e(!0),Yt.current?.setSessionReady(!0),Ct.current=null,Br(et.current,"stream-connected"),Pe.tuiProgress!==void 0&&Vn.getState().setSessionTuiProgress(Et,Pe.tuiProgress??null),Pe.shellTitle!==void 0&&Vn.getState().setSessionShellTitle(Et,Pe.shellTitle??null),Pe.promptState!==void 0&&Pe.promptState!==null&&Vn.getState().setSessionPromptState(Et,Pe.promptState);const It=Vn.getState().getTerminalSession(Et);if(It?.terminalSessionId&&Pe.mode&&Vn.getState().setTerminalSession(Et,{sessionId:It.terminalSessionId,cols:80,rows:24,mode:Pe.mode,tmuxSessionName:Pe.tmuxSessionName??null,cwd:Pe.cwd??null}),Pe.activeProgram!==void 0&&nt(Et,Pe.activeProgram??null,Pe.activeProgramSource??null,Pe.activeProgramRaw??null),requestAnimationFrame(()=>{requestAnimationFrame(()=>{Yt.current?.requestRefresh("connected",{force:!0,resizeDebounceMs:0})})}),typeof window<"u"&&un.current&&_n.current&&(window.setTimeout(()=>{Yt.current?.requestRefresh("connected",{force:!0,resizeDebounceMs:0})},120),window.setTimeout(()=>{Yt.current?.requestRefresh("connected",{force:!0,resizeDebounceMs:0})},360)),Pe.mode!=="tmux"&&(rr(null),vt(Et,!1)),C("[Terminal] Connected event received:",{frontendSessionId:Et,backendSessionId:Vt.current,storeHasState:!!It,storeTerminalId:It?.terminalSessionId,hasHistoryInStore:!!It?.history?.length,historyLength:It?.history?.length??0}),It?.history&&It.history.length>0){C(`[Terminal] Restoring ${It.history.length} history chunks to frontend session ${Et}`);const Ar=It.history.reduce((Gr,zr)=>Gr+zr.length,0),vn=Math.max(300,Math.min(2e3,Math.ceil(Ar/200)));On.current=Date.now()+vn,It.history.forEach(Gr=>{We(Et,Gr,{markActivity:!1})}),Vn.getState().setSessionHistory(Et,[]),C(`[Terminal] History restoration complete for ${Et}`)}else C(`[Terminal] No history to restore for ${Et}`);const br=Pe.replayChunks;if(br&&br.length>0){Pe.replayOutOfWindow?(C(`[Terminal] Replay out-of-window, clearing buffer before replay (${br.length} chunks)`),Ce(Et),Yt.current?.clear()):C(`[Terminal] Replay incremental: ${br.length} chunks`);const Ar=br.reduce((Gr,zr)=>Gr+zr.length,0),vn=Math.max(200,Math.min(1500,Math.ceil(Ar/200)));On.current=Math.max(On.current,Date.now()+vn);for(const Gr of br)We(Et,Gr)}break}case"reconnecting":{const It=Pe.attempt??0,br=Pe.maxAttempts??3;ot(`Reconnecting (${It}/${br})...`),Rt(!1);break}case"data":{Pe.data&&(et.current?Fn.current.push(Pe.data):We(Et,Pe.data));break}case"tmux-layout":{rr(Pe.layout??null),Pe.layout&&vt(Et,Pe.layout.inCopyMode);break}case"active-program":{nt(Et,Pe.activeProgram??null,Pe.activeProgramSource??null,Pe.activeProgramRaw??null);break}case"cwd":{kt(Et,Pe.cwd??null);break}case"agent-status":{wt(Et,{agentStatus:Pe.agentStatus??null,agentIndicator:Pe.agentIndicator??null,agent:Pe.agent??null,agentMessage:Pe.agentMessage??null,agentNativeSessionId:Pe.agentNativeSessionId??null,agentRich:Pe.agentRich===!0,agentActivity:Pe.agentActivity??0,agentCwd:Pe.agentCwd??null});break}case"git-status":{Vn.getState().setSessionGitStatus(Et,Pe.gitStatus??null);break}case"focus-mode":{C("[Terminal] focus tracking mode",{backendSessionId:Vt.current,requested:Pe.focusTrackingRequested===!0});break}case"pty-size":{typeof Pe.cols=="number"&&typeof Pe.rows=="number"&&Yt.current?.notifyServerSize(Pe.cols,Pe.rows,Pe.source);break}case"shell-title":{ts(Et,Pe.title??null);break}case"prompt-state":{$e(Et,Pe.state??"idle",Pe.exitCode??null);break}case"tui-progress":{Vn.getState().setSessionTuiProgress(Et,Pe.tuiProgress??null);break}case"exit":{const It=typeof Pe.exitCode=="number"?Pe.exitCode:null,br=typeof Pe.signal=="number"?Pe.signal:null;We(Et,`\r
|
|
73
73
|
[Process exited${It!==null?` with code ${It}`:""}${br!==null?` (signal ${br})`:""}]\r
|
|
74
|
-
`),he(Et),Ve(Et,!1),ot("Terminal session ended"),_e(!1),Rt(!1),rr(null),vt(Et,!1),gr();break}}},onError:(Pe,Et)=>{if(Rr.current!==Je)return;const It=D;if(!It)return;const br=Et?`Connection failed: ${Pe.message}`:Pe.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${Et}):`,br),Pe.message==="Session not found on server"&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:Vt.current,frontendSessionId:It,isActive:a,isMobile:R,fatal:Et,stack:new Error().stack}),ot(br),Rt(!!Et),Et&&(Ve(It,!1),gr(),Pe.message==="Session not found on server"&&(C("[onError] Session lost, auto-recreating"),ot("Reconnecting..."),Rt(!1),he(It),Ce(It),Vt.current=null,Fr.current=!1,setTimeout(()=>{Fr.current=!1,mt(Ar=>Ar+1)},200)))}},aN);yr.current=()=>{ft.close(),Rr.current===Je&&(cn.current=null)},cn.current=ve},[We,Ce,he,C,gr,Br,ts,Ve,nt,wt,vt,kt,$e,T,D]),Fr=P.useRef(!1),hn=P.useRef(0);P.useEffect(()=>()=>{hn.current+=1,Fr.current=!1,gr()},[gr]);const $n=P.useRef(be),ta=P.useRef(Te);P.useEffect(()=>{const ve=$n.current,Je=ta.current;$n.current=be,ta.current=Te,le.current===D&&(ve===be&&Je===Te||(Fr.current=!1,gr(),mt(ft=>ft+1)))},[be,Te,gr,D]),P.useEffect(()=>{if(le.current!==D&&(C(`[useEffect] sessionId changed from ${le.current} to ${D}, allowing reinitialization`),Fr.current=!1),Fr.current&&le.current===D){C(`[useEffect] Already initialized for sessionId=${D}, skipping`);return}C(`[useEffect] Running ensureSession for sessionId=${D}, hasInitialized=${Fr.current}`),Fr.current=!0;const ve=++hn.current;return(async()=>{if(C(`[ensureSession] Starting for sessionId=${D}, runId=${ve}`),!le.current||le.current!==D){C(`[ensureSession] SessionId mismatch or stale run (current=${le.current}, target=${D}), skipping`);return}if(ve!==hn.current){C(`[ensureSession] Stale run detected (runId=${ve}, currentRunId=${hn.current}), skipping`);return}const ft=Vn.getState(),Pe=ft.getTerminalSession(D),Et=Pe?.mode??be;C("[ensureSession] Current state from store:",{terminalSessionId:Pe?.terminalSessionId,mode:Pe?.mode,tmuxSessionName:Pe?.tmuxSessionName,isConnecting:Pe?.isConnecting});let It=Pe?.terminalSessionId??null,br=!It;if(It&&Et!==be?(C(`[ensureSession] Store mode mismatch for ${It}: current=${Et} desired=${be}, will create new session`),br=!0,ft.clearTerminalSession(D),It=null):It&&be==="tmux"&&Te&&Pe?.tmuxSessionName!==Te&&(C(`[ensureSession] Store tmux name mismatch for ${It}: current=${Pe?.tmuxSessionName} desired=${Te}, will create new session`),br=!0,ft.clearTerminalSession(D),It=null),It&&T.checkHealth){C(`[ensureSession] Checking health of existing session ${It}`);try{const Ar=await T.checkHealth(It);if(C("[ensureSession] Health check result:",Ar),!Ar.healthy)C(`[ensureSession] Session ${It} is NOT healthy (healthy=${Ar.healthy}), will create new session`),C("[ensureSession] Health check details:",Ar),br=!0,Ar.mode&&Pe?.terminalSessionId&&ft.setTerminalSession(D,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:Ar.mode,tmuxSessionName:Ar.tmuxSessionName??null}),ft.clearTerminalSession(D),C("[ensureSession] Cleared unhealthy session from store");else{C(`[ensureSession] Session ${It} is healthy, reusing it, cwd=${Ar.cwd}, clients=${Ar.clients}, lastActivity=${Date.now()-(Ar.lastActivity||0)}ms ago`),Ar.mode&&Pe?.terminalSessionId&&ft.setTerminalSession(D,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:Ar.mode,tmuxSessionName:Ar.tmuxSessionName??null}),C(`[ensureSession] Setting terminalIdRef to ${It} and starting stream`),Vt.current=It,Es(It),C(`[ensureSession] Successfully reused healthy session ${It}, returning early`);return}}catch(Ar){C(`[ensureSession] Failed to check health of session ${It}:`,Ar),C("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(C(`[ensureSession] Decision: shouldCreateNewSession=${br}, terminalId=${It}`),br){C(`[ensureSession] Creating new session, shouldCreateNewSession=${br}, runId=${ve}`),ot(null),Rt(!1),ft.setConnecting(D,!0);const vn=Vn.getState().getTerminalSession(D),zr=(vn?.mode??be)===be&&(be!=="tmux"||!Te||vn?.tmuxSessionName===Te);if(vn?.terminalSessionId&&zr)C(`[ensureSession] Race condition avoided: another instance already created session ${vn.terminalSessionId}`),ft.setConnecting(D,!1),It=vn.terminalSessionId,br=!1;else try{const ss=await ks();if(C(`[ensureSession] Opened managed backend session ${ss.sessionId}`),ve!==hn.current){C(`[ensureSession] Stale run after session creation (runId=${ve}, currentRunId=${hn.current}), leaving ${ss.sessionId} for sibling`);return}ft.setTerminalSession(D,ss),C(`[ensureSession] Updated store with new session ${ss.sessionId}`),It=ss.sessionId}catch(ss){if(ve!==hn.current){C("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(ss instanceof N6&&ss.code==="STALE_SESSION_RESTORE_REJECTED"){C("[ensureSession] Dropping stale persisted session:",{sessionId:D,error:ss.message}),ft.clearTerminalSession(D),window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:D,closeMode:"detach"}}));return}ot(ss instanceof Error?ss.message:"Failed to start terminal session"),Rt(!0),ft.setConnecting(D,!1);return}}if(ve!==hn.current){C(`[ensureSession] Stale run before starting stream (runId=${ve}, currentRunId=${hn.current}), skipping`);return}if(!It){C(`[ensureSession] No terminalId, terminalId=${It}`);return}C(`[ensureSession] Starting stream for session ${It}`),Vt.current=It,Es(It),C(`[ensureSession] ensureSession completed for sessionId=${D}, terminalId=${It}`)})(),()=>{C(`[useEffect] Cleanup for sessionId=${D}, runId=${ve}`)}},[D,st,Es,gr,T,C,be,Te,$t]);const vr=P.useCallback(async()=>{if(D&&!at){qe(!0),ot(null),Rt(!1),gr();try{T.forceKill&&await T.forceKill({sessionId:D})}catch{}Be(D),Ce(D),Yt.current?.clear(),await new Promise(ve=>setTimeout(ve,100));try{Ve(D,!0);const ve=await ks();Ae(D,ve),Vt.current=ve.sessionId,Es(ve.sessionId)}catch(ve){ot(ve instanceof Error?ve.message:"Failed to create terminal"),Rt(!0),Ve(D,!1)}finally{qe(!1)}}},[D,at,gr,T,Be,Ce,Ve,Ae,Es,ks]),Xr=P.useCallback((ve,Je)=>{if(!un.current||!ve)return;const ft=/^(\x1b\[<[0-9]+;[0-9]+;[0-9]+[mM])+$/.test(ve),Pe=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(ve);if(Mt&&Pe&&(lr.current=!0),Date.now()<On.current)return;let Et=ve,It=Je?.consumeModifier??!1;if(!Je?.skipModifierTransform&&fe&&ve.length>0){const vn=ve[0];if(vn.length===1&&/[a-zA-Z]/.test(vn)){const Gr=vn.toUpperCase();fe==="ctrl"?(Et=String.fromCharCode(Gr.charCodeAt(0)&31),It=!0):fe==="alt"&&(Et=`\x1B${ve}`,It=!0)}It||(fe==="alt"&&(Et=`\x1B${ve}`),It=!0)}const br=Vt.current;if(!br)return;(async()=>{try{if(Mt&&!ft&&lr.current&&T.tmuxAction){lr.current=!1;try{await T.tmuxAction(br,{action:"copy-mode",enabled:!1})}catch{}}await T.sendInput(br,Et)}catch(vn){ot(vn instanceof Error?vn.message:"Failed to send input")}})(),It&&(de||Qe(null),dn())},[fe,dn,Mt,de,T]);P.useEffect(()=>{const ve=Je=>{if(!un.current)return;const ft=Je,Pe=ft.detail?.text;Pe&&(Yt.current?.sendSequence(Pe),ft.detail?.focus!==!1&&dn())};return window.addEventListener("termdock-insert-reference",ve),()=>window.removeEventListener("termdock-insert-reference",ve)},[dn]);const Jr=P.useCallback((ve,Je)=>{const ft=Vt.current;if(!ft){E("xterm resize push skipped: no terminalId",{cols:ve,rows:Je});return}E("xterm resize push",{cols:ve,rows:Je}),T.resize({sessionId:ft,cols:ve,rows:Je}).catch(Pe=>{Pe&&/session not found/i.test(String(Pe.message||Pe))&&console.warn("[Terminal] resize 404 session not found",{sessionId:ft,cols:ve,rows:Je,stack:new Error().stack})})},[T,E]),Pr=P.useCallback(async ve=>{const Je=Vt.current;if(!(!Je||!T.tmuxAction))try{const ft=await T.tmuxAction(Je,ve);ft.layout&&(rr(ft.layout),ve.action==="switch-session"&&(Ae(D,{sessionId:Je,cols:80,rows:24,mode:"tmux",tmuxSessionName:ft.layout.sessionName}),Lf(D,{tmuxSessionName:ft.layout.sessionName}).catch(Pe=>{console.warn("[Terminal] failed to update inventory after tmux switch",Pe)})))}catch(ft){ot(ft instanceof Error?ft.message:"Failed to execute tmux action")}},[D,Ae,T]);P.useEffect(()=>{if(!Ze||!ne)return;const Je=Ze.windows.find(ft=>ft.id===Ze.activeWindowId)?.panes.find(ft=>ft.id===Ze.activePaneId);Je&&Yt.current?.requestRefresh("tmux-layout",{candidateSize:{cols:Je.width,rows:Je.height},skipScrollToBottom:!0,dedupeKey:`${ne}:${Ze.sessionId}:${Je.id}:${Je.width}x${Je.height}`})},[Ze,ne]);const fn=P.useCallback((ve,Je=5)=>{const ft=Math.max(1,Math.min(Math.floor(Je)||1,40));lr.current=!0;const Pe=Bt.current;if(Pe&&Pe.direction===ve){Pe.lines+=ft;return}Pe&&Pr({action:"scroll",direction:Pe.direction,lines:Pe.lines}).finally(()=>{dn()}),Bt.current={direction:ve,lines:ft},nn.current&&clearTimeout(nn.current),nn.current=setTimeout(()=>{const Et=Bt.current;Et&&(Bt.current=null,Pr({action:"scroll",direction:Et.direction,lines:Et.lines}).finally(()=>{dn()}))},0)},[dn,Pr]),lo=P.useCallback(ve=>{const Je=Date.now(),ft=qn.current,Pe=ft!==null&&ft.modifier===ve&&Je-ft.timestamp<=oN;if(qn.current={modifier:ve,timestamp:Je},de===ve){Fe(null),Qe(null);return}if(Pe){Fe(ve),Qe(ve);return}de!==null&&de!==ve&&Fe(null),Qe(Et=>Et===ve?null:ve)},[de]),co=P.useCallback(ve=>{if(W(ve&&un.current),E("input focus changed",{focused:ve,isActive:un.current,isMobile:_n.current}),!_n.current||!un.current){G(!1);return}G(Je=>Je===ve?Je:ve)},[E]),Ur=P.useCallback(ve=>{if(et.current=ve,Br(ve,"viewport-watermark"),!ve&&Fn.current.length>0){const Je=D;if(Je){const ft=Fn.current;Fn.current=[];for(const Pe of ft)We(Je,Pe)}}},[We,Br,D]),_r=P.useCallback(ve=>{un.current&&Yt.current?.ensureSizeMatches(ve)},[]),Hn=P.useRef(null);P.useEffect(()=>{if(!a)return;const ve=Hn.current;if(!ve)return;const Je=()=>_r("pointerdown"),ft=()=>_r("keydown"),Pe=()=>_r("touchstart"),Et=()=>_r("wheel");return ve.addEventListener("pointerdown",Je),ve.addEventListener("keydown",ft),ve.addEventListener("touchstart",Pe,{passive:!0}),ve.addEventListener("wheel",Et,{passive:!0}),()=>{ve.removeEventListener("pointerdown",Je),ve.removeEventListener("keydown",ft),ve.removeEventListener("touchstart",Pe),ve.removeEventListener("wheel",Et)}},[a,_r]);const Mo=P.useCallback(ve=>{Yt.current=ve},[]),si=P.useCallback(ve=>{const Je=KR(ve);if(!Je)return;const ft=fe!==null;Yt.current?.sendSequence(Je,{consumeModifier:ft})},[fe]),Ai=P.useCallback(ve=>{const Je=WR(ve);if(Je.length===0)return;const ft=fe!==null;Yt.current?.sendSequence(Wx(Je[0]),{consumeModifier:ft});for(let Pe=1;Pe<Je.length;Pe+=1){const Et=Je[Pe];window.setTimeout(()=>{Yt.current?.sendSequence(Wx(Et))},zR*Pe)}},[fe]),ms=P.useCallback(()=>{Yt.current?.pasteClipboardText()},[]),rs=Me||ue!==null,yn=P.useRef(ut);rs||(yn.current=ut);const Is=rs?yn.current:ut,ii=P.useMemo(()=>VR(Is,Oe),[Is,Oe]),oi=P.useMemo(()=>qx(Oe,Ee),[Ee,Oe]),Sn=!R&&Ee!=="auto"&&oi.showOnDesktop!==!0?"auto":Ee,uo=Sn==="auto"?ii:Sn,ai=P.useMemo(()=>qx(Oe,uo),[uo,Oe]),Mn=P.useMemo(()=>ai.actions.filter(ve=>ve.sequence.trim().length>0).map((ve,Je)=>({...ve,label:B1(ve,Je)})),[ai.actions]),Ti=P.useMemo(()=>qw(ut),[ut]),Ei=ai.label,nr=P.useMemo(()=>Sn!=="auto"?`Manual preset: ${ai.label}`:Ti?`Auto preset · ${ai.label} (${Ti})`:"Auto preset",[Ti,Sn,ai.label]),Ii=P.useCallback(ve=>{ce(ve)},[]),li=P.useCallback(()=>{De(ve=>ve==="copy"?"arrows":"copy"),ge("idle")},[]),us=P.useCallback(()=>{typeof window>"u"||(on.current!==null&&window.clearTimeout(on.current),on.current=window.setTimeout(()=>{on.current=null,ge("idle")},1200))},[]),Lr=P.useCallback(ve=>{on.current!==null&&typeof window<"u"&&(window.clearTimeout(on.current),on.current=null),ge(ve?"copied":"failed"),us()},[us]),Ms=P.useCallback(ve=>{ht(ve)},[]),Yi=P.useMemo(()=>R?qR(Oe):YR(Oe),[R,Oe]),en=P.useMemo(()=>MR(s),[s]),pn=P.useMemo(()=>`terminal::${D}`,[D]);P.useEffect(()=>{y?.({isConnecting:Me,isRestarting:at,hasError:!!ue,sessionId:ne})},[Me,at,ue,ne,y]);const Ln=!ne||Me||at,Si=P.useCallback((ve,Je)=>{if(Ln)return;const ft=Math.max(1,Math.min(Math.floor(Je)||1,40));fn(ve,ft)},[fn,Ln]);P.useEffect(()=>{if(!a||!R)return;Yt.current?.requestRefresh("resize",{resizeDebounceMs:0,skipScrollToBottom:!se,force:!0})},[a,R,se,ie,D]),P.useEffect(()=>{if(!a||!R)return;const ve=Je=>{const ft=Je.detail;Yt.current?.requestRefresh("resize",{resizeDebounceMs:0,skipScrollToBottom:ft?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",ve),()=>{document.removeEventListener("termdock:viewport-keyboard-change",ve)}},[a,R,D]);const ns=R||ai.showOnDesktop===!0,Zi=a,ds=R?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,gs=R?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0;return c.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:ds,children:[Tt&&c.jsx(JR,{isMobile:R,isInputFocused:H,isIOS:M,isConnecting:Me,connectionError:ue,terminalSessionId:ne}),c.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:en.background,...gs},children:[c.jsx("div",{ref:Hn,className:"h-full w-full box-border",children:c.jsx(Ww,{fallback:c.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[c.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:c.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.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"})})}),c.jsx("span",{className:"text-sm text-muted-foreground",children:"Terminal component failed to load"})]})}),children:c.jsx(kR,{ref:Mo,sessionKey:pn,chunks:it,onInput:Xr,onResize:Jr,onFlowControl:Ur,onTmuxScroll:Mt?Si:void 0,tmuxScrollSensitivity:.38,onDoubleTap:R?()=>{Yt.current?.sendSequence(" ")}:void 0,onInputFocusChange:co,onMobileLongPressCopyResult:Lr,terminalSettings:N,theme:en,enableTouchScroll:R,mobileLongPressMode:je,autoFocus:!R},pn)})}),c.jsx(tN,{connectionError:ue,isFatalError:xt,isRestarting:at,isConnecting:Me,onHardRestart:vr})]}),c.jsx(XR,{visible:ns,interactive:Zi,presentation:R?"mobile":"desktop-actions",activeModifier:fe,lockedModifier:de,disabled:Ln,defaultShowExtended:rt,presetLabel:Ei,presetModeLabel:nr,presetMode:Sn,presetOptions:Yi,includeAlt:ai.includeAlt,presetRowLayout:ai.rowLayout,extraActions:Mn,onKeyPress:si,onTextPress:Ai,onPastePress:R?ms:void 0,longPressMode:je,copyFeedback:ke,onLongPressModeToggle:li,onModifierToggle:lo,onPresetSelect:Ii,onExpandedChange:Ms})]})},cN=1e3,uN=2e4,dN=9e4,hN=5e3,Yr={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let tf=0,Uu=null;function fN(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function Jw(){Yr.idleCloseTimer&&(clearTimeout(Yr.idleCloseTimer),Yr.idleCloseTimer=null)}function pN(){Jw(),!(Yr.ws&&Yr.ws.readyState===WebSocket.OPEN)&&(Yr.idleCloseTimer=setTimeout(()=>{Yr.idleCloseTimer=null,Yr.listeners.size===0&&mN()},hN))}function mN(){if(Yr.ws){try{Yr.ws.close()}catch{}Yr.ws=null}Uu&&(clearInterval(Uu),Uu=null)}function ey(){if(Yr.reconnectTimer)return;const e=Math.min(cN*Math.pow(2,Yr.reconnectAttempt),uN);Yr.reconnectAttempt+=1,Yr.reconnectTimer=setTimeout(()=>{Yr.reconnectTimer=null,e4()},e)}function e4(){const e=fN();if(!e||Yr.ws&&Yr.ws.readyState===WebSocket.OPEN)return;let t;try{t=new WebSocket(e)}catch{ey();return}Yr.ws=t,t.onopen=()=>{Yr.reconnectAttempt=0,tf=Date.now(),Uu||(Uu=setInterval(()=>{if(!(!Yr.ws||Yr.ws.readyState!==WebSocket.OPEN)&&tf>0&&Date.now()-tf>dN)try{Yr.ws.close()}catch{}},3e4),Uu.unref?.())},t.onmessage=r=>{tf=Date.now();let n=null;try{n=JSON.parse(r.data)}catch{return}if(!n)return;if(n.type==="config-updated"){if(n.key!=="toolbar-presets"&&n.key!=="agent-rules"&&n.key!=="program-detection")return;const i={type:"config-updated",key:n.key,updatedAt:typeof n.updatedAt=="number"?n.updatedAt:void 0};for(const a of Yr.listeners)try{a(i)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(n.type!=="client-state"||!n.state)return;const s={type:"client-state",clientState:{sessions:Array.isArray(n.state.sessions)?n.state.sessions:[],updatedAt:typeof n.state.updatedAt=="number"?n.state.updatedAt:Date.now()},inventory:n.inventory,seq:typeof n.seq=="number"?n.seq:void 0};for(const i of Yr.listeners)try{i(s)}catch(a){console.error("[clientStateSync] listener threw:",a)}},t.onclose=()=>{Yr.ws===t&&(Yr.ws=null),Yr.listeners.size>0&&ey()},t.onerror=()=>{}}function t4(e){return Yr.listeners.add(e),Jw(),Yr.ws||e4(),()=>{Yr.listeners.delete(e),Yr.listeners.size===0&&pN()}}const Eg="termdock-sessions",P1="termdock-active-session",z2="termdock-sessions-cache";function ty(){try{const e=localStorage.getItem(P1);return e&&e.trim().length>0?e:null}catch{return null}}function Tu(e){try{e?localStorage.setItem(P1,e):localStorage.removeItem(P1)}catch{}}function gN(){if(typeof window>"u")return null;try{const e=localStorage.getItem(z2);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="object"&&r!==null&&typeof r.sessionId=="string"&&typeof r.name=="string"):null}catch{return null}}function mc(e){if(!(typeof window>"u"))try{localStorage.setItem(z2,JSON.stringify(e))}catch{}}function ry(){if(!(typeof window>"u"))try{localStorage.removeItem(z2)}catch{}}function r4(e){return e.map(t=>({...t,mode:t.mode==="tmux"?"tmux":"shell",tmuxSessionName:t.tmuxSessionName??null,customName:t.customName===!0}))}function ny(e){return r4(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,r)=>({...t,activeProgram:e[r]?.activeProgram??null,cwd:e[r]?.cwd??null}))}function sy(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 iy(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function bN(){const e=A.useRef(gN()).current,t=A.useRef(ty()).current,[r,n]=A.useState(e??[]),[s,i]=A.useState(null),[a,u]=A.useState(e&&e.length>0?iy(e,t):t),[d,f]=A.useState(e===null),b=A.useRef(!1),g=A.useRef(null),y=A.useRef(e===null),v=A.useRef(0);A.useEffect(()=>{y.current=d},[d]),A.useEffect(()=>{g.current=a},[a]);const w=A.useCallback(J=>{const ee=iy(J,g.current??ty());return u(ae=>ae===ee?ae:ee),Tu(ee),g.current=ee,ee},[]),T=A.useCallback((J,ee)=>{n(ae=>sy(ae)===sy(J)?ae:J),mc(J),ee?.reconcileActive&&w(J)},[w]),C=A.useCallback((J,ee)=>{i(J),T(ny(J.clientSessions),ee)},[T]),E=A.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(Eg)?(localStorage.removeItem(Eg),ry(),Tu(null),n([]),u(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),N=A.useCallback(async()=>{if(typeof window>"u")return[];try{const J=await ZC();C(J,{reconcileActive:!0});const ee=ny(J.clientSessions);return ee.length>0?ee:E()}catch(J){console.error("Failed to restore sessions from server:",J);try{return E()}catch(ee){console.error("Failed to discard legacy local sessions:",ee)}}finally{f(!1)}return[]},[C,E]),D=A.useCallback(async J=>{const ee=await Q6(J);return C(ee.inventory),u(ee.session.sessionId),Tu(ee.session.sessionId),ee},[C]),R=A.useCallback(async J=>{n(ee=>{const ae=ee.filter(Le=>Le.sessionId!==J),Se=g.current===J?ae[0]?.sessionId??null:g.current;return u(Se),Tu(Se),mc(ae),ae});try{await XC(J)}catch(ee){console.error("Failed to remove session from inventory:",ee)}},[]),_=A.useCallback(J=>{const ee=Date.now();n(ae=>{const Se=ae.map(Le=>Le.sessionId===J?{...Le,lastActivity:ee}:Le);return mc(Se),Se})},[]),M=A.useCallback(J=>{u(J),Tu(J)},[]),O=A.useCallback(async(J,ee)=>{const ae=ee.trim();if(ae){n(Se=>{const Le=Se.map(_e=>_e.sessionId===J?{..._e,name:ae,customName:!0}:_e);return mc(Le),Le});try{const Se=await Lf(J,{name:ae,customName:!0});C(Se)}catch(Se){console.error("Failed to rename session in inventory:",Se)}}},[C]),H=A.useCallback(async J=>{n(ee=>{const ae=ee.map(Se=>Se.sessionId===J?{...Se,customName:!1}:Se);return mc(ae),ae});try{const ee=await Lf(J,{customName:!1});C(ee)}catch(ee){console.error("Failed to reset session name in inventory:",ee)}},[C]),G=A.useCallback(async J=>{n(ee=>{const ae=new Map(ee.map(ie=>[ie.sessionId,ie])),Se=J.map(ie=>ae.get(ie)).filter(ie=>ie!==void 0),Le=new Set(J),_e=ee.filter(ie=>!Le.has(ie.sessionId)),se=[...Se,..._e];return mc(se),se});try{const ee=await KC(J);C(ee)}catch(ee){console.error("Failed to reorder sessions in inventory:",ee)}},[C]),U=A.useCallback(async()=>{n([]),i(null),u(null),Tu(null),ry(),typeof window<"u"&&localStorage.removeItem(Eg);try{await JC()}catch(J){console.error("Failed to clear session inventory:",J)}},[]),W=A.useCallback(async(J,ee)=>{n(ae=>{const Se=ae.map(Le=>Le.sessionId===J?{...Le,backendSessionId:ee}:Le);return mc(Se),Se});try{const ae=await Lf(J,{backendSessionId:ee});C(ae)}catch(ae){console.error("Failed to update session backend in inventory:",ae)}},[C]);return A.useEffect(()=>{b.current||(b.current=!0,N())},[N]),A.useEffect(()=>t4(ee=>{if(ee.type!=="client-state"||y.current)return;const ae=typeof ee.seq=="number"?ee.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(ee.inventory){C(ee.inventory,{reconcileActive:!0});return}const Se=r4(ee.clientState.sessions||[]);T(Se,{reconcileActive:!0})}),[C,T]),{sessions:r,inventory:s,activeSessionId:a,isLoading:d,openSession:D,removeSession:R,updateSessionActivity:_,setActiveSession:M,updateSessionBackendId:W,renameSession:O,resetSessionCustomName:H,reorderSessions:G,clearAllSessions:U,restoreSessions:N}}function Zr(e,t){if(typeof window>"u")return null;try{const r=window.localStorage.getItem(e);if(r===null||r==="")return null;const n=JSON.parse(r);return t(n)?n:null}catch{return null}}function ir(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}const kd=new Map,Ed=new Map,Pf=new Map;function Od(e,t,r){if(typeof window>"u")return;const n=Date.now(),s=Pf.get(e)??0,i=n-s;if(i>=r){Pf.set(e,n),ir(e,t);return}if(Ed.set(e,t),kd.has(e))return;const a=r-i,u=setTimeout(()=>{kd.delete(e);const d=Ed.get(e);Ed.delete(e),Pf.set(e,Date.now()),d!==void 0&&ir(e,d)},a);kd.set(e,u)}function yd(e){const t=kd.get(e);t&&(clearTimeout(t),kd.delete(e));const r=Ed.get(e);r!==void 0&&(Ed.delete(e),Pf.set(e,Date.now()),ir(e,r))}function xN(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}const n4="termdock:right-sidebar:tabs-by-root:v1",s4="termdock:right-sidebar:explorer-roots:v1",i4="termdock:right-sidebar:pinned-explorer-roots:v1",o4="termdock:right-sidebar:selected-files:v1",a4="termdock:right-sidebar:show-hidden-files:v1",j1="termdock-sidebar-group-by-folder",l4="termdock-sidebar-collapsed-folder-groups",c4="termdock-left-sidebar-pinned",u4="termdock-left-sidebar-width";function yN(){if(typeof window>"u")return!1;try{const e=window.localStorage.getItem(c4);return e!==null?e==="1":window.matchMedia("(min-width: 1024px)").matches}catch{return!1}}function oy(e){if(!(typeof window>"u"))try{window.localStorage.setItem(c4,e?"1":"0")}catch{}}function vN(){if(typeof window>"u")return 300;try{const e=window.localStorage.getItem(u4);if(!e)return 300;const t=parseInt(e,10);return Number.isFinite(t)&&t>=200&&t<=500?t:300}catch{return 300}}function wN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(u4,String(e))}catch{}}function AN(){if(typeof window>"u")return!0;try{const e=window.localStorage.getItem(j1);return e===null?!0:e==="1"}catch{return!0}}function ay(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(j1,"1"):window.localStorage.setItem(j1,"0")}catch{}}function TN(){if(typeof window>"u")return new Set;try{const e=window.localStorage.getItem(l4);if(!e)return new Set;const t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function SN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(l4,JSON.stringify([...e]))}catch{}}function CN(e){return e==="git"||e==="files"||e==="diff"||e==="file"}function _N(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(CN)}function d4(){return Zr(n4,_N)??{}}function LN(e,t){e&&ir(n4,{...d4(),[e]:t})}function kN(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function EN(){return Zr(s4,kN)??{}}function ly(e){ir(s4,e)}function IN(e){return e!==null&&typeof e=="object"&&typeof e.path=="string"&&(e.kind==="file"||e.kind==="directory")}function MN(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"||IN(r)))}function RN(e){const t=new Set,r=[];for(const n of e){const s=typeof n=="string"?{path:n,kind:"directory"}:n;!s.path||t.has(s.path)||(t.add(s.path),r.push(s))}return r}function NN(){const e=Zr(i4,MN)??{},t={};for(const[r,n]of Object.entries(e))t[r]=RN(n);return t}function cy(e){ir(i4,e)}function DN(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function h4(){return Zr(o4,DN)??{}}function uy(e,t){if(!e)return;const r={...h4()};t?r[e]=t:delete r[e],ir(o4,r)}function BN(e){return typeof e=="boolean"}function PN(){return Zr(a4,BN)??!1}function jN(e){const t=e.replace(/\/+$/,"")||"/";return t==="/"?"/":t.slice(0,t.lastIndexOf("/"))||"/"}function id(e,t){const r=e.replace(/\/+$/,"")||"/";return t===r||t.startsWith(`${r}/`)}function QN(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name))}function FN(e){return e.entry?{name:e.entry.name,path:e.entry.path,type:e.entry.type,isSymlink:e.entry.isSymlink,expanded:!1,loaded:!1,children:e.entry.type==="directory"?[]:void 0}:null}const dt=R6(e=>({leftOpen:!1,rightOpen:!1,leftPinned:yN(),leftSidebarWidth:vN(),rightTab:"files",rightSearchOpen:!1,rootPath:null,explorerRoot:null,explorerRootCache:EN(),pinnedExplorerRootsCache:NN(),expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,showHiddenFiles:PN(),groupByFolder:AN(),collapsedGroups:TN(),changedFiles:new Map,fileChangeVersions:new Map,gitBundleLoading:!1,gitBundleSlow:!1,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 r=!t.leftPinned;return oy(r),{leftPinned:r,leftOpen:!0}}),setLeftPinned:t=>e(()=>(oy(t),{leftPinned:t})),setLeftSidebarWidth:t=>e(r=>{const n=Math.min(Math.max(t,200),500);return r.leftSidebarWidth===n?r:(wN(n),{leftSidebarWidth:n})}),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(r=>(LN(r.rootPath,t),{rightTab:t})),openRightSearch:()=>e({rightSearchOpen:!0}),closeRightSearch:()=>e({rightSearchOpen:!1}),setRightSearchOpen:t=>e({rightSearchOpen:t}),setRootPath:t=>e(r=>{if(r.rootPath===t)return r;const n=new Map(r.projectStateCache);r.rootPath&&n.set(r.rootPath,{rightTab:r.rightTab,explorerRoot:r.explorerRoot,expandedPaths:new Set(r.expandedPaths),selectedFilePath:r.selectedFilePath,directoryCache:new Map(r.directoryCache),changedFiles:new Map(r.changedFiles),gitBundleError:r.gitBundleError,gitBundleLastLoadedAt:r.gitBundleLastLoadedAt,gitBundleCacheInfo:r.gitBundleCacheInfo});const s=t?n.get(t):void 0,i=t?d4()[t]:void 0,a=t?r.explorerRootCache[t]:void 0,u=t?h4()[t]:void 0;return{rootPath:t,rightTab:s?.rightTab??i??"files",explorerRoot:s?.explorerRoot??a??t,expandedPaths:s?new Set(s.expandedPaths):new Set,selectedFilePath:s?.selectedFilePath??u??null,directoryCache:s?new Map(s.directoryCache):new Map,changedFiles:s?new Map(s.changedFiles):new Map,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleError:s?.gitBundleError??null,gitBundleLastLoadedAt:s?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:s?.gitBundleCacheInfo??null,projectStateCache:n}}),setExplorerRoot:t=>e(r=>{if(r.explorerRoot===t)return r;const n={...r.explorerRootCache};return r.rootPath&&t&&(n[r.rootPath]=t,ly(n)),{explorerRoot:t,explorerRootCache:n}}),resetExplorerToProject:()=>e(t=>{if(t.explorerRoot===t.rootPath)return t;const r={...t.explorerRootCache};return t.rootPath&&(r[t.rootPath]=t.rootPath,ly(r)),{explorerRoot:t.rootPath,explorerRootCache:r}}),pinExplorerRoot:(t,r="directory")=>e(n=>{if(!n.rootPath||!t)return n;const s=n.pinnedExplorerRootsCache[n.rootPath]??[];if(s.some(a=>a.path===t))return n;const i={...n.pinnedExplorerRootsCache,[n.rootPath]:[{path:t,kind:r},...s].slice(0,12)};return cy(i),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:t=>e(r=>{if(!r.rootPath||!t)return r;const n=r.pinnedExplorerRootsCache[r.rootPath]??[];if(!n.some(a=>a.path===t))return r;const s=n.filter(a=>a.path!==t),i={...r.pinnedExplorerRootsCache};return s.length>0?i[r.rootPath]=s:delete i[r.rootPath],cy(i),{pinnedExplorerRootsCache:i}}),toggleExpanded:t=>e(r=>{const n=new Set(r.expandedPaths);return n.has(t)?n.delete(t):n.add(t),{expandedPaths:n}}),selectFile:t=>e(r=>(uy(r.rootPath,t),{selectedFilePath:t})),toggleShowHiddenFiles:()=>e(t=>{const r=!t.showHiddenFiles;ir(a4,r);const n=new Map(t.projectStateCache);for(const[s,i]of n)n.set(s,{...i,directoryCache:new Map});return{showHiddenFiles:r,directoryCache:new Map,projectStateCache:n}}),toggleGroupByFolder:()=>e(t=>{const r=!t.groupByFolder;return ay(r),{groupByFolder:r}}),setGroupByFolder:t=>e(r=>r.groupByFolder===t?r:(ay(t),{groupByFolder:t})),toggleGroupCollapsed:t=>e(r=>{const n=new Set(r.collapsedGroups);return n.has(t)?n.delete(t):n.add(t),SN(n),{collapsedGroups:n}}),setDirectoryCache:(t,r)=>e(n=>{const s=new Map(n.directoryCache);return s.set(t,r),{directoryCache:s}}),invalidateDirectoryCache:(t,r=!1)=>e(n=>{const s=new Map(n.directoryCache);for(const i of s.keys())(i===t||r&&id(t,i))&&s.delete(i);return{directoryCache:s}}),applyFileWatchEvents:t=>e(r=>{if(t.length===0)return r;const n=new Map(r.directoryCache),s=new Map(r.fileChangeVersions);let i=r.selectedFilePath,a=!1,u=!1;const d=f=>{s.set(f,(s.get(f)??0)+1),u=!0};for(const f of t){if(f.type==="rescan-required"){for(const T of n.keys())id(f.path,T)&&(n.delete(T),a=!0);i&&id(f.path,i)&&d(i);continue}const b=jN(f.path),g=n.get(b);if(f.type==="deleted"){if(d(f.path),i&&id(f.path,i)&&(i=null,uy(r.rootPath,null)),g){const T=g.filter(C=>C.path!==f.path);T.length!==g.length&&(n.set(b,T),a=!0)}for(const T of n.keys())id(f.path,T)&&(n.delete(T),a=!0);continue}d(f.path);const y=FN(f);if(!y||!g)continue;const v=g.find(T=>T.path===y.path),w=QN(v?g.map(T=>T.path===y.path?{...T,...y,children:T.children}:T):[...g,y]);n.set(b,w),a=!0}return!a&&!u?r:{directoryCache:a?n:r.directoryCache,selectedFilePath:i,fileChangeVersions:u?s:r.fileChangeVersions}}),setChangedFiles:t=>e({changedFiles:t}),setGitBundleLoading:t=>e({gitBundleLoading:t}),setGitBundleSlow:t=>e({gitBundleSlow:t}),setGitBundleError:t=>e({gitBundleError:t}),markGitBundleLoaded:(t=null)=>e({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:t,gitBundleLoading:!1,gitBundleSlow:!1})})),Q1=320,f4=1,ON=Q1+120;function dy(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function rf(e,t){const r=ep(e,t);if(r===null)return;const n=e.wrapperEl;dy(e),n&&(n.style.transitionDuration="0ms");try{const s=e;s.setTransition?.(0),s.setTranslate?.(r),dy(e),n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}catch{n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}}function F1(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 ep(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function $N(e,t){const r=F1(e),n=ep(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=f4}function HN(e){const t=[],r=new Map,n=new Map,s=new Map;for(const i of e){const a=r.get(i.id)??[];if(a.push(i.id),r.set(i.id,a),i.sessionId){const u=n.get(i.sessionId)??[];u.push(i.id),n.set(i.sessionId,u)}if(i.mode==="tmux"&&i.tmuxSessionName){const u=s.get(i.tmuxSessionName)??[];u.push(i.id),s.set(i.tmuxSessionName,u)}}for(const[i,a]of r)a.length>1&&t.push({kind:"frontend",key:i,sessionIds:a});for(const[i,a]of n)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 p4(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function m4(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 UN(e,t){const r=p4(e),n=r.findIndex(s=>s.id===t.id);if(n>=0){const s=[...r];return s[n]=t,s}return[...r,t]}function hy(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const s=r.get(n.sessionId);return{...m4(n),history:s?.history}})}function GN(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function fy(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 py(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function zN(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t)if(e.get(r)!==n)return!1;return!0}function WN(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const r=Date.now().toString(36),n=Math.random().toString(36).slice(2,8);return`wt-${r}${n}`}const VN=({terminalSettings:e=O2(),colorTheme:t="dark",toolbarPresets:r=[],showDebug:n,terminalFocusAvailable:s=!0,defaultSessionMode:i="shell",defaultTmuxSessionName:a="",onStatusChange:u,onSessionDataUpdate:d})=>{const f=A.useMemo(()=>Nc("session"),[]),b=A.useMemo(()=>Nc("terminal"),[]),[g,y]=A.useState([]),[v,w]=A.useState(null),[T,C]=A.useState(!0),[E,N]=A.useState({token:0,reason:"visibility"}),D=A.useRef(!1),R=A.useRef(null),_=A.useRef({}),[M,O]=A.useState(null),H=A.useRef(s),G=A.useRef(!1),U=A.useRef(null),W=A.useRef(null),J=A.useRef(!1),ee=A.useRef(null),ae=A.useRef([]),Se=A.useRef(0),Le=A.useRef(null),_e=A.useRef(!1),se=A.useRef(!0),ie=A.useRef(null),fe=A.useRef("");A.useEffect(()=>{if(typeof window>"u")return;const ne=()=>{const be=navigator.maxTouchPoints>0||"ontouchstart"in window,Te=window.innerWidth<768;J.current=be&&Te};return ne(),window.addEventListener("resize",ne),()=>window.removeEventListener("resize",ne)},[]);const{sessions:Qe,activeSessionId:de,isLoading:Fe,openSession:rt,setActiveSession:ht,removeSession:Ee,renameSession:ce,resetSessionCustomName:je,reorderSessions:De}=bN(),ke=dt(ne=>ne.groupByFolder),ge=dt(ne=>ne.leftOpen||ne.rightOpen),[Re,ct]=A.useState(()=>py(Vn.getState().sessions));A.useEffect(()=>Vn.subscribe(ne=>{const be=py(ne.sessions);ct(Te=>zN(Te,be)?Te:be)}),[]);const{arranged:Ae}=A.useMemo(()=>Uw(g,ne=>Re.get(ne.id)??null,ke,""),[g,Re,ke]),Ve=A.useRef(Ae);Ve.current=Ae,ee.current=v,ae.current=g,Le.current=de,_e.current=Fe,se.current=T,H.current=s;const We=A.useCallback((ne=R.current)=>{const be=Se.current,Te=typeof window<"u"?window.visualViewport:null,ue=ne?F1(ne):null,ot=ne?ep(ne,be):null;return{sessionsLength:ae.current.length,sessionIds:ae.current.map(xt=>xt.id),activeSessionId:ee.current,activeSessionIndex:be,persistedActiveId:Le.current,isLoading:_e.current,isRestoring:se.current,activeIndex:ne?.activeIndex??null,previousIndex:ne?.previousIndex??null,animating:ne?.animating??null,allowTouchMove:ne?.allowTouchMove??null,width:ne?.width??null,translate:ue,targetTranslate:ot,translateDelta:ue!==null&&ot!==null?ue-ot:null,snapGridLength:ne?.snapGrid?.length??null,targetSnap:ne?.snapGrid?.[be]??null,visualViewport:Te?{width:Math.round(Te.width),height:Math.round(Te.height),offsetTop:Math.round(Te.offsetTop)}:null}},[]),he=A.useCallback((ne,be)=>{f(ne,{...We(),...be})},[f,We]);A.useEffect(()=>{Fe||T||v!==de&&ht(v)},[v,Fe,T,de,ht]);const Be=A.useMemo(()=>{if(Ae.length===0||!v)return 0;const ne=Ae.findIndex(be=>be.id===v);return ne>=0?ne:0},[Ae,v]);Se.current=Be;const Ce=A.useCallback(()=>{U.current&&(clearTimeout(U.current),U.current=null)},[]),nt=A.useCallback(ne=>{Ce(),U.current=setTimeout(()=>{U.current=null,G.current=!1,he("[swiper:touch-guard-clear]",{reason:ne})},ON)},[Ce,he]),kt=A.useCallback((ne,be={})=>{const Te=R.current,ue=Se.current,ot=ae.current;if(!Te||ot.length===0||ue<0||ue>=ot.length)return;if(G.current){he("[swiper:sync-skip-touch]",{reason:ne});return}if(Te.animating){he("[swiper:sync-skip-animating]",{reason:ne});return}const xt=F1(Te),Rt=ep(Te,ue),at=xt!==null&&Rt!==null&&Math.abs(xt-Rt)<=f4,qe=Te.activeIndex===ue;if(he("[swiper:sync-check]",{reason:ne,activeIndexAligned:qe,translateAligned:at,immediate:be.immediate===!0}),!(qe&&at)){if(qe){rf(Te,ue),he("[swiper:sync-forced-active]",{reason:ne,translateAligned:at,immediate:be.immediate===!0});return}be.immediate?(rf(Te,ue),Te.slideTo(ue,0,!1),rf(Te,ue)):Te.slideTo(ue,Q1,!1),he("[swiper:sync-applied]",{reason:ne,activeIndexAligned:qe,translateAligned:at,immediate:be.immediate===!0})}},[he]);A.useEffect(()=>{const ne=be=>{const Te=be;R.current&&(R.current.allowTouchMove=!Te.detail.locked),he("[swiper:gesture-lock]",{locked:Te.detail.locked})};return document.addEventListener("termdock:gesture-lock",ne),()=>document.removeEventListener("termdock:gesture-lock",ne)},[he]),A.useEffect(()=>{if(g.length===0){v!==null&&w(null);return}if(!v){w(g[0].id);return}g.some(be=>be.id===v)||w(g[0].id)},[g,v]);const vt=A.useCallback((ne,be)=>{_.current[ne]=be},[]),wt=A.useCallback(ne=>{const be=Ve.current[ne.activeIndex]?.id;if(he("[swiper:slide-change]",{nextSessionId:be??null,instanceActiveIndex:ne.activeIndex}),!be||be===v)return;const Te=!!v&&_.current[v]===!0,ue=H.current&&(!J.current||Te);if(W.current=be,w(be),ue){O({sessionId:be,token:Date.now()});return}O(null)},[g,v,he]);A.useEffect(()=>{if(W.current===v){he("[swiper:sync-skip-swiper-driven]",{activeSessionId:v}),W.current=null;return}kt("active-session-index",{immediate:!0})},[v,Be,g.length,kt,he]),A.useEffect(()=>{const ne=R.current;if(!ne)return;const be=Ae.length>1&&!ge;ne.allowTouchMove!==be&&(ne.allowTouchMove=be,he("[swiper:allow-touch-sync]",{nextAllow:be,sidebarOverlayOpen:ge}))},[Ae.length,he,ge]);const Xe=A.useCallback(ne=>{const be=R.current;if(!be)return;const Te=be.el;if(he("[swiper:layout-before]",{reason:ne,scrollLeft:Te?.scrollLeft??null}),Te&&(Te.scrollLeft=0),be.updateSize(),be.updateSlides(),be.updateProgress(),be.updateSlidesClasses(),Te&&(Te.scrollLeft=0),he("[swiper:layout-after]",{reason:ne,scrollLeft:Te?.scrollLeft??null}),G.current||be.animating){he("[swiper:layout-skip-sync-motion]",{reason:ne});return}kt(`layout:${ne}`,{immediate:!0}),requestAnimationFrame(()=>{const ue=R.current;ue&&(G.current||ue.animating||rf(ue,Se.current))})},[he,kt]);A.useEffect(()=>()=>Ce(),[Ce]);const $e=Ae.map(ne=>ne.id).join("\0");A.useEffect(()=>{requestAnimationFrame(()=>Xe("group-change"))},[ke,$e,Xe]),A.useEffect(()=>{const ne=()=>{requestAnimationFrame(()=>Xe("viewport-change"))};return window.addEventListener("resize",ne),window.visualViewport?.addEventListener("resize",ne),window.visualViewport?.addEventListener("scroll",ne),ne(),()=>{window.removeEventListener("resize",ne),window.visualViewport?.removeEventListener("resize",ne),window.visualViewport?.removeEventListener("scroll",ne)}},[Xe]),A.useEffect(()=>{if(typeof document>"u")return;let ne=null;const be=xt=>{if(xt!=="online"&&document.hidden)return;const Rt=xt==="bfcache"||xt==="online"?xt:"visibility";N(at=>({token:at.token+1,reason:Rt})),requestAnimationFrame(()=>Xe(`resume:${xt}:raf`)),ne&&clearTimeout(ne),ne=setTimeout(()=>{ne=null,Xe(`resume:${xt}:settled`)},320)},Te=()=>{document.hidden||be("visibility")},ue=xt=>{be(xt.persisted?"bfcache":"pageshow")},ot=()=>be("online");return document.addEventListener("visibilitychange",Te),window.addEventListener("pageshow",ue),window.addEventListener("online",ot),()=>{document.removeEventListener("visibilitychange",Te),window.removeEventListener("pageshow",ue),window.removeEventListener("online",ot),ne&&clearTimeout(ne)}},[Xe]),A.useEffect(()=>{const ne=HN(g),be=JSON.stringify(ne);ne.length>0&&be!==fe.current?(fe.current=be,console.warn("[session-invariant] duplicate mapping detected",ne)):ne.length===0&&fe.current&&(fe.current=""),d?.({sessions:g.map(Te=>({id:Te.id,name:Te.name,customName:Te.customName,mode:Te.mode,tmuxSessionName:Te.tmuxSessionName})),activeSessionId:v})},[g,v,d]),A.useEffect(()=>{if(Fe||D.current)return;D.current=!0;const ne=GN(Qe,de),be=p4(Qe.map(m4));if(f("[Session] Restoring",be.length,"persisted sessions (one-shot)"),he("[swiper:restore-start]",{persistedSessionIds:Qe.map(ue=>ue.sessionId),nextActiveSessionId:ne}),be.length>0){const ue=Vn.getState();be.forEach(ot=>{ot.sessionId&&ue.setTerminalSession(ot.id,{sessionId:ot.sessionId,cols:80,rows:24,mode:ot.mode,tmuxSessionName:ot.tmuxSessionName,history:ot.history})}),Qe.forEach(ot=>{ot.activeProgram!=null&&ue.setSessionActiveProgram(ot.sessionId,ot.activeProgram),ot.cwd!=null&&ue.setSessionCwd(ot.sessionId,ot.cwd)}),y(be),w(ne||be[0]?.id||null),he("[swiper:restore-complete]",{restoredSessionIds:be.map(ot=>ot.id),nextActiveSessionId:ne||be[0]?.id||null})}(async()=>(be.length===0&&await ie.current?.({createIfEmpty:!0}),C(!1),requestAnimationFrame(()=>kt("restore-finished",{immediate:!0}))))()},[Fe,Qe,de,f,he,kt]);const lt=A.useRef([]),$t=A.useRef(!1);ee.current=v,A.useEffect(()=>{if(T)return;const ne=lt.current,be=Qe;if(!$t.current){y(qe=>hy(qe,be)),lt.current=be,$t.current=!0;return}const Te=new Set(ne.map(qe=>qe.sessionId)),ue=new Set(be.map(qe=>qe.sessionId)),ot=new Map(ne.map(qe=>[qe.sessionId,qe.name]));lt.current=be,y(qe=>{const st=hy(qe,be);return(!ee.current||!st.some(mt=>mt.id===ee.current))&&w(st[0]?.id??null),st});const xt=be.filter(qe=>!Te.has(qe.sessionId)),Rt=[...Te].filter(qe=>!ue.has(qe)),at=be.filter(qe=>Te.has(qe.sessionId)&&ot.get(qe.sessionId)!==qe.name);(xt.length>0||Rt.length>0||at.length>0)&&f("[Session] Synced persisted sessions:",{newSessionIds:xt.map(qe=>qe.sessionId),removedSessionIds:Rt,renamedSessionIds:at.map(qe=>qe.sessionId),currentSessionIds:be.map(qe=>qe.sessionId)});for(const qe of be){if(!qe.backendSessionId)continue;Vn.getState().setTerminalSession(qe.sessionId,{sessionId:qe.backendSessionId,cols:80,rows:24,mode:qe.mode,tmuxSessionName:qe.tmuxSessionName})}},[Qe,T,f]);const Ht=A.useCallback(async ne=>{try{const be=ne?.mode==="tmux"||ne?.mode==="shell"?ne.mode:i,Te=(ne?.tmuxSessionName||"").trim(),ue=a.trim(),ot=be==="tmux"?Te||ue||WN():null,xt=typeof ne?.cwd=="string"?ne.cwd:null,Rt=v?Vn.getState().sessions.get(v)?.cwd??null:null,at=typeof xt=="string"&&xt.trim().length>0?xt:typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0,qe=await rt({mode:be,tmuxSessionName:ot,cwd:at,termType:"xterm-256color",createIfEmpty:ne?.createIfEmpty===!0}),st=qe.session,mt=qe.terminalSession,Ze={id:st.sessionId,name:st.name,customName:st.customName===!0,sessionId:mt.sessionId,mode:mt.mode??st.mode,tmuxSessionName:mt.tmuxSessionName??st.tmuxSessionName};y(Tt=>UN(Tt,Ze)),w(Ze.id),Vn.getState().setTerminalSession(Ze.id,{sessionId:mt.sessionId,cols:80,rows:24,mode:Ze.mode,tmuxSessionName:Ze.tmuxSessionName,activeProgram:mt.activeProgram,activeProgramRaw:mt.activeProgramRaw,activeProgramSource:mt.activeProgramSource,cwd:mt.cwd}),f("[Session] Inventory opened session:",{frontendSessionId:Ze.id,backendSessionId:mt.sessionId,reused:qe.reused,mode:Ze.mode,tmuxSessionName:Ze.tmuxSessionName})}catch(be){console.error("[Session] Failed to create new session:",be)}},[i,a,v,rt,f]);ie.current=Ht;const St=A.useCallback(ne=>{g.find(Te=>Te.id===ne)&&(w(ne),H.current&&!J.current&&O({sessionId:ne,token:Date.now()}),f("[Session] Switched to session:",ne))},[g,f]),ut=A.useCallback((ne,be)=>{be.trim()&&(y(Te=>Te.map(ue=>ue.id===ne?{...ue,name:be.trim(),customName:!0}:ue)),ce(ne,be.trim()))},[ce]),Oe=A.useCallback(ne=>{y(be=>be.map(Te=>Te.id===ne?{...Te,customName:!1}:Te)),je(ne)},[je]),Mt=A.useCallback(ne=>{y(be=>{const Te=new Map(be.map(Rt=>[Rt.id,Rt])),ue=ne.map(Rt=>Te.get(Rt)).filter(Rt=>Rt!==void 0),ot=new Set(ne),xt=be.filter(Rt=>!ot.has(Rt.id));return[...ue,...xt]}),De(ne),f("[Session] Reordered sessions:",ne),requestAnimationFrame(()=>{R.current?.update()})},[De,f]),it=A.useCallback(async ne=>{const be=typeof ne=="string"?ne:ne.sessionId,Te=typeof ne=="string"?"auto":ne.closeMode??"auto",ue=g.find(ot=>ot.id===be);if(ue){try{Te==="destroy"&&ue.mode==="tmux"&&ue.tmuxSessionName?(await j6(ue.tmuxSessionName),f("[Session] Destroyed tmux session:",{frontendSessionId:ue.id,tmuxSessionName:ue.tmuxSessionName})):ue.sessionId&&(await P6(ue.sessionId),f("[Session] Closed backend terminal:",ue.sessionId))}catch(ot){console.error("[Session] Failed to close backend terminal:",ot);return}y(ot=>{const xt=ot.filter(at=>at.id!==be),Rt=xt.length>0?xt[0].id:null;return w(Rt),xt}),Ee(be),delete _.current[be],f("[Session] Closed session:",{sessionId:be,closeMode:Te})}},[g,Ee,f]),Me=A.useCallback(ne=>{if(!ne)return;const be=g.filter(Te=>Te.sessionId===ne);if(be.length!==0){be.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:ne,frontendSessionIds:be.map(Te=>Te.id)}),y(Te=>{const ue=Te.filter(ot=>ot.sessionId!==ne);return ue.length!==Te.length&&!ue.some(xt=>xt.id===v)&&w(ue.length>0?ue[0].id:null),ue});for(const Te of be)Ee(Te.id),delete _.current[Te.id];f("[Session] Backend gone, dropped local session(s):",be.map(Te=>Te.id))}},[g,v,Ee,f]);return A.useEffect(()=>{const ne=st=>{Ht(st.detail)},be=st=>{St(st.detail)},Te=()=>{const st=ee.current;!st||J.current||O({sessionId:st,token:Date.now()})},ue=st=>{const Ze=st.detail?.direction;if(Ze!=="prev"&&Ze!=="next")return;const rr=Ve.current;if(rr.length<=1)return;const Tt=ee.current,yr=Tt?rr.findIndex(et=>et.id===Tt):-1,le=((yr>=0?yr:0)+(Ze==="next"?1:-1)+rr.length)%rr.length,Yt=rr[le]?.id;Yt&&Yt!==Tt&&St(Yt)},ot=st=>{it(st.detail)},xt=st=>{Me(st.detail)},Rt=st=>{const mt=st;!mt.detail?.sessionId||!mt.detail?.name||ut(mt.detail.sessionId,mt.detail.name)},at=st=>{const mt=st;mt.detail?.sessionId&&Oe(mt.detail.sessionId)},qe=st=>{const mt=st;mt.detail?.sessionIds&&Mt(mt.detail.sessionIds)};return window.addEventListener("new-terminal-session",ne),window.addEventListener("switch-terminal-session",be),window.addEventListener("focus-active-terminal-session",Te),window.addEventListener("cycle-terminal-session",ue),window.addEventListener("close-terminal-session",ot),window.addEventListener("close-terminal-session-by-backend",xt),window.addEventListener("rename-terminal-session",Rt),window.addEventListener("reset-terminal-session-name",at),window.addEventListener("reorder-terminal-session",qe),()=>{window.removeEventListener("new-terminal-session",ne),window.removeEventListener("switch-terminal-session",be),window.removeEventListener("focus-active-terminal-session",Te),window.removeEventListener("cycle-terminal-session",ue),window.removeEventListener("close-terminal-session",ot),window.removeEventListener("close-terminal-session-by-backend",xt),window.removeEventListener("rename-terminal-session",Rt),window.removeEventListener("reset-terminal-session-name",at),window.removeEventListener("reorder-terminal-session",qe)}},[Ht,St,it,Me,ut,Oe,Mt]),c.jsx("div",{className:"h-full flex flex-col",children:c.jsx("div",{className:"flex-1 overflow-hidden",children:c.jsx(sh,{onSwiper:ne=>{R.current=ne,ne.allowTouchMove=Ae.length>1&&!ge,he("[swiper:on-swiper]",{allowTouchMove:ne.allowTouchMove}),requestAnimationFrame(()=>Xe("on-swiper"))},onSlideChange:wt,onTouchStart:(ne,be)=>{const Te=fy(be),ue=Te==="touch"||Te==="pen"||Te==="unknown";b("[swipe:touch-start]",{pointerType:Te,allowed:ue}),he("[swiper:touch-start]",{pointerType:Te,allowed:ue}),ue&&(Ce(),G.current=!0)},onTouchEnd:(ne,be)=>{const Te=fy(be),ue=Te==="touch"||Te==="pen"||Te==="unknown";b("[swipe:touch-end]",{pointerType:Te,allowed:ue}),he("[swiper:touch-end]",{pointerType:Te,allowed:ue}),ue&&nt("touch-end")},onTransitionEnd:()=>{const ne=R.current;if(G.current&&ne&&!$N(ne,Se.current)){he("[swiper:transition-end-deferred]");return}Ce(),G.current=!1,he("[swiper:transition-end]")},initialSlide:Math.max(0,Be),speed:Q1,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:Ae.map(ne=>{const be=ne.id===v;return c.jsx(Ec,{className:"h-full",children:c.jsx(lN,{sessionId:ne.id,mode:ne.mode,tmuxSessionName:ne.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:be,focusRequestToken:M?.sessionId===ne.id?M.token:0,resumeRequestToken:E.token,resumeRequestReason:E.reason,onKeyboardVisibilityChange:vt,showDebug:n,onStatusChange:be?u:void 0})},ne.id)})})})})};function zi(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 qN=typeof Symbol=="function"&&Symbol.observable||"@@observable",my=qN,gy=()=>Math.random().toString(36).substring(7).split("").join("."),YN={INIT:`@@redux/INIT${gy()}`,REPLACE:`@@redux/REPLACE${gy()}`},by=YN;function ZN(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 g4(e,t,r){if(typeof e!="function")throw new Error(zi(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(zi(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(zi(1));return r(g4)(e,t)}let n=e,s=t,i=new Map,a=i,u=0,d=!1;function f(){a===i&&(a=new Map,i.forEach((C,E)=>{a.set(E,C)}))}function b(){if(d)throw new Error(zi(3));return s}function g(C){if(typeof C!="function")throw new Error(zi(4));if(d)throw new Error(zi(5));let E=!0;f();const N=u++;return a.set(N,C),function(){if(E){if(d)throw new Error(zi(6));E=!1,f(),a.delete(N),i=null}}}function y(C){if(!ZN(C))throw new Error(zi(7));if(typeof C.type>"u")throw new Error(zi(8));if(typeof C.type!="string")throw new Error(zi(17));if(d)throw new Error(zi(9));try{d=!0,s=n(s,C)}finally{d=!1}return(i=a).forEach(N=>{N()}),C}function v(C){if(typeof C!="function")throw new Error(zi(10));n=C,y({type:by.REPLACE})}function w(){const C=g;return{subscribe(E){if(typeof E!="object"||E===null)throw new Error(zi(11));function N(){const R=E;R.next&&R.next(b())}return N(),{unsubscribe:C(N)}},[my](){return this}}}return y({type:by.INIT}),{dispatch:y,subscribe:g,getState:b,replaceReducer:v,[my]:w}}function xy(e,t){return function(...r){return t(e.apply(this,r))}}function yy(e,t){if(typeof e=="function")return xy(e,t);if(typeof e!="object"||e===null)throw new Error(zi(16));const r={};for(const n in e){const s=e[n];typeof s=="function"&&(r[n]=xy(s,t))}return r}function b4(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function KN(...e){return t=>(r,n)=>{const s=t(r,n);let i=()=>{throw new Error(zi(15))};const a={getState:s.getState,dispatch:(d,...f)=>i(d,...f)},u=e.map(d=>d(a));return i=b4(...u)(s.dispatch),{...s,dispatch:i}}}var Ig={exports:{}},Mg={};var vy;function XN(){if(vy)return Mg;vy=1;var e=_p();function t(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var r=typeof Object.is=="function"?Object.is:t,n=e.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,u=e.useDebugValue;return Mg.useSyncExternalStoreWithSelector=function(d,f,b,g,y){var v=s(null);if(v.current===null){var w={hasValue:!1,value:null};v.current=w}else w=v.current;v=a(function(){function C(_){if(!E){if(E=!0,N=_,_=g(_),y!==void 0&&w.hasValue){var M=w.value;if(y(M,_))return D=M}return D=_}if(M=D,r(N,_))return M;var O=g(_);return y!==void 0&&y(M,O)?(N=_,M):(N=_,D=O)}var E=!1,N,D,R=b===void 0?null:b;return[function(){return C(f())},R===null?void 0:function(){return C(R())}]},[f,b,g,y]);var T=n(d,v[0],v[1]);return i(function(){w.hasValue=!0,w.value=T},[T]),u(T),T},Mg}var wy;function JN(){return wy||(wy=1,Ig.exports=XN()),Ig.exports}JN();var eD=A.version.startsWith("19"),tD=Symbol.for(eD?"react.transitional.element":"react.element"),rD=Symbol.for("react.portal"),nD=Symbol.for("react.fragment"),sD=Symbol.for("react.strict_mode"),iD=Symbol.for("react.profiler"),oD=Symbol.for("react.consumer"),aD=Symbol.for("react.context"),x4=Symbol.for("react.forward_ref"),lD=Symbol.for("react.suspense"),cD=Symbol.for("react.suspense_list"),W2=Symbol.for("react.memo"),uD=Symbol.for("react.lazy"),dD=x4,hD=W2;function fD(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case tD:switch(e=e.type,e){case nD:case iD:case sD:case lD:case cD:return e;default:switch(e=e&&e.$$typeof,e){case aD:case x4:case uD:case W2:return e;case oD:return e;default:return t}}case rD:return t}}}function pD(e){return fD(e)===W2}function mD(e,t,r,n,{areStatesEqual:s,areOwnPropsEqual:i,areStatePropsEqual:a}){let u=!1,d,f,b,g,y;function v(N,D){return d=N,f=D,b=e(d,f),g=t(n,f),y=r(b,g,f),u=!0,y}function w(){return b=e(d,f),t.dependsOnOwnProps&&(g=t(n,f)),y=r(b,g,f),y}function T(){return e.dependsOnOwnProps&&(b=e(d,f)),t.dependsOnOwnProps&&(g=t(n,f)),y=r(b,g,f),y}function C(){const N=e(d,f),D=!a(N,b);return b=N,D&&(y=r(b,g,f)),y}function E(N,D){const R=!i(D,f),_=!s(N,d,D,f);return d=N,f=D,R&&_?w():R?T():_?C():y}return function(D,R){return u?E(D,R):v(D,R)}}function gD(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...s}){const i=t(e,s),a=r(e,s),u=n(e,s);return mD(i,a,u,e,s)}function bD(e,t){const r={};for(const n in e){const s=e[n];typeof s=="function"&&(r[n]=(...i)=>t(s(...i)))}return r}function O1(e){return function(r){const n=e(r);function s(){return n}return s.dependsOnOwnProps=!1,s}}function Ay(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function y4(e,t){return function(n,{displayName:s}){const i=function(u,d){return i.dependsOnOwnProps?i.mapToProps(u,d):i.mapToProps(u,void 0)};return i.dependsOnOwnProps=!0,i.mapToProps=function(u,d){i.mapToProps=e,i.dependsOnOwnProps=Ay(e);let f=i(u,d);return typeof f=="function"&&(i.mapToProps=f,i.dependsOnOwnProps=Ay(f),f=i(u,d)),f},i}}function V2(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function xD(e){return e&&typeof e=="object"?O1(t=>bD(e,t)):e?typeof e=="function"?y4(e):V2(e,"mapDispatchToProps"):O1(t=>({dispatch:t}))}function yD(e){return e?typeof e=="function"?y4(e):V2(e,"mapStateToProps"):O1(()=>({}))}function vD(e,t,r){return{...r,...e,...t}}function wD(e){return function(r,{displayName:n,areMergedPropsEqual:s}){let i=!1,a;return function(d,f,b){const g=e(d,f,b);return i?s(g,a)||(a=g):(i=!0,a=g),a}}}function AD(e){return e?typeof e=="function"?wD(e):V2(e,"mergeProps"):()=>vD}function TD(e){e()}function SD(){let e=null,t=null;return{clear(){e=null,t=null},notify(){TD(()=>{let r=e;for(;r;)r.callback(),r=r.next})},get(){const r=[];let n=e;for(;n;)r.push(n),n=n.next;return r},subscribe(r){let n=!0;const s=t={callback:r,next:null,prev:t};return s.prev?s.prev.next=s:e=s,function(){!n||e===null||(n=!1,s.next?s.next.prev=s.prev:t=s.prev,s.prev?s.prev.next=s.next:e=s.next)}}}}var Ty={notify(){},get:()=>[]};function v4(e,t){let r,n=Ty,s=0,i=!1;function a(T){b();const C=n.subscribe(T);let E=!1;return()=>{E||(E=!0,C(),g())}}function u(){n.notify()}function d(){w.onStateChange&&w.onStateChange()}function f(){return i}function b(){s++,r||(r=t?t.addNestedSub(d):e.subscribe(d),n=SD())}function g(){s--,r&&s===0&&(r(),r=void 0,n.clear(),n=Ty)}function y(){i||(i=!0,b())}function v(){i&&(i=!1,g())}const w={addNestedSub:a,notifyNestedSubs:u,handleChangeWrapper:d,isSubscribed:f,trySubscribe:y,tryUnsubscribe:v,getListeners:()=>n};return w}var CD=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",_D=CD(),LD=()=>typeof navigator<"u"&&navigator.product==="ReactNative",kD=LD(),ED=()=>_D||kD?A.useLayoutEffect:A.useEffect,tp=ED();function Sy(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Rg(e,t){if(Sy(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let s=0;s<r.length;s++)if(!Object.prototype.hasOwnProperty.call(t,r[s])||!Sy(e[r[s]],t[r[s]]))return!1;return!0}var ID={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},MD={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},RD={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},w4={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},ND={[dD]:RD,[hD]:w4};function Cy(e){return pD(e)?w4:ND[e.$$typeof]||ID}var DD=Object.defineProperty,BD=Object.getOwnPropertyNames,_y=Object.getOwnPropertySymbols,PD=Object.getOwnPropertyDescriptor,jD=Object.getPrototypeOf,Ly=Object.prototype;function $1(e,t){if(typeof t!="string"){if(Ly){const i=jD(t);i&&i!==Ly&&$1(e,i)}let r=BD(t);_y&&(r=r.concat(_y(t)));const n=Cy(e),s=Cy(t);for(let i=0;i<r.length;++i){const a=r[i];if(!MD[a]&&!(s&&s[a])&&!(n&&n[a])){const u=PD(t,a);try{DD(e,a,u)}catch{}}}}return e}var QD=Symbol.for("react-redux-context"),FD=typeof globalThis<"u"?globalThis:{};function OD(){if(!A.createContext)return{};const e=FD[QD]??=new Map;let t=e.get(A.createContext);return t||(t=A.createContext(null),e.set(A.createContext,t)),t}var A4=OD(),$D=[null,null];function HD(e,t,r){tp(()=>e(...t),r)}function UD(e,t,r,n,s,i){e.current=n,r.current=!1,s.current&&(s.current=null,i())}function GD(e,t,r,n,s,i,a,u,d,f,b){if(!e)return()=>{};let g=!1,y=null;const v=()=>{if(g||!u.current)return;const T=t.getState();let C,E;try{C=n(T,s.current)}catch(N){E=N,y=N}E||(y=null),C===i.current?a.current||f():(i.current=C,d.current=C,a.current=!0,b())};return r.onStateChange=v,r.trySubscribe(),v(),()=>{if(g=!0,r.tryUnsubscribe(),r.onStateChange=null,y)throw y}}function zD(e,t){return e===t}function WD(e,t,r,{pure:n,areStatesEqual:s=zD,areOwnPropsEqual:i=Rg,areStatePropsEqual:a=Rg,areMergedPropsEqual:u=Rg,forwardRef:d=!1,context:f=A4}={}){const b=f,g=yD(e),y=xD(t),v=AD(r),w=!!e;return C=>{const E=C.displayName||C.name||"Component",N=`Connect(${E})`,D={shouldHandleStateChanges:w,displayName:N,wrappedComponentName:E,WrappedComponent:C,initMapStateToProps:g,initMapDispatchToProps:y,initMergeProps:v,areStatesEqual:s,areStatePropsEqual:a,areOwnPropsEqual:i,areMergedPropsEqual:u};function R(O){const[H,G,U]=A.useMemo(()=>{const{reactReduxForwardedRef:Re,...ct}=O;return[O.context,Re,ct]},[O]),W=A.useMemo(()=>{let Re=b;return H?.Consumer,Re},[H,b]),J=A.useContext(W),ee=!!O.store&&!!O.store.getState&&!!O.store.dispatch,ae=!!J&&!!J.store,Se=ee?O.store:J.store,Le=ae?J.getServerState:Se.getState,_e=A.useMemo(()=>gD(Se.dispatch,D),[Se]),[se,ie]=A.useMemo(()=>{if(!w)return $D;const Re=v4(Se,ee?void 0:J.subscription),ct=Re.notifyNestedSubs.bind(Re);return[Re,ct]},[Se,ee,J]),fe=A.useMemo(()=>ee?J:{...J,subscription:se},[ee,J,se]),Qe=A.useRef(void 0),de=A.useRef(U),Fe=A.useRef(void 0),rt=A.useRef(!1),ht=A.useRef(!1),Ee=A.useRef(void 0);tp(()=>(ht.current=!0,()=>{ht.current=!1}),[]);const ce=A.useMemo(()=>()=>Fe.current&&U===de.current?Fe.current:_e(Se.getState(),U),[Se,U]),je=A.useMemo(()=>ct=>se?GD(w,Se,se,_e,de,Qe,rt,ht,Fe,ie,ct):()=>{},[se]);HD(UD,[de,Qe,rt,U,Fe,ie]);let De;try{De=A.useSyncExternalStore(je,ce,Le?()=>_e(Le(),U):ce)}catch(Re){throw Ee.current&&(Re.message+=`
|
|
74
|
+
`),he(Et),Ve(Et,!1),ot("Terminal session ended"),_e(!1),Rt(!1),rr(null),vt(Et,!1),gr();break}}},onError:(Pe,Et)=>{if(Rr.current!==Je)return;const It=D;if(!It)return;const br=Et?`Connection failed: ${Pe.message}`:Pe.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${Et}):`,br),Pe.message==="Session not found on server"&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:Vt.current,frontendSessionId:It,isActive:a,isMobile:R,fatal:Et,stack:new Error().stack}),ot(br),Rt(!!Et),Et&&(Ve(It,!1),gr(),Pe.message==="Session not found on server"&&(C("[onError] Session lost, auto-recreating"),ot("Reconnecting..."),Rt(!1),he(It),Ce(It),Vt.current=null,Fr.current=!1,setTimeout(()=>{Fr.current=!1,mt(Ar=>Ar+1)},200)))}},aN);yr.current=()=>{ft.close(),Rr.current===Je&&(cn.current=null)},cn.current=ve},[We,Ce,he,C,gr,Br,ts,Ve,nt,wt,vt,kt,$e,T,D]),Fr=P.useRef(!1),hn=P.useRef(0);P.useEffect(()=>()=>{hn.current+=1,Fr.current=!1,gr()},[gr]);const $n=P.useRef(be),ta=P.useRef(Te);P.useEffect(()=>{const ve=$n.current,Je=ta.current;$n.current=be,ta.current=Te,le.current===D&&(ve===be&&Je===Te||(Fr.current=!1,gr(),mt(ft=>ft+1)))},[be,Te,gr,D]),P.useEffect(()=>{if(le.current!==D&&(C(`[useEffect] sessionId changed from ${le.current} to ${D}, allowing reinitialization`),Fr.current=!1),Fr.current&&le.current===D){C(`[useEffect] Already initialized for sessionId=${D}, skipping`);return}C(`[useEffect] Running ensureSession for sessionId=${D}, hasInitialized=${Fr.current}`),Fr.current=!0;const ve=++hn.current;return(async()=>{if(C(`[ensureSession] Starting for sessionId=${D}, runId=${ve}`),!le.current||le.current!==D){C(`[ensureSession] SessionId mismatch or stale run (current=${le.current}, target=${D}), skipping`);return}if(ve!==hn.current){C(`[ensureSession] Stale run detected (runId=${ve}, currentRunId=${hn.current}), skipping`);return}const ft=Vn.getState(),Pe=ft.getTerminalSession(D),Et=Pe?.mode??be;C("[ensureSession] Current state from store:",{terminalSessionId:Pe?.terminalSessionId,mode:Pe?.mode,tmuxSessionName:Pe?.tmuxSessionName,isConnecting:Pe?.isConnecting});let It=Pe?.terminalSessionId??null,br=!It;if(It&&Et!==be?(C(`[ensureSession] Store mode mismatch for ${It}: current=${Et} desired=${be}, will create new session`),br=!0,ft.clearTerminalSession(D),It=null):It&&be==="tmux"&&Te&&Pe?.tmuxSessionName!==Te&&(C(`[ensureSession] Store tmux name mismatch for ${It}: current=${Pe?.tmuxSessionName} desired=${Te}, will create new session`),br=!0,ft.clearTerminalSession(D),It=null),It&&T.checkHealth){C(`[ensureSession] Checking health of existing session ${It}`);try{const Ar=await T.checkHealth(It);if(C("[ensureSession] Health check result:",Ar),!Ar.healthy)C(`[ensureSession] Session ${It} is NOT healthy (healthy=${Ar.healthy}), will create new session`),C("[ensureSession] Health check details:",Ar),br=!0,Ar.mode&&Pe?.terminalSessionId&&ft.setTerminalSession(D,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:Ar.mode,tmuxSessionName:Ar.tmuxSessionName??null}),ft.clearTerminalSession(D),C("[ensureSession] Cleared unhealthy session from store");else{C(`[ensureSession] Session ${It} is healthy, reusing it, cwd=${Ar.cwd}, clients=${Ar.clients}, lastActivity=${Date.now()-(Ar.lastActivity||0)}ms ago`),Ar.mode&&Pe?.terminalSessionId&&ft.setTerminalSession(D,{sessionId:Pe.terminalSessionId,cols:80,rows:24,mode:Ar.mode,tmuxSessionName:Ar.tmuxSessionName??null}),C(`[ensureSession] Setting terminalIdRef to ${It} and starting stream`),Vt.current=It,Es(It),C(`[ensureSession] Successfully reused healthy session ${It}, returning early`);return}}catch(Ar){C(`[ensureSession] Failed to check health of session ${It}:`,Ar),C("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(C(`[ensureSession] Decision: shouldCreateNewSession=${br}, terminalId=${It}`),br){C(`[ensureSession] Creating new session, shouldCreateNewSession=${br}, runId=${ve}`),ot(null),Rt(!1),ft.setConnecting(D,!0);const vn=Vn.getState().getTerminalSession(D),zr=(vn?.mode??be)===be&&(be!=="tmux"||!Te||vn?.tmuxSessionName===Te);if(vn?.terminalSessionId&&zr)C(`[ensureSession] Race condition avoided: another instance already created session ${vn.terminalSessionId}`),ft.setConnecting(D,!1),It=vn.terminalSessionId,br=!1;else try{const ss=await ks();if(C(`[ensureSession] Opened managed backend session ${ss.sessionId}`),ve!==hn.current){C(`[ensureSession] Stale run after session creation (runId=${ve}, currentRunId=${hn.current}), leaving ${ss.sessionId} for sibling`);return}ft.setTerminalSession(D,ss),C(`[ensureSession] Updated store with new session ${ss.sessionId}`),It=ss.sessionId}catch(ss){if(ve!==hn.current){C("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(ss instanceof N6&&ss.code==="STALE_SESSION_RESTORE_REJECTED"){C("[ensureSession] Dropping stale persisted session:",{sessionId:D,error:ss.message}),ft.clearTerminalSession(D),window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:D,closeMode:"detach"}}));return}ot(ss instanceof Error?ss.message:"Failed to start terminal session"),Rt(!0),ft.setConnecting(D,!1);return}}if(ve!==hn.current){C(`[ensureSession] Stale run before starting stream (runId=${ve}, currentRunId=${hn.current}), skipping`);return}if(!It){C(`[ensureSession] No terminalId, terminalId=${It}`);return}C(`[ensureSession] Starting stream for session ${It}`),Vt.current=It,Es(It),C(`[ensureSession] ensureSession completed for sessionId=${D}, terminalId=${It}`)})(),()=>{C(`[useEffect] Cleanup for sessionId=${D}, runId=${ve}`)}},[D,st,Es,gr,T,C,be,Te,$t]);const vr=P.useCallback(async()=>{if(D&&!at){qe(!0),ot(null),Rt(!1),gr();try{T.forceKill&&await T.forceKill({sessionId:D})}catch{}Be(D),Ce(D),Yt.current?.clear(),await new Promise(ve=>setTimeout(ve,100));try{Ve(D,!0);const ve=await ks();Ae(D,ve),Vt.current=ve.sessionId,Es(ve.sessionId)}catch(ve){ot(ve instanceof Error?ve.message:"Failed to create terminal"),Rt(!0),Ve(D,!1)}finally{qe(!1)}}},[D,at,gr,T,Be,Ce,Ve,Ae,Es,ks]),Xr=P.useCallback((ve,Je)=>{if(!un.current||!ve)return;const ft=/^(\x1b\[<[0-9]+;[0-9]+;[0-9]+[mM])+$/.test(ve),Pe=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(ve);if(Mt&&Pe&&(lr.current=!0),Date.now()<On.current)return;let Et=ve,It=Je?.consumeModifier??!1;if(!Je?.skipModifierTransform&&fe&&ve.length>0){const vn=ve[0];if(vn.length===1&&/[a-zA-Z]/.test(vn)){const Gr=vn.toUpperCase();fe==="ctrl"?(Et=String.fromCharCode(Gr.charCodeAt(0)&31),It=!0):fe==="alt"&&(Et=`\x1B${ve}`,It=!0)}It||(fe==="alt"&&(Et=`\x1B${ve}`),It=!0)}const br=Vt.current;if(!br)return;(async()=>{try{if(Mt&&!ft&&lr.current&&T.tmuxAction){lr.current=!1;try{await T.tmuxAction(br,{action:"copy-mode",enabled:!1})}catch{}}await T.sendInput(br,Et)}catch(vn){ot(vn instanceof Error?vn.message:"Failed to send input")}})(),It&&(de||Qe(null),dn())},[fe,dn,Mt,de,T]);P.useEffect(()=>{const ve=Je=>{if(!un.current)return;const ft=Je,Pe=ft.detail?.text;Pe&&(Yt.current?.sendSequence(Pe),ft.detail?.focus!==!1&&dn())};return window.addEventListener("termdock-insert-reference",ve),()=>window.removeEventListener("termdock-insert-reference",ve)},[dn]);const Jr=P.useCallback((ve,Je)=>{const ft=Vt.current;if(!ft){E("xterm resize push skipped: no terminalId",{cols:ve,rows:Je});return}E("xterm resize push",{cols:ve,rows:Je}),T.resize({sessionId:ft,cols:ve,rows:Je}).catch(Pe=>{Pe&&/session not found/i.test(String(Pe.message||Pe))&&console.warn("[Terminal] resize 404 session not found",{sessionId:ft,cols:ve,rows:Je,stack:new Error().stack})})},[T,E]),Pr=P.useCallback(async ve=>{const Je=Vt.current;if(!(!Je||!T.tmuxAction))try{const ft=await T.tmuxAction(Je,ve);ft.layout&&(rr(ft.layout),ve.action==="switch-session"&&(Ae(D,{sessionId:Je,cols:80,rows:24,mode:"tmux",tmuxSessionName:ft.layout.sessionName}),Lf(D,{tmuxSessionName:ft.layout.sessionName}).catch(Pe=>{console.warn("[Terminal] failed to update inventory after tmux switch",Pe)})))}catch(ft){ot(ft instanceof Error?ft.message:"Failed to execute tmux action")}},[D,Ae,T]);P.useEffect(()=>{if(!Ze||!ne)return;const Je=Ze.windows.find(ft=>ft.id===Ze.activeWindowId)?.panes.find(ft=>ft.id===Ze.activePaneId);Je&&Yt.current?.requestRefresh("tmux-layout",{candidateSize:{cols:Je.width,rows:Je.height},skipScrollToBottom:!0,dedupeKey:`${ne}:${Ze.sessionId}:${Je.id}:${Je.width}x${Je.height}`})},[Ze,ne]);const fn=P.useCallback((ve,Je=5)=>{const ft=Math.max(1,Math.min(Math.floor(Je)||1,40));lr.current=!0;const Pe=Bt.current;if(Pe&&Pe.direction===ve){Pe.lines+=ft;return}Pe&&Pr({action:"scroll",direction:Pe.direction,lines:Pe.lines}).finally(()=>{dn()}),Bt.current={direction:ve,lines:ft},nn.current&&clearTimeout(nn.current),nn.current=setTimeout(()=>{const Et=Bt.current;Et&&(Bt.current=null,Pr({action:"scroll",direction:Et.direction,lines:Et.lines}).finally(()=>{dn()}))},0)},[dn,Pr]),lo=P.useCallback(ve=>{const Je=Date.now(),ft=qn.current,Pe=ft!==null&&ft.modifier===ve&&Je-ft.timestamp<=oN;if(qn.current={modifier:ve,timestamp:Je},de===ve){Fe(null),Qe(null);return}if(Pe){Fe(ve),Qe(ve);return}de!==null&&de!==ve&&Fe(null),Qe(Et=>Et===ve?null:ve)},[de]),co=P.useCallback(ve=>{if(W(ve&&un.current),E("input focus changed",{focused:ve,isActive:un.current,isMobile:_n.current}),!_n.current||!un.current){G(!1);return}G(Je=>Je===ve?Je:ve)},[E]),Ur=P.useCallback(ve=>{if(et.current=ve,Br(ve,"viewport-watermark"),!ve&&Fn.current.length>0){const Je=D;if(Je){const ft=Fn.current;Fn.current=[];for(const Pe of ft)We(Je,Pe)}}},[We,Br,D]),_r=P.useCallback(ve=>{un.current&&Yt.current?.ensureSizeMatches(ve)},[]),Hn=P.useRef(null);P.useEffect(()=>{if(!a)return;const ve=Hn.current;if(!ve)return;const Je=()=>_r("pointerdown"),ft=()=>_r("keydown"),Pe=()=>_r("touchstart"),Et=()=>_r("wheel");return ve.addEventListener("pointerdown",Je),ve.addEventListener("keydown",ft),ve.addEventListener("touchstart",Pe,{passive:!0}),ve.addEventListener("wheel",Et,{passive:!0}),()=>{ve.removeEventListener("pointerdown",Je),ve.removeEventListener("keydown",ft),ve.removeEventListener("touchstart",Pe),ve.removeEventListener("wheel",Et)}},[a,_r]);const Mo=P.useCallback(ve=>{Yt.current=ve},[]),si=P.useCallback(ve=>{const Je=KR(ve);if(!Je)return;const ft=fe!==null;Yt.current?.sendSequence(Je,{consumeModifier:ft})},[fe]),Ai=P.useCallback(ve=>{const Je=WR(ve);if(Je.length===0)return;const ft=fe!==null;Yt.current?.sendSequence(Wx(Je[0]),{consumeModifier:ft});for(let Pe=1;Pe<Je.length;Pe+=1){const Et=Je[Pe];window.setTimeout(()=>{Yt.current?.sendSequence(Wx(Et))},zR*Pe)}},[fe]),ms=P.useCallback(()=>{Yt.current?.pasteClipboardText()},[]),rs=Me||ue!==null,yn=P.useRef(ut);rs||(yn.current=ut);const Is=rs?yn.current:ut,ii=P.useMemo(()=>VR(Is,Oe),[Is,Oe]),oi=P.useMemo(()=>qx(Oe,Ee),[Ee,Oe]),Sn=!R&&Ee!=="auto"&&oi.showOnDesktop!==!0?"auto":Ee,uo=Sn==="auto"?ii:Sn,ai=P.useMemo(()=>qx(Oe,uo),[uo,Oe]),Mn=P.useMemo(()=>ai.actions.filter(ve=>ve.sequence.trim().length>0).map((ve,Je)=>({...ve,label:B1(ve,Je)})),[ai.actions]),Ti=P.useMemo(()=>qw(ut),[ut]),Ei=ai.label,nr=P.useMemo(()=>Sn!=="auto"?`Manual preset: ${ai.label}`:Ti?`Auto preset · ${ai.label} (${Ti})`:"Auto preset",[Ti,Sn,ai.label]),Ii=P.useCallback(ve=>{ce(ve)},[]),li=P.useCallback(()=>{De(ve=>ve==="copy"?"arrows":"copy"),ge("idle")},[]),us=P.useCallback(()=>{typeof window>"u"||(on.current!==null&&window.clearTimeout(on.current),on.current=window.setTimeout(()=>{on.current=null,ge("idle")},1200))},[]),Lr=P.useCallback(ve=>{on.current!==null&&typeof window<"u"&&(window.clearTimeout(on.current),on.current=null),ge(ve?"copied":"failed"),us()},[us]),Ms=P.useCallback(ve=>{ht(ve)},[]),Yi=P.useMemo(()=>R?qR(Oe):YR(Oe),[R,Oe]),en=P.useMemo(()=>MR(s),[s]),pn=P.useMemo(()=>`terminal::${D}`,[D]);P.useEffect(()=>{y?.({isConnecting:Me,isRestarting:at,hasError:!!ue,sessionId:ne})},[Me,at,ue,ne,y]);const Ln=!ne||Me||at,Si=P.useCallback((ve,Je)=>{if(Ln)return;const ft=Math.max(1,Math.min(Math.floor(Je)||1,40));fn(ve,ft)},[fn,Ln]);P.useEffect(()=>{if(!a||!R)return;Yt.current?.requestRefresh("resize",{resizeDebounceMs:0,skipScrollToBottom:!se,force:!0})},[a,R,se,ie,D]),P.useEffect(()=>{if(!a||!R)return;const ve=Je=>{const ft=Je.detail;Yt.current?.requestRefresh("resize",{resizeDebounceMs:0,skipScrollToBottom:ft?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",ve),()=>{document.removeEventListener("termdock:viewport-keyboard-change",ve)}},[a,R,D]);const ns=R||ai.showOnDesktop===!0,Zi=a,ds=R?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,gs=R?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0;return c.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:ds,children:[Tt&&c.jsx(JR,{isMobile:R,isInputFocused:H,isIOS:M,isConnecting:Me,connectionError:ue,terminalSessionId:ne}),c.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:en.background,...gs},children:[c.jsx("div",{ref:Hn,className:"h-full w-full box-border",children:c.jsx(Ww,{fallback:c.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[c.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:c.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.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"})})}),c.jsx("span",{className:"text-sm text-muted-foreground",children:"Terminal component failed to load"})]})}),children:c.jsx(kR,{ref:Mo,sessionKey:pn,chunks:it,onInput:Xr,onResize:Jr,onFlowControl:Ur,onTmuxScroll:Mt?Si:void 0,tmuxScrollSensitivity:.38,onDoubleTap:R?()=>{Yt.current?.sendSequence(" ")}:void 0,onInputFocusChange:co,onMobileLongPressCopyResult:Lr,terminalSettings:N,theme:en,enableTouchScroll:R,mobileLongPressMode:je,autoFocus:!R},pn)})}),c.jsx(tN,{connectionError:ue,isFatalError:xt,isRestarting:at,isConnecting:Me,onHardRestart:vr})]}),c.jsx(XR,{visible:ns,interactive:Zi,presentation:R?"mobile":"desktop-actions",activeModifier:fe,lockedModifier:de,disabled:Ln,defaultShowExtended:rt,presetLabel:Ei,presetModeLabel:nr,presetMode:Sn,presetOptions:Yi,includeAlt:ai.includeAlt,presetRowLayout:ai.rowLayout,extraActions:Mn,onKeyPress:si,onTextPress:Ai,onPastePress:R?ms:void 0,longPressMode:je,copyFeedback:ke,onLongPressModeToggle:li,onModifierToggle:lo,onPresetSelect:Ii,onExpandedChange:Ms})]})},cN=1e3,uN=2e4,dN=9e4,hN=5e3,Yr={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let tf=0,Uu=null;function fN(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function Jw(){Yr.idleCloseTimer&&(clearTimeout(Yr.idleCloseTimer),Yr.idleCloseTimer=null)}function pN(){Jw(),!(Yr.ws&&Yr.ws.readyState===WebSocket.OPEN)&&(Yr.idleCloseTimer=setTimeout(()=>{Yr.idleCloseTimer=null,Yr.listeners.size===0&&mN()},hN))}function mN(){if(Yr.ws){try{Yr.ws.close()}catch{}Yr.ws=null}Uu&&(clearInterval(Uu),Uu=null)}function ey(){if(Yr.reconnectTimer)return;const e=Math.min(cN*Math.pow(2,Yr.reconnectAttempt),uN);Yr.reconnectAttempt+=1,Yr.reconnectTimer=setTimeout(()=>{Yr.reconnectTimer=null,e4()},e)}function e4(){const e=fN();if(!e||Yr.ws&&Yr.ws.readyState===WebSocket.OPEN)return;let t;try{t=new WebSocket(e)}catch{ey();return}Yr.ws=t,t.onopen=()=>{Yr.reconnectAttempt=0,tf=Date.now(),Uu||(Uu=setInterval(()=>{if(!(!Yr.ws||Yr.ws.readyState!==WebSocket.OPEN)&&tf>0&&Date.now()-tf>dN)try{Yr.ws.close()}catch{}},3e4),Uu.unref?.())},t.onmessage=r=>{tf=Date.now();let n=null;try{n=JSON.parse(r.data)}catch{return}if(!n)return;if(n.type==="config-updated"){if(n.key!=="toolbar-presets"&&n.key!=="agent-rules"&&n.key!=="program-detection")return;const i={type:"config-updated",key:n.key,updatedAt:typeof n.updatedAt=="number"?n.updatedAt:void 0};for(const a of Yr.listeners)try{a(i)}catch(u){console.error("[clientStateSync] listener threw:",u)}return}if(n.type!=="client-state"||!n.state)return;const s={type:"client-state",clientState:{sessions:Array.isArray(n.state.sessions)?n.state.sessions:[],updatedAt:typeof n.state.updatedAt=="number"?n.state.updatedAt:Date.now()},inventory:n.inventory,seq:typeof n.seq=="number"?n.seq:void 0};for(const i of Yr.listeners)try{i(s)}catch(a){console.error("[clientStateSync] listener threw:",a)}},t.onclose=()=>{Yr.ws===t&&(Yr.ws=null),Yr.listeners.size>0&&ey()},t.onerror=()=>{}}function t4(e){return Yr.listeners.add(e),Jw(),Yr.ws||e4(),()=>{Yr.listeners.delete(e),Yr.listeners.size===0&&pN()}}const Eg="termdock-sessions",P1="termdock-active-session",z2="termdock-sessions-cache";function ty(){try{const e=localStorage.getItem(P1);return e&&e.trim().length>0?e:null}catch{return null}}function Tu(e){try{e?localStorage.setItem(P1,e):localStorage.removeItem(P1)}catch{}}function gN(){if(typeof window>"u")return null;try{const e=localStorage.getItem(z2);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="object"&&r!==null&&typeof r.sessionId=="string"&&typeof r.name=="string"):null}catch{return null}}function mc(e){if(!(typeof window>"u"))try{localStorage.setItem(z2,JSON.stringify(e))}catch{}}function ry(){if(!(typeof window>"u"))try{localStorage.removeItem(z2)}catch{}}function r4(e){return e.map(t=>({...t,mode:t.mode==="tmux"?"tmux":"shell",tmuxSessionName:t.tmuxSessionName??null,customName:t.customName===!0}))}function ny(e){return r4(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,r)=>({...t,activeProgram:e[r]?.activeProgram??null,cwd:e[r]?.cwd??null}))}function sy(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 iy(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function bN(){const e=A.useRef(gN()).current,t=A.useRef(ty()).current,[r,n]=A.useState(e??[]),[s,i]=A.useState(null),[a,u]=A.useState(e&&e.length>0?iy(e,t):t),[d,f]=A.useState(e===null),b=A.useRef(!1),g=A.useRef(null),y=A.useRef(e===null),v=A.useRef(0);A.useEffect(()=>{y.current=d},[d]),A.useEffect(()=>{g.current=a},[a]);const w=A.useCallback(J=>{const ee=iy(J,g.current??ty());return u(ae=>ae===ee?ae:ee),Tu(ee),g.current=ee,ee},[]),T=A.useCallback((J,ee)=>{n(ae=>sy(ae)===sy(J)?ae:J),mc(J),ee?.reconcileActive&&w(J)},[w]),C=A.useCallback((J,ee)=>{i(J),T(ny(J.clientSessions),ee)},[T]),E=A.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(Eg)?(localStorage.removeItem(Eg),ry(),Tu(null),n([]),u(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),N=A.useCallback(async()=>{if(typeof window>"u")return[];try{const J=await ZC();C(J,{reconcileActive:!0});const ee=ny(J.clientSessions);return ee.length>0?ee:E()}catch(J){console.error("Failed to restore sessions from server:",J);try{return E()}catch(ee){console.error("Failed to discard legacy local sessions:",ee)}}finally{f(!1)}return[]},[C,E]),D=A.useCallback(async J=>{const ee=await Q6(J);return C(ee.inventory),u(ee.session.sessionId),Tu(ee.session.sessionId),ee},[C]),R=A.useCallback(async J=>{n(ee=>{const ae=ee.filter(Le=>Le.sessionId!==J),Se=g.current===J?ae[0]?.sessionId??null:g.current;return u(Se),Tu(Se),mc(ae),ae});try{await XC(J)}catch(ee){console.error("Failed to remove session from inventory:",ee)}},[]),_=A.useCallback(J=>{const ee=Date.now();n(ae=>{const Se=ae.map(Le=>Le.sessionId===J?{...Le,lastActivity:ee}:Le);return mc(Se),Se})},[]),M=A.useCallback(J=>{u(J),Tu(J)},[]),O=A.useCallback(async(J,ee)=>{const ae=ee.trim();if(ae){n(Se=>{const Le=Se.map(_e=>_e.sessionId===J?{..._e,name:ae,customName:!0}:_e);return mc(Le),Le});try{const Se=await Lf(J,{name:ae,customName:!0});C(Se)}catch(Se){console.error("Failed to rename session in inventory:",Se)}}},[C]),H=A.useCallback(async J=>{n(ee=>{const ae=ee.map(Se=>Se.sessionId===J?{...Se,customName:!1}:Se);return mc(ae),ae});try{const ee=await Lf(J,{customName:!1});C(ee)}catch(ee){console.error("Failed to reset session name in inventory:",ee)}},[C]),G=A.useCallback(async J=>{n(ee=>{const ae=new Map(ee.map(ie=>[ie.sessionId,ie])),Se=J.map(ie=>ae.get(ie)).filter(ie=>ie!==void 0),Le=new Set(J),_e=ee.filter(ie=>!Le.has(ie.sessionId)),se=[...Se,..._e];return mc(se),se});try{const ee=await KC(J);C(ee)}catch(ee){console.error("Failed to reorder sessions in inventory:",ee)}},[C]),U=A.useCallback(async()=>{n([]),i(null),u(null),Tu(null),ry(),typeof window<"u"&&localStorage.removeItem(Eg);try{await JC()}catch(J){console.error("Failed to clear session inventory:",J)}},[]),W=A.useCallback(async(J,ee)=>{n(ae=>{const Se=ae.map(Le=>Le.sessionId===J?{...Le,backendSessionId:ee}:Le);return mc(Se),Se});try{const ae=await Lf(J,{backendSessionId:ee});C(ae)}catch(ae){console.error("Failed to update session backend in inventory:",ae)}},[C]);return A.useEffect(()=>{b.current||(b.current=!0,N())},[N]),A.useEffect(()=>t4(ee=>{if(ee.type!=="client-state"||y.current)return;const ae=typeof ee.seq=="number"?ee.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(ee.inventory){C(ee.inventory,{reconcileActive:!0});return}const Se=r4(ee.clientState.sessions||[]);T(Se,{reconcileActive:!0})}),[C,T]),{sessions:r,inventory:s,activeSessionId:a,isLoading:d,openSession:D,removeSession:R,updateSessionActivity:_,setActiveSession:M,updateSessionBackendId:W,renameSession:O,resetSessionCustomName:H,reorderSessions:G,clearAllSessions:U,restoreSessions:N}}function Zr(e,t){if(typeof window>"u")return null;try{const r=window.localStorage.getItem(e);if(r===null||r==="")return null;const n=JSON.parse(r);return t(n)?n:null}catch{return null}}function ir(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}const kd=new Map,Ed=new Map,Pf=new Map;function Od(e,t,r){if(typeof window>"u")return;const n=Date.now(),s=Pf.get(e)??0,i=n-s;if(i>=r){Pf.set(e,n),ir(e,t);return}if(Ed.set(e,t),kd.has(e))return;const a=r-i,u=setTimeout(()=>{kd.delete(e);const d=Ed.get(e);Ed.delete(e),Pf.set(e,Date.now()),d!==void 0&&ir(e,d)},a);kd.set(e,u)}function yd(e){const t=kd.get(e);t&&(clearTimeout(t),kd.delete(e));const r=Ed.get(e);r!==void 0&&(Ed.delete(e),Pf.set(e,Date.now()),ir(e,r))}function xN(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}const n4="termdock:right-sidebar:tabs-by-root:v1",s4="termdock:right-sidebar:explorer-roots:v1",i4="termdock:right-sidebar:pinned-explorer-roots:v1",o4="termdock:right-sidebar:selected-files:v1",a4="termdock:right-sidebar:show-hidden-files:v1",j1="termdock-sidebar-group-by-folder",l4="termdock-sidebar-collapsed-folder-groups",c4="termdock-left-sidebar-pinned",u4="termdock-left-sidebar-width";function yN(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(c4)==="1"}catch{return!1}}function oy(e){if(!(typeof window>"u"))try{window.localStorage.setItem(c4,e?"1":"0")}catch{}}function vN(){if(typeof window>"u")return 300;try{const e=window.localStorage.getItem(u4);if(!e)return 300;const t=parseInt(e,10);return Number.isFinite(t)&&t>=200&&t<=500?t:300}catch{return 300}}function wN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(u4,String(e))}catch{}}function AN(){if(typeof window>"u")return!0;try{const e=window.localStorage.getItem(j1);return e===null?!0:e==="1"}catch{return!0}}function ay(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(j1,"1"):window.localStorage.setItem(j1,"0")}catch{}}function TN(){if(typeof window>"u")return new Set;try{const e=window.localStorage.getItem(l4);if(!e)return new Set;const t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(r=>typeof r=="string")):new Set}catch{return new Set}}function SN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(l4,JSON.stringify([...e]))}catch{}}function CN(e){return e==="git"||e==="files"||e==="diff"||e==="file"}function _N(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(CN)}function d4(){return Zr(n4,_N)??{}}function LN(e,t){e&&ir(n4,{...d4(),[e]:t})}function kN(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function EN(){return Zr(s4,kN)??{}}function ly(e){ir(s4,e)}function IN(e){return e!==null&&typeof e=="object"&&typeof e.path=="string"&&(e.kind==="file"||e.kind==="directory")}function MN(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"||IN(r)))}function RN(e){const t=new Set,r=[];for(const n of e){const s=typeof n=="string"?{path:n,kind:"directory"}:n;!s.path||t.has(s.path)||(t.add(s.path),r.push(s))}return r}function NN(){const e=Zr(i4,MN)??{},t={};for(const[r,n]of Object.entries(e))t[r]=RN(n);return t}function cy(e){ir(i4,e)}function DN(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string")}function h4(){return Zr(o4,DN)??{}}function uy(e,t){if(!e)return;const r={...h4()};t?r[e]=t:delete r[e],ir(o4,r)}function BN(e){return typeof e=="boolean"}function PN(){return Zr(a4,BN)??!1}function jN(e){const t=e.replace(/\/+$/,"")||"/";return t==="/"?"/":t.slice(0,t.lastIndexOf("/"))||"/"}function id(e,t){const r=e.replace(/\/+$/,"")||"/";return t===r||t.startsWith(`${r}/`)}function QN(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name))}function FN(e){return e.entry?{name:e.entry.name,path:e.entry.path,type:e.entry.type,isSymlink:e.entry.isSymlink,expanded:!1,loaded:!1,children:e.entry.type==="directory"?[]:void 0}:null}const dt=R6(e=>({leftOpen:!1,rightOpen:!1,leftPinned:yN(),leftSidebarWidth:vN(),rightTab:"files",rightSearchOpen:!1,rootPath:null,explorerRoot:null,explorerRootCache:EN(),pinnedExplorerRootsCache:NN(),expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,showHiddenFiles:PN(),groupByFolder:AN(),collapsedGroups:TN(),changedFiles:new Map,fileChangeVersions:new Map,gitBundleLoading:!1,gitBundleSlow:!1,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 r=!t.leftPinned;return oy(r),{leftPinned:r,leftOpen:!0}}),setLeftPinned:t=>e(()=>(oy(t),{leftPinned:t})),setLeftSidebarWidth:t=>e(r=>{const n=Math.min(Math.max(t,200),500);return r.leftSidebarWidth===n?r:(wN(n),{leftSidebarWidth:n})}),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(r=>(LN(r.rootPath,t),{rightTab:t})),openRightSearch:()=>e({rightSearchOpen:!0}),closeRightSearch:()=>e({rightSearchOpen:!1}),setRightSearchOpen:t=>e({rightSearchOpen:t}),setRootPath:t=>e(r=>{if(r.rootPath===t)return r;const n=new Map(r.projectStateCache);r.rootPath&&n.set(r.rootPath,{rightTab:r.rightTab,explorerRoot:r.explorerRoot,expandedPaths:new Set(r.expandedPaths),selectedFilePath:r.selectedFilePath,directoryCache:new Map(r.directoryCache),changedFiles:new Map(r.changedFiles),gitBundleError:r.gitBundleError,gitBundleLastLoadedAt:r.gitBundleLastLoadedAt,gitBundleCacheInfo:r.gitBundleCacheInfo});const s=t?n.get(t):void 0,i=t?d4()[t]:void 0,a=t?r.explorerRootCache[t]:void 0,u=t?h4()[t]:void 0;return{rootPath:t,rightTab:s?.rightTab??i??"files",explorerRoot:s?.explorerRoot??a??t,expandedPaths:s?new Set(s.expandedPaths):new Set,selectedFilePath:s?.selectedFilePath??u??null,directoryCache:s?new Map(s.directoryCache):new Map,changedFiles:s?new Map(s.changedFiles):new Map,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleError:s?.gitBundleError??null,gitBundleLastLoadedAt:s?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:s?.gitBundleCacheInfo??null,projectStateCache:n}}),setExplorerRoot:t=>e(r=>{if(r.explorerRoot===t)return r;const n={...r.explorerRootCache};return r.rootPath&&t&&(n[r.rootPath]=t,ly(n)),{explorerRoot:t,explorerRootCache:n}}),resetExplorerToProject:()=>e(t=>{if(t.explorerRoot===t.rootPath)return t;const r={...t.explorerRootCache};return t.rootPath&&(r[t.rootPath]=t.rootPath,ly(r)),{explorerRoot:t.rootPath,explorerRootCache:r}}),pinExplorerRoot:(t,r="directory")=>e(n=>{if(!n.rootPath||!t)return n;const s=n.pinnedExplorerRootsCache[n.rootPath]??[];if(s.some(a=>a.path===t))return n;const i={...n.pinnedExplorerRootsCache,[n.rootPath]:[{path:t,kind:r},...s].slice(0,12)};return cy(i),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:t=>e(r=>{if(!r.rootPath||!t)return r;const n=r.pinnedExplorerRootsCache[r.rootPath]??[];if(!n.some(a=>a.path===t))return r;const s=n.filter(a=>a.path!==t),i={...r.pinnedExplorerRootsCache};return s.length>0?i[r.rootPath]=s:delete i[r.rootPath],cy(i),{pinnedExplorerRootsCache:i}}),toggleExpanded:t=>e(r=>{const n=new Set(r.expandedPaths);return n.has(t)?n.delete(t):n.add(t),{expandedPaths:n}}),selectFile:t=>e(r=>(uy(r.rootPath,t),{selectedFilePath:t})),toggleShowHiddenFiles:()=>e(t=>{const r=!t.showHiddenFiles;ir(a4,r);const n=new Map(t.projectStateCache);for(const[s,i]of n)n.set(s,{...i,directoryCache:new Map});return{showHiddenFiles:r,directoryCache:new Map,projectStateCache:n}}),toggleGroupByFolder:()=>e(t=>{const r=!t.groupByFolder;return ay(r),{groupByFolder:r}}),setGroupByFolder:t=>e(r=>r.groupByFolder===t?r:(ay(t),{groupByFolder:t})),toggleGroupCollapsed:t=>e(r=>{const n=new Set(r.collapsedGroups);return n.has(t)?n.delete(t):n.add(t),SN(n),{collapsedGroups:n}}),setDirectoryCache:(t,r)=>e(n=>{const s=new Map(n.directoryCache);return s.set(t,r),{directoryCache:s}}),invalidateDirectoryCache:(t,r=!1)=>e(n=>{const s=new Map(n.directoryCache);for(const i of s.keys())(i===t||r&&id(t,i))&&s.delete(i);return{directoryCache:s}}),applyFileWatchEvents:t=>e(r=>{if(t.length===0)return r;const n=new Map(r.directoryCache),s=new Map(r.fileChangeVersions);let i=r.selectedFilePath,a=!1,u=!1;const d=f=>{s.set(f,(s.get(f)??0)+1),u=!0};for(const f of t){if(f.type==="rescan-required"){for(const T of n.keys())id(f.path,T)&&(n.delete(T),a=!0);i&&id(f.path,i)&&d(i);continue}const b=jN(f.path),g=n.get(b);if(f.type==="deleted"){if(d(f.path),i&&id(f.path,i)&&(i=null,uy(r.rootPath,null)),g){const T=g.filter(C=>C.path!==f.path);T.length!==g.length&&(n.set(b,T),a=!0)}for(const T of n.keys())id(f.path,T)&&(n.delete(T),a=!0);continue}d(f.path);const y=FN(f);if(!y||!g)continue;const v=g.find(T=>T.path===y.path),w=QN(v?g.map(T=>T.path===y.path?{...T,...y,children:T.children}:T):[...g,y]);n.set(b,w),a=!0}return!a&&!u?r:{directoryCache:a?n:r.directoryCache,selectedFilePath:i,fileChangeVersions:u?s:r.fileChangeVersions}}),setChangedFiles:t=>e({changedFiles:t}),setGitBundleLoading:t=>e({gitBundleLoading:t}),setGitBundleSlow:t=>e({gitBundleSlow:t}),setGitBundleError:t=>e({gitBundleError:t}),markGitBundleLoaded:(t=null)=>e({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:t,gitBundleLoading:!1,gitBundleSlow:!1})})),Q1=320,f4=1,ON=Q1+120;function dy(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function rf(e,t){const r=ep(e,t);if(r===null)return;const n=e.wrapperEl;dy(e),n&&(n.style.transitionDuration="0ms");try{const s=e;s.setTransition?.(0),s.setTranslate?.(r),dy(e),n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}catch{n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}}function F1(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 ep(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function $N(e,t){const r=F1(e),n=ep(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=f4}function HN(e){const t=[],r=new Map,n=new Map,s=new Map;for(const i of e){const a=r.get(i.id)??[];if(a.push(i.id),r.set(i.id,a),i.sessionId){const u=n.get(i.sessionId)??[];u.push(i.id),n.set(i.sessionId,u)}if(i.mode==="tmux"&&i.tmuxSessionName){const u=s.get(i.tmuxSessionName)??[];u.push(i.id),s.set(i.tmuxSessionName,u)}}for(const[i,a]of r)a.length>1&&t.push({kind:"frontend",key:i,sessionIds:a});for(const[i,a]of n)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 p4(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function m4(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 UN(e,t){const r=p4(e),n=r.findIndex(s=>s.id===t.id);if(n>=0){const s=[...r];return s[n]=t,s}return[...r,t]}function hy(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const s=r.get(n.sessionId);return{...m4(n),history:s?.history}})}function GN(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function fy(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 py(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function zN(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t)if(e.get(r)!==n)return!1;return!0}function WN(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const r=Date.now().toString(36),n=Math.random().toString(36).slice(2,8);return`wt-${r}${n}`}const VN=({terminalSettings:e=O2(),colorTheme:t="dark",toolbarPresets:r=[],showDebug:n,terminalFocusAvailable:s=!0,defaultSessionMode:i="shell",defaultTmuxSessionName:a="",onStatusChange:u,onSessionDataUpdate:d})=>{const f=A.useMemo(()=>Nc("session"),[]),b=A.useMemo(()=>Nc("terminal"),[]),[g,y]=A.useState([]),[v,w]=A.useState(null),[T,C]=A.useState(!0),[E,N]=A.useState({token:0,reason:"visibility"}),D=A.useRef(!1),R=A.useRef(null),_=A.useRef({}),[M,O]=A.useState(null),H=A.useRef(s),G=A.useRef(!1),U=A.useRef(null),W=A.useRef(null),J=A.useRef(!1),ee=A.useRef(null),ae=A.useRef([]),Se=A.useRef(0),Le=A.useRef(null),_e=A.useRef(!1),se=A.useRef(!0),ie=A.useRef(null),fe=A.useRef("");A.useEffect(()=>{if(typeof window>"u")return;const ne=()=>{const be=navigator.maxTouchPoints>0||"ontouchstart"in window,Te=window.innerWidth<768;J.current=be&&Te};return ne(),window.addEventListener("resize",ne),()=>window.removeEventListener("resize",ne)},[]);const{sessions:Qe,activeSessionId:de,isLoading:Fe,openSession:rt,setActiveSession:ht,removeSession:Ee,renameSession:ce,resetSessionCustomName:je,reorderSessions:De}=bN(),ke=dt(ne=>ne.groupByFolder),ge=dt(ne=>ne.leftOpen||ne.rightOpen),[Re,ct]=A.useState(()=>py(Vn.getState().sessions));A.useEffect(()=>Vn.subscribe(ne=>{const be=py(ne.sessions);ct(Te=>zN(Te,be)?Te:be)}),[]);const{arranged:Ae}=A.useMemo(()=>Uw(g,ne=>Re.get(ne.id)??null,ke,""),[g,Re,ke]),Ve=A.useRef(Ae);Ve.current=Ae,ee.current=v,ae.current=g,Le.current=de,_e.current=Fe,se.current=T,H.current=s;const We=A.useCallback((ne=R.current)=>{const be=Se.current,Te=typeof window<"u"?window.visualViewport:null,ue=ne?F1(ne):null,ot=ne?ep(ne,be):null;return{sessionsLength:ae.current.length,sessionIds:ae.current.map(xt=>xt.id),activeSessionId:ee.current,activeSessionIndex:be,persistedActiveId:Le.current,isLoading:_e.current,isRestoring:se.current,activeIndex:ne?.activeIndex??null,previousIndex:ne?.previousIndex??null,animating:ne?.animating??null,allowTouchMove:ne?.allowTouchMove??null,width:ne?.width??null,translate:ue,targetTranslate:ot,translateDelta:ue!==null&&ot!==null?ue-ot:null,snapGridLength:ne?.snapGrid?.length??null,targetSnap:ne?.snapGrid?.[be]??null,visualViewport:Te?{width:Math.round(Te.width),height:Math.round(Te.height),offsetTop:Math.round(Te.offsetTop)}:null}},[]),he=A.useCallback((ne,be)=>{f(ne,{...We(),...be})},[f,We]);A.useEffect(()=>{Fe||T||v!==de&&ht(v)},[v,Fe,T,de,ht]);const Be=A.useMemo(()=>{if(Ae.length===0||!v)return 0;const ne=Ae.findIndex(be=>be.id===v);return ne>=0?ne:0},[Ae,v]);Se.current=Be;const Ce=A.useCallback(()=>{U.current&&(clearTimeout(U.current),U.current=null)},[]),nt=A.useCallback(ne=>{Ce(),U.current=setTimeout(()=>{U.current=null,G.current=!1,he("[swiper:touch-guard-clear]",{reason:ne})},ON)},[Ce,he]),kt=A.useCallback((ne,be={})=>{const Te=R.current,ue=Se.current,ot=ae.current;if(!Te||ot.length===0||ue<0||ue>=ot.length)return;if(G.current){he("[swiper:sync-skip-touch]",{reason:ne});return}if(Te.animating){he("[swiper:sync-skip-animating]",{reason:ne});return}const xt=F1(Te),Rt=ep(Te,ue),at=xt!==null&&Rt!==null&&Math.abs(xt-Rt)<=f4,qe=Te.activeIndex===ue;if(he("[swiper:sync-check]",{reason:ne,activeIndexAligned:qe,translateAligned:at,immediate:be.immediate===!0}),!(qe&&at)){if(qe){rf(Te,ue),he("[swiper:sync-forced-active]",{reason:ne,translateAligned:at,immediate:be.immediate===!0});return}be.immediate?(rf(Te,ue),Te.slideTo(ue,0,!1),rf(Te,ue)):Te.slideTo(ue,Q1,!1),he("[swiper:sync-applied]",{reason:ne,activeIndexAligned:qe,translateAligned:at,immediate:be.immediate===!0})}},[he]);A.useEffect(()=>{const ne=be=>{const Te=be;R.current&&(R.current.allowTouchMove=!Te.detail.locked),he("[swiper:gesture-lock]",{locked:Te.detail.locked})};return document.addEventListener("termdock:gesture-lock",ne),()=>document.removeEventListener("termdock:gesture-lock",ne)},[he]),A.useEffect(()=>{if(g.length===0){v!==null&&w(null);return}if(!v){w(g[0].id);return}g.some(be=>be.id===v)||w(g[0].id)},[g,v]);const vt=A.useCallback((ne,be)=>{_.current[ne]=be},[]),wt=A.useCallback(ne=>{const be=Ve.current[ne.activeIndex]?.id;if(he("[swiper:slide-change]",{nextSessionId:be??null,instanceActiveIndex:ne.activeIndex}),!be||be===v)return;const Te=!!v&&_.current[v]===!0,ue=H.current&&(!J.current||Te);if(W.current=be,w(be),ue){O({sessionId:be,token:Date.now()});return}O(null)},[g,v,he]);A.useEffect(()=>{if(W.current===v){he("[swiper:sync-skip-swiper-driven]",{activeSessionId:v}),W.current=null;return}kt("active-session-index",{immediate:!0})},[v,Be,g.length,kt,he]),A.useEffect(()=>{const ne=R.current;if(!ne)return;const be=Ae.length>1&&!ge;ne.allowTouchMove!==be&&(ne.allowTouchMove=be,he("[swiper:allow-touch-sync]",{nextAllow:be,sidebarOverlayOpen:ge}))},[Ae.length,he,ge]);const Xe=A.useCallback(ne=>{const be=R.current;if(!be)return;const Te=be.el;if(he("[swiper:layout-before]",{reason:ne,scrollLeft:Te?.scrollLeft??null}),Te&&(Te.scrollLeft=0),be.updateSize(),be.updateSlides(),be.updateProgress(),be.updateSlidesClasses(),Te&&(Te.scrollLeft=0),he("[swiper:layout-after]",{reason:ne,scrollLeft:Te?.scrollLeft??null}),G.current||be.animating){he("[swiper:layout-skip-sync-motion]",{reason:ne});return}kt(`layout:${ne}`,{immediate:!0}),requestAnimationFrame(()=>{const ue=R.current;ue&&(G.current||ue.animating||rf(ue,Se.current))})},[he,kt]);A.useEffect(()=>()=>Ce(),[Ce]);const $e=Ae.map(ne=>ne.id).join("\0");A.useEffect(()=>{requestAnimationFrame(()=>Xe("group-change"))},[ke,$e,Xe]),A.useEffect(()=>{const ne=()=>{requestAnimationFrame(()=>Xe("viewport-change"))};return window.addEventListener("resize",ne),window.visualViewport?.addEventListener("resize",ne),window.visualViewport?.addEventListener("scroll",ne),ne(),()=>{window.removeEventListener("resize",ne),window.visualViewport?.removeEventListener("resize",ne),window.visualViewport?.removeEventListener("scroll",ne)}},[Xe]),A.useEffect(()=>{if(typeof document>"u")return;let ne=null;const be=xt=>{if(xt!=="online"&&document.hidden)return;const Rt=xt==="bfcache"||xt==="online"?xt:"visibility";N(at=>({token:at.token+1,reason:Rt})),requestAnimationFrame(()=>Xe(`resume:${xt}:raf`)),ne&&clearTimeout(ne),ne=setTimeout(()=>{ne=null,Xe(`resume:${xt}:settled`)},320)},Te=()=>{document.hidden||be("visibility")},ue=xt=>{be(xt.persisted?"bfcache":"pageshow")},ot=()=>be("online");return document.addEventListener("visibilitychange",Te),window.addEventListener("pageshow",ue),window.addEventListener("online",ot),()=>{document.removeEventListener("visibilitychange",Te),window.removeEventListener("pageshow",ue),window.removeEventListener("online",ot),ne&&clearTimeout(ne)}},[Xe]),A.useEffect(()=>{const ne=HN(g),be=JSON.stringify(ne);ne.length>0&&be!==fe.current?(fe.current=be,console.warn("[session-invariant] duplicate mapping detected",ne)):ne.length===0&&fe.current&&(fe.current=""),d?.({sessions:g.map(Te=>({id:Te.id,name:Te.name,customName:Te.customName,mode:Te.mode,tmuxSessionName:Te.tmuxSessionName})),activeSessionId:v})},[g,v,d]),A.useEffect(()=>{if(Fe||D.current)return;D.current=!0;const ne=GN(Qe,de),be=p4(Qe.map(m4));if(f("[Session] Restoring",be.length,"persisted sessions (one-shot)"),he("[swiper:restore-start]",{persistedSessionIds:Qe.map(ue=>ue.sessionId),nextActiveSessionId:ne}),be.length>0){const ue=Vn.getState();be.forEach(ot=>{ot.sessionId&&ue.setTerminalSession(ot.id,{sessionId:ot.sessionId,cols:80,rows:24,mode:ot.mode,tmuxSessionName:ot.tmuxSessionName,history:ot.history})}),Qe.forEach(ot=>{ot.activeProgram!=null&&ue.setSessionActiveProgram(ot.sessionId,ot.activeProgram),ot.cwd!=null&&ue.setSessionCwd(ot.sessionId,ot.cwd)}),y(be),w(ne||be[0]?.id||null),he("[swiper:restore-complete]",{restoredSessionIds:be.map(ot=>ot.id),nextActiveSessionId:ne||be[0]?.id||null})}(async()=>(be.length===0&&await ie.current?.({createIfEmpty:!0}),C(!1),requestAnimationFrame(()=>kt("restore-finished",{immediate:!0}))))()},[Fe,Qe,de,f,he,kt]);const lt=A.useRef([]),$t=A.useRef(!1);ee.current=v,A.useEffect(()=>{if(T)return;const ne=lt.current,be=Qe;if(!$t.current){y(qe=>hy(qe,be)),lt.current=be,$t.current=!0;return}const Te=new Set(ne.map(qe=>qe.sessionId)),ue=new Set(be.map(qe=>qe.sessionId)),ot=new Map(ne.map(qe=>[qe.sessionId,qe.name]));lt.current=be,y(qe=>{const st=hy(qe,be);return(!ee.current||!st.some(mt=>mt.id===ee.current))&&w(st[0]?.id??null),st});const xt=be.filter(qe=>!Te.has(qe.sessionId)),Rt=[...Te].filter(qe=>!ue.has(qe)),at=be.filter(qe=>Te.has(qe.sessionId)&&ot.get(qe.sessionId)!==qe.name);(xt.length>0||Rt.length>0||at.length>0)&&f("[Session] Synced persisted sessions:",{newSessionIds:xt.map(qe=>qe.sessionId),removedSessionIds:Rt,renamedSessionIds:at.map(qe=>qe.sessionId),currentSessionIds:be.map(qe=>qe.sessionId)});for(const qe of be){if(!qe.backendSessionId)continue;Vn.getState().setTerminalSession(qe.sessionId,{sessionId:qe.backendSessionId,cols:80,rows:24,mode:qe.mode,tmuxSessionName:qe.tmuxSessionName})}},[Qe,T,f]);const Ht=A.useCallback(async ne=>{try{const be=ne?.mode==="tmux"||ne?.mode==="shell"?ne.mode:i,Te=(ne?.tmuxSessionName||"").trim(),ue=a.trim(),ot=be==="tmux"?Te||ue||WN():null,xt=typeof ne?.cwd=="string"?ne.cwd:null,Rt=v?Vn.getState().sessions.get(v)?.cwd??null:null,at=typeof xt=="string"&&xt.trim().length>0?xt:typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0,qe=await rt({mode:be,tmuxSessionName:ot,cwd:at,termType:"xterm-256color",createIfEmpty:ne?.createIfEmpty===!0}),st=qe.session,mt=qe.terminalSession,Ze={id:st.sessionId,name:st.name,customName:st.customName===!0,sessionId:mt.sessionId,mode:mt.mode??st.mode,tmuxSessionName:mt.tmuxSessionName??st.tmuxSessionName};y(Tt=>UN(Tt,Ze)),w(Ze.id),Vn.getState().setTerminalSession(Ze.id,{sessionId:mt.sessionId,cols:80,rows:24,mode:Ze.mode,tmuxSessionName:Ze.tmuxSessionName,activeProgram:mt.activeProgram,activeProgramRaw:mt.activeProgramRaw,activeProgramSource:mt.activeProgramSource,cwd:mt.cwd}),f("[Session] Inventory opened session:",{frontendSessionId:Ze.id,backendSessionId:mt.sessionId,reused:qe.reused,mode:Ze.mode,tmuxSessionName:Ze.tmuxSessionName})}catch(be){console.error("[Session] Failed to create new session:",be)}},[i,a,v,rt,f]);ie.current=Ht;const St=A.useCallback(ne=>{g.find(Te=>Te.id===ne)&&(w(ne),H.current&&!J.current&&O({sessionId:ne,token:Date.now()}),f("[Session] Switched to session:",ne))},[g,f]),ut=A.useCallback((ne,be)=>{be.trim()&&(y(Te=>Te.map(ue=>ue.id===ne?{...ue,name:be.trim(),customName:!0}:ue)),ce(ne,be.trim()))},[ce]),Oe=A.useCallback(ne=>{y(be=>be.map(Te=>Te.id===ne?{...Te,customName:!1}:Te)),je(ne)},[je]),Mt=A.useCallback(ne=>{y(be=>{const Te=new Map(be.map(Rt=>[Rt.id,Rt])),ue=ne.map(Rt=>Te.get(Rt)).filter(Rt=>Rt!==void 0),ot=new Set(ne),xt=be.filter(Rt=>!ot.has(Rt.id));return[...ue,...xt]}),De(ne),f("[Session] Reordered sessions:",ne),requestAnimationFrame(()=>{R.current?.update()})},[De,f]),it=A.useCallback(async ne=>{const be=typeof ne=="string"?ne:ne.sessionId,Te=typeof ne=="string"?"auto":ne.closeMode??"auto",ue=g.find(ot=>ot.id===be);if(ue){try{Te==="destroy"&&ue.mode==="tmux"&&ue.tmuxSessionName?(await j6(ue.tmuxSessionName),f("[Session] Destroyed tmux session:",{frontendSessionId:ue.id,tmuxSessionName:ue.tmuxSessionName})):ue.sessionId&&(await P6(ue.sessionId),f("[Session] Closed backend terminal:",ue.sessionId))}catch(ot){console.error("[Session] Failed to close backend terminal:",ot);return}y(ot=>{const xt=ot.filter(at=>at.id!==be),Rt=xt.length>0?xt[0].id:null;return w(Rt),xt}),Ee(be),delete _.current[be],f("[Session] Closed session:",{sessionId:be,closeMode:Te})}},[g,Ee,f]),Me=A.useCallback(ne=>{if(!ne)return;const be=g.filter(Te=>Te.sessionId===ne);if(be.length!==0){be.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:ne,frontendSessionIds:be.map(Te=>Te.id)}),y(Te=>{const ue=Te.filter(ot=>ot.sessionId!==ne);return ue.length!==Te.length&&!ue.some(xt=>xt.id===v)&&w(ue.length>0?ue[0].id:null),ue});for(const Te of be)Ee(Te.id),delete _.current[Te.id];f("[Session] Backend gone, dropped local session(s):",be.map(Te=>Te.id))}},[g,v,Ee,f]);return A.useEffect(()=>{const ne=st=>{Ht(st.detail)},be=st=>{St(st.detail)},Te=()=>{const st=ee.current;!st||J.current||O({sessionId:st,token:Date.now()})},ue=st=>{const Ze=st.detail?.direction;if(Ze!=="prev"&&Ze!=="next")return;const rr=Ve.current;if(rr.length<=1)return;const Tt=ee.current,yr=Tt?rr.findIndex(et=>et.id===Tt):-1,le=((yr>=0?yr:0)+(Ze==="next"?1:-1)+rr.length)%rr.length,Yt=rr[le]?.id;Yt&&Yt!==Tt&&St(Yt)},ot=st=>{it(st.detail)},xt=st=>{Me(st.detail)},Rt=st=>{const mt=st;!mt.detail?.sessionId||!mt.detail?.name||ut(mt.detail.sessionId,mt.detail.name)},at=st=>{const mt=st;mt.detail?.sessionId&&Oe(mt.detail.sessionId)},qe=st=>{const mt=st;mt.detail?.sessionIds&&Mt(mt.detail.sessionIds)};return window.addEventListener("new-terminal-session",ne),window.addEventListener("switch-terminal-session",be),window.addEventListener("focus-active-terminal-session",Te),window.addEventListener("cycle-terminal-session",ue),window.addEventListener("close-terminal-session",ot),window.addEventListener("close-terminal-session-by-backend",xt),window.addEventListener("rename-terminal-session",Rt),window.addEventListener("reset-terminal-session-name",at),window.addEventListener("reorder-terminal-session",qe),()=>{window.removeEventListener("new-terminal-session",ne),window.removeEventListener("switch-terminal-session",be),window.removeEventListener("focus-active-terminal-session",Te),window.removeEventListener("cycle-terminal-session",ue),window.removeEventListener("close-terminal-session",ot),window.removeEventListener("close-terminal-session-by-backend",xt),window.removeEventListener("rename-terminal-session",Rt),window.removeEventListener("reset-terminal-session-name",at),window.removeEventListener("reorder-terminal-session",qe)}},[Ht,St,it,Me,ut,Oe,Mt]),c.jsx("div",{className:"h-full flex flex-col",children:c.jsx("div",{className:"flex-1 overflow-hidden",children:c.jsx(sh,{onSwiper:ne=>{R.current=ne,ne.allowTouchMove=Ae.length>1&&!ge,he("[swiper:on-swiper]",{allowTouchMove:ne.allowTouchMove}),requestAnimationFrame(()=>Xe("on-swiper"))},onSlideChange:wt,onTouchStart:(ne,be)=>{const Te=fy(be),ue=Te==="touch"||Te==="pen"||Te==="unknown";b("[swipe:touch-start]",{pointerType:Te,allowed:ue}),he("[swiper:touch-start]",{pointerType:Te,allowed:ue}),ue&&(Ce(),G.current=!0)},onTouchEnd:(ne,be)=>{const Te=fy(be),ue=Te==="touch"||Te==="pen"||Te==="unknown";b("[swipe:touch-end]",{pointerType:Te,allowed:ue}),he("[swiper:touch-end]",{pointerType:Te,allowed:ue}),ue&&nt("touch-end")},onTransitionEnd:()=>{const ne=R.current;if(G.current&&ne&&!$N(ne,Se.current)){he("[swiper:transition-end-deferred]");return}Ce(),G.current=!1,he("[swiper:transition-end]")},initialSlide:Math.max(0,Be),speed:Q1,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:Ae.map(ne=>{const be=ne.id===v;return c.jsx(Ec,{className:"h-full",children:c.jsx(lN,{sessionId:ne.id,mode:ne.mode,tmuxSessionName:ne.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:be,focusRequestToken:M?.sessionId===ne.id?M.token:0,resumeRequestToken:E.token,resumeRequestReason:E.reason,onKeyboardVisibilityChange:vt,showDebug:n,onStatusChange:be?u:void 0})},ne.id)})})})})};function zi(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 qN=typeof Symbol=="function"&&Symbol.observable||"@@observable",my=qN,gy=()=>Math.random().toString(36).substring(7).split("").join("."),YN={INIT:`@@redux/INIT${gy()}`,REPLACE:`@@redux/REPLACE${gy()}`},by=YN;function ZN(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 g4(e,t,r){if(typeof e!="function")throw new Error(zi(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(zi(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(zi(1));return r(g4)(e,t)}let n=e,s=t,i=new Map,a=i,u=0,d=!1;function f(){a===i&&(a=new Map,i.forEach((C,E)=>{a.set(E,C)}))}function b(){if(d)throw new Error(zi(3));return s}function g(C){if(typeof C!="function")throw new Error(zi(4));if(d)throw new Error(zi(5));let E=!0;f();const N=u++;return a.set(N,C),function(){if(E){if(d)throw new Error(zi(6));E=!1,f(),a.delete(N),i=null}}}function y(C){if(!ZN(C))throw new Error(zi(7));if(typeof C.type>"u")throw new Error(zi(8));if(typeof C.type!="string")throw new Error(zi(17));if(d)throw new Error(zi(9));try{d=!0,s=n(s,C)}finally{d=!1}return(i=a).forEach(N=>{N()}),C}function v(C){if(typeof C!="function")throw new Error(zi(10));n=C,y({type:by.REPLACE})}function w(){const C=g;return{subscribe(E){if(typeof E!="object"||E===null)throw new Error(zi(11));function N(){const R=E;R.next&&R.next(b())}return N(),{unsubscribe:C(N)}},[my](){return this}}}return y({type:by.INIT}),{dispatch:y,subscribe:g,getState:b,replaceReducer:v,[my]:w}}function xy(e,t){return function(...r){return t(e.apply(this,r))}}function yy(e,t){if(typeof e=="function")return xy(e,t);if(typeof e!="object"||e===null)throw new Error(zi(16));const r={};for(const n in e){const s=e[n];typeof s=="function"&&(r[n]=xy(s,t))}return r}function b4(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function KN(...e){return t=>(r,n)=>{const s=t(r,n);let i=()=>{throw new Error(zi(15))};const a={getState:s.getState,dispatch:(d,...f)=>i(d,...f)},u=e.map(d=>d(a));return i=b4(...u)(s.dispatch),{...s,dispatch:i}}}var Ig={exports:{}},Mg={};var vy;function XN(){if(vy)return Mg;vy=1;var e=_p();function t(d,f){return d===f&&(d!==0||1/d===1/f)||d!==d&&f!==f}var r=typeof Object.is=="function"?Object.is:t,n=e.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,u=e.useDebugValue;return Mg.useSyncExternalStoreWithSelector=function(d,f,b,g,y){var v=s(null);if(v.current===null){var w={hasValue:!1,value:null};v.current=w}else w=v.current;v=a(function(){function C(_){if(!E){if(E=!0,N=_,_=g(_),y!==void 0&&w.hasValue){var M=w.value;if(y(M,_))return D=M}return D=_}if(M=D,r(N,_))return M;var O=g(_);return y!==void 0&&y(M,O)?(N=_,M):(N=_,D=O)}var E=!1,N,D,R=b===void 0?null:b;return[function(){return C(f())},R===null?void 0:function(){return C(R())}]},[f,b,g,y]);var T=n(d,v[0],v[1]);return i(function(){w.hasValue=!0,w.value=T},[T]),u(T),T},Mg}var wy;function JN(){return wy||(wy=1,Ig.exports=XN()),Ig.exports}JN();var eD=A.version.startsWith("19"),tD=Symbol.for(eD?"react.transitional.element":"react.element"),rD=Symbol.for("react.portal"),nD=Symbol.for("react.fragment"),sD=Symbol.for("react.strict_mode"),iD=Symbol.for("react.profiler"),oD=Symbol.for("react.consumer"),aD=Symbol.for("react.context"),x4=Symbol.for("react.forward_ref"),lD=Symbol.for("react.suspense"),cD=Symbol.for("react.suspense_list"),W2=Symbol.for("react.memo"),uD=Symbol.for("react.lazy"),dD=x4,hD=W2;function fD(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case tD:switch(e=e.type,e){case nD:case iD:case sD:case lD:case cD:return e;default:switch(e=e&&e.$$typeof,e){case aD:case x4:case uD:case W2:return e;case oD:return e;default:return t}}case rD:return t}}}function pD(e){return fD(e)===W2}function mD(e,t,r,n,{areStatesEqual:s,areOwnPropsEqual:i,areStatePropsEqual:a}){let u=!1,d,f,b,g,y;function v(N,D){return d=N,f=D,b=e(d,f),g=t(n,f),y=r(b,g,f),u=!0,y}function w(){return b=e(d,f),t.dependsOnOwnProps&&(g=t(n,f)),y=r(b,g,f),y}function T(){return e.dependsOnOwnProps&&(b=e(d,f)),t.dependsOnOwnProps&&(g=t(n,f)),y=r(b,g,f),y}function C(){const N=e(d,f),D=!a(N,b);return b=N,D&&(y=r(b,g,f)),y}function E(N,D){const R=!i(D,f),_=!s(N,d,D,f);return d=N,f=D,R&&_?w():R?T():_?C():y}return function(D,R){return u?E(D,R):v(D,R)}}function gD(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...s}){const i=t(e,s),a=r(e,s),u=n(e,s);return mD(i,a,u,e,s)}function bD(e,t){const r={};for(const n in e){const s=e[n];typeof s=="function"&&(r[n]=(...i)=>t(s(...i)))}return r}function O1(e){return function(r){const n=e(r);function s(){return n}return s.dependsOnOwnProps=!1,s}}function Ay(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function y4(e,t){return function(n,{displayName:s}){const i=function(u,d){return i.dependsOnOwnProps?i.mapToProps(u,d):i.mapToProps(u,void 0)};return i.dependsOnOwnProps=!0,i.mapToProps=function(u,d){i.mapToProps=e,i.dependsOnOwnProps=Ay(e);let f=i(u,d);return typeof f=="function"&&(i.mapToProps=f,i.dependsOnOwnProps=Ay(f),f=i(u,d)),f},i}}function V2(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function xD(e){return e&&typeof e=="object"?O1(t=>bD(e,t)):e?typeof e=="function"?y4(e):V2(e,"mapDispatchToProps"):O1(t=>({dispatch:t}))}function yD(e){return e?typeof e=="function"?y4(e):V2(e,"mapStateToProps"):O1(()=>({}))}function vD(e,t,r){return{...r,...e,...t}}function wD(e){return function(r,{displayName:n,areMergedPropsEqual:s}){let i=!1,a;return function(d,f,b){const g=e(d,f,b);return i?s(g,a)||(a=g):(i=!0,a=g),a}}}function AD(e){return e?typeof e=="function"?wD(e):V2(e,"mergeProps"):()=>vD}function TD(e){e()}function SD(){let e=null,t=null;return{clear(){e=null,t=null},notify(){TD(()=>{let r=e;for(;r;)r.callback(),r=r.next})},get(){const r=[];let n=e;for(;n;)r.push(n),n=n.next;return r},subscribe(r){let n=!0;const s=t={callback:r,next:null,prev:t};return s.prev?s.prev.next=s:e=s,function(){!n||e===null||(n=!1,s.next?s.next.prev=s.prev:t=s.prev,s.prev?s.prev.next=s.next:e=s.next)}}}}var Ty={notify(){},get:()=>[]};function v4(e,t){let r,n=Ty,s=0,i=!1;function a(T){b();const C=n.subscribe(T);let E=!1;return()=>{E||(E=!0,C(),g())}}function u(){n.notify()}function d(){w.onStateChange&&w.onStateChange()}function f(){return i}function b(){s++,r||(r=t?t.addNestedSub(d):e.subscribe(d),n=SD())}function g(){s--,r&&s===0&&(r(),r=void 0,n.clear(),n=Ty)}function y(){i||(i=!0,b())}function v(){i&&(i=!1,g())}const w={addNestedSub:a,notifyNestedSubs:u,handleChangeWrapper:d,isSubscribed:f,trySubscribe:y,tryUnsubscribe:v,getListeners:()=>n};return w}var CD=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",_D=CD(),LD=()=>typeof navigator<"u"&&navigator.product==="ReactNative",kD=LD(),ED=()=>_D||kD?A.useLayoutEffect:A.useEffect,tp=ED();function Sy(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Rg(e,t){if(Sy(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let s=0;s<r.length;s++)if(!Object.prototype.hasOwnProperty.call(t,r[s])||!Sy(e[r[s]],t[r[s]]))return!1;return!0}var ID={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},MD={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},RD={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},w4={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},ND={[dD]:RD,[hD]:w4};function Cy(e){return pD(e)?w4:ND[e.$$typeof]||ID}var DD=Object.defineProperty,BD=Object.getOwnPropertyNames,_y=Object.getOwnPropertySymbols,PD=Object.getOwnPropertyDescriptor,jD=Object.getPrototypeOf,Ly=Object.prototype;function $1(e,t){if(typeof t!="string"){if(Ly){const i=jD(t);i&&i!==Ly&&$1(e,i)}let r=BD(t);_y&&(r=r.concat(_y(t)));const n=Cy(e),s=Cy(t);for(let i=0;i<r.length;++i){const a=r[i];if(!MD[a]&&!(s&&s[a])&&!(n&&n[a])){const u=PD(t,a);try{DD(e,a,u)}catch{}}}}return e}var QD=Symbol.for("react-redux-context"),FD=typeof globalThis<"u"?globalThis:{};function OD(){if(!A.createContext)return{};const e=FD[QD]??=new Map;let t=e.get(A.createContext);return t||(t=A.createContext(null),e.set(A.createContext,t)),t}var A4=OD(),$D=[null,null];function HD(e,t,r){tp(()=>e(...t),r)}function UD(e,t,r,n,s,i){e.current=n,r.current=!1,s.current&&(s.current=null,i())}function GD(e,t,r,n,s,i,a,u,d,f,b){if(!e)return()=>{};let g=!1,y=null;const v=()=>{if(g||!u.current)return;const T=t.getState();let C,E;try{C=n(T,s.current)}catch(N){E=N,y=N}E||(y=null),C===i.current?a.current||f():(i.current=C,d.current=C,a.current=!0,b())};return r.onStateChange=v,r.trySubscribe(),v(),()=>{if(g=!0,r.tryUnsubscribe(),r.onStateChange=null,y)throw y}}function zD(e,t){return e===t}function WD(e,t,r,{pure:n,areStatesEqual:s=zD,areOwnPropsEqual:i=Rg,areStatePropsEqual:a=Rg,areMergedPropsEqual:u=Rg,forwardRef:d=!1,context:f=A4}={}){const b=f,g=yD(e),y=xD(t),v=AD(r),w=!!e;return C=>{const E=C.displayName||C.name||"Component",N=`Connect(${E})`,D={shouldHandleStateChanges:w,displayName:N,wrappedComponentName:E,WrappedComponent:C,initMapStateToProps:g,initMapDispatchToProps:y,initMergeProps:v,areStatesEqual:s,areStatePropsEqual:a,areOwnPropsEqual:i,areMergedPropsEqual:u};function R(O){const[H,G,U]=A.useMemo(()=>{const{reactReduxForwardedRef:Re,...ct}=O;return[O.context,Re,ct]},[O]),W=A.useMemo(()=>{let Re=b;return H?.Consumer,Re},[H,b]),J=A.useContext(W),ee=!!O.store&&!!O.store.getState&&!!O.store.dispatch,ae=!!J&&!!J.store,Se=ee?O.store:J.store,Le=ae?J.getServerState:Se.getState,_e=A.useMemo(()=>gD(Se.dispatch,D),[Se]),[se,ie]=A.useMemo(()=>{if(!w)return $D;const Re=v4(Se,ee?void 0:J.subscription),ct=Re.notifyNestedSubs.bind(Re);return[Re,ct]},[Se,ee,J]),fe=A.useMemo(()=>ee?J:{...J,subscription:se},[ee,J,se]),Qe=A.useRef(void 0),de=A.useRef(U),Fe=A.useRef(void 0),rt=A.useRef(!1),ht=A.useRef(!1),Ee=A.useRef(void 0);tp(()=>(ht.current=!0,()=>{ht.current=!1}),[]);const ce=A.useMemo(()=>()=>Fe.current&&U===de.current?Fe.current:_e(Se.getState(),U),[Se,U]),je=A.useMemo(()=>ct=>se?GD(w,Se,se,_e,de,Qe,rt,ht,Fe,ie,ct):()=>{},[se]);HD(UD,[de,Qe,rt,U,Fe,ie]);let De;try{De=A.useSyncExternalStore(je,ce,Le?()=>_e(Le(),U):ce)}catch(Re){throw Ee.current&&(Re.message+=`
|
|
75
75
|
The error may be correlated with this previous error:
|
|
76
76
|
${Ee.current.stack}
|
|
77
77
|
|
|
@@ -163,7 +163,7 @@ ${M.desc}`:""}`,"aria-pressed":v===M.key,onPointerEnter:()=>y(M.key),onPointerLe
|
|
|
163
163
|
`),blockKey:`${t}-code-${C}`},`${t}-code-${C}`):["math","latex","tex"].includes(T.toLowerCase())?c.jsx(th,{tex:v.join(`
|
|
164
164
|
`),display:!0},`${t}-code-${C}`):c.jsx(nh,{code:v.join(`
|
|
165
165
|
`),lang:T,blockKey:`${t}-code-${C}`},`${t}-code-${C}`));continue}if(Ap(i)){const v=[],w=s;for(;s<e.length&&(Ap(e[s])||!e[s].trim());)v.push(e[s].trim()?g9(e[s]):""),s+=1;n.push(c.jsx(nh,{code:v.join(`
|
|
166
|
-
`).replace(/\n+$/,""),lang:"",blockKey:`${t}-indented-code-${w}`},`${t}-indented-code-${w}`));continue}const f=a.match(/^(#{1,6})\s+(.+)$/);if(f){const w=`h${Math.min(6,f[1].length+1)}`,T=a9(f[2]),C=x2(T,r);n.push(c.jsx(w,{id:C,className:"scroll-mt-16 font-semibold text-foreground",children:Xs(T,`${t}-heading-${s}`,!0,r)},`${t}-heading-${s}`)),s+=1;continue}if(s+1<e.length&&i.includes("|")&&Sp(e[s+1])){const v=rh(i),w=b9(e[s+1]),T=[],C=s;for(s+=2;s<e.length&&e[s].includes("|")&&e[s].trim();)T.push(rh(e[s])),s+=1;n.push(c.jsx("div",{className:Z8,"data-markdown-table-scroll":!0,children:c.jsxs("table",{className:"w-max min-w-full max-w-none table-auto border-collapse text-left text-[11px] sm:text-xs",children:[c.jsx("thead",{className:"bg-surface-2 text-foreground",children:c.jsx("tr",{children:v.map((E,N)=>c.jsx("th",{className:`${q8} ${Tp(w[N]??null)}`,children:c.jsx("div",{className:vp,children:Xs(E,`${t}-th-${C}-${N}`,!0,r)})},`h-${N}`))})}),c.jsx("tbody",{children:T.map((E,N)=>c.jsx("tr",{className:"border-t border-border/10",children:v.map((D,R)=>c.jsx("td",{className:`${Y8} ${Tp(w[R]??null)}`,children:c.jsx("div",{className:vp,children:Xs(E[R]??"",`${t}-td-${C}-${N}-${R}`,!0,r)})},`c-${R}`))},`r-${N}`))})]})},`${t}-table-${C}`));continue}const b=P5(i);if(b){const v=b.ordered,w=B5(i),T=b.start,C=s,E=x9(e,s,w,v,!1);s=E.nextIndex;const N=v?"ol":"ul";n.push(c.jsx(N,{start:v?T:void 0,className:`${v?"list-decimal":"list-disc"} space-y-0.5 pl-4 marker:text-muted-foreground/70`,children:j5(E.items,C,r)},`${t}-list-${C}`));continue}const g=[i.trimStart()],y=s;for(s+=1;s<e.length&&e[s].trim()&&!b2(e[s])&&!(s+1<e.length&&e[s].includes("|")&&Sp(e[s+1]));)g.push(e[s].trimStart()),s+=1;n.push(c.jsx("p",{children:Dd(g,`${t}-p-${y}`,r)},`${t}-p-${y}`))}return n}let yf=null,j3=!1;const vf=16,y9=192;function IW(){return yf||(yf=qd(()=>import("./mermaid.core-
|
|
166
|
+
`).replace(/\n+$/,""),lang:"",blockKey:`${t}-indented-code-${w}`},`${t}-indented-code-${w}`));continue}const f=a.match(/^(#{1,6})\s+(.+)$/);if(f){const w=`h${Math.min(6,f[1].length+1)}`,T=a9(f[2]),C=x2(T,r);n.push(c.jsx(w,{id:C,className:"scroll-mt-16 font-semibold text-foreground",children:Xs(T,`${t}-heading-${s}`,!0,r)},`${t}-heading-${s}`)),s+=1;continue}if(s+1<e.length&&i.includes("|")&&Sp(e[s+1])){const v=rh(i),w=b9(e[s+1]),T=[],C=s;for(s+=2;s<e.length&&e[s].includes("|")&&e[s].trim();)T.push(rh(e[s])),s+=1;n.push(c.jsx("div",{className:Z8,"data-markdown-table-scroll":!0,children:c.jsxs("table",{className:"w-max min-w-full max-w-none table-auto border-collapse text-left text-[11px] sm:text-xs",children:[c.jsx("thead",{className:"bg-surface-2 text-foreground",children:c.jsx("tr",{children:v.map((E,N)=>c.jsx("th",{className:`${q8} ${Tp(w[N]??null)}`,children:c.jsx("div",{className:vp,children:Xs(E,`${t}-th-${C}-${N}`,!0,r)})},`h-${N}`))})}),c.jsx("tbody",{children:T.map((E,N)=>c.jsx("tr",{className:"border-t border-border/10",children:v.map((D,R)=>c.jsx("td",{className:`${Y8} ${Tp(w[R]??null)}`,children:c.jsx("div",{className:vp,children:Xs(E[R]??"",`${t}-td-${C}-${N}-${R}`,!0,r)})},`c-${R}`))},`r-${N}`))})]})},`${t}-table-${C}`));continue}const b=P5(i);if(b){const v=b.ordered,w=B5(i),T=b.start,C=s,E=x9(e,s,w,v,!1);s=E.nextIndex;const N=v?"ol":"ul";n.push(c.jsx(N,{start:v?T:void 0,className:`${v?"list-decimal":"list-disc"} space-y-0.5 pl-4 marker:text-muted-foreground/70`,children:j5(E.items,C,r)},`${t}-list-${C}`));continue}const g=[i.trimStart()],y=s;for(s+=1;s<e.length&&e[s].trim()&&!b2(e[s])&&!(s+1<e.length&&e[s].includes("|")&&Sp(e[s+1]));)g.push(e[s].trimStart()),s+=1;n.push(c.jsx("p",{children:Dd(g,`${t}-p-${y}`,r)},`${t}-p-${y}`))}return n}let yf=null,j3=!1;const vf=16,y9=192;function IW(){return yf||(yf=qd(()=>import("./mermaid.core-D2G1KcAK.js").then(e=>e.aJ),__vite__mapDeps([3,1,4])).then(e=>e.default??e).catch(e=>{throw yf=null,e})),yf}function MW(e){j3||(e.initialize({startOnLoad:!1,securityLevel:"strict",theme:"neutral"}),j3=!0)}function RW(e){const t=e.match(/\sviewBox=(["'])([^"']+)\1/i);if(!t)return e;const[,,r]=t,n=r.trim().split(/[\s,]+/).map(Number),[,,s,i]=n;if(!Number.isFinite(s)||!Number.isFinite(i)||s<=0||i<=0)return e;const a=Math.max(y9,Math.ceil(s)),u=Math.ceil(a/s*i);return e.replace(/<svg\b([^>]*)>/i,(d,f)=>`<svg${f.replace(/\s(?:width|height)=(["']).*?\1/gi,"").replace(/\sstyle=(["']).*?\1/gi,"")} width="${a}" height="${u}">`)}function NW(e){const t=e?.querySelector("svg");if(!t)return;let r;try{r=t.getBBox()}catch{return}if(!Number.isFinite(r.width)||!Number.isFinite(r.height)||r.width<=0||r.height<=0)return;const n=r.x-vf,s=r.y-vf,i=r.width+vf*2,a=r.height+vf*2,u=Math.max(y9,Math.ceil(i)),d=Math.ceil(u/i*a);t.setAttribute("viewBox",`${n} ${s} ${i} ${a}`),t.setAttribute("width",String(u)),t.setAttribute("height",String(d)),t.removeAttribute("style")}function DW(e){const t=e.trim().split(/\s+/,1)[0]?.toLowerCase();if(!t)return null;const r=t.replace(/^language-/,"");return B8(`code.${r}`)??r}function v9({code:e,blockKey:t}){const[r,n]=A.useState(null),[s,i]=A.useState(!1),a=A.useRef(null),u=A.useContext(i9);A.useEffect(()=>{let f=!1;return n(null),i(!1),IW().then(async b=>{MW(b);const g=`termdock-md-mermaid-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`,{svg:y}=await b.render(g,e);f||n(RW(y))}).catch(()=>{f||i(!0)}),()=>{f=!0}},[t,e]),A.useLayoutEffect(()=>{r&&NW(a.current)},[r]);const d=A.useCallback(()=>{const f=a.current?.querySelector("svg")?.outerHTML??r;f&&u?.(f)},[u,r]);return s?c.jsx(nh,{code:e,lang:"mermaid",blockKey:`${t}-fallback`}):c.jsxs("div",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface shadow-sm",children:[c.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"}),c.jsx("div",{className:"bg-surface p-3",children:r?c.jsx("button",{type:"button",className:"block max-w-full rounded text-left focus:outline-none focus:ring-2 focus:ring-ring/45",title:"Open Mermaid diagram",onClick:f=>{f.stopPropagation(),d()},children:c.jsx("span",{ref:a,role:"img","aria-label":"Mermaid diagram",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}})}):c.jsx("div",{className:"py-6 text-center text-xs text-muted-foreground",children:"Rendering diagram..."})})]})}function nh({code:e,lang:t,blockKey:r}){const n=DW(t),[s,i]=A.useState(null);return A.useEffect(()=>{if(!n||!P8(e)){i(null);return}let a=!1;return j8().then(u=>{if(a||!u.registered(n)){a||i(null);return}try{i(Q8(u.highlight(e,n),`md-code-${r}`))}catch{a||i(null)}}).catch(()=>{a||i(null)}),()=>{a=!0}},[r,e,n]),c.jsxs("div",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface shadow-sm",children:[t&&c.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}),c.jsx("pre",{className:`${D5} termdock-code overflow-auto p-3 text-[11px] leading-relaxed text-foreground`,children:c.jsx("code",{children:s??(e||" ")})})]})}function BW(e,t,r,n){e=dW(e);const s=lW(e),i=uW(e),a=[],u={markdownFilePath:t,rootPath:r,referenceDefinitions:s,footnoteDefinitions:cW(e),headingSlugCounts:new Map,images:a,onImageOpen:n},d=[];let f=0;for(;f<e.length;){const g=e[f],y=g.trim();if(wp(g)||i.has(f)){f+=1;continue}if(!y){f+=1;continue}if(/^<details>\s*$/i.test(y)){const D=f;let R="Details";const _=[];for(f+=1;f<e.length&&!/^<\/details>\s*$/i.test(e[f].trim());){const M=e[f].trim().match(/^<summary>(.*?)<\/summary>\s*$/i);M?R=M[1].trim()||R:_.push(e[f].trimStart()),f+=1}f<e.length&&(f+=1),d.push({key:`details-${D}`,startLine:D+1,endLine:f,content:c.jsxs("details",{className:"overflow-hidden rounded-lg border border-border/20 bg-surface px-3 py-2 text-muted-foreground",children:[c.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-foreground",children:Xs(R,`details-${D}-summary`,!0,u)}),_.length>0&&c.jsx("div",{className:"mt-2 text-sm leading-6",children:Dd(_,`details-${D}`,u)})]})});continue}const v=m9(g);if(v){const D=[g],R=f;for(f+=1;f<e.length&&!v.selfContained&&!new RegExp(`</${v.tag}>`,"i").test(e[f]);)D.push(e[f]),f+=1;f<e.length&&!v.selfContained&&(D.push(e[f]),f+=1),d.push({key:`html-${R}`,startLine:R+1,endLine:f,content:c.jsx(p9,{html:D.join(`
|
|
167
167
|
`)})});continue}const w=y.match(/^(```|~~~)\s*(.*)$/);if(w){const D=[],R=w[1],_=w[2]?.trim(),M=f;for(f+=1;f<e.length&&!e[f].trim().startsWith(R);)D.push(e[f]),f+=1;f<e.length&&(f+=1),d.push({key:`code-${M}`,startLine:M+1,endLine:f,content:_.toLowerCase()==="mermaid"?c.jsx(v9,{code:D.join(`
|
|
168
168
|
`),blockKey:`code-${M}`}):["math","latex","tex"].includes(_.toLowerCase())?c.jsx(th,{tex:D.join(`
|
|
169
169
|
`),display:!0}):c.jsx(nh,{code:D.join(`
|
|
@@ -405,4 +405,4 @@ ${Te}
|
|
|
405
405
|
config.retry = 2;
|
|
406
406
|
return config;
|
|
407
407
|
}`}};function l6(){if(typeof window>"u")return"kotlin";const t=new URLSearchParams(window.location.search).get("fixture");return t&&t in A2?t:"kotlin"}function c6(){return typeof window>"u"?"unified":new URLSearchParams(window.location.search).get("view")==="split"?"split":"unified"}function u6(){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 d6(){return typeof window>"u"?!0:new URLSearchParams(window.location.search).get("wrap")!=="off"}function UV(){const[e,t]=A.useState(()=>l6()),[r,n]=A.useState(()=>c6()),[s,i]=A.useState(()=>u6()),[a,u]=A.useState(()=>d6()),d=A2[e],f=A.useMemo(()=>Object.entries(A2),[]);return A.useEffect(()=>{if(typeof window>"u")return;let b=window.location.search;const g=()=>{window.location.search!==b&&(b=window.location.search,t(l6()),n(c6()),i(u6()),u(d6()))};window.addEventListener("popstate",g),window.addEventListener("pageshow",g),window.addEventListener("focus",g);const y=window.setInterval(g,250);return()=>{window.removeEventListener("popstate",g),window.removeEventListener("pageshow",g),window.removeEventListener("focus",g),window.clearInterval(y)}},[]),c.jsx("div",{className:"min-h-screen bg-background-subtle text-foreground","data-diff-lab":!0,"data-diff-lab-fixture":e,"data-diff-lab-view":r,"data-diff-lab-inline":s,"data-diff-lab-wrap":a?"on":"off",children:c.jsxs("div",{className:"mx-auto flex min-h-screen max-w-[1180px] flex-col px-4 py-4",children:[c.jsxs("header",{className:"mb-3 flex flex-wrap items-center justify-between gap-3 border-b border-border/20 pb-3",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-sm font-semibold",children:"Diff Lab"}),c.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."})]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx("select",{value:e,onChange:b=>t(b.target.value),className:"h-8 rounded-md border border-border/30 bg-surface px-2 text-xs text-foreground outline-none",children:f.map(([b,g])=>c.jsx("option",{value:b,children:g.label},b))}),c.jsxs("div",{className:"inline-flex h-8 overflow-hidden rounded-full bg-surface-2 p-0.5",children:[c.jsx("button",{type:"button",onClick:()=>n("unified"),className:`rounded-full px-3 text-xs font-semibold ${r==="unified"?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:"Unified"}),c.jsx("button",{type:"button",onClick:()=>n("split"),className:`rounded-full px-3 text-xs font-semibold ${r==="split"?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:"Split"})]}),c.jsx("div",{className:"inline-flex h-8 overflow-hidden rounded-full bg-surface-2 p-0.5",children:["none","words","chars"].map(b=>c.jsx("button",{type:"button",onClick:()=>i(b),className:`rounded-full px-3 text-xs font-semibold ${s===b?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:b},b))}),c.jsxs("button",{type:"button",onClick:()=>u(b=>!b),className:`h-8 rounded-full px-3 text-xs font-semibold ${a?"bg-primary/15 text-primary":"bg-surface-2 text-muted-foreground"}`,children:["Wrap ",a?"on":"off"]})]})]}),c.jsx("main",{className:"min-h-0 flex-1 overflow-auto rounded-lg border border-border/20 bg-surface",children:c.jsx(R8,{filePath:d.path,repoRoot:"/tmp/termdock-diff-lab",changedFile:{path:d.path,absolutePath:`/tmp/termdock-diff-lab/${d.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:d.diff,oldSourceOverride:d.oldSource,active:!0,wrap:a,showScrollHint:!a,viewType:r,inlineMode:s})})]})})}const R9=40,T2="/tmp/termdock-diff-review-lab";function h6(e,t){const r=[`diff --git a/${e} b/${e}`,`--- a/${e}`,`+++ b/${e}`,`@@ -1,${t} +1,${t} @@`];for(let n=0;n<t;n+=1)n%5===0&&r.push(`-const removed_${n} = ${n};`),n%3===0&&r.push(`+const added_${n} = ${n} * 2;`),r.push(` context line ${n} in ${e}`);return r.join(`
|
|
408
|
-
`)}function GV(e,t){return Array.from({length:R9},(r,n)=>{const s=6+n*7%60,i=`src/module${String(n).padStart(2,"0")}/File${n}.ts`,a=`${T2}/${i}`,u=h6(i,s),d=h6(i,1);return{key:a,path:i,absolutePath:a,status:"modified",repoRoot:T2,displayName:`File${n}.ts`,displayDir:`src/module${String(n).padStart(2,"0")} · ${s} lines`,diffOverride:!t||e.has(n)?u:d,auditRecords:[]}})}function zV(){const e=A.useMemo(()=>{if(typeof window>"u")return 0;const T=new URLSearchParams(window.location.search).get("delay"),C=T===null?0:Number.parseInt(T,10);return Number.isInteger(C)&&C>0?C:0},[]),t=e>0,[r,n]=A.useState(()=>new Set);A.useEffect(()=>{if(!t)return;const T=Array.from({length:R9},(C,E)=>window.setTimeout(()=>{n(N=>{const D=new Set(N);return D.add(E),D})},e+E*20));return()=>T.forEach(C=>window.clearTimeout(C))},[t,e]);const s=A.useMemo(()=>GV(r,t),[r,t]),i=A.useMemo(()=>[{key:"mock-repo",root:T2,label:"diff-review-lab",files:s.map(T=>({key:T.key,path:T.path,absolutePath:T.absolutePath,displayName:T.displayName,displayDir:T.displayDir,status:T.status}))}],[s]),a=A.useMemo(()=>{if(typeof window>"u")return null;const T=new URLSearchParams(window.location.search).get("select");if(T===null)return null;const C=Number.parseInt(T,10);return Number.isInteger(C)&&C>=0&&C<s.length?C:null},[s.length]),[u,d]=A.useState(()=>a!==null?s[a].key:null),[f,b]=A.useState("list"),[g,y]=A.useState(new Set),[v,w]=A.useState(a!==null?1:0);return c.jsxs("div",{className:"flex h-screen flex-col bg-background text-foreground","data-diff-review-lab":!0,children:[c.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: ",c.jsx("span",{"data-lab-selected":!0,children:u??"none"})," · slide ",v]}),c.jsx("div",{className:"min-h-0 flex-1",children:c.jsx(Nd,{mobile:!0,backLabel:"Back",files:s,groups:i,selectedKey:u,mode:f,onModeChange:T=>{T!=="ai"&&b(T)},collapsedDirectoryKeys:g,onToggleDirectory:T=>y(C=>{const E=new Set(C);return E.has(T)?E.delete(T):E.add(T),E}),onSelectFile:T=>d(T.key),onMobileSlideChange:w,renderLeading:()=>null,renderStreamBadge:T=>c.jsx("span",{className:"text-[10px] text-muted-foreground",children:T}),wrap:!0,showScrollHint:!1,activePane:!0})})]})}const WV=6e4,m1="termdock:build-id:v1";let f6=!1;function p6(){f6||(f6=!0,window.setTimeout(()=>{window.location.reload()},80))}function S2(e){e.waiting?.postMessage({type:"SKIP_WAITING"})}async function VV(){if(typeof caches>"u")return;const e=await caches.keys();await Promise.all(e.map(t=>caches.delete(t)))}function qV(e){e.addEventListener("updatefound",()=>{const t=e.installing;t&&t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&S2(e)})})}function YV(){if(typeof window>"u"||!("serviceWorker"in navigator))return;const e="
|
|
408
|
+
`)}function GV(e,t){return Array.from({length:R9},(r,n)=>{const s=6+n*7%60,i=`src/module${String(n).padStart(2,"0")}/File${n}.ts`,a=`${T2}/${i}`,u=h6(i,s),d=h6(i,1);return{key:a,path:i,absolutePath:a,status:"modified",repoRoot:T2,displayName:`File${n}.ts`,displayDir:`src/module${String(n).padStart(2,"0")} · ${s} lines`,diffOverride:!t||e.has(n)?u:d,auditRecords:[]}})}function zV(){const e=A.useMemo(()=>{if(typeof window>"u")return 0;const T=new URLSearchParams(window.location.search).get("delay"),C=T===null?0:Number.parseInt(T,10);return Number.isInteger(C)&&C>0?C:0},[]),t=e>0,[r,n]=A.useState(()=>new Set);A.useEffect(()=>{if(!t)return;const T=Array.from({length:R9},(C,E)=>window.setTimeout(()=>{n(N=>{const D=new Set(N);return D.add(E),D})},e+E*20));return()=>T.forEach(C=>window.clearTimeout(C))},[t,e]);const s=A.useMemo(()=>GV(r,t),[r,t]),i=A.useMemo(()=>[{key:"mock-repo",root:T2,label:"diff-review-lab",files:s.map(T=>({key:T.key,path:T.path,absolutePath:T.absolutePath,displayName:T.displayName,displayDir:T.displayDir,status:T.status}))}],[s]),a=A.useMemo(()=>{if(typeof window>"u")return null;const T=new URLSearchParams(window.location.search).get("select");if(T===null)return null;const C=Number.parseInt(T,10);return Number.isInteger(C)&&C>=0&&C<s.length?C:null},[s.length]),[u,d]=A.useState(()=>a!==null?s[a].key:null),[f,b]=A.useState("list"),[g,y]=A.useState(new Set),[v,w]=A.useState(a!==null?1:0);return c.jsxs("div",{className:"flex h-screen flex-col bg-background text-foreground","data-diff-review-lab":!0,children:[c.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: ",c.jsx("span",{"data-lab-selected":!0,children:u??"none"})," · slide ",v]}),c.jsx("div",{className:"min-h-0 flex-1",children:c.jsx(Nd,{mobile:!0,backLabel:"Back",files:s,groups:i,selectedKey:u,mode:f,onModeChange:T=>{T!=="ai"&&b(T)},collapsedDirectoryKeys:g,onToggleDirectory:T=>y(C=>{const E=new Set(C);return E.has(T)?E.delete(T):E.add(T),E}),onSelectFile:T=>d(T.key),onMobileSlideChange:w,renderLeading:()=>null,renderStreamBadge:T=>c.jsx("span",{className:"text-[10px] text-muted-foreground",children:T}),wrap:!0,showScrollHint:!1,activePane:!0})})]})}const WV=6e4,m1="termdock:build-id:v1";let f6=!1;function p6(){f6||(f6=!0,window.setTimeout(()=>{window.location.reload()},80))}function S2(e){e.waiting?.postMessage({type:"SKIP_WAITING"})}async function VV(){if(typeof caches>"u")return;const e=await caches.keys();await Promise.all(e.map(t=>caches.delete(t)))}function qV(e){e.addEventListener("updatefound",()=>{const t=e.installing;t&&t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&S2(e)})})}function YV(){if(typeof window>"u"||!("serviceWorker"in navigator))return;const e="1785151490411",t=window.localStorage.getItem(m1);if(t&&t!==e){VV().finally(()=>{window.localStorage.setItem(m1,e),p6()});return}t!==e&&window.localStorage.setItem(m1,e);let r=null;navigator.serviceWorker.addEventListener("controllerchange",p6),window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js",{scope:"/"}).then(n=>{qV(n),S2(n);const s=()=>{document.visibilityState==="visible"&&n.update().then(()=>S2(n)).catch(()=>{})};s(),r=window.setInterval(s,WV),document.addEventListener("visibilitychange",s)}).catch(()=>{})}),window.addEventListener("beforeunload",()=>{r!==null&&window.clearInterval(r)})}mF();YV();try{const e=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(e==="dark"||e==="light")&&(document.documentElement.dataset.theme=e,I7(e))}catch{}function ZV(){const{t:e}=Qn(),[t,r]=A.useState(null),[n,s]=A.useState(null),i=A.useCallback(async()=>{try{const a=await s_();r(a),s(null)}catch(a){s(a instanceof Error?a.message:"Failed to query auth status")}},[]);return A.useEffect(()=>{i()},[i]),A.useEffect(()=>{const a=()=>{r(u=>u&&{...u,authenticated:!1})};return window.addEventListener(Yf,a),()=>window.removeEventListener(Yf,a)},[]),t===null?c.jsx("div",{className:"flex w-screen items-center justify-center bg-background text-muted-foreground",style:{height:"var(--app-vh, 100vh)"},children:n?`${e("common.error")}: ${n}`:e("common.loading")}):t.enabled&&!t.authenticated?c.jsx($V,{onLoginSuccess:i}):c.jsx(FV,{})}RT.createRoot(document.getElementById("root")).render(c.jsx(P.StrictMode,{children:c.jsx(HR,{children:c.jsx(Ww,{children:(()=>{const e=new URLSearchParams(window.location.search);return e.get("dag-playground")==="1"?c.jsx(HV,{}):e.get("diff-review-lab")==="1"?c.jsx(zV,{}):e.get("diff-lab")==="1"?c.jsx(UV,{}):c.jsx(ZV,{})})()})})}));export{qd as _,fC as v};
|