@mmmbuto/nexuscrew 0.8.36 → 0.8.37

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.
@@ -78,7 +78,7 @@ WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){t
78
78
  \x1B[33m[sessione finita]\x1B[0m\r
79
79
  `)})}catch(ve){return P.write(`\r
80
80
  \x1B[31m${ve.message}\x1B[0m\r
81
- `),()=>P.dispose()}k.current={term:P,fit:M,sock:ae,setKeyboardGesture:B};let ue=null;const ge=P.onData(ve=>{if(s){ue&&(ue.ok=!1);return}if(!ue&&f&&f.current&&ve.length===1){const ot=ve.charCodeAt(0);let ht=ot;ot>=97&&ot<=122?ht=ot-96:ot>=64&&ot<=95?ht=ot-64:ot===32&&(ht=0),ve=String.fromCharCode(ht),f.current=!1,_&&_(!1)}const Ye=ae.sendInput(ve);ue&&(ue.seen=!0,ue.ok=ue.ok&&Ye)});u&&(u.current=ve=>ae.sendInput(ve)),p&&(p.current=ve=>ae.action(ve)),h&&(h.current=jC({isReady:()=>!s&&ae.isReady(),paste:ve=>{const Ye={seen:!1,ok:!0};ue=Ye;try{P.paste(ve)}catch{Ye.ok=!1}finally{ue=null}return Ye.seen&&Ye.ok},send:ve=>ae.sendInput(ve)}));const Z=P.onSelectionChange(()=>D(P.getSelection()));P.attachCustomKeyEventHandler(ve=>(ve.ctrlKey||ve.metaKey)&&ve.key.toLowerCase()==="c"&&P.getSelection()?(ve.type==="keydown"&&hv(P.getSelection()),!1):!0);const q=C.current;let fe=!1;const Ie=async ve=>{if(!ve.length||fe)return;if(s){K({error:g("settings-readonly")});return}fe=!0,K({current:0,total:ve.length,name:""});const Ye=await Ky({files:ve,token:n,session:e,node:t,paste:!0,onProgress:({index:ot,total:ht,name:mn,state:Pn,error:Ai})=>K({current:ot+1,total:ht,name:mn,...Pn==="error"?{error:Ai}:{}})});fe=!1,Ye.errors.length?K({error:Ye.errors.map(ot=>`${ot.name}: ${ot.message}`).join(" · ")}):(K({done:!0,total:Ye.paths.length}),setTimeout(()=>K(null),1600))},et=ve=>{const Ye=ve.clipboardData;if(!Hu(Ye))return;const ot=pv(Ye);ot.length&&(ve.preventDefault(),ve.stopPropagation(),Ie(ot))},ze=ve=>{Hu(ve.dataTransfer)&&(ve.preventDefault(),ve.stopPropagation())},Fe=ve=>{Hu(ve.dataTransfer)&&(ve.preventDefault(),ve.stopPropagation(),Ie(pv(ve.dataTransfer)))};q.addEventListener("paste",et,!0),q.addEventListener("dragenter",ze,!0),q.addEventListener("dragover",ze,!0),q.addEventListener("drop",Fe,!0);const Ct=24,Ge=(ve,Ye={mode:null,remainder:0},ot=null)=>{const ht=C.current,mn=ht?ht.getBoundingClientRect().height:Ct,Pn=ot||KC({alternateScreen:P.buffer.active.type==="alternate",readonly:s}),Ai=Ye.mode===Pn?Ye.remainder+ve:ve,$o=VC({mode:Pn,accumulated:Ai,threshold:Pn==="page"?mn:Ct});for(const Jn of YC($o))Jn.kind==="input"?ae.sendInput(Jn.seq):ae.action(Jn.name);return{mode:Pn,remainder:$o.remainder}};let rt=null,ut=null,ct=null,vt=null,it=!1,lt=!1,mt={mode:null,remainder:0},le=null,be=null,Be=null,$e=!1;const he=()=>{Be&&clearTimeout(Be),Be=null},V=(ve,Ye)=>{const ht=(q.querySelector(".xterm-screen")||q).getBoundingClientRect(),mn=Math.max(0,Math.min(P.cols-1,Math.floor((ve-ht.left)/Math.max(1,ht.width)*P.cols))),Pn=Math.max(0,Math.min(P.rows-1,Math.floor((Ye-ht.top)/Math.max(1,ht.height)*P.rows)));return{col:mn,row:P.buffer.active.viewportY+Pn}},ne=ve=>V(ve.clientX,ve.clientY),z=ve=>{if(he(),$e=!1,it=!1,lt||ve.touches.length!==1){lt=!0,it=!0,T=null,rt=null,ut=null,ct=null,vt=null;return}if(A.current){ve.preventDefault(),ve.stopPropagation(),be=ne(ve.touches[0]),P.clearSelection();return}rt=ve.touches[0].clientY,ut=ve.touches[0].clientX,ct=ut,vt=rt,mt={mode:null,remainder:0},le=null;const Ye={x:ut,y:rt};Be=setTimeout(()=>{Be=null,$e=!0,it=!0,T=null,A.current=!0,S==null||S(!0),be=V(Ye.x,Ye.y),P.clearSelection(),P.select(be.col,be.row,1),rt=null,ut=null,le=null,mt={mode:null,remainder:0}},TC)},se=ve=>{if((A.current||$e)&&be&&ve.touches.length===1){ve.preventDefault(),ve.stopPropagation();const ht=ne(ve.touches[0]),mn=be.row*P.cols+be.col,Pn=ht.row*P.cols+ht.col,Ai=mn<=Pn?be:ht;P.select(Ai.col,Ai.row,Math.abs(Pn-mn)+1);return}if(rt===null||ve.touches.length!==1)return;ve.preventDefault(),ve.stopPropagation();const Ye=ve.touches[0];if(MC(ct,vt,Ye.clientX,Ye.clientY)&&(it=!0,T=null,Be&&he()),le===null&&(Math.abs(Ye.clientY-rt)>8||Math.abs(Ye.clientX-ut)>8)&&(le=Math.abs(Ye.clientY-rt)>Math.abs(Ye.clientX-ut)),!le)return;const ot=Ye.clientY-rt;rt=Ye.clientY,mt=Ge(ot,mt,"scroll")},me=()=>{he(),rt=null,ut=null,ct=null,vt=null,be=null,$e=!1,it=!1,lt=!1,mt={mode:null,remainder:0}},ke=ve=>{if(lt){T=null,he(),(!ve.touches||ve.touches.length===0)&&me();return}const Ye=ve.changedTouches&&ve.changedTouches[0];if(!it&&!$e&&!A.current&&Ye){const ot={at:Date.now(),x:Ye.clientX,y:Ye.clientY},ht=$C(G.current,T,ot);T=ht.next,ht.open&&L()}me()},Ne=()=>{T=null,me()};let we={mode:null,remainder:0};const Re=ve=>{ve.preventDefault(),ve.stopPropagation(),we=Ge(-ve.deltaY,we)};q.addEventListener("touchstart",z,{passive:!1}),q.addEventListener("touchmove",se,{passive:!1,capture:!0}),q.addEventListener("touchend",ke,{passive:!0}),q.addEventListener("touchcancel",Ne,{passive:!0});const Je=()=>{!A.current&&G.current==="double-tap"&&L()};q.addEventListener("dblclick",Je);const Tt=ve=>{(A.current||$e)&&(ve.preventDefault(),ve.stopPropagation())};q.addEventListener("contextmenu",Tt,!0),q.addEventListener("wheel",Re,{passive:!1,capture:!0});let Me=null;const pn=ve=>{LC(ve)&&(ve.preventDefault(),ve.stopPropagation(),Me=V(ve.clientX,ve.clientY),P.clearSelection())},bt=ve=>{if(!Me)return;ve.preventDefault(),ve.stopPropagation();const Ye=V(ve.clientX,ve.clientY),ot=Me.row*P.cols+Me.col,ht=Ye.row*P.cols+Ye.col,mn=ot<=ht?Me:Ye;P.select(mn.col,mn.row,Math.abs(ht-ot)+1)},Ke=ve=>{Me&&(ve.stopPropagation(),Me=null)};q.addEventListener("mousedown",pn,!0),q.addEventListener("mousemove",bt,!0),q.addEventListener("mouseup",Ke,!0);const $t=ve=>{!DC(ve)||!(k.current&&k.current.term&&k.current.term.getSelection())||(ve.preventDefault(),ve.stopPropagation(),j.current&&j.current())};q.addEventListener("keydown",$t,!0);const de=()=>{M.fit(),ae.resize(P.cols,P.rows)};window.addEventListener("resize",de);const Ee=window.visualViewport;let Ue=Ee&&Number(Ee.height);const _t=()=>{const ve=Ee&&Number(Ee.height);te&&G.current==="double-tap"&&Number.isFinite(Ue)&&Number.isFinite(ve)&&ve>Ue+80&&ie(),Ue=ve,de()};Ee&&(Ee.addEventListener("resize",_t),Ee.addEventListener("scroll",de));const dt=typeof navigator<"u"?navigator.virtualKeyboard:null,Ti=()=>{var ve;te&&G.current==="double-tap"&&Number(((ve=dt==null?void 0:dt.boundingRect)==null?void 0:ve.height)||0)===0&&ie()};(Mi=dt==null?void 0:dt.addEventListener)==null||Mi.call(dt,"geometrychange",Ti);let Vt=null,Xn=0;return typeof ResizeObserver<"u"&&(Vt=new ResizeObserver(()=>{Xn&&cancelAnimationFrame(Xn),Xn=requestAnimationFrame(de)}),Vt.observe(q)),()=>{var ve;k.current=null,u&&(u.current=()=>!1),h&&(h.current=()=>!1),p&&(p.current=()=>!1),ge.dispose(),Z.dispose(),q.removeEventListener("touchstart",z),q.removeEventListener("touchmove",se,{capture:!0}),q.removeEventListener("touchend",ke),q.removeEventListener("touchcancel",Ne),q.removeEventListener("dblclick",Je),q.removeEventListener("contextmenu",Tt,!0),he(),q.removeEventListener("wheel",Re,{capture:!0}),q.removeEventListener("mousedown",pn,!0),q.removeEventListener("mousemove",bt,!0),q.removeEventListener("mouseup",Ke,!0),q.removeEventListener("keydown",$t,!0),q.removeEventListener("paste",et,!0),q.removeEventListener("dragenter",ze,!0),q.removeEventListener("dragover",ze,!0),q.removeEventListener("drop",Fe,!0),window.removeEventListener("resize",de),Ee&&(Ee.removeEventListener("resize",_t),Ee.removeEventListener("scroll",de)),(ve=dt==null?void 0:dt.removeEventListener)==null||ve.call(dt,"geometrychange",Ti),$==null||$.removeEventListener("blur",X),Vt&&Vt.disconnect(),Xn&&cancelAnimationFrame(Xn),ae.close(),P.dispose()}},[e,t,n,s,o,u,h,p,f,_,b]),c.jsxs("div",{className:`nc-terminal${w?" selecting":""}`,children:[c.jsx("div",{className:"nc-terminal-host",ref:C}),ee&&c.jsx("div",{className:`nc-upload-state${ee.error?" error":""}`,role:"status",children:ee.error?ee.error:ee.done?g("attach-uploaded").replace("{n}",String(ee.total||0)):g("attach-upload-progress").replace("{n}",String(ee.current||0)).replace("{total}",String(ee.total||0))}),(F||w)&&c.jsxs("div",{className:"nc-selection-tools",children:[F?c.jsx("button",{type:"button",onClick:O,children:J||g("copy")}):c.jsx("span",{children:g("select-drag")}),c.jsx("button",{type:"button",onClick:()=>{var P,M;(M=(P=k.current)==null?void 0:P.term)==null||M.clearSelection(),D(""),S==null||S(!1)},children:g("cancel")}),J===g("copy-manual")&&c.jsx("textarea",{readOnly:!0,value:F,onFocus:P=>P.target.select()})]})]})}const gv="",Ot="\x1B",GC=[{label:"↑",seq:Ot+"[A"},{label:"↓",seq:Ot+"[B"},{label:"PGUP",seq:Ot+"[5~"},{label:"PGDN",seq:Ot+"[6~"}];function XC({send:e,action:t,ctrlArmed:n=!1,onCtrl:s,onKeyboard:o,selectionMode:a=!1,onSelectionMode:u,keepKeyboardClosed:h=!0,showEnter:p=!0,keybarLayout:f="full"}){const[_,b]=N.useState(!1),[y,w]=N.useState(!1),[S,x]=N.useState(!1),[C,k]=N.useState(!1),R=f==="compact"&&!C;N.useEffect(()=>{f!=="compact"&&k(!1)},[f]);const I=O=>{S?(e(Ot+O),x(!1)):e(O)},A=O=>{h&&lh(),O()},G=O=>({onPointerDown:j=>{j.preventDefault(),A(O)},onClick:j=>{j.detail===0&&A(O)}}),F=(O,j,P)=>c.jsx("button",{type:"button",...G(()=>{I(j),P&&P()}),children:O},O),D=(O,j)=>c.jsx("button",{type:"button",...G(()=>{t(j),w(!1)}),children:O},O),J=p&&c.jsx("button",{type:"button",className:"nc-enter-key","aria-label":"ENTER",title:"ENTER",...G(()=>I("\r")),children:c.jsx(nt,{name:"enter",size:24})}),W=y&&c.jsxs("div",{className:"nc-keymenu",children:[D("←WIN","prev-window"),D("WIN→","next-window"),D("⬅PANE","pane-left"),D("PANE➡","pane-right"),F("SCROLL",gv+"[",()=>{b(!0),w(!1)}),c.jsx("button",{type:"button",className:a?"armed":"",...G(()=>{u==null||u(!a),w(!1)}),children:"SELECT"}),F("⌃C","",()=>w(!1)),F("DETACH",gv+"d",()=>w(!1))]});if(_)return c.jsxs("div",{className:"nc-keybar copy",children:[c.jsx("span",{className:"tag",children:"copy-mode"}),GC.map(O=>F(O.label,O.seq)),F("ESCI (q)","q",()=>b(!1))]});if(R)return c.jsxs("div",{className:"nc-keybar termux",children:[W,c.jsxs("div",{className:`nc-keygrid compact${p?"":" no-enter"}`,children:[c.jsx("div",{className:"nc-keyrows",children:c.jsxs("div",{className:"row",children:[c.jsx("button",{type:"button","aria-label":"expand keybar",title:"expand",...G(()=>k(!0)),children:c.jsx(nt,{name:"chevronUp",size:20})},"expand"),c.jsx("button",{type:"button",...G(()=>{o&&o()}),children:"⌨"},"kbd"),c.jsx("button",{type:"button",className:y?"armed":"",...G(()=>w(O=>!O)),children:"☰"},"menu"),F("↑",Ot+"[A"),F("↓",Ot+"[B"),F("←",Ot+"[D"),F("→",Ot+"[C"),F("PGUP",Ot+"[5~"),F("PGDN",Ot+"[6~")]})}),J]})]});const ee=f==="compact"&&C,K=ee&&c.jsx("button",{type:"button",className:"nc-retract-key","aria-label":"retract keybar",title:"retract",...G(()=>k(!1)),children:c.jsx(nt,{name:"chevronDown",size:20})});return c.jsxs("div",{className:`nc-keybar termux${ee?" expanded":""}`,children:[W,c.jsxs("div",{className:`nc-keygrid${p?"":" no-enter"}${ee?" expanded":""}`,children:[K,c.jsxs("div",{className:"nc-keyrows",children:[c.jsxs("div",{className:"row",children:[F("ESC",Ot),c.jsx("button",{type:"button",className:y?"armed":"",...G(()=>w(O=>!O)),children:"☰"},"menu"),F("/","/"),F("—","-"),F("HOME",Ot+"[H"),F("↑",Ot+"[A"),F("END",Ot+"[F"),F("PGUP",Ot+"[5~")]}),c.jsxs("div",{className:"row",children:[F("⇥"," "),c.jsx("button",{type:"button",...G(()=>{o&&o()}),children:"⌨"},"kbd"),c.jsx("button",{type:"button",className:n?"armed":"",...G(()=>{s&&s()}),children:"CTRL"},"ctrl"),c.jsx("button",{type:"button",className:S?"armed":"",...G(()=>x(O=>!O)),children:"ALT"},"alt"),F("←",Ot+"[D"),F("↓",Ot+"[B"),F("→",Ot+"[C"),F("PGDN",Ot+"[6~")]})]}),J]})]})}const JC=e=>e>1048576?`${(e/1048576).toFixed(1)}M`:e>1024?`${(e/1024).toFixed(0)}K`:`${e}B`;function Gy({session:e,node:t,token:n,filesEvent:s,onClose:o}){zn();const a=t?`/api/route/${String(t).split("/").map(encodeURIComponent).join("/")}/_`:"/api",u=t?`${t}:${e}`:e,[h,p]=N.useState("outbox"),[f,_]=N.useState({inbox:[],outbox:[]}),[b,y]=N.useState(""),w=N.useRef(null);async function S(){try{const I=await(await tn(`${a}/files?session=${encodeURIComponent(e)}`,n)).json();if(I.error){y(I.error);return}_(I);const A=I.outbox[0]?I.outbox[0].mtime:0;localStorage.setItem(R_(u),String(A))}catch(R){y(String(R))}}N.useEffect(()=>{S()},[e,t]),N.useEffect(()=>{s&&s.session===e&&S()},[s]);async function x(R){for(const I of R){y(`carico ${I.name}…`);const A=new FormData;A.append("session",e),A.append("file",I);try{const F=await(await tn(`${a}/files/upload`,n,{method:"POST",body:A})).json();y(F.error?`errore: ${F.error}`:"")}catch(G){y(String(G))}}S()}async function C(R){const I=await tn(`${a}/files/download?session=${encodeURIComponent(e)}&box=${h}&name=${encodeURIComponent(R)}`,n);if(!I.ok){y("errore download");return}const A=await I.blob(),G=URL.createObjectURL(A),F=document.createElement("a");F.href=G,F.download=R,F.click(),URL.revokeObjectURL(G)}async function k(R){await tn(`${a}/files?session=${encodeURIComponent(e)}&box=${h}&name=${encodeURIComponent(R)}`,n,{method:"DELETE"}),S()}return c.jsxs("div",{className:"nc-files",children:[c.jsxs("header",{children:[c.jsx("b",{children:t?`${t}:${e}`:e}),c.jsx("button",{onClick:o,title:g("close"),children:c.jsx(nt,{name:"x",size:20})})]}),c.jsxs("nav",{children:[c.jsx("button",{className:h==="outbox"?"on":"",onClick:()=>p("outbox"),children:"outbox"}),c.jsx("button",{className:h==="inbox"?"on":"",onClick:()=>p("inbox"),children:"inbox"}),c.jsxs("button",{className:"up",onClick:()=>w.current&&w.current.click(),children:[c.jsx(nt,{name:"upload",size:18})," ",g("upload")]}),c.jsx("input",{type:"file",multiple:!0,ref:w,style:{display:"none"},onChange:R=>{x(Array.from(R.target.files||[])),R.target.value=""}})]}),b&&c.jsx("div",{className:"nc-busy",children:b}),c.jsxs("ul",{children:[f[h].map(R=>c.jsxs("li",{children:[c.jsx("span",{className:"name",onClick:()=>C(R.name),children:R.name}),c.jsx("small",{children:JC(R.size)}),c.jsx("button",{onClick:()=>k(R.name),title:"elimina",children:c.jsx(nt,{name:"trash",size:18})})]},R.name)),f[h].length===0&&c.jsx("li",{className:"empty",children:g("empty-files")})]})]})}const Ol="nc_composer_v1",ch="nc-composer-reset",QC=50,Xy=256*1024,Jy=512*1024,ZC=768*1024,vv=2*1024*1024,Qy=720*60*60*1e3,uh=1;function Zy(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:0}function Uh(e){if(e!==void 0)return e;try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function jl(){return{version:uh,cells:{}}}function ew(e){const t=[];for(const s of Array.isArray(e)?e:[]){const o=typeof s=="string"?s:s&&s.text,a=Zy(typeof s=="string"?0:s&&s.at);if(!(typeof o!="string"||!o||o.length>Xy)&&!(t.length&&t[t.length-1].text===o)&&(t.push({text:o,at:a}),t.length>=QC))break}let n=0;return t.filter(s=>n+s.text.length>ZC?!1:(n+=s.text.length,!0))}function Ll(e){if(!e||typeof e!="object")return null;const t=typeof e.draft=="string"&&e.draft.length<=Jy?e.draft:"",n=ew(e.history),s=Zy(e.updatedAt),o=e.expanded===!0;return!t&&!n.length&&!o?null:{draft:t,history:n,expanded:o,updatedAt:s}}function eE(e){let t;try{t=typeof e=="string"?JSON.parse(e):e}catch{return jl()}if(!t||typeof t!="object"||t.version!==uh||!t.cells||typeof t.cells!="object")return jl();const n=Object.create(null);for(const[s,o]of Object.entries(t.cells)){if(!s||typeof s!="string"||s.length>512||s==="__proto__"||s==="constructor"||s==="prototype")continue;const a=Ll(o);a&&(n[s]=a)}return{version:uh,cells:n}}function tw(e){const t=Uh(e);if(!t)return jl();try{return eE(t.getItem(Ol))}catch{return jl()}}function _v(e){try{return JSON.stringify(e).length}catch{return 1/0}}function tE(e,t,n){for(const[s,o]of Object.entries(e.cells))s!==n&&o.updatedAt>0&&t-o.updatedAt>Qy&&delete e.cells[s]}function nw(e,t){return Object.entries(e.cells).filter(([n])=>n!==t).sort((n,s)=>n[1].updatedAt-s[1].updatedAt).map(([n])=>n)}function nE(e,t){for(;_v(e)>vv;){const n=Object.entries(e.cells).filter(([,s])=>s.history.length).sort((s,o)=>s[1].updatedAt-o[1].updatedAt);if(!n.length)break;n[0][1].history.pop()}for(const n of nw(e,t)){if(_v(e)<=vv)break;delete e.cells[n]}}function iw(e,t,n){const s=Uh(e);if(!s)return!1;nE(t,n);const o=()=>(s.setItem(Ol,JSON.stringify(t)),!0);try{return o()}catch{for(const u of nw(t,n)){delete t.cells[u];try{return o()}catch{}}return!1}}function zo(e,t,n,s){const o=tw(t);tE(o,n,e);const a=Ll(o.cells[e])||{draft:"",history:[],expanded:!1,updatedAt:0},u=s({...a,history:[...a.history]}),h=Ll(u);return h?o.cells[e]={...h,updatedAt:n}:delete o.cells[e],{ok:iw(t,o,e),cell:o.cells[e]||{draft:"",history:[],expanded:!1,updatedAt:n}}}function iE({ownerId:e,node:t,session:n}){const s=String(n||"");if(!s)return"";const o=Ss.test(String(e||""))?String(e):t?`route:${String(t)}`:"local";return`${encodeURIComponent(o)}:${encodeURIComponent(s)}`}function _o(e,t,n=Date.now()){if(!e)return{draft:"",history:[],expanded:!1,updatedAt:0};const s=tw(t),o=Ll(s.cells[e]);return!o||o.updatedAt>0&&n-o.updatedAt>Qy?(s.cells[e]&&(delete s.cells[e],iw(t,s,"")),{draft:"",history:[],expanded:!1,updatedAt:0}):{...o,history:[...o.history]}}function yv(e,t,n,s=Date.now()){const o=String(t||"");return!e||o.length>Jy?!1:zo(e,n,s,a=>({...a,draft:o})).ok}function wv(e,t,n=Date.now()){return e?zo(e,t,n,s=>({...s,draft:""})).ok:!1}function rE(e,t,n,s=Date.now()){return e?zo(e,n,s,o=>({...o,expanded:!!t})).ok:!1}function sE(e,t,n,s=Date.now()){const o=String(t||"");return!e||!o||o.length>Xy?!1:zo(e,n,s,a=>{const u=a.history.filter(h=>h.text!==o);return u.unshift({text:o,at:s}),{...a,history:ew(u)}}).ok}function oE(e,t,n=Date.now()){return e?zo(e,t,n,s=>({...s,history:[]})).ok:!1}function aE(e){const t=Uh(e);if(!t)return!1;try{return t.removeItem(Ol),!0}catch{return!1}}const lE=300;function cE(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function uE({ownerId:e,node:t,session:n,storage:s=cE()}){const o=N.useMemo(()=>iE({ownerId:e,node:t,session:n}),[e,t,n]),a=N.useMemo(()=>_o(o,s),[]),[u,h]=N.useState(a.draft),[p,f]=N.useState(a.expanded),[_,b]=N.useState(a.history),[y,w]=N.useState(-1),S=N.useRef(o),x=N.useRef(a.draft),C=N.useRef(null),k=N.useRef(a.updatedAt||0),R=N.useRef(a.draft),I=N.useCallback(()=>{C.current&&clearTimeout(C.current),C.current=null},[]),A=N.useCallback(()=>{I(),yv(S.current,x.current,s)},[I,s]),G=N.useCallback(()=>{I(),C.current=setTimeout(()=>{C.current=null,yv(S.current,x.current,s)},lE)},[I,s]),F=N.useCallback(P=>{const M=String(typeof P=="function"?P(x.current):P||"");x.current=M,k.current=Date.now(),R.current=M,w(-1),h(M),G()},[G]),D=N.useCallback((P,M)=>{I(),x.current=P,k.current=Date.now(),h(P),w(M),G()},[I,G]),J=N.useCallback(()=>{if(!_.length)return!1;const P=Math.min(y+1,_.length-1);return y<0&&(R.current=x.current),D(_[P].text,P),!0},[D,_,y]),W=N.useCallback(()=>{if(y<0)return!1;const P=y-1;return D(P<0?R.current:_[P].text,P),!0},[D,_,y]),ee=N.useCallback(P=>{R.current=x.current;const M=_.findIndex(H=>H.text===P);D(String(P||""),M)},[D,_]),K=N.useCallback(()=>{f(P=>{const M=!P;return rE(S.current,M,s),M})},[s]),O=N.useCallback((P,M,H)=>{if(!P)return;if(sE(P,H,s),!(S.current===P)){_o(P,s).draft===M&&wv(P,s);return}b(_o(P,s).history),R.current="",w(-1),x.current===M?(I(),x.current="",k.current=Date.now(),h(""),wv(P,s)):G()},[I,G,s]),j=N.useCallback(()=>{oE(S.current,s),b([]),w(-1),R.current=x.current},[s]);return N.useEffect(()=>{if(S.current===o)return;A(),S.current=o;const P=_o(o,s);x.current=P.draft,k.current=P.updatedAt||0,R.current=P.draft,h(P.draft),f(P.expanded),b(P.history),w(-1)},[o,A,s]),N.useEffect(()=>{const P=()=>A(),M=()=>{document.visibilityState==="hidden"&&A()};return window.addEventListener("pagehide",P),document.addEventListener("visibilitychange",M),()=>{window.removeEventListener("pagehide",P),document.removeEventListener("visibilitychange",M),A()}},[A]),N.useEffect(()=>{const P=()=>{I(),x.current="",k.current=0,R.current="",h(""),f(!1),b([]),w(-1)},M=te=>{if(te.key!==Ol)return;if(te.newValue==null){P();return}const T=_o(S.current,s);T.updatedAt<k.current||(I(),x.current=T.draft,k.current=T.updatedAt,R.current=T.draft,h(T.draft),f(T.expanded),b(T.history),w(-1))},H=()=>P();return window.addEventListener("storage",M),window.addEventListener(ch,H),()=>{window.removeEventListener("storage",M),window.removeEventListener(ch,H)}},[I,s]),{cellKey:o,text:u,setText:F,expanded:p,toggleExpanded:K,history:_,historyCursor:y,recallPrevious:J,recallNext:W,selectHistory:ee,confirmSubmitted:O,clearHistory:j,flush:A}}function rw({submitText:e,token:t,session:n,node:s,ownerId:o,keepKeyboardClosedOnVoice:a=!0}){zn();const u=s?`/api/route/${String(s).split("/").map(encodeURIComponent).join("/")}/_`:"/api",{cellKey:h,text:p,setText:f,expanded:_,toggleExpanded:b,history:y,historyCursor:w,recallPrevious:S,recallNext:x,selectHistory:C,confirmSubmitted:k,clearHistory:R,flush:I}=uE({ownerId:o,node:s,session:n}),[A,G]=N.useState(!1),[F,D]=N.useState(""),[J,W]=N.useState(!1),ee=N.useRef(null),K=N.useRef(null),O=N.useRef(null),[j,P]=N.useState(!1),[M,H]=N.useState({left:0,bottom:0}),[te,T]=N.useState(!1),[ie,B]=N.useState(!1),L=N.useRef(null),$=N.useRef(null),X=N.useRef(null),ae=N.useRef(null),ue=N.useRef(null),ge=N.useRef(null),Z=N.useRef(null),q=N.useRef(!1),[fe,Ie]=N.useState(!1),[et,ze]=N.useState({left:0,bottom:0,width:320}),Fe=N.useRef(`nc-attach-${Math.random().toString(36).slice(2,8)}`);N.useEffect(()=>{let he=!1;if(s){W(!1);return}return tn(`${u}/voice/status`,t).then(V=>V.json()).then(V=>{he||W(!!V.serverSttConfigured)}).catch(()=>{he||W(!1)}),()=>{he=!0}},[t,u]);const Ge=!!(typeof window<"u"&&(window.SpeechRecognition||window.webkitSpeechRecognition)||J);async function rt(){const he=O.current&&typeof O.current.value=="string"?O.current.value:p;lh(),he!==p&&f(he);const V=he,ne=PC(V);if(!ne||ie)return;B(!0),D("");let z=!1;try{z=!!await e(ne)}catch{z=!1}z?k(h,V,ne):D(g("composer-send-failed")),B(!1)}function ut(){const he=L.current&&L.current.getBoundingClientRect();he&&H({left:Math.max(6,Math.min(he.left,window.innerWidth-186)),bottom:window.innerHeight-he.top+6}),P(!0)}function ct(he){P(!1),he&&L.current&&L.current.focus()}function vt(){const he=X.current&&X.current.getBoundingClientRect();if(he){const V=Math.max(220,Math.min(360,window.innerWidth-12));ze({left:Math.max(6,Math.min(he.right-V,window.innerWidth-V-6)),bottom:window.innerHeight-he.top+6,width:V})}Ie(!0)}function it(he){Ie(!1),he&&X.current&&X.current.focus()}N.useEffect(()=>{if(!j)return;const he=ne=>{ne.key==="Escape"&&ct(!0)},V=ne=>{const z=$.current&&$.current.contains(ne.target),se=L.current&&L.current.contains(ne.target);!z&&!se&&ct(!1)};return document.addEventListener("keydown",he),document.addEventListener("pointerdown",V),()=>{document.removeEventListener("keydown",he),document.removeEventListener("pointerdown",V)}},[j]),N.useEffect(()=>{if(!fe)return;const he=ne=>{ne.key==="Escape"&&it(!0)},V=ne=>{const z=ae.current&&ae.current.contains(ne.target),se=X.current&&X.current.contains(ne.target);!z&&!se&&it(!1)};return document.addEventListener("keydown",he),document.addEventListener("pointerdown",V),()=>{document.removeEventListener("keydown",he),document.removeEventListener("pointerdown",V)}},[fe]);function lt(he){if(!(he.isComposing||q.current||he.altKey||he.ctrlKey||he.metaKey)){if(he.key==="ArrowUp"&&he.currentTarget.selectionStart===0&&he.currentTarget.selectionEnd===0){S()&&he.preventDefault();return}he.key==="ArrowDown"&&w>=0&&he.currentTarget.selectionStart===p.length&&he.currentTarget.selectionEnd===p.length&&x()&&he.preventDefault()}}function mt(he){ct(!1),he.current&&he.current.click()}async function le(he){if(!he.length||!n)return;T(!0),D("");const{paths:V,errors:ne}=await Ky({files:he,token:t,session:n,node:s,paste:!1});ne.length&&D(ne.map(z=>`${z.name}: ${z.message}`).join(" · ")),V.length&&f(z=>z+(z&&!z.endsWith(" ")?" ":"")+V.join(" ")),T(!1)}function be(){ee.current&&ee.current.stop(),K.current&&K.current.stop(),G(!1)}async function Be(){D("");const he=window.SpeechRecognition||window.webkitSpeechRecognition;if(he){const V=new he;V.lang="it-IT",V.continuous=!1,V.interimResults=!0;const ne=p?`${p} `:"";V.onresult=z=>{const se=Array.from(z.results).map(me=>me[0].transcript).join("");f(ne+se)},V.onend=()=>G(!1),V.onerror=z=>{D(`voice: ${z.error||"errore"}`),G(!1)},ee.current=V,V.start(),G(!0);return}try{const V=await navigator.mediaDevices.getUserMedia({audio:!0}),ne=new MediaRecorder(V),z=[];ne.ondataavailable=se=>z.push(se.data),ne.onstop=async()=>{V.getTracks().forEach(se=>se.stop()),G(!1),D("trascrivo…");try{const se=new Blob(z,{type:ne.mimeType||"audio/webm"}),ke=await(await tn(`${u}/voice/transcribe`,t,{method:"POST",headers:{"content-type":"application/octet-stream"},body:se})).json();ke.error?D(ke.error):(D(""),f(Ne=>Ne+(Ne?" ":"")+(ke.text||"")))}catch(se){D(String(se))}},K.current={stop:()=>ne.state!=="inactive"&&ne.stop()},ne.start(),G(!0)}catch{D("microfono non disponibile"),G(!1)}}function $e(){a&&lh(),A?be():Be()}return c.jsxs("div",{className:"nc-composer",children:[F&&c.jsx("div",{className:"nc-composer-err",children:F}),c.jsxs("div",{className:"nc-composer-row",children:[n&&c.jsx("button",{ref:L,className:te?"attach busy":"attach",disabled:te,onClick:()=>j?ct(!1):ut(),title:g(te?"attach-uploading":"attach"),"aria-label":g("attach"),"aria-haspopup":"menu","aria-expanded":j,"aria-controls":Fe.current,children:c.jsx(nt,{name:"attach",size:22})}),j&&c.jsxs("div",{ref:$,id:Fe.current,role:"menu",className:"nc-attach-menu",style:{left:M.left,bottom:M.bottom},children:[c.jsxs("button",{role:"menuitem",onClick:()=>mt(ue),children:[c.jsx(nt,{name:"file",size:18})," ",g("attach-file")]}),c.jsxs("button",{role:"menuitem",onClick:()=>mt(ge),children:[c.jsx(nt,{name:"camera",size:18})," ",g("attach-camera")]}),c.jsxs("button",{role:"menuitem",onClick:()=>mt(Z),children:[c.jsx(nt,{name:"image",size:18})," ",g("attach-gallery")]})]}),c.jsx("button",{ref:X,type:"button",className:"history",onPointerDown:he=>he.preventDefault(),onClick:()=>fe?it(!1):vt(),title:g("composer-history-tools"),"aria-label":g("composer-history-tools"),"aria-haspopup":"menu","aria-expanded":fe,children:c.jsx(nt,{name:"history",size:21})}),fe&&c.jsxs("div",{ref:ae,role:"menu",className:"nc-composer-history-menu",style:{left:et.left,bottom:et.bottom,width:et.width},children:[c.jsxs("button",{role:"menuitem",className:"nc-composer-history-action",onPointerDown:he=>he.preventDefault(),onClick:()=>{b(),it(!1)},children:[c.jsx(nt,{name:_?"chevronDown":"chevronUp",size:18}),g(_?"composer-collapse":"composer-expand")]}),c.jsx("div",{className:"nc-composer-history-title",children:g("composer-history")}),y.length===0&&c.jsx("div",{className:"nc-composer-history-empty",children:g("composer-history-empty")}),y.map((he,V)=>c.jsxs("button",{type:"button",role:"menuitem",className:"nc-composer-history-entry",onPointerDown:ne=>ne.preventDefault(),onClick:()=>{C(he.text),it(!1)},children:[c.jsx("span",{children:he.text.replace(/\s+/g," ").slice(0,180)}),he.at>0&&c.jsx("small",{children:new Date(he.at).toLocaleString()})]},`${he.at}:${V}`)),y.length>0&&c.jsx("button",{type:"button",role:"menuitem",className:"nc-composer-history-clear",onPointerDown:he=>he.preventDefault(),onClick:()=>{R(),it(!1)},children:g("composer-history-clear")})]}),c.jsx("input",{ref:ue,type:"file",multiple:!0,hidden:!0,onChange:he=>{le(Array.from(he.target.files||[])),he.target.value=""}}),c.jsx("input",{ref:ge,type:"file",accept:"image/*",capture:"environment",hidden:!0,onChange:he=>{le(Array.from(he.target.files||[])),he.target.value=""}}),c.jsx("input",{ref:Z,type:"file",accept:"image/*,video/*",multiple:!0,hidden:!0,onChange:he=>{le(Array.from(he.target.files||[])),he.target.value=""}}),c.jsx("textarea",{ref:O,className:_?"expanded":"",rows:_?8:2,value:p,placeholder:g("composer-placeholder"),onChange:he=>f(he.target.value),onKeyDown:lt,onCompositionStart:()=>{q.current=!0},onCompositionEnd:()=>{q.current=!1},onBlur:I}),Ge&&c.jsx("button",{type:"button",className:A?"mic on":"mic",title:g("voice"),"aria-label":g("voice"),onPointerDown:he=>{he.preventDefault(),$e()},onClick:he=>{he.detail===0&&$e()},children:c.jsx(nt,{name:"mic",size:22})}),c.jsx("button",{type:"button",className:"go",disabled:ie,onPointerDown:he=>he.preventDefault(),onClick:rt,title:g("send"),children:c.jsx(nt,{name:"enter",size:22})})]})]})}function Sv(e){return String(e||"?").replace(/^[^a-zA-Z0-9]+/,"").charAt(0).toUpperCase()||"?"}const dE=180,hE=480,ps=(e,t=[])=>`${t.length?t.join("/"):"local"}:${e}`;function fE({sessions:e=[],cells:t=[],activeSessions:n=[],nodeGroups:s=[],onPick:o,onAddTile:a,onPower:u,onBoot:h,onNodePower:p,onKill:f,onVisibility:_,onNew:b,onNodeRename:y,onSettings:w,onBootError:S,localNodeId:x,fleetCapabilities:C=[],bootSettlement:k=null,onBootSettlementApplied:R,width:I=240,collapsed:A=!1,onResize:G,onToggleCollapse:F}){const[D,J]=zn(),{pins:W,orders:ee,togglePin:K,viewFor:O,updateView:j,canMoveRoster:P,moveRoster:M,stepRoster:H}=W_(),{groupsFor:te,moveNode:T,stepNode:ie,nodeKey:B}=K_(),L=new Set((t||[]).map(V=>V.tmuxSession)),$=new Map((e||[]).map(V=>[V.name,V])),X=(V,ne)=>H0(W,V,ne),ae=W0,ue=[...t||[]].sort((V,ne)=>ae(X(V.tmuxSession,($.get(V.tmuxSession)||{}).activity),X(ne.tmuxSession,($.get(ne.tmuxSession)||{}).activity))),ge=(e||[]).filter(V=>!L.has(V.name)).sort((V,ne)=>ae(X(V.name,V.activity),X(ne.name,ne.activity))||V.name.localeCompare(ne.name)),Z=new Set(n||[]),q=G_(ue,ge,$),fe=Mr(q,W,O("local").filter,ur(ee,"local")),et=te(s||[]).map(V=>{const ne=(V.route||[V.name]).join("/"),z=O(ne),{rawItems:se}=bd(V),me=Mr(se,W,z.filter,ur(ee,ne));return{g:V,nodeRoute:ne,groupView:z,rawItems:se,items:me}}),ze=(V,ne,z)=>o&&o({session:V,...ne?{node:ne}:{},...Ss.test(String(z||""))?{ownerId:z}:{}}),Fe=async V=>{if(!(V!=null&&V.direct)||!y)return;const ne=window.prompt(g("rename-node-prompt"),V.label||V.name);if(ne!==null)try{await y(V,ne)||window.alert(g("rename-node-invalid"))}catch(z){window.alert(String((z==null?void 0:z.message)||z))}},[Ct,Ge]=N.useState({}),[rt,ut]=N.useState(new Set);N.useEffect(()=>{const V=new Map;for(const ne of t||[])V.set(ps(ne.cell),!!ne.boot);for(const ne of s||[]){const z=ne.route||[ne.name];for(const se of ne.cells||[])V.set(ps(se.cell,z),!!se.boot)}Ge(ne=>{let z=!1;const se={...ne};for(const[me,ke]of Object.entries(ne))V.has(me)&&V.get(me)===ke&&(delete se[me],z=!0);return z?se:ne})},[t,s]),N.useEffect(()=>{if(!(k!=null&&k.cell))return;const V=Array.isArray(k.route)?k.route:[],ne=ps(k.cell,V);Ge(z=>({...z,[ne]:!!k.enabled})),R&&R(k.id)},[k,R]);const ct=(V,ne=[])=>{const z=ps(V.cell,ne);return Object.prototype.hasOwnProperty.call(Ct,z)?Ct[z]:!!V.boot},vt=async(V,ne,z=[])=>{if(V.stopPropagation(),!h)return;const se=ps(ne.cell,z),me=!ct(ne,z);Ge(ke=>({...ke,[se]:me})),ut(ke=>new Set(ke).add(se));try{await h(ne.cell,me,z)}catch(ke){Ge(Ne=>{const we={...Ne};return delete we[se],we}),S&&S(ke)}finally{ut(ke=>{const Ne=new Set(ke);return Ne.delete(se),Ne})}},it=(V,ne=[])=>{const z=ps(V.cell,ne),se=ct(V,ne),me=`${g(se?"boot-disable":"boot-enable")} ${V.cell}`;return c.jsx("button",{className:`nc-boot${se?" on":""}`,disabled:rt.has(z),onClick:ke=>vt(ke,V,ne),title:me,"aria-label":me,children:c.jsx(nt,{name:"boot",size:14})})},[lt,mt]=N.useState(null),le=(V,ne)=>{const z=V.currentTarget.getBoundingClientRect();mt({text:ne,y:z.top+z.height/2})},be=()=>mt(null),Be=N.useRef(null);N.useEffect(()=>()=>{Be.current&&Be.current()},[]);function $e(V){V.preventDefault(),V.stopPropagation();const ne=V.clientX,z=I,se=ke=>{const Ne=Math.max(dE,Math.min(hE,z+(ke.clientX-ne)));G&&G(Ne)},me=()=>{window.removeEventListener("pointermove",se),window.removeEventListener("pointerup",me),window.removeEventListener("pointercancel",me),window.removeEventListener("blur",me),Be.current=null};window.addEventListener("pointermove",se),window.addEventListener("pointerup",me),window.addEventListener("pointercancel",me),window.addEventListener("blur",me),Be.current=me}const he=A?{width:48,flex:"0 0 48px"}:{width:I,flex:`0 0 ${I}px`};return A?c.jsxs("aside",{className:"nc-sidebar mini",style:he,children:[c.jsx("div",{className:"nc-side-head mini",children:c.jsx("button",{className:"nc-collapse-btn",onClick:F,title:g("expand"),children:"⟩"})}),c.jsx("button",{className:"nc-side-gear mini",onClick:()=>w&&w("nodes",!1),title:g("settings"),onMouseEnter:V=>le(V,g("settings")),onMouseLeave:be,children:c.jsx(nt,{name:"gear",size:16})}),c.jsx("div",{className:"nc-side-scroll mini",children:c.jsxs("div",{className:"nc-side-group mini",children:[O("local").open&&fe.map(V=>V.type==="cell"?(()=>{const ne=V.value,z=ne.degraded?"warn":ne.tmux?"on":"",se=!!ne.tmux;return c.jsx("button",{type:"button",className:`nc-mini-dot${Z.has(ne.tmuxSession)?" active":""}`,onMouseEnter:me=>le(me,`${ne.cell}: ${V.subtitle}`),onMouseLeave:be,draggable:se,onDragStart:se?me=>me.dataTransfer.setData("text/nc-session",ne.tmuxSession):void 0,onClick:se?()=>a&&a(ne.tmuxSession):()=>u&&u(ne),onDoubleClick:se?()=>ze(ne.tmuxSession,"",x):void 0,children:c.jsx("span",{className:`nc-dot ${z}${V.working?" working":""}`})},V.key)})():(()=>{const ne=V.value;return c.jsx("button",{type:"button",className:`nc-mini-init${Z.has(ne.name)?" active":""}`,onMouseEnter:z=>le(z,ne.name),onMouseLeave:be,draggable:!0,onDragStart:z=>z.dataTransfer.setData("text/nc-session",ne.name),onClick:()=>a&&a(ne.name),onDoubleClick:()=>ze(ne.name,"",x),children:Sv(ne.name)},V.key)})()),et.flatMap(({g:V,nodeRoute:ne,groupView:z,items:se})=>V.status==="up"?z.open?se.map(me=>me.type==="cell"?(()=>{const ke=me.value,Ne=!!ke.tmux;return c.jsx("button",{type:"button",className:`nc-mini-dot${Z.has(me.key)?" active":""}`,onMouseEnter:we=>le(we,`${V.label||ne}: ${ke.cell} · ${me.subtitle}`),onMouseLeave:be,draggable:Ne,onDragStart:Ne?we=>we.dataTransfer.setData("text/nc-session",me.key):void 0,onClick:Ne?()=>a&&a(me.key):()=>u&&u({...ke,route:V.route,availableEngines:V.engines||[]}),onDoubleClick:Ne?()=>ze(ke.tmuxSession,ne,V.instanceId):void 0,children:c.jsx("span",{className:`nc-dot ${ke.degraded?"warn":Ne?`on${me.working?" working":""}`:""}`})},me.key)})():(()=>{const ke=me.value;return c.jsx("button",{type:"button",className:`nc-mini-init${Z.has(me.key)?" active":""}`,onMouseEnter:Ne=>le(Ne,`${V.label||ne}: ${ke.name}`),onMouseLeave:be,draggable:!0,onDragStart:Ne=>Ne.dataTransfer.setData("text/nc-session",me.key),onClick:()=>a&&a(me.key),onDoubleClick:()=>ze(ke.name,ne,V.instanceId),children:Sv(ke.name)},me.key)})()):[]:[c.jsx("button",{type:"button",className:"nc-mini-dot",onMouseEnter:me=>le(me,`${V.label||(V.route||[V.name]).join(" › ")}: ${vs(V)}`),onMouseLeave:be,children:c.jsx("span",{className:`nc-dot${V.status==="passive"?"":" warn"}`})},`nodo-${(V.route||[V.name]).join("/")}`)])]})}),lt&&c.jsx("div",{className:"nc-mini-tip",style:{top:lt.y},children:lt.text})]}):c.jsxs("aside",{className:"nc-sidebar",style:he,children:[c.jsxs("div",{className:"nc-side-head",children:[c.jsx("button",{className:"nc-collapse-btn",onClick:F,title:g("collapse"),children:"⟨"}),c.jsx("span",{className:"nc-side-title",children:g("fleet")}),c.jsxs("button",{className:"nc-new-btn",onClick:b,title:g("fleet-new-cell"),children:["+ ",g("new")]})]}),c.jsxs("button",{className:"nc-side-gear",onClick:()=>w&&w("nodes",!1),title:g("settings"),children:[c.jsx(nt,{name:"gear",size:15})," ",g("settings")]}),c.jsxs("div",{className:"nc-side-scroll",children:[c.jsx(pE,{label:g("position-local"),count:fe.length,state:O("local"),onToggle:()=>j("local",{open:!O("local").open}),onFilter:V=>j("local",{filter:V})}),O("local").open&&c.jsxs("div",{className:"nc-side-group",children:[fe.map(V=>V.type==="cell"?(()=>{const ne=V.value,z=ne.degraded?"warn":ne.tmux?"on":"",se=ne.degraded?g("cell-degraded"):V.working?V.subtitle:ne.tmux?g("cell-idle"):g("cell-off"),me=!!ne.tmux;return c.jsxs("div",{"data-roster-key":V.key,"data-position":"local",className:`nc-cell${me?" live":""}${Z.has(ne.tmuxSession)?" active":""}`,title:`${ne.cell} · ${V.subtitle}${se===V.subtitle?"":` · ${se}`}`,"aria-label":`${ne.cell}, ${V.subtitle}${se===V.subtitle?"":`, ${se}`}`,draggable:me,onDragStart:me?ke=>ke.dataTransfer.setData("text/nc-session",ne.tmuxSession):void 0,onClick:me?()=>a&&a(ne.tmuxSession):void 0,onDoubleClick:me?()=>ze(ne.tmuxSession,"",x):void 0,children:[c.jsx(ar,{position:"local",itemKey:V.key,label:ne.cell,canMove:P,onMove:(ke,Ne)=>M("local",ke,Ne,q),onStep:ke=>H("local",V.key,ke,q)}),c.jsx("span",{className:`nc-dot ${z}${V.working?" working":""}`}),c.jsxs("span",{className:"nc-cell-main",children:[c.jsx("b",{title:ne.cell,children:ne.cell}),c.jsx("small",{title:V.subtitle,children:V.subtitle})]}),c.jsx("button",{className:`nc-pin${W.includes(V.key)?" on":""}`,title:g("pin"),onClick:ke=>{ke.stopPropagation(),K(V.key)},children:W.includes(V.key)?"★":"☆"}),h&&C.includes("boot")&&it(ne),c.jsx("button",{className:`nc-power${ne.tmux?" on":""}${ne.degraded?" warn":""}`,onClick:ke=>{ke.stopPropagation(),u&&u({...ne,boot:ct(ne)})},title:ne.active?g("power-off"):g("power-on"),children:c.jsx(nt,{name:"power",size:14})})]},V.key)})():(()=>{var z;const ne=V.value;return c.jsxs("div",{"data-roster-key":V.key,"data-position":"local",className:`nc-side-card${Z.has(ne.name)?" active":""}`,draggable:!0,onDragStart:se=>se.dataTransfer.setData("text/nc-session",ne.name),onClick:()=>a&&a(ne.name),onDoubleClick:()=>ze(ne.name,"",x),children:[c.jsx(ar,{position:"local",itemKey:V.key,label:ne.name,canMove:P,onMove:(se,me)=>M("local",se,me,q),onStep:se=>H("local",V.key,se,q)}),c.jsx("span",{className:ne.attached?"nc-dot on":"nc-dot"}),c.jsxs("span",{className:"nc-card-main",children:[c.jsx("b",{children:ne.name}),c.jsxs("small",{children:[ne.preview||ne.cmd||g("windows").replace("{n}",String(ne.windows||0)),((z=ne.outbox)==null?void 0:z.count)>0?` · 📦${ne.outbox.count}`:""]})]}),ne.activity?c.jsx("span",{className:"nc-rel",children:ws(ne.activity)}):null,c.jsx("button",{className:`nc-pin${W.includes(V.key)?" on":""}`,title:g("pin"),onClick:se=>{se.stopPropagation(),K(V.key)},children:W.includes(V.key)?"★":"☆"}),c.jsx("button",{className:`nc-technical${ne.technical?" on":""}`,title:ne.technical?g("mark-normal"):g("mark-technical"),"aria-label":`${ne.technical?g("mark-normal"):g("mark-technical")} ${ne.name}`,onClick:se=>{se.stopPropagation(),_&&_(ne.name,!ne.technical,[])},children:"T"}),c.jsx("button",{className:"nc-menu",title:g("terminate"),onClick:se=>{se.stopPropagation(),window.confirm(g("terminate-confirm").replace("{name}",ne.name))&&f&&f(ne.name)},children:"⋯"})]},V.key)})()),fe.length===0&&c.jsx("div",{className:"nc-empty",children:g("no-sessions-short")})]}),et.map(({g:V,nodeRoute:ne,groupView:z,rawItems:se,items:me})=>{const Ne=q_(V.health)||(V.status==="up"?"on":V.status==="passive"?"":"warn");return c.jsxs("div",{className:"nc-node-order-wrap","data-node-order-key":B(V),children:[c.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onContextMenu:V.direct&&y?we=>{we.preventDefault(),Fe(V)}:void 0,onClick:()=>j(ne,{open:!z.open}),onKeyDown:we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),j(ne,{open:!z.open}))},children:[c.jsx(ar,{scope:"node",position:"nodes",itemKey:B(V),label:V.label||V.name,onMove:(we,Re)=>T(we,Re,s||[]),onStep:we=>ie(B(V),we,s||[])}),c.jsx("span",{className:"nc-node-chevron",children:z.open?"⌄":"›"}),c.jsx("span",{className:`nc-dot ${Ne}`,title:V.health?wl(V.health):""}),c.jsx("b",{children:V.label||V.name}),c.jsxs("small",{children:[" · ",V.status==="up"?g("node-sessions").replace("{n}",String(me.length)):V.health&&wl(V.health)||vs(V)]}),c.jsxs("select",{className:"nc-node-filter",value:z.filter,title:g(`view-${z.filter}`),onClick:we=>we.stopPropagation(),onChange:we=>j(ne,{filter:we.target.value}),children:[c.jsx("option",{value:"all",children:g("view-all")}),c.jsx("option",{value:"pinned",children:g("view-pinned")}),c.jsx("option",{value:"active",children:g("view-active")}),c.jsx("option",{value:"off",children:g("view-off")}),c.jsx("option",{value:"technical",children:g("view-technical")})]}),V.direct&&y&&c.jsx("button",{type:"button",className:"nc-node-rename",title:g("rename-node"),"aria-label":`${g("rename-node")} ${V.label||V.name}`,onClick:we=>{we.stopPropagation(),Fe(V)},children:"✎"}),V.direct&&V.health&&V.health.managed!==!1&&c.jsx("button",{type:"button",className:`nc-power${V.tunnelStatus==="up"?" on":""}`,title:V.tunnelStatus==="up"?g("power-off"):g("power-on"),onClick:we=>{we.stopPropagation(),p&&p(V)},children:c.jsx(nt,{name:"power",size:14})})]}),V.status==="up"&&z.open&&c.jsxs("div",{className:"nc-side-group",children:[me.map(we=>we.type==="cell"?(()=>{const Re=we.value,Je=!!Re.tmux,Tt=Re.degraded?"warn":Re.tmux?"on":"";return c.jsxs("div",{"data-roster-key":we.key,"data-position":ne,className:`nc-side-card nc-cell${Je?" live":""}${Z.has(Re.key)?" active":""}`,title:we.working?we.subtitle:Re.tmux?g("cell-idle"):g("cell-off"),draggable:Je,onDragStart:Je?Me=>Me.dataTransfer.setData("text/nc-session",Re.key):void 0,onClick:Je?()=>a&&a(Re.key):void 0,onDoubleClick:Je?()=>ze(Re.tmuxSession,ne,V.instanceId):void 0,children:[c.jsx(ar,{position:ne,itemKey:we.key,label:Re.cell,canMove:P,onMove:(Me,pn)=>M(ne,Me,pn,se),onStep:Me=>H(ne,we.key,Me,se)}),c.jsx("span",{className:`nc-dot ${Tt}${we.working?" working":""}`}),c.jsxs("span",{className:"nc-card-main",children:[c.jsx("b",{children:Re.cell}),c.jsx("small",{title:we.subtitle,children:we.subtitle})]}),c.jsx("button",{className:`nc-pin${W.includes(we.key)?" on":""}`,title:g("pin"),onClick:Me=>{Me.stopPropagation(),K(we.key)},children:W.includes(we.key)?"★":"☆"}),h&&(V.capabilities||[]).includes("boot")&&it(Re,V.route||[]),(V.capabilities||[]).includes(Re.active?"down":"up")&&c.jsx("button",{className:`nc-power${Re.active?" on":""}${Re.degraded?" warn":""}`,onClick:Me=>{Me.stopPropagation(),u&&u({...Re,boot:ct(Re,V.route||[]),route:V.route,availableEngines:V.engines||[]})},title:Re.active?g("power-off"):g("power-on"),children:c.jsx(nt,{name:"power",size:14})})]},we.key)})():(()=>{const Re=we.value;return c.jsxs("div",{"data-roster-key":we.key,"data-position":ne,className:`nc-side-card${Z.has(Re.key)?" active":""}`,draggable:!0,onDragStart:Je=>Je.dataTransfer.setData("text/nc-session",Re.key),onClick:()=>a&&a(Re.key),onDoubleClick:()=>ze(Re.name,Re.node||ne,V.instanceId),children:[c.jsx(ar,{position:ne,itemKey:we.key,label:Re.name,canMove:P,onMove:(Je,Tt)=>M(ne,Je,Tt,se),onStep:Je=>H(ne,we.key,Je,se)}),c.jsx("span",{className:Re.attached?"nc-dot on":"nc-dot"}),c.jsxs("span",{className:"nc-card-main",children:[c.jsx("b",{children:Re.name}),c.jsx("small",{children:Re.preview?Re.preview:Re.cmd?Re.cmd:g("windows").replace("{n}",String(Re.windows||0))})]}),Re.activity?c.jsx("span",{className:"nc-rel",children:ws(Re.activity)}):null,c.jsx("button",{className:`nc-pin${W.includes(we.key)?" on":""}`,title:g("pin"),onClick:Je=>{Je.stopPropagation(),K(we.key)},children:W.includes(we.key)?"★":"☆"}),c.jsx("button",{className:`nc-technical${Re.technical?" on":""}`,title:Re.technical?g("mark-normal"):g("mark-technical"),"aria-label":`${Re.technical?g("mark-normal"):g("mark-technical")} ${Re.name}`,onClick:Je=>{Je.stopPropagation(),_&&_(Re.name,!Re.technical,V.route||[])},children:"T"}),c.jsx("button",{className:"nc-menu",title:g("terminate"),onClick:Je=>{Je.stopPropagation(),window.confirm(g("terminate-confirm").replace("{name}",Re.name))&&f&&f(Re.name,V.route)},children:"⋯"})]},we.key)})()),me.length===0&&c.jsx("div",{className:"nc-empty",children:g("no-sessions-short")})]})]},`nodo-${(V.route||[V.name]).join("/")}`)})]}),c.jsx("div",{className:"nc-side-lang",children:H_.map((V,ne)=>c.jsxs("span",{children:[ne>0&&" · ",c.jsx("button",{className:`nc-lang-btn${D===V?" on":""}`,onClick:()=>J(V),title:V,children:V.toUpperCase()})]},V))}),c.jsx("div",{className:"nc-side-resize",onPointerDown:$e,title:""})]})}function pE({label:e,count:t,state:n,onToggle:s,onFilter:o}){return c.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onClick:s,onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),s())},children:[c.jsx("span",{className:"nc-node-chevron",children:n.open?"⌄":"›"}),c.jsx("span",{className:"nc-dot on"}),c.jsx("b",{children:e}),c.jsxs("small",{children:[" · ",g("node-sessions").replace("{n}",String(t))]}),c.jsxs("select",{className:"nc-node-filter",value:n.filter,title:g(`view-${n.filter}`),onClick:a=>a.stopPropagation(),onChange:a=>o(a.target.value),children:[c.jsx("option",{value:"all",children:g("view-all")}),c.jsx("option",{value:"pinned",children:g("view-pinned")}),c.jsx("option",{value:"active",children:g("view-active")}),c.jsx("option",{value:"off",children:g("view-off")}),c.jsx("option",{value:"technical",children:g("view-technical")})]})]})}function mE(e,t,n){return!e&&t?n+1:n}const Kh="nc_input_preferences_v1",Wu="nc-input-preferences",sw=Object.freeze(["double-tap","single-tap","never"]),ow=Object.freeze(["full","compact"]),lr=Object.freeze({terminalKeyboardGesture:"double-tap",keybarKeepsKeyboardClosed:!0,voiceKeepsKeyboardClosed:!0,showKeybarEnter:!0,keybarLayout:"full"});function qh(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{terminalKeyboardGesture:sw.includes(t.terminalKeyboardGesture)?t.terminalKeyboardGesture:lr.terminalKeyboardGesture,keybarKeepsKeyboardClosed:typeof t.keybarKeepsKeyboardClosed=="boolean"?t.keybarKeepsKeyboardClosed:lr.keybarKeepsKeyboardClosed,voiceKeepsKeyboardClosed:typeof t.voiceKeepsKeyboardClosed=="boolean"?t.voiceKeepsKeyboardClosed:lr.voiceKeepsKeyboardClosed,showKeybarEnter:typeof t.showKeybarEnter=="boolean"?t.showKeybarEnter:lr.showKeybarEnter,keybarLayout:ow.includes(t.keybarLayout)?t.keybarLayout:lr.keybarLayout}}function aw(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function bv(e=aw()){if(!e)return{...lr};try{return qh(JSON.parse(e.getItem(Kh)||"null"))}catch{return{...lr}}}function gE(e,t=aw()){const n=qh(e);if(t)try{t.setItem(Kh,JSON.stringify(n))}catch{}return n}function Vh(){const[e,t]=N.useState(bv);N.useEffect(()=>{const s=o=>{if((o==null?void 0:o.type)==="storage"&&o.key!==Kh&&o.key!==null)return;const a=o!=null&&o.detail?qh(o.detail):bv();t(a)};return window.addEventListener(Wu,s),window.addEventListener("storage",s),()=>{window.removeEventListener(Wu,s),window.removeEventListener("storage",s)}},[]);const n=N.useCallback(s=>{t(o=>{const a=gE({...o,...s||{}});return window.dispatchEvent(new CustomEvent(Wu,{detail:a})),a})},[]);return[e,n]}function vE({session:e,node:t,ownerId:n,cellName:s,token:o,readonly:a=!1,focused:u,onFocus:h,onClose:p,onOpenSingle:f,alive:_=!0,available:b=!0,fontSize:y=Mo,onZoom:w,decks:S=[],currentDeck:x,onSendToDeck:C}){const[k]=Vh(),R=s||e,I=N.useRef(()=>{}),A=N.useRef(()=>!1),G=N.useRef(()=>{}),F=N.useRef(!1),[D,J]=N.useState(!1),[W,ee]=N.useState(!1),[K,O]=N.useState(!1),[j,P]=N.useState(null),[M,H]=N.useState(0),te=N.useRef(_),T=t?`${t}:${e}`:e,ie=S.filter(B=>B.id!==x&&B.available!==!1);return N.useEffect(()=>{const B=te.current;!B&&_&&H(L=>mE(B,_,L)),te.current=_},[_]),c.jsxs("div",{className:`nc-tile${u?" focused":""}`,onMouseDown:()=>h&&h(T),children:[c.jsxs("div",{className:"nc-tile-head",draggable:!0,onDragStart:B=>{B.dataTransfer.setData("text/nc-session",T),B.dataTransfer.effectAllowed="move"},children:[c.jsxs("button",{className:"nc-tile-name",onClick:()=>h&&h(T),title:t?`${R} · ${t}`:R,children:[c.jsx("span",{className:_?"nc-dot on":"nc-dot"}),c.jsx("b",{children:R})]}),c.jsxs("span",{className:"nc-tile-actions",children:[w&&c.jsx("button",{onClick:()=>w(-1),title:g("zoom-out"),children:c.jsx(nt,{name:"zoomOut",size:14})}),w&&c.jsx("button",{onClick:()=>w(1),title:g("zoom-in"),children:c.jsx(nt,{name:"zoomIn",size:14})}),C&&ie.length>0&&c.jsxs("select",{className:"nc-tile-deck",title:g("send-to-deck"),value:"",onMouseDown:B=>B.stopPropagation(),onChange:B=>{const L=B.target.value;L&&C(T,L),B.target.value=""},children:[c.jsx("option",{value:"",children:g("send-to-deck")}),ie.map(B=>c.jsxs("option",{value:B.id,children:[B.ownerLabel," · ",B.name]},B.id))]}),c.jsx("button",{onClick:()=>ee(B=>!B),title:"composer",children:"⌨"}),c.jsx("button",{onClick:()=>O(B=>!B),title:"file",children:"📁"}),f&&c.jsx("button",{onClick:()=>f({session:e,node:t,ownerId:n}),title:"vista singola",children:"↗"}),p&&c.jsx("button",{className:"nc-tile-close",onClick:()=>p(T),title:"chiudi",children:"✕"})]})]}),c.jsxs("div",{className:"nc-tile-body",children:[b?c.jsx(Yy,{session:e,node:t,token:o,readonly:a,takeSize:!1,focused:u,sendRef:I,composerRef:A,actionRef:G,ctrlRef:F,setCtrlArmed:J,onFiles:P,fontSize:y,keyboardGesture:k.terminalKeyboardGesture},`${T}:${M}`):c.jsx("div",{className:"nc-tile-unavailable",children:g("deck-owner-unavailable")}),b&&K&&c.jsx("div",{className:"nc-tile-files",onMouseDown:B=>B.stopPropagation(),children:c.jsx(Gy,{session:e,node:t,token:o,filesEvent:j,onClose:()=>O(!1)})})]}),b&&W&&c.jsx("div",{className:"nc-tile-composer",onMouseDown:B=>B.stopPropagation(),children:c.jsx(rw,{submitText:B=>A.current(B),token:o,session:e,node:t,ownerId:n,keepKeyboardClosedOnVoice:k.voiceKeepsKeyboardClosed})})]})}function _E({session:e,node:t,ownerId:n,cells:s,nodeGroups:o}={}){const a=typeof e=="string"?e:"";if(!a)return null;if(t){const h=Array.isArray(o)?o:[];for(const p of h){if(!p||(Array.isArray(p.route)?p.route:[]).join("/")!==t||n&&p.instanceId&&String(n)!==String(p.instanceId))continue;const _=(Array.isArray(p.cells)?p.cells:[]).find(b=>b&&b.tmuxSession===a);if(_)return _}return null}return(Array.isArray(s)?s:[]).find(h=>h&&h.tmuxSession===a)||null}function Yh({session:e,cell:t,node:n,ownerId:s,cells:o,nodeGroups:a}={}){const u=typeof e=="string"?e:"";if(t&&typeof t.cell=="string"&&t.cell)return t.cell;const h=_E({session:u,node:n,ownerId:s,cells:o,nodeGroups:a});return h&&h.cell?h.cell:u}const kv=.2,xv=.28,lw=(e,t)=>Array.from((e==null?void 0:e.types)||[]).includes(t),Uu=e=>lw(e,"text/nc-session"),Cv=e=>{var t;return lw(e,"Files")||(((t=e==null?void 0:e.files)==null?void 0:t.length)||0)>0};function yE(e,t,n){const s=(e-n.left)/(n.width||1),o=(t-n.top)/(n.height||1);return s<xv?"left":s>1-xv?"right":o<.5?"top":"bottom"}function wE({layout:e,onLayoutChange:t,token:n,readonly:s=!1,sessionsAlive:o,focusSession:a,onFocus:u,onOpenSingle:h,decks:p=[],currentDeck:f,onSendToDeck:_,cells:b=[],nodeGroups:y=[]}){zn();const[w,S]=N.useState(null),x=N.useRef(null),C=N.useRef([]),k=N.useRef(null);function R(K,O){const j=()=>{window.removeEventListener("pointermove",K),window.removeEventListener("pointerup",j),window.removeEventListener("pointercancel",j),window.removeEventListener("blur",j),k.current=null};window.addEventListener("pointermove",K),window.addEventListener("pointerup",j),window.addEventListener("pointercancel",j),window.addEventListener("blur",j),k.current=j}N.useEffect(()=>()=>{k.current&&k.current()},[]),N.useEffect(()=>{const K=()=>S(null);return window.addEventListener("dragend",K),window.addEventListener("drop",K),()=>{window.removeEventListener("dragend",K),window.removeEventListener("drop",K)}},[]);const I=e.columns.length,A=K=>w&&w.col===K&&w.row===void 0,G=!!w&&w.col===I,F=(K,O)=>w&&w.col===K&&w.row===O&&w.quadrant?` drop-${w.quadrant}`:"";function D(K){if(K.preventDefault(),Cv(K.dataTransfer)){S(null);return}const O=K.dataTransfer.getData("text/nc-session"),j=w;if(S(null),!O||!j)return;let P;if(j.quadrant){if(P=n1(e,j.col,j.row,j.quadrant),!P)return}else P={col:j.col};t(vi(e).includes(O)?J0(e,O,P):Th(e,O,P))}function J(K,O){K.preventDefault(),K.stopPropagation();const j=K.clientX,P=e.columns[O].width,M=x.current&&x.current.clientWidth||1,H=e.columns[O+1];R(T=>{let ie=Math.max(kv,P+(T.clientX-j)/M);if(H){const B=fg(ie/(ie+H.width));ie=B/(1-B)*H.width}t(Z0(e,O,ie))})}function W(K,O,j){K.preventDefault(),K.stopPropagation();const P=K.clientY,M=e.columns[O].tiles[j].height,H=C.current[O],te=H&&H.clientHeight||1,T=e.columns[O].tiles[j+1];R(B=>{let L=Math.max(kv,M+(B.clientY-P)/te);if(T){const $=fg(L/(L+T.height));L=$/(1-$)*T.height}t(e1(e,O,j,L))})}function ee(K){t(kl(e,K))}return c.jsxs("div",{className:"nc-grid",ref:x,onDragOver:K=>{if(Cv(K.dataTransfer)){K.preventDefault(),S(null);return}Uu(K.dataTransfer)&&(K.preventDefault(),w&&w.col===I||S({col:I}))},onDrop:D,onDragLeave:K=>{const O=K.relatedTarget;(!O||!(x.current&&x.current.contains(O)))&&S(null)},children:[e.columns.flatMap((K,O)=>{const j=[];return j.push(c.jsx("div",{className:`nc-col${A(O)?" drop-newcol":""}`,ref:P=>{C.current[O]=P},style:{flexGrow:K.width,flexBasis:0},onDragOver:P=>{Uu(P.dataTransfer)&&(P.preventDefault(),P.stopPropagation(),w&&w.col===O&&w.row===void 0||S({col:O}))},children:K.tiles.flatMap((P,M)=>{const H=[],te=In(P),T=Yh({session:P.session,node:P.node,ownerId:P.ownerId,cells:b,nodeGroups:y});return H.push(c.jsx("div",{className:`nc-tile-slot${F(O,M)}`,style:{flexGrow:P.height,flexBasis:0},onDragOver:ie=>{if(!Uu(ie.dataTransfer))return;ie.preventDefault(),ie.stopPropagation();const B=yE(ie.clientX,ie.clientY,ie.currentTarget.getBoundingClientRect());w&&w.col===O&&w.row===M&&w.quadrant===B||S({col:O,row:M,quadrant:B})},children:c.jsx(vE,{session:P.session,node:P.node,ownerId:P.ownerId,cellName:T,token:n,readonly:s,focused:a===te,onFocus:u,onClose:ee,onOpenSingle:h,available:P.unavailable!==!0,alive:P.unavailable!==!0&&(!o||o.has(te)),fontSize:P.fontSize,onZoom:ie=>t(t1(e,O,M,ie)),decks:p,currentDeck:f,onSendToDeck:_})},te)),M<K.tiles.length-1&&H.push(c.jsx("div",{className:"nc-divider-h",onPointerDown:ie=>W(ie,O,M)},`h${M}`)),H})},`c${O}`)),O<I-1&&j.push(c.jsx("div",{className:"nc-divider-v",onPointerDown:P=>J(P,O)},`v${O}`)),j}),G&&c.jsx("div",{className:"nc-drop-line-v nc-drop-line-end"}),I===0&&c.jsx("div",{className:"nc-grid-empty",children:g("grid-empty")})]})}const mi="local",Bn=/^[a-f0-9]{16,64}$/;function ys(e,t){return`${e&&Bn.test(e)?e:mi}:${t}`}function zl(e){const t=String(e||""),n=t.indexOf(":");if(n<1)return null;const s=t.slice(0,n),o=t.slice(n+1);return s!==mi&&!Bn.test(s)||!/^[a-z0-9-]{1,32}$/.test(o)?null:{ownerId:s===mi?null:s,name:o}}function Fl(e){return Array.isArray(e)&&e.length?e.join("/"):""}function Gh(e){return{columns:Ar(e).columns.map(t=>({width:t.width,tiles:t.tiles.map(n=>({...n}))}))}}function SE(e){const t=new Map;for(const n of Array.isArray(e)?e:[])n&&Bn.test(String(n.instanceId||""))&&Array.isArray(n.route)&&t.set(Fl(n.route),n.instanceId);return t}function bE(e){const t=new Map;for(const n of Array.isArray(e)?e:[])n&&Bn.test(String(n.instanceId||""))&&Array.isArray(n.route)&&t.set(n.instanceId,[...n.route]);return t}function dh(e,t,n=[]){const s=Gh(e),o=SE(n);for(const a of s.columns)for(const u of a.tiles)u.ownerId||(!u.node&&Bn.test(String(t||""))?u.ownerId=t:u.node&&o.has(u.node)&&(u.ownerId=o.get(u.node)));return s}function hh(e,t,n=[]){const s=Gh(e),o=new Map;for(const a of n)a&&Bn.test(String(a.instanceId||""))&&Array.isArray(a.route)&&o.set(a.instanceId,[...a.route]);for(const a of s.columns)for(const u of a.tiles)u.ownerId&&(u.ownerId===t?(delete u.node,delete u.unavailable):o.has(u.ownerId)?(u.node=Fl(o.get(u.ownerId)),delete u.unavailable):u.unavailable=!0);return s}function Ev(e,t,n=[]){const s=Gh(e),o=bE(n);for(const a of s.columns)for(const u of a.tiles)delete u.unavailable,u.ownerId&&(u.ownerId===t?delete u.node:o.has(u.ownerId)&&(u.node=Fl(o.get(u.ownerId))));return s}function cw(e,t,n=[]){const s=fr(e);if(!s)return null;if(s.ownerId)return s;if(!s.node)return{...s,...Bn.test(String(t||""))?{ownerId:t}:{}};const o=n.find(a=>Fl(a&&a.route)===s.node);return{...s,...o&&Bn.test(String(o.instanceId||""))?{ownerId:o.instanceId}:{}}}const kE=/^[a-z0-9-]{1,32}$/,On="main",uw="nc_decks",dw="nc_deck_order_v1",hw=24;function Nv(e){return typeof e!="string"?"":e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,32).replace(/-+$/,"")}function xs(e){return typeof e=="string"&&kE.test(e)}function xE(e){const t=String(e||"").match(/^\/deck\/([^/]+)\/?$/);if(t){let n;try{n=decodeURIComponent(t[1])}catch{n=t[1]}return xs(n)?n:On}return On}function CE(e){const t=String(e||"").match(/^\/deck\/([^/]+)\/([^/]+)\/?$/);if(t){let s,o;try{s=decodeURIComponent(t[1]),o=decodeURIComponent(t[2])}catch{return{id:ys(null,On),ownerId:null,name:On}}if(Bn.test(s)&&xs(o))return{id:ys(s,o),ownerId:s,name:o}}const n=xE(e);return{id:ys(null,n),ownerId:null,name:n}}function Ku(e,t){const n=typeof e=="object"&&e?{ownerId:e.ownerId||null,name:e.name}:zl(e)||{ownerId:null,name:e},s=xs(n.name)?n.name:On,o=n.ownerId?`/deck/${encodeURIComponent(n.ownerId)}/${encodeURIComponent(s)}`:s===On?"/":`/deck/${encodeURIComponent(s)}`;return t?`${o}#token=${encodeURIComponent(t)}`:o}function fw(e){return e===On?"nc_grid_v1":`nc_grid_v1__${e}`}function pw(e){const t=[On];if(Array.isArray(e)){for(const n of e)if(xs(n)&&n!==On&&!t.includes(n)&&t.push(n),t.length>=hw)break}return t}function Ps(){return typeof localStorage<"u"?localStorage:null}function EE(){const e=Ps();if(!e)return[On];try{return pw(JSON.parse(e.getItem(uw)||"null"))}catch{return[On]}}function NE(e){const t=Ps();if(t)try{t.setItem(uw,JSON.stringify(pw(e)))}catch{}}function Fo(e){return e==="local"||Bn.test(String(e||""))}function $l(e,t){const n=zl(e);return!!n&&(n.ownerId||"local")===t}function yi(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[n,s]of Object.entries(e).slice(0,64)){if(!Fo(n)||!Array.isArray(s))continue;const o=[...new Set(s.filter(a=>typeof a=="string"&&a.length<=100&&$l(a,n)))].slice(0,hw);o.length&&(t[n]=o)}return t}function il(e=Ps()){if(!e)return{};try{return yi(JSON.parse(e.getItem(dw)||"null"))}catch{return{}}}function qu(e,t=Ps()){const n=yi(e);if(t)try{t.setItem(dw,JSON.stringify(n))}catch{}return n}function Hl(e,t){return Array.isArray(e==null?void 0:e[t])?e[t]:[]}function RE(e,t,n,s,o=[]){if(!Fo(t)||n===s)return yi(e);const a=[...new Set(o.filter(b=>$l(b,t)))];if(!a.includes(n)||!a.includes(s))return yi(e);const u=Hl(e,t).filter(b=>a.includes(b)),h=[...u,...a.filter(b=>!u.includes(b))],p=h.indexOf(n),f=h.indexOf(s);h.splice(p,1);const _=h.indexOf(s);return h.splice(p<f?_+1:_,0,n),yi({...e,[t]:h})}function PE(e,t,n,s){if(!Fo(t)||!$l(s,t))return yi(e);const o=Hl(e,t);return o.includes(n)?yi({...e,[t]:o.map(a=>a===n?s:a)}):yi(e)}function jE(e,t,n){return Fo(t)?yi({...e,[t]:Hl(e,t).filter(s=>s!==n)}):yi(e)}function Rv(e,t={}){const n=new Map;for(const o of Array.isArray(e)?e:[]){const a=o!=null&&o.local?"local":String((o==null?void 0:o.ownerId)||"");!Fo(a)||!$l(o==null?void 0:o.id,a)||(n.has(a)||n.set(a,[]),n.get(a).push(o))}const s=[];for(const[,o]of n){const a=o[0].local?"local":o[0].ownerId,u=Hl(t,a),h=new Map(u.map((p,f)=>[p,f]));o.sort((p,f)=>{const _=h.has(p.id)?h.get(p.id):Number.MAX_SAFE_INTEGER,b=h.has(f.id)?h.get(f.id):Number.MAX_SAFE_INTEGER;return _-b}),s.push(...o)}return s}function fh(e){const t=Ps();if(!t)return null;try{return JSON.parse(t.getItem(fw(e))||"null")}catch{return null}}function LE(e,t){const n=Ps();if(n)try{n.setItem(fw(e),JSON.stringify(t))}catch{}}const Xh="nc_deckbar_collapsed_v1",mw=64;function Jh(e){return e===mi||Bn.test(String(e||""))}function Qh(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[s,o]of Object.entries(e)){if(n>=mw)break;if(Jh(s)){if(o===!0)t[s]=!0;else if(o===!1)t[s]=!1;else continue;n+=1}}return t}function gw(e,t){return Jh(t)&&Object.prototype.hasOwnProperty.call(e||{},t)?e[t]===!0:!0}function DE(e,t){const n=Qh(e);return Jh(t)&&(!Object.prototype.hasOwnProperty.call(n,t)&&Object.keys(n).length>=mw&&delete n[Object.keys(n)[0]],n[t]=!gw(n,t)),n}function vw(){return typeof localStorage<"u"?localStorage:null}function Pv(e=vw()){if(!e)return{};try{return Qh(JSON.parse(e.getItem(Xh)||"null"))}catch{return{}}}function TE(e,t=vw()){const n=Qh(e);if(t)try{t.setItem(Xh,JSON.stringify(n))}catch{}return n}function ME(){const[e,t]=N.useState(Pv);N.useEffect(()=>{const o=a=>{(a.key===Xh||a.key===null)&&t(Pv())};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)},[]);const n=N.useCallback(o=>gw(e,o),[e]),s=N.useCallback(o=>{t(a=>TE(DE(a,o)))},[]);return{collapsed:e,isCollapsed:n,toggle:s}}const Zh="nc_deck_presence_v1",jv=3e4,AE=18e4,_w=1e4,yw=32,IE=/^[A-Za-z0-9_-]{1,64}$/,BE=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Lv="working",OE="on",zE="neutral",FE="warn";function ef(e){return typeof e=="string"&&IE.test(e)&&!BE.has(e)}function ww(e){return typeof e=="string"&&zl(e)!==null}function tf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Cs(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[s,o]of Object.entries(e)){if(n>=yw)break;ef(s)&&(!o||typeof o!="object"||ww(o.deckId)&&tf(o.ts)&&(t[s]={deckId:o.deckId,ts:o.ts,focus:o.focus===!0,visible:o.visible===!0},n+=1))}return t}function Sw(e,t){const n=Cs(e);if(!tf(t))return n;const s={};for(const[o,a]of Object.entries(n)){const u=a.visible?jv:AE,h=t-u;a.ts>=h&&a.ts<=t+jv&&(s[o]=a)}return s}function Dv(e,t,n,s){if(!ef(t)||!tf(s))return Cs(e);const o=Sw(e,s);if(!ww(n==null?void 0:n.deckId))return o;if(!Object.prototype.hasOwnProperty.call(o,t)&&Object.keys(o).length>=yw){let a="",u=1/0;for(const[h,p]of Object.entries(o))p.ts<u&&(a=h,u=p.ts);a&&delete o[a]}return o[t]={deckId:n.deckId,ts:s,focus:(n==null?void 0:n.focus)===!0,visible:(n==null?void 0:n.visible)===!0},Cs(o)}function $E(e,t){const n=Cs(e);if(!ef(t))return n;const s={...n};return delete s[t],s}function HE(e,t){const n=Sw(e,t),s={};for(const o of Object.values(n)){const a=o.focus&&o.visible?Lv:OE;s[o.deckId]!==Lv&&(s[o.deckId]=a)}return s}function bw(){return typeof localStorage<"u"?localStorage:null}function rl(e=bw()){if(!e)return{};try{return Cs(JSON.parse(e.getItem(Zh)||"null"))}catch{return{}}}function Vu(e,t=bw()){const n=Cs(e);if(t)try{t.setItem(Zh,JSON.stringify(n))}catch{}return n}const WE=Math.min(_w,5e3);function UE(){var e,t;try{const n=(t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e);if(n)return`w${n.replaceAll("-","")}`}catch{}return`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,14)}`}const KE=UE();function Tv(){const e=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0,t=typeof document<"u"&&typeof document.visibilityState=="string"?document.visibilityState!=="hidden":!0;return{focus:e,visible:t}}function qE(e,t=!0){const s=N.useRef(KE).current,o=N.useRef(e);o.current=e;const[a,u]=N.useState(()=>({map:{},now:Date.now()})),h=N.useCallback(()=>{u({map:rl(),now:Date.now()})},[]);N.useEffect(()=>{if(!t)return;const _=()=>{const C=Date.now(),k=Dv(rl(),s,{deckId:o.current,...Tv()},C);return Vu(k),{map:k,now:C}},b=()=>u(_());b();const y=setInterval(_,_w),w=setInterval(h,WE),S=b,x=C=>{(C.key===Zh||C.key===null)&&h()};return window.addEventListener("focus",S),window.addEventListener("blur",S),typeof document<"u"&&document.addEventListener("visibilitychange",S),window.addEventListener("storage",x),()=>{clearInterval(y),clearInterval(w),window.removeEventListener("focus",S),window.removeEventListener("blur",S),typeof document<"u"&&document.removeEventListener("visibilitychange",S),window.removeEventListener("storage",x);try{Vu($E(rl(),s))}catch{}}},[t,s,h]),N.useEffect(()=>{if(!t)return;const _=Date.now(),b=Dv(rl(),s,{deckId:e,...Tv()},_);Vu(b),u({map:b,now:_})},[e,t,s]);const p=N.useMemo(()=>t?HE(a.map,a.now):{},[t,a]);return{dotFor:N.useCallback((_,b=!1)=>t?b?FE:p[_]||zE:null,[p,t]),windowId:s}}const Mv=52,Av=18;function VE({ownerKey:e,deckId:t,label:n,onMove:s,onStep:o}){const a=N.useRef(null),u=N.useRef(0),[h,p]=N.useState(!1),f=()=>{var x,C,k,R;const S=a.current;(C=(x=S==null?void 0:S.over)==null?void 0:x.classList)==null||C.remove("nc-deck-over"),(R=(k=S==null?void 0:S.source)==null?void 0:k.classList)==null||R.remove("nc-deck-dragging"),u.current&&cancelAnimationFrame(u.current),u.current=0},_=(S=!1)=>{const x=a.current;if(!x)return;const C=x.target;f(),a.current=null,p(!1);try{x.handle.releasePointerCapture(x.pointerId)}catch{}S&&C&&C!==t&&s(t,C)},b=(S,x)=>{var A,G,F,D,J,W,ee,K;const C=a.current;if(!C)return;C.x=S,C.y=x;const k=(G=(A=document.elementFromPoint(S,x))==null?void 0:A.closest)==null?void 0:G.call(A,"[data-deck-id][data-owner-key]"),R=(F=k==null?void 0:k.dataset)==null?void 0:F.deckId,I=((D=k==null?void 0:k.dataset)==null?void 0:D.ownerKey)===e&&R&&R!==t;C.over!==(I?k:null)&&((W=(J=C.over)==null?void 0:J.classList)==null||W.remove("nc-deck-over"),C.over=I?k:null,(K=(ee=C.over)==null?void 0:ee.classList)==null||K.add("nc-deck-over")),C.target=I?R:null},y=()=>{var C,k;const S=a.current;if(!S){u.current=0;return}const x=(k=(C=S.container)==null?void 0:C.getBoundingClientRect)==null?void 0:k.call(C);if(x){const R=S.x<x.left+Mv?-Av:S.x>x.right-Mv?Av:0;R&&(S.container.scrollLeft+=R,b(S.x,S.y))}u.current=requestAnimationFrame(y)};N.useEffect(()=>{const S=C=>{C.key==="Escape"&&a.current&&(C.preventDefault(),_(!1))},x=()=>_(!1);return window.addEventListener("keydown",S),window.addEventListener("blur",x),()=>{window.removeEventListener("keydown",S),window.removeEventListener("blur",x),f(),a.current=null}},[t,e]);const w=S=>{var k;if(S.pointerType==="mouse"&&S.button!==0)return;S.preventDefault(),S.stopPropagation(),S.currentTarget.focus({preventScroll:!0});const x=S.currentTarget.closest("[data-deck-id][data-owner-key]"),C=S.currentTarget.closest(".nc-deckbar");a.current={pointerId:S.pointerId,handle:S.currentTarget,source:x,container:C,target:null,over:null,x:S.clientX,y:S.clientY},(k=x==null?void 0:x.classList)==null||k.add("nc-deck-dragging");try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}p(!0),u.current=requestAnimationFrame(y)};return c.jsx("button",{type:"button",className:`nc-deck-handle${h?" active":""}`,"aria-label":`${g("reorder")} ${n}`,"aria-keyshortcuts":"ArrowLeft ArrowRight",title:g("reorder-deck-help"),onClick:S=>{S.preventDefault(),S.stopPropagation()},onDragStart:S=>S.preventDefault(),onKeyDown:S=>{S.key!=="ArrowLeft"&&S.key!=="ArrowRight"||(S.preventDefault(),S.stopPropagation(),o(S.key==="ArrowLeft"?-1:1))},onPointerDown:w,onPointerMove:S=>{!a.current||S.pointerId!==a.current.pointerId||(S.preventDefault(),S.stopPropagation(),b(S.clientX,S.clientY))},onPointerUp:S=>{!a.current||S.pointerId!==a.current.pointerId||(S.preventDefault(),S.stopPropagation(),_(!0))},onPointerCancel:()=>_(!1),onLostPointerCapture:()=>{a.current&&_(!1)},children:"↔"})}function YE({decks:e=[],currentDeck:t="local:main",onCreate:n,onRename:s,onDelete:o,onReorder:a,onOpenWindow:u,onNavigate:h,saveState:p="idle",error:f="",sidebarVisible:_,onToggleSidebar:b}){zn();const{isCollapsed:y,toggle:w}=ME(),{dotFor:S}=qE(t),[x,C]=N.useState(null),[k,R]=N.useState(""),[I,A]=N.useState(!1),[G,F]=N.useState(""),[D,J]=N.useState(""),W=Nv(k),ee=xs(W),K=[];for(const H of e){const te=H.local?"local":H.ownerId;let T=K.find(ie=>ie.key===te);T||(T={key:te,label:H.ownerLabel||(H.local?"Local":te),local:!!H.local,decks:[]},K.push(T)),T.decks.push(H)}const O=async()=>{if(ee){A(!0),F("");try{n&&await n(W,x),R(""),C(null)}catch(H){F(String(H.message||H))}A(!1)}},j=H=>{J(""),u&&u(H.id)||J(H.id)},P=async H=>{if(!(H.id===t||!h||I||H.available===!1)){A(!0),F("");try{await h(H.id)}catch(te){F(String((te==null?void 0:te.message)||te))}A(!1)}},M=(H,te,T)=>{const ie=H.decks.findIndex(L=>L.id===te.id),B=H.decks[ie+T];ie>=0&&B&&a&&!I&&a(te.id,B.id)};return c.jsxs("div",{className:"nc-deckbar",children:[b&&c.jsx("button",{className:"nc-deck-sidebar-toggle",title:g("toggle-sidebar"),onClick:b,children:_?"◀":"☰"}),c.jsx("span",{className:"nc-deckbar-label",children:g("decks")}),c.jsx("div",{className:"nc-deck-chips",children:K.map(H=>{const te=y(H.key),T=`nc-deck-content-${H.key}`,ie=H.local?"Local":H.label,B=H.decks.some(X=>X.id===t),L=(H.decks.find(X=>X.id===t)||{}).name,$=g(H.decks.length===1?"owner-deck-count-one":"owner-deck-count-many").replace("{count}",H.decks.length);return c.jsxs("span",{className:`nc-deck-owner-group${te?" collapsed":""}`,"data-owner-key":H.key,"data-collapsed":te?"1":"0",children:[c.jsxs("button",{type:"button",className:"nc-deck-owner-toggle","aria-expanded":!te,"aria-controls":T,title:g(te?"expand-owner":"collapse-owner").replace("{owner}",ie),onClick:()=>{!te&&x===H.key&&(R(""),C(null)),w(H.key)},children:[c.jsx("span",{className:"nc-deck-owner-caret","aria-hidden":"true",children:te?"▸":"▾"}),c.jsx("span",{className:"nc-deck-owner",children:ie})]}),te&&c.jsxs("span",{className:"nc-deck-summary",title:$,children:[c.jsx("span",{className:"nc-deck-summary-count",children:H.decks.length}),B&&c.jsxs("span",{className:"nc-deck-summary-current",children:["• ",L]})]}),c.jsxs("span",{id:T,className:"nc-deck-owner-content",hidden:te,children:[H.decks.map(X=>{const ae=S(X.id,X.available===!1);return c.jsxs("span",{"data-deck-id":X.id,"data-owner-key":H.key,className:`nc-deck-chip${X.id===t?" current":""}${X.available===!1?" offline":""}`,children:[ae&&c.jsx(GE,{state:ae}),c.jsx(VE,{ownerKey:H.key,deckId:X.id,label:`${H.label} · ${X.name}`,onMove:(ue,ge)=>{a&&!I&&a(ue,ge)},onStep:ue=>M(H,X,ue)}),c.jsxs("button",{className:"nc-deck-open",title:X.available===!1?`${X.ownerLabel} offline`:X.id===t?g("deck-current"):`${X.ownerLabel} · ${X.name}`,disabled:I||X.available===!1,onClick:()=>P(X),children:[X.name,X.id===t?" •":""]}),c.jsx("button",{className:"nc-deck-mini",disabled:X.available===!1,title:g("detach-deck"),onClick:()=>j(X),children:"↗"}),X.name!==On&&c.jsxs(c.Fragment,{children:[c.jsx("button",{className:"nc-deck-mini",disabled:X.available===!1,title:g("rename-deck"),onClick:()=>{const ue=(typeof window<"u"?window.prompt(g("rename-deck"),X.name):"")||"",ge=Nv(ue);xs(ge)&&ge!==X.name&&s&&s(X.id,ge).catch(Z=>F(String(Z.message||Z)))},children:"✎"}),c.jsx("button",{className:"nc-deck-mini nc-deck-del",disabled:X.available===!1,title:g("delete-deck"),onClick:()=>{(typeof window>"u"||window.confirm(g("delete-deck-confirm").replace("{name}",`${X.ownerLabel} · ${X.name}`)))&&o&&o(X.id).catch(ue=>F(String(ue.message||ue)))},children:"✕"})]})]},X.id)}),x===H.key?c.jsxs("span",{className:"nc-deck-add",children:[c.jsx("input",{autoFocus:!0,className:ee||!k?"":"invalid",placeholder:g("deck-name"),value:k,onChange:X=>R(X.target.value),onKeyDown:X=>{X.key==="Enter"&&O(),X.key==="Escape"&&(R(""),C(null))}}),k&&ee&&W!==k&&c.jsxs("span",{className:"nc-deck-slug",children:["→ ",W]}),c.jsx("button",{className:"nc-deck-ok",disabled:!ee||I,onClick:O,children:g("create")}),c.jsx("button",{className:"nc-deck-cancel",onClick:()=>{R(""),C(null)},children:g("cancel")})]}):c.jsxs("button",{className:"nc-deck-newbtn",disabled:I||H.decks.every(X=>X.available===!1),title:`${g("new-deck")} · ${H.label}`,onClick:()=>{R(""),C(H.key)},children:["+ ",g("new")]})]})]},H.key)})}),c.jsx("span",{className:`nc-deck-state ${p}`,title:g("deck-autosave"),children:g(p==="saving"?"saving":p==="saved"?"saved":"deck-autosave")}),(G||f)&&c.jsx("span",{className:"nc-deck-error",children:G||f}),D&&c.jsx("button",{className:"nc-deck-fallback",onClick:()=>u&&u(D),children:g("popup-blocked")})]})}function GE({state:e}){if(!e)return null;const t=g(`dot-${e}`);return c.jsx("span",{className:`nc-deck-dot ${e}`,role:"img","aria-label":t,title:t})}var ms={},Yu,Iv;function XE(){return Iv||(Iv=1,Yu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Yu}var Gu={},rr={},Bv;function $r(){if(Bv)return rr;Bv=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return rr.getSymbolSize=function(s){if(!s)throw new Error('"version" cannot be null or undefined');if(s<1||s>40)throw new Error('"version" should be in range from 1 to 40');return s*4+17},rr.getSymbolTotalCodewords=function(s){return t[s]},rr.getBCHDigit=function(n){let s=0;for(;n!==0;)s++,n>>>=1;return s},rr.setToSJISFunction=function(s){if(typeof s!="function")throw new Error('"toSJISFunc" is not a valid function.');e=s},rr.isKanjiModeEnabled=function(){return typeof e<"u"},rr.toSJIS=function(s){return e(s)},rr}var Xu={},Ov;function nf(){return Ov||(Ov=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(s){return s&&typeof s.bit<"u"&&s.bit>=0&&s.bit<4},e.from=function(s,o){if(e.isValid(s))return s;try{return t(s)}catch{return o}}})(Xu)),Xu}var Ju,zv;function JE(){if(zv)return Ju;zv=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const n=Math.floor(t/8);return(this.buffer[n]>>>7-t%8&1)===1},put:function(t,n){for(let s=0;s<n;s++)this.putBit((t>>>n-s-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),t&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Ju=e,Ju}var Qu,Fv;function QE(){if(Fv)return Qu;Fv=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,n,s,o){const a=t*this.size+n;this.data[a]=s,o&&(this.reservedBit[a]=!0)},e.prototype.get=function(t,n){return this.data[t*this.size+n]},e.prototype.xor=function(t,n,s){this.data[t*this.size+n]^=s},e.prototype.isReserved=function(t,n){return this.reservedBit[t*this.size+n]},Qu=e,Qu}var Zu={},$v;function ZE(){return $v||($v=1,(function(e){const t=$r().getSymbolSize;e.getRowColCoords=function(s){if(s===1)return[];const o=Math.floor(s/7)+2,a=t(s),u=a===145?26:Math.ceil((a-13)/(2*o-2))*2,h=[a-7];for(let p=1;p<o-1;p++)h[p]=h[p-1]-u;return h.push(6),h.reverse()},e.getPositions=function(s){const o=[],a=e.getRowColCoords(s),u=a.length;for(let h=0;h<u;h++)for(let p=0;p<u;p++)h===0&&p===0||h===0&&p===u-1||h===u-1&&p===0||o.push([a[h],a[p]]);return o}})(Zu)),Zu}var ed={},Hv;function e2(){if(Hv)return ed;Hv=1;const e=$r().getSymbolSize,t=7;return ed.getPositions=function(s){const o=e(s);return[[0,0],[o-t,0],[0,o-t]]},ed}var td={},Wv;function t2(){return Wv||(Wv=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const a=o.size;let u=0,h=0,p=0,f=null,_=null;for(let b=0;b<a;b++){h=p=0,f=_=null;for(let y=0;y<a;y++){let w=o.get(b,y);w===f?h++:(h>=5&&(u+=t.N1+(h-5)),f=w,h=1),w=o.get(y,b),w===_?p++:(p>=5&&(u+=t.N1+(p-5)),_=w,p=1)}h>=5&&(u+=t.N1+(h-5)),p>=5&&(u+=t.N1+(p-5))}return u},e.getPenaltyN2=function(o){const a=o.size;let u=0;for(let h=0;h<a-1;h++)for(let p=0;p<a-1;p++){const f=o.get(h,p)+o.get(h,p+1)+o.get(h+1,p)+o.get(h+1,p+1);(f===4||f===0)&&u++}return u*t.N2},e.getPenaltyN3=function(o){const a=o.size;let u=0,h=0,p=0;for(let f=0;f<a;f++){h=p=0;for(let _=0;_<a;_++)h=h<<1&2047|o.get(f,_),_>=10&&(h===1488||h===93)&&u++,p=p<<1&2047|o.get(_,f),_>=10&&(p===1488||p===93)&&u++}return u*t.N3},e.getPenaltyN4=function(o){let a=0;const u=o.data.length;for(let p=0;p<u;p++)a+=o.data[p];return Math.abs(Math.ceil(a*100/u/5)-10)*t.N4};function n(s,o,a){switch(s){case e.Patterns.PATTERN000:return(o+a)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return a%3===0;case e.Patterns.PATTERN011:return(o+a)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(a/3))%2===0;case e.Patterns.PATTERN101:return o*a%2+o*a%3===0;case e.Patterns.PATTERN110:return(o*a%2+o*a%3)%2===0;case e.Patterns.PATTERN111:return(o*a%3+(o+a)%2)%2===0;default:throw new Error("bad maskPattern:"+s)}}e.applyMask=function(o,a){const u=a.size;for(let h=0;h<u;h++)for(let p=0;p<u;p++)a.isReserved(p,h)||a.xor(p,h,n(o,p,h))},e.getBestMask=function(o,a){const u=Object.keys(e.Patterns).length;let h=0,p=1/0;for(let f=0;f<u;f++){a(f),e.applyMask(f,o);const _=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(f,o),_<p&&(p=_,h=f)}return h}})(td)),td}var sl={},Uv;function kw(){if(Uv)return sl;Uv=1;const e=nf(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return sl.getBlocksCount=function(o,a){switch(a){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},sl.getTotalCodewordsCount=function(o,a){switch(a){case e.L:return n[(o-1)*4+0];case e.M:return n[(o-1)*4+1];case e.Q:return n[(o-1)*4+2];case e.H:return n[(o-1)*4+3];default:return}},sl}var nd={},yo={},Kv;function n2(){if(Kv)return yo;Kv=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let s=1;for(let o=0;o<255;o++)e[o]=s,t[s]=o,s<<=1,s&256&&(s^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),yo.log=function(s){if(s<1)throw new Error("log("+s+")");return t[s]},yo.exp=function(s){return e[s]},yo.mul=function(s,o){return s===0||o===0?0:e[t[s]+t[o]]},yo}var qv;function i2(){return qv||(qv=1,(function(e){const t=n2();e.mul=function(s,o){const a=new Uint8Array(s.length+o.length-1);for(let u=0;u<s.length;u++)for(let h=0;h<o.length;h++)a[u+h]^=t.mul(s[u],o[h]);return a},e.mod=function(s,o){let a=new Uint8Array(s);for(;a.length-o.length>=0;){const u=a[0];for(let p=0;p<o.length;p++)a[p]^=t.mul(o[p],u);let h=0;for(;h<a.length&&a[h]===0;)h++;a=a.slice(h)}return a},e.generateECPolynomial=function(s){let o=new Uint8Array([1]);for(let a=0;a<s;a++)o=e.mul(o,new Uint8Array([1,t.exp(a)]));return o}})(nd)),nd}var id,Vv;function r2(){if(Vv)return id;Vv=1;const e=i2();function t(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(s){this.degree=s,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(s){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(s.length+this.degree);o.set(s);const a=e.mod(o,this.genPoly),u=this.degree-a.length;if(u>0){const h=new Uint8Array(this.degree);return h.set(a,u),h}return a},id=t,id}var rd={},sd={},od={},Yv;function xw(){return Yv||(Yv=1,od.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),od}var fi={},Gv;function Cw(){if(Gv)return fi;Gv=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const s="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
81
+ `),()=>P.dispose()}k.current={term:P,fit:M,sock:ae,setKeyboardGesture:B};let ue=null;const ge=P.onData(ve=>{if(s){ue&&(ue.ok=!1);return}if(!ue&&f&&f.current&&ve.length===1){const ot=ve.charCodeAt(0);let ht=ot;ot>=97&&ot<=122?ht=ot-96:ot>=64&&ot<=95?ht=ot-64:ot===32&&(ht=0),ve=String.fromCharCode(ht),f.current=!1,_&&_(!1)}const Ye=ae.sendInput(ve);ue&&(ue.seen=!0,ue.ok=ue.ok&&Ye)});u&&(u.current=ve=>ae.sendInput(ve)),p&&(p.current=ve=>ae.action(ve)),h&&(h.current=jC({isReady:()=>!s&&ae.isReady(),paste:ve=>{const Ye={seen:!1,ok:!0};ue=Ye;try{P.paste(ve)}catch{Ye.ok=!1}finally{ue=null}return Ye.seen&&Ye.ok},send:ve=>ae.sendInput(ve)}));const Z=P.onSelectionChange(()=>D(P.getSelection()));P.attachCustomKeyEventHandler(ve=>(ve.ctrlKey||ve.metaKey)&&ve.key.toLowerCase()==="c"&&P.getSelection()?(ve.type==="keydown"&&hv(P.getSelection()),!1):!0);const q=C.current;let fe=!1;const Ie=async ve=>{if(!ve.length||fe)return;if(s){K({error:g("settings-readonly")});return}fe=!0,K({current:0,total:ve.length,name:""});const Ye=await Ky({files:ve,token:n,session:e,node:t,paste:!0,onProgress:({index:ot,total:ht,name:mn,state:Pn,error:Ai})=>K({current:ot+1,total:ht,name:mn,...Pn==="error"?{error:Ai}:{}})});fe=!1,Ye.errors.length?K({error:Ye.errors.map(ot=>`${ot.name}: ${ot.message}`).join(" · ")}):(K({done:!0,total:Ye.paths.length}),setTimeout(()=>K(null),1600))},et=ve=>{const Ye=ve.clipboardData;if(!Hu(Ye))return;const ot=pv(Ye);ot.length&&(ve.preventDefault(),ve.stopPropagation(),Ie(ot))},ze=ve=>{Hu(ve.dataTransfer)&&(ve.preventDefault(),ve.stopPropagation())},Fe=ve=>{Hu(ve.dataTransfer)&&(ve.preventDefault(),ve.stopPropagation(),Ie(pv(ve.dataTransfer)))};q.addEventListener("paste",et,!0),q.addEventListener("dragenter",ze,!0),q.addEventListener("dragover",ze,!0),q.addEventListener("drop",Fe,!0);const Ct=24,Ge=(ve,Ye={mode:null,remainder:0},ot=null)=>{const ht=C.current,mn=ht?ht.getBoundingClientRect().height:Ct,Pn=ot||KC({alternateScreen:P.buffer.active.type==="alternate",readonly:s}),Ai=Ye.mode===Pn?Ye.remainder+ve:ve,$o=VC({mode:Pn,accumulated:Ai,threshold:Pn==="page"?mn:Ct});for(const Jn of YC($o))Jn.kind==="input"?ae.sendInput(Jn.seq):ae.action(Jn.name);return{mode:Pn,remainder:$o.remainder}};let rt=null,ut=null,ct=null,vt=null,it=!1,lt=!1,mt={mode:null,remainder:0},le=null,be=null,Be=null,$e=!1;const he=()=>{Be&&clearTimeout(Be),Be=null},V=(ve,Ye)=>{const ht=(q.querySelector(".xterm-screen")||q).getBoundingClientRect(),mn=Math.max(0,Math.min(P.cols-1,Math.floor((ve-ht.left)/Math.max(1,ht.width)*P.cols))),Pn=Math.max(0,Math.min(P.rows-1,Math.floor((Ye-ht.top)/Math.max(1,ht.height)*P.rows)));return{col:mn,row:P.buffer.active.viewportY+Pn}},ne=ve=>V(ve.clientX,ve.clientY),z=ve=>{if(he(),$e=!1,it=!1,lt||ve.touches.length!==1){lt=!0,it=!0,T=null,rt=null,ut=null,ct=null,vt=null;return}if(A.current){ve.preventDefault(),ve.stopPropagation(),be=ne(ve.touches[0]),P.clearSelection();return}rt=ve.touches[0].clientY,ut=ve.touches[0].clientX,ct=ut,vt=rt,mt={mode:null,remainder:0},le=null;const Ye={x:ut,y:rt};Be=setTimeout(()=>{Be=null,$e=!0,it=!0,T=null,A.current=!0,S==null||S(!0),be=V(Ye.x,Ye.y),P.clearSelection(),P.select(be.col,be.row,1),rt=null,ut=null,le=null,mt={mode:null,remainder:0}},TC)},se=ve=>{if((A.current||$e)&&be&&ve.touches.length===1){ve.preventDefault(),ve.stopPropagation();const ht=ne(ve.touches[0]),mn=be.row*P.cols+be.col,Pn=ht.row*P.cols+ht.col,Ai=mn<=Pn?be:ht;P.select(Ai.col,Ai.row,Math.abs(Pn-mn)+1);return}if(rt===null||ve.touches.length!==1)return;ve.preventDefault(),ve.stopPropagation();const Ye=ve.touches[0];if(MC(ct,vt,Ye.clientX,Ye.clientY)&&(it=!0,T=null,Be&&he()),le===null&&(Math.abs(Ye.clientY-rt)>8||Math.abs(Ye.clientX-ut)>8)&&(le=Math.abs(Ye.clientY-rt)>Math.abs(Ye.clientX-ut)),!le)return;const ot=Ye.clientY-rt;rt=Ye.clientY,mt=Ge(ot,mt,"scroll")},me=()=>{he(),rt=null,ut=null,ct=null,vt=null,be=null,$e=!1,it=!1,lt=!1,mt={mode:null,remainder:0}},ke=ve=>{if(lt){T=null,he(),(!ve.touches||ve.touches.length===0)&&me();return}const Ye=ve.changedTouches&&ve.changedTouches[0];if(!it&&!$e&&!A.current&&Ye){const ot={at:Date.now(),x:Ye.clientX,y:Ye.clientY},ht=$C(G.current,T,ot);T=ht.next,ht.open&&L()}me()},Ne=()=>{T=null,me()};let we={mode:null,remainder:0};const Re=ve=>{ve.preventDefault(),ve.stopPropagation(),we=Ge(-ve.deltaY,we,ve.shiftKey?null:"scroll")};q.addEventListener("touchstart",z,{passive:!1}),q.addEventListener("touchmove",se,{passive:!1,capture:!0}),q.addEventListener("touchend",ke,{passive:!0}),q.addEventListener("touchcancel",Ne,{passive:!0});const Je=()=>{!A.current&&G.current==="double-tap"&&L()};q.addEventListener("dblclick",Je);const Tt=ve=>{(A.current||$e)&&(ve.preventDefault(),ve.stopPropagation())};q.addEventListener("contextmenu",Tt,!0),q.addEventListener("wheel",Re,{passive:!1,capture:!0});let Me=null;const pn=ve=>{LC(ve)&&(ve.preventDefault(),ve.stopPropagation(),Me=V(ve.clientX,ve.clientY),P.clearSelection())},bt=ve=>{if(!Me)return;ve.preventDefault(),ve.stopPropagation();const Ye=V(ve.clientX,ve.clientY),ot=Me.row*P.cols+Me.col,ht=Ye.row*P.cols+Ye.col,mn=ot<=ht?Me:Ye;P.select(mn.col,mn.row,Math.abs(ht-ot)+1)},Ke=ve=>{Me&&(ve.stopPropagation(),Me=null)};q.addEventListener("mousedown",pn,!0),q.addEventListener("mousemove",bt,!0),q.addEventListener("mouseup",Ke,!0);const $t=ve=>{!DC(ve)||!(k.current&&k.current.term&&k.current.term.getSelection())||(ve.preventDefault(),ve.stopPropagation(),j.current&&j.current())};q.addEventListener("keydown",$t,!0);const de=()=>{M.fit(),ae.resize(P.cols,P.rows)};window.addEventListener("resize",de);const Ee=window.visualViewport;let Ue=Ee&&Number(Ee.height);const _t=()=>{const ve=Ee&&Number(Ee.height);te&&G.current==="double-tap"&&Number.isFinite(Ue)&&Number.isFinite(ve)&&ve>Ue+80&&ie(),Ue=ve,de()};Ee&&(Ee.addEventListener("resize",_t),Ee.addEventListener("scroll",de));const dt=typeof navigator<"u"?navigator.virtualKeyboard:null,Ti=()=>{var ve;te&&G.current==="double-tap"&&Number(((ve=dt==null?void 0:dt.boundingRect)==null?void 0:ve.height)||0)===0&&ie()};(Mi=dt==null?void 0:dt.addEventListener)==null||Mi.call(dt,"geometrychange",Ti);let Vt=null,Xn=0;return typeof ResizeObserver<"u"&&(Vt=new ResizeObserver(()=>{Xn&&cancelAnimationFrame(Xn),Xn=requestAnimationFrame(de)}),Vt.observe(q)),()=>{var ve;k.current=null,u&&(u.current=()=>!1),h&&(h.current=()=>!1),p&&(p.current=()=>!1),ge.dispose(),Z.dispose(),q.removeEventListener("touchstart",z),q.removeEventListener("touchmove",se,{capture:!0}),q.removeEventListener("touchend",ke),q.removeEventListener("touchcancel",Ne),q.removeEventListener("dblclick",Je),q.removeEventListener("contextmenu",Tt,!0),he(),q.removeEventListener("wheel",Re,{capture:!0}),q.removeEventListener("mousedown",pn,!0),q.removeEventListener("mousemove",bt,!0),q.removeEventListener("mouseup",Ke,!0),q.removeEventListener("keydown",$t,!0),q.removeEventListener("paste",et,!0),q.removeEventListener("dragenter",ze,!0),q.removeEventListener("dragover",ze,!0),q.removeEventListener("drop",Fe,!0),window.removeEventListener("resize",de),Ee&&(Ee.removeEventListener("resize",_t),Ee.removeEventListener("scroll",de)),(ve=dt==null?void 0:dt.removeEventListener)==null||ve.call(dt,"geometrychange",Ti),$==null||$.removeEventListener("blur",X),Vt&&Vt.disconnect(),Xn&&cancelAnimationFrame(Xn),ae.close(),P.dispose()}},[e,t,n,s,o,u,h,p,f,_,b]),c.jsxs("div",{className:`nc-terminal${w?" selecting":""}`,children:[c.jsx("div",{className:"nc-terminal-host",ref:C}),ee&&c.jsx("div",{className:`nc-upload-state${ee.error?" error":""}`,role:"status",children:ee.error?ee.error:ee.done?g("attach-uploaded").replace("{n}",String(ee.total||0)):g("attach-upload-progress").replace("{n}",String(ee.current||0)).replace("{total}",String(ee.total||0))}),(F||w)&&c.jsxs("div",{className:"nc-selection-tools",children:[F?c.jsx("button",{type:"button",onClick:O,children:J||g("copy")}):c.jsx("span",{children:g("select-drag")}),c.jsx("button",{type:"button",onClick:()=>{var P,M;(M=(P=k.current)==null?void 0:P.term)==null||M.clearSelection(),D(""),S==null||S(!1)},children:g("cancel")}),J===g("copy-manual")&&c.jsx("textarea",{readOnly:!0,value:F,onFocus:P=>P.target.select()})]})]})}const gv="",Ot="\x1B",GC=[{label:"↑",seq:Ot+"[A"},{label:"↓",seq:Ot+"[B"},{label:"PGUP",seq:Ot+"[5~"},{label:"PGDN",seq:Ot+"[6~"}];function XC({send:e,action:t,ctrlArmed:n=!1,onCtrl:s,onKeyboard:o,selectionMode:a=!1,onSelectionMode:u,keepKeyboardClosed:h=!0,showEnter:p=!0,keybarLayout:f="full"}){const[_,b]=N.useState(!1),[y,w]=N.useState(!1),[S,x]=N.useState(!1),[C,k]=N.useState(!1),R=f==="compact"&&!C;N.useEffect(()=>{f!=="compact"&&k(!1)},[f]);const I=O=>{S?(e(Ot+O),x(!1)):e(O)},A=O=>{h&&lh(),O()},G=O=>({onPointerDown:j=>{j.preventDefault(),A(O)},onClick:j=>{j.detail===0&&A(O)}}),F=(O,j,P)=>c.jsx("button",{type:"button",...G(()=>{I(j),P&&P()}),children:O},O),D=(O,j)=>c.jsx("button",{type:"button",...G(()=>{t(j),w(!1)}),children:O},O),J=p&&c.jsx("button",{type:"button",className:"nc-enter-key","aria-label":"ENTER",title:"ENTER",...G(()=>I("\r")),children:c.jsx(nt,{name:"enter",size:24})}),W=y&&c.jsxs("div",{className:"nc-keymenu",children:[D("←WIN","prev-window"),D("WIN→","next-window"),D("⬅PANE","pane-left"),D("PANE➡","pane-right"),F("SCROLL",gv+"[",()=>{b(!0),w(!1)}),c.jsx("button",{type:"button",className:a?"armed":"",...G(()=>{u==null||u(!a),w(!1)}),children:"SELECT"}),F("⌃C","",()=>w(!1)),F("DETACH",gv+"d",()=>w(!1))]});if(_)return c.jsxs("div",{className:"nc-keybar copy",children:[c.jsx("span",{className:"tag",children:"copy-mode"}),GC.map(O=>F(O.label,O.seq)),F("ESCI (q)","q",()=>b(!1))]});if(R)return c.jsxs("div",{className:"nc-keybar termux",children:[W,c.jsxs("div",{className:`nc-keygrid compact${p?"":" no-enter"}`,children:[c.jsx("div",{className:"nc-keyrows",children:c.jsxs("div",{className:"row",children:[c.jsx("button",{type:"button","aria-label":"expand keybar",title:"expand",...G(()=>k(!0)),children:c.jsx(nt,{name:"chevronUp",size:20})},"expand"),c.jsx("button",{type:"button",...G(()=>{o&&o()}),children:"⌨"},"kbd"),c.jsx("button",{type:"button",className:y?"armed":"",...G(()=>w(O=>!O)),children:"☰"},"menu"),F("↑",Ot+"[A"),F("↓",Ot+"[B"),F("←",Ot+"[D"),F("→",Ot+"[C"),F("PGUP",Ot+"[5~"),F("PGDN",Ot+"[6~")]})}),J]})]});const ee=f==="compact"&&C,K=ee&&c.jsx("button",{type:"button",className:"nc-retract-key","aria-label":"retract keybar",title:"retract",...G(()=>k(!1)),children:c.jsx(nt,{name:"chevronDown",size:20})});return c.jsxs("div",{className:`nc-keybar termux${ee?" expanded":""}`,children:[W,c.jsxs("div",{className:`nc-keygrid${p?"":" no-enter"}${ee?" expanded":""}`,children:[K,c.jsxs("div",{className:"nc-keyrows",children:[c.jsxs("div",{className:"row",children:[F("ESC",Ot),c.jsx("button",{type:"button",className:y?"armed":"",...G(()=>w(O=>!O)),children:"☰"},"menu"),F("/","/"),F("—","-"),F("HOME",Ot+"[H"),F("↑",Ot+"[A"),F("END",Ot+"[F"),F("PGUP",Ot+"[5~")]}),c.jsxs("div",{className:"row",children:[F("⇥"," "),c.jsx("button",{type:"button",...G(()=>{o&&o()}),children:"⌨"},"kbd"),c.jsx("button",{type:"button",className:n?"armed":"",...G(()=>{s&&s()}),children:"CTRL"},"ctrl"),c.jsx("button",{type:"button",className:S?"armed":"",...G(()=>x(O=>!O)),children:"ALT"},"alt"),F("←",Ot+"[D"),F("↓",Ot+"[B"),F("→",Ot+"[C"),F("PGDN",Ot+"[6~")]})]}),J]})]})}const JC=e=>e>1048576?`${(e/1048576).toFixed(1)}M`:e>1024?`${(e/1024).toFixed(0)}K`:`${e}B`;function Gy({session:e,node:t,token:n,filesEvent:s,onClose:o}){zn();const a=t?`/api/route/${String(t).split("/").map(encodeURIComponent).join("/")}/_`:"/api",u=t?`${t}:${e}`:e,[h,p]=N.useState("outbox"),[f,_]=N.useState({inbox:[],outbox:[]}),[b,y]=N.useState(""),w=N.useRef(null);async function S(){try{const I=await(await tn(`${a}/files?session=${encodeURIComponent(e)}`,n)).json();if(I.error){y(I.error);return}_(I);const A=I.outbox[0]?I.outbox[0].mtime:0;localStorage.setItem(R_(u),String(A))}catch(R){y(String(R))}}N.useEffect(()=>{S()},[e,t]),N.useEffect(()=>{s&&s.session===e&&S()},[s]);async function x(R){for(const I of R){y(`carico ${I.name}…`);const A=new FormData;A.append("session",e),A.append("file",I);try{const F=await(await tn(`${a}/files/upload`,n,{method:"POST",body:A})).json();y(F.error?`errore: ${F.error}`:"")}catch(G){y(String(G))}}S()}async function C(R){const I=await tn(`${a}/files/download?session=${encodeURIComponent(e)}&box=${h}&name=${encodeURIComponent(R)}`,n);if(!I.ok){y("errore download");return}const A=await I.blob(),G=URL.createObjectURL(A),F=document.createElement("a");F.href=G,F.download=R,F.click(),URL.revokeObjectURL(G)}async function k(R){await tn(`${a}/files?session=${encodeURIComponent(e)}&box=${h}&name=${encodeURIComponent(R)}`,n,{method:"DELETE"}),S()}return c.jsxs("div",{className:"nc-files",children:[c.jsxs("header",{children:[c.jsx("b",{children:t?`${t}:${e}`:e}),c.jsx("button",{onClick:o,title:g("close"),children:c.jsx(nt,{name:"x",size:20})})]}),c.jsxs("nav",{children:[c.jsx("button",{className:h==="outbox"?"on":"",onClick:()=>p("outbox"),children:"outbox"}),c.jsx("button",{className:h==="inbox"?"on":"",onClick:()=>p("inbox"),children:"inbox"}),c.jsxs("button",{className:"up",onClick:()=>w.current&&w.current.click(),children:[c.jsx(nt,{name:"upload",size:18})," ",g("upload")]}),c.jsx("input",{type:"file",multiple:!0,ref:w,style:{display:"none"},onChange:R=>{x(Array.from(R.target.files||[])),R.target.value=""}})]}),b&&c.jsx("div",{className:"nc-busy",children:b}),c.jsxs("ul",{children:[f[h].map(R=>c.jsxs("li",{children:[c.jsx("span",{className:"name",onClick:()=>C(R.name),children:R.name}),c.jsx("small",{children:JC(R.size)}),c.jsx("button",{onClick:()=>k(R.name),title:"elimina",children:c.jsx(nt,{name:"trash",size:18})})]},R.name)),f[h].length===0&&c.jsx("li",{className:"empty",children:g("empty-files")})]})]})}const Ol="nc_composer_v1",ch="nc-composer-reset",QC=50,Xy=256*1024,Jy=512*1024,ZC=768*1024,vv=2*1024*1024,Qy=720*60*60*1e3,uh=1;function Zy(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:0}function Uh(e){if(e!==void 0)return e;try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function jl(){return{version:uh,cells:{}}}function ew(e){const t=[];for(const s of Array.isArray(e)?e:[]){const o=typeof s=="string"?s:s&&s.text,a=Zy(typeof s=="string"?0:s&&s.at);if(!(typeof o!="string"||!o||o.length>Xy)&&!(t.length&&t[t.length-1].text===o)&&(t.push({text:o,at:a}),t.length>=QC))break}let n=0;return t.filter(s=>n+s.text.length>ZC?!1:(n+=s.text.length,!0))}function Ll(e){if(!e||typeof e!="object")return null;const t=typeof e.draft=="string"&&e.draft.length<=Jy?e.draft:"",n=ew(e.history),s=Zy(e.updatedAt),o=e.expanded===!0;return!t&&!n.length&&!o?null:{draft:t,history:n,expanded:o,updatedAt:s}}function eE(e){let t;try{t=typeof e=="string"?JSON.parse(e):e}catch{return jl()}if(!t||typeof t!="object"||t.version!==uh||!t.cells||typeof t.cells!="object")return jl();const n=Object.create(null);for(const[s,o]of Object.entries(t.cells)){if(!s||typeof s!="string"||s.length>512||s==="__proto__"||s==="constructor"||s==="prototype")continue;const a=Ll(o);a&&(n[s]=a)}return{version:uh,cells:n}}function tw(e){const t=Uh(e);if(!t)return jl();try{return eE(t.getItem(Ol))}catch{return jl()}}function _v(e){try{return JSON.stringify(e).length}catch{return 1/0}}function tE(e,t,n){for(const[s,o]of Object.entries(e.cells))s!==n&&o.updatedAt>0&&t-o.updatedAt>Qy&&delete e.cells[s]}function nw(e,t){return Object.entries(e.cells).filter(([n])=>n!==t).sort((n,s)=>n[1].updatedAt-s[1].updatedAt).map(([n])=>n)}function nE(e,t){for(;_v(e)>vv;){const n=Object.entries(e.cells).filter(([,s])=>s.history.length).sort((s,o)=>s[1].updatedAt-o[1].updatedAt);if(!n.length)break;n[0][1].history.pop()}for(const n of nw(e,t)){if(_v(e)<=vv)break;delete e.cells[n]}}function iw(e,t,n){const s=Uh(e);if(!s)return!1;nE(t,n);const o=()=>(s.setItem(Ol,JSON.stringify(t)),!0);try{return o()}catch{for(const u of nw(t,n)){delete t.cells[u];try{return o()}catch{}}return!1}}function zo(e,t,n,s){const o=tw(t);tE(o,n,e);const a=Ll(o.cells[e])||{draft:"",history:[],expanded:!1,updatedAt:0},u=s({...a,history:[...a.history]}),h=Ll(u);return h?o.cells[e]={...h,updatedAt:n}:delete o.cells[e],{ok:iw(t,o,e),cell:o.cells[e]||{draft:"",history:[],expanded:!1,updatedAt:n}}}function iE({ownerId:e,node:t,session:n}){const s=String(n||"");if(!s)return"";const o=Ss.test(String(e||""))?String(e):t?`route:${String(t)}`:"local";return`${encodeURIComponent(o)}:${encodeURIComponent(s)}`}function _o(e,t,n=Date.now()){if(!e)return{draft:"",history:[],expanded:!1,updatedAt:0};const s=tw(t),o=Ll(s.cells[e]);return!o||o.updatedAt>0&&n-o.updatedAt>Qy?(s.cells[e]&&(delete s.cells[e],iw(t,s,"")),{draft:"",history:[],expanded:!1,updatedAt:0}):{...o,history:[...o.history]}}function yv(e,t,n,s=Date.now()){const o=String(t||"");return!e||o.length>Jy?!1:zo(e,n,s,a=>({...a,draft:o})).ok}function wv(e,t,n=Date.now()){return e?zo(e,t,n,s=>({...s,draft:""})).ok:!1}function rE(e,t,n,s=Date.now()){return e?zo(e,n,s,o=>({...o,expanded:!!t})).ok:!1}function sE(e,t,n,s=Date.now()){const o=String(t||"");return!e||!o||o.length>Xy?!1:zo(e,n,s,a=>{const u=a.history.filter(h=>h.text!==o);return u.unshift({text:o,at:s}),{...a,history:ew(u)}}).ok}function oE(e,t,n=Date.now()){return e?zo(e,t,n,s=>({...s,history:[]})).ok:!1}function aE(e){const t=Uh(e);if(!t)return!1;try{return t.removeItem(Ol),!0}catch{return!1}}const lE=300;function cE(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function uE({ownerId:e,node:t,session:n,storage:s=cE()}){const o=N.useMemo(()=>iE({ownerId:e,node:t,session:n}),[e,t,n]),a=N.useMemo(()=>_o(o,s),[]),[u,h]=N.useState(a.draft),[p,f]=N.useState(a.expanded),[_,b]=N.useState(a.history),[y,w]=N.useState(-1),S=N.useRef(o),x=N.useRef(a.draft),C=N.useRef(null),k=N.useRef(a.updatedAt||0),R=N.useRef(a.draft),I=N.useCallback(()=>{C.current&&clearTimeout(C.current),C.current=null},[]),A=N.useCallback(()=>{I(),yv(S.current,x.current,s)},[I,s]),G=N.useCallback(()=>{I(),C.current=setTimeout(()=>{C.current=null,yv(S.current,x.current,s)},lE)},[I,s]),F=N.useCallback(P=>{const M=String(typeof P=="function"?P(x.current):P||"");x.current=M,k.current=Date.now(),R.current=M,w(-1),h(M),G()},[G]),D=N.useCallback((P,M)=>{I(),x.current=P,k.current=Date.now(),h(P),w(M),G()},[I,G]),J=N.useCallback(()=>{if(!_.length)return!1;const P=Math.min(y+1,_.length-1);return y<0&&(R.current=x.current),D(_[P].text,P),!0},[D,_,y]),W=N.useCallback(()=>{if(y<0)return!1;const P=y-1;return D(P<0?R.current:_[P].text,P),!0},[D,_,y]),ee=N.useCallback(P=>{R.current=x.current;const M=_.findIndex(H=>H.text===P);D(String(P||""),M)},[D,_]),K=N.useCallback(()=>{f(P=>{const M=!P;return rE(S.current,M,s),M})},[s]),O=N.useCallback((P,M,H)=>{if(!P)return;if(sE(P,H,s),!(S.current===P)){_o(P,s).draft===M&&wv(P,s);return}b(_o(P,s).history),R.current="",w(-1),x.current===M?(I(),x.current="",k.current=Date.now(),h(""),wv(P,s)):G()},[I,G,s]),j=N.useCallback(()=>{oE(S.current,s),b([]),w(-1),R.current=x.current},[s]);return N.useEffect(()=>{if(S.current===o)return;A(),S.current=o;const P=_o(o,s);x.current=P.draft,k.current=P.updatedAt||0,R.current=P.draft,h(P.draft),f(P.expanded),b(P.history),w(-1)},[o,A,s]),N.useEffect(()=>{const P=()=>A(),M=()=>{document.visibilityState==="hidden"&&A()};return window.addEventListener("pagehide",P),document.addEventListener("visibilitychange",M),()=>{window.removeEventListener("pagehide",P),document.removeEventListener("visibilitychange",M),A()}},[A]),N.useEffect(()=>{const P=()=>{I(),x.current="",k.current=0,R.current="",h(""),f(!1),b([]),w(-1)},M=te=>{if(te.key!==Ol)return;if(te.newValue==null){P();return}const T=_o(S.current,s);T.updatedAt<k.current||(I(),x.current=T.draft,k.current=T.updatedAt,R.current=T.draft,h(T.draft),f(T.expanded),b(T.history),w(-1))},H=()=>P();return window.addEventListener("storage",M),window.addEventListener(ch,H),()=>{window.removeEventListener("storage",M),window.removeEventListener(ch,H)}},[I,s]),{cellKey:o,text:u,setText:F,expanded:p,toggleExpanded:K,history:_,historyCursor:y,recallPrevious:J,recallNext:W,selectHistory:ee,confirmSubmitted:O,clearHistory:j,flush:A}}function rw({submitText:e,token:t,session:n,node:s,ownerId:o,keepKeyboardClosedOnVoice:a=!0}){zn();const u=s?`/api/route/${String(s).split("/").map(encodeURIComponent).join("/")}/_`:"/api",{cellKey:h,text:p,setText:f,expanded:_,toggleExpanded:b,history:y,historyCursor:w,recallPrevious:S,recallNext:x,selectHistory:C,confirmSubmitted:k,clearHistory:R,flush:I}=uE({ownerId:o,node:s,session:n}),[A,G]=N.useState(!1),[F,D]=N.useState(""),[J,W]=N.useState(!1),ee=N.useRef(null),K=N.useRef(null),O=N.useRef(null),[j,P]=N.useState(!1),[M,H]=N.useState({left:0,bottom:0}),[te,T]=N.useState(!1),[ie,B]=N.useState(!1),L=N.useRef(null),$=N.useRef(null),X=N.useRef(null),ae=N.useRef(null),ue=N.useRef(null),ge=N.useRef(null),Z=N.useRef(null),q=N.useRef(!1),[fe,Ie]=N.useState(!1),[et,ze]=N.useState({left:0,bottom:0,width:320}),Fe=N.useRef(`nc-attach-${Math.random().toString(36).slice(2,8)}`);N.useEffect(()=>{let he=!1;if(s){W(!1);return}return tn(`${u}/voice/status`,t).then(V=>V.json()).then(V=>{he||W(!!V.serverSttConfigured)}).catch(()=>{he||W(!1)}),()=>{he=!0}},[t,u]);const Ge=!!(typeof window<"u"&&(window.SpeechRecognition||window.webkitSpeechRecognition)||J);async function rt(){const he=O.current&&typeof O.current.value=="string"?O.current.value:p;lh(),he!==p&&f(he);const V=he,ne=PC(V);if(!ne||ie)return;B(!0),D("");let z=!1;try{z=!!await e(ne)}catch{z=!1}z?k(h,V,ne):D(g("composer-send-failed")),B(!1)}function ut(){const he=L.current&&L.current.getBoundingClientRect();he&&H({left:Math.max(6,Math.min(he.left,window.innerWidth-186)),bottom:window.innerHeight-he.top+6}),P(!0)}function ct(he){P(!1),he&&L.current&&L.current.focus()}function vt(){const he=X.current&&X.current.getBoundingClientRect();if(he){const V=Math.max(220,Math.min(360,window.innerWidth-12));ze({left:Math.max(6,Math.min(he.right-V,window.innerWidth-V-6)),bottom:window.innerHeight-he.top+6,width:V})}Ie(!0)}function it(he){Ie(!1),he&&X.current&&X.current.focus()}N.useEffect(()=>{if(!j)return;const he=ne=>{ne.key==="Escape"&&ct(!0)},V=ne=>{const z=$.current&&$.current.contains(ne.target),se=L.current&&L.current.contains(ne.target);!z&&!se&&ct(!1)};return document.addEventListener("keydown",he),document.addEventListener("pointerdown",V),()=>{document.removeEventListener("keydown",he),document.removeEventListener("pointerdown",V)}},[j]),N.useEffect(()=>{if(!fe)return;const he=ne=>{ne.key==="Escape"&&it(!0)},V=ne=>{const z=ae.current&&ae.current.contains(ne.target),se=X.current&&X.current.contains(ne.target);!z&&!se&&it(!1)};return document.addEventListener("keydown",he),document.addEventListener("pointerdown",V),()=>{document.removeEventListener("keydown",he),document.removeEventListener("pointerdown",V)}},[fe]);function lt(he){if(!(he.isComposing||q.current||he.altKey||he.ctrlKey||he.metaKey)){if(he.key==="ArrowUp"&&he.currentTarget.selectionStart===0&&he.currentTarget.selectionEnd===0){S()&&he.preventDefault();return}he.key==="ArrowDown"&&w>=0&&he.currentTarget.selectionStart===p.length&&he.currentTarget.selectionEnd===p.length&&x()&&he.preventDefault()}}function mt(he){ct(!1),he.current&&he.current.click()}async function le(he){if(!he.length||!n)return;T(!0),D("");const{paths:V,errors:ne}=await Ky({files:he,token:t,session:n,node:s,paste:!1});ne.length&&D(ne.map(z=>`${z.name}: ${z.message}`).join(" · ")),V.length&&f(z=>z+(z&&!z.endsWith(" ")?" ":"")+V.join(" ")),T(!1)}function be(){ee.current&&ee.current.stop(),K.current&&K.current.stop(),G(!1)}async function Be(){D("");const he=window.SpeechRecognition||window.webkitSpeechRecognition;if(he){const V=new he;V.lang="it-IT",V.continuous=!1,V.interimResults=!0;const ne=p?`${p} `:"";V.onresult=z=>{const se=Array.from(z.results).map(me=>me[0].transcript).join("");f(ne+se)},V.onend=()=>G(!1),V.onerror=z=>{D(`voice: ${z.error||"errore"}`),G(!1)},ee.current=V,V.start(),G(!0);return}try{const V=await navigator.mediaDevices.getUserMedia({audio:!0}),ne=new MediaRecorder(V),z=[];ne.ondataavailable=se=>z.push(se.data),ne.onstop=async()=>{V.getTracks().forEach(se=>se.stop()),G(!1),D("trascrivo…");try{const se=new Blob(z,{type:ne.mimeType||"audio/webm"}),ke=await(await tn(`${u}/voice/transcribe`,t,{method:"POST",headers:{"content-type":"application/octet-stream"},body:se})).json();ke.error?D(ke.error):(D(""),f(Ne=>Ne+(Ne?" ":"")+(ke.text||"")))}catch(se){D(String(se))}},K.current={stop:()=>ne.state!=="inactive"&&ne.stop()},ne.start(),G(!0)}catch{D("microfono non disponibile"),G(!1)}}function $e(){a&&lh(),A?be():Be()}return c.jsxs("div",{className:"nc-composer",children:[F&&c.jsx("div",{className:"nc-composer-err",children:F}),c.jsxs("div",{className:"nc-composer-row",children:[n&&c.jsx("button",{ref:L,className:te?"attach busy":"attach",disabled:te,onClick:()=>j?ct(!1):ut(),title:g(te?"attach-uploading":"attach"),"aria-label":g("attach"),"aria-haspopup":"menu","aria-expanded":j,"aria-controls":Fe.current,children:c.jsx(nt,{name:"attach",size:22})}),j&&c.jsxs("div",{ref:$,id:Fe.current,role:"menu",className:"nc-attach-menu",style:{left:M.left,bottom:M.bottom},children:[c.jsxs("button",{role:"menuitem",onClick:()=>mt(ue),children:[c.jsx(nt,{name:"file",size:18})," ",g("attach-file")]}),c.jsxs("button",{role:"menuitem",onClick:()=>mt(ge),children:[c.jsx(nt,{name:"camera",size:18})," ",g("attach-camera")]}),c.jsxs("button",{role:"menuitem",onClick:()=>mt(Z),children:[c.jsx(nt,{name:"image",size:18})," ",g("attach-gallery")]})]}),c.jsx("button",{ref:X,type:"button",className:"history",onPointerDown:he=>he.preventDefault(),onClick:()=>fe?it(!1):vt(),title:g("composer-history-tools"),"aria-label":g("composer-history-tools"),"aria-haspopup":"menu","aria-expanded":fe,children:c.jsx(nt,{name:"history",size:21})}),fe&&c.jsxs("div",{ref:ae,role:"menu",className:"nc-composer-history-menu",style:{left:et.left,bottom:et.bottom,width:et.width},children:[c.jsxs("button",{role:"menuitem",className:"nc-composer-history-action",onPointerDown:he=>he.preventDefault(),onClick:()=>{b(),it(!1)},children:[c.jsx(nt,{name:_?"chevronDown":"chevronUp",size:18}),g(_?"composer-collapse":"composer-expand")]}),c.jsx("div",{className:"nc-composer-history-title",children:g("composer-history")}),y.length===0&&c.jsx("div",{className:"nc-composer-history-empty",children:g("composer-history-empty")}),y.map((he,V)=>c.jsxs("button",{type:"button",role:"menuitem",className:"nc-composer-history-entry",onPointerDown:ne=>ne.preventDefault(),onClick:()=>{C(he.text),it(!1)},children:[c.jsx("span",{children:he.text.replace(/\s+/g," ").slice(0,180)}),he.at>0&&c.jsx("small",{children:new Date(he.at).toLocaleString()})]},`${he.at}:${V}`)),y.length>0&&c.jsx("button",{type:"button",role:"menuitem",className:"nc-composer-history-clear",onPointerDown:he=>he.preventDefault(),onClick:()=>{R(),it(!1)},children:g("composer-history-clear")})]}),c.jsx("input",{ref:ue,type:"file",multiple:!0,hidden:!0,onChange:he=>{le(Array.from(he.target.files||[])),he.target.value=""}}),c.jsx("input",{ref:ge,type:"file",accept:"image/*",capture:"environment",hidden:!0,onChange:he=>{le(Array.from(he.target.files||[])),he.target.value=""}}),c.jsx("input",{ref:Z,type:"file",accept:"image/*,video/*",multiple:!0,hidden:!0,onChange:he=>{le(Array.from(he.target.files||[])),he.target.value=""}}),c.jsx("textarea",{ref:O,className:_?"expanded":"",rows:_?8:2,value:p,placeholder:g("composer-placeholder"),onChange:he=>f(he.target.value),onKeyDown:lt,onCompositionStart:()=>{q.current=!0},onCompositionEnd:()=>{q.current=!1},onBlur:I}),Ge&&c.jsx("button",{type:"button",className:A?"mic on":"mic",title:g("voice"),"aria-label":g("voice"),onPointerDown:he=>{he.preventDefault(),$e()},onClick:he=>{he.detail===0&&$e()},children:c.jsx(nt,{name:"mic",size:22})}),c.jsx("button",{type:"button",className:"go",disabled:ie,onPointerDown:he=>he.preventDefault(),onClick:rt,title:g("send"),children:c.jsx(nt,{name:"enter",size:22})})]})]})}function Sv(e){return String(e||"?").replace(/^[^a-zA-Z0-9]+/,"").charAt(0).toUpperCase()||"?"}const dE=180,hE=480,ps=(e,t=[])=>`${t.length?t.join("/"):"local"}:${e}`;function fE({sessions:e=[],cells:t=[],activeSessions:n=[],nodeGroups:s=[],onPick:o,onAddTile:a,onPower:u,onBoot:h,onNodePower:p,onKill:f,onVisibility:_,onNew:b,onNodeRename:y,onSettings:w,onBootError:S,localNodeId:x,fleetCapabilities:C=[],bootSettlement:k=null,onBootSettlementApplied:R,width:I=240,collapsed:A=!1,onResize:G,onToggleCollapse:F}){const[D,J]=zn(),{pins:W,orders:ee,togglePin:K,viewFor:O,updateView:j,canMoveRoster:P,moveRoster:M,stepRoster:H}=W_(),{groupsFor:te,moveNode:T,stepNode:ie,nodeKey:B}=K_(),L=new Set((t||[]).map(V=>V.tmuxSession)),$=new Map((e||[]).map(V=>[V.name,V])),X=(V,ne)=>H0(W,V,ne),ae=W0,ue=[...t||[]].sort((V,ne)=>ae(X(V.tmuxSession,($.get(V.tmuxSession)||{}).activity),X(ne.tmuxSession,($.get(ne.tmuxSession)||{}).activity))),ge=(e||[]).filter(V=>!L.has(V.name)).sort((V,ne)=>ae(X(V.name,V.activity),X(ne.name,ne.activity))||V.name.localeCompare(ne.name)),Z=new Set(n||[]),q=G_(ue,ge,$),fe=Mr(q,W,O("local").filter,ur(ee,"local")),et=te(s||[]).map(V=>{const ne=(V.route||[V.name]).join("/"),z=O(ne),{rawItems:se}=bd(V),me=Mr(se,W,z.filter,ur(ee,ne));return{g:V,nodeRoute:ne,groupView:z,rawItems:se,items:me}}),ze=(V,ne,z)=>o&&o({session:V,...ne?{node:ne}:{},...Ss.test(String(z||""))?{ownerId:z}:{}}),Fe=async V=>{if(!(V!=null&&V.direct)||!y)return;const ne=window.prompt(g("rename-node-prompt"),V.label||V.name);if(ne!==null)try{await y(V,ne)||window.alert(g("rename-node-invalid"))}catch(z){window.alert(String((z==null?void 0:z.message)||z))}},[Ct,Ge]=N.useState({}),[rt,ut]=N.useState(new Set);N.useEffect(()=>{const V=new Map;for(const ne of t||[])V.set(ps(ne.cell),!!ne.boot);for(const ne of s||[]){const z=ne.route||[ne.name];for(const se of ne.cells||[])V.set(ps(se.cell,z),!!se.boot)}Ge(ne=>{let z=!1;const se={...ne};for(const[me,ke]of Object.entries(ne))V.has(me)&&V.get(me)===ke&&(delete se[me],z=!0);return z?se:ne})},[t,s]),N.useEffect(()=>{if(!(k!=null&&k.cell))return;const V=Array.isArray(k.route)?k.route:[],ne=ps(k.cell,V);Ge(z=>({...z,[ne]:!!k.enabled})),R&&R(k.id)},[k,R]);const ct=(V,ne=[])=>{const z=ps(V.cell,ne);return Object.prototype.hasOwnProperty.call(Ct,z)?Ct[z]:!!V.boot},vt=async(V,ne,z=[])=>{if(V.stopPropagation(),!h)return;const se=ps(ne.cell,z),me=!ct(ne,z);Ge(ke=>({...ke,[se]:me})),ut(ke=>new Set(ke).add(se));try{await h(ne.cell,me,z)}catch(ke){Ge(Ne=>{const we={...Ne};return delete we[se],we}),S&&S(ke)}finally{ut(ke=>{const Ne=new Set(ke);return Ne.delete(se),Ne})}},it=(V,ne=[])=>{const z=ps(V.cell,ne),se=ct(V,ne),me=`${g(se?"boot-disable":"boot-enable")} ${V.cell}`;return c.jsx("button",{className:`nc-boot${se?" on":""}`,disabled:rt.has(z),onClick:ke=>vt(ke,V,ne),title:me,"aria-label":me,children:c.jsx(nt,{name:"boot",size:14})})},[lt,mt]=N.useState(null),le=(V,ne)=>{const z=V.currentTarget.getBoundingClientRect();mt({text:ne,y:z.top+z.height/2})},be=()=>mt(null),Be=N.useRef(null);N.useEffect(()=>()=>{Be.current&&Be.current()},[]);function $e(V){V.preventDefault(),V.stopPropagation();const ne=V.clientX,z=I,se=ke=>{const Ne=Math.max(dE,Math.min(hE,z+(ke.clientX-ne)));G&&G(Ne)},me=()=>{window.removeEventListener("pointermove",se),window.removeEventListener("pointerup",me),window.removeEventListener("pointercancel",me),window.removeEventListener("blur",me),Be.current=null};window.addEventListener("pointermove",se),window.addEventListener("pointerup",me),window.addEventListener("pointercancel",me),window.addEventListener("blur",me),Be.current=me}const he=A?{width:48,flex:"0 0 48px"}:{width:I,flex:`0 0 ${I}px`};return A?c.jsxs("aside",{className:"nc-sidebar mini",style:he,children:[c.jsx("div",{className:"nc-side-head mini",children:c.jsx("button",{className:"nc-collapse-btn",onClick:F,title:g("expand"),children:"⟩"})}),c.jsx("button",{className:"nc-side-gear mini",onClick:()=>w&&w("nodes",!1),title:g("settings"),onMouseEnter:V=>le(V,g("settings")),onMouseLeave:be,children:c.jsx(nt,{name:"gear",size:16})}),c.jsx("div",{className:"nc-side-scroll mini",children:c.jsxs("div",{className:"nc-side-group mini",children:[O("local").open&&fe.map(V=>V.type==="cell"?(()=>{const ne=V.value,z=ne.degraded?"warn":ne.tmux?"on":"",se=!!ne.tmux;return c.jsx("button",{type:"button",className:`nc-mini-dot${Z.has(ne.tmuxSession)?" active":""}`,onMouseEnter:me=>le(me,`${ne.cell}: ${V.subtitle}`),onMouseLeave:be,draggable:se,onDragStart:se?me=>me.dataTransfer.setData("text/nc-session",ne.tmuxSession):void 0,onClick:se?()=>a&&a(ne.tmuxSession):()=>u&&u(ne),onDoubleClick:se?()=>ze(ne.tmuxSession,"",x):void 0,children:c.jsx("span",{className:`nc-dot ${z}${V.working?" working":""}`})},V.key)})():(()=>{const ne=V.value;return c.jsx("button",{type:"button",className:`nc-mini-init${Z.has(ne.name)?" active":""}`,onMouseEnter:z=>le(z,ne.name),onMouseLeave:be,draggable:!0,onDragStart:z=>z.dataTransfer.setData("text/nc-session",ne.name),onClick:()=>a&&a(ne.name),onDoubleClick:()=>ze(ne.name,"",x),children:Sv(ne.name)},V.key)})()),et.flatMap(({g:V,nodeRoute:ne,groupView:z,items:se})=>V.status==="up"?z.open?se.map(me=>me.type==="cell"?(()=>{const ke=me.value,Ne=!!ke.tmux;return c.jsx("button",{type:"button",className:`nc-mini-dot${Z.has(me.key)?" active":""}`,onMouseEnter:we=>le(we,`${V.label||ne}: ${ke.cell} · ${me.subtitle}`),onMouseLeave:be,draggable:Ne,onDragStart:Ne?we=>we.dataTransfer.setData("text/nc-session",me.key):void 0,onClick:Ne?()=>a&&a(me.key):()=>u&&u({...ke,route:V.route,availableEngines:V.engines||[]}),onDoubleClick:Ne?()=>ze(ke.tmuxSession,ne,V.instanceId):void 0,children:c.jsx("span",{className:`nc-dot ${ke.degraded?"warn":Ne?`on${me.working?" working":""}`:""}`})},me.key)})():(()=>{const ke=me.value;return c.jsx("button",{type:"button",className:`nc-mini-init${Z.has(me.key)?" active":""}`,onMouseEnter:Ne=>le(Ne,`${V.label||ne}: ${ke.name}`),onMouseLeave:be,draggable:!0,onDragStart:Ne=>Ne.dataTransfer.setData("text/nc-session",me.key),onClick:()=>a&&a(me.key),onDoubleClick:()=>ze(ke.name,ne,V.instanceId),children:Sv(ke.name)},me.key)})()):[]:[c.jsx("button",{type:"button",className:"nc-mini-dot",onMouseEnter:me=>le(me,`${V.label||(V.route||[V.name]).join(" › ")}: ${vs(V)}`),onMouseLeave:be,children:c.jsx("span",{className:`nc-dot${V.status==="passive"?"":" warn"}`})},`nodo-${(V.route||[V.name]).join("/")}`)])]})}),lt&&c.jsx("div",{className:"nc-mini-tip",style:{top:lt.y},children:lt.text})]}):c.jsxs("aside",{className:"nc-sidebar",style:he,children:[c.jsxs("div",{className:"nc-side-head",children:[c.jsx("button",{className:"nc-collapse-btn",onClick:F,title:g("collapse"),children:"⟨"}),c.jsx("span",{className:"nc-side-title",children:g("fleet")}),c.jsxs("button",{className:"nc-new-btn",onClick:b,title:g("fleet-new-cell"),children:["+ ",g("new")]})]}),c.jsxs("button",{className:"nc-side-gear",onClick:()=>w&&w("nodes",!1),title:g("settings"),children:[c.jsx(nt,{name:"gear",size:15})," ",g("settings")]}),c.jsxs("div",{className:"nc-side-scroll",children:[c.jsx(pE,{label:g("position-local"),count:fe.length,state:O("local"),onToggle:()=>j("local",{open:!O("local").open}),onFilter:V=>j("local",{filter:V})}),O("local").open&&c.jsxs("div",{className:"nc-side-group",children:[fe.map(V=>V.type==="cell"?(()=>{const ne=V.value,z=ne.degraded?"warn":ne.tmux?"on":"",se=ne.degraded?g("cell-degraded"):V.working?V.subtitle:ne.tmux?g("cell-idle"):g("cell-off"),me=!!ne.tmux;return c.jsxs("div",{"data-roster-key":V.key,"data-position":"local",className:`nc-cell${me?" live":""}${Z.has(ne.tmuxSession)?" active":""}`,title:`${ne.cell} · ${V.subtitle}${se===V.subtitle?"":` · ${se}`}`,"aria-label":`${ne.cell}, ${V.subtitle}${se===V.subtitle?"":`, ${se}`}`,draggable:me,onDragStart:me?ke=>ke.dataTransfer.setData("text/nc-session",ne.tmuxSession):void 0,onClick:me?()=>a&&a(ne.tmuxSession):void 0,onDoubleClick:me?()=>ze(ne.tmuxSession,"",x):void 0,children:[c.jsx(ar,{position:"local",itemKey:V.key,label:ne.cell,canMove:P,onMove:(ke,Ne)=>M("local",ke,Ne,q),onStep:ke=>H("local",V.key,ke,q)}),c.jsx("span",{className:`nc-dot ${z}${V.working?" working":""}`}),c.jsxs("span",{className:"nc-cell-main",children:[c.jsx("b",{title:ne.cell,children:ne.cell}),c.jsx("small",{title:V.subtitle,children:V.subtitle})]}),c.jsx("button",{className:`nc-pin${W.includes(V.key)?" on":""}`,title:g("pin"),onClick:ke=>{ke.stopPropagation(),K(V.key)},children:W.includes(V.key)?"★":"☆"}),h&&C.includes("boot")&&it(ne),c.jsx("button",{className:`nc-power${ne.tmux?" on":""}${ne.degraded?" warn":""}`,onClick:ke=>{ke.stopPropagation(),u&&u({...ne,boot:ct(ne)})},title:ne.active?g("power-off"):g("power-on"),children:c.jsx(nt,{name:"power",size:14})})]},V.key)})():(()=>{var z;const ne=V.value;return c.jsxs("div",{"data-roster-key":V.key,"data-position":"local",className:`nc-side-card${Z.has(ne.name)?" active":""}`,draggable:!0,onDragStart:se=>se.dataTransfer.setData("text/nc-session",ne.name),onClick:()=>a&&a(ne.name),onDoubleClick:()=>ze(ne.name,"",x),children:[c.jsx(ar,{position:"local",itemKey:V.key,label:ne.name,canMove:P,onMove:(se,me)=>M("local",se,me,q),onStep:se=>H("local",V.key,se,q)}),c.jsx("span",{className:ne.attached?"nc-dot on":"nc-dot"}),c.jsxs("span",{className:"nc-card-main",children:[c.jsx("b",{children:ne.name}),c.jsxs("small",{children:[ne.preview||ne.cmd||g("windows").replace("{n}",String(ne.windows||0)),((z=ne.outbox)==null?void 0:z.count)>0?` · 📦${ne.outbox.count}`:""]})]}),ne.activity?c.jsx("span",{className:"nc-rel",children:ws(ne.activity)}):null,c.jsx("button",{className:`nc-pin${W.includes(V.key)?" on":""}`,title:g("pin"),onClick:se=>{se.stopPropagation(),K(V.key)},children:W.includes(V.key)?"★":"☆"}),c.jsx("button",{className:`nc-technical${ne.technical?" on":""}`,title:ne.technical?g("mark-normal"):g("mark-technical"),"aria-label":`${ne.technical?g("mark-normal"):g("mark-technical")} ${ne.name}`,onClick:se=>{se.stopPropagation(),_&&_(ne.name,!ne.technical,[])},children:"T"}),c.jsx("button",{className:"nc-menu",title:g("terminate"),onClick:se=>{se.stopPropagation(),window.confirm(g("terminate-confirm").replace("{name}",ne.name))&&f&&f(ne.name)},children:"⋯"})]},V.key)})()),fe.length===0&&c.jsx("div",{className:"nc-empty",children:g("no-sessions-short")})]}),et.map(({g:V,nodeRoute:ne,groupView:z,rawItems:se,items:me})=>{const Ne=q_(V.health)||(V.status==="up"?"on":V.status==="passive"?"":"warn");return c.jsxs("div",{className:"nc-node-order-wrap","data-node-order-key":B(V),children:[c.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onContextMenu:V.direct&&y?we=>{we.preventDefault(),Fe(V)}:void 0,onClick:()=>j(ne,{open:!z.open}),onKeyDown:we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),j(ne,{open:!z.open}))},children:[c.jsx(ar,{scope:"node",position:"nodes",itemKey:B(V),label:V.label||V.name,onMove:(we,Re)=>T(we,Re,s||[]),onStep:we=>ie(B(V),we,s||[])}),c.jsx("span",{className:"nc-node-chevron",children:z.open?"⌄":"›"}),c.jsx("span",{className:`nc-dot ${Ne}`,title:V.health?wl(V.health):""}),c.jsx("b",{children:V.label||V.name}),c.jsxs("small",{children:[" · ",V.status==="up"?g("node-sessions").replace("{n}",String(me.length)):V.health&&wl(V.health)||vs(V)]}),c.jsxs("select",{className:"nc-node-filter",value:z.filter,title:g(`view-${z.filter}`),onClick:we=>we.stopPropagation(),onChange:we=>j(ne,{filter:we.target.value}),children:[c.jsx("option",{value:"all",children:g("view-all")}),c.jsx("option",{value:"pinned",children:g("view-pinned")}),c.jsx("option",{value:"active",children:g("view-active")}),c.jsx("option",{value:"off",children:g("view-off")}),c.jsx("option",{value:"technical",children:g("view-technical")})]}),V.direct&&y&&c.jsx("button",{type:"button",className:"nc-node-rename",title:g("rename-node"),"aria-label":`${g("rename-node")} ${V.label||V.name}`,onClick:we=>{we.stopPropagation(),Fe(V)},children:"✎"}),V.direct&&V.health&&V.health.managed!==!1&&c.jsx("button",{type:"button",className:`nc-power${V.tunnelStatus==="up"?" on":""}`,title:V.tunnelStatus==="up"?g("power-off"):g("power-on"),onClick:we=>{we.stopPropagation(),p&&p(V)},children:c.jsx(nt,{name:"power",size:14})})]}),V.status==="up"&&z.open&&c.jsxs("div",{className:"nc-side-group",children:[me.map(we=>we.type==="cell"?(()=>{const Re=we.value,Je=!!Re.tmux,Tt=Re.degraded?"warn":Re.tmux?"on":"";return c.jsxs("div",{"data-roster-key":we.key,"data-position":ne,className:`nc-side-card nc-cell${Je?" live":""}${Z.has(Re.key)?" active":""}`,title:we.working?we.subtitle:Re.tmux?g("cell-idle"):g("cell-off"),draggable:Je,onDragStart:Je?Me=>Me.dataTransfer.setData("text/nc-session",Re.key):void 0,onClick:Je?()=>a&&a(Re.key):void 0,onDoubleClick:Je?()=>ze(Re.tmuxSession,ne,V.instanceId):void 0,children:[c.jsx(ar,{position:ne,itemKey:we.key,label:Re.cell,canMove:P,onMove:(Me,pn)=>M(ne,Me,pn,se),onStep:Me=>H(ne,we.key,Me,se)}),c.jsx("span",{className:`nc-dot ${Tt}${we.working?" working":""}`}),c.jsxs("span",{className:"nc-card-main",children:[c.jsx("b",{children:Re.cell}),c.jsx("small",{title:we.subtitle,children:we.subtitle})]}),c.jsx("button",{className:`nc-pin${W.includes(we.key)?" on":""}`,title:g("pin"),onClick:Me=>{Me.stopPropagation(),K(we.key)},children:W.includes(we.key)?"★":"☆"}),h&&(V.capabilities||[]).includes("boot")&&it(Re,V.route||[]),(V.capabilities||[]).includes(Re.active?"down":"up")&&c.jsx("button",{className:`nc-power${Re.active?" on":""}${Re.degraded?" warn":""}`,onClick:Me=>{Me.stopPropagation(),u&&u({...Re,boot:ct(Re,V.route||[]),route:V.route,availableEngines:V.engines||[]})},title:Re.active?g("power-off"):g("power-on"),children:c.jsx(nt,{name:"power",size:14})})]},we.key)})():(()=>{const Re=we.value;return c.jsxs("div",{"data-roster-key":we.key,"data-position":ne,className:`nc-side-card${Z.has(Re.key)?" active":""}`,draggable:!0,onDragStart:Je=>Je.dataTransfer.setData("text/nc-session",Re.key),onClick:()=>a&&a(Re.key),onDoubleClick:()=>ze(Re.name,Re.node||ne,V.instanceId),children:[c.jsx(ar,{position:ne,itemKey:we.key,label:Re.name,canMove:P,onMove:(Je,Tt)=>M(ne,Je,Tt,se),onStep:Je=>H(ne,we.key,Je,se)}),c.jsx("span",{className:Re.attached?"nc-dot on":"nc-dot"}),c.jsxs("span",{className:"nc-card-main",children:[c.jsx("b",{children:Re.name}),c.jsx("small",{children:Re.preview?Re.preview:Re.cmd?Re.cmd:g("windows").replace("{n}",String(Re.windows||0))})]}),Re.activity?c.jsx("span",{className:"nc-rel",children:ws(Re.activity)}):null,c.jsx("button",{className:`nc-pin${W.includes(we.key)?" on":""}`,title:g("pin"),onClick:Je=>{Je.stopPropagation(),K(we.key)},children:W.includes(we.key)?"★":"☆"}),c.jsx("button",{className:`nc-technical${Re.technical?" on":""}`,title:Re.technical?g("mark-normal"):g("mark-technical"),"aria-label":`${Re.technical?g("mark-normal"):g("mark-technical")} ${Re.name}`,onClick:Je=>{Je.stopPropagation(),_&&_(Re.name,!Re.technical,V.route||[])},children:"T"}),c.jsx("button",{className:"nc-menu",title:g("terminate"),onClick:Je=>{Je.stopPropagation(),window.confirm(g("terminate-confirm").replace("{name}",Re.name))&&f&&f(Re.name,V.route)},children:"⋯"})]},we.key)})()),me.length===0&&c.jsx("div",{className:"nc-empty",children:g("no-sessions-short")})]})]},`nodo-${(V.route||[V.name]).join("/")}`)})]}),c.jsx("div",{className:"nc-side-lang",children:H_.map((V,ne)=>c.jsxs("span",{children:[ne>0&&" · ",c.jsx("button",{className:`nc-lang-btn${D===V?" on":""}`,onClick:()=>J(V),title:V,children:V.toUpperCase()})]},V))}),c.jsx("div",{className:"nc-side-resize",onPointerDown:$e,title:""})]})}function pE({label:e,count:t,state:n,onToggle:s,onFilter:o}){return c.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onClick:s,onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),s())},children:[c.jsx("span",{className:"nc-node-chevron",children:n.open?"⌄":"›"}),c.jsx("span",{className:"nc-dot on"}),c.jsx("b",{children:e}),c.jsxs("small",{children:[" · ",g("node-sessions").replace("{n}",String(t))]}),c.jsxs("select",{className:"nc-node-filter",value:n.filter,title:g(`view-${n.filter}`),onClick:a=>a.stopPropagation(),onChange:a=>o(a.target.value),children:[c.jsx("option",{value:"all",children:g("view-all")}),c.jsx("option",{value:"pinned",children:g("view-pinned")}),c.jsx("option",{value:"active",children:g("view-active")}),c.jsx("option",{value:"off",children:g("view-off")}),c.jsx("option",{value:"technical",children:g("view-technical")})]})]})}function mE(e,t,n){return!e&&t?n+1:n}const Kh="nc_input_preferences_v1",Wu="nc-input-preferences",sw=Object.freeze(["double-tap","single-tap","never"]),ow=Object.freeze(["full","compact"]),lr=Object.freeze({terminalKeyboardGesture:"double-tap",keybarKeepsKeyboardClosed:!0,voiceKeepsKeyboardClosed:!0,showKeybarEnter:!0,keybarLayout:"full"});function qh(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{terminalKeyboardGesture:sw.includes(t.terminalKeyboardGesture)?t.terminalKeyboardGesture:lr.terminalKeyboardGesture,keybarKeepsKeyboardClosed:typeof t.keybarKeepsKeyboardClosed=="boolean"?t.keybarKeepsKeyboardClosed:lr.keybarKeepsKeyboardClosed,voiceKeepsKeyboardClosed:typeof t.voiceKeepsKeyboardClosed=="boolean"?t.voiceKeepsKeyboardClosed:lr.voiceKeepsKeyboardClosed,showKeybarEnter:typeof t.showKeybarEnter=="boolean"?t.showKeybarEnter:lr.showKeybarEnter,keybarLayout:ow.includes(t.keybarLayout)?t.keybarLayout:lr.keybarLayout}}function aw(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function bv(e=aw()){if(!e)return{...lr};try{return qh(JSON.parse(e.getItem(Kh)||"null"))}catch{return{...lr}}}function gE(e,t=aw()){const n=qh(e);if(t)try{t.setItem(Kh,JSON.stringify(n))}catch{}return n}function Vh(){const[e,t]=N.useState(bv);N.useEffect(()=>{const s=o=>{if((o==null?void 0:o.type)==="storage"&&o.key!==Kh&&o.key!==null)return;const a=o!=null&&o.detail?qh(o.detail):bv();t(a)};return window.addEventListener(Wu,s),window.addEventListener("storage",s),()=>{window.removeEventListener(Wu,s),window.removeEventListener("storage",s)}},[]);const n=N.useCallback(s=>{t(o=>{const a=gE({...o,...s||{}});return window.dispatchEvent(new CustomEvent(Wu,{detail:a})),a})},[]);return[e,n]}function vE({session:e,node:t,ownerId:n,cellName:s,token:o,readonly:a=!1,focused:u,onFocus:h,onClose:p,onOpenSingle:f,alive:_=!0,available:b=!0,fontSize:y=Mo,onZoom:w,decks:S=[],currentDeck:x,onSendToDeck:C}){const[k]=Vh(),R=s||e,I=N.useRef(()=>{}),A=N.useRef(()=>!1),G=N.useRef(()=>{}),F=N.useRef(!1),[D,J]=N.useState(!1),[W,ee]=N.useState(!1),[K,O]=N.useState(!1),[j,P]=N.useState(null),[M,H]=N.useState(0),te=N.useRef(_),T=t?`${t}:${e}`:e,ie=S.filter(B=>B.id!==x&&B.available!==!1);return N.useEffect(()=>{const B=te.current;!B&&_&&H(L=>mE(B,_,L)),te.current=_},[_]),c.jsxs("div",{className:`nc-tile${u?" focused":""}`,onMouseDown:()=>h&&h(T),children:[c.jsxs("div",{className:"nc-tile-head",draggable:!0,onDragStart:B=>{B.dataTransfer.setData("text/nc-session",T),B.dataTransfer.effectAllowed="move"},children:[c.jsxs("button",{className:"nc-tile-name",onClick:()=>h&&h(T),title:t?`${R} · ${t}`:R,children:[c.jsx("span",{className:_?"nc-dot on":"nc-dot"}),c.jsx("b",{children:R})]}),c.jsxs("span",{className:"nc-tile-actions",children:[w&&c.jsx("button",{onClick:()=>w(-1),title:g("zoom-out"),children:c.jsx(nt,{name:"zoomOut",size:14})}),w&&c.jsx("button",{onClick:()=>w(1),title:g("zoom-in"),children:c.jsx(nt,{name:"zoomIn",size:14})}),C&&ie.length>0&&c.jsxs("select",{className:"nc-tile-deck",title:g("send-to-deck"),value:"",onMouseDown:B=>B.stopPropagation(),onChange:B=>{const L=B.target.value;L&&C(T,L),B.target.value=""},children:[c.jsx("option",{value:"",children:g("send-to-deck")}),ie.map(B=>c.jsxs("option",{value:B.id,children:[B.ownerLabel," · ",B.name]},B.id))]}),c.jsx("button",{onClick:()=>ee(B=>!B),title:"composer",children:"⌨"}),c.jsx("button",{onClick:()=>O(B=>!B),title:"file",children:"📁"}),f&&c.jsx("button",{onClick:()=>f({session:e,node:t,ownerId:n}),title:"vista singola",children:"↗"}),p&&c.jsx("button",{className:"nc-tile-close",onClick:()=>p(T),title:"chiudi",children:"✕"})]})]}),c.jsxs("div",{className:"nc-tile-body",children:[b?c.jsx(Yy,{session:e,node:t,token:o,readonly:a,takeSize:!1,focused:u,sendRef:I,composerRef:A,actionRef:G,ctrlRef:F,setCtrlArmed:J,onFiles:P,fontSize:y,keyboardGesture:k.terminalKeyboardGesture},`${T}:${M}`):c.jsx("div",{className:"nc-tile-unavailable",children:g("deck-owner-unavailable")}),b&&K&&c.jsx("div",{className:"nc-tile-files",onMouseDown:B=>B.stopPropagation(),children:c.jsx(Gy,{session:e,node:t,token:o,filesEvent:j,onClose:()=>O(!1)})})]}),b&&W&&c.jsx("div",{className:"nc-tile-composer",onMouseDown:B=>B.stopPropagation(),children:c.jsx(rw,{submitText:B=>A.current(B),token:o,session:e,node:t,ownerId:n,keepKeyboardClosedOnVoice:k.voiceKeepsKeyboardClosed})})]})}function _E({session:e,node:t,ownerId:n,cells:s,nodeGroups:o}={}){const a=typeof e=="string"?e:"";if(!a)return null;if(t){const h=Array.isArray(o)?o:[];for(const p of h){if(!p||(Array.isArray(p.route)?p.route:[]).join("/")!==t||n&&p.instanceId&&String(n)!==String(p.instanceId))continue;const _=(Array.isArray(p.cells)?p.cells:[]).find(b=>b&&b.tmuxSession===a);if(_)return _}return null}return(Array.isArray(s)?s:[]).find(h=>h&&h.tmuxSession===a)||null}function Yh({session:e,cell:t,node:n,ownerId:s,cells:o,nodeGroups:a}={}){const u=typeof e=="string"?e:"";if(t&&typeof t.cell=="string"&&t.cell)return t.cell;const h=_E({session:u,node:n,ownerId:s,cells:o,nodeGroups:a});return h&&h.cell?h.cell:u}const kv=.2,xv=.28,lw=(e,t)=>Array.from((e==null?void 0:e.types)||[]).includes(t),Uu=e=>lw(e,"text/nc-session"),Cv=e=>{var t;return lw(e,"Files")||(((t=e==null?void 0:e.files)==null?void 0:t.length)||0)>0};function yE(e,t,n){const s=(e-n.left)/(n.width||1),o=(t-n.top)/(n.height||1);return s<xv?"left":s>1-xv?"right":o<.5?"top":"bottom"}function wE({layout:e,onLayoutChange:t,token:n,readonly:s=!1,sessionsAlive:o,focusSession:a,onFocus:u,onOpenSingle:h,decks:p=[],currentDeck:f,onSendToDeck:_,cells:b=[],nodeGroups:y=[]}){zn();const[w,S]=N.useState(null),x=N.useRef(null),C=N.useRef([]),k=N.useRef(null);function R(K,O){const j=()=>{window.removeEventListener("pointermove",K),window.removeEventListener("pointerup",j),window.removeEventListener("pointercancel",j),window.removeEventListener("blur",j),k.current=null};window.addEventListener("pointermove",K),window.addEventListener("pointerup",j),window.addEventListener("pointercancel",j),window.addEventListener("blur",j),k.current=j}N.useEffect(()=>()=>{k.current&&k.current()},[]),N.useEffect(()=>{const K=()=>S(null);return window.addEventListener("dragend",K),window.addEventListener("drop",K),()=>{window.removeEventListener("dragend",K),window.removeEventListener("drop",K)}},[]);const I=e.columns.length,A=K=>w&&w.col===K&&w.row===void 0,G=!!w&&w.col===I,F=(K,O)=>w&&w.col===K&&w.row===O&&w.quadrant?` drop-${w.quadrant}`:"";function D(K){if(K.preventDefault(),Cv(K.dataTransfer)){S(null);return}const O=K.dataTransfer.getData("text/nc-session"),j=w;if(S(null),!O||!j)return;let P;if(j.quadrant){if(P=n1(e,j.col,j.row,j.quadrant),!P)return}else P={col:j.col};t(vi(e).includes(O)?J0(e,O,P):Th(e,O,P))}function J(K,O){K.preventDefault(),K.stopPropagation();const j=K.clientX,P=e.columns[O].width,M=x.current&&x.current.clientWidth||1,H=e.columns[O+1];R(T=>{let ie=Math.max(kv,P+(T.clientX-j)/M);if(H){const B=fg(ie/(ie+H.width));ie=B/(1-B)*H.width}t(Z0(e,O,ie))})}function W(K,O,j){K.preventDefault(),K.stopPropagation();const P=K.clientY,M=e.columns[O].tiles[j].height,H=C.current[O],te=H&&H.clientHeight||1,T=e.columns[O].tiles[j+1];R(B=>{let L=Math.max(kv,M+(B.clientY-P)/te);if(T){const $=fg(L/(L+T.height));L=$/(1-$)*T.height}t(e1(e,O,j,L))})}function ee(K){t(kl(e,K))}return c.jsxs("div",{className:"nc-grid",ref:x,onDragOver:K=>{if(Cv(K.dataTransfer)){K.preventDefault(),S(null);return}Uu(K.dataTransfer)&&(K.preventDefault(),w&&w.col===I||S({col:I}))},onDrop:D,onDragLeave:K=>{const O=K.relatedTarget;(!O||!(x.current&&x.current.contains(O)))&&S(null)},children:[e.columns.flatMap((K,O)=>{const j=[];return j.push(c.jsx("div",{className:`nc-col${A(O)?" drop-newcol":""}`,ref:P=>{C.current[O]=P},style:{flexGrow:K.width,flexBasis:0},onDragOver:P=>{Uu(P.dataTransfer)&&(P.preventDefault(),P.stopPropagation(),w&&w.col===O&&w.row===void 0||S({col:O}))},children:K.tiles.flatMap((P,M)=>{const H=[],te=In(P),T=Yh({session:P.session,node:P.node,ownerId:P.ownerId,cells:b,nodeGroups:y});return H.push(c.jsx("div",{className:`nc-tile-slot${F(O,M)}`,style:{flexGrow:P.height,flexBasis:0},onDragOver:ie=>{if(!Uu(ie.dataTransfer))return;ie.preventDefault(),ie.stopPropagation();const B=yE(ie.clientX,ie.clientY,ie.currentTarget.getBoundingClientRect());w&&w.col===O&&w.row===M&&w.quadrant===B||S({col:O,row:M,quadrant:B})},children:c.jsx(vE,{session:P.session,node:P.node,ownerId:P.ownerId,cellName:T,token:n,readonly:s,focused:a===te,onFocus:u,onClose:ee,onOpenSingle:h,available:P.unavailable!==!0,alive:P.unavailable!==!0&&(!o||o.has(te)),fontSize:P.fontSize,onZoom:ie=>t(t1(e,O,M,ie)),decks:p,currentDeck:f,onSendToDeck:_})},te)),M<K.tiles.length-1&&H.push(c.jsx("div",{className:"nc-divider-h",onPointerDown:ie=>W(ie,O,M)},`h${M}`)),H})},`c${O}`)),O<I-1&&j.push(c.jsx("div",{className:"nc-divider-v",onPointerDown:P=>J(P,O)},`v${O}`)),j}),G&&c.jsx("div",{className:"nc-drop-line-v nc-drop-line-end"}),I===0&&c.jsx("div",{className:"nc-grid-empty",children:g("grid-empty")})]})}const mi="local",Bn=/^[a-f0-9]{16,64}$/;function ys(e,t){return`${e&&Bn.test(e)?e:mi}:${t}`}function zl(e){const t=String(e||""),n=t.indexOf(":");if(n<1)return null;const s=t.slice(0,n),o=t.slice(n+1);return s!==mi&&!Bn.test(s)||!/^[a-z0-9-]{1,32}$/.test(o)?null:{ownerId:s===mi?null:s,name:o}}function Fl(e){return Array.isArray(e)&&e.length?e.join("/"):""}function Gh(e){return{columns:Ar(e).columns.map(t=>({width:t.width,tiles:t.tiles.map(n=>({...n}))}))}}function SE(e){const t=new Map;for(const n of Array.isArray(e)?e:[])n&&Bn.test(String(n.instanceId||""))&&Array.isArray(n.route)&&t.set(Fl(n.route),n.instanceId);return t}function bE(e){const t=new Map;for(const n of Array.isArray(e)?e:[])n&&Bn.test(String(n.instanceId||""))&&Array.isArray(n.route)&&t.set(n.instanceId,[...n.route]);return t}function dh(e,t,n=[]){const s=Gh(e),o=SE(n);for(const a of s.columns)for(const u of a.tiles)u.ownerId||(!u.node&&Bn.test(String(t||""))?u.ownerId=t:u.node&&o.has(u.node)&&(u.ownerId=o.get(u.node)));return s}function hh(e,t,n=[]){const s=Gh(e),o=new Map;for(const a of n)a&&Bn.test(String(a.instanceId||""))&&Array.isArray(a.route)&&o.set(a.instanceId,[...a.route]);for(const a of s.columns)for(const u of a.tiles)u.ownerId&&(u.ownerId===t?(delete u.node,delete u.unavailable):o.has(u.ownerId)?(u.node=Fl(o.get(u.ownerId)),delete u.unavailable):u.unavailable=!0);return s}function Ev(e,t,n=[]){const s=Gh(e),o=bE(n);for(const a of s.columns)for(const u of a.tiles)delete u.unavailable,u.ownerId&&(u.ownerId===t?delete u.node:o.has(u.ownerId)&&(u.node=Fl(o.get(u.ownerId))));return s}function cw(e,t,n=[]){const s=fr(e);if(!s)return null;if(s.ownerId)return s;if(!s.node)return{...s,...Bn.test(String(t||""))?{ownerId:t}:{}};const o=n.find(a=>Fl(a&&a.route)===s.node);return{...s,...o&&Bn.test(String(o.instanceId||""))?{ownerId:o.instanceId}:{}}}const kE=/^[a-z0-9-]{1,32}$/,On="main",uw="nc_decks",dw="nc_deck_order_v1",hw=24;function Nv(e){return typeof e!="string"?"":e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,32).replace(/-+$/,"")}function xs(e){return typeof e=="string"&&kE.test(e)}function xE(e){const t=String(e||"").match(/^\/deck\/([^/]+)\/?$/);if(t){let n;try{n=decodeURIComponent(t[1])}catch{n=t[1]}return xs(n)?n:On}return On}function CE(e){const t=String(e||"").match(/^\/deck\/([^/]+)\/([^/]+)\/?$/);if(t){let s,o;try{s=decodeURIComponent(t[1]),o=decodeURIComponent(t[2])}catch{return{id:ys(null,On),ownerId:null,name:On}}if(Bn.test(s)&&xs(o))return{id:ys(s,o),ownerId:s,name:o}}const n=xE(e);return{id:ys(null,n),ownerId:null,name:n}}function Ku(e,t){const n=typeof e=="object"&&e?{ownerId:e.ownerId||null,name:e.name}:zl(e)||{ownerId:null,name:e},s=xs(n.name)?n.name:On,o=n.ownerId?`/deck/${encodeURIComponent(n.ownerId)}/${encodeURIComponent(s)}`:s===On?"/":`/deck/${encodeURIComponent(s)}`;return t?`${o}#token=${encodeURIComponent(t)}`:o}function fw(e){return e===On?"nc_grid_v1":`nc_grid_v1__${e}`}function pw(e){const t=[On];if(Array.isArray(e)){for(const n of e)if(xs(n)&&n!==On&&!t.includes(n)&&t.push(n),t.length>=hw)break}return t}function Ps(){return typeof localStorage<"u"?localStorage:null}function EE(){const e=Ps();if(!e)return[On];try{return pw(JSON.parse(e.getItem(uw)||"null"))}catch{return[On]}}function NE(e){const t=Ps();if(t)try{t.setItem(uw,JSON.stringify(pw(e)))}catch{}}function Fo(e){return e==="local"||Bn.test(String(e||""))}function $l(e,t){const n=zl(e);return!!n&&(n.ownerId||"local")===t}function yi(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[n,s]of Object.entries(e).slice(0,64)){if(!Fo(n)||!Array.isArray(s))continue;const o=[...new Set(s.filter(a=>typeof a=="string"&&a.length<=100&&$l(a,n)))].slice(0,hw);o.length&&(t[n]=o)}return t}function il(e=Ps()){if(!e)return{};try{return yi(JSON.parse(e.getItem(dw)||"null"))}catch{return{}}}function qu(e,t=Ps()){const n=yi(e);if(t)try{t.setItem(dw,JSON.stringify(n))}catch{}return n}function Hl(e,t){return Array.isArray(e==null?void 0:e[t])?e[t]:[]}function RE(e,t,n,s,o=[]){if(!Fo(t)||n===s)return yi(e);const a=[...new Set(o.filter(b=>$l(b,t)))];if(!a.includes(n)||!a.includes(s))return yi(e);const u=Hl(e,t).filter(b=>a.includes(b)),h=[...u,...a.filter(b=>!u.includes(b))],p=h.indexOf(n),f=h.indexOf(s);h.splice(p,1);const _=h.indexOf(s);return h.splice(p<f?_+1:_,0,n),yi({...e,[t]:h})}function PE(e,t,n,s){if(!Fo(t)||!$l(s,t))return yi(e);const o=Hl(e,t);return o.includes(n)?yi({...e,[t]:o.map(a=>a===n?s:a)}):yi(e)}function jE(e,t,n){return Fo(t)?yi({...e,[t]:Hl(e,t).filter(s=>s!==n)}):yi(e)}function Rv(e,t={}){const n=new Map;for(const o of Array.isArray(e)?e:[]){const a=o!=null&&o.local?"local":String((o==null?void 0:o.ownerId)||"");!Fo(a)||!$l(o==null?void 0:o.id,a)||(n.has(a)||n.set(a,[]),n.get(a).push(o))}const s=[];for(const[,o]of n){const a=o[0].local?"local":o[0].ownerId,u=Hl(t,a),h=new Map(u.map((p,f)=>[p,f]));o.sort((p,f)=>{const _=h.has(p.id)?h.get(p.id):Number.MAX_SAFE_INTEGER,b=h.has(f.id)?h.get(f.id):Number.MAX_SAFE_INTEGER;return _-b}),s.push(...o)}return s}function fh(e){const t=Ps();if(!t)return null;try{return JSON.parse(t.getItem(fw(e))||"null")}catch{return null}}function LE(e,t){const n=Ps();if(n)try{n.setItem(fw(e),JSON.stringify(t))}catch{}}const Xh="nc_deckbar_collapsed_v1",mw=64;function Jh(e){return e===mi||Bn.test(String(e||""))}function Qh(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[s,o]of Object.entries(e)){if(n>=mw)break;if(Jh(s)){if(o===!0)t[s]=!0;else if(o===!1)t[s]=!1;else continue;n+=1}}return t}function gw(e,t){return Jh(t)&&Object.prototype.hasOwnProperty.call(e||{},t)?e[t]===!0:!0}function DE(e,t){const n=Qh(e);return Jh(t)&&(!Object.prototype.hasOwnProperty.call(n,t)&&Object.keys(n).length>=mw&&delete n[Object.keys(n)[0]],n[t]=!gw(n,t)),n}function vw(){return typeof localStorage<"u"?localStorage:null}function Pv(e=vw()){if(!e)return{};try{return Qh(JSON.parse(e.getItem(Xh)||"null"))}catch{return{}}}function TE(e,t=vw()){const n=Qh(e);if(t)try{t.setItem(Xh,JSON.stringify(n))}catch{}return n}function ME(){const[e,t]=N.useState(Pv);N.useEffect(()=>{const o=a=>{(a.key===Xh||a.key===null)&&t(Pv())};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)},[]);const n=N.useCallback(o=>gw(e,o),[e]),s=N.useCallback(o=>{t(a=>TE(DE(a,o)))},[]);return{collapsed:e,isCollapsed:n,toggle:s}}const Zh="nc_deck_presence_v1",jv=3e4,AE=18e4,_w=1e4,yw=32,IE=/^[A-Za-z0-9_-]{1,64}$/,BE=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Lv="working",OE="on",zE="neutral",FE="warn";function ef(e){return typeof e=="string"&&IE.test(e)&&!BE.has(e)}function ww(e){return typeof e=="string"&&zl(e)!==null}function tf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Cs(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[s,o]of Object.entries(e)){if(n>=yw)break;ef(s)&&(!o||typeof o!="object"||ww(o.deckId)&&tf(o.ts)&&(t[s]={deckId:o.deckId,ts:o.ts,focus:o.focus===!0,visible:o.visible===!0},n+=1))}return t}function Sw(e,t){const n=Cs(e);if(!tf(t))return n;const s={};for(const[o,a]of Object.entries(n)){const u=a.visible?jv:AE,h=t-u;a.ts>=h&&a.ts<=t+jv&&(s[o]=a)}return s}function Dv(e,t,n,s){if(!ef(t)||!tf(s))return Cs(e);const o=Sw(e,s);if(!ww(n==null?void 0:n.deckId))return o;if(!Object.prototype.hasOwnProperty.call(o,t)&&Object.keys(o).length>=yw){let a="",u=1/0;for(const[h,p]of Object.entries(o))p.ts<u&&(a=h,u=p.ts);a&&delete o[a]}return o[t]={deckId:n.deckId,ts:s,focus:(n==null?void 0:n.focus)===!0,visible:(n==null?void 0:n.visible)===!0},Cs(o)}function $E(e,t){const n=Cs(e);if(!ef(t))return n;const s={...n};return delete s[t],s}function HE(e,t){const n=Sw(e,t),s={};for(const o of Object.values(n)){const a=o.focus&&o.visible?Lv:OE;s[o.deckId]!==Lv&&(s[o.deckId]=a)}return s}function bw(){return typeof localStorage<"u"?localStorage:null}function rl(e=bw()){if(!e)return{};try{return Cs(JSON.parse(e.getItem(Zh)||"null"))}catch{return{}}}function Vu(e,t=bw()){const n=Cs(e);if(t)try{t.setItem(Zh,JSON.stringify(n))}catch{}return n}const WE=Math.min(_w,5e3);function UE(){var e,t;try{const n=(t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e);if(n)return`w${n.replaceAll("-","")}`}catch{}return`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,14)}`}const KE=UE();function Tv(){const e=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0,t=typeof document<"u"&&typeof document.visibilityState=="string"?document.visibilityState!=="hidden":!0;return{focus:e,visible:t}}function qE(e,t=!0){const s=N.useRef(KE).current,o=N.useRef(e);o.current=e;const[a,u]=N.useState(()=>({map:{},now:Date.now()})),h=N.useCallback(()=>{u({map:rl(),now:Date.now()})},[]);N.useEffect(()=>{if(!t)return;const _=()=>{const C=Date.now(),k=Dv(rl(),s,{deckId:o.current,...Tv()},C);return Vu(k),{map:k,now:C}},b=()=>u(_());b();const y=setInterval(_,_w),w=setInterval(h,WE),S=b,x=C=>{(C.key===Zh||C.key===null)&&h()};return window.addEventListener("focus",S),window.addEventListener("blur",S),typeof document<"u"&&document.addEventListener("visibilitychange",S),window.addEventListener("storage",x),()=>{clearInterval(y),clearInterval(w),window.removeEventListener("focus",S),window.removeEventListener("blur",S),typeof document<"u"&&document.removeEventListener("visibilitychange",S),window.removeEventListener("storage",x);try{Vu($E(rl(),s))}catch{}}},[t,s,h]),N.useEffect(()=>{if(!t)return;const _=Date.now(),b=Dv(rl(),s,{deckId:e,...Tv()},_);Vu(b),u({map:b,now:_})},[e,t,s]);const p=N.useMemo(()=>t?HE(a.map,a.now):{},[t,a]);return{dotFor:N.useCallback((_,b=!1)=>t?b?FE:p[_]||zE:null,[p,t]),windowId:s}}const Mv=52,Av=18;function VE({ownerKey:e,deckId:t,label:n,onMove:s,onStep:o}){const a=N.useRef(null),u=N.useRef(0),[h,p]=N.useState(!1),f=()=>{var x,C,k,R;const S=a.current;(C=(x=S==null?void 0:S.over)==null?void 0:x.classList)==null||C.remove("nc-deck-over"),(R=(k=S==null?void 0:S.source)==null?void 0:k.classList)==null||R.remove("nc-deck-dragging"),u.current&&cancelAnimationFrame(u.current),u.current=0},_=(S=!1)=>{const x=a.current;if(!x)return;const C=x.target;f(),a.current=null,p(!1);try{x.handle.releasePointerCapture(x.pointerId)}catch{}S&&C&&C!==t&&s(t,C)},b=(S,x)=>{var A,G,F,D,J,W,ee,K;const C=a.current;if(!C)return;C.x=S,C.y=x;const k=(G=(A=document.elementFromPoint(S,x))==null?void 0:A.closest)==null?void 0:G.call(A,"[data-deck-id][data-owner-key]"),R=(F=k==null?void 0:k.dataset)==null?void 0:F.deckId,I=((D=k==null?void 0:k.dataset)==null?void 0:D.ownerKey)===e&&R&&R!==t;C.over!==(I?k:null)&&((W=(J=C.over)==null?void 0:J.classList)==null||W.remove("nc-deck-over"),C.over=I?k:null,(K=(ee=C.over)==null?void 0:ee.classList)==null||K.add("nc-deck-over")),C.target=I?R:null},y=()=>{var C,k;const S=a.current;if(!S){u.current=0;return}const x=(k=(C=S.container)==null?void 0:C.getBoundingClientRect)==null?void 0:k.call(C);if(x){const R=S.x<x.left+Mv?-Av:S.x>x.right-Mv?Av:0;R&&(S.container.scrollLeft+=R,b(S.x,S.y))}u.current=requestAnimationFrame(y)};N.useEffect(()=>{const S=C=>{C.key==="Escape"&&a.current&&(C.preventDefault(),_(!1))},x=()=>_(!1);return window.addEventListener("keydown",S),window.addEventListener("blur",x),()=>{window.removeEventListener("keydown",S),window.removeEventListener("blur",x),f(),a.current=null}},[t,e]);const w=S=>{var k;if(S.pointerType==="mouse"&&S.button!==0)return;S.preventDefault(),S.stopPropagation(),S.currentTarget.focus({preventScroll:!0});const x=S.currentTarget.closest("[data-deck-id][data-owner-key]"),C=S.currentTarget.closest(".nc-deckbar");a.current={pointerId:S.pointerId,handle:S.currentTarget,source:x,container:C,target:null,over:null,x:S.clientX,y:S.clientY},(k=x==null?void 0:x.classList)==null||k.add("nc-deck-dragging");try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}p(!0),u.current=requestAnimationFrame(y)};return c.jsx("button",{type:"button",className:`nc-deck-handle${h?" active":""}`,"aria-label":`${g("reorder")} ${n}`,"aria-keyshortcuts":"ArrowLeft ArrowRight",title:g("reorder-deck-help"),onClick:S=>{S.preventDefault(),S.stopPropagation()},onDragStart:S=>S.preventDefault(),onKeyDown:S=>{S.key!=="ArrowLeft"&&S.key!=="ArrowRight"||(S.preventDefault(),S.stopPropagation(),o(S.key==="ArrowLeft"?-1:1))},onPointerDown:w,onPointerMove:S=>{!a.current||S.pointerId!==a.current.pointerId||(S.preventDefault(),S.stopPropagation(),b(S.clientX,S.clientY))},onPointerUp:S=>{!a.current||S.pointerId!==a.current.pointerId||(S.preventDefault(),S.stopPropagation(),_(!0))},onPointerCancel:()=>_(!1),onLostPointerCapture:()=>{a.current&&_(!1)},children:"↔"})}function YE({decks:e=[],currentDeck:t="local:main",onCreate:n,onRename:s,onDelete:o,onReorder:a,onOpenWindow:u,onNavigate:h,saveState:p="idle",error:f="",sidebarVisible:_,onToggleSidebar:b}){zn();const{isCollapsed:y,toggle:w}=ME(),{dotFor:S}=qE(t),[x,C]=N.useState(null),[k,R]=N.useState(""),[I,A]=N.useState(!1),[G,F]=N.useState(""),[D,J]=N.useState(""),W=Nv(k),ee=xs(W),K=[];for(const H of e){const te=H.local?"local":H.ownerId;let T=K.find(ie=>ie.key===te);T||(T={key:te,label:H.ownerLabel||(H.local?"Local":te),local:!!H.local,decks:[]},K.push(T)),T.decks.push(H)}const O=async()=>{if(ee){A(!0),F("");try{n&&await n(W,x),R(""),C(null)}catch(H){F(String(H.message||H))}A(!1)}},j=H=>{J(""),u&&u(H.id)||J(H.id)},P=async H=>{if(!(H.id===t||!h||I||H.available===!1)){A(!0),F("");try{await h(H.id)}catch(te){F(String((te==null?void 0:te.message)||te))}A(!1)}},M=(H,te,T)=>{const ie=H.decks.findIndex(L=>L.id===te.id),B=H.decks[ie+T];ie>=0&&B&&a&&!I&&a(te.id,B.id)};return c.jsxs("div",{className:"nc-deckbar",children:[b&&c.jsx("button",{className:"nc-deck-sidebar-toggle",title:g("toggle-sidebar"),onClick:b,children:_?"◀":"☰"}),c.jsx("span",{className:"nc-deckbar-label",children:g("decks")}),c.jsx("div",{className:"nc-deck-chips",children:K.map(H=>{const te=y(H.key),T=`nc-deck-content-${H.key}`,ie=H.local?"Local":H.label,B=H.decks.some(X=>X.id===t),L=(H.decks.find(X=>X.id===t)||{}).name,$=g(H.decks.length===1?"owner-deck-count-one":"owner-deck-count-many").replace("{count}",H.decks.length);return c.jsxs("span",{className:`nc-deck-owner-group${te?" collapsed":""}`,"data-owner-key":H.key,"data-collapsed":te?"1":"0",children:[c.jsxs("button",{type:"button",className:"nc-deck-owner-toggle","aria-expanded":!te,"aria-controls":T,title:g(te?"expand-owner":"collapse-owner").replace("{owner}",ie),onClick:()=>{!te&&x===H.key&&(R(""),C(null)),w(H.key)},children:[c.jsx("span",{className:"nc-deck-owner-caret","aria-hidden":"true",children:te?"▸":"▾"}),c.jsx("span",{className:"nc-deck-owner",children:ie})]}),te&&c.jsxs("span",{className:"nc-deck-summary",title:$,children:[c.jsx("span",{className:"nc-deck-summary-count",children:H.decks.length}),B&&c.jsxs("span",{className:"nc-deck-summary-current",children:["• ",L]})]}),c.jsxs("span",{id:T,className:"nc-deck-owner-content",hidden:te,children:[H.decks.map(X=>{const ae=S(X.id,X.available===!1);return c.jsxs("span",{"data-deck-id":X.id,"data-owner-key":H.key,className:`nc-deck-chip${X.id===t?" current":""}${X.available===!1?" offline":""}`,children:[ae&&c.jsx(GE,{state:ae}),c.jsx(VE,{ownerKey:H.key,deckId:X.id,label:`${H.label} · ${X.name}`,onMove:(ue,ge)=>{a&&!I&&a(ue,ge)},onStep:ue=>M(H,X,ue)}),c.jsxs("button",{className:"nc-deck-open",title:X.available===!1?`${X.ownerLabel} offline`:X.id===t?g("deck-current"):`${X.ownerLabel} · ${X.name}`,disabled:I||X.available===!1,onClick:()=>P(X),children:[X.name,X.id===t?" •":""]}),c.jsx("button",{className:"nc-deck-mini",disabled:X.available===!1,title:g("detach-deck"),onClick:()=>j(X),children:"↗"}),X.name!==On&&c.jsxs(c.Fragment,{children:[c.jsx("button",{className:"nc-deck-mini",disabled:X.available===!1,title:g("rename-deck"),onClick:()=>{const ue=(typeof window<"u"?window.prompt(g("rename-deck"),X.name):"")||"",ge=Nv(ue);xs(ge)&&ge!==X.name&&s&&s(X.id,ge).catch(Z=>F(String(Z.message||Z)))},children:"✎"}),c.jsx("button",{className:"nc-deck-mini nc-deck-del",disabled:X.available===!1,title:g("delete-deck"),onClick:()=>{(typeof window>"u"||window.confirm(g("delete-deck-confirm").replace("{name}",`${X.ownerLabel} · ${X.name}`)))&&o&&o(X.id).catch(ue=>F(String(ue.message||ue)))},children:"✕"})]})]},X.id)}),x===H.key?c.jsxs("span",{className:"nc-deck-add",children:[c.jsx("input",{autoFocus:!0,className:ee||!k?"":"invalid",placeholder:g("deck-name"),value:k,onChange:X=>R(X.target.value),onKeyDown:X=>{X.key==="Enter"&&O(),X.key==="Escape"&&(R(""),C(null))}}),k&&ee&&W!==k&&c.jsxs("span",{className:"nc-deck-slug",children:["→ ",W]}),c.jsx("button",{className:"nc-deck-ok",disabled:!ee||I,onClick:O,children:g("create")}),c.jsx("button",{className:"nc-deck-cancel",onClick:()=>{R(""),C(null)},children:g("cancel")})]}):c.jsxs("button",{className:"nc-deck-newbtn",disabled:I||H.decks.every(X=>X.available===!1),title:`${g("new-deck")} · ${H.label}`,onClick:()=>{R(""),C(H.key)},children:["+ ",g("new")]})]})]},H.key)})}),c.jsx("span",{className:`nc-deck-state ${p}`,title:g("deck-autosave"),children:g(p==="saving"?"saving":p==="saved"?"saved":"deck-autosave")}),(G||f)&&c.jsx("span",{className:"nc-deck-error",children:G||f}),D&&c.jsx("button",{className:"nc-deck-fallback",onClick:()=>u&&u(D),children:g("popup-blocked")})]})}function GE({state:e}){if(!e)return null;const t=g(`dot-${e}`);return c.jsx("span",{className:`nc-deck-dot ${e}`,role:"img","aria-label":t,title:t})}var ms={},Yu,Iv;function XE(){return Iv||(Iv=1,Yu=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Yu}var Gu={},rr={},Bv;function $r(){if(Bv)return rr;Bv=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return rr.getSymbolSize=function(s){if(!s)throw new Error('"version" cannot be null or undefined');if(s<1||s>40)throw new Error('"version" should be in range from 1 to 40');return s*4+17},rr.getSymbolTotalCodewords=function(s){return t[s]},rr.getBCHDigit=function(n){let s=0;for(;n!==0;)s++,n>>>=1;return s},rr.setToSJISFunction=function(s){if(typeof s!="function")throw new Error('"toSJISFunc" is not a valid function.');e=s},rr.isKanjiModeEnabled=function(){return typeof e<"u"},rr.toSJIS=function(s){return e(s)},rr}var Xu={},Ov;function nf(){return Ov||(Ov=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(s){return s&&typeof s.bit<"u"&&s.bit>=0&&s.bit<4},e.from=function(s,o){if(e.isValid(s))return s;try{return t(s)}catch{return o}}})(Xu)),Xu}var Ju,zv;function JE(){if(zv)return Ju;zv=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const n=Math.floor(t/8);return(this.buffer[n]>>>7-t%8&1)===1},put:function(t,n){for(let s=0;s<n;s++)this.putBit((t>>>n-s-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),t&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Ju=e,Ju}var Qu,Fv;function QE(){if(Fv)return Qu;Fv=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,n,s,o){const a=t*this.size+n;this.data[a]=s,o&&(this.reservedBit[a]=!0)},e.prototype.get=function(t,n){return this.data[t*this.size+n]},e.prototype.xor=function(t,n,s){this.data[t*this.size+n]^=s},e.prototype.isReserved=function(t,n){return this.reservedBit[t*this.size+n]},Qu=e,Qu}var Zu={},$v;function ZE(){return $v||($v=1,(function(e){const t=$r().getSymbolSize;e.getRowColCoords=function(s){if(s===1)return[];const o=Math.floor(s/7)+2,a=t(s),u=a===145?26:Math.ceil((a-13)/(2*o-2))*2,h=[a-7];for(let p=1;p<o-1;p++)h[p]=h[p-1]-u;return h.push(6),h.reverse()},e.getPositions=function(s){const o=[],a=e.getRowColCoords(s),u=a.length;for(let h=0;h<u;h++)for(let p=0;p<u;p++)h===0&&p===0||h===0&&p===u-1||h===u-1&&p===0||o.push([a[h],a[p]]);return o}})(Zu)),Zu}var ed={},Hv;function e2(){if(Hv)return ed;Hv=1;const e=$r().getSymbolSize,t=7;return ed.getPositions=function(s){const o=e(s);return[[0,0],[o-t,0],[0,o-t]]},ed}var td={},Wv;function t2(){return Wv||(Wv=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const a=o.size;let u=0,h=0,p=0,f=null,_=null;for(let b=0;b<a;b++){h=p=0,f=_=null;for(let y=0;y<a;y++){let w=o.get(b,y);w===f?h++:(h>=5&&(u+=t.N1+(h-5)),f=w,h=1),w=o.get(y,b),w===_?p++:(p>=5&&(u+=t.N1+(p-5)),_=w,p=1)}h>=5&&(u+=t.N1+(h-5)),p>=5&&(u+=t.N1+(p-5))}return u},e.getPenaltyN2=function(o){const a=o.size;let u=0;for(let h=0;h<a-1;h++)for(let p=0;p<a-1;p++){const f=o.get(h,p)+o.get(h,p+1)+o.get(h+1,p)+o.get(h+1,p+1);(f===4||f===0)&&u++}return u*t.N2},e.getPenaltyN3=function(o){const a=o.size;let u=0,h=0,p=0;for(let f=0;f<a;f++){h=p=0;for(let _=0;_<a;_++)h=h<<1&2047|o.get(f,_),_>=10&&(h===1488||h===93)&&u++,p=p<<1&2047|o.get(_,f),_>=10&&(p===1488||p===93)&&u++}return u*t.N3},e.getPenaltyN4=function(o){let a=0;const u=o.data.length;for(let p=0;p<u;p++)a+=o.data[p];return Math.abs(Math.ceil(a*100/u/5)-10)*t.N4};function n(s,o,a){switch(s){case e.Patterns.PATTERN000:return(o+a)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return a%3===0;case e.Patterns.PATTERN011:return(o+a)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(a/3))%2===0;case e.Patterns.PATTERN101:return o*a%2+o*a%3===0;case e.Patterns.PATTERN110:return(o*a%2+o*a%3)%2===0;case e.Patterns.PATTERN111:return(o*a%3+(o+a)%2)%2===0;default:throw new Error("bad maskPattern:"+s)}}e.applyMask=function(o,a){const u=a.size;for(let h=0;h<u;h++)for(let p=0;p<u;p++)a.isReserved(p,h)||a.xor(p,h,n(o,p,h))},e.getBestMask=function(o,a){const u=Object.keys(e.Patterns).length;let h=0,p=1/0;for(let f=0;f<u;f++){a(f),e.applyMask(f,o);const _=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(f,o),_<p&&(p=_,h=f)}return h}})(td)),td}var sl={},Uv;function kw(){if(Uv)return sl;Uv=1;const e=nf(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return sl.getBlocksCount=function(o,a){switch(a){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},sl.getTotalCodewordsCount=function(o,a){switch(a){case e.L:return n[(o-1)*4+0];case e.M:return n[(o-1)*4+1];case e.Q:return n[(o-1)*4+2];case e.H:return n[(o-1)*4+3];default:return}},sl}var nd={},yo={},Kv;function n2(){if(Kv)return yo;Kv=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let s=1;for(let o=0;o<255;o++)e[o]=s,t[s]=o,s<<=1,s&256&&(s^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),yo.log=function(s){if(s<1)throw new Error("log("+s+")");return t[s]},yo.exp=function(s){return e[s]},yo.mul=function(s,o){return s===0||o===0?0:e[t[s]+t[o]]},yo}var qv;function i2(){return qv||(qv=1,(function(e){const t=n2();e.mul=function(s,o){const a=new Uint8Array(s.length+o.length-1);for(let u=0;u<s.length;u++)for(let h=0;h<o.length;h++)a[u+h]^=t.mul(s[u],o[h]);return a},e.mod=function(s,o){let a=new Uint8Array(s);for(;a.length-o.length>=0;){const u=a[0];for(let p=0;p<o.length;p++)a[p]^=t.mul(o[p],u);let h=0;for(;h<a.length&&a[h]===0;)h++;a=a.slice(h)}return a},e.generateECPolynomial=function(s){let o=new Uint8Array([1]);for(let a=0;a<s;a++)o=e.mul(o,new Uint8Array([1,t.exp(a)]));return o}})(nd)),nd}var id,Vv;function r2(){if(Vv)return id;Vv=1;const e=i2();function t(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(s){this.degree=s,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(s){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(s.length+this.degree);o.set(s);const a=e.mod(o,this.genPoly),u=this.degree-a.length;if(u>0){const h=new Uint8Array(this.degree);return h.set(a,u),h}return a},id=t,id}var rd={},sd={},od={},Yv;function xw(){return Yv||(Yv=1,od.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),od}var fi={},Gv;function Cw(){if(Gv)return fi;Gv=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const s="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
82
82
  ]))+`;fi.KANJI=new RegExp(n,"g"),fi.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),fi.BYTE=new RegExp(s,"g"),fi.NUMERIC=new RegExp(e,"g"),fi.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+n+"$"),a=new RegExp("^"+e+"$"),u=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return fi.testKanji=function(p){return o.test(p)},fi.testNumeric=function(p){return a.test(p)},fi.testAlphanumeric=function(p){return u.test(p)},fi}var Xv;function Hr(){return Xv||(Xv=1,(function(e){const t=xw(),n=Cw();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(a,u){if(!a.ccBits)throw new Error("Invalid mode: "+a);if(!t.isValid(u))throw new Error("Invalid version: "+u);return u>=1&&u<10?a.ccBits[0]:u<27?a.ccBits[1]:a.ccBits[2]},e.getBestModeForData=function(a){return n.testNumeric(a)?e.NUMERIC:n.testAlphanumeric(a)?e.ALPHANUMERIC:n.testKanji(a)?e.KANJI:e.BYTE},e.toString=function(a){if(a&&a.id)return a.id;throw new Error("Invalid mode")},e.isValid=function(a){return a&&a.bit&&a.ccBits};function s(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(a,u){if(e.isValid(a))return a;try{return s(a)}catch{return u}}})(sd)),sd}var Jv;function s2(){return Jv||(Jv=1,(function(e){const t=$r(),n=kw(),s=nf(),o=Hr(),a=xw(),u=7973,h=t.getBCHDigit(u);function p(y,w,S){for(let x=1;x<=40;x++)if(w<=e.getCapacity(x,S,y))return x}function f(y,w){return o.getCharCountIndicator(y,w)+4}function _(y,w){let S=0;return y.forEach(function(x){const C=f(x.mode,w);S+=C+x.getBitsLength()}),S}function b(y,w){for(let S=1;S<=40;S++)if(_(y,S)<=e.getCapacity(S,w,o.MIXED))return S}e.from=function(w,S){return a.isValid(w)?parseInt(w,10):S},e.getCapacity=function(w,S,x){if(!a.isValid(w))throw new Error("Invalid QR Code version");typeof x>"u"&&(x=o.BYTE);const C=t.getSymbolTotalCodewords(w),k=n.getTotalCodewordsCount(w,S),R=(C-k)*8;if(x===o.MIXED)return R;const I=R-f(x,w);switch(x){case o.NUMERIC:return Math.floor(I/10*3);case o.ALPHANUMERIC:return Math.floor(I/11*2);case o.KANJI:return Math.floor(I/13);case o.BYTE:default:return Math.floor(I/8)}},e.getBestVersionForData=function(w,S){let x;const C=s.from(S,s.M);if(Array.isArray(w)){if(w.length>1)return b(w,C);if(w.length===0)return 1;x=w[0]}else x=w;return p(x.mode,x.getLength(),C)},e.getEncodedBits=function(w){if(!a.isValid(w)||w<7)throw new Error("Invalid QR Code version");let S=w<<12;for(;t.getBCHDigit(S)-h>=0;)S^=u<<t.getBCHDigit(S)-h;return w<<12|S}})(rd)),rd}var ad={},Qv;function o2(){if(Qv)return ad;Qv=1;const e=$r(),t=1335,n=21522,s=e.getBCHDigit(t);return ad.getEncodedBits=function(a,u){const h=a.bit<<3|u;let p=h<<10;for(;e.getBCHDigit(p)-s>=0;)p^=t<<e.getBCHDigit(p)-s;return(h<<10|p)^n},ad}var ld={},cd,Zv;function a2(){if(Zv)return cd;Zv=1;const e=Hr();function t(n){this.mode=e.NUMERIC,this.data=n.toString()}return t.getBitsLength=function(s){return 10*Math.floor(s/3)+(s%3?s%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(s){let o,a,u;for(o=0;o+3<=this.data.length;o+=3)a=this.data.substr(o,3),u=parseInt(a,10),s.put(u,10);const h=this.data.length-o;h>0&&(a=this.data.substr(o),u=parseInt(a,10),s.put(u,h*3+1))},cd=t,cd}var ud,e_;function l2(){if(e_)return ud;e_=1;const e=Hr(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(s){this.mode=e.ALPHANUMERIC,this.data=s}return n.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(o){let a;for(a=0;a+2<=this.data.length;a+=2){let u=t.indexOf(this.data[a])*45;u+=t.indexOf(this.data[a+1]),o.put(u,11)}this.data.length%2&&o.put(t.indexOf(this.data[a]),6)},ud=n,ud}var dd,t_;function c2(){if(t_)return dd;t_=1;const e=Hr();function t(n){this.mode=e.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return t.getBitsLength=function(s){return s*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){for(let s=0,o=this.data.length;s<o;s++)n.put(this.data[s],8)},dd=t,dd}var hd,n_;function u2(){if(n_)return hd;n_=1;const e=Hr(),t=$r();function n(s){this.mode=e.KANJI,this.data=s}return n.getBitsLength=function(o){return o*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(s){let o;for(o=0;o<this.data.length;o++){let a=t.toSJIS(this.data[o]);if(a>=33088&&a<=40956)a-=33088;else if(a>=57408&&a<=60351)a-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
83
83
  Make sure your charset is UTF-8`);a=(a>>>8&255)*192+(a&255),s.put(a,13)}},hd=n,hd}var fd={exports:{}},i_;function d2(){return i_||(i_=1,(function(e){var t={single_source_shortest_paths:function(n,s,o){var a={},u={};u[s]=0;var h=t.PriorityQueue.make();h.push(s,0);for(var p,f,_,b,y,w,S,x,C;!h.empty();){p=h.pop(),f=p.value,b=p.cost,y=n[f]||{};for(_ in y)y.hasOwnProperty(_)&&(w=y[_],S=b+w,x=u[_],C=typeof u[_]>"u",(C||x>S)&&(u[_]=S,h.push(_,S),a[_]=f))}if(typeof o<"u"&&typeof u[o]>"u"){var k=["Could not find a path from ",s," to ",o,"."].join("");throw new Error(k)}return a},extract_shortest_path_from_predecessor_list:function(n,s){for(var o=[],a=s;a;)o.push(a),n[a],a=n[a];return o.reverse(),o},find_path:function(n,s,o){var a=t.single_source_shortest_paths(n,s,o);return t.extract_shortest_path_from_predecessor_list(a,o)},PriorityQueue:{make:function(n){var s=t.PriorityQueue,o={},a;n=n||{};for(a in s)s.hasOwnProperty(a)&&(o[a]=s[a]);return o.queue=[],o.sorter=n.sorter||s.default_sorter,o},default_sorter:function(n,s){return n.cost-s.cost},push:function(n,s){var o={value:n,cost:s};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(fd)),fd.exports}var r_;function h2(){return r_||(r_=1,(function(e){const t=Hr(),n=a2(),s=l2(),o=c2(),a=u2(),u=Cw(),h=$r(),p=d2();function f(k){return unescape(encodeURIComponent(k)).length}function _(k,R,I){const A=[];let G;for(;(G=k.exec(I))!==null;)A.push({data:G[0],index:G.index,mode:R,length:G[0].length});return A}function b(k){const R=_(u.NUMERIC,t.NUMERIC,k),I=_(u.ALPHANUMERIC,t.ALPHANUMERIC,k);let A,G;return h.isKanjiModeEnabled()?(A=_(u.BYTE,t.BYTE,k),G=_(u.KANJI,t.KANJI,k)):(A=_(u.BYTE_KANJI,t.BYTE,k),G=[]),R.concat(I,A,G).sort(function(D,J){return D.index-J.index}).map(function(D){return{data:D.data,mode:D.mode,length:D.length}})}function y(k,R){switch(R){case t.NUMERIC:return n.getBitsLength(k);case t.ALPHANUMERIC:return s.getBitsLength(k);case t.KANJI:return a.getBitsLength(k);case t.BYTE:return o.getBitsLength(k)}}function w(k){return k.reduce(function(R,I){const A=R.length-1>=0?R[R.length-1]:null;return A&&A.mode===I.mode?(R[R.length-1].data+=I.data,R):(R.push(I),R)},[])}function S(k){const R=[];for(let I=0;I<k.length;I++){const A=k[I];switch(A.mode){case t.NUMERIC:R.push([A,{data:A.data,mode:t.ALPHANUMERIC,length:A.length},{data:A.data,mode:t.BYTE,length:A.length}]);break;case t.ALPHANUMERIC:R.push([A,{data:A.data,mode:t.BYTE,length:A.length}]);break;case t.KANJI:R.push([A,{data:A.data,mode:t.BYTE,length:f(A.data)}]);break;case t.BYTE:R.push([{data:A.data,mode:t.BYTE,length:f(A.data)}])}}return R}function x(k,R){const I={},A={start:{}};let G=["start"];for(let F=0;F<k.length;F++){const D=k[F],J=[];for(let W=0;W<D.length;W++){const ee=D[W],K=""+F+W;J.push(K),I[K]={node:ee,lastCount:0},A[K]={};for(let O=0;O<G.length;O++){const j=G[O];I[j]&&I[j].node.mode===ee.mode?(A[j][K]=y(I[j].lastCount+ee.length,ee.mode)-y(I[j].lastCount,ee.mode),I[j].lastCount+=ee.length):(I[j]&&(I[j].lastCount=ee.length),A[j][K]=y(ee.length,ee.mode)+4+t.getCharCountIndicator(ee.mode,R))}}G=J}for(let F=0;F<G.length;F++)A[G[F]].end=0;return{map:A,table:I}}function C(k,R){let I;const A=t.getBestModeForData(k);if(I=t.from(R,A),I!==t.BYTE&&I.bit<A.bit)throw new Error('"'+k+'" cannot be encoded with mode '+t.toString(I)+`.
84
84
  Suggested mode is: `+t.toString(A));switch(I===t.KANJI&&!h.isKanjiModeEnabled()&&(I=t.BYTE),I){case t.NUMERIC:return new n(k);case t.ALPHANUMERIC:return new s(k);case t.KANJI:return new a(k);case t.BYTE:return new o(k)}}e.fromArray=function(R){return R.reduce(function(I,A){return typeof A=="string"?I.push(C(A,null)):A.data&&I.push(C(A.data,A.mode)),I},[])},e.fromString=function(R,I){const A=b(R,h.isKanjiModeEnabled()),G=S(A),F=x(G,I),D=p.find_path(F.map,"start","end"),J=[];for(let W=1;W<D.length-1;W++)J.push(F.table[D[W]].node);return e.fromArray(w(J))},e.rawSplit=function(R){return e.fromArray(b(R,h.isKanjiModeEnabled()))}})(ld)),ld}var s_;function f2(){if(s_)return Gu;s_=1;const e=$r(),t=nf(),n=JE(),s=QE(),o=ZE(),a=e2(),u=t2(),h=kw(),p=r2(),f=s2(),_=o2(),b=Hr(),y=h2();function w(F,D){const J=F.size,W=a.getPositions(D);for(let ee=0;ee<W.length;ee++){const K=W[ee][0],O=W[ee][1];for(let j=-1;j<=7;j++)if(!(K+j<=-1||J<=K+j))for(let P=-1;P<=7;P++)O+P<=-1||J<=O+P||(j>=0&&j<=6&&(P===0||P===6)||P>=0&&P<=6&&(j===0||j===6)||j>=2&&j<=4&&P>=2&&P<=4?F.set(K+j,O+P,!0,!0):F.set(K+j,O+P,!1,!0))}}function S(F){const D=F.size;for(let J=8;J<D-8;J++){const W=J%2===0;F.set(J,6,W,!0),F.set(6,J,W,!0)}}function x(F,D){const J=o.getPositions(D);for(let W=0;W<J.length;W++){const ee=J[W][0],K=J[W][1];for(let O=-2;O<=2;O++)for(let j=-2;j<=2;j++)O===-2||O===2||j===-2||j===2||O===0&&j===0?F.set(ee+O,K+j,!0,!0):F.set(ee+O,K+j,!1,!0)}}function C(F,D){const J=F.size,W=f.getEncodedBits(D);let ee,K,O;for(let j=0;j<18;j++)ee=Math.floor(j/3),K=j%3+J-8-3,O=(W>>j&1)===1,F.set(ee,K,O,!0),F.set(K,ee,O,!0)}function k(F,D,J){const W=F.size,ee=_.getEncodedBits(D,J);let K,O;for(K=0;K<15;K++)O=(ee>>K&1)===1,K<6?F.set(K,8,O,!0):K<8?F.set(K+1,8,O,!0):F.set(W-15+K,8,O,!0),K<8?F.set(8,W-K-1,O,!0):K<9?F.set(8,15-K-1+1,O,!0):F.set(8,15-K-1,O,!0);F.set(W-8,8,1,!0)}function R(F,D){const J=F.size;let W=-1,ee=J-1,K=7,O=0;for(let j=J-1;j>0;j-=2)for(j===6&&j--;;){for(let P=0;P<2;P++)if(!F.isReserved(ee,j-P)){let M=!1;O<D.length&&(M=(D[O]>>>K&1)===1),F.set(ee,j-P,M),K--,K===-1&&(O++,K=7)}if(ee+=W,ee<0||J<=ee){ee-=W,W=-W;break}}}function I(F,D,J){const W=new n;J.forEach(function(P){W.put(P.mode.bit,4),W.put(P.getLength(),b.getCharCountIndicator(P.mode,F)),P.write(W)});const ee=e.getSymbolTotalCodewords(F),K=h.getTotalCodewordsCount(F,D),O=(ee-K)*8;for(W.getLengthInBits()+4<=O&&W.put(0,4);W.getLengthInBits()%8!==0;)W.putBit(0);const j=(O-W.getLengthInBits())/8;for(let P=0;P<j;P++)W.put(P%2?17:236,8);return A(W,F,D)}function A(F,D,J){const W=e.getSymbolTotalCodewords(D),ee=h.getTotalCodewordsCount(D,J),K=W-ee,O=h.getBlocksCount(D,J),j=W%O,P=O-j,M=Math.floor(W/O),H=Math.floor(K/O),te=H+1,T=M-H,ie=new p(T);let B=0;const L=new Array(O),$=new Array(O);let X=0;const ae=new Uint8Array(F.buffer);for(let fe=0;fe<O;fe++){const Ie=fe<P?H:te;L[fe]=ae.slice(B,B+Ie),$[fe]=ie.encode(L[fe]),B+=Ie,X=Math.max(X,Ie)}const ue=new Uint8Array(W);let ge=0,Z,q;for(Z=0;Z<X;Z++)for(q=0;q<O;q++)Z<L[q].length&&(ue[ge++]=L[q][Z]);for(Z=0;Z<T;Z++)for(q=0;q<O;q++)ue[ge++]=$[q][Z];return ue}function G(F,D,J,W){let ee;if(Array.isArray(F))ee=y.fromArray(F);else if(typeof F=="string"){let M=D;if(!M){const H=y.rawSplit(F);M=f.getBestVersionForData(H,J)}ee=y.fromString(F,M||40)}else throw new Error("Invalid data");const K=f.getBestVersionForData(ee,J);if(!K)throw new Error("The amount of data is too big to be stored in a QR Code");if(!D)D=K;else if(D<K)throw new Error(`
@@ -90,4 +90,4 @@ Minimum version required to store current data is: `+K+`.
90
90
  `).filter(o=>o!==""),promptMode:e.promptMode};return e.modelFlag&&(s.model={flag:e.modelFlag,value:e.modelValue||""}),e.promptMode==="flag"&&(s.promptFlag=e.promptFlag),t&&(s.env=Object.fromEntries(e.envRows.filter(o=>!o.remove&&o.key).map(o=>[o.key,o.value]))),s}function Nr({children:e,onClose:t,label:n,error:s=""}){const o=N.useRef(null),a=N.useRef(null),u=N.useRef(t);return u.current=t,N.useEffect(()=>{const h=document.activeElement,p=o.current,f=()=>Array.from((p==null?void 0:p.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'))||[]).filter(y=>y.offsetParent!==null),_=requestAnimationFrame(()=>{var y;return(y=f()[0]||p)==null?void 0:y.focus({preventScroll:!0})}),b=y=>{var C;if(y.key==="Escape"){y.preventDefault(),(C=u.current)==null||C.call(u);return}if(y.key!=="Tab")return;const w=f();if(!w.length){y.preventDefault(),p==null||p.focus();return}const S=w[0],x=w[w.length-1];y.shiftKey&&document.activeElement===S?(y.preventDefault(),x.focus()):!y.shiftKey&&document.activeElement===x&&(y.preventDefault(),S.focus())};return document.addEventListener("keydown",b),()=>{cancelAnimationFrame(_),document.removeEventListener("keydown",b),h&&h.isConnected&&typeof h.focus=="function"&&h.focus({preventScroll:!0})}},[]),N.useEffect(()=>{s&&requestAnimationFrame(()=>{var h;return(h=a.current)==null?void 0:h.scrollIntoView({block:"nearest"})})},[s]),c.jsx("div",{className:"nc-fleet-modal",role:"presentation",onMouseDown:h=>{h.target===h.currentTarget&&t()},children:c.jsxs("div",{ref:o,className:"nc-fleet-modal-dialog",role:"dialog","aria-modal":"true","aria-label":n||g("settings"),tabIndex:-1,children:[e,s&&c.jsx("div",{ref:a,className:"nc-err nc-fleet-modal-error",role:"alert","aria-live":"assertive",children:s})]})})}function vd({token:e,targets:t=[],readonly:n=!1,onPower:s,onImport:o}){const[a,u]=N.useState([]),[h,p]=N.useState(0);N.useEffect(()=>{let C=!0;async function k(){const I=[{route:[],label:g("local")}].concat((t||[]).map(G=>({route:Array.isArray(G.route)?G.route:[],label:G.label||(G.route||[]).join(" › ")}))),A=await Promise.all(I.map(async G=>{const F={...G,available:!1,readonly:!1,capabilities:[],provider:null,cells:[],unmanaged:[],err:""};try{const D=await zr(e,G.route);F.available=!!D.available,F.capabilities=D.capabilities||[],F.provider=D.provider||null,F.cells=(D.cells||[]).map(J=>({...J,route:G.route}));try{F.readonly=!!(await Nh(e,G.route)).readonlyDefault}catch{}try{const J=await M_(e,G.route),W=new Set(F.cells.map(ee=>ee.tmuxSession).filter(Boolean));F.unmanaged=(J.sessions||[]).filter(ee=>ee&&!W.has(ee.name))}catch{}}catch(D){F.err=String(D&&D.message||D)}return F}));C&&u(A)}k();const R=setInterval(k,6e3);return()=>{C=!1,clearInterval(R)}},[e,t,h]);const f=(C,k)=>Array.isArray(C.capabilities)&&C.capabilities.includes(k)&&!n&&!C.readonly,_=()=>p(C=>C+1),b=(C,k)=>{s&&s({...C,route:k})},y=(C,k)=>{s&&s({...C,route:k})},w=async(C,k)=>{try{await So(e,C.cell,k)}catch{}_()},S=async(C,k)=>{if(window.confirm(g("fleet-remove-cell").replace("{id}",C.cell))){try{await L_(e,C.cell,!0,k)}catch{}_()}},x=async(C,k)=>{if(window.confirm(g("terminate-confirm").replace("{name}",C.name))){try{await Ch(e,C.name,k)}catch{}_()}};return c.jsxs("div",{className:"nc-fleet-inventory",children:[c.jsxs("div",{className:"nc-fleet-section-head",children:[c.jsx("b",{children:g("fleet-inventory")}),c.jsx("small",{children:g("fleet-inventory-help")})]}),a.map(C=>{const k=C.route.length?C.route.join("/"):"local";return c.jsxs("div",{className:"nc-fleet-pos",children:[c.jsxs("div",{className:"nc-fleet-pos-title",children:[c.jsx("span",{className:`dot ${C.available?"on":"warn"}`}),c.jsx("b",{children:C.label}),c.jsx("small",{children:C.available?`${C.cells.length} ${g("fleet-cells")} · ${C.unmanaged.length} ${g("fleet-tmux")}`:C.err||g("fleet-not-available")})]}),C.cells.map(R=>c.jsxs("div",{className:"nc-fleet-item nc-fleet-cell",children:[c.jsxs("span",{children:[c.jsx("b",{children:R.cell}),c.jsx("small",{children:`${R.engine||""}${R.key?`·${R.key}`:""}${R.active?"":` · ${g("cell-off")}`}`})]}),c.jsxs("span",{className:"nc-fleet-cell-actions",children:[R.active&&f(C,"down")&&c.jsx("button",{className:"nc-btn ghost",title:g("power-off"),onClick:()=>y(R,C.route),children:g("stop")}),!R.active&&f(C,"up")&&c.jsx("button",{className:"nc-btn ghost",title:g("power-on"),onClick:()=>b(R,C.route),children:g("start")}),f(C,"restart")&&R.active&&c.jsx("button",{className:"nc-btn ghost",title:g("restart"),onClick:()=>w(R,C.route),children:g("restart")}),f(C,"remove")&&c.jsx("button",{className:"nc-btn danger",title:g("delete"),onClick:()=>S(R,C.route),children:"×"})]})]},`${k}:${R.cell}`)),C.unmanaged.map(R=>c.jsxs("div",{className:"nc-fleet-item nc-fleet-unmanaged",children:[c.jsxs("span",{children:[c.jsx("b",{children:R.name}),c.jsx("small",{children:g("fleet-tmux")})]}),c.jsxs("span",{className:"nc-fleet-cell-actions",children:[f(C,"import")&&o&&c.jsx("button",{className:"nc-btn ghost",title:g("import-as-cell"),onClick:()=>o(R,C.route),children:g("import-as-cell")}),c.jsx("button",{className:"nc-btn danger",title:g("terminate"),onClick:()=>x(R,C.route),children:"×"})]})]},`${k}:u:${R.name}`)),C.available&&C.cells.length===0&&C.unmanaged.length===0&&c.jsx("div",{className:"nc-empty",children:g("fleet-inventory-empty")})]},k)})]})}function Z2({cells:e=[],engines:t=[],busy:n,canRestore:s=!1,onRestore:o,onClose:a}){const[u,h]=N.useState("export"),[p,f]=N.useState(()=>new Set(e.map(j=>j.id))),[_,b]=N.useState(()=>new Set(t.map(j=>j.id))),[y,w]=N.useState([]),[S,x]=N.useState([]),[C,k]=N.useState(""),R=new Set(t.map(j=>j.id)),I=new Set(e.map(j=>j.id)),A=(j,P)=>j(M=>{const H=new Set(M);return H.has(P)?H.delete(P):H.add(P),H}),G=()=>{const j=q2(e,p,t,_);if(j.ok===!1){k(g(`fleet-backup-${j.error}`));return}const P=e.filter(ie=>p.has(ie.id)).length,M=t.filter(ie=>_.has(ie.id)).length;if(j.cells.length!==P){k(g("fleet-backup-invalid-cell"));return}if(j.engines.length!==M){k(g("fleet-backup-invalid-engine"));return}if(!j.cells.length&&!j.engines.length){k(g("fleet-backup-select-one"));return}const H=new Blob([`${JSON.stringify(j,null,2)}
91
91
  `],{type:"application/json"}),te=URL.createObjectURL(H),T=document.createElement("a");T.href=te,T.download=`nexuscrew-fleet-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(T),T.click(),T.remove(),setTimeout(()=>URL.revokeObjectURL(te),0),k("")},F=async j=>{if(k(""),w([]),x([]),!!j){if(j.size>1024*1024){k(g("fleet-backup-too-large"));return}try{const P=V2(await j.text());if(!P.ok){k(g(`fleet-backup-${P.error}`));return}const M=new Set(P.engines.map(H=>H.id));x(P.engines.map(H=>({engine:H,exists:R.has(H.id),selected:!R.has(H.id)}))),w(P.cells.map(H=>{const te=R.has(H.engine)||M.has(H.engine),T=I.has(H.id);return{cell:H,engine:te?H.engine:"",selected:te&&!T,exists:T}}))}catch(P){k(String(P.message||P))}}},D=(j,P)=>w(M=>M.map((H,te)=>te===j?{...H,...P}:H)),J=(j,P)=>x(M=>M.map((H,te)=>te===j?{...H,...P}:H)),W=new Set([...R,...S.filter(j=>j.selected).map(j=>j.engine.id)]),ee=y.filter(j=>j.selected&&j.engine&&W.has(j.engine)),K=S.filter(j=>j.selected),O=[...new Map([...t.map(j=>[j.id,j.label||j.id]),...S.filter(j=>j.selected).map(j=>[j.engine.id,j.engine.label||j.engine.id])]).entries()];return c.jsxs("div",{className:"nc-set-form nc-fleet-form nc-backup-dialog",children:[c.jsx("b",{children:g("fleet-backup")}),c.jsx("small",{children:g("fleet-backup-help")}),c.jsxs("div",{className:"nc-set-tabs nc-backup-tabs",children:[c.jsx("button",{type:"button",className:`nc-set-tabbtn${u==="export"?" on":""}`,onClick:()=>{h("export"),k("")},children:g("fleet-backup-export")}),c.jsx("button",{type:"button",className:`nc-set-tabbtn${u==="import"?" on":""}`,disabled:!s,title:s?"":g("fleet-backup-restore-unavailable"),onClick:()=>{h("import"),k("")},children:g("fleet-backup-import")})]}),u==="export"?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{f(new Set(e.map(j=>j.id))),b(new Set(t.map(j=>j.id)))},children:g("select-all")}),c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{f(new Set),b(new Set)},children:g("select-none")})]}),c.jsxs("div",{className:"nc-backup-list",children:[c.jsx("b",{children:g("fleet-engines")}),t.map(j=>{var P;return c.jsxs("label",{className:"nc-check nc-backup-row",children:[c.jsx("input",{type:"checkbox",checked:_.has(j.id),onChange:()=>A(b,j.id)}),c.jsxs("span",{children:[c.jsx("b",{children:j.label||j.id}),c.jsxs("small",{children:[j.id,(P=j.envKeys)!=null&&P.length?` · ${j.envKeys.length} ${g("fleet-backup-env-names")}`:""]})]})]},j.id)}),c.jsx("b",{children:g("fleet-cells")}),e.map(j=>c.jsxs("label",{className:"nc-check nc-backup-row",children:[c.jsx("input",{type:"checkbox",checked:p.has(j.id),onChange:()=>A(f,j.id)}),c.jsxs("span",{children:[c.jsx("b",{children:j.id}),c.jsxs("small",{children:[j.engine," · ",g("fleet-system-prompt")," ",(j.prompt||"").length," ",g("characters")]})]})]},j.id)),!e.length&&!t.length&&c.jsx("div",{className:"nc-empty",children:g("fleet-backup-empty")})]}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:a,children:g("cancel")}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:!p.size&&!_.size,onClick:G,children:g("fleet-backup-download")})]})]}):c.jsxs(c.Fragment,{children:[c.jsx("input",{type:"file",accept:"application/json,.json",disabled:n,onChange:j=>F(j.target.files&&j.target.files[0])}),c.jsx("small",{children:g("fleet-backup-import-help")}),!!(y.length||S.length)&&c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{x(j=>j.map(P=>({...P,selected:!0}))),w(j=>j.map(P=>({...P,selected:!!P.engine})))},children:g("select-all")}),c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{x(j=>j.map(P=>({...P,selected:!1}))),w(j=>j.map(P=>({...P,selected:!1})))},children:g("select-none")})]}),c.jsxs("div",{className:"nc-backup-list",children:[!!S.length&&c.jsx("b",{children:g("fleet-engines")}),S.map((j,P)=>{var M;return c.jsx("div",{className:"nc-backup-import-row",children:c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:j.selected,onChange:H=>J(P,{selected:H.target.checked})}),c.jsxs("span",{children:[c.jsx("b",{children:j.engine.label||j.engine.id}),c.jsxs("small",{children:[j.engine.id," · ",j.exists?g("fleet-backup-overwrite"):g("fleet-backup-new"),(M=j.engine.envKeys)!=null&&M.length?` · ${g("fleet-backup-env-values-required")}`:""]})]})]})},j.engine.id)}),!!y.length&&c.jsx("b",{children:g("fleet-cells")}),y.map((j,P)=>c.jsxs("div",{className:"nc-backup-import-row",children:[c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:j.selected,disabled:!j.engine||!W.has(j.engine),onChange:M=>D(P,{selected:M.target.checked})}),c.jsxs("span",{children:[c.jsx("b",{children:j.cell.id}),c.jsxs("small",{children:[j.exists?g("fleet-backup-overwrite"):g("fleet-backup-new")," · ",g("fleet-system-prompt")," ",j.cell.systemPrompt.length," ",g("characters")]})]})]}),c.jsxs("select",{value:j.engine,onChange:M=>D(P,{engine:M.target.value,selected:!!M.target.value}),children:[c.jsx("option",{value:"",children:g("fleet-backup-engine-missing")}),O.map(([M,H])=>c.jsx("option",{value:M,children:H},M))]})]},j.cell.id))]}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:a,children:g("cancel")}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||!ee.length&&!K.length,onClick:()=>o({engineRows:S,cellRows:y}),children:g("fleet-backup-restore")})]})]}),C&&c.jsx("div",{className:"nc-err",children:C})]})}function eN({state:e,setState:t,busy:n,onSave:s,catalog:o}){var C;const a=e.form,u=k=>t({...e,form:{...a,...k}}),h=a.envRows||[],p=[...new Map(o.map(k=>[k.client,k.clientLabel||k.client])).entries()],f=o.filter(k=>k.client===a.client),_=Do(o,a),b=typeof(_==null?void 0:_.credentialEnv)=="string"?_.credentialEnv:"",y=Array.isArray(_==null?void 0:_.credentialUsedBy)?_.credentialUsedBy:[],w=(_==null?void 0:_.credentialSource)||"missing",S=!!b&&e.mode==="new"&&(_==null?void 0:_.authConfigured)!==!0&&!a.credentialValue&&!a.allowMissingCredential,x=k=>{k&&u({client:k.client,provider:k.provider,credentialProfile:k.credentialProfile||"",managedModel:k.model||"",protocol:k.protocol||"",permissionPolicy:k.permissionPolicyDefault||"standard",rc:!!k.rc,displayName:k.custom?g("fleet-custom-provider-default"):"",baseUrl:k.custom?"":k.endpoint||"",envKey:k.defaultEnvKey||"",providerId:"nexuscrew-custom",credentialValue:"",credentialReveal:!1,allowMissingCredential:!1,...e.mode==="new"?{id:k.id,label:""}:{}})};return c.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[c.jsx("b",{children:e.mode==="new"?g("fleet-new-engine"):`${g("edit")} ${a.id}`}),c.jsx("input",{value:a.id,disabled:e.mode!=="new",placeholder:"id",onChange:k=>u({id:k.target.value})}),c.jsx("input",{value:a.label,placeholder:g("label"),onChange:k=>u({label:k.target.value})}),c.jsxs("select",{value:a.kind,disabled:e.mode!=="new",onChange:k=>u({kind:k.target.value}),children:[c.jsx("option",{value:"managed",children:g("fleet-managed")}),c.jsx("option",{value:"custom",children:g("fleet-custom")})]}),a.kind==="managed"?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"nc-fleet-pair",children:[c.jsx("select",{value:a.client,disabled:e.mode!=="new",onChange:k=>x(o.find(R=>R.client===k.target.value&&R.default)||o.find(R=>R.client===k.target.value)),children:p.map(([k,R])=>c.jsx("option",{value:k,children:R},k))}),c.jsx("select",{value:((C=Do(o,a))==null?void 0:C.id)||"",disabled:e.mode!=="new",onChange:k=>x(o.find(R=>R.id===k.target.value)),children:f.map(k=>c.jsx("option",{value:k.id,children:k.label},k.id))})]}),a.client!=="shell"&&c.jsxs(c.Fragment,{children:[c.jsx("input",{value:a.managedModel,list:"nc-managed-models",placeholder:g(_!=null&&_.requiresModel?"fleet-model-required":"fleet-model-default"),onChange:k=>u({managedModel:k.target.value})}),c.jsx("datalist",{id:"nc-managed-models",children:[...(_==null?void 0:_.models)||[],...a.modelOptions||[]].filter((k,R,I)=>k&&I.indexOf(k)===R).map(k=>c.jsx("option",{value:k},k))})]}),_!=null&&_.supportsUnsafe?c.jsxs("select",{value:a.permissionPolicy,onChange:k=>u({permissionPolicy:k.target.value}),children:[c.jsx("option",{value:"standard",children:g("fleet-standard-permissions")}),c.jsx("option",{value:"unsafe",children:g("fleet-unsafe-permissions")})]}):c.jsx("small",{children:g("fleet-standard-permissions")}),(_==null?void 0:_.supportsUnsafe)&&a.permissionPolicy==="unsafe"&&c.jsx("small",{className:"nc-err",children:g("fleet-unsafe-warning")}),(_==null?void 0:_.credentialEnv)===!0&&c.jsxs(c.Fragment,{children:[c.jsx("input",{value:a.envKey,placeholder:g("fleet-api-key-env"),onChange:k=>u({envKey:k.target.value})}),c.jsx("small",{children:g("fleet-custom-secret-help")})]}),b&&c.jsxs("section",{className:"nc-fleet-key","aria-label":g("fleet-key-section"),children:[c.jsxs("div",{className:"nc-fleet-key-head",children:[c.jsx("b",{children:g("fleet-key-section")}),c.jsx("span",{children:g(`fleet-credential-source-${w}`)})]}),c.jsxs("label",{className:"nc-field",children:[g("fleet-key-variable"),c.jsx("input",{value:b,readOnly:!0,"aria-label":g("fleet-key-variable")})]}),c.jsx("small",{children:y.length?g("fleet-key-used-by").replace("{engines}",y.join(", ")):g("fleet-key-used-by-none")}),y.length>0&&c.jsx("small",{children:g("fleet-key-shared-impact").replace("{key}",b).replace("{engines}",y.join(", "))}),c.jsxs("div",{className:"nc-fleet-key-input",children:[c.jsx("input",{type:a.credentialReveal?"text":"password",value:a.credentialValue||"","aria-label":g("fleet-key-value").replace("{key}",b),autoComplete:"new-password",spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",placeholder:_!=null&&_.authConfigured||e.mode==="edit"?g("fleet-key-blank-keeps"):g("fleet-key-enter"),onChange:k=>u({credentialValue:k.target.value,allowMissingCredential:k.target.value?!1:a.allowMissingCredential})}),c.jsx("button",{type:"button",className:"nc-btn ghost","aria-label":g(a.credentialReveal?"fleet-key-hide":"fleet-key-reveal"),onClick:()=>u({credentialReveal:!a.credentialReveal}),children:g(a.credentialReveal?"fleet-key-hide":"fleet-key-reveal")})]}),c.jsx("small",{children:g("fleet-key-local-help")}),e.mode==="new"&&(_==null?void 0:_.authConfigured)!==!0&&!a.credentialValue&&c.jsxs("label",{className:"nc-check nc-fleet-key-missing",children:[c.jsx("input",{type:"checkbox",checked:!!a.allowMissingCredential,onChange:k=>u({allowMissingCredential:k.target.checked})}),g("fleet-key-create-missing")]}),(_==null?void 0:_.notice)&&c.jsx("small",{className:"nc-fleet-provider-notice",children:g(`fleet-provider-notice-${_.notice}`)})]}),a.provider==="custom"&&c.jsxs(c.Fragment,{children:[c.jsx("input",{value:a.displayName,placeholder:g("fleet-provider-display"),onChange:k=>u({displayName:k.target.value})}),c.jsx("input",{value:a.baseUrl,placeholder:"https://api.example.com/v1",onChange:k=>u({baseUrl:k.target.value})}),((_==null?void 0:_.protocols)||[]).length>1&&c.jsx("select",{value:a.protocol,onChange:k=>u({protocol:k.target.value}),children:_.protocols.map(k=>c.jsx("option",{value:k,children:k},k))}),c.jsxs("div",{className:"nc-fleet-pair",children:[c.jsx("input",{value:a.envKey,placeholder:g("fleet-api-key-env"),onChange:k=>u({envKey:k.target.value})}),c.jsx("input",{value:a.providerId,placeholder:g("fleet-provider-id"),onChange:k=>u({providerId:k.target.value})})]}),c.jsxs("small",{children:[a.protocol," · ",g("fleet-custom-secret-help")]})]}),c.jsx("small",{children:g(a.client==="shell"?"fleet-shell-engine-help":"fleet-managed-help")})]}):c.jsxs(c.Fragment,{children:[c.jsx("input",{value:a.command,placeholder:g("command-path"),onChange:k=>u({command:k.target.value})}),c.jsx("textarea",{value:a.argsText,placeholder:g("args-lines"),onChange:k=>u({argsText:k.target.value})}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:a.rc,onChange:k=>u({rc:k.target.checked})})," remote control"]}),c.jsxs("select",{value:a.promptMode,onChange:k=>u({promptMode:k.target.value}),children:[c.jsx("option",{value:"send-keys",children:"send-keys"}),c.jsx("option",{value:"flag",children:"flag"})]}),a.promptMode==="flag"&&c.jsx("input",{value:a.promptFlag,placeholder:"prompt flag",onChange:k=>u({promptFlag:k.target.value})}),c.jsxs("div",{className:"nc-fleet-pair",children:[c.jsx("input",{value:a.modelFlag,placeholder:"model flag",onChange:k=>u({modelFlag:k.target.value})}),c.jsx("input",{value:a.modelValue,placeholder:"model default",onChange:k=>u({modelValue:k.target.value})})]}),c.jsx("small",{children:g("env-write-only")}),h.map((k,R)=>c.jsxs("div",{className:"nc-fleet-env",children:[c.jsx("input",{value:k.key,disabled:k.configured,placeholder:"ENV_KEY",onChange:I=>{const A=h.slice();A[R]={...k,key:I.target.value},u({envRows:A})}}),c.jsx("input",{type:"password",value:k.value,placeholder:k.configured?"•••••• (unchanged)":"value",onChange:I=>{const A=h.slice();A[R]={...k,value:I.target.value},u({envRows:A})}}),c.jsx("button",{className:"nc-btn danger",onClick:()=>u({envRows:h.filter((I,A)=>A!==R)}),children:"×"})]},`${k.key}-${R}`)),c.jsx("button",{className:"nc-btn ghost",onClick:()=>u({envRows:[...h,{key:"",value:"",configured:!1}]}),children:"+ env"})]}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{className:"nc-btn ghost",onClick:()=>t(null),children:g("cancel")}),c.jsx("button",{className:"nc-btn primary",disabled:n||!a.id||S||a.kind==="custom"&&!a.command||a.kind==="managed"&&(_==null?void 0:_.requiresModel)&&!a.managedModel||a.kind==="managed"&&(_==null?void 0:_.credentialEnv)===!0&&!a.envKey||a.kind==="managed"&&a.provider==="custom"&&(!a.displayName||!a.baseUrl||!a.envKey||!a.providerId),onClick:s,children:g("save")})]})]})}function tN({token:e,route:t,targets:n=[],location:s,setLocation:o,state:a,setState:u,engines:h,busy:p,onSave:f}){var F;const[_,b]=N.useState(null),[y,w]=N.useState(""),S=a.form,x=D=>u({...a,form:{...S,...D}}),C=h.find(D=>D.id===S.engine),k=((F=C==null?void 0:C.managed)==null?void 0:F.client)==="shell",R=D=>{var ee,K,O,j;const J=h.find(P=>P.id===D),W={...S.commands||{}};((ee=C==null?void 0:C.managed)==null?void 0:ee.client)==="shell"&&(S.command?W[S.engine]=S.command:delete W[S.engine]),x({engine:D,model:((K=S.models)==null?void 0:K[D])||((O=J==null?void 0:J.managed)==null?void 0:O.model)||((j=J==null?void 0:J.model)==null?void 0:j.value)||"",commands:W,command:W[D]||""})},I=D=>{const J={...S.commands||{}};D?J[S.engine]=D:delete J[S.engine],x({command:D,commands:J})},A=k&&/[|&;<>()`$*?{}\[\]~]/.test(S.command||""),G=async D=>{try{const J=await Eh(e,D,t);b(J),x({cwd:J.path}),w("")}catch(J){w(String(J.message||J))}};return c.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[c.jsx("b",{children:a.mode==="new"?g("fleet-new-cell"):`${g("edit")} ${S.id}`}),a.mode==="new"&&c.jsxs("label",{className:"nc-field",children:[g("location"),c.jsx("span",{className:"nc-req",children:" *"}),c.jsxs("select",{value:s,onChange:D=>{o(D.target.value),x({engine:""})},children:[c.jsx("option",{value:"",children:g("local")}),n.map(D=>c.jsxs("option",{value:D.route.join("/"),disabled:D.status&&D.status!=="up",children:[D.label,D.status&&D.status!=="up"?` · ${g("node-offline")}`:""]},D.route.join("/")))]})]}),c.jsx("input",{value:S.id,disabled:a.mode!=="new",placeholder:"id",onChange:D=>x({id:D.target.value})}),c.jsxs("div",{className:"nc-fleet-pair",children:[c.jsx("input",{value:S.cwd,placeholder:g("cwd"),onChange:D=>x({cwd:D.target.value})}),c.jsx("button",{className:"nc-btn ghost",onClick:()=>_?b(null):G(S.cwd),children:g("browse")})]}),_&&c.jsxs("div",{className:"nc-fs",children:[c.jsx("div",{className:"nc-fs-path",children:_.path}),c.jsxs("div",{className:"nc-fs-list",children:[_.parent&&c.jsxs("button",{className:"nc-fs-item nc-fs-nav",onClick:()=>G(_.parent),children:["↑ ",g("fs-parent")]}),(_.dirs||[]).map(D=>c.jsxs("button",{className:"nc-fs-item",onClick:()=>G(`${_.path.replace(/\/$/,"")}/${D}`),children:["📁 ",D]},D))]})]}),y&&c.jsx("div",{className:"nc-err",children:y}),c.jsx("select",{value:S.engine,onChange:D=>R(D.target.value),children:h.map(D=>c.jsx("option",{value:D.id,children:D.label},D.id))}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:!!S.boot,onChange:D=>x({boot:D.target.checked})})," boot"]}),k?c.jsxs(c.Fragment,{children:[c.jsx("input",{value:S.command||"",maxLength:4096,placeholder:g("fleet-shell-command-placeholder"),onChange:D=>I(D.target.value)}),c.jsx("small",{children:S.command?g("fleet-shell-command-help"):g("fleet-shell-interactive")}),A&&c.jsx("small",{className:"nc-note",children:g("fleet-shell-command-metachar")})]}):c.jsxs(c.Fragment,{children:[c.jsx("input",{value:S.model||"",list:"nc-cell-models",placeholder:g("fleet-model-override"),onChange:D=>x({model:D.target.value})}),c.jsx("datalist",{id:"nc-cell-models",children:((C==null?void 0:C.availableModels)||[]).map(D=>c.jsx("option",{value:D},D))}),c.jsx("textarea",{value:S.prompt||"",placeholder:"prompt",onChange:D=>x({prompt:D.target.value})})]}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{className:"nc-btn ghost",onClick:()=>u(null),children:g("cancel")}),c.jsx("button",{className:"nc-btn primary",disabled:p||!S.id||!S.cwd||!S.engine,onClick:f,children:g("save")})]})]})}function m_({token:e,route:t=[],state:n,setState:s,busy:o,onSave:a}){const[u,h]=N.useState(null),[p,f]=N.useState([]),[_,b]=N.useState(""),y=Array.isArray(t)?t.join("/"):"";N.useEffect(()=>{let k=!0;return xh(e,y?y.split("/"):[]).then(R=>{k&&(f(R.engines||[]),b(""))}).catch(R=>{k&&(f([]),b(String(R.message||R)))}),()=>{k=!1}},[e,y]);const w=n.form,S=k=>s({...n,form:{...w,...k}}),x=async k=>{try{const R=await Eh(e,k,t);h(R),S({cwd:R.path})}catch{}},C=!w.id&&w.tmuxSession?w.tmuxSession.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32):w.id;return c.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[c.jsxs("b",{children:[g("import-as-cell")," · ",w.tmuxSession]}),c.jsx("small",{children:g("import-help")}),c.jsx("input",{value:w.tmuxSession,disabled:!0,placeholder:"tmux session",readOnly:!0}),c.jsx("input",{value:w.id,placeholder:g("name"),onChange:k=>S({id:k.target.value})}),c.jsxs("div",{className:"nc-fleet-pair",children:[c.jsx("input",{value:w.cwd,placeholder:g("cwd"),onChange:k=>S({cwd:k.target.value})}),c.jsx("button",{className:"nc-btn ghost",type:"button",onClick:()=>u?h(null):x(w.cwd),children:g("browse")})]}),u&&c.jsxs("div",{className:"nc-fs",children:[c.jsx("div",{className:"nc-fs-path",children:u.path}),c.jsxs("div",{className:"nc-fs-list",children:[u.parent&&c.jsxs("button",{className:"nc-fs-item nc-fs-nav",onClick:()=>x(u.parent),children:["↑ ",g("fs-parent")]}),(u.dirs||[]).map(k=>c.jsxs("button",{className:"nc-fs-item",onClick:()=>x(`${u.path.replace(/\/$/,"")}/${k}`),children:["📁 ",k]},k))]})]}),c.jsxs("select",{value:w.engine,onChange:k=>S({engine:k.target.value}),children:[c.jsx("option",{value:"",children:g("import-engine-required")}),p.map(k=>c.jsx("option",{value:k.id,children:k.label},k.id))]}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:!!w.boot,onChange:k=>S({boot:k.target.checked})})," boot"]}),(n.err||_)&&c.jsx("div",{className:"nc-err",children:n.err||_}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{className:"nc-btn ghost",onClick:()=>s(null),children:g("cancel")}),c.jsx("button",{className:"nc-btn primary",disabled:o||!w.tmuxSession||!w.engine||!p.length,onClick:a,children:g(C?"import-as-cell":"save")})]})]})}function ol(e){const t=Lr(e);return t===null?`~/${e}`:t?`~/${t}`:"~"}function nN(e){if(!e||typeof e.path!="string"||typeof e.home!="string")return"";const{path:t,home:n}=e;return!n||t===n||!t.startsWith(n+"/")?"":t.slice(n.length+1).replace(/\/+$/,"")}function iN({token:e,route:t,cell:n,busy:s=!1,onSaved:o,onClose:a}){const[u,h]=N.useState(""),[p,f]=N.useState(null),[_,b]=N.useState(!1),[y,w]=N.useState(""),S=typeof(n==null?void 0:n.cwdSuggestion)=="string"&&Lr(n.cwdSuggestion)!==null?Lr(n.cwdSuggestion):null,[x,C]=N.useState(S),k=n==null?void 0:n.id,R=s||_,I=async W=>{const ee=Lr(W);if(ee===null){f({rel:"",dirs:[],loading:!1,err:g("fleet-cwd-repair-invalid")});return}f({rel:ee,dirs:[],loading:!0,err:""});try{const K=await Eh(e,ee,t),O=nN(K);f({rel:O,dirs:Array.isArray(K.dirs)?K.dirs:[],loading:!1,err:""})}catch(K){f({rel:ee,dirs:[],loading:!1,err:String(K&&K.message||K)})}},A=W=>{if(!p)return;const ee=p.rel?`${p.rel}/${W}`:W;I(ee)},G=()=>{p!=null&&p.rel&&I(p.rel.split("/").slice(0,-1).join("/"))},F=()=>{p&&(h(p.rel||""),f(null),w(""),C(null))},D=()=>{x!==null&&(h(x),C(null),w(""))},J=async()=>{if(R)return;const W=Lr(u);if(W===null){w(g("fleet-cwd-repair-invalid"));return}const ee=ol(W);let K=!0;try{K=window.confirm(g("fleet-cwd-repair-confirm").replace("{id}",String(k||"")).replace("{path}",ee))}catch{K=!1}if(K){b(!0),w(""),C(null);try{const O=await j_(e,k,{cwdRel:W},t);o==null||o(O)}catch(O){const j=O&&O.data||{};if(j.code==="unportable-cwd"){w(g("fleet-cwd-repair-unportable"));const P=Array.isArray(j.cells)?j.cells.find(H=>H&&H.id===k):null,M=P&&typeof P.suggestion=="string"?P.suggestion:null;M!==null&&Lr(M)!==null&&C(M)}else w(String(O&&O.message||O))}finally{b(!1)}}};return c.jsxs("div",{className:"nc-set-form nc-fleet-form nc-cwd-repair",children:[c.jsx("b",{children:g("fleet-cwd-repair-title").replace("{id}",String(k||""))}),c.jsx("small",{className:"nc-set-info",children:g("fleet-cwd-repair-help")}),c.jsx("small",{className:"nc-cwd-no-source",children:g("fleet-cwd-repair-no-source-path")}),c.jsxs("label",{className:"nc-field",children:[g("cwd"),c.jsxs("div",{className:"nc-cwd-rel-row",children:[c.jsx("span",{className:"nc-cwd-rel-prefix",children:"~/"}),c.jsx("input",{value:u,placeholder:g("fleet-cwd-repair-placeholder"),autoComplete:"off",spellCheck:"false",autoCapitalize:"none",onChange:W=>h(W.target.value)}),c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:R,onClick:()=>p?f(null):I(""),children:g(p?"close":"fleet-cwd-repair-browse")})]})]}),c.jsx("div",{className:"nc-cwd-preview",children:g("fleet-cwd-repair-preview").replace("{path}",ol(u))}),p&&c.jsxs("div",{className:"nc-fs",children:[c.jsx("div",{className:"nc-fs-path",children:ol(p.rel)}),c.jsxs("div",{className:"nc-fs-list",children:[p.rel&&c.jsxs("button",{type:"button",className:"nc-fs-item nc-fs-nav",onClick:G,children:["↑ ",g("fs-parent")]}),p.loading&&c.jsx("div",{className:"nc-fs-empty",children:"…"}),!p.loading&&p.dirs.length===0&&c.jsx("div",{className:"nc-fs-empty",children:g("fleet-cwd-repair-fs-empty")}),!p.loading&&p.dirs.map(W=>c.jsxs("button",{type:"button",className:"nc-fs-item",onClick:()=>A(W),children:["📁 ",W]},W))]}),p.err&&c.jsx("div",{className:"nc-err",children:p.err}),c.jsx("div",{className:"nc-sheet-actions",children:c.jsx("button",{type:"button",className:"nc-btn primary",disabled:R||p.loading||!!p.err,onClick:F,children:g("fleet-cwd-repair-use-current")})})]}),y&&c.jsx("div",{className:"nc-err",role:"alert",children:y}),x!==null&&c.jsxs("div",{className:"nc-cwd-suggestion",role:"status",children:[c.jsx("span",{children:g("fleet-cwd-repair-suggestion")}),c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:D,children:g("fleet-cwd-repair-use-suggestion").replace("{path}",ol(x))})]}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:a,children:g("cancel")}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:R,onClick:J,children:_?"…":g("save")})]})]})}function rN({token:e,readonly:t,targets:n=[],startNewCell:s=!1,initialLocation:o=""}){const[a,u]=N.useState({engines:[],cells:[],managedCatalog:[]}),[h,p]=N.useState({available:!1,capabilities:[]}),[f,_]=N.useState(!1),[b,y]=N.useState(null),[w,S]=N.useState(null),[x,C]=N.useState(!1),[k,R]=N.useState(""),[I,A]=N.useState(""),[G,F]=N.useState(o),[D,J]=N.useState(!1),[W,ee]=N.useState(null),[K,O]=N.useState(null),[j,P]=N.useState(null),[M,H]=N.useState(!1),[te,T]=N.useState([]),[ie,B]=N.useState(null),[L,$]=N.useState("manage"),X=N.useRef(!1),ae=G?G.split("/"):[],ue=N.useCallback(async()=>{try{const le=await zr(e,ae);p(le);try{const be=await Nh(e,ae);J(!!be.readonlyDefault)}catch{J(!1)}if(le.provider==="builtin"&&(le.capabilities||[]).includes("definitions")){const be=await xh(e,ae),Be=new Map((le.engines||[]).map($e=>[$e.id,$e]));if(be.engines=(be.engines||[]).map($e=>{var he;return{...$e,availableModels:((he=Be.get($e.id))==null?void 0:he.models)||[]}}),u(be),(le.capabilities||[]).includes("credentials"))try{T((await Xb(e,ae)).credentials||[])}catch{T([])}else T([])}R("")}catch(le){R(String(le.message||le))}finally{_(!0)}},[e,G]);N.useEffect(()=>{ue();const le=setInterval(ue,5e3);return()=>clearInterval(le)},[ue]);const ge=new Set((h.cells||[]).filter(le=>le.active).map(le=>le.cell)),Z=h.provider==="builtin"&&(h.capabilities||[]).includes("edit"),q=(h.capabilities||[]).includes("restore");N.useEffect(()=>{!s||X.current||!Z||!a.engines.length||(X.current=!0,S({mode:"new",form:p_(a.engines[0].id)}))},[s,Z,a.engines]);const fe=async le=>{C(!0),R(""),A("");try{await le(),await ue()}catch(be){R(String(be.message||be))}C(!1)},Ie=()=>fe(async()=>{var Ne;const le=b.mode==="new",be=b.form,Be=a.managedCatalog||[],$e=be.kind==="managed"?Do(Be,be):null,he=typeof($e==null?void 0:$e.credentialEnv)=="string"?$e.credentialEnv:"",V=he&&be.credentialValue||"",ne=Q2(be,le,Be);!le&&b.form.kind==="custom"&&!b.form.modelFlag&&(ne.model=null),!le&&b.form.kind==="custom"&&b.form.promptMode!=="flag"&&(ne.promptFlag=null);let z;if(le)z=await Qb(e,ne,ae);else{const we=b.original,Re=new Set(b.form.envRows.filter(Me=>!Me.remove).map(Me=>Me.key)),Je=(we.envKeys||[]).filter(Me=>!Re.has(Me)),Tt=Object.fromEntries(b.form.envRows.filter(Me=>!Me.remove&&Me.key&&(!Me.configured||Me.value!=="")).map(Me=>[Me.key,Me.value]));z=await Zb(e,we.id,ne,b.form.kind==="custom"?{set:Tt,remove:Je}:void 0,ae)}let se=null;if(he&&V)try{se=await Jm(e,he,V,ae),T(se.credentials||[])}catch{throw await ue(),le&&y({mode:"edit",original:{...ne,id:be.id},form:{...be,credentialReveal:!1}}),new Error(g(le?"fleet-key-partial-create":"fleet-key-partial-edit"))}await ue(),y(null),A(g("fleet-saved"));const me=((Ne=((se==null?void 0:se.credentials)||[]).find(we=>we.envKey===he))==null?void 0:Ne.activeCells)||[],ke=[...new Set([...(z==null?void 0:z.activeCells)||[],...me])];if(ke.length&&window.confirm(g("fleet-restart-confirm").replace("{cells}",ke.join(", "))))for(const we of ke)await So(e,we,ae)}),et=()=>fe(async()=>{var z,se,me,ke,Ne,we;const le=w.mode==="new",be=w.form,Be={...le?{id:be.id}:{},cwd:be.cwd,engine:be.engine,boot:!!be.boot},$e={...be.commands||{}},he=a.engines.find(Re=>Re.id===be.engine);((z=he==null?void 0:he.managed)==null?void 0:z.client)==="shell"&&typeof be.command=="string"&&be.command.length?$e[be.engine]=be.command:((se=he==null?void 0:he.managed)==null?void 0:se.client)==="shell"&&delete $e[be.engine],(Object.keys($e).length||!le)&&(Be.commands=$e),le?(((me=he==null?void 0:he.managed)==null?void 0:me.client)!=="shell"&&be.model&&(Be.model=be.model),((ke=he==null?void 0:he.managed)==null?void 0:ke.client)!=="shell"&&be.prompt&&(Be.prompt=be.prompt)):(Be.model=((Ne=he==null?void 0:he.managed)==null?void 0:Ne.client)==="shell"?null:be.model||null,((we=he==null?void 0:he.managed)==null?void 0:we.client)!=="shell"&&(Be.prompt=be.prompt||null));const V=le?await t0(e,Be,ae):await j_(e,w.original.id,Be,ae),ne=le?be.id:w.original.id;S(null),A(g("fleet-saved")),!le&&(V!=null&&V.active)&&window.confirm(g("fleet-restart-confirm").replace("{cells}",ne))&&await So(e,ne,ae)}),ze=t||D,Fe=le=>te.find(be=>{var Be;return(Be=be.engines)==null?void 0:Be.includes(le.id)})||null,Ct=()=>fe(async()=>{var Be;const le=await Jm(e,ie.envKey,ie.value,ae);T(le.credentials||[]),B(null),A(g("fleet-credential-saved"));const be=((Be=(le.credentials||[]).find($e=>$e.envKey===ie.envKey))==null?void 0:Be.activeCells)||[];if(be.length&&window.confirm(g("fleet-restart-confirm").replace("{cells}",be.join(", "))))for(const $e of be)await So(e,$e,ae)}),Ge=le=>fe(async()=>{if(!window.confirm(g("fleet-credential-remove-confirm").replace("{key}",le.envKey)))return;const be=await Jb(e,le.envKey,ae);T(be.credentials||[]),A(g("fleet-credential-removed"))}),rt=le=>ee({...le,route:Array.isArray(le==null?void 0:le.route)?le.route:ae}),ut=async le=>{if(!W)return;const be=W.cell||W.id,Be=Array.isArray(W.route)?W.route:ae;le.action==="up"?await kh(e,{cell:be,boot:!!le.boot,...le.engine?{engine:le.engine}:{},...le.model!==void 0?{model:le.model}:{},...le.permissionPolicy?{permissionPolicy:le.permissionPolicy}:{}},Be):await gl(e,{cell:be,boot:!!le.boot},Be)},ct=(le,be)=>{R(""),O({mode:"new",route:Array.isArray(be)?be:ae,form:{tmuxSession:le.name,id:"",engine:"",cwd:"",boot:!1},err:""})},vt=()=>fe(async()=>{const le=K.form;if(!le.engine){O({...K,err:g("import-engine-required")});return}await n0(e,{tmuxSession:le.tmuxSession,id:le.id||void 0,engine:le.engine,cwd:le.cwd||void 0,boot:!!le.boot},le.route||ae),O(null),A(g("fleet-saved"))}),it=({engineRows:le=[],cellRows:be=[]})=>fe(async()=>{const Be=le.filter(Ne=>Ne.selected),$e=Be.map(Ne=>Aw(Ne.engine));if($e.some(Ne=>!Ne))throw new Error(g("fleet-backup-invalid-engine"));const he=Be.filter(Ne=>Ne.exists).map(Ne=>Ne.engine.id);if(he.length&&!window.confirm(g("fleet-backup-confirm-engine-overwrite").replace("{engines}",he.join(", "))))return;const V=[...new Set([...a.engines.map(Ne=>Ne.id),...$e.map(Ne=>Ne.id)])],ne=[];for(const Ne of be.filter(we=>we.selected)){const we=Y2(Ne.cell,Ne.engine,V);if(!we)throw new Error(`${Ne.cell.id}: ${g("fleet-backup-engine-missing")}`);ne.push(we)}const z=be.filter(Ne=>Ne.selected&&Ne.exists).map(Ne=>Ne.cell.id);if(z.length&&!window.confirm(g("fleet-backup-confirm-overwrite").replace("{cells}",z.join(", "))))return;const se=$e.length?await r0(e,$e,he.length>0,ae):{needsRestart:[]},me=ne.length?await i0(e,ne,ae):{needsRestart:[]},ke=[...new Set([...se.needsRestart||[],...me.needsRestart||[]])];H(!1),A(`${g("fleet-backup-restored").replace("{n}",String(ne.length))}${$e.length?` · ${$e.length} ${g("fleet-engines").toLowerCase()}`:""}${ke.length?` · ${g("fleet-backup-needs-restart").replace("{cells}",ke.join(", "))}`:""}`)}),lt=c.jsxs("label",{className:"nc-field",children:[g("location"),c.jsxs("select",{value:G,onChange:le=>{F(le.target.value),y(null),S(null),R(""),A(""),J(!1),_(!1),p({available:!1,capabilities:[]}),u({engines:[],cells:[],managedCatalog:[]}),T([]),B(null)},children:[c.jsx("option",{value:"",children:g("local")}),n.map(le=>c.jsxs("option",{value:le.route.join("/"),disabled:le.status&&le.status!=="up",children:[le.label,le.status&&le.status!=="up"?` · ${g("node-offline")}`:""]},le.route.join("/")))]})]}),mt=c.jsxs("div",{className:"nc-fleet-view-tabs",role:"tablist","aria-label":g("tab-fleet"),children:[c.jsx("button",{type:"button",role:"tab","aria-selected":L==="manage",className:`nc-set-tabbtn${L==="manage"?" on":""}`,onClick:()=>$("manage"),children:g("fleet-manage-location")}),c.jsx("button",{type:"button",role:"tab","aria-selected":L==="overview",className:`nc-set-tabbtn${L==="overview"?" on":""}`,onClick:()=>$("overview"),children:g("fleet-network-overview")})]});return f?Z?c.jsxs("div",{className:"nc-set-tab nc-fleet-editor",children:[mt,L==="overview"?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"nc-set-info",children:g("fleet-overview-help")}),c.jsx(vd,{token:e,targets:n,readonly:t,onPower:rt,onImport:ct})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"nc-set-info",children:g("fleet-manage-help")}),lt,c.jsxs("div",{className:"nc-set-row nc-fleet-backup-actions",children:[c.jsx("button",{className:"nc-btn ghost",disabled:ze||x,onClick:()=>{R(""),H(!0)},children:g("fleet-backup")}),c.jsx("small",{children:g("fleet-backup-help")})]}),c.jsxs("div",{className:"nc-fleet-section-head",children:[c.jsx("b",{children:g("fleet-cells")}),c.jsx("span",{className:"nc-fleet-head-actions",children:c.jsxs("button",{className:"nc-btn primary",disabled:ze||x||!a.engines.length,onClick:()=>{var le;R(""),S({mode:"new",form:p_((le=a.engines[0])==null?void 0:le.id)})},children:["+ ",g("add")]})})]}),a.cells.map(le=>{const be=ge.has(le.id),Be=h.capabilities||[],$e=le.needsRepair===!0;return c.jsxs("div",{className:"nc-fleet-item",children:[c.jsxs("span",{children:[c.jsx("b",{children:le.id}),c.jsxs("small",{children:[le.engine," · ",$e?c.jsx("span",{className:"nc-fleet-tag nc-fleet-tag-warn",children:g("fleet-cwd-needs-repair")}):le.cwd,be?` · ${g("service-active")}`:` · ${g("cell-off")}`]})]}),c.jsxs("span",{children:[be&&Be.includes("down")&&c.jsx("button",{className:"nc-btn ghost",disabled:ze||x,onClick:()=>fe(()=>gl(e,{cell:le.id},ae)),children:g("stop")}),!be&&Be.includes("up")&&c.jsx("button",{className:"nc-btn primary",disabled:ze||x,onClick:()=>rt({cell:le.id,id:le.id,engine:le.engine,model:le.model,models:le.models,permissionPolicies:le.permissionPolicies,active:!1,boot:le.boot}),children:g("start")}),be&&Be.includes("restart")&&c.jsx("button",{className:"nc-btn ghost",disabled:ze||x,onClick:()=>fe(()=>So(e,le.id,ae)),children:g("restart")}),$e?c.jsx("button",{className:"nc-btn ghost",disabled:ze||x,onClick:()=>{R(""),P(le)},children:g("fleet-cwd-repair")}):c.jsx("button",{className:"nc-btn ghost",disabled:ze||x,onClick:()=>{var he;R(""),S({mode:"edit",original:le,form:{...le,commands:{...le.commands||{}},command:((he=le.commands)==null?void 0:he[le.engine])||""}})},children:g("edit")}),c.jsx("button",{className:"nc-btn danger",disabled:ze||x,onClick:()=>fe(async()=>{window.confirm(g("fleet-remove-cell").replace("{id}",le.id))&&await L_(e,le.id,!0,ae)}),children:"×"})]})]},le.id)}),c.jsxs("div",{className:"nc-fleet-section-head",children:[c.jsx("b",{children:g("fleet-engines")}),c.jsxs("button",{className:"nc-btn primary",disabled:ze||x,onClick:()=>{R(""),y({mode:"new",form:G2()})},children:["+ ",g("add")]})]}),a.engines.map(le=>{var Be,$e;const be=Fe(le);return c.jsxs("div",{className:"nc-fleet-item",children:[c.jsxs("span",{children:[c.jsx("b",{children:le.label}),c.jsx("small",{children:le.managed?`${le.id} · ${le.managed.client} / ${le.managed.provider} · ${(Be=le.managedInfo)!=null&&Be.configured?g("fleet-ready"):(($e=le.managedInfo)==null?void 0:$e.reason)||g("fleet-not-ready")}`:`${le.id} · ${le.command}`}),be&&c.jsxs("small",{children:[be.envKey," · ",g(`fleet-credential-source-${be.source||"missing"}`)]})]}),c.jsxs("span",{children:[be&&c.jsx("button",{className:"nc-btn ghost",disabled:ze||x,onClick:()=>{R(""),B({envKey:be.envKey,value:""})},children:be.configured?g("fleet-credential-change"):g("fleet-credential-set")}),(be==null?void 0:be.source)==="local"&&c.jsx("button",{className:"nc-btn danger",disabled:ze||x,onClick:()=>Ge(be),children:g("fleet-credential-forget")}),c.jsx("button",{className:"nc-btn ghost",disabled:ze||x,onClick:()=>{R(""),y({mode:"edit",original:le,form:J2(le)})},children:g("edit")}),c.jsx("button",{className:"nc-btn danger",disabled:ze||x,onClick:()=>fe(async()=>{window.confirm(g("fleet-remove-engine").replace("{id}",le.id))&&await e0(e,le.id,ae)}),children:"×"})]})]},le.id)})]}),b&&c.jsx(Nr,{onClose:()=>y(null),label:g("fleet-new-engine"),error:k,children:c.jsx(eN,{state:b,setState:y,busy:x,onSave:Ie,catalog:a.managedCatalog||[]})}),w&&c.jsx(Nr,{onClose:()=>S(null),label:g("fleet-new-cell"),error:k,children:c.jsx(tN,{token:e,route:ae,targets:n,location:G,setLocation:F,state:w,setState:S,engines:a.engines,busy:x,onSave:et})}),j&&c.jsx(Nr,{onClose:()=>P(null),label:g("fleet-cwd-repair-title").replace("{id}",j.id),error:"",children:c.jsx(iN,{token:e,route:ae,cell:j,busy:x,onSaved:async()=>{P(null),A(g("fleet-cwd-repaired")),await ue()},onClose:()=>P(null)})}),I&&c.jsx("div",{className:"nc-set-note",children:I}),k&&c.jsx("div",{className:"nc-err",children:k}),M&&c.jsx(Nr,{onClose:()=>H(!1),label:g("fleet-backup"),error:k,children:c.jsx(Z2,{cells:a.cells,engines:a.engines,busy:x,canRestore:q,onRestore:it,onClose:()=>H(!1)})}),ie&&c.jsx(Nr,{onClose:()=>B(null),label:g("fleet-credential-title"),error:k,children:c.jsxs("div",{className:"nc-fleet-form nc-credential-form",children:[c.jsx("b",{children:g("fleet-credential-title")}),c.jsx("small",{children:g("fleet-credential-help")}),c.jsxs("label",{className:"nc-field",children:[ie.envKey,c.jsx("input",{type:"password",autoComplete:"off",spellCheck:"false",autoCapitalize:"none",value:ie.value,onChange:le=>B({...ie,value:le.target.value})})]}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{className:"nc-btn ghost",onClick:()=>B(null),children:g("cancel")}),c.jsx("button",{className:"nc-btn primary",disabled:x||!ie.value,onClick:Ct,children:g("save")})]})]})}),K&&c.jsx(Nr,{onClose:()=>O(null),label:g("import-as-cell"),error:k,children:c.jsx(m_,{token:e,route:K.route||ae,state:K,setState:O,busy:x,onSave:vt})}),W&&c.jsx(_l,{cell:W,token:e,route:Array.isArray(W.route)?W.route:ae,onConfirm:async le=>{try{await ut(le)}finally{await ue()}},onClose:()=>ee(null)})]}):c.jsxs("div",{className:"nc-set-tab",children:[mt,L==="overview"?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"nc-set-info",children:g("fleet-overview-help")}),c.jsx(vd,{token:e,targets:n,readonly:t,onPower:rt,onImport:ct})]}):c.jsxs(c.Fragment,{children:[lt,c.jsxs("div",{className:"nc-set-info",children:[g(k?"fleet-editor-load-error":"fleet-editor-unavailable"),!k&&h.reason?` ${h.reason}`:""]})]}),k&&c.jsx("div",{className:"nc-err",children:k}),K&&c.jsx(Nr,{onClose:()=>O(null),label:g("import-as-cell"),error:k,children:c.jsx(m_,{token:e,route:K.route||ae,state:K,setState:O,busy:x,onSave:vt})}),W&&c.jsx(_l,{cell:W,token:e,route:Array.isArray(W.route)?W.route:ae,onConfirm:async le=>{try{await ut(le)}finally{await ue()}},onClose:()=>ee(null)})]}):c.jsxs("div",{className:"nc-set-tab",children:[mt,L==="overview"?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"nc-set-info",children:g("fleet-overview-help")}),c.jsx(vd,{token:e,targets:n,readonly:t,onPower:rt,onImport:ct})]}):c.jsxs(c.Fragment,{children:[lt,c.jsx("div",{className:"nc-set-info",children:g("fleet-editor-loading")})]})]})}const of="nc_notification_speech_v1",al="nc-notification-speech",mh="nc-notification-speech-preview",sN=320,oN=2,aN=3e4,lN=1e4,cN=6e4,uN=64,g_=Object.freeze({enabled:!1}),v_=Object.freeze({it:"it-IT",en:"en-US",es:"es-ES"}),af=new WeakSet;function lf(e){return{enabled:(e&&typeof e=="object"&&!Array.isArray(e)?e:{}).enabled===!0}}function Bw(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function __(e=Bw()){if(!e)return{...g_};try{return lf(JSON.parse(e.getItem(of)||"null"))}catch{return{...g_}}}function dN(e,t=Bw()){const n=lf(e);if(t)try{t.setItem(of,JSON.stringify(n))}catch{}return n}function js(){try{return typeof window<"u"?window:null}catch{return null}}function To(e=js()){try{return!!(e&&e.speechSynthesis&&typeof e.speechSynthesis.speak=="function"&&typeof e.SpeechSynthesisUtterance=="function")}catch{return!1}}function Ow(e=js()){return!!(e&&(typeof e=="object"||typeof e=="function")&&af.has(e))}function gh(e=js()){e&&(typeof e=="object"||typeof e=="function")&&af.delete(e)}function zw(e){return v_[e]||v_.en}function cf(e){return String(e||"").normalize("NFC").replace(/[\p{Cc}\p{Cf}]+/gu," ").replace(/\s+/g," ").trim()}function y_(e){return cf(e).replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\b(?:sk|hf|zai|xox[baprs]|gh[pousr]|npm)[_-][A-Za-z0-9._-]{8,}\b/gi,"[redacted]").replace(/\b(?:token|password|secret|credential|api[_-]?key)\s*[=:]\s*(?:"[^"]*"|'[^']*'|\S+)/gi,"[redacted]").replace(/\b[A-Z][A-Z0-9_]{2,}\s*=\s*(?:"[^"]*"|'[^']*'|\S+)/g,"[redacted]").replace(/(?:\/home\/[^/\s]+|\/Users\/[^/\s]+|\/data\/(?:data|user\/\d+)\/[^/\s]+)(?:\/[^\s]*)?/g,"[private path]").replace(/\b[A-Za-z]:\\Users\\[^\\\s]+(?:\\[^\s]*)?/g,"[private path]")}function hN(e,t=sN){const n=y_(e&&e.title),s=y_(e&&e.body),o=[n,s&&s!==n?s:""].filter(Boolean).join(". "),a=Array.from(o);return a.length<=t?o:`${a.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function fN(e){try{return!!(e&&e.visibilityState==="visible"&&typeof e.hasFocus=="function"&&e.hasFocus())}catch{return!1}}function Fw(e=js()){if(!To(e))return!1;try{return e.speechSynthesis.cancel(),!0}catch{return!1}}function pN(e){try{e&&typeof e.dispatchEvent=="function"&&typeof e.Event=="function"&&e.dispatchEvent(new e.Event(mh))}catch{}}function mN(e,t,n=js(),s={}){var f;if(gh(n),!To(n))return Promise.resolve(!1);const o=cf(e);if(!o||(f=s.signal)!=null&&f.aborted)return Promise.resolve(!1);const a=Number.isFinite(s.timeoutMs)&&s.timeoutMs>0?s.timeoutMs:lN,u=s.setTimer||((_,b)=>setTimeout(_,b)),h=s.clearTimer||(_=>clearTimeout(_)),p=s.signal;return pN(n),new Promise(_=>{let b=!1,y=!1,w=null,S=null;const x=C=>{if(!b){if(b=!0,p&&S&&p.removeEventListener("abort",S),w!==null&&h(w),C)af.add(n);else try{n.speechSynthesis.cancel()}catch{}_(C)}};S=()=>x(!1),p&&p.addEventListener("abort",S,{once:!0});try{n.speechSynthesis.cancel();const C=new n.SpeechSynthesisUtterance(o);C.lang=zw(t),C.onstart=()=>{y=!0},C.onend=()=>x(y),C.onerror=()=>x(!1),w=u(()=>x(!1),a),n.speechSynthesis.speak(C)}catch{x(!1)}})}function gN(e={}){const t=e.scope||js(),n=e.document||t&&t.document,s=Number.isInteger(e.maxPending)&&e.maxPending>=0?e.maxPending:oN,o=Number.isFinite(e.watchdogMs)&&e.watchdogMs>0?e.watchdogMs:aN,a=Number.isFinite(e.dedupWindowMs)&&e.dedupWindowMs>0?e.dedupWindowMs:cN,u=Number.isInteger(e.maxDedup)&&e.maxDedup>0?e.maxDedup:uN,h=e.now||Date.now,p=e.setTimer||((F,D)=>setTimeout(F,D)),f=e.clearTimer||(F=>clearTimeout(F)),_=e.isPrimed||(()=>Ow(t));let b=null,y=null,w=[];const S=new Map,x=F=>{if(F&&typeof F.id=="string"&&F.id)return`id:${F.id}`;const D=Number(F&&F.ts),J=cf(F&&F.title);return Number.isFinite(D)&&J?`frame:${D}:${J}`:""},C=F=>{if(!F)return!0;const D=h();for(const[J,W]of S)D-W>=a&&S.delete(J);if(S.has(F))return!1;for(S.set(F,D);S.size>u;)S.delete(S.keys().next().value);return!0},k=()=>{y!==null&&f(y),y=null},R=()=>{k(),b&&(b.onend=null,b.onerror=null,b=null),Fw(t)},I=F=>{if(!To(t))return w=[],"unsupported";let D;try{D=new t.SpeechSynthesisUtterance(F.text),D.lang=zw(F.lang)}catch{return w=[],"error"}b=D;const J=()=>{if(b!==D)return;k(),b=null,D.onend=null,D.onerror=null;const W=w.shift();W&&I(W)};D.onend=J,D.onerror=J;try{return y=p(()=>{if(b!==D)return;b=null,D.onend=null,D.onerror=null;try{t.speechSynthesis.cancel()}catch{}k();const W=w.shift();W&&I(W)},o),t.speechSynthesis.speak(D),"speaking"}catch{return J(),"error"}};return{enqueue:(F,D)=>{if(!To(t))return"unsupported";const J=hN(F);if(!J)return"empty";if(!C(x(F)))return"duplicate";if(!fN(n))return"inactive";if(!_())return"unprimed";const W={text:J,lang:D};return F&&F.urgency==="high"?(w=[],R(),I(W)):b?s===0?"dropped":(w.length>=s&&w.shift(),w.push(W),"queued"):I(W)},stop:()=>{w=[],R()}}}function $w(){const[e,t]=N.useState(__);N.useEffect(()=>{const s=o=>{if((o==null?void 0:o.type)==="storage"&&o.key!==of&&o.key!==null)return;const a=(o==null?void 0:o.type)===al?lf(o.detail):__();t(a)};return window.addEventListener(al,s),window.addEventListener("storage",s),()=>{window.removeEventListener(al,s),window.removeEventListener("storage",s)}},[]);const n=N.useCallback(s=>{const o=dN({enabled:s===!0});return t(o),window.dispatchEvent(new CustomEvent(al,{detail:o})),o.enabled},[]);return[e.enabled,n]}function vN({text:e}){const[t,n]=N.useState(!1),s=async()=>{try{await navigator.clipboard.writeText(e),n(!0),setTimeout(()=>n(!1),1500)}catch{}};return c.jsxs("div",{className:"nc-set-copyline",children:[c.jsx("code",{children:e}),c.jsxs("button",{type:"button",className:"nc-btn ghost",onClick:s,children:[c.jsx(nt,{name:"copy",size:14})," ",g(t?"copied":"copy")]})]})}function _N({value:e}){const[t,n]=N.useState("");return N.useEffect(()=>{let s=!0;return _2.toDataURL(e,{margin:1,width:220}).then(o=>{s&&n(o)}).catch(()=>{}),()=>{s=!1}},[e]),t?c.jsx("img",{src:t,width:"220",height:"220",alt:"NexusCrew pairing QR"}):null}function yN({token:e,nodes:t,roster:n,settings:s,readonly:o,refresh:a,refreshAliases:u}){const[h,p]=N.useState(null),[f,_]=N.useState(null),[b,y]=N.useState({}),[w,S]=N.useState(null),[x,C]=N.useState({ssh:"",sshPort:"",name:""}),[k,R]=N.useState(""),[I,A]=N.useState(""),[G,F]=N.useState(""),[D,J]=N.useState(!1),[W,ee]=N.useState(null),[K,O]=N.useState(null),j=Date.now(),P=s&&s.deviceName||"",M=(t||[]).filter(Z=>Z&&Z.direction==="outbound"&&Z.name&&Z.ssh),H=M.find(Z=>Z.name===k)||M[0]||null,te=M.find(Z=>Z.name===I)||M[0]||null,T=te?gg(te.tunnel,j):null,ie=te!=null&&te.shared?T!=null&&T.up?"share-local-active":"share-local-pending":T!=null&&T.up?"share-local-private":"share-local-private-down",B=[{key:"peer-group-hubs",rows:(t||[]).filter(Z=>Z.kind!=="transitive"&&Z.relation!=="client")},{key:"peer-group-clients",rows:(t||[]).filter(Z=>Z.kind!=="transitive"&&Z.relation==="client")},{key:"peer-group-routed",rows:(t||[]).filter(Z=>Z.kind==="transitive")}],L=async(Z,q)=>{p(null),_(`${Z}:${q}`);try{const fe=await Rh(e,Z,q);q==="test"&&y(Ie=>({...Ie,[Z]:fe})),await a()}catch(fe){p(`${Z}: ${String(fe.message||fe)}`)}_(null)},$=async Z=>{p(null),_(`${Z}:remove`);try{await f0(e,Z),O(null),await a()}catch(q){p(`${Z}: ${String(q.message||q)}`)}_(null)},X=Z=>ee({name:Z.name,direction:Z.direction,label:Z.label||Z.name,ssh:Z.ssh||"",sshPort:Z.sshPort?String(Z.sshPort):"",autostart:Z.autostart===!0,visibility:Z.visibility||"network",selected:[...Z.selected||[]]}),ae=async()=>{if(!W||!bs(W.label)){p(g("err-label"));return}const Z=W.direction==="inbound"?{label:W.label,visibility:W.visibility,selected:W.visibility==="selected"?W.selected:[]}:{label:W.label,ssh:W.ssh,autostart:W.autostart,...W.sshPort?{sshPort:Number(W.sshPort)}:{}};p(null),_(`${W.name}:edit`);try{await h0(e,W.name,Z),ee(null),await a()}catch(q){p(`${W.name}: ${String(q.message||q)}`)}_(null)},ue=async Z=>{if(te){p(null),_(`${te.name}:share`);try{await p0(e,te.name,Z),await a()}catch(q){const fe=q!=null&&q.data&&q.data.shared===!1?q.data:null;if(fe)try{await a()}catch{}const Ie=q!=null&&q.data&&typeof q.data.hint=="string"?q.data.hint:"",et=(fe==null?void 0:fe.revoked)===!0&&(fe==null?void 0:fe.localReconcilePending)===!0?g("share-off-local-reconcile-pending"):(fe==null?void 0:fe.revoked)===!1&&(fe==null?void 0:fe.reconcilePending)===!0?g("share-off-hub-reconcile-pending"):"";p(`${te.name}: ${String(q.message||q)}${Ie?` — ${Ie}`:""}${et?` — ${et}`:""}`)}_(null)}},ge=async()=>{if(p(null),H){const fe=mg({name:H.name,ssh:H.ssh,sshPort:H.sshPort||""});if(!fe.ok){p(g(fe.error));return}_("invite");try{S(await Zm(e,{ssh:fe.value.ssh,...fe.value.sshPort?{sshPort:fe.value.sshPort}:{}},[H.name]))}catch(Ie){p(String(Ie.message||Ie))}_(null);return}const Z=dr(x.name||G||P||"NexusCrew"),q=mg({name:Z,ssh:x.ssh,sshPort:x.sshPort});if(!q.ok){p(g(q.error));return}_("invite");try{S(await Zm(e,{...G||P?{label:G||P}:{},name:Z,ssh:q.value.ssh,...q.value.sshPort?{sshPort:q.value.sshPort}:{}}))}catch(fe){p(String(fe.message||fe))}_(null)};return c.jsxs("div",{className:"nc-set-tab",children:[c.jsx("div",{className:"nc-sheet-label",children:g("peer-inventory-title")}),(t||[]).length===0&&c.jsx("div",{className:"nc-empty",children:g("no-nodes")}),B.map(Z=>Z.rows.length>0&&c.jsxs("div",{className:"nc-peer-group",children:[c.jsxs("div",{className:"nc-peer-group-title",children:[g(Z.key)," ",c.jsx("span",{children:Z.rows.length})]}),Z.rows.map(q=>{var Fe,Ct;const fe=q.kind==="transitive",Ie=fe?{up:q.stale!==!0,label:q.stale===!0?"peer-routed-stale":"peer-routed"}:gg(q.tunnel,j),et=b[q.name],ze=q.actions||{};return c.jsxs("div",{className:`nc-set-node${fe?" routed":""}`,children:[c.jsxs("div",{className:"nc-set-node-head",children:[c.jsx("span",{className:`nc-dot ${Ie.up?"on":""}`}),c.jsx("b",{children:q.label||q.name}),c.jsxs("small",{children:[q.name,fe?` · ${q.route.join(" → ")}`:q.direction==="outbound"?` · SSH ${q.ssh||""}`:` · ${g("node-connected-client")}`,(Fe=q.tunnel)!=null&&Fe.transport?` · ${q.tunnel.transport} ${g("transport-used")}`:""]}),c.jsxs("span",{className:`nc-set-tunnel${Ie.up?" up":""}`,children:[g(Ie.label),Ie.since?` · ${Ie.since}`:""]})]}),!fe&&q.direction==="inbound"&&c.jsx("div",{className:"nc-set-info",children:g(q.shared?"peer-shared":"peer-private")}),ze.visibility&&q.shared&&c.jsxs(c.Fragment,{children:[c.jsxs("select",{value:q.visibility||"network",disabled:o||!!f,onChange:async Ge=>{_(`${q.name}:visibility`);try{await tg(e,q.name,Ge.target.value),await a()}catch(rt){p(String(rt.message||rt))}_(null)},children:[c.jsx("option",{value:"network",children:g("visibility-network")}),c.jsx("option",{value:"relay-only",children:g("visibility-relay")}),c.jsx("option",{value:"selected",children:g("visibility-selected")})]}),q.visibility==="selected"&&c.jsx("div",{className:"nc-set-row",children:(t||[]).filter(Ge=>Ge.name!==q.name&&Ge.nodeId).map(Ge=>{const rt=(q.selected||[]).includes(Ge.nodeId);return c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:rt,disabled:o||!!f,onChange:async ut=>{const ct=ut.target.checked?[...q.selected||[],Ge.nodeId]:(q.selected||[]).filter(vt=>vt!==Ge.nodeId);_(`${q.name}:visibility`);try{await tg(e,q.name,"selected",ct),await a()}catch(vt){p(String(vt.message||vt))}_(null)}})," ",Ge.label||Ge.name]},Ge.nodeId)})})]}),c.jsxs("div",{className:"nc-set-node-actions",children:[ze.edit&&c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:o||!!f,onClick:()=>X(q),children:g("edit")}),ze.test&&c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!!f,onClick:()=>L(q.name,"test"),children:g("node-test")}),ze.disconnect&&Ie.up&&c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:o||!!f,onClick:()=>L(q.name,"down"),children:g("tunnel-stop")}),ze.connect&&!Ie.up&&c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:o||!!f,onClick:()=>L(q.name,"up"),children:g("tunnel-start")}),ze.restart&&c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:o||!!f,onClick:()=>L(q.name,"restart"),children:g("tunnel-restart")}),ze.remove&&c.jsxs("button",{type:"button",className:"nc-btn danger",disabled:o||!!f,title:g(o?"settings-readonly":"delete"),onClick:()=>O(q.name),children:[c.jsx(nt,{name:"trash",size:14})," ",g("delete")]})]}),(W==null?void 0:W.name)===q.name&&c.jsxs("div",{className:"nc-set-form nc-node-editor",children:[c.jsxs("label",{className:"nc-field",children:[g("node-display-label"),c.jsx("input",{value:W.label,disabled:!!f,onChange:Ge=>ee({...W,label:Ge.target.value})})]}),W.direction==="outbound"?c.jsxs(c.Fragment,{children:[c.jsxs("label",{className:"nc-field",children:[g("node-ssh-label"),c.jsx("input",{value:W.ssh,disabled:!!f,onChange:Ge=>ee({...W,ssh:Ge.target.value})})]}),c.jsxs("label",{className:"nc-field",children:[g("node-ssh-port-label"),c.jsx("input",{inputMode:"numeric",value:W.sshPort,disabled:!!f,onChange:Ge=>ee({...W,sshPort:Ge.target.value.replace(/[^0-9]/g,"").slice(0,5)})})]}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:W.autostart,disabled:!!f,onChange:Ge=>ee({...W,autostart:Ge.target.checked})})," ",g("boot-persist")]})]}):c.jsxs("label",{className:"nc-field",children:[g("peer-visibility"),c.jsxs("select",{value:W.visibility,disabled:!!f,onChange:Ge=>ee({...W,visibility:Ge.target.value}),children:[c.jsx("option",{value:"network",children:g("visibility-network")}),c.jsx("option",{value:"relay-only",children:g("visibility-relay")}),c.jsx("option",{value:"selected",children:g("visibility-selected")})]})]}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn primary",disabled:!!f,onClick:ae,children:g("save")}),c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!!f,onClick:()=>ee(null),children:g("cancel")})]})]}),K===q.name&&c.jsxs("div",{className:"nc-set-confirm",children:[c.jsx("b",{children:g("node-remove-confirm").replace("{name}",q.label||q.name)}),c.jsx("small",{children:g("node-remove-warning")}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn danger",disabled:!!f,onClick:()=>$(q.name),children:g("delete")}),c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!!f,onClick:()=>O(null),children:g("cancel")})]})]}),((Ct=q.health)==null?void 0:Ct.detail)&&c.jsx("div",{className:`nc-set-test${q.health.status==="healthy"?" ok":q.health.status==="passive"?"":" ko"}`,children:q.health.detail}),et&&c.jsxs("div",{className:`nc-set-test${et.ok?" ok":" ko"}`,children:[et.result,et.detail?` — ${et.detail}`:""]})]},`${q.kind||"direct"}:${q.nodeId||q.name}`)})]},Z.key)),(n||[]).some(Z=>!Z.direct&&Z.instanceId)&&c.jsxs("div",{className:"nc-set-form",children:[c.jsx("div",{className:"nc-sheet-label",children:g("routed-node-aliases")}),c.jsx("small",{className:"nc-set-hint",children:g("routed-node-aliases-help")}),(n||[]).filter(Z=>!Z.direct&&Z.instanceId).map(Z=>c.jsxs("div",{className:"nc-set-node",children:[c.jsxs("div",{className:"nc-set-node-head",children:[c.jsx("span",{className:`nc-dot ${Z.status==="up"?"on":""}`}),c.jsx("b",{children:Z.label||Z.name}),c.jsx("small",{children:(Z.route||[]).join(" › ")})]}),c.jsxs("div",{className:"nc-set-node-actions",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:o||!!f,onClick:async()=>{const q=window.prompt(g("node-local-alias"),Z.alias||"");if(q!=null){if(q.trim()&&!bs(q.normalize("NFC"))){p(g("err-label"));return}_(`${Z.instanceId}:alias`),p(null);try{q.trim()?await d0(e,Z.instanceId,q):await eg(e,Z.instanceId),u()}catch(fe){p(String(fe.message||fe))}_(null)}},children:g("alias-on-device")}),Z.alias&&c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:o||!!f,onClick:async()=>{_(`${Z.instanceId}:alias-reset`),p(null);try{await eg(e,Z.instanceId),u()}catch(q){p(String(q.message||q))}_(null)},children:g("reset-alias")})]})]},Z.instanceId))]}),te&&c.jsxs("div",{className:"nc-set-form nc-local-share",children:[c.jsx("div",{className:"nc-sheet-label",children:g("share-local-heading")}),M.length>1&&c.jsxs("label",{className:"nc-field",children:[g("share-local-hub"),c.jsx("select",{value:te.name,disabled:o||!!f,onChange:Z=>A(Z.target.value),children:M.map(Z=>c.jsx("option",{value:Z.name,children:Z.label||Z.name},Z.name))})]}),c.jsxs("label",{className:"nc-check nc-node-share",children:[c.jsx("input",{type:"checkbox",checked:te.shared===!0,disabled:o||!!f,onChange:Z=>ue(Z.target.checked)}),c.jsxs("span",{children:[c.jsx("b",{children:g("share-local-through").replace("{device}",P||g("local")).replace("{hub}",te.label||te.name)}),c.jsx("small",{children:g(te.shared?"share-node-on-desc":"share-node-off-desc")})]})]}),c.jsx("div",{className:`nc-set-test${te.shared&&(T!=null&&T.up)?" ok":T!=null&&T.up?"":" ko"}`,children:g(ie)}),!(T!=null&&T.up)&&c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:o||!!f,onClick:()=>ue(te.shared===!0),children:g("share-local-reconnect")})]}),c.jsx(Nw,{token:e,deviceDefault:P,localNodeId:s&&s.nodeId||"",localNameDefault:s&&s.localName||"",readonly:o,onSuccess:a}),c.jsxs("div",{className:"nc-set-form",children:[c.jsx("div",{className:"nc-sheet-label",children:g("invite-node")}),c.jsx("small",{className:"nc-set-hint",children:g(H?"invite-network-hint":"invite-v2-hint")}),H?c.jsxs(c.Fragment,{children:[M.length>1&&c.jsxs("label",{className:"nc-field",children:[g("invite-network-label"),c.jsx("select",{value:H.name,disabled:o||!!f,onChange:Z=>{R(Z.target.value),S(null)},children:M.map(Z=>c.jsx("option",{value:Z.name,children:Z.label||Z.name},Z.name))})]}),c.jsxs("div",{className:"nc-set-info nc-invite-endpoint",children:[g("invite-network-via"),": ",c.jsx("b",{children:H.label||H.name})," · ",H.ssh,H.sshPort?`:${H.sshPort}`:""]}),c.jsx("small",{className:"nc-set-hint",children:g("invite-network-route")})]}):c.jsxs("label",{className:"nc-field",children:[g("invite-endpoint-label"),c.jsx("input",{placeholder:"user@host",value:x.ssh,disabled:o,onChange:Z=>C({...x,ssh:Z.target.value})}),c.jsx("small",{className:"nc-set-hint",children:g("invite-endpoint-needed")})]}),!H&&D&&c.jsxs("div",{className:"nc-invite-advanced",children:[c.jsxs("label",{className:"nc-field",children:[g("node-ssh-port-label"),c.jsx("input",{inputMode:"numeric",placeholder:"22",value:x.sshPort,disabled:o,onChange:Z=>C({...x,sshPort:Z.target.value.replace(/[^0-9]/g,"").slice(0,5)})})]}),c.jsxs("label",{className:"nc-field",children:[g("device-name-label"),c.jsx("input",{placeholder:P||"NexusCrew",value:G,disabled:o,onChange:Z=>F(Z.target.value)}),c.jsx("small",{className:"nc-set-hint",children:g("device-name-hint")})]}),c.jsxs("label",{className:"nc-field",children:[g("node-name-label"),c.jsx("input",{placeholder:dr(G||P||g("node-name-ph")),value:x.name,disabled:o,onChange:Z=>C({...x,name:Z.target.value?dr(Z.target.value):""})})]})]}),c.jsxs("div",{className:"nc-set-row nc-invite-actions",children:[c.jsx("button",{type:"button",className:"nc-btn primary",disabled:o||!!f||!H&&!x.ssh.trim(),onClick:ge,children:g("create-pairing-link")}),!H&&c.jsxs("button",{type:"button",className:"nc-btn ghost",disabled:!!f,onClick:()=>J(Z=>!Z),children:[D?"▾":"▸"," ",g("pair-advanced")]})]}),w&&c.jsxs(c.Fragment,{children:[c.jsx(_N,{value:w.pairingUrl}),c.jsx(vN,{text:w.pairingUrl}),c.jsx("div",{className:"nc-set-info",children:g("invite-next-steps")})]})]}),h&&c.jsx("div",{className:"nc-err",children:h})]})}function wN({token:e,readonly:t}){const[n,s]=N.useState("idle"),[o,a]=N.useState(!1),[u,h]=N.useState(null);N.useEffect(()=>{let f=!1;return j2().then(_=>{f||s(_)}),()=>{f=!0}},[]);const p=async()=>{h(null),a(!0);try{n==="subscribed"?(await D2(e),s("idle")):(await L2(e),s("subscribed"))}catch(f){const _=String(f.message||f);_==="push-denied"?(s("denied"),h(g("push-denied"))):_==="push-unsupported"?(s("unsupported"),h(g("push-unsupported"))):h(_)}a(!1)};return n==="unsupported"?c.jsx("div",{className:"nc-set-info",children:g("push-unsupported")}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:t||o||n==="denied",title:t?g("settings-readonly"):"",onClick:p,children:g(n==="subscribed"?"push-disable":"push-enable")}),c.jsx("span",{className:"nc-set-info",children:g(n==="subscribed"?"push-on":n==="denied"?"push-denied":"push-off")})]}),u&&c.jsx("div",{className:"nc-err",children:u})]})}function SN(){const[e,t]=$w(),[n,s]=N.useState(""),[o,a]=N.useState(""),[u,h]=N.useState(!1),[p,f]=N.useState(Ow),_=N.useRef(0),b=N.useRef(!1),y=N.useRef(null),w=To();N.useEffect(()=>()=>{var C;_.current+=1,b.current&&((C=y.current)==null||C.abort(),y.current=null,b.current=!1,gh())},[]);const S=async()=>{const C=_.current+=1,k=typeof AbortController=="function"?new AbortController:null;s(""),a(""),h(!0),f(!1),b.current=!0,y.current=k;const R=await mN(g("notification-speech-preview"),vl(),void 0,k?{signal:k.signal}:{});return C!==_.current||(y.current=null,b.current=!1,h(!1),f(R),R?a(g("notification-speech-preview-ok")):s(g("notification-speech-preview-failed"))),R},x=C=>{var k;if(t(C),s(""),a(""),C)S();else{_.current+=1;const R=b.current;(k=y.current)==null||k.abort(),y.current=null,b.current=!1,h(!1),f(!1),gh(),R||Fw()}};return c.jsxs("div",{className:"nc-set-form",children:[c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox","aria-label":g("notification-speech-enable"),checked:e,disabled:!w,onChange:C=>x(C.target.checked)}),c.jsxs("span",{children:[c.jsx("b",{children:g("notification-speech-enable")}),c.jsx("small",{children:g("notification-speech-help")})]})]}),w?c.jsx("div",{className:"nc-set-row",children:c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!e||u,onClick:()=>{S()},children:g(u?"notification-speech-testing":"notification-speech-test")})}):c.jsx("div",{className:"nc-set-info",children:g("notification-speech-unsupported")}),e&&!p&&!u&&!n&&c.jsx("div",{className:"nc-set-info",children:g("notification-speech-needs-test")}),o&&c.jsx("div",{className:"nc-set-info",role:"status",children:o}),n&&c.jsx("div",{className:"nc-err",children:n})]})}function bN(){const[e,t]=Vh();return c.jsxs("div",{className:"nc-set-tab nc-input-settings",children:[c.jsx("div",{className:"nc-set-info",children:g("input-settings-local")}),c.jsxs("div",{className:"nc-set-form",children:[c.jsxs("label",{className:"nc-field",children:[g("terminal-keyboard-gesture"),c.jsx("select",{"aria-label":g("terminal-keyboard-gesture"),value:e.terminalKeyboardGesture,onChange:n=>t({terminalKeyboardGesture:n.target.value}),children:sw.map(n=>c.jsx("option",{value:n,children:g(`terminal-keyboard-${n}`)},n))}),c.jsx("small",{children:g("terminal-keyboard-gesture-help")})]}),c.jsxs("label",{className:"nc-field",children:[g("keybar-layout"),c.jsx("select",{"aria-label":g("keybar-layout"),value:e.keybarLayout,onChange:n=>t({keybarLayout:n.target.value}),children:ow.map(n=>c.jsx("option",{value:n,children:g(`keybar-layout-${n}`)},n))}),c.jsx("small",{children:g("keybar-layout-help")})]})]}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:e.keybarKeepsKeyboardClosed,onChange:n=>t({keybarKeepsKeyboardClosed:n.target.checked})}),c.jsxs("span",{children:[c.jsx("b",{children:g("keybar-ime-lock")}),c.jsx("small",{children:g("keybar-ime-lock-help")})]})]}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:e.voiceKeepsKeyboardClosed,onChange:n=>t({voiceKeepsKeyboardClosed:n.target.checked})}),c.jsxs("span",{children:[c.jsx("b",{children:g("voice-ime-lock")}),c.jsx("small",{children:g("voice-ime-lock-help")})]})]}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:e.showKeybarEnter,onChange:n=>t({showKeybarEnter:n.target.checked})}),c.jsxs("span",{children:[c.jsx("b",{children:g("keybar-enter-show")}),c.jsx("small",{children:g("keybar-enter-show-help")})]})]}),c.jsx("div",{className:"nc-set-row",children:c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>t(lr),children:g("input-settings-reset")})})]})}function kN({token:e,roster:t=[],readonly:n}){const s=[{key:"local",route:[],label:g("diagnostics-local"),status:"up"},...t.filter(M=>Array.isArray(M.route)&&M.route.length).map(M=>({key:M.route.join("/"),route:M.route,label:M.label||M.name,status:M.status}))],[o,a]=N.useState("local"),u=s.find(M=>M.key===o)||s[0],[h,p]=N.useState(null),[f,_]=N.useState([]),[b,y]=N.useState(""),[w,S]=N.useState(!1),[x,C]=N.useState(!0),[k,R]=N.useState(900),[I,A]=N.useState("all"),[G,F]=N.useState(""),D=N.useRef(0),J=N.useRef(null),W=N.useCallback(async()=>{try{const M=await _0(e,u.route);if(p(M),y(""),!w){const H=await y0(e,{after:D.current,limit:200},u.route);Array.isArray(H.records)&&H.records.length&&(D.current=H.cursor,_(te=>[...te,...H.records].slice(-500)))}}catch(M){y(M&&M.status===404?g("diagnostics-unsupported"):String(M.message||M))}},[e,u.key,w]);N.useEffect(()=>{D.current=0,_([]),p(null),y("")},[u.key]),N.useEffect(()=>{let M=null,H=!0;const te=()=>{!H||document.visibilityState==="hidden"||W()},T=()=>{M&&clearInterval(M),M=document.visibilityState==="hidden"?null:setInterval(te,2e3),document.visibilityState!=="hidden"&&te()};return document.addEventListener("visibilitychange",T),T(),()=>{H=!1,M&&clearInterval(M),document.removeEventListener("visibilitychange",T)}},[W]),N.useEffect(()=>{x&&J.current&&(J.current.scrollTop=J.current.scrollHeight)},[f,x]);const ee=f.filter(M=>(I==="all"||M.level===I)&&(!G||String(M.component||"").toLowerCase().includes(G.toLowerCase()))),K=ee.map(M=>`${M.ts} ${M.level.toUpperCase()} ${M.component} ${M.code} ${M.message}${Object.keys(M.meta||{}).length?` ${JSON.stringify(M.meta)}`:""}`).join(`
92
92
  `),O=async M=>{y("");try{const H=await M();p(H),await W()}catch(H){y(String(H.message||H))}},j=async()=>{try{await navigator.clipboard.writeText(K)}catch{y(g("copy-manual"))}},P=()=>{try{const M=new Blob([`${JSON.stringify(ee,null,2)}
93
- `],{type:"application/json"}),H=URL.createObjectURL(M),te=document.createElement("a");te.href=H,te.download="nexuscrew-diagnostics.json",te.click(),URL.revokeObjectURL(H)}catch{y(g("diagnostics-export-failed"))}};return c.jsxs("div",{className:"nc-set-tab nc-diagnostics",children:[c.jsxs("label",{className:"nc-field",children:[g("diagnostics-target"),c.jsx("select",{value:u.key,onChange:M=>a(M.target.value),children:s.map(M=>c.jsxs("option",{value:M.key,children:[M.label,M.status!=="up"?` · ${M.status}`:""]},M.key))})]}),c.jsxs("div",{className:"nc-set-form nc-diag-controls",children:[c.jsx("div",{className:"nc-sheet-label",children:g("diagnostics-verbose")}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("select",{"aria-label":g("diagnostics-duration"),value:k,onChange:M=>R(Number(M.target.value)),disabled:n,children:[300,900,1800,3600].map(M=>c.jsxs("option",{value:M,children:[M/60," min"]},M))}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(h==null?void 0:h.verbose)===!0,onClick:()=>O(()=>ng(e,!0,k,u.route)),children:g("enable")}),c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||(h==null?void 0:h.verbose)!==!0,onClick:()=>O(()=>ng(e,!1,k,u.route)),children:g("stop")})]}),c.jsx("small",{className:"nc-set-hint",children:h!=null&&h.verbose?g("diagnostics-expires").replace("{time}",new Date(h.expiresAt).toLocaleTimeString()):g("diagnostics-off")})]}),c.jsxs("div",{className:"nc-diag-filters",children:[c.jsxs("select",{"aria-label":g("diagnostics-level"),value:I,onChange:M=>A(M.target.value),children:[c.jsx("option",{value:"all",children:g("diagnostics-all-levels")}),["debug","info","warn","error"].map(M=>c.jsx("option",{value:M,children:M},M))]}),c.jsx("input",{"aria-label":g("diagnostics-component"),placeholder:g("diagnostics-component"),value:G,onChange:M=>F(M.target.value)})]}),c.jsxs("div",{className:"nc-set-row",children:[c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:w,onChange:M=>S(M.target.checked)})," ",g("diagnostics-pause")]}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:x,onChange:M=>C(M.target.checked)})," ",g("diagnostics-autoscroll")]})]}),c.jsx("pre",{ref:J,className:"nc-diag-log","aria-label":g("diagnostics-log"),children:K||g("diagnostics-empty")}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:j,children:g("copy")}),c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:P,children:g("diagnostics-export")}),c.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(g("diagnostics-clear-confirm"))&&O(async()=>{const M=await w0(e,u.route);return D.current=0,_([]),M})},children:g("diagnostics-clear")})]}),b&&c.jsx("div",{className:"nc-err",children:b})]})}function xN({token:e,settings:t,readonly:n,refresh:s}){const[o,a]=N.useState(null),[u,h]=N.useState(null),[p,f]=N.useState(!1),[_,b]=N.useState(!1),[y,w]=N.useState(null),[S,x]=N.useState(!0);N.useEffect(()=>{w(t&&t.update||null),x(!t||t.autoUpdate!==!1)},[t]);const C=async()=>{a(null),h(null),b(!0);try{const D=await l0(e);h(D.note||"ok"),f(!1)}catch(D){a(String(D.message||D))}b(!1)},k=async()=>{a(null),h(null),b(!0);try{const D=await m0(e);h(`${D.note||"ok"}${D.target?` (${D.target})`:""}`)}catch(D){a(String(D.message||D))}b(!1)},R=async D=>{a(null),h(null),b(!0);try{await A_(e,{autoUpdate:D}),x(D),s&&await s()}catch(J){a(String(J.message||J))}b(!1)},I=async()=>{a(null),h(null),b(!0);try{w(await g0(e))}catch(D){a(String(D.message||D))}b(!1)},A=async()=>{a(null),h(null),b(!0);try{const D=await v0(e);w(D),h(g("npm-update-restarting"))}catch(D){a(String(D.message||D))}b(!1)},G=()=>{window.confirm(g("composer-clear-confirm"))&&(a(null),aE()?(window.dispatchEvent(new Event(ch)),h(g("composer-clear-done"))):a(g("composer-clear-failed")))},F=t&&t.service;return c.jsxs("div",{className:"nc-set-tab",children:[t&&c.jsxs("div",{className:"nc-set-info",children:["v",t.version," · ",t.platform," · :",t.port,c.jsx("br",{}),F&&F.installed?g("service-installed"):g("service-missing"),F&&F.installed?` · ${F.active?g("service-active"):g("service-inactive")}`:"",F?` · boot ${F.boot?"on":"off"}`:""]}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||_,title:n?g("settings-readonly"):"",onClick:()=>{a(null),h(null),f(!0)},children:g("token-rotate")}),c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||_,title:n?g("settings-readonly"):"",onClick:k,children:g("service-regenerate")})]}),c.jsxs("div",{className:"nc-set-form nc-update-settings",children:[c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:S,disabled:n||_||y&&!y.supported,onChange:D=>R(D.target.checked)}),c.jsxs("span",{children:[c.jsx("b",{children:g("npm-auto-update")}),c.jsx("small",{children:g("npm-auto-update-help")})]})]}),y&&c.jsxs("div",{className:"nc-set-info",children:[g("npm-update-current")," v",y.current,y.latest?` · ${g("npm-update-latest")} v${y.latest}`:""," · ",g(`npm-update-${y.supported?y.phase:"unsupported"}`)]}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||_||!y||!y.supported,onClick:I,children:g("npm-update-check")}),y&&y.available&&c.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||_||y.phase==="installing",onClick:A,children:g("npm-update-install")})]}),y&&y.lastError&&c.jsx("div",{className:"nc-err",children:y.lastError})]}),c.jsx(wN,{token:e,readonly:n}),c.jsx(SN,{}),c.jsxs("div",{className:"nc-set-form",children:[c.jsx("div",{className:"nc-sheet-label",children:g("composer-clear-data")}),c.jsx("small",{className:"nc-set-hint",children:g("composer-clear-data-help")}),c.jsx("div",{className:"nc-set-row",children:c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:G,children:g("composer-clear-data")})})]}),p&&c.jsxs("div",{className:"nc-set-confirm",children:[c.jsx("div",{children:g("token-rotate-explain")}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>f(!1),children:g("cancel")}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:_,onClick:C,children:g("confirm")})]})]}),u&&c.jsx("div",{className:"nc-set-note",children:u}),o&&c.jsx("div",{className:"nc-err",children:o})]})}function CN({token:e,onClose:t,initialTab:n="nodes",initialLocation:s="",startNewCell:o=!1}){zn();const[a,u]=N.useState(n),[h,p]=N.useState(null),[f,_]=N.useState([]),[b,y]=N.useState(!1),[w,S]=N.useState(null),[x,C]=N.useState(0),k=jh(e,!0,x),R=N.useCallback(async()=>{try{const I=await T_(e);p(I),S(null)}catch(I){S(String(I.message||I))}try{const I=await o0(e);_(I.peers||[])}catch(I){S(String(I.message||I))}},[e]);return N.useEffect(()=>{R();const I=setInterval(R,5e3);return()=>clearInterval(I)},[R]),N.useEffect(()=>{let I=!1;return tn("/api/config",e).then(A=>A.json()).then(A=>{I||y(!!A.readonlyDefault)}).catch(()=>{}),()=>{I=!0}},[e]),c.jsx("div",{className:"nc-set-overlay",onClick:t,children:c.jsxs("div",{className:"nc-set-panel",onClick:I=>I.stopPropagation(),children:[c.jsxs("div",{className:"nc-set-head",children:[c.jsx(nt,{name:"gear",size:18}),c.jsx("b",{children:g("settings")}),c.jsx("button",{type:"button",className:"nc-set-close",onClick:t,title:g("close"),children:c.jsx(nt,{name:"x",size:18})})]}),b&&c.jsx("div",{className:"nc-set-readonly",children:g("settings-readonly")}),w&&c.jsx("div",{className:"nc-err",children:w}),c.jsx("div",{className:"nc-set-tabs",children:["nodes","fleet","input","diagnostics","system"].map(I=>c.jsx("button",{type:"button",className:`nc-set-tabbtn${a===I?" on":""}`,onClick:()=>u(I),children:g(`tab-${I}`)},I))}),c.jsxs("div",{className:"nc-set-body",children:[a==="nodes"&&c.jsx(yN,{token:e,nodes:f,roster:k,settings:h,readonly:b,refresh:R,refreshAliases:()=>C(I=>I+1)}),a==="fleet"&&c.jsx(rN,{token:e,readonly:b,startNewCell:o,initialLocation:s,targets:k.map(I=>({route:I.route,label:I.label||I.name,status:I.status}))}),a==="input"&&c.jsx(bN,{}),a==="diagnostics"&&c.jsx(kN,{token:e,roster:k,readonly:b}),a==="system"&&c.jsx(xN,{token:e,settings:h,readonly:b,refresh:R})]})]})})}function EN({token:e,initialPair:t,deviceDefault:n="",localNodeId:s="",localNameDefault:o="",onPairDone:a,onDone:u}){zn();const[h,p]=N.useState(t?"pair":"welcome"),[f,_]=N.useState(!1),[b,y]=N.useState(null),w=async()=>{_(!0),y(null);try{await A_(e,{wizardDone:!0}),a&&a(),u()}catch(S){y(String(S.message||S)),_(!1)}};return c.jsx("div",{className:"nc-wiz-overlay",children:c.jsxs("div",{className:"nc-wiz",children:[c.jsxs("div",{className:"nc-wiz-head",children:[c.jsx("b",{children:g("wizard-title")}),c.jsx("small",{children:g("hydra-simple")})]}),h==="welcome"&&c.jsxs("div",{className:"nc-wiz-body",children:[c.jsx("div",{className:"nc-wiz-done",children:g("local-ready")}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{className:"nc-btn ghost",disabled:f,onClick:w,children:g("local-only")}),c.jsx("button",{className:"nc-btn primary",disabled:f,onClick:()=>p("pair"),children:g("add-node")})]})]}),h==="pair"&&c.jsxs("div",{className:"nc-wiz-body",children:[c.jsx(Nw,{token:e,initial:t||"",autoStart:!!t,deviceDefault:n,localNodeId:s,localNameDefault:o,onBusyChange:_,onSuccess:async()=>{a&&a(),p("done")}}),c.jsx("div",{className:"nc-sheet-actions",children:c.jsx("button",{className:"nc-btn ghost",disabled:f,onClick:()=>{a&&a(),p("welcome")},children:g("back")})})]}),h==="done"&&c.jsxs("div",{className:"nc-wiz-body",children:[c.jsx("div",{className:"nc-wiz-done",children:g("node-connected")}),c.jsx("div",{className:"nc-sheet-actions",children:c.jsx("button",{className:"nc-btn primary",disabled:f,onClick:w,children:g("finish")})})]}),b&&c.jsx("div",{className:"nc-err",children:b})]})})}function NN(e,t){if(typeof EventSource>"u"||!e)return()=>{};const n=new EventSource(`/api/events?token=${encodeURIComponent(e)}`);return n.onmessage=s=>{try{const o=JSON.parse(s.data);o&&typeof o=="object"&&typeof o.type=="string"&&t(o)}catch{}},()=>{try{n.close()}catch{}}}const RN=6e3,PN=12e3;function jN({n:e,onClose:t}){return c.jsxs("div",{className:`nc-ntf-toast${e.urgency==="high"?" high":""}`,role:"status","aria-live":"polite",children:[c.jsxs("div",{className:"nc-ntf-toast-txt",children:[c.jsx("b",{children:e.title}),e.body&&c.jsx("small",{children:e.body}),e.session&&c.jsx("span",{className:"nc-ntf-from",children:e.session})]}),c.jsx("button",{type:"button",className:"nc-ntf-x",onClick:t,title:g("close"),children:c.jsx(nt,{name:"x",size:14})})]})}function LN({ask:e,token:t,onAnswered:n}){const[s,o]=N.useState(""),[a,u]=N.useState(!1),[h,p]=N.useState(null),f=async _=>{const b=String(_||"").trim();if(!(!b||a)){p(null),u(!0);try{await b0(t,e.id,b),n(e.id)}catch(y){p(String(y.message||y))}u(!1)}};return c.jsxs("div",{className:"nc-ask-card",children:[c.jsxs("div",{className:"nc-ask-head",children:[c.jsx("span",{className:"nc-ntf-from",children:e.session}),c.jsxs("code",{className:"nc-ask-id",children:["#",e.id]})]}),c.jsx("div",{className:"nc-ask-q",children:e.question}),Array.isArray(e.options)&&e.options.length>0&&c.jsx("div",{className:"nc-ask-opts",children:e.options.map(_=>c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:a,onClick:()=>f(_),children:_},_))}),c.jsxs("div",{className:"nc-ask-reply",children:[c.jsx("textarea",{rows:2,placeholder:g("ask-reply-ph"),value:s,disabled:a,onChange:_=>o(_.target.value)}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:a||!s.trim(),onClick:()=>f(s),children:g("send")})]}),h&&c.jsx("div",{className:"nc-err",children:h})]})}function DN({token:e}){const[t]=zn(),[n]=$w(),[s,o]=N.useState([]),[a,u]=N.useState([]),[h,p]=N.useState(()=>{try{return/(?:^|[#&])ask=/.test(location.hash)}catch{return!1}}),f=N.useRef(0),_=N.useRef(null);_.current||(_.current=gN());const b=N.useRef({enabled:n,lang:t});b.current={enabled:n,lang:t};const y=N.useCallback(x=>{o(C=>C.filter(k=>k.key!==x))},[]),w=N.useCallback(x=>{const C=`t${f.current+=1}`;o(R=>[...R.slice(-3),{...x,key:C}]),setTimeout(()=>y(C),x.urgency==="high"?PN:RN);const k=b.current;if(k.enabled)try{_.current.enqueue(x,k.lang)}catch{}},[y]);N.useEffect(()=>{n||_.current.stop()},[n]),N.useEffect(()=>{const x=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&_.current.stop()},C=()=>_.current.stop();return document.addEventListener("visibilitychange",x),window.addEventListener("blur",x),window.addEventListener(mh,C),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("blur",x),window.removeEventListener(mh,C),_.current.stop()}},[]),N.useEffect(()=>{if(!e)return;let x=!1;S0(e).then(k=>{x||u(k.asks||[])}).catch(()=>{});const C=NN(e,k=>{k.type==="notify"?w(k):k.type==="ask"&&k.ask&&k.ask.id?u(R=>R.some(I=>I.id===k.ask.id)?R:[...R,k.ask]):k.type==="ask-answered"&&k.id&&u(R=>R.filter(I=>I.id!==k.id))});return()=>{x=!0,C()}},[e,w]);const S=x=>u(C=>C.filter(k=>k.id!==x));return c.jsxs(c.Fragment,{children:[s.length>0&&c.jsx("div",{className:"nc-ntf-toasts",children:s.map(x=>c.jsx(jN,{n:x,onClose:()=>y(x.key)},x.key))}),a.length>0&&!h&&c.jsxs("button",{type:"button",className:"nc-ask-badge",onClick:()=>p(!0),title:g("asks-title"),children:["? ",c.jsx("span",{className:"nc-ask-count",children:a.length})]}),a.length>0&&h&&c.jsxs("div",{className:"nc-ask-panel",children:[c.jsxs("div",{className:"nc-ask-panel-head",children:[c.jsx("b",{children:g("asks-title")}),c.jsx("span",{className:"nc-ask-count",children:a.length}),c.jsx("button",{type:"button",className:"nc-ntf-x",onClick:()=>p(!1),title:g("close"),children:c.jsx(nt,{name:"x",size:16})})]}),c.jsx("div",{className:"nc-ask-panel-body",children:a.map(x=>c.jsx(LN,{ask:x,token:e,onAnswered:S},x.id))})]})]})}const _d=e=>vi(Ar(e)).length===0,yd=e=>Array.isArray(e)?e.join("/"):"";function TN(e){const t=new Set,n=[];for(const s of Array.isArray(e)?e:[])!s||!Bn.test(String(s.instanceId||""))||!Array.isArray(s.route)||!s.route.length||t.has(s.instanceId)||(t.add(s.instanceId),n.push({instanceId:s.instanceId,route:[...s.route],label:String(s.label||s.name||s.route.join(" › ")),status:s.status||"offline"}));return n.sort((s,o)=>s.label.localeCompare(o.label))}function wo(e){return{instanceId:e.ownerId,route:e.ownerRoute||[],label:e.ownerLabel,status:e.available===!1?"offline":"up"}}function Rr(e,t,n,s=!1,o=!0){const a=t.instanceId;return{...e,id:ys(s?null:a,e.name),ownerId:a,ownerRoute:s?[]:[...t.route],ownerLabel:s?"Local":t.label,local:s,available:o,ownerTopology:Array.isArray(n)?n:[],layout:dh(e.layout,a,n)}}function MN(e,t,n,s,o=[]){const[a,u]=N.useState([]),[h,p]=N.useState(!1),[f,_]=N.useState("idle"),[b,y]=N.useState(""),[w,S]=N.useState(""),x=N.useRef([]),C=N.useRef([]),k=N.useRef(""),R=N.useRef(t),I=N.useRef(n),A=N.useRef(!1),G=N.useRef(!0),F=N.useRef(""),D=N.useMemo(()=>TN(o),[o]),J=D.map(B=>`${B.instanceId}:${yd(B.route)}:${B.status}:${B.label}`).join("|");C.current=D,I.current=n,R.current=t,x.current=a;const W=N.useCallback(B=>hh(B.layout,k.current,C.current),[]),ee=N.useCallback((B,L=!0,$=R.current)=>{const X=Rv(B,il()),ae=x.current.some(ge=>ge.id===$);x.current=X,u(X);const ue=X.find(ge=>ge.id===$);if(L&&ue){G.current=!0;const ge=W(ue);s(ge),ue.local&&LE(ue.name,ge)}else ae&&!ue&&(G.current=!0,s(_s()),y("deck non più condiviso dal nodo owner"));NE(X.filter(ge=>ge.local).map(ge=>ge.name))},[s,W]),K=N.useCallback(async B=>{let L=await Ya(e);const $=L.decks.find(X=>X.name==="main");if(L.decks.length===1&&$&&$.revision===0&&_d($.layout)){const X=EE(),ae=Ar(fh("main")||_s());if(!_d(ae)){const ue=dh(ae,B,[]);L.decks[0]=await Ga(e,"main",ue,0,[])}for(const ue of X.filter(ge=>ge!=="main"))try{let ge=await ig(e,ue,[]);const Z=Ar(fh(ue)||_s());_d(Z)||(ge=await Ga(e,ue,dh(Z,B,[]),ge.revision,[]))}catch{}L=await Ya(e)}return L},[e]),O=N.useCallback(async({migrate:B=!1}={})=>{const L=await Nh(e,[]),$=Bn.test(String(L.instanceId||""))?L.instanceId:"";if(!$)throw new Error("instanceId locale non disponibile");k.current=$,S($);const[X,ae]=await Promise.all([B?K($):Ya(e),Qm(e,[]).catch(()=>({nodes:[]}))]),ue={instanceId:$,route:[],label:"Local"},ge=X.decks.map(q=>Rr(q,ue,ae.nodes,!0,!0)),Z=x.current;return await Promise.all(C.current.map(async q=>{if(q.status!=="up"){ge.push(...Z.filter(fe=>!fe.local&&fe.ownerId===q.instanceId).map(fe=>({...fe,ownerRoute:[...q.route],ownerLabel:q.label,available:!1})));return}try{const[fe,Ie]=await Promise.all([Ya(e,q.route),Qm(e,q.route).catch(()=>({nodes:[]}))]);ge.push(...fe.decks.map(et=>Rr(et,q,Ie.nodes,!1,!0)))}catch{ge.push(...Z.filter(Ie=>!Ie.local&&Ie.ownerId===q.instanceId).map(Ie=>({...Ie,ownerRoute:[...q.route],ownerLabel:q.label,available:!1})))}})),ge.sort((q,fe)=>q.local===fe.local?q.ownerLabel.localeCompare(fe.ownerLabel)||(q.name==="main"?-1:fe.name==="main"?1:q.name.localeCompare(fe.name)):q.local?-1:1),ge},[e,K,J]);N.useEffect(()=>{if(!e)return;let B=!1;const L=F.current!==e;return F.current=e,O({migrate:L}).then($=>{if(B)return;const X=x.current.find(ge=>ge.id===R.current),ae=$.find(ge=>ge.id===R.current),ue=ae&&(!X||ae.revision>X.revision||X.available!==ae.available||yd(X.ownerRoute)!==yd(ae.ownerRoute));ee($,L||!!ue&&!A.current),p(!0),ae&&y("")}).catch($=>{B||(p(!0),y(String($.message||$)))}),()=>{B=!0}},[ee,O,J,e]);const j=N.useCallback(async(B=R.current)=>{if(!h||!A.current)return!0;const L=x.current.find($=>$.id===B);if(!L)return y(`deck inesistente: ${B}`),!1;if(L.available===!1)return y(`nodo owner offline: ${L.ownerLabel}`),!1;_("saving");try{const $=Ev(Ar(I.current),L.ownerId,L.ownerTopology),X=await Ga(e,L.name,$,L.revision,L.ownerRoute),ae=Rr(X,wo(L),L.ownerTopology,L.local,!0);return ee(x.current.map(ue=>ue.id===B?ae:ue),!1),A.current=!1,_("saved"),y(""),setTimeout(()=>_("idle"),1500),!0}catch($){if(_("error"),y(String($.message||$)),$.status===409&&$.data&&$.data.current){const X=x.current.find(ue=>ue.id===B),ae=Rr($.data.current,wo(X),X.ownerTopology,X.local,!0);ee(x.current.map(ue=>ue.id===B?ae:ue),!1)}return!1}},[h,e,ee]);return N.useEffect(()=>{if(!h)return;if(G.current){G.current=!1;return}A.current=!0,_("saving");const B=setTimeout(j,650);return()=>clearTimeout(B)},[n,h,j]),N.useEffect(()=>{if(!h)return;const B=setInterval(async()=>{try{const L=await O(),$=x.current.find(ue=>ue.id===R.current),X=L.find(ue=>ue.id===R.current),ae=X&&(!$||X.revision>$.revision||$.available!==X.available);ee(L,ae&&!A.current)}catch{}},5e3);return()=>clearInterval(B)},[h,O,ee]),{decks:a,records:a,localNodeId:w,ready:h,saveState:f,error:b,setError:y,saveNow:j,select:async B=>{if(A.current&&!await j(R.current))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const L=x.current.find($=>$.id===B);if(!L)throw new Error(`deck inesistente: ${B}`);return A.current=!1,G.current=!0,W(L)},add:async(B,L=null)=>{const $=L===mi?x.current.find(ue=>ue.local):L?x.current.find(ue=>ue.ownerId===L):null;if(!$||$.available===!1)throw new Error("nodo owner non disponibile");const X=await ig(e,B,$.ownerRoute),ae=Rr(X,wo($),$.ownerTopology,$.local,!0);return ee([...x.current,ae],!1),ae},rename:async(B,L)=>{const $=x.current.find(Z=>Z.id===B);if(!$)throw new Error("deck inesistente");if(B===R.current&&A.current&&!await j(B))throw new Error(`salvataggio di "${$.name}" fallito: rinomina annullata`);const X=x.current.find(Z=>Z.id===B);if(!X)throw new Error("deck inesistente");const ae=await k0(e,X.name,L,X.revision,X.ownerRoute),ue=Rr(ae,wo(X),X.ownerTopology,X.local,!0),ge=X.local?mi:X.ownerId;return qu(PE(il(),ge,B,ue.id)),ee(x.current.map(Z=>Z.id===B?ue:Z),!1),ue},remove:async B=>{const L=x.current.find(X=>X.id===B);if(!L)throw new Error("deck inesistente");B===R.current&&(A.current=!1),await x0(e,L.name,L.revision,L.ownerRoute);const $=L.local?mi:L.ownerId;qu(jE(il(),$,B)),ee(x.current.filter(X=>X.id!==B),!1)},reorder:(B,L)=>{const $=x.current.find(q=>q.id===B),X=x.current.find(q=>q.id===L);if(!$||!X)return!1;const ae=$.local?mi:$.ownerId,ue=X.local?mi:X.ownerId;if(ae!==ue)return!1;const ge=x.current.filter(q=>(q.local?mi:q.ownerId)===ae).map(q=>q.id),Z=qu(RE(il(),ae,B,L,ge));return ee(Rv(x.current,Z),!1),!0},addTileTo:async(B,L)=>{const $=x.current.find(q=>q.id===B);if(!$)throw new Error("deck inesistente");if($.available===!1)throw new Error(`nodo owner offline: ${$.ownerLabel}`);const X=cw(L,k.current,C.current);if(!X)throw new Error("riferimento sessione non valido");const ae=W($),ue=Ev(Q_(ae,X),$.ownerId,$.ownerTopology),ge=await Ga(e,$.name,ue,$.revision,$.ownerRoute),Z=Rr(ge,wo($),$.ownerTopology,$.local,!0);return ee(x.current.map(q=>q.id===B?Z:q),!1),Z},localMainId:ys(null,"main"),parseDeckId:zl}}const AN="/sw.js",vh="nc-sw-update";let _h=null,yh=!1,wh=null,Hw=Object.freeze({needed:!1,kind:null,version:""}),Ww=!1;function Uw(){typeof window<"u"&&window.dispatchEvent(new Event(vh))}function Kw(){const e=wh||(yh?{kind:"reload",version:""}:null);Hw=Object.freeze({needed:!!e,kind:(e==null?void 0:e.kind)||null,version:(e==null?void 0:e.version)||""})}function w_(){return Hw}function IN(e){return typeof window>"u"?()=>{}:(window.addEventListener(vh,e),()=>window.removeEventListener(vh,e))}function uf(e){yh!==e&&(yh=e,Kw(),Uw())}function BN(e,t,n){let s=null;e&&t&&e!==t?s={kind:"install",version:e}:t&&n&&t!==n&&(s={kind:"reload",version:t});const o=JSON.stringify(s)===JSON.stringify(wh);wh=s,Kw(),o||Uw()}function ON(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&uf(!0)})}function zN(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{Ww&&location.reload()}),navigator.serviceWorker.register(AN).then(e=>{_h=e,e.waiting&&uf(!0),e.addEventListener("updatefound",()=>{const t=e.installing;t&&ON(t)}),setInterval(()=>{e.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function FN(){Ww=!0,uf(!1);const e=_h&&_h.waiting;e?(e.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function $N({hash:e="",origin:t="",pathname:n="",search:s=""}={}){const o=String(e||"").replace(/^#/,""),a=`${n||""}${s||""}`;if(!o)return{token:"",pair:"",nextUrl:a};const u=new URLSearchParams(o),h=u.get("token")||"",p=u.get("pair")||"",f=p?`${t||""}${n||""}#pair=${p}`:"";return{token:h,pair:f,nextUrl:a}}const qw=9,Vw=24,Yw="nc_side_w",S_="nc_side_min",HN=240,b_="(min-width:1024px) and (pointer:fine)";function WN(){const e=Number(localStorage.getItem(Yw));return e>=180&&e<=480?e:HN}function UN(){const e=Number(localStorage.getItem("nc_fontsize"));return e>=qw&&e<=Vw?e:13}function KN(){const e={token:"",pair:""};try{const{token:t,pair:n,nextUrl:s}=$N({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(t){e.token=t;try{localStorage.setItem("nc_token",t)}catch{}}if(n){e.pair=n;try{sessionStorage.setItem("nc_pair",n)}catch{}}if(location.hash)try{history.replaceState(null,"",s)}catch{}}catch{}if(e.token||(e.token=sessionStorage.getItem("nc_token")||localStorage.getItem("nc_token")||""),!e.pair){const t=sessionStorage.getItem("nc_pair");t&&(e.pair=t)}return e}function qN(e){try{return Ar(fh(e))}catch{return _s()}}function k_(e){if(!e)return"";const t=Math.floor(Date.now()/1e3)-e;return t<0||t<60?"ora":t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:`${Math.floor(t/86400)}g`}function VN(){const[e,t]=N.useState(()=>window.matchMedia(b_).matches);return N.useEffect(()=>{const n=window.matchMedia(b_),s=o=>t(o.matches);return n.addEventListener("change",s),()=>n.removeEventListener("change",s)},[]),e}function x_({session:e,node:t,ownerId:n,cellName:s,token:o,readonly:a=!1,onBack:u}){zn();const[h]=Vh(),[p,f]=N.useState(!1),[_,b]=N.useState(()=>window.matchMedia("(pointer: coarse)").matches),[y,w]=N.useState(null),[S,x]=N.useState(UN),[C,k]=N.useState(s||e),[R,I]=N.useState(""),A=P=>x(M=>{const H=Math.max(qw,Math.min(Vw,M+P));return localStorage.setItem("nc_fontsize",String(H)),H}),G=N.useRef(()=>{}),F=N.useRef(()=>!1),D=N.useRef(()=>{}),J=N.useRef(!1),[W,ee]=N.useState(!1),[K,O]=N.useState(!1),j=()=>{J.current=!J.current,ee(J.current)};return N.useEffect(()=>{k(s||e)},[s,e]),N.useEffect(()=>{let P=!0;const M=t?t.split("/"):[],H=t?`/api/route/${t.split("/").map(encodeURIComponent).join("/")}/_`:"/api";async function te(){let ie=null,B=null;try{const X=await(await tn(`${H}/sessions`,o)).json();Array.isArray(X.sessions)&&(ie=X.sessions.find(ae=>ae.name===e))}catch{}try{const $=await zr(o,M);$.available&&Array.isArray($.cells)&&(B=$.cells.find(X=>X.tmuxSession===e))}catch{}if(!P)return;k(Yh({session:e,cell:B||(s?{cell:s}:null)}));let L="";B?L=`${B.engine}${B.key?`·${B.key}`:""}`:ie&&(L=ie.attached?`attached · ${k_(ie.activity)}`:ie.activity?k_(ie.activity):""),I(L)}te();const T=setInterval(te,4e3);return()=>{P=!1,clearInterval(T)}},[e,t,o]),c.jsxs("div",{className:"nc-app",children:[c.jsxs("header",{className:"nc-bar nc-bar-single",children:[c.jsxs("button",{onClick:u,title:g("sessions"),children:[c.jsx(nt,{name:"chevronLeft",size:18}),c.jsx("span",{className:"nc-bar-label",children:g("sessions")})]}),c.jsxs("span",{className:"nc-bar-center",children:[c.jsx("b",{title:t?`${C} · ${t}`:C,children:C}),R&&c.jsx("small",{className:"nc-bar-sub",children:R})]}),c.jsxs("span",{className:"nc-bar-right",children:[c.jsx("button",{onClick:()=>A(-1),title:g("zoom-out"),children:c.jsx(nt,{name:"zoomOut",size:18})}),c.jsx("button",{onClick:()=>A(1),title:g("zoom-in"),children:c.jsx(nt,{name:"zoomIn",size:18})}),c.jsx("button",{onClick:()=>b(P=>!P),title:g("composer"),children:c.jsx(nt,{name:"keyboard",size:20})}),c.jsx("button",{onClick:()=>f(P=>!P),title:g("files"),children:c.jsx(nt,{name:"folder",size:20})})]})]}),c.jsx("div",{className:"nc-termwrap",children:c.jsx(Yy,{session:e,node:t,token:o,readonly:a,takeSize:!0,sendRef:G,composerRef:F,actionRef:D,ctrlRef:J,setCtrlArmed:ee,onFiles:w,fontSize:S,selectionMode:K,onSelectionModeChange:O,keyboardGesture:h.terminalKeyboardGesture})}),c.jsx(XC,{onKeyboard:()=>b(P=>!P),send:P=>G.current(P),action:P=>D.current(P),ctrlArmed:W,onCtrl:j,selectionMode:K,onSelectionMode:O,keepKeyboardClosed:h.keybarKeepsKeyboardClosed,showEnter:h.showKeybarEnter,keybarLayout:h.keybarLayout}),_&&c.jsx(rw,{submitText:P=>F.current(P),token:o,session:e,node:t,ownerId:n,keepKeyboardClosedOnVoice:h.voiceKeepsKeyboardClosed}),p&&c.jsx(Gy,{session:e,node:t,token:o,filesEvent:y,onClose:()=>f(!1)})]})}function YN(){zn();const[e]=N.useState(KN),[t,n]=N.useState(e.token),[s,o]=N.useState(e.pair||""),a=N.useCallback(()=>{o("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),[u,h]=N.useState(!1),p=VN(),[f]=N.useState(()=>CE(typeof location<"u"?location.pathname:"/")),[_,b]=N.useState(f.id),y=_===ys(null,On),[w,S]=N.useState(null),x=de=>{const Ee=fr(de);S(Ee?{...Ee,...typeof(de==null?void 0:de.cellName)=="string"&&de.cellName?{cellName:de.cellName}:{}}:null)},[C,k]=N.useState([]),[R,I]=N.useState([]),[A,G]=N.useState([]),[F,D]=N.useState(()=>f.ownerId?_s():qN(f.name)),[J,W]=N.useState(null),[ee,K]=N.useState(null),O=de=>K(fr(de)),j=jh(t,p),P=N.useMemo(()=>(j||[]).filter(de=>de.instanceId).map(de=>({instanceId:de.instanceId,route:de.route,label:de.label,status:de.status})),[j]),M=MN(t,_,F,D,P),H=M.decks;N.useEffect(()=>{const de=new Map;for(const Ee of j||[]){const Ue=(Ee.route||[Ee.name]).join("/"),_t=new Set((Ee.sessions||[]).map(dt=>dt.name));for(const dt of Ee.cells||[])!dt.cell||!dt.tmuxSession||dt.cell===dt.tmuxSession||_t.has(dt.cell)||de.set(`${Ue}:${dt.cell}`,`${Ue}:${dt.tmuxSession}`)}D(Ee=>Q0(Ee,de))},[j]),N.useEffect(()=>{M.localNodeId&&D(de=>{const Ee=hh(de,M.localNodeId,P);return JSON.stringify(Ee)===JSON.stringify(de)?de:Ee})},[P,M.localNodeId]);const[te,T]=N.useState(null),[ie,B]=N.useState(null),L=N.useRef(0),[$,X]=N.useState(!1),[ae,ue]=N.useState(WN),[ge,Z]=N.useState(!y),[q,fe]=N.useState(()=>y?localStorage.getItem(S_)==="1":!0),[Ie,et]=N.useState(!1),[ze,Fe]=N.useState("nodes"),[Ct,Ge]=N.useState(!1),[rt,ut]=N.useState(""),ct=(de="nodes",Ee=!1,Ue="")=>{Fe(de),Ge(Ee),ut(Ue),et(!0)},[vt,it]=N.useState(!1),[lt,mt]=N.useState({deviceDefault:"",localNodeId:"",localNameDefault:""}),[le,be]=N.useState(!1);N.useEffect(()=>{try{localStorage.setItem(Yw,String(ae))}catch{}},[ae]),N.useEffect(()=>{try{localStorage.setItem(S_,q?"1":"")}catch{}},[q]),N.useEffect(()=>{if(!t)return;let de=!1;return Promise.all([T_(t),tn("/api/config",t).then(Ee=>Ee.json())]).then(([Ee,Ue])=>{de||(mt({deviceDefault:Ee.deviceName||"",localNodeId:Ee.nodeId||"",localNameDefault:Ee.localName||""}),be(!!Ue.readonlyDefault),(Ee.firstRun===!0&&!Ue.readonlyDefault||s)&&it(!0))}).catch(()=>{}),()=>{de=!0}},[t,s]);const Be=N.useCallback(async()=>{try{const Ee=await(await tn("/api/sessions",t)).json();Ee.error||k(Ee.sessions||[])}catch{}try{const de=await zr(t);I(de.available?de.cells||[]:[]),G(de.available?de.capabilities||[]:[])}catch{I([]),G([])}},[t]);N.useEffect(()=>{if(!p)return;Be();const de=setInterval(Be,4e3);return()=>clearInterval(de)},[p,Be]),N.useEffect(()=>{let de=!1;return tn("/api/config",t).then(Ee=>Ee.json()).then(Ee=>{de||BN(Ee.version,Ee.uiVersion,"0.8.36")}).catch(()=>{}),()=>{de=!0}},[t]);const $e=new Set([...C.map(de=>de.name),...j.flatMap(de=>de.sessions.map(Ee=>Ee.key))]),he=vi(F),V=de=>D(Ee=>{const Ue=cw(de,M.localNodeId,P)||de,_t=Q_(Ee,Ue);return _t===Ee&&vi(Ee).length>=9&&M.setError(g("grid-full")),_t}),ne=async(de,Ee=[])=>{try{await Ch(t,de,Ee)}catch{return}const Ue=Ee.length?`${Ee.join("/")}:${de}`:de;D(_t=>kl(_t,Ue)),Be()},z=async(de,Ee,Ue=[])=>{try{await D_(t,de,Ee,Ue)}catch{return}Be()},se=async(de,Ee,Ue=[])=>{await P_(t,{cell:de,enabled:!!Ee},Ue),Be()},me=async de=>{if(!te)return;const{cell:Ee}=te,Ue=Array.isArray(te.route)?te.route:[];de.action==="up"?await kh(t,{cell:Ee,boot:!!de.boot,...de.engine?{engine:de.engine}:{},...de.model!==void 0?{model:de.model}:{},...de.permissionPolicy?{permissionPolicy:de.permissionPolicy}:{}},Ue):await gl(t,{cell:Ee,boot:!!de.boot},Ue);const _t=de.action==="up"?!!de.boot:de.boot?!1:!!te.boot;B({id:++L.current,cell:Ee,route:Ue,enabled:_t}),Be()},ke=N.useCallback(de=>{B(Ee=>(Ee==null?void 0:Ee.id)===de?null:Ee)},[]),Ne=async de=>{if(!(!(de!=null&&de.direct)||$)){X(!0);try{await Rh(t,de.name,de.tunnelStatus==="up"?"down":"up")}finally{X(!1)}}},we=async(de,Ee)=>{const Ue=String(Ee||"").trim();return!(de!=null&&de.direct)||!bs(Ue)?!1:(await I_(t,de.name,Ue),!0)},Re=de=>{const Ee=H.find(Ue=>Ue.id===de);if(!Ee)return!1;try{const Ue=window.open(Ku(Ee,t),"_blank");return Ue&&(Ue.opener=null),!!Ue}catch{return!1}},Je=async de=>{if(!de||de===_)return;const Ee=await M.select(de),Ue=M.records.find(_t=>_t.id===de);b(de),D(Ee),W(null),K(null);try{history.replaceState(null,"",Ku(Ue||de,null))}catch{}},Tt=async(de,Ee)=>{const Ue=await M.add(de,Ee);await Je(Ue.id)},Me=async(de,Ee)=>{const Ue=await M.rename(de,Ee);if(de===_){b(Ue.id),D(hh(Ue.layout,M.localNodeId,P)),W(null),K(null);try{history.replaceState(null,"",Ku(Ue,null))}catch{}}},pn=async de=>{await M.remove(de),de===_&&await Je(M.localMainId)},bt=async(de,Ee)=>{!Ee||Ee===_||(await M.addTileTo(Ee,de),D(Ue=>kl(Ue,de)))};if(!t)return c.jsxs("div",{className:"nc-auth",children:[c.jsx("p",{children:g("auth-prompt")}),c.jsx("input",{onChange:de=>n(de.target.value.trim()),placeholder:"token"}),c.jsxs("label",{children:[c.jsx("input",{type:"checkbox",checked:u,onChange:de=>h(de.target.checked)})," ",g("remember-device")]}),c.jsx("button",{onClick:()=>{(u?localStorage:sessionStorage).setItem("nc_token",t)},children:"ok"})]});const Ke=c.jsxs(c.Fragment,{children:[Ie&&c.jsx(CN,{token:t,initialTab:ze,initialLocation:rt,startNewCell:Ct,onClose:()=>{et(!1),Ge(!1),ut("")}}),vt&&c.jsx(EN,{token:t,initialPair:s,...lt,onPairDone:a,onDone:()=>it(!1)}),c.jsx(DN,{token:t})]});if(!p)return w?c.jsxs(c.Fragment,{children:[c.jsx(x_,{session:w.session,node:w.node,ownerId:w.ownerId,cellName:w.cellName,token:t,readonly:le,onBack:()=>S(null)}),Ke]}):c.jsxs(c.Fragment,{children:[c.jsx(f1,{onPick:x,token:t,onSettings:ct}),Ke]});const $t=y||!ge;return c.jsxs("div",{className:"nc-workspace",children:[$t&&c.jsx(fE,{sessions:C,cells:R,activeSessions:he,nodeGroups:j,fleetCapabilities:A,bootSettlement:ie,onBootSettlementApplied:ke,localNodeId:M.localNodeId,onPick:O,onAddTile:V,onPower:T,onBoot:se,onBootError:de=>M.setError(String((de==null?void 0:de.message)||de)),onNodePower:Ne,onNodeRename:we,onKill:ne,onVisibility:z,onNew:()=>ct("fleet",!0),onSettings:ct,width:ae,collapsed:q,onResize:ue,onToggleCollapse:()=>fe(de=>!de)}),c.jsxs("div",{className:"nc-workspace-main",children:[c.jsx(YE,{decks:H,currentDeck:_,onCreate:Tt,onRename:Me,onDelete:pn,onReorder:M.reorder,onOpenWindow:Re,onNavigate:Je,saveState:M.saveState,error:M.error,sidebarVisible:$t,onToggleSidebar:y?null:()=>Z(de=>!de)}),c.jsx(wE,{layout:F,onLayoutChange:D,token:t,readonly:le,sessionsAlive:$e,focusSession:J,onFocus:W,onOpenSingle:O,decks:H,currentDeck:_,onSendToDeck:bt,cells:R,nodeGroups:j})]}),ee&&c.jsx("div",{className:"nc-single-overlay",children:c.jsx(x_,{session:ee.session,node:ee.node,ownerId:ee.ownerId,cellName:Yh({session:ee.session,node:ee.node,ownerId:ee.ownerId,cells:R,nodeGroups:j}),token:t,readonly:le,onBack:()=>K(null)})}),te&&c.jsx(_l,{cell:te,token:t,route:Array.isArray(te.route)?te.route:[],onConfirm:me,onClose:()=>T(null)}),Ke]})}function GN(){zn();const e=N.useSyncExternalStore(IN,w_,w_);if(!e.needed)return null;const t=e.kind==="install"?g("install-version-mismatch").replace("{v}",e.version):g("update-available").replace("{v}",e.version).replace(" "," ").trim();return c.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[c.jsx("span",{className:"nc-update-msg",children:t}),e.kind==="reload"&&c.jsx("button",{className:"nc-update-btn",onClick:FN,children:g("reload")})]})}zN();Gb.createRoot(document.getElementById("root")).render(c.jsxs(Hb.StrictMode,{children:[c.jsx(YN,{}),c.jsx(GN,{})]}));
93
+ `],{type:"application/json"}),H=URL.createObjectURL(M),te=document.createElement("a");te.href=H,te.download="nexuscrew-diagnostics.json",te.click(),URL.revokeObjectURL(H)}catch{y(g("diagnostics-export-failed"))}};return c.jsxs("div",{className:"nc-set-tab nc-diagnostics",children:[c.jsxs("label",{className:"nc-field",children:[g("diagnostics-target"),c.jsx("select",{value:u.key,onChange:M=>a(M.target.value),children:s.map(M=>c.jsxs("option",{value:M.key,children:[M.label,M.status!=="up"?` · ${M.status}`:""]},M.key))})]}),c.jsxs("div",{className:"nc-set-form nc-diag-controls",children:[c.jsx("div",{className:"nc-sheet-label",children:g("diagnostics-verbose")}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("select",{"aria-label":g("diagnostics-duration"),value:k,onChange:M=>R(Number(M.target.value)),disabled:n,children:[300,900,1800,3600].map(M=>c.jsxs("option",{value:M,children:[M/60," min"]},M))}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(h==null?void 0:h.verbose)===!0,onClick:()=>O(()=>ng(e,!0,k,u.route)),children:g("enable")}),c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||(h==null?void 0:h.verbose)!==!0,onClick:()=>O(()=>ng(e,!1,k,u.route)),children:g("stop")})]}),c.jsx("small",{className:"nc-set-hint",children:h!=null&&h.verbose?g("diagnostics-expires").replace("{time}",new Date(h.expiresAt).toLocaleTimeString()):g("diagnostics-off")})]}),c.jsxs("div",{className:"nc-diag-filters",children:[c.jsxs("select",{"aria-label":g("diagnostics-level"),value:I,onChange:M=>A(M.target.value),children:[c.jsx("option",{value:"all",children:g("diagnostics-all-levels")}),["debug","info","warn","error"].map(M=>c.jsx("option",{value:M,children:M},M))]}),c.jsx("input",{"aria-label":g("diagnostics-component"),placeholder:g("diagnostics-component"),value:G,onChange:M=>F(M.target.value)})]}),c.jsxs("div",{className:"nc-set-row",children:[c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:w,onChange:M=>S(M.target.checked)})," ",g("diagnostics-pause")]}),c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:x,onChange:M=>C(M.target.checked)})," ",g("diagnostics-autoscroll")]})]}),c.jsx("pre",{ref:J,className:"nc-diag-log","aria-label":g("diagnostics-log"),children:K||g("diagnostics-empty")}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:j,children:g("copy")}),c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:P,children:g("diagnostics-export")}),c.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(g("diagnostics-clear-confirm"))&&O(async()=>{const M=await w0(e,u.route);return D.current=0,_([]),M})},children:g("diagnostics-clear")})]}),b&&c.jsx("div",{className:"nc-err",children:b})]})}function xN({token:e,settings:t,readonly:n,refresh:s}){const[o,a]=N.useState(null),[u,h]=N.useState(null),[p,f]=N.useState(!1),[_,b]=N.useState(!1),[y,w]=N.useState(null),[S,x]=N.useState(!0);N.useEffect(()=>{w(t&&t.update||null),x(!t||t.autoUpdate!==!1)},[t]);const C=async()=>{a(null),h(null),b(!0);try{const D=await l0(e);h(D.note||"ok"),f(!1)}catch(D){a(String(D.message||D))}b(!1)},k=async()=>{a(null),h(null),b(!0);try{const D=await m0(e);h(`${D.note||"ok"}${D.target?` (${D.target})`:""}`)}catch(D){a(String(D.message||D))}b(!1)},R=async D=>{a(null),h(null),b(!0);try{await A_(e,{autoUpdate:D}),x(D),s&&await s()}catch(J){a(String(J.message||J))}b(!1)},I=async()=>{a(null),h(null),b(!0);try{w(await g0(e))}catch(D){a(String(D.message||D))}b(!1)},A=async()=>{a(null),h(null),b(!0);try{const D=await v0(e);w(D),h(g("npm-update-restarting"))}catch(D){a(String(D.message||D))}b(!1)},G=()=>{window.confirm(g("composer-clear-confirm"))&&(a(null),aE()?(window.dispatchEvent(new Event(ch)),h(g("composer-clear-done"))):a(g("composer-clear-failed")))},F=t&&t.service;return c.jsxs("div",{className:"nc-set-tab",children:[t&&c.jsxs("div",{className:"nc-set-info",children:["v",t.version," · ",t.platform," · :",t.port,c.jsx("br",{}),F&&F.installed?g("service-installed"):g("service-missing"),F&&F.installed?` · ${F.active?g("service-active"):g("service-inactive")}`:"",F?` · boot ${F.boot?"on":"off"}`:""]}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||_,title:n?g("settings-readonly"):"",onClick:()=>{a(null),h(null),f(!0)},children:g("token-rotate")}),c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||_,title:n?g("settings-readonly"):"",onClick:k,children:g("service-regenerate")})]}),c.jsxs("div",{className:"nc-set-form nc-update-settings",children:[c.jsxs("label",{className:"nc-check",children:[c.jsx("input",{type:"checkbox",checked:S,disabled:n||_||y&&!y.supported,onChange:D=>R(D.target.checked)}),c.jsxs("span",{children:[c.jsx("b",{children:g("npm-auto-update")}),c.jsx("small",{children:g("npm-auto-update-help")})]})]}),y&&c.jsxs("div",{className:"nc-set-info",children:[g("npm-update-current")," v",y.current,y.latest?` · ${g("npm-update-latest")} v${y.latest}`:""," · ",g(`npm-update-${y.supported?y.phase:"unsupported"}`)]}),c.jsxs("div",{className:"nc-set-row",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||_||!y||!y.supported,onClick:I,children:g("npm-update-check")}),y&&y.available&&c.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||_||y.phase==="installing",onClick:A,children:g("npm-update-install")})]}),y&&y.lastError&&c.jsx("div",{className:"nc-err",children:y.lastError})]}),c.jsx(wN,{token:e,readonly:n}),c.jsx(SN,{}),c.jsxs("div",{className:"nc-set-form",children:[c.jsx("div",{className:"nc-sheet-label",children:g("composer-clear-data")}),c.jsx("small",{className:"nc-set-hint",children:g("composer-clear-data-help")}),c.jsx("div",{className:"nc-set-row",children:c.jsx("button",{type:"button",className:"nc-btn ghost",onClick:G,children:g("composer-clear-data")})})]}),p&&c.jsxs("div",{className:"nc-set-confirm",children:[c.jsx("div",{children:g("token-rotate-explain")}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>f(!1),children:g("cancel")}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:_,onClick:C,children:g("confirm")})]})]}),u&&c.jsx("div",{className:"nc-set-note",children:u}),o&&c.jsx("div",{className:"nc-err",children:o})]})}function CN({token:e,onClose:t,initialTab:n="nodes",initialLocation:s="",startNewCell:o=!1}){zn();const[a,u]=N.useState(n),[h,p]=N.useState(null),[f,_]=N.useState([]),[b,y]=N.useState(!1),[w,S]=N.useState(null),[x,C]=N.useState(0),k=jh(e,!0,x),R=N.useCallback(async()=>{try{const I=await T_(e);p(I),S(null)}catch(I){S(String(I.message||I))}try{const I=await o0(e);_(I.peers||[])}catch(I){S(String(I.message||I))}},[e]);return N.useEffect(()=>{R();const I=setInterval(R,5e3);return()=>clearInterval(I)},[R]),N.useEffect(()=>{let I=!1;return tn("/api/config",e).then(A=>A.json()).then(A=>{I||y(!!A.readonlyDefault)}).catch(()=>{}),()=>{I=!0}},[e]),c.jsx("div",{className:"nc-set-overlay",onClick:t,children:c.jsxs("div",{className:"nc-set-panel",onClick:I=>I.stopPropagation(),children:[c.jsxs("div",{className:"nc-set-head",children:[c.jsx(nt,{name:"gear",size:18}),c.jsx("b",{children:g("settings")}),c.jsx("button",{type:"button",className:"nc-set-close",onClick:t,title:g("close"),children:c.jsx(nt,{name:"x",size:18})})]}),b&&c.jsx("div",{className:"nc-set-readonly",children:g("settings-readonly")}),w&&c.jsx("div",{className:"nc-err",children:w}),c.jsx("div",{className:"nc-set-tabs",children:["nodes","fleet","input","diagnostics","system"].map(I=>c.jsx("button",{type:"button",className:`nc-set-tabbtn${a===I?" on":""}`,onClick:()=>u(I),children:g(`tab-${I}`)},I))}),c.jsxs("div",{className:"nc-set-body",children:[a==="nodes"&&c.jsx(yN,{token:e,nodes:f,roster:k,settings:h,readonly:b,refresh:R,refreshAliases:()=>C(I=>I+1)}),a==="fleet"&&c.jsx(rN,{token:e,readonly:b,startNewCell:o,initialLocation:s,targets:k.map(I=>({route:I.route,label:I.label||I.name,status:I.status}))}),a==="input"&&c.jsx(bN,{}),a==="diagnostics"&&c.jsx(kN,{token:e,roster:k,readonly:b}),a==="system"&&c.jsx(xN,{token:e,settings:h,readonly:b,refresh:R})]})]})})}function EN({token:e,initialPair:t,deviceDefault:n="",localNodeId:s="",localNameDefault:o="",onPairDone:a,onDone:u}){zn();const[h,p]=N.useState(t?"pair":"welcome"),[f,_]=N.useState(!1),[b,y]=N.useState(null),w=async()=>{_(!0),y(null);try{await A_(e,{wizardDone:!0}),a&&a(),u()}catch(S){y(String(S.message||S)),_(!1)}};return c.jsx("div",{className:"nc-wiz-overlay",children:c.jsxs("div",{className:"nc-wiz",children:[c.jsxs("div",{className:"nc-wiz-head",children:[c.jsx("b",{children:g("wizard-title")}),c.jsx("small",{children:g("hydra-simple")})]}),h==="welcome"&&c.jsxs("div",{className:"nc-wiz-body",children:[c.jsx("div",{className:"nc-wiz-done",children:g("local-ready")}),c.jsxs("div",{className:"nc-sheet-actions",children:[c.jsx("button",{className:"nc-btn ghost",disabled:f,onClick:w,children:g("local-only")}),c.jsx("button",{className:"nc-btn primary",disabled:f,onClick:()=>p("pair"),children:g("add-node")})]})]}),h==="pair"&&c.jsxs("div",{className:"nc-wiz-body",children:[c.jsx(Nw,{token:e,initial:t||"",autoStart:!!t,deviceDefault:n,localNodeId:s,localNameDefault:o,onBusyChange:_,onSuccess:async()=>{a&&a(),p("done")}}),c.jsx("div",{className:"nc-sheet-actions",children:c.jsx("button",{className:"nc-btn ghost",disabled:f,onClick:()=>{a&&a(),p("welcome")},children:g("back")})})]}),h==="done"&&c.jsxs("div",{className:"nc-wiz-body",children:[c.jsx("div",{className:"nc-wiz-done",children:g("node-connected")}),c.jsx("div",{className:"nc-sheet-actions",children:c.jsx("button",{className:"nc-btn primary",disabled:f,onClick:w,children:g("finish")})})]}),b&&c.jsx("div",{className:"nc-err",children:b})]})})}function NN(e,t){if(typeof EventSource>"u"||!e)return()=>{};const n=new EventSource(`/api/events?token=${encodeURIComponent(e)}`);return n.onmessage=s=>{try{const o=JSON.parse(s.data);o&&typeof o=="object"&&typeof o.type=="string"&&t(o)}catch{}},()=>{try{n.close()}catch{}}}const RN=6e3,PN=12e3;function jN({n:e,onClose:t}){return c.jsxs("div",{className:`nc-ntf-toast${e.urgency==="high"?" high":""}`,role:"status","aria-live":"polite",children:[c.jsxs("div",{className:"nc-ntf-toast-txt",children:[c.jsx("b",{children:e.title}),e.body&&c.jsx("small",{children:e.body}),e.session&&c.jsx("span",{className:"nc-ntf-from",children:e.session})]}),c.jsx("button",{type:"button",className:"nc-ntf-x",onClick:t,title:g("close"),children:c.jsx(nt,{name:"x",size:14})})]})}function LN({ask:e,token:t,onAnswered:n}){const[s,o]=N.useState(""),[a,u]=N.useState(!1),[h,p]=N.useState(null),f=async _=>{const b=String(_||"").trim();if(!(!b||a)){p(null),u(!0);try{await b0(t,e.id,b),n(e.id)}catch(y){p(String(y.message||y))}u(!1)}};return c.jsxs("div",{className:"nc-ask-card",children:[c.jsxs("div",{className:"nc-ask-head",children:[c.jsx("span",{className:"nc-ntf-from",children:e.session}),c.jsxs("code",{className:"nc-ask-id",children:["#",e.id]})]}),c.jsx("div",{className:"nc-ask-q",children:e.question}),Array.isArray(e.options)&&e.options.length>0&&c.jsx("div",{className:"nc-ask-opts",children:e.options.map(_=>c.jsx("button",{type:"button",className:"nc-btn ghost",disabled:a,onClick:()=>f(_),children:_},_))}),c.jsxs("div",{className:"nc-ask-reply",children:[c.jsx("textarea",{rows:2,placeholder:g("ask-reply-ph"),value:s,disabled:a,onChange:_=>o(_.target.value)}),c.jsx("button",{type:"button",className:"nc-btn primary",disabled:a||!s.trim(),onClick:()=>f(s),children:g("send")})]}),h&&c.jsx("div",{className:"nc-err",children:h})]})}function DN({token:e}){const[t]=zn(),[n]=$w(),[s,o]=N.useState([]),[a,u]=N.useState([]),[h,p]=N.useState(()=>{try{return/(?:^|[#&])ask=/.test(location.hash)}catch{return!1}}),f=N.useRef(0),_=N.useRef(null);_.current||(_.current=gN());const b=N.useRef({enabled:n,lang:t});b.current={enabled:n,lang:t};const y=N.useCallback(x=>{o(C=>C.filter(k=>k.key!==x))},[]),w=N.useCallback(x=>{const C=`t${f.current+=1}`;o(R=>[...R.slice(-3),{...x,key:C}]),setTimeout(()=>y(C),x.urgency==="high"?PN:RN);const k=b.current;if(k.enabled)try{_.current.enqueue(x,k.lang)}catch{}},[y]);N.useEffect(()=>{n||_.current.stop()},[n]),N.useEffect(()=>{const x=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&_.current.stop()},C=()=>_.current.stop();return document.addEventListener("visibilitychange",x),window.addEventListener("blur",x),window.addEventListener(mh,C),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("blur",x),window.removeEventListener(mh,C),_.current.stop()}},[]),N.useEffect(()=>{if(!e)return;let x=!1;S0(e).then(k=>{x||u(k.asks||[])}).catch(()=>{});const C=NN(e,k=>{k.type==="notify"?w(k):k.type==="ask"&&k.ask&&k.ask.id?u(R=>R.some(I=>I.id===k.ask.id)?R:[...R,k.ask]):k.type==="ask-answered"&&k.id&&u(R=>R.filter(I=>I.id!==k.id))});return()=>{x=!0,C()}},[e,w]);const S=x=>u(C=>C.filter(k=>k.id!==x));return c.jsxs(c.Fragment,{children:[s.length>0&&c.jsx("div",{className:"nc-ntf-toasts",children:s.map(x=>c.jsx(jN,{n:x,onClose:()=>y(x.key)},x.key))}),a.length>0&&!h&&c.jsxs("button",{type:"button",className:"nc-ask-badge",onClick:()=>p(!0),title:g("asks-title"),children:["? ",c.jsx("span",{className:"nc-ask-count",children:a.length})]}),a.length>0&&h&&c.jsxs("div",{className:"nc-ask-panel",children:[c.jsxs("div",{className:"nc-ask-panel-head",children:[c.jsx("b",{children:g("asks-title")}),c.jsx("span",{className:"nc-ask-count",children:a.length}),c.jsx("button",{type:"button",className:"nc-ntf-x",onClick:()=>p(!1),title:g("close"),children:c.jsx(nt,{name:"x",size:16})})]}),c.jsx("div",{className:"nc-ask-panel-body",children:a.map(x=>c.jsx(LN,{ask:x,token:e,onAnswered:S},x.id))})]})]})}const _d=e=>vi(Ar(e)).length===0,yd=e=>Array.isArray(e)?e.join("/"):"";function TN(e){const t=new Set,n=[];for(const s of Array.isArray(e)?e:[])!s||!Bn.test(String(s.instanceId||""))||!Array.isArray(s.route)||!s.route.length||t.has(s.instanceId)||(t.add(s.instanceId),n.push({instanceId:s.instanceId,route:[...s.route],label:String(s.label||s.name||s.route.join(" › ")),status:s.status||"offline"}));return n.sort((s,o)=>s.label.localeCompare(o.label))}function wo(e){return{instanceId:e.ownerId,route:e.ownerRoute||[],label:e.ownerLabel,status:e.available===!1?"offline":"up"}}function Rr(e,t,n,s=!1,o=!0){const a=t.instanceId;return{...e,id:ys(s?null:a,e.name),ownerId:a,ownerRoute:s?[]:[...t.route],ownerLabel:s?"Local":t.label,local:s,available:o,ownerTopology:Array.isArray(n)?n:[],layout:dh(e.layout,a,n)}}function MN(e,t,n,s,o=[]){const[a,u]=N.useState([]),[h,p]=N.useState(!1),[f,_]=N.useState("idle"),[b,y]=N.useState(""),[w,S]=N.useState(""),x=N.useRef([]),C=N.useRef([]),k=N.useRef(""),R=N.useRef(t),I=N.useRef(n),A=N.useRef(!1),G=N.useRef(!0),F=N.useRef(""),D=N.useMemo(()=>TN(o),[o]),J=D.map(B=>`${B.instanceId}:${yd(B.route)}:${B.status}:${B.label}`).join("|");C.current=D,I.current=n,R.current=t,x.current=a;const W=N.useCallback(B=>hh(B.layout,k.current,C.current),[]),ee=N.useCallback((B,L=!0,$=R.current)=>{const X=Rv(B,il()),ae=x.current.some(ge=>ge.id===$);x.current=X,u(X);const ue=X.find(ge=>ge.id===$);if(L&&ue){G.current=!0;const ge=W(ue);s(ge),ue.local&&LE(ue.name,ge)}else ae&&!ue&&(G.current=!0,s(_s()),y("deck non più condiviso dal nodo owner"));NE(X.filter(ge=>ge.local).map(ge=>ge.name))},[s,W]),K=N.useCallback(async B=>{let L=await Ya(e);const $=L.decks.find(X=>X.name==="main");if(L.decks.length===1&&$&&$.revision===0&&_d($.layout)){const X=EE(),ae=Ar(fh("main")||_s());if(!_d(ae)){const ue=dh(ae,B,[]);L.decks[0]=await Ga(e,"main",ue,0,[])}for(const ue of X.filter(ge=>ge!=="main"))try{let ge=await ig(e,ue,[]);const Z=Ar(fh(ue)||_s());_d(Z)||(ge=await Ga(e,ue,dh(Z,B,[]),ge.revision,[]))}catch{}L=await Ya(e)}return L},[e]),O=N.useCallback(async({migrate:B=!1}={})=>{const L=await Nh(e,[]),$=Bn.test(String(L.instanceId||""))?L.instanceId:"";if(!$)throw new Error("instanceId locale non disponibile");k.current=$,S($);const[X,ae]=await Promise.all([B?K($):Ya(e),Qm(e,[]).catch(()=>({nodes:[]}))]),ue={instanceId:$,route:[],label:"Local"},ge=X.decks.map(q=>Rr(q,ue,ae.nodes,!0,!0)),Z=x.current;return await Promise.all(C.current.map(async q=>{if(q.status!=="up"){ge.push(...Z.filter(fe=>!fe.local&&fe.ownerId===q.instanceId).map(fe=>({...fe,ownerRoute:[...q.route],ownerLabel:q.label,available:!1})));return}try{const[fe,Ie]=await Promise.all([Ya(e,q.route),Qm(e,q.route).catch(()=>({nodes:[]}))]);ge.push(...fe.decks.map(et=>Rr(et,q,Ie.nodes,!1,!0)))}catch{ge.push(...Z.filter(Ie=>!Ie.local&&Ie.ownerId===q.instanceId).map(Ie=>({...Ie,ownerRoute:[...q.route],ownerLabel:q.label,available:!1})))}})),ge.sort((q,fe)=>q.local===fe.local?q.ownerLabel.localeCompare(fe.ownerLabel)||(q.name==="main"?-1:fe.name==="main"?1:q.name.localeCompare(fe.name)):q.local?-1:1),ge},[e,K,J]);N.useEffect(()=>{if(!e)return;let B=!1;const L=F.current!==e;return F.current=e,O({migrate:L}).then($=>{if(B)return;const X=x.current.find(ge=>ge.id===R.current),ae=$.find(ge=>ge.id===R.current),ue=ae&&(!X||ae.revision>X.revision||X.available!==ae.available||yd(X.ownerRoute)!==yd(ae.ownerRoute));ee($,L||!!ue&&!A.current),p(!0),ae&&y("")}).catch($=>{B||(p(!0),y(String($.message||$)))}),()=>{B=!0}},[ee,O,J,e]);const j=N.useCallback(async(B=R.current)=>{if(!h||!A.current)return!0;const L=x.current.find($=>$.id===B);if(!L)return y(`deck inesistente: ${B}`),!1;if(L.available===!1)return y(`nodo owner offline: ${L.ownerLabel}`),!1;_("saving");try{const $=Ev(Ar(I.current),L.ownerId,L.ownerTopology),X=await Ga(e,L.name,$,L.revision,L.ownerRoute),ae=Rr(X,wo(L),L.ownerTopology,L.local,!0);return ee(x.current.map(ue=>ue.id===B?ae:ue),!1),A.current=!1,_("saved"),y(""),setTimeout(()=>_("idle"),1500),!0}catch($){if(_("error"),y(String($.message||$)),$.status===409&&$.data&&$.data.current){const X=x.current.find(ue=>ue.id===B),ae=Rr($.data.current,wo(X),X.ownerTopology,X.local,!0);ee(x.current.map(ue=>ue.id===B?ae:ue),!1)}return!1}},[h,e,ee]);return N.useEffect(()=>{if(!h)return;if(G.current){G.current=!1;return}A.current=!0,_("saving");const B=setTimeout(j,650);return()=>clearTimeout(B)},[n,h,j]),N.useEffect(()=>{if(!h)return;const B=setInterval(async()=>{try{const L=await O(),$=x.current.find(ue=>ue.id===R.current),X=L.find(ue=>ue.id===R.current),ae=X&&(!$||X.revision>$.revision||$.available!==X.available);ee(L,ae&&!A.current)}catch{}},5e3);return()=>clearInterval(B)},[h,O,ee]),{decks:a,records:a,localNodeId:w,ready:h,saveState:f,error:b,setError:y,saveNow:j,select:async B=>{if(A.current&&!await j(R.current))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const L=x.current.find($=>$.id===B);if(!L)throw new Error(`deck inesistente: ${B}`);return A.current=!1,G.current=!0,W(L)},add:async(B,L=null)=>{const $=L===mi?x.current.find(ue=>ue.local):L?x.current.find(ue=>ue.ownerId===L):null;if(!$||$.available===!1)throw new Error("nodo owner non disponibile");const X=await ig(e,B,$.ownerRoute),ae=Rr(X,wo($),$.ownerTopology,$.local,!0);return ee([...x.current,ae],!1),ae},rename:async(B,L)=>{const $=x.current.find(Z=>Z.id===B);if(!$)throw new Error("deck inesistente");if(B===R.current&&A.current&&!await j(B))throw new Error(`salvataggio di "${$.name}" fallito: rinomina annullata`);const X=x.current.find(Z=>Z.id===B);if(!X)throw new Error("deck inesistente");const ae=await k0(e,X.name,L,X.revision,X.ownerRoute),ue=Rr(ae,wo(X),X.ownerTopology,X.local,!0),ge=X.local?mi:X.ownerId;return qu(PE(il(),ge,B,ue.id)),ee(x.current.map(Z=>Z.id===B?ue:Z),!1),ue},remove:async B=>{const L=x.current.find(X=>X.id===B);if(!L)throw new Error("deck inesistente");B===R.current&&(A.current=!1),await x0(e,L.name,L.revision,L.ownerRoute);const $=L.local?mi:L.ownerId;qu(jE(il(),$,B)),ee(x.current.filter(X=>X.id!==B),!1)},reorder:(B,L)=>{const $=x.current.find(q=>q.id===B),X=x.current.find(q=>q.id===L);if(!$||!X)return!1;const ae=$.local?mi:$.ownerId,ue=X.local?mi:X.ownerId;if(ae!==ue)return!1;const ge=x.current.filter(q=>(q.local?mi:q.ownerId)===ae).map(q=>q.id),Z=qu(RE(il(),ae,B,L,ge));return ee(Rv(x.current,Z),!1),!0},addTileTo:async(B,L)=>{const $=x.current.find(q=>q.id===B);if(!$)throw new Error("deck inesistente");if($.available===!1)throw new Error(`nodo owner offline: ${$.ownerLabel}`);const X=cw(L,k.current,C.current);if(!X)throw new Error("riferimento sessione non valido");const ae=W($),ue=Ev(Q_(ae,X),$.ownerId,$.ownerTopology),ge=await Ga(e,$.name,ue,$.revision,$.ownerRoute),Z=Rr(ge,wo($),$.ownerTopology,$.local,!0);return ee(x.current.map(q=>q.id===B?Z:q),!1),Z},localMainId:ys(null,"main"),parseDeckId:zl}}const AN="/sw.js",vh="nc-sw-update";let _h=null,yh=!1,wh=null,Hw=Object.freeze({needed:!1,kind:null,version:""}),Ww=!1;function Uw(){typeof window<"u"&&window.dispatchEvent(new Event(vh))}function Kw(){const e=wh||(yh?{kind:"reload",version:""}:null);Hw=Object.freeze({needed:!!e,kind:(e==null?void 0:e.kind)||null,version:(e==null?void 0:e.version)||""})}function w_(){return Hw}function IN(e){return typeof window>"u"?()=>{}:(window.addEventListener(vh,e),()=>window.removeEventListener(vh,e))}function uf(e){yh!==e&&(yh=e,Kw(),Uw())}function BN(e,t,n){let s=null;e&&t&&e!==t?s={kind:"install",version:e}:t&&n&&t!==n&&(s={kind:"reload",version:t});const o=JSON.stringify(s)===JSON.stringify(wh);wh=s,Kw(),o||Uw()}function ON(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&uf(!0)})}function zN(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{Ww&&location.reload()}),navigator.serviceWorker.register(AN).then(e=>{_h=e,e.waiting&&uf(!0),e.addEventListener("updatefound",()=>{const t=e.installing;t&&ON(t)}),setInterval(()=>{e.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function FN(){Ww=!0,uf(!1);const e=_h&&_h.waiting;e?(e.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function $N({hash:e="",origin:t="",pathname:n="",search:s=""}={}){const o=String(e||"").replace(/^#/,""),a=`${n||""}${s||""}`;if(!o)return{token:"",pair:"",nextUrl:a};const u=new URLSearchParams(o),h=u.get("token")||"",p=u.get("pair")||"",f=p?`${t||""}${n||""}#pair=${p}`:"";return{token:h,pair:f,nextUrl:a}}const qw=9,Vw=24,Yw="nc_side_w",S_="nc_side_min",HN=240,b_="(min-width:1024px) and (pointer:fine)";function WN(){const e=Number(localStorage.getItem(Yw));return e>=180&&e<=480?e:HN}function UN(){const e=Number(localStorage.getItem("nc_fontsize"));return e>=qw&&e<=Vw?e:13}function KN(){const e={token:"",pair:""};try{const{token:t,pair:n,nextUrl:s}=$N({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(t){e.token=t;try{localStorage.setItem("nc_token",t)}catch{}}if(n){e.pair=n;try{sessionStorage.setItem("nc_pair",n)}catch{}}if(location.hash)try{history.replaceState(null,"",s)}catch{}}catch{}if(e.token||(e.token=sessionStorage.getItem("nc_token")||localStorage.getItem("nc_token")||""),!e.pair){const t=sessionStorage.getItem("nc_pair");t&&(e.pair=t)}return e}function qN(e){try{return Ar(fh(e))}catch{return _s()}}function k_(e){if(!e)return"";const t=Math.floor(Date.now()/1e3)-e;return t<0||t<60?"ora":t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:`${Math.floor(t/86400)}g`}function VN(){const[e,t]=N.useState(()=>window.matchMedia(b_).matches);return N.useEffect(()=>{const n=window.matchMedia(b_),s=o=>t(o.matches);return n.addEventListener("change",s),()=>n.removeEventListener("change",s)},[]),e}function x_({session:e,node:t,ownerId:n,cellName:s,token:o,readonly:a=!1,onBack:u}){zn();const[h]=Vh(),[p,f]=N.useState(!1),[_,b]=N.useState(()=>window.matchMedia("(pointer: coarse)").matches),[y,w]=N.useState(null),[S,x]=N.useState(UN),[C,k]=N.useState(s||e),[R,I]=N.useState(""),A=P=>x(M=>{const H=Math.max(qw,Math.min(Vw,M+P));return localStorage.setItem("nc_fontsize",String(H)),H}),G=N.useRef(()=>{}),F=N.useRef(()=>!1),D=N.useRef(()=>{}),J=N.useRef(!1),[W,ee]=N.useState(!1),[K,O]=N.useState(!1),j=()=>{J.current=!J.current,ee(J.current)};return N.useEffect(()=>{k(s||e)},[s,e]),N.useEffect(()=>{let P=!0;const M=t?t.split("/"):[],H=t?`/api/route/${t.split("/").map(encodeURIComponent).join("/")}/_`:"/api";async function te(){let ie=null,B=null;try{const X=await(await tn(`${H}/sessions`,o)).json();Array.isArray(X.sessions)&&(ie=X.sessions.find(ae=>ae.name===e))}catch{}try{const $=await zr(o,M);$.available&&Array.isArray($.cells)&&(B=$.cells.find(X=>X.tmuxSession===e))}catch{}if(!P)return;k(Yh({session:e,cell:B||(s?{cell:s}:null)}));let L="";B?L=`${B.engine}${B.key?`·${B.key}`:""}`:ie&&(L=ie.attached?`attached · ${k_(ie.activity)}`:ie.activity?k_(ie.activity):""),I(L)}te();const T=setInterval(te,4e3);return()=>{P=!1,clearInterval(T)}},[e,t,o]),c.jsxs("div",{className:"nc-app",children:[c.jsxs("header",{className:"nc-bar nc-bar-single",children:[c.jsxs("button",{onClick:u,title:g("sessions"),children:[c.jsx(nt,{name:"chevronLeft",size:18}),c.jsx("span",{className:"nc-bar-label",children:g("sessions")})]}),c.jsxs("span",{className:"nc-bar-center",children:[c.jsx("b",{title:t?`${C} · ${t}`:C,children:C}),R&&c.jsx("small",{className:"nc-bar-sub",children:R})]}),c.jsxs("span",{className:"nc-bar-right",children:[c.jsx("button",{onClick:()=>A(-1),title:g("zoom-out"),children:c.jsx(nt,{name:"zoomOut",size:18})}),c.jsx("button",{onClick:()=>A(1),title:g("zoom-in"),children:c.jsx(nt,{name:"zoomIn",size:18})}),c.jsx("button",{onClick:()=>b(P=>!P),title:g("composer"),children:c.jsx(nt,{name:"keyboard",size:20})}),c.jsx("button",{onClick:()=>f(P=>!P),title:g("files"),children:c.jsx(nt,{name:"folder",size:20})})]})]}),c.jsx("div",{className:"nc-termwrap",children:c.jsx(Yy,{session:e,node:t,token:o,readonly:a,takeSize:!0,sendRef:G,composerRef:F,actionRef:D,ctrlRef:J,setCtrlArmed:ee,onFiles:w,fontSize:S,selectionMode:K,onSelectionModeChange:O,keyboardGesture:h.terminalKeyboardGesture})}),c.jsx(XC,{onKeyboard:()=>b(P=>!P),send:P=>G.current(P),action:P=>D.current(P),ctrlArmed:W,onCtrl:j,selectionMode:K,onSelectionMode:O,keepKeyboardClosed:h.keybarKeepsKeyboardClosed,showEnter:h.showKeybarEnter,keybarLayout:h.keybarLayout}),_&&c.jsx(rw,{submitText:P=>F.current(P),token:o,session:e,node:t,ownerId:n,keepKeyboardClosedOnVoice:h.voiceKeepsKeyboardClosed}),p&&c.jsx(Gy,{session:e,node:t,token:o,filesEvent:y,onClose:()=>f(!1)})]})}function YN(){zn();const[e]=N.useState(KN),[t,n]=N.useState(e.token),[s,o]=N.useState(e.pair||""),a=N.useCallback(()=>{o("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),[u,h]=N.useState(!1),p=VN(),[f]=N.useState(()=>CE(typeof location<"u"?location.pathname:"/")),[_,b]=N.useState(f.id),y=_===ys(null,On),[w,S]=N.useState(null),x=de=>{const Ee=fr(de);S(Ee?{...Ee,...typeof(de==null?void 0:de.cellName)=="string"&&de.cellName?{cellName:de.cellName}:{}}:null)},[C,k]=N.useState([]),[R,I]=N.useState([]),[A,G]=N.useState([]),[F,D]=N.useState(()=>f.ownerId?_s():qN(f.name)),[J,W]=N.useState(null),[ee,K]=N.useState(null),O=de=>K(fr(de)),j=jh(t,p),P=N.useMemo(()=>(j||[]).filter(de=>de.instanceId).map(de=>({instanceId:de.instanceId,route:de.route,label:de.label,status:de.status})),[j]),M=MN(t,_,F,D,P),H=M.decks;N.useEffect(()=>{const de=new Map;for(const Ee of j||[]){const Ue=(Ee.route||[Ee.name]).join("/"),_t=new Set((Ee.sessions||[]).map(dt=>dt.name));for(const dt of Ee.cells||[])!dt.cell||!dt.tmuxSession||dt.cell===dt.tmuxSession||_t.has(dt.cell)||de.set(`${Ue}:${dt.cell}`,`${Ue}:${dt.tmuxSession}`)}D(Ee=>Q0(Ee,de))},[j]),N.useEffect(()=>{M.localNodeId&&D(de=>{const Ee=hh(de,M.localNodeId,P);return JSON.stringify(Ee)===JSON.stringify(de)?de:Ee})},[P,M.localNodeId]);const[te,T]=N.useState(null),[ie,B]=N.useState(null),L=N.useRef(0),[$,X]=N.useState(!1),[ae,ue]=N.useState(WN),[ge,Z]=N.useState(!y),[q,fe]=N.useState(()=>y?localStorage.getItem(S_)==="1":!0),[Ie,et]=N.useState(!1),[ze,Fe]=N.useState("nodes"),[Ct,Ge]=N.useState(!1),[rt,ut]=N.useState(""),ct=(de="nodes",Ee=!1,Ue="")=>{Fe(de),Ge(Ee),ut(Ue),et(!0)},[vt,it]=N.useState(!1),[lt,mt]=N.useState({deviceDefault:"",localNodeId:"",localNameDefault:""}),[le,be]=N.useState(!1);N.useEffect(()=>{try{localStorage.setItem(Yw,String(ae))}catch{}},[ae]),N.useEffect(()=>{try{localStorage.setItem(S_,q?"1":"")}catch{}},[q]),N.useEffect(()=>{if(!t)return;let de=!1;return Promise.all([T_(t),tn("/api/config",t).then(Ee=>Ee.json())]).then(([Ee,Ue])=>{de||(mt({deviceDefault:Ee.deviceName||"",localNodeId:Ee.nodeId||"",localNameDefault:Ee.localName||""}),be(!!Ue.readonlyDefault),(Ee.firstRun===!0&&!Ue.readonlyDefault||s)&&it(!0))}).catch(()=>{}),()=>{de=!0}},[t,s]);const Be=N.useCallback(async()=>{try{const Ee=await(await tn("/api/sessions",t)).json();Ee.error||k(Ee.sessions||[])}catch{}try{const de=await zr(t);I(de.available?de.cells||[]:[]),G(de.available?de.capabilities||[]:[])}catch{I([]),G([])}},[t]);N.useEffect(()=>{if(!p)return;Be();const de=setInterval(Be,4e3);return()=>clearInterval(de)},[p,Be]),N.useEffect(()=>{let de=!1;return tn("/api/config",t).then(Ee=>Ee.json()).then(Ee=>{de||BN(Ee.version,Ee.uiVersion,"0.8.37")}).catch(()=>{}),()=>{de=!0}},[t]);const $e=new Set([...C.map(de=>de.name),...j.flatMap(de=>de.sessions.map(Ee=>Ee.key))]),he=vi(F),V=de=>D(Ee=>{const Ue=cw(de,M.localNodeId,P)||de,_t=Q_(Ee,Ue);return _t===Ee&&vi(Ee).length>=9&&M.setError(g("grid-full")),_t}),ne=async(de,Ee=[])=>{try{await Ch(t,de,Ee)}catch{return}const Ue=Ee.length?`${Ee.join("/")}:${de}`:de;D(_t=>kl(_t,Ue)),Be()},z=async(de,Ee,Ue=[])=>{try{await D_(t,de,Ee,Ue)}catch{return}Be()},se=async(de,Ee,Ue=[])=>{await P_(t,{cell:de,enabled:!!Ee},Ue),Be()},me=async de=>{if(!te)return;const{cell:Ee}=te,Ue=Array.isArray(te.route)?te.route:[];de.action==="up"?await kh(t,{cell:Ee,boot:!!de.boot,...de.engine?{engine:de.engine}:{},...de.model!==void 0?{model:de.model}:{},...de.permissionPolicy?{permissionPolicy:de.permissionPolicy}:{}},Ue):await gl(t,{cell:Ee,boot:!!de.boot},Ue);const _t=de.action==="up"?!!de.boot:de.boot?!1:!!te.boot;B({id:++L.current,cell:Ee,route:Ue,enabled:_t}),Be()},ke=N.useCallback(de=>{B(Ee=>(Ee==null?void 0:Ee.id)===de?null:Ee)},[]),Ne=async de=>{if(!(!(de!=null&&de.direct)||$)){X(!0);try{await Rh(t,de.name,de.tunnelStatus==="up"?"down":"up")}finally{X(!1)}}},we=async(de,Ee)=>{const Ue=String(Ee||"").trim();return!(de!=null&&de.direct)||!bs(Ue)?!1:(await I_(t,de.name,Ue),!0)},Re=de=>{const Ee=H.find(Ue=>Ue.id===de);if(!Ee)return!1;try{const Ue=window.open(Ku(Ee,t),"_blank");return Ue&&(Ue.opener=null),!!Ue}catch{return!1}},Je=async de=>{if(!de||de===_)return;const Ee=await M.select(de),Ue=M.records.find(_t=>_t.id===de);b(de),D(Ee),W(null),K(null);try{history.replaceState(null,"",Ku(Ue||de,null))}catch{}},Tt=async(de,Ee)=>{const Ue=await M.add(de,Ee);await Je(Ue.id)},Me=async(de,Ee)=>{const Ue=await M.rename(de,Ee);if(de===_){b(Ue.id),D(hh(Ue.layout,M.localNodeId,P)),W(null),K(null);try{history.replaceState(null,"",Ku(Ue,null))}catch{}}},pn=async de=>{await M.remove(de),de===_&&await Je(M.localMainId)},bt=async(de,Ee)=>{!Ee||Ee===_||(await M.addTileTo(Ee,de),D(Ue=>kl(Ue,de)))};if(!t)return c.jsxs("div",{className:"nc-auth",children:[c.jsx("p",{children:g("auth-prompt")}),c.jsx("input",{onChange:de=>n(de.target.value.trim()),placeholder:"token"}),c.jsxs("label",{children:[c.jsx("input",{type:"checkbox",checked:u,onChange:de=>h(de.target.checked)})," ",g("remember-device")]}),c.jsx("button",{onClick:()=>{(u?localStorage:sessionStorage).setItem("nc_token",t)},children:"ok"})]});const Ke=c.jsxs(c.Fragment,{children:[Ie&&c.jsx(CN,{token:t,initialTab:ze,initialLocation:rt,startNewCell:Ct,onClose:()=>{et(!1),Ge(!1),ut("")}}),vt&&c.jsx(EN,{token:t,initialPair:s,...lt,onPairDone:a,onDone:()=>it(!1)}),c.jsx(DN,{token:t})]});if(!p)return w?c.jsxs(c.Fragment,{children:[c.jsx(x_,{session:w.session,node:w.node,ownerId:w.ownerId,cellName:w.cellName,token:t,readonly:le,onBack:()=>S(null)}),Ke]}):c.jsxs(c.Fragment,{children:[c.jsx(f1,{onPick:x,token:t,onSettings:ct}),Ke]});const $t=y||!ge;return c.jsxs("div",{className:"nc-workspace",children:[$t&&c.jsx(fE,{sessions:C,cells:R,activeSessions:he,nodeGroups:j,fleetCapabilities:A,bootSettlement:ie,onBootSettlementApplied:ke,localNodeId:M.localNodeId,onPick:O,onAddTile:V,onPower:T,onBoot:se,onBootError:de=>M.setError(String((de==null?void 0:de.message)||de)),onNodePower:Ne,onNodeRename:we,onKill:ne,onVisibility:z,onNew:()=>ct("fleet",!0),onSettings:ct,width:ae,collapsed:q,onResize:ue,onToggleCollapse:()=>fe(de=>!de)}),c.jsxs("div",{className:"nc-workspace-main",children:[c.jsx(YE,{decks:H,currentDeck:_,onCreate:Tt,onRename:Me,onDelete:pn,onReorder:M.reorder,onOpenWindow:Re,onNavigate:Je,saveState:M.saveState,error:M.error,sidebarVisible:$t,onToggleSidebar:y?null:()=>Z(de=>!de)}),c.jsx(wE,{layout:F,onLayoutChange:D,token:t,readonly:le,sessionsAlive:$e,focusSession:J,onFocus:W,onOpenSingle:O,decks:H,currentDeck:_,onSendToDeck:bt,cells:R,nodeGroups:j})]}),ee&&c.jsx("div",{className:"nc-single-overlay",children:c.jsx(x_,{session:ee.session,node:ee.node,ownerId:ee.ownerId,cellName:Yh({session:ee.session,node:ee.node,ownerId:ee.ownerId,cells:R,nodeGroups:j}),token:t,readonly:le,onBack:()=>K(null)})}),te&&c.jsx(_l,{cell:te,token:t,route:Array.isArray(te.route)?te.route:[],onConfirm:me,onClose:()=>T(null)}),Ke]})}function GN(){zn();const e=N.useSyncExternalStore(IN,w_,w_);if(!e.needed)return null;const t=e.kind==="install"?g("install-version-mismatch").replace("{v}",e.version):g("update-available").replace("{v}",e.version).replace(" "," ").trim();return c.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[c.jsx("span",{className:"nc-update-msg",children:t}),e.kind==="reload"&&c.jsx("button",{className:"nc-update-btn",onClick:FN,children:g("reload")})]})}zN();Gb.createRoot(document.getElementById("root")).render(c.jsxs(Hb.StrictMode,{children:[c.jsx(YN,{}),c.jsx(GN,{})]}));