@camstack/addon-admin-ui 1.2.626 → 1.2.628
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/dist/assets/Addons-DYXP9Vml.js +5 -0
- package/dist/assets/{AdminPage-dLt1mKEa.js → AdminPage-D8jyd8NK.js} +1 -1
- package/dist/assets/{AdminSectionedPage-BYn7-4dT.js → AdminSectionedPage-BVfSxBNr.js} +1 -1
- package/dist/assets/AiProfiles-cx0x2sbl.js +3 -0
- package/dist/assets/{Authentication-CykaHfAJ.js → Authentication-C15V7E8r.js} +1 -1
- package/dist/assets/Build-goVTGENZ.js +39 -0
- package/dist/assets/{Calendars-D_iMy7Yy.js → Calendars-BwAVxLT1.js} +1 -1
- package/dist/assets/{CameraGrids-WkOqz0ai.js → CameraGrids-DZskmHW3.js} +1 -1
- package/dist/assets/Cluster-B1_BYrrA.js +1 -0
- package/dist/assets/CompositionBlockEditor-BXmpBbjk.js +2 -0
- package/dist/assets/CompositionEditorPage-ewhTgbIT.js +1 -0
- package/dist/assets/Data-CRPjnR7i.js +2 -0
- package/dist/assets/DeviceDetail-B5-2vX2l.js +2 -0
- package/dist/assets/{DeviceDoActionFields-CAAMOfrL.js → DeviceDoActionFields-C5X74bZ6.js} +1 -1
- package/dist/assets/{Devices-CelRF0ak.js → Devices-BZZZzZZt.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-CMOLFarm.js → EmbedPlayerPage-B7SerkXI.js} +1 -1
- package/dist/assets/History-CB2UV29J.js +1 -0
- package/dist/assets/Identity-FncxI-3k.js +1 -0
- package/dist/assets/{InstanceSwitchCell-BQekirNX.js → InstanceSwitchCell-DL1wNRqw.js} +1 -1
- package/dist/assets/InstancesTable-C9lW5ahJ.js +1 -0
- package/dist/assets/IntegrationDetail-CRgTh0vI.js +1 -0
- package/dist/assets/{IntegrationHub-jVzJirPk.js → IntegrationHub-itremyka.js} +1 -1
- package/dist/assets/Integrations-CKsDYSo_.js +2 -0
- package/dist/assets/Integrations-Doe4DOLd.js +1 -0
- package/dist/assets/Library-DZAOkZl5.js +1 -0
- package/dist/assets/Locations-BWYHqMs1.js +3 -0
- package/dist/assets/{Logs-DOFxrXxZ.js → Logs-BtV5zfyp.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-C6vw0mq_.js → MaskShapeCanvas-C5NPlFTZ.js} +1 -1
- package/dist/assets/{MotionZonesSettings-BPLgHoj3.js → MotionZonesSettings-DBiJiDpA.js} +1 -1
- package/dist/assets/MyAccess-Dn6aOrRH.js +2 -0
- package/dist/assets/Network-Bb5q027q.js +1 -0
- package/dist/assets/{NodeAddonsSettingsPanel-BGB_St7Q.js → NodeAddonsSettingsPanel-B2CB5Cql.js} +1 -1
- package/dist/assets/Notifications-B96nhFZS.js +1 -0
- package/dist/assets/Pipeline-DGVG0VZc.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-mpx3kl1W.js → PrivacyMaskSettings-Cxcz6fqW.js} +1 -1
- package/dist/assets/Recordings-DwBtl1P7.js +1 -0
- package/dist/assets/{ScanSubnetEditor-MFkKIxnM.js → ScanSubnetEditor-Om5o0_fX.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-HTEqKGnK.js → SceneMonitorEditor-C3Ht01Y_.js} +1 -1
- package/dist/assets/SessionsList-CLJLWiDV.js +2 -0
- package/dist/assets/{Showroom-CyZpVw5e.js → Showroom-DHls8MSr.js} +1 -1
- package/dist/assets/{StorageLocationsTable-DznxRZnK.js → StorageLocationsTable-Ch3ABRRX.js} +1 -1
- package/dist/assets/{System-C-k3Rz-I.js → System-DTVt3mqw.js} +1 -1
- package/dist/assets/{Templates-DAIsSP23.js → Templates-DSIFW4Sg.js} +1 -1
- package/dist/assets/{Terminal-C1QNo9AN.js → Terminal-DtQsE9UM.js} +3 -3
- package/dist/assets/{TrainingProviders-DbqfB5Q6.js → TrainingProviders-d3o_ZKQJ.js} +1 -1
- package/dist/assets/{Viewer-CZuKd6lk.js → Viewer-630uaAn-.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CSfv8t1Z.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CCci1-8S.js} +1 -1
- package/dist/assets/{ai-page.helpers-CJk-hY0M.js → ai-page.helpers-DYP6h9NO.js} +1 -1
- package/dist/assets/{archive-CvMfQY3E.js → archive-JrYGCSml.js} +1 -1
- package/dist/assets/{assignment-candidates-DN-VoSTA.js → assignment-candidates-Bg8uFhC2.js} +1 -1
- package/dist/assets/{authed-media-DkaeZ1M8.js → authed-media-Bf-hw8ZZ.js} +1 -1
- package/dist/assets/{bell-off-B4ksiU12.js → bell-off-Bpmfs7A4.js} +1 -1
- package/dist/assets/{board-model-D-CIwcV1.js → board-model-C4Q-Tf8g.js} +1 -1
- package/dist/assets/{boxes-C9Y0YvOc.js → boxes-li1RD5xe.js} +1 -1
- package/dist/assets/{calendar-clock-CqZRVSc3.js → calendar-clock-DztRh5OG.js} +1 -1
- package/dist/assets/circle-arrow-up-CZgLptGX.js +1 -0
- package/dist/assets/circle-slash-xZwqd0BU.js +1 -0
- package/dist/assets/client-BGa0ynTX.js +809 -0
- package/dist/assets/create-composition-D8ndL58S.js +2 -0
- package/dist/assets/crop-BoVOvHci.js +1 -0
- package/dist/assets/{database-zap-Bk33ph_X.js → database-zap-D5EwGo_g.js} +1 -1
- package/dist/assets/{device-integration-icon-Duw74rkd.js → device-integration-icon-C4Qf-4Rd.js} +1 -1
- package/dist/assets/device-picker-model-LnwJcnrH.js +1 -0
- package/dist/assets/{dist-Dli1FBe2.js → dist-COIeUAeS.js} +1 -1
- package/dist/assets/dist-ClneX5Rj.js +809 -0
- package/dist/assets/{eraser-C1LaIkqO.js → eraser-CrZ4yaiD.js} +1 -1
- package/dist/assets/{file-up-CODncsO3.js → file-up-CCndGa8K.js} +1 -1
- package/dist/assets/{format-C7beVF9i.js → format-vZthOBDI.js} +1 -1
- package/dist/assets/{hard-drive-download-gFUluoPC.js → hard-drive-download-BOts87eq.js} +1 -1
- package/dist/assets/{hostInit-OZrStRqO.js → hostInit-KnMePivw.js} +1 -1
- package/dist/assets/i18n-CKtnf08g.js +1 -0
- package/dist/assets/icons-DzRQ57dB.js +1 -0
- package/dist/assets/index-DCQq1ksG.js +4 -0
- package/dist/assets/index-cBkBJKJv.css +2 -0
- package/dist/assets/{key-BSgMvX5L.js → key-DlDr1x_1.js} +1 -1
- package/dist/assets/{key-square-CX058EfV.js → key-square-Dg-fQSMX.js} +1 -1
- package/dist/assets/{layers-DgoxyPih.js → layers-qknQ4SI0.js} +1 -1
- package/dist/assets/{link-2-off-DmtgBwh-.js → link-2-off-ClQoCkvl.js} +1 -1
- package/dist/assets/{linked-devices-model-B_gqV5Gg.js → linked-devices-model-BxDwmRW0.js} +1 -1
- package/dist/assets/{list-ordered-C0l-Wwk-.js → list-ordered-DK6yrsuq.js} +1 -1
- package/dist/assets/{memory-stick-BSUaqG9H.js → memory-stick-4bgTdR1n.js} +1 -1
- package/dist/assets/{message-square-plus-spORh6qX.js → message-square-plus-Bv2lcMzp.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-762c2049.js → mf-entry-bootstrap-0-9a11aec7.js} +2 -2
- package/dist/assets/{mic-off-DiGyKjsE.js → mic-off-CwdWl1x4.js} +1 -1
- package/dist/assets/{monitor-off-CatAL1-V.js → monitor-off-Ccscg8YU.js} +1 -1
- package/dist/assets/{monitor-smartphone-CrChoiUo.js → monitor-smartphone-C8BeBYyf.js} +1 -1
- package/dist/assets/mount-LnwJcnrH.js +1 -0
- package/dist/assets/{notification-rule-status-BaZr2lCj.js → notification-rule-status-BrmTbrp9.js} +1 -1
- package/dist/assets/player-overlays-BPvPXIk8.js +1 -0
- package/dist/assets/remoteEntry-Bfe_8orj.js +1 -0
- package/dist/assets/{ruler-6Q54d4xt.js → ruler-CH-94_uK.js} +1 -1
- package/dist/assets/{tv-BdJr-riI.js → scan-eye-D_sweDOa.js} +1 -1
- package/dist/assets/{scissors-BBC_GGoc.js → scissors-DPQ0H7Hw.js} +1 -1
- package/dist/assets/{search-x-CHDiifxm.js → search-x-Bcr_N2Jd.js} +1 -1
- package/dist/assets/{send-CwDFB9fX.js → send-dBvBmsQA.js} +1 -1
- package/dist/assets/{settings-2-C5tt8eea.js → settings-2-CUqyfTbY.js} +1 -1
- package/dist/assets/{shapes-C5Nnn9NE.js → shapes-1kA4AD87.js} +1 -1
- package/dist/assets/{sigma-BSlFNDI5.js → sigma--1BGzaqj.js} +1 -1
- package/dist/assets/src-Bgosi05F.js +169 -0
- package/dist/assets/{sso-popup-C6eP07wS.js → sso-popup-BGoesDjS.js} +1 -1
- package/dist/assets/{step-inspector-model-CEg8vezx.js → step-inspector-model-XS8YChH9.js} +1 -1
- package/dist/assets/{table-2-CeAydAOI.js → table-2-CilKmwQl.js} +1 -1
- package/dist/assets/{timer-reset-B_Ta8kGS.js → timer-reset-D4i4Gq1v.js} +1 -1
- package/dist/assets/{unlink-DzO14DVn.js → unlink-D4LV8ueN.js} +1 -1
- package/dist/assets/{usb-W-ktPgHL.js → usb-CReSdVpL.js} +1 -1
- package/dist/assets/{use-device-bound-caps-xJuEMYyg.js → use-device-bound-caps-D1IKyog8.js} +1 -1
- package/dist/assets/{use-scenes-feed-BFZqBAYX.js → use-scenes-feed-Ch0tafaX.js} +1 -1
- package/dist/assets/{use-stationary-objects-CHjUAUSJ.js → use-stationary-objects-YYdmB4ug.js} +1 -1
- package/dist/assets/{useAdminDeviceRemoval-YiBXHBHP.js → useAdminDeviceRemoval-BFZd48u8.js} +1 -1
- package/dist/assets/useEventInvalidation-LnwJcnrH.js +1 -0
- package/dist/assets/{useNodeUrlSelection-D9CPif56.js → useNodeUrlSelection-DuUq732x.js} +1 -1
- package/dist/assets/useTemplateSave-DB88BNeY.js +1 -0
- package/dist/assets/user-round-DeoBP4Ew.js +1 -0
- package/dist/assets/{user-x--TnMk2gT.js → user-x-o0ouhQrV.js} +1 -1
- package/dist/assets/{variable-Bz8zKWo2.js → variable-BER3ndF7.js} +1 -1
- package/dist/assets/{video-b4uGYAxS.js → video-Cifrbvwj.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Cs7a4rE-.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-ET0QdTsB.js} +2 -2
- package/dist/index.html +10 -11
- package/dist/server/addon.js +1069 -173
- package/package.json +2 -2
- package/dist/assets/Addons-B4N1LxY8.js +0 -5
- package/dist/assets/AiProfiles-DcAkO0SI.js +0 -3
- package/dist/assets/Build-DvxNre5q.js +0 -39
- package/dist/assets/Cluster-CyLi0SW_.js +0 -1
- package/dist/assets/CompositionBlockEditor-B6GFdIeM.js +0 -2
- package/dist/assets/CompositionEditorPage-B8-97pRO.js +0 -1
- package/dist/assets/Data-CDo9vIwN.js +0 -2
- package/dist/assets/DeviceDetail-BBanvUVD.js +0 -2
- package/dist/assets/History-Cvy2subh.js +0 -1
- package/dist/assets/Identity-DrFBCRWk.js +0 -1
- package/dist/assets/InstancesTable-Bt8qoWMR.js +0 -1
- package/dist/assets/IntegrationDetail-DvlDDD_J.js +0 -1
- package/dist/assets/Integrations-B9p5_Qf7.js +0 -1
- package/dist/assets/Integrations-HUB0bAoi.js +0 -2
- package/dist/assets/Library-DCDTlPnF.js +0 -1
- package/dist/assets/Locations-1E3b4qVs.js +0 -3
- package/dist/assets/MyAccess-CShkG3rs.js +0 -2
- package/dist/assets/Network-CRBMMSjJ.js +0 -1
- package/dist/assets/Notifications-CEls0HQ3.js +0 -1
- package/dist/assets/Pipeline-CHz7NNm6.js +0 -1
- package/dist/assets/Recordings-Bccg5edp.js +0 -1
- package/dist/assets/SessionsList-CLTlUoNj.js +0 -2
- package/dist/assets/addon-icons-context-WCP6A9AS.js +0 -1
- package/dist/assets/circle-slash-DDhnvhLN.js +0 -1
- package/dist/assets/client-kWeONSGL.js +0 -809
- package/dist/assets/create-composition-CNJkzaMb.js +0 -2
- package/dist/assets/crop-D1l0Xs25.js +0 -1
- package/dist/assets/device-picker-model-DCNN-HPV.js +0 -1
- package/dist/assets/dist-DXhYk_uu.js +0 -809
- package/dist/assets/i18n-Cmy3cCDH.js +0 -1
- package/dist/assets/icons-BM3wcj03.js +0 -1
- package/dist/assets/index-D4z5SYp_.css +0 -2
- package/dist/assets/index-DwCHDODI.js +0 -4
- package/dist/assets/mount-DCNN-HPV.js +0 -1
- package/dist/assets/player-overlays-CC-b3--a.js +0 -1
- package/dist/assets/remoteEntry-C16PJyFZ.js +0 -1
- package/dist/assets/speaker-ydML9LxI.js +0 -1
- package/dist/assets/src-DGSNF4l8.js +0 -100
- package/dist/assets/useEventInvalidation-DCNN-HPV.js +0 -1
- package/dist/assets/useTemplateSave-DBc8G5sM.js +0 -1
- package/dist/assets/user-round-D8euVsR1.js +0 -1
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,o as d,t as f,x as p}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{An as m,Di as h,Fi as g,Kt as _,Ni as v,Rr as y,Sr as b,St as x,Un as S,Ut as C,Wn as w,Yn as T,br as E,ct as D,ht as O,ut as k,wn as A,xa as j}from"./player-overlays-CC-b3--a.js";import{$a as M,As as N,Ba as P,Ca as F,Ga as I,Ha as L,Ja as R,Ka as z,Ki as B,La as V,Mi as ee,No as H,Qa as te,Ra as ne,Tr as re,Ua as ie,Vi as ae,Vt as oe,Wa as se,Xa as ce,_a as le,ao as ue,eo as de,gs as fe,io as pe,ji as U,ki as me,lo as he,no as ge,oo as _e,or as ve,pa as ye,qa as be,ro as xe,so as Se,to as Ce,xa as W,za as we}from"./client-kWeONSGL.js";import{t as Te}from"./boxes-C9Y0YvOc.js";import{t as Ee}from"./calendar-clock-CqZRVSc3.js";import{c as De}from"./video-b4uGYAxS.js";import{n as Oe,r as ke,t as Ae}from"./variable-Bz8zKWo2.js";import{$a as je,$d as Me,Bi as Ne,Bn as Pe,Br as Fe,Bu as Ie,Di as G,Dt as Le,Fr as Re,Go as ze,Gu as Be,Hi as Ve,Hu as He,J as Ue,K as We,Ku as Ge,Li as Ke,Ln as qe,Lr as Je,Ms as Ye,Mt as Xe,Nn as Ze,Nt as Qe,Qa as $e,Qo as et,Qr as tt,Ri as nt,Rn as rt,Rr as it,Si as at,Tt as ot,Uu as st,Vi as ct,Vo as lt,Vr as ut,Vu as dt,Wi as ft,Wr as pt,Wu as mt,Xr as ht,Yr as K,ao as gt,ar as _t,bd as vt,bn as yt,co as bt,cr as xt,eo as St,fn as Ct,fu as wt,gt as Tt,ir as Et,kf as Dt,lo as Ot,ms as kt,nf as At,nr as jt,oi as Mt,pn as Nt,ri as Pt,ro as Ft,rr as It,sf as q,sn as Lt,so as Rt,tr as zt,ur as Bt,v as Vt,vn as Ht,yi as J,zn as Ut,zr as Wt,zu as Gt}from"./src-DGSNF4l8.js";import{t as Y}from"./i18n-Cmy3cCDH.js";import{t as X}from"./useTranslation-BJr-n0es.js";import{Br as Kt,Fr as qt,H as Jt,Pr as Z,Rr as Yt,S as Xt,h as Zt,m as Qt,st as $t,ut as en}from"./index-DwCHDODI.js";import{t as tn}from"./AdminSectionedPage-BYn7-4dT.js";import{n as nn}from"./format-C7beVF9i.js";import{C as rn,D as an,E as on,O as sn,S as cn,_ as ln,a as Q,b as un,c as dn,d as fn,f as pn,g as mn,h as hn,i as gn,k as _n,l as vn,m as yn,n as bn,o as xn,p as Sn,r as Cn,s as wn,t as Tn,u as En,v as Dn,w as On,x as kn,y as An}from"./create-composition-CNJkzaMb.js";import{C as jn,a as Mn,at as Nn,b as Pn,g as Fn,i as In,lt as Ln,n as Rn,nt as zn,o as Bn,r as Vn,w as Hn,y as Un}from"./CompositionBlockEditor-B6GFdIeM.js";var Wn=`const AUTOMATION_RECIPE =`,Gn=`// EJECTED from the visual automation editor — this file is now hand-owned.
|
|
2
|
-
// The recipe that produced it was removed with it, on purpose: while it was
|
|
3
|
-
// here the editor could re-open this block and overwrite everything below.`;function Kn(e){return e.includes(Wn)}function qn(e){let t=e.indexOf(Wn);if(t<0)return null;let n=e.indexOf(`{`,t+25);if(n<0)return null;let r=0,i=!1,a=!1;for(let o=n;o<e.length;o+=1){let s=e.charAt(o);if(i){a?a=!1:s===`\\`?a=!0:s===`"`&&(i=!1);continue}if(s===`"`){i=!0;continue}if(s===`{`)r+=1;else if(s===`}`&&(--r,r===0))return{declStart:t,literalEnd:o+1,json:e.slice(n,o+1)}}return null}function Jn(e){let t=qn(e);if(t===null)return{ok:!1,reason:Y.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:Y.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=R.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Y.t(`helpers.recipeFromCode.schemaMismatch`):Y.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function Yn(e){let t=qn(e);if(t===null)return e;let n=e.slice(t.literalEnd),r=/^\s*as\s+const/.exec(n),i=t.literalEnd+(r===null?0:r[0].length);return`${e.slice(0,t.declStart)}${Gn}${e.slice(i)}`}u();function Xn(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function Zn(e,t){return be(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.name}`,e.description)}))}var Qn={name:``,steps:[],variables:[]};function $n(e){return e===null?Qn:{name:e.name,steps:e.steps??[],variables:e.variables??[]}}function er(e){let t=[],n=e=>{t.includes(e)||t.push(e)},r=e=>{if(on(e)){n(e.$var);return}Array.isArray(e)?e.forEach(r):typeof e==`object`&&e&&Object.values(e).forEach(r)};for(let t of e)t.kind===`cap`&&(r(t.deviceId),t.target?.kind===`var`&&n(t.target.name),r(t.args));return t}function tr(e){let t=new Set(e.variables.map(e=>e.name));return er(e.steps).find(e=>!t.has(e))??null}function nr(e){if(e.name.trim()===``)return{ok:!1,reason:{kind:`name`}};if(e.steps.length===0)return{ok:!1,reason:{kind:`no-steps`}};let t=e.variables.find(e=>!sr(e.name));if(t!==void 0)return{ok:!1,reason:{kind:`bad-name`,name:t.name}};let n=cr(e.variables)[0];if(n!==void 0)return{ok:!1,reason:{kind:`duplicate`,name:n}};let r=tr(e);if(r!==null)return{ok:!1,reason:{kind:`undeclared`,name:r}};let i=L.safeParse({name:e.name.trim(),steps:e.steps,...e.variables.length===0?{}:{variables:e.variables}});if(!i.success){let e=i.error.issues[0];return{ok:!1,reason:{kind:`schema`,message:`${e===void 0||e.path.length===0?``:`${e.path.join(`.`)}: `}${e?.message??`invalid`}`}}}return{ok:!0,input:i.data}}function rr(e,t,n){return on(e)?e.$var===t?{$var:n}:e:Array.isArray(e)?e.map(e=>rr(e,t,n)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,rr(r,t,n)])):e}function ir(e,t,n){if(e.kind!==`cap`)return e;let r=on(e.deviceId)&&e.deviceId.$var===t?{$var:n}:e.deviceId,i=e.target?.kind===`var`&&e.target.name===t?{kind:`var`,name:n}:e.target,a=e.args===void 0?void 0:Object.fromEntries(Object.entries(e.args).map(([e,r])=>[e,rr(r,t,n)]));return{...e,...r===void 0?{}:{deviceId:r},...i===void 0?{}:{target:i},...a===void 0?{}:{args:a}}}function ar(e,t,n){let r=e.variables[t];return r===void 0||r.name===n?e:{...e,variables:e.variables.map((e,r)=>r===t?{...e,name:n}:e),steps:e.steps.map(e=>ir(e,r.name,n))}}function or(e){let t=new Set(e.map(e=>e.name)),n=`value`;for(let e=2;t.has(n);e++)n=`value${String(e)}`;return{name:n,type:`string`}}function sr(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function cr(e){let t=new Set,n=new Set;for(let r of e)t.has(r.name)&&n.add(r.name),t.add(r.name);return[...n]}function lr(e){return e.some(e=>e.required===!0&&e.default===void 0)}function ur(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function dr(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function fr(e,t){return e.filter(e=>e.required===!0&&!dr(t[e.name])).map(e=>e.name)}function pr(e,t){let n={};for(let r of e){let e=t[r.name];dr(e)&&(n[r.name]=e)}return n}function mr({variable:e,value:t,onChange:n}){let{t:r}=X(),i=e.label??e.name;return e.type===`number`?o(sn,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?o(an,{widthClass:`w-28`,"aria-label":i,value:t===!0?`yes`:`no`,onChange:e=>n(e.target.value===`yes`),options:[{value:`yes`,label:r(`common.yes`,`Yes`)},{value:`no`,label:r(`common.no`,`No`)}]}):e.type===`select`?o(an,{widthClass:`w-48`,"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`actions.editor.runDialog.choose`,`Choose…`)},...(e.options??[]).map(e=>({value:e,label:e}))]}):o(q,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function hr({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:s}=X(),[l,u]=c(()=>ur(n)),d=fr(n,l);return o(Re,{open:!0,onOpenChange:e=>!e&&a(),children:e(Je,{"aria-label":s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(Fe,{children:[o(ut,{children:s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),o(it,{children:s(`actions.editor.runDialog.description`,`Give the variables this run should use.`)})]}),o(`div`,{className:`space-y-3`,"data-testid":`run-variables-form`,children:n.map(t=>e(`label`,{className:`block space-y-1`,children:[e(`span`,{className:`text-xs text-foreground-subtle`,children:[t.label??t.name,t.required===!0?` *`:``]}),o(mr,{variable:t,value:l[t.name],onChange:e=>u({...l,[t.name]:e})})]},t.name))}),e(Wt,{className:`flex flex-wrap gap-2`,children:[o(J,{variant:`ghost`,onClick:a,children:s(`common.cancel`,`Cancel`)}),e(J,{disabled:r||d.length>0,onClick:()=>i(pr(n,l)),children:[r?o(E,{className:`h-4 w-4 animate-spin`}):o(w,{className:`h-4 w-4`}),` `,s(`actions.editor.runNow`,`Run now`)]})]})]})})}var gr=[`number`,`string`,`boolean`,`select`];function _r(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function vr(e,t){let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``),r=e.default!==void 0&&typeof e.default==`string`&&n.includes(e.default),{default:i,...a}=e;return{...r?e:a,options:n.length===0?[`option`]:n}}function yr(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function br(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function xr({variables:t,onChange:n,onRename:r}){let{t:i}=X(),a=e=>{switch(e){case`number`:return i(`actions.variables.typeNumber`,`number`);case`string`:return i(`actions.variables.typeText`,`text`);case`boolean`:return i(`actions.variables.typeBoolean`,`yes / no`);default:return i(`actions.variables.typeSelect`,`select`)}},s=(e,r)=>n(t.map((t,n)=>n===e?r:t));return o(qe,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:Ae,actions:e(J,{variant:`outline`,size:`sm`,onClick:()=>n([...t,or(t)]),children:[o(S,{className:`h-4 w-4`}),` `,i(`actions.variables.add`,`Variable`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[t.map((c,l)=>e(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_8rem_1fr_1.2fr_auto] sm:items-end`,"data-testid":`variable-row`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.name`,`Name`)}),o(q,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!sr(c.name),onChange:e=>r(l,e.target.value)})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.label`,`Label`)}),o(q,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,br(c,e.target.value))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.type`,`Type`)}),o(an,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:gr.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=gr.find(t=>t===e.target.value);t!==void 0&&s(l,_r(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(Sr,{variable:c,onChange:e=>s(l,yr(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(q,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>s(l,vr(c,e.target.value))})]}),o(J,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(_,{className:`h-4 w-4`})})]},`${String(l)}`)),o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function Sr({variable:e,onChange:t}){let{t:n}=X(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(sn,{"aria-label":r,value:typeof e.default==`number`?e.default:void 0,onValue:t});if(e.type===`boolean`||e.type===`select`){let i=e.type===`boolean`?[{value:`true`,label:n(`common.yes`,`Yes`)},{value:`false`,label:n(`common.no`,`No`)}]:(e.options??[]).map(e=>({value:e,label:e}));return o(an,{widthClass:`w-full`,"aria-label":r,value:e.default===void 0?``:String(e.default),options:[{value:``,label:n(`actions.variables.noDefault`,`None`)},...i],onChange:n=>{n.target.value===``?t(null):t(e.type===`boolean`?n.target.value===`true`:n.target.value)}})}return o(q,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var Cr=5e3;function wr(e){return e.kind===`cap`||e.kind===`wait`}function Tr(e){return e instanceof Error?e.message:String(e)}function Er(){let{t:e}=X();return t=>{switch(t.kind){case`name`:return e(`actions.editor.problemName`,`Give the action a name.`);case`no-steps`:return e(`actions.editor.problemNoSteps`,`Add at least one step.`);case`undeclared`:return e(`actions.editor.problemUndeclared`,`A step uses {{name}}, which is not declared under Variables.`,{name:t.name});case`duplicate`:return e(`actions.editor.problemDuplicate`,`The variable {{name}} is declared twice.`,{name:t.name});case`bad-name`:return e(`actions.editor.problemBadName`,`The variable name "{{name}}" must start with a letter and use letters, digits or _.`,{name:t.name});default:return t.message}}}function Dr({entry:t,onClose:n,onSaved:i}){let{t:a}=X(),s=d(),l=D(),u=wn(),f=Er(),[m,h]=c(()=>$n(t)),[g,v]=c(null),[y,x]=c(!1),S=t!==null&&t.readOnly,C=()=>{s.invalidateQueries({queryKey:[[`actions`]]})},T=Ke({onSuccess:e=>{C(),i(e.action.id)}}),O=ft({onSuccess:C}),k=nt({onSuccess:()=>{C(),n()}}),A=Ve({onSuccess:C}),j=Ne({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Cr}),M=j.data?.traces.find(e=>e.runId===g)??null,N=r(()=>M===null?null:cn(M),[M]),P=r(()=>M===null?null:kn(M).steps,[M]),F=nr(m),I=r(()=>Xn(m.variables,a),[m.variables,a]),L=T.isPending||O.isPending,R=T.error??O.error??k.error??A.error,z=lr(t?.variables??[]);return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`action-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(b,{className:`h-4 w-4 text-foreground-muted`}),o(q,{"aria-label":a(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,disabled:S,placeholder:a(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>h({...m,name:e.target.value})}),o(G,{variant:S?`info`:`primary`,children:S?t?.addonId??``:a(`actions.source.internal`,`Internal`)})]}),S?o(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:a(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(p,{children:[o(xr,{variables:m.variables,onChange:e=>h({...m,variables:e}),onRename:(e,t)=>h(ar(m,e,t))}),o(ln,{step:`steps`,title:a(`actions.editor.steps`,`Steps`),trace:N===null?null:N.thenBlock,children:o(Cn,{actions:m.steps,devices:u,allowedKinds:[`cap`,`wait`],stepTones:N===null?void 0:m.steps.map((e,t)=>un(N,t)??`idle`),stepResults:P===null?void 0:m.steps.map((e,t)=>P.find(e=>e.index===t)),variables:I,onChange:e=>h({...m,steps:e.filter(wr)})})})]}),!F.ok&&!S&&m.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:f(F.reason)}),R!==null&&o(K,{message:Tr(R)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!S&&e(J,{onClick:()=>{F.ok&&(t===null?T.mutate({action:F.input}):O.mutate({actionId:t.id,action:F.input}))},disabled:L||!F.ok,children:[L&&o(E,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(J,{variant:`outline`,disabled:A.isPending,onClick:()=>z?x(!0):A.mutate({actionId:t.id}),children:[o(w,{className:`h-4 w-4`}),` `,a(`actions.editor.runNow`,`Run now`)]}),t!==null&&!S&&e(J,{variant:`ghost`,disabled:k.isPending,onClick:()=>{l({title:a(`actions.editor.deleteTitle`,`Delete this action?`),message:a(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&k.mutate({actionId:t.id})})},children:[o(_,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(J,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(mn,{traces:t===null?[]:j.data?.traces,selectedId:g,onSelect:v})}),y&&t!==null&&o(hr,{actionName:t.name,variables:t.variables??[],running:A.isPending,onCancel:()=>x(!1),onRun:e=>{A.mutate({actionId:t.id,variables:e}),x(!1)}})]})}u();var Or=5e3;function kr(e){return e instanceof Error?e.message:String(e)}function Ar(){let{t:e}=X();return t=>t.status.isRunning?{variant:`info`,label:e(`actions.status.running`,`Running`)}:t.status.lastError===null?t.status.lastRunAt===null?{variant:`neutral`,label:e(`actions.status.neverRan`,`Never ran`)}:{variant:`success`,label:e(`actions.status.ok`,`OK`)}:{variant:`danger`,label:e(`actions.status.failed`,`Failed`)}}function jr({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=X(),a=d(),c=Ar(),{state:l,openNew:u,openEdit:f,close:m}=ot({editKey:`action`,newKey:`new`}),h=ct({},{refetchInterval:Or}),g=Ve({onSuccess:()=>void a.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(u(),n?.())},[t,n,u]);let _=h.data??[],v=l.mode===`edit`?_.find(e=>e.id===l.id)??null:null,y=r(()=>[{key:`name`,header:i(`actions.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:i(`actions.list.source`,`Source`),render:e=>e.readOnly?o(G,{variant:`info`,children:e.addonId}):o(G,{variant:`primary`,children:i(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:i(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?o(`span`,{className:`text-foreground-subtle`,children:`-`}):nn(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:i(`actions.list.status`,`Status`),render:e=>{let t=c(e);return o(`span`,{title:e.status.lastError??void 0,children:o(G,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(J,{variant:`outline`,size:`sm`,disabled:g.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),g.mutate({actionId:t.id})},children:[o(w,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[g,c,i]);return l.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),g.error!=null&&o(K,{message:kr(g.error)}),h.data===void 0?h.error==null?o(tt,{className:`h-24 w-full`}):o(K,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:kr(h.error),onRetry:()=>void h.refetch()}):_.length===0?o(ht,{icon:b,title:i(`actions.list.emptyTitle`,`No actions yet`),description:i(`actions.list.emptyDescription`,`An action is a short list of commands, such as feeding the dog, that you can reuse.`),action:e(J,{onClick:u,children:[o(S,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(p,{children:[h.error!=null&&o(K,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:kr(h.error),onRetry:()=>void h.refetch()}),o(Ut,{columns:y,rows:_,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Pe,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>f(e.id)})]})]}):o(Dr,{entry:v,onClose:m,onSaved:f},v?.id??`new`)}u();function Mr({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=X(),[l,u]=c(!1),d=D(),f=async()=>{await d({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(J,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?g:v,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(J,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[o(De,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),l&&o(`div`,{className:`border-t border-border p-3`,children:t===null?o(`p`,{className:`text-xs text-warning`,children:n??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):o(Ze,{maxHeight:420,children:t})})]})}var Nr=[`single`,`restart`,`queued`,`parallel`,`cooldown`],Pr=2,Fr=30;function Ir(e){return e.runMode??{mode:`single`}}function Lr(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function Rr(e){switch(e){case`queued`:return{mode:`queued`,max:Pr};case`parallel`:return{mode:`parallel`,max:Pr};case`cooldown`:return{mode:`cooldown`,minutes:Fr};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function zr(e){return Nr.find(t=>t===e)??`single`}function Br({value:t,onChange:n}){let{t:r}=X(),i={single:r(`flow.runMode.single`,`Skip it`),restart:r(`flow.runMode.restart`,`Restart the run`),queued:r(`flow.runMode.queued`,`Queue it`),parallel:r(`flow.runMode.parallel`,`Run at the same time`),cooldown:r(`flow.runMode.cooldown`,`Wait after a run`)},a={single:r(`flow.runMode.singleHint`,`A trigger that arrives during a run is dropped.`),restart:r(`flow.runMode.restartHint`,`The run in progress stops and a new one starts.`),queued:r(`flow.runMode.queuedHint`,`Triggers wait their turn, up to the limit.`),parallel:r(`flow.runMode.parallelHint`,`Runs overlap, up to the limit.`),cooldown:r(`flow.runMode.cooldownHint`,`No new run until this long after the last one began.`)};return e(`div`,{className:`flex flex-wrap items-end gap-3`,"data-testid":`run-mode`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.label`,`When it is already running`)}),o(an,{widthClass:`w-56`,value:t.mode,options:Nr.map(e=>({value:e,label:i[e]})),onChange:e=>n(Rr(zr(e.target.value)))})]}),(t.mode===`queued`||t.mode===`parallel`)&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.max`,`Up to`)}),o(sn,{className:`w-20`,"aria-label":r(`flow.runMode.max`,`Up to`),value:t.max,onValue:e=>{e!==null&&n({mode:t.mode,max:Math.round(e)})}})]}),t.mode===`cooldown`&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.minutes`,`Minutes`)}),o(sn,{className:`w-20`,"aria-label":r(`flow.runMode.minutes`,`Minutes`),value:t.minutes,onValue:e=>{e!==null&&n({mode:`cooldown`,minutes:Math.round(e)})}})]}),o(`p`,{className:`basis-full text-xs text-foreground-subtle`,children:a[t.mode]})]})}var Vr;function Hr(){return Vr??=ne(re),Vr}function Ur(e,t=Hr()){return V(e,t)}function Wr({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=X(),c=Zr(n,r,i);if(n?.kind===`boolean`)return o(k,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:s(`common.true`)},{value:`false`,label:s(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return o(k,{value:String(t),onChange:e=>a(e.target.value),options:n.enumValues.map(e=>({value:e,label:e}))});if(n?.kind===`number`){let n=typeof t==`number`&&c?c.toDisplayValue(t):t;return e(`span`,{className:`inline-flex items-center gap-1`,children:[o(q,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?o(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return o(q,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Gr({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=X(),s=Zr(t,n,r);return o(q,{value:(s?e.map(e=>typeof e==`number`?s.toDisplayValue(e):e):e).join(`, `),placeholder:a(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let n=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);i(t?.kind===`number`?n.map(e=>Number(e)).filter(e=>!Number.isNaN(e)).map(e=>s?s.fromDisplayValue(e):e):n)}})}function Kr(e){return typeof e==`object`&&!he(e)}function qr(e){return he(e)?e.value:Kr(e)?e[0]??``:e}function Jr(e){return he(e)?[e.value]:Kr(e)?e:typeof e==`boolean`?[]:[e]}function Yr(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!fe(t)||t===`none`||t===`device`))return P(t).length>0?t:void 0}function Xr(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Zr(e,t,n){let r=Nt(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=lt({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=fe(s)?s:void 0,l=Xr(e?.quantity,c);if(l===void 0)return;let u=o?.display;return Ct({quantity:l,display:u,capName:n,unitPreferences:r})}function Qr({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=xn(a),c=yn(s?.kind),l=t.operator===`in`,u=Yr(s),d=u===void 0?void 0:we(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=$r(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...Jr(t.value)]:qr(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(gn,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[o(Q,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(k,{value:t.operator,onChange:e=>p(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Gr,{value:Jr(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?o(We,{quantity:u,storedUnit:d,value:typeof t.value==`number`?t.value:void 0,unit:t.unit,"aria-label":i(`automation.conditionRow.value`,`Value`),onChange:e=>{let n=Ue(e,d);r({...t,value:n.value,unit:n.unit})}}):o(Wr,{value:qr(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function $r(e,t){return t.find(t=>t.value===e)?.value??`eq`}var ei=Object.values(N).sort((e,t)=>e.localeCompare(t));function ti({leaf:t,onChange:n}){let{t:r}=X();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(q,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>n({kind:`schedule`,cron:e.target.value})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]})}function ni(){return o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})}function ri(e,t){return{kind:`device-becomes`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function ii({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=xn(a),c={...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}};return e(p,{children:[o(gn,{value:a,devices:n,onChange:e=>r(ri(e,c))}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),e(`div`,{className:`flex items-center gap-2`,children:[e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Bt,{checked:t.becomes===void 0,onChange:e=>r(ri(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o(Wr,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(ri(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Bt,{checked:t.edge===!0,onChange:e=>r(ri(a,{...c,...e.target.checked?{edge:!0}:{edge:void 0}}))}),i(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.heldForS`,`Held for (s)`)}),o(q,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(ri(a,{...c,forMs:ai(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(q,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(ri(a,{...c,debounceMs:ai(e.target.value)}))})]})]})}function ai(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function oi({leaf:t,devices:n,onChange:r}){let{t:i}=X();return e(p,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(k,{value:t.category,onChange:e=>r({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:i(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...ei.map(e=>({value:e,label:e}))]})]}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(_n,{devices:n,selection:`single`,value:t.deviceId===void 0?[]:[t.deviceId],emptyLabel:i(`automation.triggerEditor.anyDevice`,`Any device`),testId:`trigger-event-device`,onChange:e=>r({kind:`device-event`,category:t.category,...e[0]===void 0?{}:{deviceId:e[0]}})})]})]})}function si(e,t){let n=e.find(e=>e.id===t.deviceId);return{kind:`global`,sourceStableId:n?.stableId??``,...n?.addonId===void 0?{}:{addonId:n.addonId},cap:t.cap,fieldPath:t.fieldPath}}function ci(e,t){if(t.addonId!==void 0)return e.find(e=>e.stableId===t.sourceStableId&&e.addonId===t.addonId)?.id??0;let n=e.filter(e=>e.stableId===t.sourceStableId);return n.length===1?n[0]?.id??0:0}var li={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function ui({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=Object.entries(t.bindings),s=e=>{r({kind:`expression`,expr:t.expr,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`label`,{className:`block`,children:[o(Q,{children:i(`automation.expressionLeafRow.expression`,`Expression`)}),o(q,{value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:e=>r({kind:`expression`,expr:e.target.value,bindings:t.bindings})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.mustEvaluateToTrueOr`,`Must evaluate to true or false. Every name in it has to be bound below — an unbound name is refused when the automation is saved, not when it runs.`)})]}),e(`div`,{className:`space-y-1.5`,children:[a.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),a.map(([e,r])=>o(di,{alias:e,source:r,devices:n,onRename:n=>s(mi(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(hi(t.bindings,e))},e)),e(J,{variant:`ghost`,onClick:()=>s({...t.bindings,[pi(t.bindings)]:li}),children:[o(S,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function di({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=X(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:n.kind===`global`?ci(r,n):0,cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[o(Q,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(q,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Q,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(k,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:li),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(q,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:fi(e.target.value)})})]}):o(gn,{value:u,devices:r,onChange:e=>a(si(r,e))}),o(J,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(_,{className:`h-3.5 w-3.5`})})]})}function fi(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function pi(e){for(let t=0;t<26;t+=1){let n=String.fromCharCode(97+t);if(!(n in e))return n}return`n${String(Object.keys(e).length)}`}function mi(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function hi(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var gi=`text-xs text-foreground-subtle`;function _i({children:e}){return o(`span`,{className:gi,children:e})}function vi(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function yi({devices:t,selected:n,onChange:r}){let{t:i}=X(),a=t.filter(e=>e.type===H.Camera);return e(`div`,{className:`space-y-1`,children:[o(_i,{children:i(`flow.scene.cameras`,`Cameras`)}),o(_n,{devices:a,selection:`multiple`,noun:`camera`,value:n,testId:`scene-cameras`,onChange:r})]})}function bi({device:t,deviceId:n,selected:r,onToggle:i}){let a=Me({deviceId:n});return a.data===void 0||a.data.length===0?null:e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:gi,children:t?.name??`#${String(n)}`}),a.data.map(e=>o(J,{size:`sm`,variant:r.includes(e.id)?`primary`:`outline`,"aria-pressed":r.includes(e.id),onClick:()=>i(e.id),children:e.name},e.id))]})}function xi({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=X();if(n.length===0)return null;let s=e=>{let t=vi(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(_i,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(bi,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:gi,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var Si=[`animal`,`person`,`vehicle`,`package`,`other`];function Ci(e){return Si.find(t=>t===e)??`other`}function wi(e){switch(e){case`animal`:return{macro:`animal`};case`person`:return{macro:`person`};case`vehicle`:return{macro:`vehicle`};case`package`:return{macro:`package`};default:return{macro:`other`,className:``}}}function Ti(){let{t:e}=X();return t=>{switch(t){case`person`:return e(`flow.class.person`,`Person`);case`vehicle`:return e(`flow.class.vehicle`,`Vehicle`);case`animal`:return e(`flow.class.animal`,`Animal`);case`package`:return e(`flow.class.package`,`Package`);default:return e(`automation.whenTree.macroOther`,`Other class`)}}}function Ei(e,t){let n={kind:`sub-class`,className:t};switch(e){case`animal`:return{macro:e,label:n};case`package`:return{macro:e,label:n};case`vehicle`:return{macro:e,label:n};default:return{macro:`person`}}}var Di=[`automation`,`class-taxonomy`];function Oi(){let e=O();return oe(l({queryKey:Di,retry:!1,staleTime:1/0,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}).data?.taxonomy)}function ki(e,t,n){let r=n?.groups.find(t=>t.key===e),i=r===void 0?Se(e).filter(t=>t!==e).map(e=>({value:e,label:e})):r.options.filter(t=>t.value!==e).map(e=>({value:e.value,label:e.label}));return t!==void 0&&!i.some(e=>e.value===t)?[...i,{value:t,label:t}]:i}function Ai({subject:e,onChange:t}){let{t:n}=X(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=Oi(),a=ki(e.macro,r,i);return a.length===0?null:o(k,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:r??``,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...a],onChange:n=>{let r=n.target.value;t(r===``?wi(e.macro):Ei(e.macro,r))}})}function ji({onChange:e,subject:t}){let{t:n}=X(),r=Ye(),i=t.macro===`person`?t.label:void 0,a=r.data??[],s=a.map(e=>({value:e.id,label:e.name}));return i!==void 0&&!a.some(e=>e.id===i.identityId)&&s.push({value:i.identityId,label:i.name}),o(k,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:i?.identityId??``,options:[{value:``,label:n(`automation.whenTree.anyPerson`,`Anyone`)},...s],onChange:t=>{let n=t.target.value,r=s.find(e=>e.value===n);e(n===``||r===void 0?{macro:`person`}:{macro:`person`,label:{kind:`identity`,identityId:n,name:r.label}})}})}var Mi=`plate:`,Ni=`class:`,Pi=200;function Fi({onChange:e,subject:t}){let{t:n}=X(),r=wt({includeCrops:!1,limit:Pi}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,s=Oi(),c=i?.kind===`sub-class`?i.className:void 0,l=[...new Set((r.data??[]).map(e=>e.text))];a!==void 0&&!l.includes(a)&&l.push(a);let u=a===void 0?c===void 0?``:`${Ni}${c}`:`${Mi}${a}`;return o(k,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:u,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...ki(`vehicle`,c,s).map(e=>({value:`${Ni}${e.value}`,label:e.label})),...l.map(e=>({value:`${Mi}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(Mi)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(Ni)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function Ii({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:s}=X(),c=Ti(),l=t.macro===`other`?[]:_e[t.macro],u=l.some(e=>e.kind===`cap`&&e.label===`identity`),d=l.some(e=>e.kind===`cap`&&e.label===`plate`);return e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`subject-row`,children:[o(`div`,{className:`w-36`,children:o(k,{"aria-label":s(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:Si.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=Ci(e.target.value);n!==t.macro&&i(wi(n))}})}),o(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?o(q,{className:`w-40`,"aria-label":s(`automation.whenTree.className`,`Class name`),"data-testid":`subject-class-name`,placeholder:s(`automation.whenTree.classNamePlaceholder`,`Class name`),value:t.className,onChange:e=>i({macro:`other`,className:e.target.value})}):u&&!n?o(`div`,{className:`w-44`,children:o(ji,{subject:t,onChange:i})}):d&&!n?o(`div`,{className:`w-44`,children:o(Fi,{subject:t,onChange:i})}):!u&&o(`div`,{className:`w-44`,children:o(Ai,{subject:t,onChange:i})}),a!==null&&o(J,{variant:`ghost`,onClick:a,title:s(`automation.whenTree.removeClass`,`Remove this class`),children:o(_,{className:`h-3.5 w-3.5`})})]})}function Li({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:s}=X(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>o(Ii,{subject:e,classLabelsOnly:r,verb:n===0?i:s(`automation.whenTree.orSubject`,`or`),onChange:e=>a(t.map((t,r)=>r===n?e:t)),onRemove:c?()=>a(t.filter((e,t)=>t!==n)):null},`${e.macro}-${String(n)}`)),t.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:s(`flow.scene.anyClass`,`None picked: any class counts.`)}),e(J,{variant:`ghost`,size:`sm`,onClick:()=>a([...t,wi(`person`)]),children:[o(S,{className:`h-3.5 w-3.5`}),` `,t.length===0?s(`automation.whenTree.onlySomeClasses`,`Only some classes`):s(`automation.whenTree.addClass`,`Add a class`)]})]})}var Ri=100;function zi({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=Math.round((t.minScore??0)*Ri),s=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{minScore:n,...i}=t;r(e<=0?i:{...i,minScore:e/Ri})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(Li,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),o(yi,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(xi,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(_i,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/Ri).toFixed(2)})}),o(xt,{min:0,max:Ri,value:a,"aria-label":i(`flow.scene.minScoreAria`,`Minimum score`),className:`block w-full max-w-sm accent-primary`,onChange:e=>c(Number(e.target.value))})]})]})}function Bi({leaf:t,devices:n,onChange:r}){let{t:i}=X();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(Li,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.parked`,`object`),onChange:e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})}}),o(yi,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(xi,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(Tt,{label:i(`flow.scene.firesWhen`,`Fires when it`),value:t.phase,onChange:e=>r({...t,phase:e}),options:[{value:`appeared`,label:i(`flow.scene.phaseAppeared`,`Stopped (parked)`)},{value:`departed`,label:i(`flow.scene.phaseDeparted`,`Left`)}]})]})}function Vi({leaf:t,onChange:n}){let{t:r}=X();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(_i,{children:r(`flow.scene.every`,`Every`)}),o(sn,{"aria-label":r(`flow.scene.intervalMinutes`,`Minutes`),className:`w-20`,value:t.minutes,onValue:e=>{e!==null&&n({kind:`interval`,minutes:Math.round(e)})}}),o(_i,{children:r(`flow.scene.minutes`,`minutes`)})]})}function Hi({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=n.filter(e=>e.type===H.Camera),s=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},c=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},l=e=>{let{zones:n,...i}=t;r({...i,deviceId:e})};return e(`div`,{className:`space-y-3`,"data-testid":`stationary-present-fields`,children:[e(`div`,{className:`space-y-1`,children:[o(_i,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(_n,{devices:a,selection:`single`,noun:`camera`,value:t.deviceId>0?[t.deviceId]:[],testId:`stationary-present-camera`,onChange:e=>{let n=e[0];n!==void 0&&n!==t.deviceId&&l(n)}})]}),o(Li,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.isParked`,`is parked`),onChange:s}),e(`div`,{className:`flex items-center gap-2`,children:[o(_i,{children:i(`flow.scene.minCount`,`At least`)}),o(sn,{"aria-label":i(`flow.scene.minCountAria`,`Minimum parked objects`),"data-testid":`stationary-present-min-count`,className:`w-20`,value:t.minCount??1,onValue:e=>{let{minCount:n,...i}=t;r(e===null||e<=1?i:{...i,minCount:Math.floor(e)})}}),o(_i,{children:i(`flow.scene.minCountUnit`,`parked objects`)})]}),o(xi,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:c})]})}function Ui(e){return e.kind===`all`||e.kind===`any`}function Wi(e){return[`when`,...e].join(`.`)}function Gi(e){let t=e.when;return Ui(t)?t:{kind:`all`,children:[t]}}function Ki(e,t){return{...e,when:t}}function qi(e){return Ki(e,Gi(e))}function Ji(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?Ji(e.child,r):null;if(Ce(e))return null;let i=e.children[n];return i===void 0?null:Ji(i,r)}function Yi(e,t,n){let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=Yi(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(Ce(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Yi(a,i,n),s=o===null?[...e.children.slice(0,r),...e.children.slice(r+1)]:[...e.children.slice(0,r),o,...e.children.slice(r+1)];return s.length===0?null:{kind:e.kind,children:s}}function Xi(e,t,n){let r=Gi(e);return Ki(e,Yi(r,t,n)??{kind:r.kind,children:[]})}function Zi(e){return{kind:e,children:[Sn(`device-is`)]}}function Qi(e,t,n){return Xi(e,t,e=>Ui(e)?{kind:e.kind,children:[...e.children,n]}:e)}function $i(e,t,n){return Xi(e,t,()=>n)}function ea(e,t){return Xi(e,t,()=>null)}function ta(e,t,n){return Xi(e,t,e=>Ui(e)?{kind:n,children:e.children}:e)}function na(e,t){return t.length===0?e:Xi(e,t,e=>({kind:`not`,child:e}))}function ra(e,t){return Xi(e,t,e=>e.kind===`not`?e.child:e)}function ia(e,t){let n=Gi(e),r=Ji(n,t),i=t.slice(0,-1),a=t[t.length-1],o=Ji(n,i);return r===null||!Ui(r)||a===void 0||o===null||!Ui(o)?e:Xi(e,i,()=>({kind:o.kind,children:[...o.children.slice(0,a),...r.children,...o.children.slice(a+1)]}))}function aa(e,t){if(e.kind===t)return e;if(e.kind===`device-is`&&t===`device-becomes`){let{deviceId:n,cap:r,fieldPath:i,operator:a,value:o}=e,s={kind:t,deviceId:n,cap:r,fieldPath:i};return a===`eq`&&!Array.isArray(o)&&typeof o!=`object`?{...s,becomes:o}:s}if(e.kind===`device-becomes`&&t===`device-is`){let{deviceId:n,cap:r,fieldPath:i,becomes:a}=e;return{kind:t,deviceId:n,cap:r,fieldPath:i,operator:`eq`,value:a??``}}return Sn(t)}function oa(e){let t=Gi(e),n=t.children.length===0;return{depth:n?0:xe(t),leaves:n?0:te(t),depthLimit:4,leafLimit:32}}function sa(e,t){let n=Gi(e),r=1,i=n;for(let e of t){let t=Ji(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function ca(e){let t=new Map,n=(e,r)=>{if(Ce(e))return!1;let i=e.kind===`not`?[e.child]:e.children,a=!1;if(i.forEach((e,t)=>{n(e,[...r,t])&&(a=!0)}),a)return!0;let o=ge(e);return o===null?!1:(t.set(Wi(r),o),!0)};return n(e,[]),t}function la(){let{t:e}=X(),t={detection:e(`flow.triggerHint.detection`,`An object class is detected on a camera`),stationary:e(`flow.triggerHint.stationary`,`An object stops, or leaves`),"device-becomes":e(`automation.whenTree.hint_device_becomes`,`A device value takes a value`),"device-event":e(`flow.triggerHint.deviceEvent`,`An event on the system`),schedule:e(`flow.triggerHint.schedule`,`At a time of day`),interval:e(`flow.triggerHint.interval`,`Again and again, every few minutes`),manual:e(`flow.triggerHint.manual`,`Only when you run it`),"device-is":e(`automation.whenTree.hint_device_is`,`A device value is, right now`),"stationary-present":e(`automation.whenTree.hint_stationary_present`,`An object is parked on a camera, right now`),expression:e(`automation.whenTree.hint_expression`,`Arithmetic across device values, right now`)},n=e(`automation.whenTree.groupEvents`,`Happens (an event)`),r=e(`automation.whenTree.groupStates`,`Is true (a state)`);return fn.map(e=>({value:e,label:pn(e),description:t[e],group:En.includes(e)?n:r}))}function ua(e){return fn.find(t=>t===e)??null}function da({leaf:t,devices:n,toneClass:r,result:i,onNegate:a,onChange:s,onRemove:c}){let{t:l}=X(),u=la(),d=de(t);return e(`div`,{className:`rounded border p-2 ${r}`,"data-testid":`when-row`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`div`,{className:`min-w-[13rem] max-w-xs flex-1`,children:[o(Q,{children:l(`automation.whenTree.rowType`,`Row type`)}),o(at,{mode:`single`,singleDisplay:`field`,options:u,value:t.kind,testId:`when-row-type`,optionTestIdPrefix:`when-kind`,onChange:e=>{let n=ua(e);n!==null&&n!==t.kind&&s(aa(t,n))}})]}),o(G,{variant:d?`info`:`neutral`,"data-testid":`when-row-nature`,children:d?l(`automation.whenTree.natureEvent`,`Event`):l(`automation.whenTree.natureState`,`State`)}),o(`span`,{className:`flex-1`}),a!==null&&o(J,{variant:`ghost`,onClick:a,title:l(`automation.whenTree.negateRow`,`Invert this row (NOT)`),children:`NOT`}),o(J,{variant:`ghost`,onClick:c,title:l(`automation.whenTree.removeRow`,`Remove this row`),children:o(_,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:o(fa,{leaf:t,devices:n,onChange:s})}),i!==void 0&&o(`div`,{className:`mt-2`,children:i})]})}function fa({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return o(ii,{leaf:e,devices:t,onChange:n});case`device-event`:return o(oi,{leaf:e,devices:t,onChange:n});case`schedule`:return o(ti,{leaf:e,onChange:n});case`interval`:return o(Vi,{leaf:e,onChange:n});case`manual`:return o(ni,{});case`detection`:return o(zi,{leaf:e,devices:t,onChange:n});case`stationary`:return o(Bi,{leaf:e,devices:t,onChange:n});case`device-is`:return o(Qr,{leaf:e,devices:t,onChange:n});case`stationary-present`:return o(Hi,{leaf:e,devices:t,onChange:n});case`expression`:return o(ui,{leaf:e,devices:t,onChange:n})}}u();function pa(e){return e===`any`?`any`:`all`}function ma(e){return e===`pass`?`pass`:e===`fail`?`fail`:`idle`}function ha(e,t,n=!0){return e===void 0?t:n?Dn(ma(e)):An(ma(e))}function ga(e,t){return e.run?.nodes.get(Wi(t))}function _a({recipe:t,devices:n,onChange:i,run:a=null}){let{t:s}=X(),c=Gi(t),l=oa(t),u={recipe:t,devices:n,issues:r(()=>ca(c),[c]),run:a,onChange:i},d=c.children.length===0;return e(`div`,{className:`space-y-2`,"data-testid":`when-tree`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:s(`automation.whenTree.rule`,`An event starts a run when it happens and everything here is true at that moment. With only states, a run starts when they become true.`)}),o(Ta,{block:c,path:[],ctx:u,underNot:!1,budgetText:s(`automation.whenTree.budget`,{depth:l.depth,depthLimit:l.depthLimit,leaves:l.leaves,leafLimit:l.leafLimit}),emptyHint:d?s(`automation.whenTree.empty`,`Add a row to say when this runs. Without one nothing can ever start this automation.`):null})]})}function va({node:e,path:t,ctx:n,underNot:r}){return Ce(e)?o(ya,{leaf:e,path:t,ctx:n,underNot:r}):e.kind===`not`?o(wa,{child:e.child,path:t,ctx:n}):o(Ta,{block:e,path:t,ctx:n,underNot:r,budgetText:null,emptyHint:null})}function ya({leaf:e,path:t,ctx:n,underNot:r}){let i=ga(n,t),a=n.run!==null&&n.run.triggerPath===Wi(t)?n.run.vars:void 0;return o(da,{leaf:e,devices:n.devices,toneClass:ha(i?.outcome,`border-border`),result:i===void 0?void 0:o(ba,{leaf:e,node:i,vars:a}),onNegate:r?null:()=>n.onChange(na(n.recipe,t)),onChange:e=>n.onChange($i(n.recipe,t,e)),onRemove:()=>n.onChange(ea(n.recipe,t))})}function ba({leaf:e,node:t,vars:n}){return e.kind===`device-is`&&e.unit!==void 0?o(xa,{leaf:e,node:t,vars:n}):o(dn,{node:t,vars:n,expected:t.expected,observed:t.observed})}function xa({leaf:e,node:t,vars:n}){let r=Yr(xn({deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})),i=r===void 0?void 0:we(r),a=t=>t===void 0?null:rn(t,i,e.unit);return o(dn,{node:t,vars:n,expected:a(t.rawExpected),observed:a(t.rawObserved)})}function Sa({node:e}){return e===void 0?null:o(dn,{node:e,expected:null,observed:null})}function Ca({message:e}){return e===void 0?null:o(`p`,{role:`alert`,"data-testid":`when-issue`,className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:e})}function wa({child:t,path:n,ctx:r}){let{t:i}=X();return e(`div`,{className:`space-y-1.5 rounded border p-2 ${ha(ga(r,n)?.outcome,`border-warning/40`,!1)}`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(G,{variant:`warning`,children:`NOT`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.whenTree.notHint`,`True when what is below is not`)}),o(`span`,{className:`flex-1`}),e(J,{variant:`ghost`,onClick:()=>r.onChange(ra(r.recipe,n)),title:i(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[o(Oe,{className:`h-3.5 w-3.5`}),` `,i(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),o(Ca,{message:r.issues.get(Wi(n))}),o(Sa,{node:ga(r,n)}),o(`div`,{className:`pl-3`,children:o(va,{node:t,path:[...n,0],ctx:r,underNot:!0})})]})}function Ta({block:t,path:n,ctx:r,underNot:i,budgetText:a,emptyHint:s}){let{t:c}=X(),l=n.length===0,u=sa(r.recipe,n),d=[{value:`all`,label:c(`automation.whenTree.allOf`,`All of (AND)`)},{value:`any`,label:c(`automation.whenTree.anyOf`,`Any of (OR)`)}],f=s===null?r.issues.get(Wi(n)):void 0;return e(`div`,{className:`space-y-2 rounded border p-2 ${ha(ga(r,n)?.outcome,`border-border`,!1)} bg-surface-subtle/40`,"data-testid":`when-block`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`div`,{className:`w-40`,children:o(k,{"aria-label":c(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:d,onChange:e=>r.onChange(ta(r.recipe,n,pa(e.target.value)))})}),a!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a}),o(`span`,{className:`flex-1`}),!l&&!i&&o(J,{variant:`ghost`,onClick:()=>r.onChange(na(r.recipe,n)),title:c(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!l&&o(J,{variant:`ghost`,onClick:()=>r.onChange(ia(r.recipe,n)),title:c(`automation.whenTree.ungroup`,`Dissolve this block, keeping its rows`),children:o(Oe,{className:`h-3.5 w-3.5`})}),!l&&o(J,{variant:`ghost`,onClick:()=>r.onChange(ea(r.recipe,n)),title:c(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:o(_,{className:`h-3.5 w-3.5`})})]}),o(Ca,{message:f}),o(Sa,{node:ga(r,n)}),s!==null&&o(`p`,{className:`text-xs text-warning`,children:s}),t.children.length>0&&o(`div`,{className:`space-y-1.5 border-l border-border pl-3`,children:t.children.map((e,t)=>o(va,{node:e,path:[...n,t],ctx:r,underNot:!1},Wi([...n,t])))}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:`outline`,onClick:()=>r.onChange(Qi(r.recipe,n,Sn(`device-is`))),title:c(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[o(S,{className:`h-4 w-4`}),` `,c(`automation.whenTree.addRow`,`Add row`)]}),e(J,{variant:`outline`,disabled:!u,onClick:()=>r.onChange(Qi(r.recipe,n,Zi(t.kind===`all`?`any`:`all`))),title:u?c(`automation.whenTree.addBlockTitle`,`Add a nested block of rows`):c(`automation.whenTree.tooDeep`,`The rules nest at most {{max}} levels deep`,{max:oa(r.recipe).depthLimit}),children:[o(S,{className:`h-4 w-4`}),` `,c(`automation.whenTree.addBlock`,`Add block`)]})]})]})}u();var Ea=`hub`,Da=5e3;function Oa({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=X(),[p,m]=c(t?.name??``),[h,g]=c(()=>qi(n)),[_,v]=c(!1),[y,b]=c(null),x=Ft({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:Da}),S=x.data?.traces.find(e=>e.runId===y)??null,C=r(()=>S===null?null:cn(S),[S]),w=r(()=>Zn(h.when,f),[h.when,f]),T=r(()=>S===null?null:On(S),[S]),D=r(()=>S===null?null:kn(S).steps,[S]),O=wn(),k=ce(h),j=r(()=>ka(h),[h]),M=r(()=>Aa(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),N=p.trim()===``,P=N||k!==null||j!==null||M.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[e(`div`,{className:`space-y-4`,children:[e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(q,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(ln,{step:`when`,title:f(`automation.automationEditor.when`,`When`),trace:C===null?null:C.when,children:o(_a,{recipe:h,devices:O,run:T,onChange:g})}),o(ln,{step:`then`,title:f(`automation.automationEditor.then`,`Then`),trace:C===null?null:C.thenBlock,hint:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(Cn,{actions:h.actions,devices:O,variables:w,stepTones:C===null?void 0:h.actions.map((e,t)=>un(C,t)??`idle`),stepResults:D===null?void 0:h.actions.map((e,t)=>D.find(e=>e.index===t)),onChange:e=>g(hn(h,e))})}),o(ln,{step:`mode`,title:f(`flow.runMode.title`,`Overlap`),trace:null,hint:f(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:o(Br,{value:Ir(h),onChange:e=>g(Lr(h,e))})}),o(Mr,{code:M.code,error:M.error,canEject:t!==null,ejecting:s,onEject:u}),k!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:k}),k===null&&j!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:j}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{onClick:()=>{M.code!==null&&l({name:p.trim(),code:M.code,enabled:t?.enabled??!0,placement:Ea})},disabled:i||P,children:[i&&o(E,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(J,{variant:`ghost`,onClick:()=>v(!_),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,"aria-expanded":_,children:[o(A,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,o(At,{expanded:_})]}),o(J,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),N&&o(G,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:me(t.id)},components:{code:o(`code`,{})}})}),o(Ht,{addonId:me(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(mn,{traces:t===null?[]:x.data?.traces,selectedId:y,onSelect:b})})]})}function ka(e){let t=R.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Y.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Aa(e,t){let n=Ur(t);if(!n.ok)return{code:null,error:n.error};try{return{code:z({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function ja(e){if(!e.enabled)return{tone:`idle`,label:Y.t(`helpers.coreBlockStatus.disabled`),detail:Y.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Y.t(`helpers.coreBlockStatus.running`),detail:Y.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Ma(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Na(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Pa(e){let t=e=>{let t=ja(e).tone;return t===`error`?0:t===`pending`?1:t===`ok`?2:3};return[...e].sort((e,n)=>t(e)-t(n)||e.name.localeCompare(n.name))}function Fa(e){if(e.length===0)return Y.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>ja(e).tone===`error`).length,n=e.filter(e=>ja(e).tone===`ok`).length,r=[Y.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Y.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Y.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var Ia=3e4;function La({block:t,logsOpen:n,unreadable:r}){let i=j(),{t:a}=X(),s=ja(t),c=Lt(t.updatedAt,i);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(G,{variant:Ma(s.tone),children:s.label}),c!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.edited`,{when:c})})]}),(s.tone===`error`||s.tone===`pending`)&&o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:s.detail}),r!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:a(`automation.editor.listUnreadable`,{reason:r})}),n&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:me(t.id)},components:{code:o(`code`,{})}})}),o(Ht,{addonId:me(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var Ra=2;function za(e){let t=[];if(M(e.when,e=>{de(e)&&t.push(pn(e.kind))}),t.length===0)return te(e.when)===0?``:Y.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,Ra).join(`, `),i=n.length-Ra;return i>0?`${r} +${i}`:r}function Ba({recipe:e}){let{t}=X();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=za(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function Va({blockId:t}){let{t:n}=X(),r=Ft({blockId:t},{refetchInterval:Ia});if(r.data===void 0)return r.error===null||r.error===void 0?o(tt,{className:`h-4 w-16`}):o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.lastRunUnknown`,`Unknown`)});let i=r.data.traces.findLast(e=>!e.outcome.startsWith(`skipped-`));if(i===void 0)return o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.neverRan`,`Never ran`)});let a=i.outcome===`failed`||i.outcome===`aborted`;return e(`span`,{className:`inline-flex items-center gap-2`,children:[nn(i.lastAt),a&&o(G,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function Ha({block:e,disabled:t,onToggle:n}){let{t:r}=X();return o(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(_t,{checked:e.enabled,disabled:t,onCheckedChange:n,"aria-label":e.enabled?r(`automation.automationList.disableNamed`,`Disable {{name}}`,{name:e.name}):r(`automation.automationList.enableNamed`,`Enable {{name}}`,{name:e.name})})})}function Ua({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=X();return o(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(Qe,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:T,disabled:e!==null,description:e===null?void 0:i(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),onClick:t},{id:`run`,label:i(`automation.automationList.runActions`,`Run actions`),icon:w,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:A,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:_,danger:!0,separatorBefore:!0,onClick:r}]})})}function Wa({onCreate:t}){let{t:n}=X();return o(ht,{icon:x,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(J,{onClick:t,"data-testid":`automation-empty-new`,children:[o(S,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();var Ga=[`coreBlocks`,`list`],Ka=5e3;function qa(e){return e instanceof Error?e.message:String(e)}function Ja({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:a}=X(),u=O(),{state:d,openNew:p,openEdit:m,close:h}=ot({editKey:`block`,newKey:`new`}),g=D(),[_,v]=c(null),y=d.mode!==`closed`;s(()=>{n&&(p(),i?.())},[n,i,p]);let b=l({queryKey:Ga,refetchInterval:Ka,queryFn:async()=>(await u.trpcClient.coreBlocks.list.query({})).blocks}),S=()=>{b.refetch()},C=e=>{h(),S(),$t({title:a(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},w=f({mutationFn:e=>u.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>C(e.block)}),T=f({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>C(e.block)}),E=f({mutationFn:e=>u.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:S}),k=f({mutationFn:e=>u.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:S}),A=f({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:Yn(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{h(),S(),t(e.block.id)}}),j=b.data,M=Pa((j??[]).filter(e=>Kn(e.code))),N=j!==void 0&&M.length===0,P=d.mode===`edit`?M.find(e=>e.id===d.id)??null:null,F=d.mode===`edit`&&j!==void 0&&P===null;s(()=>{F&&h()},[F,h]);let I=P===null?null:Jn(P.code),L=w.error===null?T.error===null?A.error===null?null:qa(A.error):qa(T.error):qa(w.error),R=r(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=Jn(e.code);return o(La,{block:e,logsOpen:_===e.id,unreadable:t.ok?null:t.reason})},sortValue:e=>e.name},{key:`trigger`,header:a(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=Jn(e.code);return o(Ba,{recipe:t.ok?t.recipe:null})},notSortableReason:a(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:a(`build.automationsTab.lastRun`,`Last run`),render:e=>o(Va,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>o(Ha,{block:e,disabled:k.isPending,onToggle:t=>k.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=Jn(e.code);return o(Ua,{unreadable:t.ok?null:t.reason,onEdit:()=>m(e.id),onToggleLogs:()=>v(_===e.id?null:e.id),onDelete:()=>{g({title:a(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:a(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&E.mutate(e.id)})}})}}],[g,_,m,E,k,a]);return y?d.mode===`edit`&&P===null?o(tt,{className:`h-24 w-full`}):e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[o(x,{className:`h-4 w-4 text-foreground-muted`}),P===null?a(`build.automationsTab.newAutomation`,`New automation`):a(`build.automationsTab.edit`,`Edit {{name}}`,{name:P.name})]}),o(Oa,{existing:P,initialRecipe:I!==null&&I.ok?I.recipe:vn,saving:w.isPending||T.isPending,saveError:L,ejecting:A.isPending,onSave:e=>{P===null?w.mutate(e):T.mutate({blockId:P.id,block:e})},onEject:()=>{P!==null&&A.mutate(P)},onCancel:()=>{w.reset(),T.reset(),A.reset(),h()}},P?.id??`new`),E.error!=null&&o(K,{message:qa(E.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:j===void 0?``:Fa(M)}),b.error!=null&&o(K,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:qa(b.error),onRetry:S}),N?o(Wa,{onCreate:p}):o(Ut,{columns:R,rows:M,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Pe,emptyMessage:j===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>m(e.id)}),E.error!=null&&o(K,{message:qa(E.error)}),k.error!=null&&o(K,{message:qa(k.error)})]})}var Ya={kind:`all`,children:[]};function Xa({value:t,devices:n,label:r,onChange:i}){let{t:a}=X(),s=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[o(_t,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?Ya:void 0)}),s!==null&&e(p,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.activeWhen.hint`,`Only states count here, such as "someone is home". While they are false, nothing runs and holds pause.`)}),o(_a,{recipe:s,devices:n,onChange:e=>i(e.when)})]})]})}var Za=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],Qa=720,$a=1440;function eo(){return{name:``,enabled:!0,priority:0,maxLateMs:ie,profiles:[to(`profile-1`,`Every day`)]}}function to(e,t){return{id:e,name:t,enabled:!0,days:[...Za],points:[]}}function no(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function ro(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function io(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function ao(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,hourCycle:`h23`,hour:`2-digit`,minute:`2-digit`}).formatToParts(new Date(e)),r=e=>Number(n.find(t=>t.type===e)?.value??0);return r(`hour`)*60+r(`minute`)}function oo(e,t=Date.now()){return pe(t,e.timeZone)}function so(e,t,n){let r=io(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=ue(e,n,r);return i===null?null:ao(i,t.timeZone)}function co(e,t,n){return e.kind===`sun`?so({...e,offsetMin:0},t,n):null}function lo(e,t,n){if(e.kind===`clock`)return{kind:`clock`,hh:Math.floor(t/60),mm:t%60};if(e.kind===`sun`&&n!==null){let r=Math.max(-720,Math.min(Qa,t-n));return{...e,offsetMin:r}}return e}function uo(e){let t=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(e);return t===null?null:{kind:`clock`,hh:Number(t[1]),mm:Number(t[2])}}function fo(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function po(e){return fo(Math.floor(e/60),e%60)}function mo(e,t,n){let r=e.flatMap(e=>{let r=so(e.at,t,n);return r===null?[]:[{point:e,minute:r}]}).toSorted((e,t)=>e.minute-t.minute);return r.flatMap((e,t)=>{if(e.point.mode!==`hold`)return[];let n=r[t+1];return[{id:e.point.id,fromMinute:e.minute,toMinute:n===void 0?$a:n.minute}]})}function ho(e,t){let n=se.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=I(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}var go=[`sunrise`,`sunset`,`dawn`,`dusk`],_o=6e4;function vo(e){return e.kind===`cap`||e.kind===`wait`}function yo(e,t){let n={id:e.id,at:e.at,mode:t,steps:t===`release`?[]:e.steps,...e.conditions===void 0?{}:{conditions:e.conditions}};return t===`hold`?{...n,...e.override===void 0?{}:{override:e.override},...e.maxHoldAttempts===void 0?{}:{maxHoldAttempts:e.maxHoldAttempts}}:n}function bo({point:t,devices:n,site:r,localDate:i,issues:a,onChange:s,onRemove:c}){let{t:l}=X(),u=t.at,d=u.kind===`sun`?so(u,r,i):null,f=co(u,r,i),m=t.override??{mode:`respect`},h=e=>s({...t,at:e});return e(`div`,{className:`space-y-3`,"data-testid":`point-editor`,children:[e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.kind`,`Point type`)}),o(k,{"aria-label":l(`schedulers.point.kind`,`Point type`),value:t.mode,options:[{value:`edge`,label:l(`schedulers.point.edge`,`Edge: run once`)},{value:`hold`,label:l(`schedulers.point.hold`,`Hold: keep true`)},{value:`release`,label:l(`schedulers.point.release`,`Release: end the hold`)}],onChange:e=>{let n=e.target.value;(n===`edge`||n===`hold`||n===`release`)&&s(yo(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.when`,`When`)}),o(k,{"aria-label":l(`schedulers.point.when`,`When`),value:u.kind===`sun`?`sun`:`clock`,options:[{value:`clock`,label:l(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:l(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{e.target.value===`sun`?h({kind:`sun`,event:`sunset`,offsetMin:0}):h({kind:`clock`,hh:12,mm:0})}})]}),u.kind===`clock`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.time`,`Time`)}),o(q,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:fo(u.hh,u.mm),onChange:e=>{let t=uo(e.target.value);t!==null&&h(t)}})]}),u.kind===`sun`&&e(p,{children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.sunEvent`,`Sun event`)}),o(k,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:go.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=go.find(t=>t===e.target.value);t!==void 0&&h({...u,event:t})}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.offset`,`Offset (minutes, negative = before)`)}),o(sn,{"aria-label":l(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-28`,value:u.offsetMin,onValue:e=>{e!==null&&h({...u,offsetMin:Math.round(e)})}})]}),o(`p`,{className:`pb-2 text-xs text-foreground-muted`,"data-testid":`sun-computed`,children:d===null||f===null?l(`schedulers.point.sunUnknown`,`No time today: the site location is not set.`):l(`schedulers.point.sunComputed`,`Today at {{time}} ({{zone}})`,{time:po(d),zone:r.timeZone})})]}),e(J,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[o(_,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&o(Cn,{actions:t.steps,devices:n,allowedKinds:[`cap`,`wait`],onChange:e=>s({...t,steps:e.filter(vo)})}),t.mode===`release`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:l(`schedulers.point.releaseHint`,`A release ends the running hold without doing anything to the devices.`)}),t.mode===`hold`&&e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.override`,`If someone changes it by hand`)}),o(k,{"aria-label":l(`schedulers.point.override`,`If someone changes it by hand`),value:m.mode,options:[{value:`respect`,label:l(`schedulers.point.respect`,`Leave it alone`)},{value:`reassert`,label:l(`schedulers.point.reassert`,`Put the hold back after a while`)}],onChange:e=>s({...t,override:e.target.value===`reassert`?{mode:`reassert`,graceMs:10*_o}:{mode:`respect`}})})]}),m.mode===`reassert`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.grace`,`Wait (minutes)`)}),o(sn,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:m.graceMs/_o,onValue:e=>{e!==null&&s({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*_o))}})}})]})]}),a.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:a.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))})]})}u();var xo=5e3,So=600,Co=6e4,wo={timeZone:`UTC`,location:null};function To(e){return e instanceof Error?e.message:String(e)}function Eo(e){if(e===null)return eo();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function Do(e,t){let[n,r]=c(e);return s(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Oo(e,t){return t(`schedulers.day.${e}`,e)}function ko({entry:t,onClose:n,onSaved:i}){let{t:a}=X(),s=d(),l=D(),u=wn(),f=vt(),p=f.data??wo,[m,h]=c(()=>Eo(t)),[g,v]=c(()=>m.profiles[0]?.id??``),[y,b]=c(null),[x,C]=c(null),w=()=>{s.invalidateQueries({queryKey:[[`schedulers`]]})},T=Ie({onSuccess:e=>{w(),i(e.scheduler.id)}}),O=Ge({onSuccess:w}),k=dt({onSuccess:()=>{w(),n()}}),A=st({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:xo}),j=r(()=>ho(m,p),[m,p]),M=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),N=Do(j.ok?j.input:null,So),P=Gt(N===null?{scheduler:m}:t===null?{scheduler:N}:{scheduler:N,schedulerId:t.id},{enabled:N!==null&&M&&f.data!==void 0}),F=m.profiles.find(e=>e.id===g)??m.profiles[0],I=F===void 0?-1:m.profiles.indexOf(F),L=oo(p),R=F?.points.find(e=>e.id===y)??null,z=F===void 0||R===null?-1:F.points.indexOf(R),B=j.ok?[]:j.issues,V=e=>B.filter(t=>t.path===e||t.path.startsWith(`${e}.`)),ee=e=>h({...m,profiles:m.profiles.map((t,n)=>n===I?e:t)}),H=e=>{F!==void 0&&ee({...F,points:F.points.map(t=>t.id===e.id?e:t)})},te=r(()=>F===void 0?[]:F.points.flatMap(e=>{let t=so(e.at,p,L);if(t===null)return[];let n=e.at.kind===`sun`?`${a(`schedulers.sun.${e.at.event}`,e.at.event)} ${e.at.offsetMin>=0?`+`:``}${String(e.at.offsetMin)} (${po(t)})`:fo(e.at.hh,e.at.mm);return[{id:e.id,minute:t,label:n,tone:e.mode===`hold`?`success`:e.mode===`release`?`neutral`:`primary`,draggable:e.at.kind===`clock`||e.at.kind===`sun`&&co(e.at,p,L)!==null}]}),[F,p,L,a]),ne=r(()=>F===void 0?[]:mo(F.points,p,L),[F,p,L]),re=(e,t)=>{let n=F?.points.find(t=>t.id===e);n!==void 0&&H({...n,at:lo(n.at,t,co(n.at,p,L))})},ie=e=>{if(F===void 0)return;let t=ro(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));ee({...F,points:[...F.points,no(e,t,720)]}),b(t)},ae=()=>{let e=ro(`profile`,m.profiles.map(e=>e.id));h({...m,profiles:[...m.profiles,to(e,a(`schedulers.profile.newName`,`New profile`))]}),v(e),b(null)},oe=T.isPending||O.isPending,se=T.error??O.error??k.error;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`scheduler-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(Ee,{className:`h-4 w-4 text-foreground-muted`}),o(q,{"aria-label":a(`schedulers.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,placeholder:a(`schedulers.editor.namePlaceholder`,`What this scheduler does`),onChange:e=>h({...m,name:e.target.value})})]}),e(qe,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[o(rt,{label:a(`schedulers.editor.enabled`,`Enabled`),children:o(_t,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>h({...m,enabled:e})})}),o(rt,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:o(sn,{"aria-label":a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),className:`w-24`,value:m.priority,onValue:e=>{e!==null&&h({...m,priority:Math.round(e)})}})}),o(rt,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:o(sn,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/Co,onValue:e=>{e!==null&&h({...m,maxLateMs:Math.round(e*Co)})}})})]}),e(`div`,{className:`p-3`,children:[o(Xa,{value:m.activeWhen,devices:u,label:a(`schedulers.editor.activeWhen`,`Only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=m;h(e===void 0?n:{...n,activeWhen:e})}}),V(`activeWhen`).map(e=>o(`p`,{className:`mt-1 text-xs text-warning`,children:e.message},e.message))]})]}),o(qe,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(J,{variant:`outline`,size:`sm`,onClick:ae,children:[o(S,{className:`h-4 w-4`}),` `,a(`schedulers.profile.add`,`Add profile`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.profile.hint`,`Each day, the first profile in this order whose days and condition hold is the one that runs.`)}),F!==void 0&&e(zt,{value:F.id,onValueChange:e=>{v(e),b(null)},appearance:`pills`,children:[o(It,{children:m.profiles.map(e=>o(Et,{value:e.id,children:e.name},e.id))}),e(jt,{value:F.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(q,{"aria-label":a(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:F.name,onChange:e=>ee({...F,name:e.target.value})}),o(_t,{checked:F.enabled,label:a(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>ee({...F,enabled:e})}),m.profiles.length>1&&e(J,{variant:`ghost`,size:`sm`,onClick:()=>{h({...m,profiles:m.profiles.filter(e=>e.id!==F.id)}),v(``),b(null)},children:[o(_,{className:`h-4 w-4`}),` `,a(`schedulers.profile.remove`,`Remove profile`)]})]}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":a(`schedulers.profile.days`,`Days`),children:Za.map(e=>{let t=F.days.includes(e);return o(J,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>ee({...F,days:t?F.days.filter(t=>t!==e):Za.filter(t=>t===e||F.days.includes(t))}),children:Oo(e,a)},e)})}),V(`profiles.${String(I)}.days`).map(e=>o(`p`,{className:`text-xs text-warning`,children:a(`schedulers.profile.daysNeeded`,`Pick at least one day.`)},e.message)),o(Xa,{value:F.activeWhen,devices:u,label:a(`schedulers.profile.activeWhen`,`This profile only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=F;ee(e===void 0?n:{...n,activeWhen:e})}}),o(Vt,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:te,bands:ne,selectedId:y,onSelect:b,onMove:re}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:`outline`,size:`sm`,onClick:()=>ie(`edge`),children:[o(S,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(J,{variant:`outline`,size:`sm`,onClick:()=>ie(`hold`),children:[o(S,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(J,{variant:`outline`,size:`sm`,onClick:()=>ie(`release`),children:[o(S,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),o(G,{variant:`neutral`,children:p.timeZone})]}),F.points.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.timeline.empty`,`Add a point to place something on the day.`)}),R!==null&&o(bo,{point:R,devices:u,site:p,localDate:L,issues:V(`profiles.${String(I)}.points.${String(z)}`),onChange:H,onRemove:()=>{ee({...F,points:F.points.filter(e=>e.id!==R.id)}),b(null)}},R.id)]})]})]})}),P.data!==void 0&&P.data.conflicts.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:P.data.conflicts.map(e=>o(`li`,{children:a(`schedulers.conflict.message`,`{{other}} wants device {{device}} in another state from {{from}} to {{to}} ({{winner}}).`,{other:e.other.schedulerName,device:e.deviceId,from:po(e.fromMinute),to:po(e.toMinute),winner:e.winner===`mine`?a(`schedulers.conflict.mine`,`this one wins`):e.winner===`other`?a(`schedulers.conflict.other`,`the other one wins`):a(`schedulers.conflict.tie`,`the one that started first wins`)})},`${e.other.schedulerId}:${e.other.pointId}:${e.mine.pointId}:${String(e.deviceId)}`))}),!j.ok&&m.name!==``&&B.length>0&&R===null&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:B.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))}),se!==null&&o(K,{message:To(se)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(J,{onClick:()=>{j.ok&&(t===null?T.mutate({scheduler:j.input}):O.mutate({schedulerId:t.id,scheduler:j.input}))},disabled:oe||!j.ok||f.data===void 0,children:[oe&&o(E,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(J,{variant:`ghost`,disabled:k.isPending,onClick:()=>{l({title:a(`schedulers.editor.deleteTitle`,`Delete this scheduler?`),message:a(`schedulers.editor.deleteMessage`,`{{name}} will be deleted and any hold it keeps will stop.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&k.mutate({schedulerId:t.id})})},children:[o(_,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(J,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(mn,{traces:t===null?[]:A.data?.traces,selectedId:x,onSelect:C})})]})}u();var Ao=5e3;function jo(e){return e instanceof Error?e.message:String(e)}function Mo({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=X(),a=d(),{state:c,openNew:l,openEdit:u,close:f}=ot({editKey:`scheduler`,newKey:`new`}),p=mt({},{refetchInterval:Ao}),m=He({},{refetchInterval:Ao}),h=Be({onSuccess:()=>void a.invalidateQueries({queryKey:[[`schedulers`]]})});s(()=>{t&&(l(),n?.())},[t,n,l]);let g=p.data??[],_=c.mode===`edit`?g.find(e=>e.id===c.id)??null:null,v=e=>{if(!e.enabled)return{variant:`neutral`,label:i(`schedulers.status.off`,`Off`)};let t=m.data?.find(t=>t.schedulerId===e.id);return t===void 0?{variant:`neutral`,label:`-`}:t.hold===null?{variant:`neutral`,label:i(`schedulers.status.idle`,`Idle`)}:t.hold.suspendedInactive?{variant:`warning`,label:i(`schedulers.status.paused`,`Paused`)}:t.hold.targets.some(e=>e.status===`gave-up`)?{variant:`danger`,label:i(`schedulers.status.gaveUp`,`Gave up`)}:{variant:`success`,label:i(`schedulers.status.holding`,`Holding`)}},y=r(()=>[{key:`name`,header:i(`schedulers.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`enabled`,header:i(`schedulers.list.enabled`,`Enabled`),render:e=>o(`span`,{onClick:e=>e.stopPropagation(),children:o(_t,{checked:e.enabled,disabled:h.isPending,"aria-label":i(`schedulers.list.enabledAria`,`Enable {{name}}`,{name:e.name}),onCheckedChange:t=>h.mutate({schedulerId:e.id,enabled:t})})}),sortValue:e=>Number(e.enabled)},{key:`profiles`,header:i(`schedulers.list.profiles`,`Profiles`),render:e=>String(e.profiles.length),sortValue:e=>e.profiles.length},{key:`priority`,header:i(`schedulers.list.priority`,`Priority`),render:e=>String(e.priority),sortValue:e=>e.priority},{key:`status`,header:i(`schedulers.list.status`,`Now`),render:e=>{let t=v(e);return o(G,{variant:t.variant,children:t.label})},notSortableReason:i(`schedulers.list.statusNotSortable`,`Derived from the live hold`)},{key:`updated`,header:i(`schedulers.list.updated`,`Updated`),render:e=>nn(e.updatedAt),sortValue:e=>e.updatedAt}],[h,m.data,i]);return c.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`schedulers.list.hint`,`A scheduler does things over the day: run something at a time or at sunset, or keep a device in a state for a stretch of time.`)}),h.error!=null&&o(K,{message:jo(h.error)}),p.data===void 0?p.error==null?o(tt,{className:`h-24 w-full`}):o(K,{title:i(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:jo(p.error),onRetry:()=>void p.refetch()}):g.length===0?o(ht,{icon:Ee,title:i(`schedulers.list.emptyTitle`,`No schedulers yet`),description:i(`schedulers.list.emptyDescription`,`A scheduler turns the garden lights on at sunset and off at 23:00, every day or only on some days.`),action:e(J,{onClick:l,children:[o(S,{className:`h-4 w-4`}),` `,i(`schedulers.list.new`,`New scheduler`)]})}):o(Ut,{columns:y,rows:g,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Pe,emptyMessage:i(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):o(ko,{entry:_,onClose:f,onSaved:u},_?.id??`new`)}async function No(e,t){let n=`${ye}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var Po=10,Fo=400;async function Io(e,t,n=Fo){for(let r=0;r<Po;r+=1){let r=await No(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var Lo=`media-player`;function Ro(e){return e===H.MediaPlayer?`media-source`:e===H.Heater?`control-source`:`none`}function zo(e){return e===H.Heater?ve():e===H.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[H.MediaPlayer],accept:[{cap:Lo,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[Lo],exclude:[]}:null}function Bo(e,t){return e!==H.Heater||t!==null&&t.cap===`switch`}var Vo={kind:`expression`,expr:`now`,bindings:{}};function Ho(e){return{kind:`fields`,cap:`switch`,fields:{on:{kind:`from`,source:e.source,cap:e.cap,fieldPath:e.fieldPath},lastChangedAt:Vo},commands:{setState:{kind:`forward`,source:e.source,cap:`switch`,method:`setState`}}}}function Uo(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:Lo,fields:{},commands:Object.fromEntries(Object.keys(B()).map(t=>[t,{kind:`forward`,source:e.source,cap:Lo,method:t}]))}]}function Wo(e,t){if(!Bo(e,t))return null;let n=e===H.Heater&&t!==null?[Ho(t)]:e===H.MediaPlayer?Uo(t):[];return{target:{kind:`new`,type:e},features:n}}u();function Go({onTitle:t}){let{t:n}=X(),r=j(),i=Yt(),a=Tn(),l=kt(),u=et({addonId:`composer`}),[d,f]=c(H.Sensor),[p,m]=c(``),[h,g]=c([]),[_,v]=c(null),y=h[0]??null,b=zo(d),x=Wo(d,y);s(()=>{t(n(`helper.newDevice`))},[t,n]);let S=async()=>{if(x!==null){v(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:x}}),r=await Io(t.id,async()=>(await u.refetch()).data??u.data);if(r===null){v(n(`helper.devicePending`));return}e!==``&&await l.mutateAsync({deviceId:r,name:e}),i(Qt(r),{replace:!0})}catch(e){v(e instanceof Error?e.message:String(e))}}};return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`device-create-form`,children:[e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.targetType`),o(k,{value:d,onChange:e=>{let t=Object.values(H).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(H).map(e=>({value:e,label:Dt(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(q,{"aria-label":n(`compositionEditor.name`),value:p,onChange:e=>m(e.target.value)})]})]}),b!==null&&e(`div`,{className:`flex flex-col gap-1`,"data-testid":`device-create-source`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:n(`helper.deviceSource.${Ro(d)}`)}),o(Nn,{kind:`members`,request:b,enabled:!0,members:h,onMembersChange:g,onRefuse:()=>void 0})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(J,{disabled:!Bo(d,y)||a.isPending,onClick:()=>void S(),children:n(`compositionEditor.save`)})]})}u();function Ko({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=X(),u=zn(!0),[d,f]=c({}),[p,m]=c(s(t.nameKey)),[h,g]=c(null),[_,v]=c([]),[y,b]=c(!1),x=r(()=>u.kind===`known`?new Map(u.value.map(e=>[W({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[W(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:jn(u.value,S)}:u,[u,S]),w=Vn(t,d),T=u.kind===`known`?Hn(u.value,w,!1):null,E=t.build(d),D=In(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(W(e))??e.stableId;return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`preset-wizard`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:s(t.descriptionKey)}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[s(`preset.name`),o(q,{"aria-label":s(`preset.name`),value:p,onChange:e=>m(e.target.value)})]}),o(`ul`,{className:`flex flex-col gap-2`,"aria-label":s(`preset.slots`),children:t.slots.map(t=>{let n=d[t.key];return e(`li`,{className:`grid grid-cols-1 gap-1 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center`,"data-testid":`preset-slot-${t.key}`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`text-xs text-foreground`,children:[s(t.labelKey),t.optionalGroup===void 0?` *`:``]}),e(`div`,{className:`text-[11px] text-foreground-muted break-words`,children:[Ln(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(J,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(J,{variant:`ghost`,size:`sm`,onClick:()=>O(t.key,void 0),children:s(`preset.clear`)})]})]},t.key)})}),E===null&&D.length>0&&o(`p`,{className:`text-[11px] text-foreground-muted`,"data-testid":`preset-missing`,children:s(`preset.missing`,{slots:D.map(e=>s(e.labelKey)).join(`, `)})}),E!==null&&e(`section`,{className:`flex flex-col gap-1`,"data-testid":`preset-preview`,children:[o(`h3`,{className:`text-xs font-medium text-foreground`,children:s(`preset.preview`)}),o(`ul`,{className:`flex flex-col gap-1 text-[11px] text-foreground-muted`,children:E.features.map(e=>e.kind===`fields`?o(`li`,{children:s(`preset.previewFeature`,{cap:Ln(e.cap,l.language),fields:Object.keys(e.fields).length,commands:Object.keys(e.commands??{}).length+Object.values(e.items??{}).filter(e=>e.reset!==void 0).length})},e.cap):null)})]}),o(Bn,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(J,{disabled:E===null||n||y,onClick:()=>{E===null||y||(b(!0),i(E,p.trim()).then(e=>{e.kind===`refused`&&v(e.lines)}).finally(()=>b(!1)))},"data-testid":`preset-create`,children:s(`preset.create`)}),o(J,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o(Pn,{open:h!==null,title:h===null?``:s(`preset.pickTitle`,{slot:s(h.labelKey)}),selection:`single`,candidates:C,room:T,confirmLabel:()=>s(`preset.pickConfirm`),onConfirm:e=>{let t=e[0],n=h;g(null),t!==void 0&&n!==null&&O(n.key,t.ref)},onClose:()=>g(null)})]})}u();var qo=`preset`;function Jo({mode:e,onTitle:t}){return o(e===`helper`?Yo:Go,{onTitle:t})}function Yo({onTitle:e}){let{t}=X(),r=Yt(),i=Tn(),a=kt(),l=et({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=Kt(),g=Mn(m.get(qo)),_=g===null?Xo(u,t):t(g.labelKey);s(()=>{f||e(_)},[e,_,f]);let v=e=>h(t=>{let n=new URLSearchParams(t);return e===null?n.delete(qo):n.set(qo,e),n},{replace:!0}),y=async(e,n)=>{try{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:e}}),s=await Io(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:Fn(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(Qt(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:Fn(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(Go,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Rn,{fillHeight:!0,onDevice:()=>p(!0),onPreset:v,purpose:`create`,initial:null,start:`template`,saving:i.isPending,onDraftChange:d,onSave:async(e,n)=>{let o=null,s=await Un(e,async(s,c)=>{let u=b.current,d;if(u!==null&&u.draft===e)d=u.blockId;else{let{block:t}=await i.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:s}});d=t.id,b.current={draft:e,blockId:d}}let f=await Io(d,async()=>(await l.refetch()).data??l.data);if(f===null)throw Error(t(`helper.devicePending`));o=f,b.current=null,c!==``&&await a.mutateAsync({deviceId:f,name:c}),n===`open`&&r(Zt(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:Zo(s,t)}:{kind:`saved`,deviceId:c}}})}):o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Ko,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function Xo(e,t){if(e===null)return t(`helper.newComposed`);if(e.kind===`statistic`)return t(`helper.newTitle.statistic`);if(e.kind===`integral`)return t(`helper.newTitle.integral`);if(e.kind===`arithmetic`)return t(`helper.newTitle.${e.op}`);if(e.kind===`threshold`||e.kind===`expression`||e.kind===`derivative`)return t(`helper.newTitle.${e.kind}`);let n=ae(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function Zo(e,t){return e.length>0?e:Fn(t(`helper.devicePending`))}function Qo(e){let t=e.helper;if(t===void 0)return{section:`advanced`,kind:null};switch(t.kind){case`group`:return{section:`group`,kind:t.templateId};case`arithmetic`:return{section:`calculation`,kind:t.op};case`expression`:return{section:`advanced`,kind:`expression`};default:return{section:`calculation`,kind:t.kind}}}function $o(e){return{state:`answered`,byRef:new Map(e.map(e=>[W(e),e]))}}function es(e,t){if(e.state!==`unanswered`)return e.byRef.get(W(t))??null}function ts(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function ns(e){return F(e).map(e=>e.source)}function rs(e){let t=e.block.source?.kind===`composition`?e.block.source.composition:null;if(t===null)return[];let n=[];for(let e of t.features){if(e.kind===`passthrough`){n.push(e.source);continue}for(let t of Object.values(e.fields))n.push(...ns(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...ns(e))}let r=new Set;return n.filter(e=>{let t=W(e);return r.has(t)?!1:(r.add(t),!0)})}function is(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:Y.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Y.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Y.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Y.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function as(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return is(e);case`degraded`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.degraded`),reason:n??Y.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Y.t(`helpers.compositionRows.failed`),reason:n??Y.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Y.t(`helpers.compositionRows.notRunning`),reason:n??Y.t(`helpers.compositionRows.notRunningReason`)}}}function os(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Y.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Y.t(`helpers.compositionRows.unknown`),reason:Y.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return as(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.notReported`),reason:Y.t(`helpers.compositionRows.noRecord`,{stored:r})}}function ss(e){return W(e)}function cs(e,t){let n=es(t,e);return{key:W(e),label:n?n.name:ss(e),presence:ts(n),deviceId:n?n.id:null}}function ls(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function us(e,t){let n=e.block.source?.kind===`composition`?e.block.source.composition:null;if(n===null)return null;let r=n.target,i=r.kind===`existing`?r.device:le(e.block.id),a=W(i),o=rs(e).filter(e=>W(e)!==a).map(e=>cs(e,t)),s=n.features.map(e=>e.enabled===!1?Y.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=es(t,i),l=ls(e),u=os(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,origin:Qo(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=ts(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:ss(r.device),namePresence:d,type:c?c.type:null,origin:Qo(n),features:s,state:u,sources:o,reportedDeviceId:l}}function ds(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function fs(e,t){return ds(e)-ds(t)||e.name.localeCompare(t.name)}function ps(e,t){let n=e.flatMap(e=>{let n=us(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(fs),customizations:n.filter(e=>e.kind===`customization`).toSorted(fs)}}u();var ms=1e4;function hs(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function gs(){let e=Jt();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Y.t(`build.customDeviceTab.deviceListPending`):Y.t(`build.customDeviceTab.deviceListUnreadable`,{error:hs(e.error)})}:$o(e.data)}function _s(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function vs({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=X(),[i,a]=Kt(),s=gt({},{refetchInterval:ms}),l=gs(),u=ot({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?_s(i.get(`new`),t):null,m=f!==null,[h,g]=c(``),_=D(),v=$e(),y=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},b=s.data;return e(p,{children:[bs(b,s.error,()=>void s.refetch(),l,{onEditComposed:e=>u.openEdit(e),deleting:v.isPending,onDelete:e=>{_({title:r(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`),message:r(`build.customDeviceTab.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:r(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&v.mutate({blockId:e.blockId},{onSuccess:()=>void s.refetch()})})}}),o(Le,{open:m,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:Te,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(Jo,{mode:f,onTitle:g},f)}),o(bn,{blockId:d,onClose:y}),v.error!=null&&o(K,{message:hs(v.error)})]})}function ys(t){return o(pt,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Y.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Y.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function bs(e,t,n,r,i){if(t!=null&&e===void 0)return o(K,{title:Y.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:hs(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Y.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return ys(e.reason);let a=t==null?null:hs(t);return o(xs,{lists:ps(e.views,r),fleet:r,refreshError:a,handlers:i})}function xs({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=X();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(Ss,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,handlers:i}),o(Ss,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,handlers:i})]})}function Ss({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=X();return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(Ut,{columns:Cs(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:Pe,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Cs(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(Ts,{row:e})},{key:`type`,header:Y.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Y.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:Y.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>ws(e.origin,i),render:e=>o(G,{variant:`default`,"data-testid":`composed-origin-badge`,children:ws(e.origin,i)})}]:[],{key:`state`,header:Y.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(G,{variant:Ma(t.state.tone),children:t.state.label}),t.state.reason!==null&&o(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:Y.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(Ds,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[o(J,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(J,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:o(_,{className:`h-4 w-4`})})]})}),a}function ws(e,t){let n=e.kind===null?null:t(`helper.template.${e.kind}`);return e.section===`group`?t(`helper.badge.group`,{kind:n}):e.section===`calculation`?t(`helper.badge.calculation`,{kind:n}):n===null?t(`helper.badge.advanced`):t(`helper.badge.advancedKind`,{kind:n})}function Ts({row:t}){let{t:n}=X();return e(`div`,{className:`space-y-0.5`,children:[o(Es,{row:t}),t.namePresence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),o(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function Es({row:e}){let{t}=X(),n=Mt(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):o(qt,{to:e.kind===`composed`?Zt(e.reportedDeviceId):Qt(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Ds({sources:t}){let{t:n}=X();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(qt,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function Os(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ks(e){if(Array.isArray(e))return e}function As(e,t,n){return(t=zs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function js(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Ms(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
4
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ns(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ps(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Ns(Object(n),!0).forEach(function(t){As(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ns(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Fs(e,t){if(e==null)return{};var n,r,i=Is(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Is(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Ls(e,t){return ks(e)||js(e,t)||Bs(e,t)||Ms()}function Rs(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function zs(e){var t=Rs(e,`string`);return typeof t==`symbol`?t:t+``}function Bs(e,t){if(e){if(typeof e==`string`)return Os(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Os(e,t):void 0}}function Vs(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Hs(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Us(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Hs(Object(n),!0).forEach(function(t){Vs(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Hs(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Ws(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Gs(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function Ks(e){return{}.toString.call(e).includes(`Object`)}function qs(e){return!Object.keys(e).length}function Js(e){return typeof e==`function`}function Ys(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Xs(e,t){return Ks(t)||tc(`changeType`),Object.keys(t).some(function(t){return!Ys(e,t)})&&tc(`changeField`),t}function Zs(e){Js(e)||tc(`selectorType`)}function Qs(e){Js(e)||Ks(e)||tc(`handlerType`),Ks(e)&&Object.values(e).some(function(e){return!Js(e)})&&tc(`handlersType`)}function $s(e){e||tc(`initialIsRequired`),Ks(e)||tc(`initialType`),qs(e)&&tc(`initialContent`)}function ec(e,t){throw Error(e[t]||e.default)}var tc=Gs(ec)({initialIsRequired:`initial state is required`,initialType:`initial state should be an object`,initialContent:`initial state shouldn't be an empty object`,handlerType:`handler should be an object or a function`,handlersType:`all handlers should be a functions`,selectorType:`selector should be a function`,changeType:`provided value of changes should be an object`,changeField:`it seams you want to change a field in the state which is not specified in the "initial" state`,default:"an unknown error accured in `state-local` package"}),nc={changes:Xs,selector:Zs,handler:Qs,initial:$s};function rc(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};nc.initial(e),nc.handler(t);var n={current:e},r=Gs(oc)(n,t),i=Gs(ac)(n),a=Gs(nc.changes)(e),o=Gs(ic)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return nc.selector(e),e(n.current)}function c(e){Ws(r,i,a,o)(e)}return[s,c]}function ic(e,t){return Js(t)?t(e.current):t}function ac(e,t){return e.current=Us(Us({},e.current),t),t}function oc(e,t,n){return Js(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var sc={create:rc},cc={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function lc(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function uc(e){return{}.toString.call(e).includes(`Object`)}function dc(e){return e||hc(`configIsRequired`),uc(e)||hc(`configType`),e.urls?(fc(),{paths:{vs:e.urls.monacoBase}}):e}function fc(){console.warn(mc.deprecation)}function pc(e,t){throw Error(e[t]||e.default)}var mc={configIsRequired:`the configuration object is required`,configType:`the configuration object should be an object`,default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
|
|
5
|
-
You are using deprecated way of configuration.
|
|
6
|
-
|
|
7
|
-
Instead of using
|
|
8
|
-
monaco.config({ urls: { monacoBase: '...' } })
|
|
9
|
-
use
|
|
10
|
-
monaco.config({ paths: { vs: '...' } })
|
|
11
|
-
|
|
12
|
-
For more please check the link https://github.com/suren-atoyan/monaco-loader#config
|
|
13
|
-
`},hc=lc(pc)(mc),gc={config:dc},_c=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function vc(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],vc(e[n],t[n]))}),Ps(Ps({},e),t)}var yc={type:`cancelation`,msg:`operation is manually canceled`};function bc(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(yc):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var xc=[`monaco`],Sc=Ls(sc.create({config:cc,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),Cc=Sc[0],wc=Sc[1];function Tc(e){var t=gc.config(e),n=t.monaco,r=Fs(t,xc);wc(function(e){return{config:vc(e.config,r),monaco:n}})}function Ec(){var e=Cc(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(wc({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),bc(Nc);if(window.monaco&&window.monaco.editor)return jc(window.monaco),e.resolve(window.monaco),bc(Nc);_c(Dc,kc)(Ac)}return bc(Nc)}function Dc(e){return document.body.appendChild(e)}function Oc(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function kc(e){var t=Cc(function(e){return{config:e.config,reject:e.reject}}),n=Oc(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function Ac(){var e=Cc(function(e){return{config:e.config,resolve:e.resolve,reject:e.reject}}),t=window.require;t.config(e.config),t([`vs/editor/editor.main`],function(t){var n=t.m||t;jc(n),e.resolve(n)},function(t){e.reject(t)})}function jc(e){Cc().monaco||wc({monaco:e})}function Mc(){return Cc(function(e){return e.monaco})}var Nc=new Promise(function(e,t){return wc({resolve:e,reject:t})}),Pc={config:Tc,init:Ec,__getMonacoInstance:Mc};u();var Fc={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},Ic={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function Lc({children:e}){return t.createElement(`div`,{style:Ic.container},e)}var Rc=Lc;function zc({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...Fc.wrapper,width:e,height:n},...s},!r&&t.createElement(Rc,null,i),t.createElement(`div`,{ref:a,style:{...Fc.fullWidth,...!r&&Fc.hide},className:o}))}var Bc=i(zc);function Vc(e){s(e,[])}var Hc=Vc;function Uc(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=Uc;function Wc(){}function Gc(e,t,n,r){return Kc(e,r)||qc(e,t,n,r)}function Kc(e,t){return e.editor.getModel(Jc(e,t))}function qc(e,t,n,r){return e.editor.createModel(t,n,r?Jc(e,r):void 0)}function Jc(e,t){return e.Uri.parse(t)}function Yc({original:e,modified:r,language:i,originalLanguage:o,modifiedLanguage:l,originalModelPath:u,modifiedModelPath:d,keepCurrentOriginalModel:f=!1,keepCurrentModifiedModel:p=!1,theme:m=`light`,loading:h=`Loading...`,options:g={},height:_=`100%`,width:v=`100%`,className:y,wrapperProps:b={},beforeMount:x=Wc,onMount:S=Wc}){let[C,w]=c(!1),[T,E]=c(!0),D=n(null),O=n(null),k=n(null),A=n(S),j=n(x),M=n(!1);Hc(()=>{let e=Pc.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?F():e.cancel()}),$(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=Gc(O.current,e||``,o||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=Gc(O.current,r||``,l||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(r||``):r!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:r||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[r],C),$(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||i||`text`),O.current.editor.setModelLanguage(t,l||i||`text`)},[i,o,l],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=a(()=>{if(!O.current)return;j.current(O.current);let t=Gc(O.current,e||``,o||i||`text`,u||``),n=Gc(O.current,r||``,l||i||`text`,d||``);D.current?.setModel({original:t,modified:n})},[i,r,l,e,o,u,d]),P=a(()=>{!M.current&&k.current&&(D.current=O.current.editor.createDiffEditor(k.current,{automaticLayout:!0,...g}),N(),O.current?.editor.setTheme(m),w(!0),M.current=!0)},[g,m,N]);s(()=>{C&&A.current(D.current,O.current)},[C]),s(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return t.createElement(Bc,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(Yc);function Xc(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var Zc=Xc,Qc=new Map;function $c({defaultValue:e,defaultLanguage:r,defaultPath:i,value:o,language:l,path:u,theme:d=`light`,line:f,loading:p=`Loading...`,options:m={},overrideServices:h={},saveViewState:g=!0,keepCurrentModel:_=!1,width:v=`100%`,height:y=`100%`,className:b,wrapperProps:x={},beforeMount:S=Wc,onMount:C=Wc,onChange:w,onValidate:T=Wc}){let[E,D]=c(!1),[O,k]=c(!0),A=n(null),j=n(null),M=n(null),N=n(C),P=n(S),F=n(),I=n(o),L=Zc(u),R=n(!1),z=n(!1);Hc(()=>{let e=Pc.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?V():e.cancel()}),$(()=>{let t=Gc(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&Qc.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(Qc.get(u)))},[u],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&l&&A.current?.editor.setModelLanguage(e,l)},[l],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let B=a(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=u||i,n=Gc(A.current,o||e||``,r||l||``,t||``);j.current=A.current?.editor.create(M.current,{model:n,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(Qc.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,r,i,o,l,u,m,h,g,d,f]);s(()=>{E&&N.current(j.current,A.current)},[E]),s(()=>{!O&&!E&&B()},[O,E,B]),I.current=o,s(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),s(()=>{if(E){let e=A.current.editor.onDidChangeMarkers(e=>{let t=j.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=A.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function V(){F.current?.dispose(),_?g&&Qc.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(Bc,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var el=i($c);u();function tl(e,t){let n=[];for(let[r,i]of Object.entries(e))r!==t&&(n.push({filePath:`file:///${r}`,content:i}),r.endsWith(`.ts`)&&n.push({filePath:`file:///${r.slice(0,-3)}.js`,content:i}));return n}var nl={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function rl(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...nl}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function il({value:e,onChange:t,extraLibs:r=[],path:i=`file:///block.ts`,onDiagnostics:c,readOnly:l=!1,heightPx:u=420,dark:d=!0}){let f=n(null),p=a((e,t)=>{if(f.current=t,rl(t,r),c===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{c(t.editor.getModelMarkers({resource:n.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(i),i()},[r,c]);return s(()=>{let e=f.current;e!==null&&rl(e,r)},[r]),o(el,{height:u,defaultLanguage:`typescript`,path:i,theme:d?`vs-dark`:`vs`,value:e,onChange:e=>t(e??``),onMount:p,options:{readOnly:l,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function al(e){return e.some(e=>e.severity>=8)}var ol=[{id:`blank`,name:`Blank script`,get description(){return Y.t(`helpers.buildExamples.blankDescription`)},entry:`main.ts`,files:{"main.ts":`import type { AddonContext } from '@camstack/types'
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* A core block. Runs in its own process, with the same \`ctx\` an addon gets.
|
|
17
|
-
* Return a function to release whatever you took (timers, sockets, listeners).
|
|
18
|
-
*
|
|
19
|
-
* Declaring devices: import { reconcileBlockDevices, exposeBlockDevices } from
|
|
20
|
-
* '@camstack/types' and hang them off the shared Blocks integration.
|
|
21
|
-
*/
|
|
22
|
-
export default function block(ctx: AddonContext) {
|
|
23
|
-
ctx.logger.info('hello from a core block')
|
|
24
|
-
|
|
25
|
-
const timer = setInterval(() => {
|
|
26
|
-
ctx.logger.info('tick')
|
|
27
|
-
}, 60_000)
|
|
28
|
-
|
|
29
|
-
return () => {
|
|
30
|
-
clearInterval(timer)
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
`}}];function sl(e){let t=e instanceof Set?e:new Set(e);if(!t.has(`file.ts`))return`file.ts`;let n=2;for(;t.has(`file-${String(n)}.ts`);)n+=1;return`file-${String(n)}.ts`}var cl=ol.find(e=>e.id===`blank`)?.files[`main.ts`]??`import type { AddonContext } from '@camstack/types'
|
|
34
|
-
|
|
35
|
-
export default function block(ctx: AddonContext) {
|
|
36
|
-
ctx.logger.info('hello from a core block')
|
|
37
|
-
return () => undefined
|
|
38
|
-
}
|
|
39
|
-
`;function ll({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Y.t(`helpers.restartGate.saveFirstNoProcess`):n?Y.t(`helpers.restartGate.saving`):r?Y.t(`helpers.restartGate.restarting`):t?Y.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Y.t(`helpers.restartGate.disabled`)}u();var ul=5e3;function dl(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=Reflect.get(n,`id`),r=Reflect.get(n,`name`),i=Reflect.get(n,`type`),a=Reflect.get(n,`stableId`);typeof e!=`number`||typeof r!=`string`||typeof i!=`string`||t.push({id:e,name:r,type:i,...typeof a==`string`?{stableId:a}:{}})}return t}function fl({blockId:t}){let{t:n}=X(),i=me(t),a=ze({addonId:i,projection:`slim`},{refetchInterval:ul}),s=r(()=>dl(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(E,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(G,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:o(`code`,{})}})}):o(`ul`,{className:`space-y-3`,children:s.map(t=>o(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${t.id}`,children:e(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[o(qt,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(Pt,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(G,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,o(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}u();function pl(e){return e===`refresh-channel-catalog`||e===`send-tv-schedule-now`||e===`refresh-nordvpn-catalog`||e===`probe-nordvpn-italy`||e===`test-nordvpn-endpoint`||e===`refresh-unifi-catalog`}function ml(e){let t=Date.now();switch(e){case`refresh-channel-catalog`:return{channelCatalogRefreshAt:t};case`send-tv-schedule-now`:return{sendNowAt:t};case`refresh-nordvpn-catalog`:return{nordVpnCatalogRefreshAt:t};case`probe-nordvpn-italy`:return{nordVpnProbeAt:t};case`test-nordvpn-endpoint`:return{nordVpnTestAt:t};case`refresh-unifi-catalog`:return{unifiCatalogRefreshAt:t}}}function hl(e){switch(e){case`refresh-channel-catalog`:return Y.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Y.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Y.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Y.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Y.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Y.t(`build.scriptSettingsPanel.enableUnifi`)}}function gl(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function _l(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function vl(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=gl(e);n!==null&&(t[n]=_l(e))}return t}function yl(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function bl({blockId:t}){let{t:n}=X(),i=O(),s=je({blockId:t},{retry:!1}),l=St({blockId:t},{refetchInterval:1e4,retry:!1}),u=Ot({onSuccess:()=>{l.refetch()}}),d=Rt(),f=bt(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=yl(l.data)?l.data:null,S=r(()=>x===null?{}:vl(x),[x]),C=p??S,w=a(e=>{m(e)},[]),T=p!==null,D=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),k=a(async(e,n)=>{if(pl(e)){b(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:ml(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(hl(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{b(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(E,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):x===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(J,{size:`sm`,variant:`primary`,onClick:D,disabled:!T||u.isPending||y,children:[u.isPending&&o(E,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(en,{schema:x,values:C,onChange:w,onAction:k}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var xl=`hub`;function Sl({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:g,onCancel:_}){let{t:v}=X(),y=O(),b=D(),{resolvedMode:x}=yt(),S=ee({code:t?.code??cl,files:t?.files,entry:t?.entry}),[w,T]=c(t?.name??``),[j,M]=c(S.files),[N,P]=c(S.entry),[F,I]=c(S.entry),[L,R]=c(t?.placement??xl),[z,B]=c(t?.integrationId??``),[V,H]=c([]),[te,ne]=c(!1),[re,ie]=c(`blank`),[ae,oe]=c(null),[se,ce]=c(``),le=j[F]??``,ue=e=>{M(t=>({...t,[F]:e}))},de=Object.keys(j).toSorted(),fe=ol.length>1,pe=r(()=>[...n?.libs??[],...tl(j,F)],[n?.libs,j,F]),U=f({mutationFn:()=>y.trpcClient.coreBlocks.compile.mutate({files:j,entry:N})}),he=r(()=>V.filter(e=>e.severity>=8),[V]),ge=al(V),_e=w.trim()===``,ve=t===null?null:ee(t),ye=t===null||ve===null||JSON.stringify(j)!==JSON.stringify(ve.files)||N!==ve.entry||w.trim()!==t.name||L!==t.placement||(z.trim()===``?void 0:z.trim())!==t.integrationId,be=()=>{U.reset(),g({name:w.trim(),files:j,entry:N,enabled:t?.enabled??!0,placement:L,...z.trim()===``?{}:{integrationId:z.trim()}})},xe=()=>{let e=sl(Object.keys(j));M(t=>({...t,[e]:``})),I(e),oe(e),ce(e)},Se=e=>{oe(e),ce(e)},Ce=()=>{if(ae===null)return;let e=ae,t=se.trim();if(oe(null),!(t===``||t===e)){if(j[t]!==void 0){I(t);return}M(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),N===e&&P(t),I(t)}},W=async e=>{let t=ol.find(t=>t.id===e);if(t===void 0)return;let n=ol.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(j)===JSON.stringify(n.files)&&N===n.entry)&&!await b({title:v(`build.blockEditor.loadExample`,`Load example`),message:v(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:v(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(ie(e),M({...t.files}),P(t.entry),I(t.entry),(w.trim()===``||re===`blank`)&&T(t.id===`blank`?``:t.name))},we=t===null?null:ja(t),Te=ll({existing:t,dirty:ye,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[we!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(G,{variant:Ma(we.tone),children:we.label})}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:v(`build.blockEditor.name`,`Name`)}),o(q,{className:`mt-1`,value:w,onChange:e=>T(e.target.value),placeholder:v(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:v(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(q,{className:`mt-1`,value:z,onChange:e=>B(e.target.value),placeholder:v(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&fe&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:v(`build.blockEditor.startFrom`,`Start from`)}),o(k,{className:`mt-1 w-full`,value:re,onChange:e=>void W(e.target.value),"data-testid":`script-example-select`,children:ol.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(Xe,{selectedNodeId:L,onSelect:R,label:v(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),L!==xl&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(C,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(Z,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[de.map(t=>ae===t?o(q,{value:se,onChange:e=>ce(e.target.value),onBlur:()=>Ce(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Ce()),e.key===`Escape`&&(e.preventDefault(),oe(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":v(`build.blockEditor.renameFile`,`Rename file`)},t):e(J,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs ${t===F?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>I(t),onDoubleClick:()=>Se(t),title:v(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===N?` · ${v(`build.blockEditor.entry`)}`:``]},t)),o(J,{variant:`unstyled`,type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:xe,"data-testid":`script-file-add`,children:v(`build.blockEditor.file`,`+ file`)}),F!==N&&o(J,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>P(F),title:v(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:v(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:v(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(il,{value:le,onChange:ue,path:`file:///${F}`,extraLibs:pe,onDiagnostics:H,dark:x===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:v(`build.blockEditor.theNodeReturnedNoType`,`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`)}),he.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:v(`build.blockEditor.errorsCannotSave`,{count:he.length})}),he.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:v(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),he.length>5&&o(`p`,{className:`text-foreground-subtle`,children:v(`build.blockEditor.moreErrors`,{count:he.length-5})})]}),U.data!==void 0&&(U.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(h,{className:`h-3.5 w-3.5`}),` `,v(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[U.data.line!==void 0&&o(`span`,{className:`mr-1`,children:v(`build.blockEditor.errorLine`,{line:String(U.data.line)})}),U.data.error??v(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),U.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[v(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,Cl(U.error)]}),s!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),t!==null&&e(`div`,{className:`space-y-3`,children:[o(bl,{blockId:t.id}),o(fl,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:`outline`,onClick:()=>U.mutate(),disabled:U.isPending||a,title:v(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[U.isPending&&o(E,{className:`h-4 w-4 animate-spin`}),` `,v(`common.compile`)]}),e(J,{onClick:be,disabled:a||ge||_e,children:[a&&o(E,{className:`h-4 w-4 animate-spin`}),` `,v(`common.save`)]}),e(J,{variant:`outline`,onClick:()=>d?.(),disabled:Te!==null||d===void 0,title:Te??v(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(m,{className:`h-4 w-4 animate-spin`}):o(m,{className:`h-4 w-4`}),` `,v(`build.blockEditor.restart`,`Restart`)]}),e(J,{variant:`ghost`,onClick:()=>ne(!te),title:v(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,"aria-expanded":te,children:[o(A,{className:`h-4 w-4`}),` `,v(`common.logs`),` `,o(At,{expanded:te})]}),o(J,{variant:`ghost`,onClick:_,disabled:a,children:v(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[v(`build.blockEditor.errorsCount`,{count:he.length}),ye&&t!==null?` · ${v(`build.blockEditor.unsavedChanges`)}`:``]}),_e&&o(G,{variant:`warning`,children:v(`build.blockEditor.nameRequired`,`Name required`)})]}),te&&e(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:t===null?v(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(p,{children:o(Z,{i18nKey:`build.blockEditor.logsOf`,values:{id:me(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(Ht,{addonId:me(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Cl(e){return e instanceof Error?e.message:String(e)}u();var wl=[`coreBlocks`,`list`],Tl=[`coreBlocks`,`getTypeDefs`],El=5e3;function Dl(e){return e instanceof Error?e.message:String(e)}function Ol({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=j(),{t:p}=X(),h=O(),{state:g,openNew:v,openEdit:y,close:b}=ot({editKey:`block`,newKey:`new`}),[x,S]=c(null),C=D(),[w,T]=c(null),E=l({queryKey:wl,refetchInterval:El,queryFn:async()=>(await h.trpcClient.coreBlocks.list.query({})).blocks}),k=g.mode!==`closed`,M=l({queryKey:Tl,enabled:k,staleTime:1/0,gcTime:1/0,queryFn:()=>h.trpcClient.coreBlocks.getTypeDefs.query({})}),N=()=>{E.refetch()},P=n(null),F=E.data;s(()=>{t===void 0||P.current===t||F?.find(e=>e.id===t&&U(e)===`code`)!==void 0&&(P.current=t,y(t),i?.(t))},[t,F,y,i]),s(()=>{a&&(S(null),v(),i?.(null),u?.())},[a,u,i,v]);let I=f({mutationFn:e=>h.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{S(e.block),y(e.block.id),i?.(e.block.id),N()}}),L=f({mutationFn:e=>h.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{S(e.block),y(e.block.id),i?.(e.block.id),N()}}),R=f({mutationFn:e=>h.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:N}),z=f({mutationFn:e=>h.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:N}),B=f({mutationFn:e=>h.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:N}),V=Pa((E.data??[]).filter(e=>U(e)===`code`)),ee=E.data!==void 0&&V.length===0,H=I.isPending||L.isPending,te=I.error===null?L.error===null?null:Dl(L.error):Dl(I.error),ne=g.mode===`edit`?V.find(e=>e.id===g.id)??(x!==null&&x.id===g.id?x:null):null,re=g.mode===`new`||ne===null?null:Na(V,ne),ie=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=ja(t),r=Lt(t.updatedAt,d);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(G,{variant:Ma(n.tone),children:n.label}),o(G,{variant:`info`,children:t.placement}),r!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`common.edited`,{when:r})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:n.detail}),w===t.id&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:me(t.id)},components:{code:o(`code`,{})}})}),o(Ht,{addonId:me(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:t=>{let n=z.isPending||R.isPending,r=B.isPending&&B.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),S(t),y(t.id),i?.(t.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),B.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(m,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),T(w===t.id?null:t.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:o(A,{className:`h-4 w-4`})}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),z.mutate({blockId:t.id,enabled:!t.enabled})},disabled:n,title:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`),children:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`)}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),C({title:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`),message:p(`build.scriptsTab.deleteMessage`,`{{name}} and its source will be deleted. This cannot be undone.`,{name:t.name}),confirmLabel:p(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&R.mutate(t.id)})},title:p(`common.delete`,`Delete`),children:o(_,{className:`h-4 w-4`})})]})}}],[C,w,i,y,R,B.isPending,B.variables,z,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:E.data===void 0?``:Fa(V)}),E.error!=null&&o(K,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Dl(E.error),onRetry:N}),o(Ut,{columns:ie,rows:V,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Pe,emptyMessage:ee?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):E.data===void 0?p(`build.scriptsTab.loadingScripts`,`Loading scripts…`):p(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{S(e),y(e.id),i?.(e.id)}}),o(Le,{open:k,onClose:()=>{I.reset(),L.reset(),B.reset(),S(null),b(),i?.(null)},title:re===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:re.name}),icon:ke,width:`xl`,testId:`script-editor-panel`,children:o(Sl,{existing:re,typeDefs:M.data,typeDefsLoading:M.isLoading,saving:H,saveError:te,restarting:B.isPending,restartError:B.error===null?null:Dl(B.error),onRestart:re===null?void 0:()=>B.mutate(re.id),onSave:e=>{let t=re;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),B.reset(),S(null),b(),i?.(null)}})}),R.error!=null&&o(K,{message:Dl(R.error)}),z.error!=null&&o(K,{message:Dl(z.error)}),B.error!=null&&o(K,{message:Dl(B.error)})]})}var kl=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`];function Al(e){return e!==null&&kl.some(t=>t===e)}var jl=[`coreBlocks`,`list`,`build-counts`],Ml=[`schedulers`,`list`,`build-counts`],Nl=[`actions`,`list`,`build-counts`],Pl=[`block`,`action`,`scheduler`,`create`,`new`];function Fl(e){return e.filter(e=>U(e)===`code`).length}function Il(e){return e.filter(e=>Kn(e.code)).length}function Ll(e,t){return t===null?e:`${e} (${String(t)})`}function Rl(){let{t}=X(),n=O(),[r,i]=Kt(),a=r.get(`tab`),s=Al(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:jl,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:Fl(u),f=u===void 0?null:Il(u),p=l({queryKey:Nl,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=l({queryKey:Ml,refetchInterval:1e4,queryFn:async()=>n.trpcClient.schedulers.list.query({})}),g=h.data===void 0?null:h.data.length,_=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),v=_.data?.state===`loaded`?_.data.views.length:null,b=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},x=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},C=()=>{i(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},w=e=>{i(()=>{let t=new URLSearchParams(window.location.search);return t.set(`tab`,`custom-device`),t.delete(`block`),t.delete(`create`),t.set(`new`,e),t},{replace:!0})},T=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},E=s===`automations`?t(`build.newAutomation`,`New automation`):s===`actions`?t(`build.newAction`,`New action`):s===`schedulers`?t(`build.newScheduler`,`New scheduler`):t(`build.newScript`,`New script`),D=Xt(`/build`,{t,isAdmin:!0})??{icon:y,title:t(`nav.build`,`Build-your-self`)};return o(tn,{icon:D.icon,title:D.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${D.title} sections`,fill:!0,actions:s===`custom-device`?e(J,{type:`button`,onClick:()=>w(`helper`),"data-testid":`build-new-composed`,children:[o(S,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(J,{type:`button`,onClick:C,"data-testid":`build-new`,children:[o(S,{className:`h-4 w-4`}),` `,E]}),sections:[{id:`automations`,label:Ll(t(`build.tabAutomations`,`Automations`),f),ownedParams:Pl,content:o(Ja,{onOpenScripts:b,createRequested:s===`automations`&&c,onCreateConsumed:T})},{id:`actions`,label:Ll(t(`build.tabActions`,`Actions`),m),ownedParams:Pl,content:o(jr,{createRequested:s===`actions`&&c,onCreateConsumed:T})},{id:`schedulers`,label:Ll(t(`build.tabSchedulers`,`Schedulers`),g),ownedParams:Pl,content:o(Mo,{createRequested:s===`schedulers`&&c,onCreateConsumed:T})},{id:`scripts`,label:Ll(t(`build.tabCode`,`Code`),d),ownedParams:Pl,content:o(Ol,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:x,createRequested:s===`scripts`&&c,onCreateConsumed:T})},{id:`custom-device`,label:Ll(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:Pl,content:o(vs,{createRequested:s===`custom-device`&&c,onCreateConsumed:T})}]})}export{Rl as BuildPage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,et as s,o as c,x as l}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$n as u,An as d,Cn as f,D as p,Di as m,Fi as h,Fn as g,Gi as _,Ii as v,Kt as y,Ln as b,Ni as x,Pn as S,Sn as C,Un as w,Ut as T,Yn as E,br as D,bt as O,ct as k,ei as A,fa as j,ht as M,ki as N,ui as ee,ut as P,vn as F,wn as I,xi as L}from"./player-overlays-CC-b3--a.js";import{Go as te,Ko as ne,Zo as re,qo as ie}from"./client-kWeONSGL.js";import{t as ae}from"./hard-drive-download-gFUluoPC.js";import{t as oe}from"./memory-stick-BSUaqG9H.js";import{t as se}from"./unlink-DzO14DVn.js";import{$u as ce,Bn as le,Br as ue,Di as de,Dl as fe,Ff as R,Fi as pe,Fl as me,Fr as he,Ft as z,Gc as ge,Go as _e,Ic as ve,Ii as ye,Ir as be,Jr as xe,Ju as Se,Kc as Ce,Kn as we,Lc as Te,Ln as Ee,Lr as De,Mf as B,Mt as Oe,Ni as ke,Pi as Ae,Qu as je,Rn as V,Rr as Me,Uc as Ne,Vr as Pe,W as Fe,Wc as Ie,Wl as Le,Xl as Re,Xr as ze,Xu as Be,Yr as H,Yu as Ve,Zu as He,_n as Ue,hf as We,jf as Ge,qu as Ke,sf as U,vd as qe,vn as Je,vt as Ye,yi as W,zn as G,zr as Xe}from"./src-DGSNF4l8.js";import{t as K}from"./i18n-Cmy3cCDH.js";import{t as q}from"./useTranslation-BJr-n0es.js";import{Br as Ze,g as Qe}from"./index-DwCHDODI.js";import{n as $e}from"./format-C7beVF9i.js";import{t as et}from"./AdminPage-dLt1mKEa.js";import{t as tt}from"./NodeAddonsSettingsPanel-BGB_St7Q.js";import{_ as nt,f as rt,h as it,p as at}from"./board-model-D-CIwcV1.js";import{t as J}from"./format-size-DIxKXxtj.js";import{n as ot,t as st}from"./useNodeUrlSelection-D9CPif56.js";s();var ct={unpaired:`Not paired`,pending:`Pairing…`,paired:`Paired`},lt=new Set([`paired`,`rejected`,`failed`,`expired`]);function Y(e){return lt.has(e)}function ut(e){return e.replace(/\D/g,``).slice(0,6)}function dt(e){return e.length===6}function ft(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3)),r=Math.floor(n/60),i=n%60;return`${r}:${String(i).padStart(2,`0`)}`}function pt(e,t){return e.includes(`:`)?`[${e}]:${t}`:`${e}:${t}`}function mt(e){return e.length<=23?e:`${e.slice(0,20)}…`}function ht({view:e,beginError:t}){if(e===null)return t===null?`sending`:`send-failed`;switch(e.state){case`paired`:return`paired`;case`rejected`:return`rejected`;case`failed`:return`failed`;case`expired`:return`expired`;case`completing`:return`completing`;case`awaiting-confirmation`:return e.hubConfirmed&&!e.agentConfirmed?`awaiting-agent`:e.agentConfirmed&&!e.hubConfirmed?`awaiting-hub`:`awaiting-both`}}function gt(e){return e===`awaiting-both`||e===`awaiting-hub`}var _t={sending:`Sending the pairing offer to the agent…`,"send-failed":`The agent could not be reached`,"awaiting-both":`Waiting for both confirmations`,"awaiting-agent":`Confirmed here — waiting for the agent`,"awaiting-hub":`The agent is confirmed — now confirm here`,completing:`Issuing the node certificate…`,paired:`Paired`,rejected:`Pairing was rejected`,failed:`Pairing failed`,expired:`The pairing expired`},vt=2e3,yt=1e3;function bt(e){return e.message.length>0?e.message:K.t(`pairing.agentsFoundSection.requestFailed`)}function xt(e){return e.length===6?`${e.slice(0,3)} ${e.slice(3)}`:e}function St(e){let[t,n]=o(()=>Date.now());return a(()=>{if(!e)return;let t=setInterval(()=>n(Date.now()),yt);return()=>clearInterval(t)},[e]),t}function Ct({target:n,onClose:r,onSettled:s,onOpenNode:c}){let{t:u}=q(),[d,f]=o(null),[p,m]=o(null),[h,g]=o(``),[_,v]=o(null),y=t(null),b=R.agentPairing.beginPairing.useMutation(),x=R.agentPairing.confirmPairing.useMutation(),S=R.agentPairing.rejectPairing.useMutation();a(()=>{if(n===null){y.current=null,f(null),m(null),g(``),v(null);return}if(y.current!==n){if(y.current=n,n.pairingId!==void 0){f(n.pairingId);return}b.mutateAsync({host:n.host,port:n.port}).then(e=>{y.current===n&&f(e.pairingId)}).catch(e=>{y.current===n&&m(bt(e))})}},[n]);let C=R.agentPairing.getPairing.useQuery({pairingId:d??``},{enabled:d!==null,refetchInterval:e=>{let t=e.state.data?.state;return t!==void 0&&Y(t)?!1:vt}}),w=wt(x.data??S.data??null,C.data??null),T=ht({view:w,beginError:p}),E=w!==null&&Y(w.state),O=t(!1);a(()=>{if(!E){O.current=!1;return}O.current||(O.current=!0,s())},[E,s]);let k=St(w!==null&&!E),A=()=>{d===null||!dt(h)||(v(null),x.mutate({pairingId:d,code:h},{onError:e=>{v(bt(e)),g(``)}}))};return i(he,{open:n!==null,onOpenChange:e=>!e&&r(),children:e(De,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[e(ue,{children:[i(Pe,{children:u(`pairing.pairingDialog.title`,{node:n?.nodeId??``})}),i(Me,{children:n===null?``:u(`pairing.pairingDialog.eachScreenShowsACode`,`Both screens show the same six digits. Check they match, then type the code you read on the agent. Agent at {{value1}}`,{value1:pt(n.host,n.port)})})]}),e(be,{className:`space-y-4`,children:[i(Tt,{phase:T}),T===`send-failed`&&p!==null&&i(H,{title:u(`pairing.pairingDialog.couldNotStartThePairing`,`Could not start the pairing`),message:p}),w!==null&&!E&&i(Et,{view:w,phase:T,now:k,typed:h,onType:e=>g(ut(e)),onSubmit:A,confirmError:_,busy:x.isPending}),T===`paired`&&w!==null&&i(Dt,{nodeId:w.nodeId,onOpenNode:c,onClose:r}),E&&T!==`paired`&&w?.failure!=null&&i(H,{message:w.failure})]}),i(Xe,{children:E||T===`send-failed`?i(W,{type:`button`,variant:`outline`,onClick:r,children:u(`common.close`,`Close`)}):e(l,{children:[i(W,{type:`button`,variant:`outline`,disabled:S.isPending,onClick:()=>{if(d===null){r();return}S.mutate({pairingId:d},{onSettled:r})},children:u(`pairing.pairingDialog.reject`,`Reject`)}),gt(T)&&e(W,{type:`button`,disabled:!dt(h)||x.isPending,onClick:A,children:[x.isPending&&i(D,{className:`h-4 w-4 animate-spin`}),u(`common.confirm`,`Confirm`)]})]})})]})})}function wt(e,t){if(t===null)return e;if(e===null)return t;let n=e=>(Y(e.state)?10:e.state===`completing`?5:0)+ +!!e.hubConfirmed+ +!!e.agentConfirmed;return n(e)>n(t)?e:t}function Tt({phase:t}){let n=t===`sending`||t===`completing`,r=t===`paired`,a=t===`rejected`||t===`failed`||t===`expired`||t===`send-failed`;return e(`p`,{role:`status`,className:`flex items-center gap-2 text-sm font-medium ${r?`text-success`:a?`text-danger`:`text-foreground`}`,children:[n&&i(D,{className:`h-4 w-4 animate-spin`}),r&&i(m,{className:`h-4 w-4`}),a&&i(L,{className:`h-4 w-4`}),_t[t]]})}function Et({view:t,phase:n,now:r,typed:a,onType:o,onSubmit:s,confirmError:c,busy:l}){let{t:u}=q();return e(`div`,{className:`space-y-4`,children:[e(`section`,{"aria-label":u(`pairing.pairingDialog.codeOnThisHub`,`Code on this hub`),className:`rounded-md border border-border bg-surface p-3`,children:[i(`p`,{className:`text-xs text-foreground-muted`,children:u(`pairing.pairingDialog.codeOnThisHubRead`,`Code on this hub: the agent must show the same digits`)}),i(`p`,{"data-testid":`hub-code`,className:`mt-1 font-mono text-3xl font-semibold tracking-widest text-foreground`,children:xt(t.code)}),i(`p`,{className:`mt-2 text-xs text-foreground-muted`,children:u(`pairing.pairingDialog.onTheAgentEnterThis`,`On the agent, enter this code and the agent’s local PIN (shown on the agent’s console or log, or on its own screen).`)})]}),gt(n)?i(`form`,{className:`space-y-2`,onSubmit:e=>{e.preventDefault(),s()},children:i(z,{label:u(`pairing.pairingDialog.codeShownOnTheAgent`,`Code shown on the agent`),description:u(`pairing.pairingDialog.typeTheSixDigitsThe`,`Type the six digits you read on the agent; do not paste. If they differ from the code above, stop and press Reject.`),...c===null?{}:{error:c},children:i(U,{value:a,onChange:e=>o(e.target.value),inputMode:`numeric`,autoComplete:`off`,spellCheck:!1,placeholder:`000000`,maxLength:6,disabled:l,"aria-label":u(`pairing.pairingDialog.codeShownOnTheAgent`,`Code shown on the agent`),className:`font-mono tracking-widest`})})}):i(`p`,{className:`text-xs text-foreground-muted`,children:n===`awaiting-agent`?u(`pairing.pairingDialog.youConfirmedHereTheAgent`,`You confirmed here. The agent still has to enter the hub code and its PIN.`):u(`pairing.pairingDialog.working`,`Working…`)}),e(`ul`,{className:`flex flex-wrap gap-x-4 gap-y-1 text-xs text-foreground-muted`,children:[i(`li`,{children:t.hubConfirmed?u(`pairing.pairingDialog.hubConfirmed`,`Hub: confirmed`):u(`pairing.pairingDialog.hubNotConfirmed`,`Hub: not confirmed`)}),i(`li`,{children:t.agentConfirmed?u(`pairing.pairingDialog.agentConfirmed`,`Agent: confirmed`):u(`pairing.pairingDialog.agentNotConfirmed`,`Agent: not confirmed`)}),i(`li`,{"data-testid":`countdown`,children:u(`pairing.pairingDialog.expiresIn`,{countdown:ft(t.expiresAt,r)})})]})]})}function Dt({nodeId:t,onOpenNode:n,onClose:r}){let{t:a}=q(),{nodes:o}=Ge(),s=o?.some(e=>e.id===t&&e.isOnline)===!0;return e(`div`,{className:`space-y-2 rounded-md border border-success/40 bg-success/10 p-3 text-sm`,children:[e(`p`,{className:`flex items-center gap-2 text-success`,children:[i(F,{className:`h-4 w-4`}),s?a(`pairing.pairingDialog.joinedAndRegisteredItsCapabilities`,`{{nodeId}} joined and registered its capabilities.`,{nodeId:t}):a(`pairing.pairingDialog.holdsItsCertificateWaitingFor`,`{{nodeId}} holds its certificate. Waiting for it to connect and register its capabilities…`,{nodeId:t})]}),i(W,{type:`button`,size:`sm`,variant:`outline`,disabled:!s,onClick:()=>{r(),n(t)},children:a(`pairing.pairingDialog.openNode`,`Open node`)})]})}var Ot={paired:`success`,pending:`warning`,unpaired:`default`};function kt({state:t,connected:n}){let{t:r}=q();return e(`span`,{className:`inline-flex items-center gap-1.5`,children:[i(de,{variant:Ot[t],className:`text-[10px]`,children:ct[t]}),t===`paired`&&i(`span`,{className:`text-[10px] text-foreground-muted`,children:n?r(`common.connected`):r(`pairing.agentStateBadge.notConnected`,`not connected`)})]})}s();var X={pending:0,unpaired:1,paired:2};function At(e){if(e.trim().length===0)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:null}function jt({onOpenNode:t}){let{t:r}=q(),a=k(),s=R.useUtils(),c=R.agentPairing.listDiscoveredAgents.useQuery(void 0,{refetchInterval:15e3}),[u,d]=o(null),[f,m]=o(null),[h,g]=o(!1),[_,v]=o(``),[y,x]=o(``),[C,T]=o(null),[E,O]=o(!1),A=()=>void s.agentPairing.listDiscoveredAgents.invalidate(),j=R.agentPairing.addAgentByAddress.useMutation({onSuccess:()=>{g(!1),v(``),x(``),T(null),A()},onError:e=>T(e.message)}),M=R.agentPairing.unpairAgent.useMutation({onSuccess:e=>{m({tone:`success`,message:`${e.nodeId}: ${e.next}${e.agentNotified?``:` The agent could not be told; forget the hub on its own page.`}`}),A()},onError:e=>m({tone:`danger`,message:r(`pairing.agentsFoundSection.unpairFailed`,`Unpair failed: {{message}}`,{message:e.message})})}),N=n(()=>(c.data?.agents??[]).toSorted((e,t)=>X[e.state]-X[t.state]),[c.data]),ee=async()=>{O(!0);try{await s.agentPairing.listDiscoveredAgents.fetch({refresh:!0}),A()}finally{O(!1)}},P=()=>{let e=At(y);if(e===null){T(`The port must be a whole number between 1 and 65535.`);return}T(null),j.mutate({host:_.trim(),...e===void 0?{}:{port:e}})},F=async e=>{await a({title:r(`pairing.agentsFoundSection.unpair`,`Unpair {{nodeId}}`,{nodeId:e.nodeId}),message:r(`pairing.agentsFoundSection.sCertificatesAreRevokedAt`,`{{nodeId}}'s certificates are revoked at once and it is disconnected from the mesh. It must be paired again before it can rejoin.`,{nodeId:e.nodeId}),confirmLabel:r(`pairing.agentsFoundSection.unpair2`,`Unpair`),variant:`danger`})&&(m(null),M.mutate({nodeId:e.nodeId}))},I=n(()=>[{key:`name`,header:r(`pairing.agentsFoundSection.name`,`Name`),render:e=>e.name??`—`,sortValue:e=>e.name},{key:`node`,header:r(`pairing.agentsFoundSection.node`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId}),sortValue:e=>e.nodeId},{key:`address`,header:r(`pairing.agentsFoundSection.address`,`Address`),render:e=>i(`span`,{className:`font-mono text-xs`,children:pt(e.host,e.port)}),sortValue:e=>e.host},{key:`version`,header:r(`pairing.agentsFoundSection.version`,`Version`),render:e=>e.version??`—`,sortValue:e=>e.version},{key:`state`,header:r(`pairing.agentsFoundSection.state`,`State`),render:e=>i(kt,{state:e.state,connected:e.connected}),sortValue:e=>X[e.state]},{key:`fingerprint`,header:r(`pairing.agentsFoundSection.certificate`,`Certificate`),render:e=>e.fingerprint===null?`—`:i(`span`,{className:`font-mono text-xs`,title:e.fingerprint,children:mt(e.fingerprint)}),sortValue:e=>e.fingerprint},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=e.pairing;return e.state===`unpaired`?i(W,{type:`button`,size:`sm`,onClick:()=>d({nodeId:e.nodeId,host:e.host,port:e.port}),children:r(`pairing.agentsFoundSection.pair`,`Pair`)}):e.state===`paired`?i(W,{type:`button`,size:`sm`,variant:`outline`,disabled:M.isPending,onClick:()=>void F(e),children:r(`pairing.agentsFoundSection.unpair2`,`Unpair`)}):e.state===`pending`&&t!==null?i(W,{type:`button`,size:`sm`,onClick:()=>d({nodeId:e.nodeId,host:e.host,port:e.port,pairingId:t.pairingId}),children:r(`pairing.agentsFoundSection.resume`,`Resume`)}):null}}],[M.isPending,r]);return e(Ee,{headingId:`agents-found`,title:r(`pairing.agentsFoundSection.agentsFoundOnTheNetwork`,`Agents found on the network`),icon:b,testId:`agents-found`,actions:e(l,{children:[e(W,{type:`button`,size:`sm`,variant:`outline`,disabled:E,onClick:()=>void ee(),children:[E?i(D,{className:`h-3.5 w-3.5 animate-spin`}):i(S,{className:`h-3.5 w-3.5`}),r(`pairing.agentsFoundSection.scan`,`Scan`)]}),e(W,{type:`button`,size:`sm`,onClick:()=>g(e=>!e),children:[i(w,{className:`h-3.5 w-3.5`}),r(`pairing.agentsFoundSection.addByAddress`,`Add by address`)]})]}),children:[e(`div`,{className:`${p} space-y-3`,children:[i(`p`,{className:`text-[11px] leading-relaxed text-foreground-muted`,children:r(`pairing.agentsFoundSection.anAgentHoldsNoSecret`,`An agent holds no secret: pairing issues it a certificate after you confirm the same six digits on this page and on the agent. Discovery needs the agent on its own IP or host networking; a Docker bridge hides it — add it by address.`)}),h&&e(`form`,{"aria-label":r(`pairing.agentsFoundSection.addAgentByAddress`,`Add agent by address`),className:`flex flex-wrap items-start gap-2`,onSubmit:e=>{e.preventDefault(),_.trim().length>0&&!j.isPending&&P()},children:[i(z,{label:r(`pairing.agentsFoundSection.address`,`Address`),description:r(`pairing.agentsFoundSection.aPrivateOrLocalAddress`,`A private or local address only.`),...C===null?{}:{error:C},children:i(U,{value:_,onChange:e=>v(e.target.value),placeholder:`192.0.2.20`,"aria-label":r(`pairing.agentsFoundSection.agentAddress`,`Agent address`),autoComplete:`off`})}),i(z,{label:r(`pairing.agentsFoundSection.port`,`Port`),description:r(`pairing.agentsFoundSection.optional`,`Optional.`),children:i(U,{value:y,onChange:e=>x(e.target.value),placeholder:`4444`,inputMode:`numeric`,"aria-label":r(`pairing.agentsFoundSection.agentPort`,`Agent port`),className:`w-24`})}),e(W,{type:`submit`,size:`sm`,className:`mt-5`,disabled:_.trim().length===0||j.isPending,children:[j.isPending&&i(D,{className:`h-3.5 w-3.5 animate-spin`}),r(`common.add`,`Add`)]})]}),f!==null&&i(`p`,{role:`status`,className:`rounded border px-3 py-2 text-xs ${f.tone===`success`?`border-success/30 text-foreground`:`border-danger/40 text-danger`}`,children:f.message}),c.isError?i(H,{title:r(`pairing.agentsFoundSection.couldNotListAgents`,`Could not list agents`),message:c.error?.message??r(`pairing.agentsFoundSection.requestFailed`,`Request failed`),onRetry:A}):c.isLoading?i(`p`,{className:`py-4 text-center text-xs text-foreground-muted`,children:r(`pairing.agentsFoundSection.lookingForAgents`,`Looking for agents…`)}):N.length===0?i(ze,{icon:b,title:r(`pairing.agentsFoundSection.noAgentsFound`,`No agents found`),description:r(`pairing.agentsFoundSection.nothingIsAdvertisingOnThis`,`Nothing is advertising on this network. Start the agent on its own IP (or host networking), or add it by address.`)}):i(G,{columns:I,rows:N,rowKey:e=>e.nodeId,minWidthPx:720,defaultSort:{columnKey:`state`,dir:`asc`}})]}),i(Ct,{target:u,onClose:()=>d(null),onSettled:A,onOpenNode:t})]})}function Mt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nt(e){if(!Mt(e))return null;let t=e.ticket;if(typeof t!=`string`||t.length===0)return null;let n=e.dashboardUrl;return typeof n==`string`&&n.length>0?{ticket:t,dashboardUrl:n}:{ticket:t}}function Pt(e){let t=e.trim();return!(t.length===0||t.includes(`/`)||t.includes(`?`)||t.includes(`#`)||t.includes(`@`)||t.includes(`:`))}function Z(e){return e.startsWith(`172.17.`)}function Ft(e){let t=/^100\.(\d+)\./.exec(e);if(t===null)return!1;let n=Number(t[1]);return n>=64&&n<=127}function It(e){if(e.startsWith(`10.`)||e.startsWith(`192.168.`))return!0;let t=/^172\.(\d+)\./.exec(e);if(t===null)return!1;let n=Number(t[1]);return n>=16&&n<=31&&!Z(e)}function Lt(e,t){if(typeof t==`string`&&Pt(t))return t.trim();let n=e.filter(e=>!e.includes(`:`)),r=n.find(e=>!e.startsWith(`127.`)&&!e.startsWith(`169.254.`)&&!Z(e)&&!Ft(e)&&It(e));if(r!==void 0)return r;for(let e of n)if(!e.startsWith(`127.`)&&!e.startsWith(`169.254.`)&&!Z(e))return e;return null}function Rt(e){return`http://${e}:4444/`}function zt(e,t){let n=new URL(Rt(e));return n.searchParams.set(`ticket`,t),n.toString()}function Bt(){return window.open(`about:blank`,`_blank`)}function Vt(e,t){return e===null||e.closed?!1:(e.location.href=t,!0)}function Ht({node:t}){let{info:n}=Qe();return!t.isHub||n===null?i(`span`,{className:`text-sm font-semibold shrink-0`,children:t.name}):e(l,{children:[i(`span`,{className:`text-sm font-semibold shrink-0`,"data-testid":`node-title-name`,children:n.name}),n.name!==t.id&&i(`span`,{className:`text-xs text-foreground-subtle shrink-0`,"data-testid":`node-title-id`,children:t.id})]})}s();function Ut(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}function Wt(e){return e===`running`?`running`:e===`crashed`||e===`failed`?`error`:`stopped`}var Gt=[`trace`,`debug`,`info`,`warn`,`error`];function Kt({proc:t,nodeId:n,defaultExpanded:r,activePanel:a,onTogglePanel:s}){let{t:c}=q(),l=t.services??[],u=l.length===1,[f,p]=o(u||r),[m,v]=o(null),[y,b]=o(`info`),S=t.name.includes(`(core)`),w=Ie(),T=ge(),E=Ce(),D=async e=>{v(e);try{await w.mutateAsync({nodeId:n,addonId:e})}catch(e){console.error(`Failed to restart addon:`,e)}finally{v(null)}},O=async()=>{v(t.name);try{await T.mutateAsync({nodeId:n,processName:t.name})}catch(e){console.error(`Failed to restart process:`,e)}finally{v(null)}},k=async e=>{let r=`${n}/${t.name}`;try{await E.mutateAsync({nodeId:r,level:e}),b(e)}catch(e){console.error(`Failed to set log level:`,e)}};return e(`div`,{className:`border border-border/50 rounded-lg overflow-hidden`,children:[e(`div`,{role:u?void 0:`button`,tabIndex:u?void 0:0,onClick:u?void 0:()=>p(!f),onKeyDown:u?void 0:e=>{(e.key===`Enter`||e.key===` `)&&p(!f)},className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 w-full px-3 py-2 bg-muted/20 transition-colors text-left select-none ${u?``:`hover:bg-muted/40 cursor-pointer`}`,children:[u?i(`span`,{className:`h-3 w-3 shrink-0`}):i(f?h:x,{className:`h-3 w-3 text-muted-foreground shrink-0`}),S?i(C,{className:`h-3.5 w-3.5 text-primary shrink-0`}):i(_,{className:`h-3.5 w-3.5 text-warning shrink-0`}),i(`span`,{className:`text-xs font-semibold min-w-0 flex-1 basis-full truncate sm:basis-auto`,children:t.name}),e(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:[`PID `,t.pid]}),i(Ye,{status:Wt(t.state),label:t.state}),i(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:c(`cluster.forksTab.cpu`,{percent:t.cpuPercent})}),i(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:J(t.memoryRss)}),i(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:Ut(t.uptimeSeconds)}),!S&&e(`div`,{className:`flex items-center gap-1`,onClick:e=>e.stopPropagation(),children:[e(ke,{children:[i(ye,{className:`text-[9px] px-1.5 py-0.5 rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors font-mono`,title:c(`cluster.forksTab.setLogLevel`,`Set log level`),children:y}),i(Ae,{align:`end`,className:`min-w-[70px] py-0.5`,children:Gt.map(e=>i(pe,{onClick:()=>k(e),className:`h-auto px-2 py-1 text-[10px] font-mono ${e===y?`text-primary font-semibold`:``}`,children:e},e))})]}),i(W,{variant:`unstyled`,onClick:O,disabled:m===t.name,className:`p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50`,title:c(`cluster.forksTab.restartProcess`,`Restart process`),children:i(d,{className:`h-3 w-3 ${m===t.name?`animate-spin`:``}`})})]})]}),f&&l.length>0&&i(`div`,{className:`divide-y divide-border/30`,children:l.map(t=>e(`div`,{children:[e(`div`,{className:`flex items-center gap-2 px-3 py-1.5 pl-9 hover:bg-muted/10 transition-colors`,children:[i(`div`,{className:`h-1.5 w-1.5 rounded-full shrink-0 ${t.status===`running`?`bg-success`:`bg-muted-foreground/30`}`}),i(`span`,{className:`text-xs font-medium flex-1 min-w-0 truncate`,children:t.addonId}),t.capabilities.length>0&&e(`div`,{className:`flex gap-1 flex-shrink-0`,children:[t.capabilities.slice(0,3).map(e=>i(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-info/10 text-info truncate max-w-[80px]`,children:e},e)),t.capabilities.length>3&&e(`span`,{className:`text-[9px] text-muted-foreground`,children:[`+`,t.capabilities.length-3]})]}),e(`div`,{className:`flex items-center gap-1 shrink-0`,children:[i(W,{variant:`unstyled`,onClick:()=>s(t.addonId,`logs`),className:`p-0.5 rounded transition-colors ${a?.addonId===t.addonId&&a.type===`logs`?`bg-primary/10 text-primary`:`hover:bg-muted text-muted-foreground hover:text-foreground`}`,title:c(`cluster.forksTab.showLogsFor`,`Show logs for {{addonId}}`,{addonId:t.addonId}),children:i(I,{className:`h-3 w-3`})}),i(W,{variant:`unstyled`,onClick:()=>s(t.addonId,`events`),className:`p-0.5 rounded transition-colors ${a?.addonId===t.addonId&&a.type===`events`?`bg-primary/10 text-primary`:`hover:bg-muted text-muted-foreground hover:text-foreground`}`,title:c(`cluster.forksTab.showEventsFor`,`Show events for {{addonId}}`,{addonId:t.addonId}),children:i(g,{className:`h-3 w-3`})}),i(W,{variant:`unstyled`,onClick:()=>D(t.addonId),disabled:m===t.addonId,className:`p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50`,title:c(`cluster.forksTab.restart`,`Restart {{addonId}}`,{addonId:t.addonId}),children:i(d,{className:`h-3 w-3 ${m===t.addonId?`animate-spin`:``}`})})]})]}),a?.addonId===t.addonId&&a.type===`logs`&&i(`div`,{className:`border-t border-border/40 bg-muted/5`,children:i(Je,{addonId:t.addonId,agentId:n,maxHeight:`max-h-48`,showFilters:!1,onClose:()=>s(t.addonId,`logs`)})}),a?.addonId===t.addonId&&a.type===`events`&&i(`div`,{className:`border-t border-border/40 bg-muted/5`,children:i(Ue,{addonId:t.addonId,category:`addon.*`,maxHeight:`max-h-48`,onClose:()=>s(t.addonId,`events`)})})]},t.addonId))}),f&&l.length===0&&i(`div`,{className:`px-3 py-2 pl-9 text-[10px] text-muted-foreground`,children:c(`cluster.forksTab.noServices`,`No services`)})]})}function qt({nodeId:e,processes:t}){let{t:n}=q(),[r,a]=o(null),s=(e,t)=>{a(n=>n?.addonId===e&&n.type===t?null:{addonId:e,type:t})};return t.length===0?i(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:n(`cluster.forksTab.noProcessesOnThisNode`,`No processes on this node`)}):i(`div`,{className:`space-y-2 py-1`,children:t.map((t,n)=>i(Kt,{proc:t,nodeId:e,defaultExpanded:n===0,activePanel:r,onTogglePanel:s},t.name))})}var Jt={system:0,managed:1,root:2};s();function Yt(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${e%60}s`:e<86400?`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`:`${Math.floor(e/86400)}d ${Math.floor(e%86400/3600)}h`}function Xt(e,t=80){return e.length<=t?e:`…${e.slice(e.length-t+1)}`}function Zt({nodeId:t}){let{t:r}=q(),a=c(),o=B(`metrics.node-processes-snapshot`,e=>e.nodeId===t),{data:s}=Te({nodeId:t}),l=o?.processes??s,u=n(()=>l?[...l]:[],[l]),d=n(()=>[{key:`classification`,header:r(`cluster.processesTab.class`,`Class`),sortValue:e=>Jt[e.classification],render:e=>i(`span`,{className:`inline-block rounded-full px-1.5 py-0.5 text-[10px] font-medium ${e.classification===`root`?`bg-info/20 text-info`:e.classification===`system`?`bg-foreground-subtle/20 text-foreground-subtle`:`bg-success/20 text-success`}`,children:e.classification})},{key:`pid`,header:`PID`,align:`right`,sortValue:e=>e.pid,render:e=>i(`span`,{className:`font-mono`,children:e.pid})},{key:`ppid`,header:`PPID`,align:`right`,sortValue:e=>e.ppid,render:e=>i(`span`,{className:`font-mono text-foreground-subtle`,children:e.ppid})},{key:`addonId`,header:r(`cluster.processesTab.addon`,`Addon`),sortValue:e=>e.addonId,render:e=>i(`span`,{className:`text-foreground-subtle text-[11px]`,children:e.addonId??`—`})},{key:`command`,header:r(`cluster.processesTab.command`,`Command`),nowrap:!1,render:e=>i(`span`,{className:`font-mono text-[10px] text-foreground-subtle break-all`,children:Xt(e.command)})},{key:`cpuPercent`,header:r(`cluster.processesTab.cpu`,`CPU%`),align:`right`,sortValue:e=>e.cpuPercent,render:e=>e.cpuPercent.toFixed(1)},{key:`memoryRssBytes`,header:`RSS`,align:`right`,sortValue:e=>e.memoryRssBytes,render:e=>J(e.memoryRssBytes)},{key:`uptimeSec`,header:r(`cluster.processesTab.uptime`,`Uptime`),align:`right`,sortValue:e=>e.uptimeSec,render:e=>i(`span`,{className:`text-foreground-subtle`,children:Yt(e.uptimeSec)})}],[r]);return e(`div`,{className:`space-y-4`,children:[i(`div`,{className:`flex items-start justify-end gap-4`,children:e(W,{variant:`unstyled`,type:`button`,onClick:()=>a.invalidateQueries({queryKey:[[`metricsProvider`,`listNodeProcesses`]]}),className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:[i(S,{className:`h-3 w-3`}),` `,r(`common.refresh`)]})}),i(G,{columns:d,rows:u,rowKey:e=>e.pid,minWidthPx:880,maxBodyHeight:le,emptyMessage:r(`cluster.processesTab.scanning`,`Scanning…`)})]})}s();var Qt=96;function $t({title:e,points:t,mainLabel:r,gcLabel:a,formatValue:o,emptyMessage:s,gapMs:c}){return i(Fe,{title:e,series:n(()=>[{id:`main`,label:r,unit:`%`,colorIndex:0,gapMs:c,points:t.map(e=>({t:e.atMs,v:e.main}))},{id:`gc`,label:a,unit:`%`,colorIndex:1,gapMs:c,points:t.map(e=>({t:e.atMs,v:e.gc}))}],[t,r,a,c]),stacked:!0,height:Qt,formatValue:e=>o(e),axisFor:()=>({floor:25}),emptyMessage:s})}function Q({title:e,points:t,formatValue:r,emptyMessage:a,axisFloor:o,axisScale:s=`linear`,gapMs:c}){return i(Fe,{title:e,series:n(()=>[{id:`value`,label:e,unit:s===`bytes`?`B`:null,colorIndex:0,gapMs:c,points:t.map(e=>({t:e.atMs,v:e.value}))}],[t,e,s,c]),height:Qt,formatValue:e=>r(e),axisFor:()=>({floor:o,scale:s}),emptyMessage:a})}function en(e,t){let n=e.at(-1);return n===void 0?[t]:t.atMs>n.atMs?[...e,t]:e.some(e=>e.atMs===t.atMs)?e:[...e,t].toSorted((e,t)=>e.atMs-t.atMs)}function tn(e,t,n,r){let i=e.get(t),a=en(i?.points??[],r);if(i!==void 0&&a===i.points)return e;let o=new Map(e);return o.set(t,{key:t,kind:n,points:a.slice(Math.max(0,a.length-720))}),o}function nn(e,t,n){let r=e;for(let e of re(t,n))r=tn(r,e.key,e.kind,e.point);return r}function rn(e,t){let n=e;for(let e of t)for(let t of e.points)n=tn(n,e.key,e.kind,t);return n}function an(e){let t=null;for(let n of e.values()){let e=n.points.at(-1);e!==void 0&&(t===null||e.atMs>t)&&(t=e.atMs)}return t}var on=12e4;function sn(e,t){return e===null?!1:t-e>on}function cn(e){let t=e=>{let t=e.points.at(-1);return t===void 0?-1:t.cpuMainPercent!==null&&t.cpuGcPercent!==null?t.cpuMainPercent+t.cpuGcPercent:t.cpuLifetimePercent};return[...e.values()].toSorted((e,n)=>{let r=t(n)-t(e);return r===0?e.key.localeCompare(n.key):r})}function ln(e){for(let t of e.values()){let e=t.points.at(-1);if(e&&e.cpuMainPercent!==null)return!0}return!1}var un={key:`cpu`,dir:`desc`};function dn(e){let t=e.points.at(-1);return t===void 0?null:t.cpuMainPercent!==null&&t.cpuGcPercent!==null?t.cpuMainPercent+t.cpuGcPercent:t.cpuLifetimePercent}function fn(e){return e.points.at(-1)?.memoryRssBytes??null}function pn(e,t,n){let r=n.trim().toLowerCase();return r===``?!0:e.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function mn(e,t){return t===`memory`?fn(e):dn(e)}function hn(e,t,n){let r=e.filter(e=>t.selectedKeys.size>0&&!t.selectedKeys.has(e.key)?!1:pn(n(e),e.key,t.search)),i=(e,t)=>e.key.localeCompare(t.key);return[...r].toSorted((e,r)=>{if(t.sort.key===`name`){let a=n(e).localeCompare(n(r)),o=t.sort.dir===`asc`?a:-a;return o===0?i(e,r):o}let a=mn(e,t.sort.key),o=mn(r,t.sort.key);if(a===null&&o===null)return i(e,r);if(a===null)return 1;if(o===null)return-1;let s=t.sort.dir===`desc`?o-a:a-o;return s===0?i(e,r):s})}s();function gn(e,n=720){let r=B(`metrics.node-processes-snapshot`,t=>t.nodeId===e),[i,s]=o(new Map),[c,l]=o(void 0),u=t(null),{data:d,isPending:f}=ve({forNodeId:e,sinceMs:c,maxPoints:n});a(()=>{d!==void 0&&s(e=>{let t=rn(e,d.series);return u.current=an(t),t})},[d]);let p=r?.timestamp;a(()=>{r==null||p===void 0||(sn(u.current,p)&&l(u.current??0),s(e=>{let t=nn(e,r.processes,p);return u.current=an(t),t}))},[p]),a(()=>{s(new Map),l(void 0),u.current=null},[e]);let m=0;for(let e of i.values())m=Math.max(m,e.points.length);return{series:cn(i),sampleCount:m,threadSplitAvailable:ln(i),loadingRetained:f,durable:d?.durable??null,bucketMs:d?.bucketMs??null,cadenceMs:d?.cadenceMs??null,retainedSamples:d?.retainedSamples??null}}var _n=`__unclaimed__`;function vn(e,t){return{kind:e,deviceId:t,cpu:0,cpuKnown:!0,rss:0,rssKnown:!0,count:0,roles:new Set}}function yn(e,t){return{key:e,kind:t.kind,deviceId:t.deviceId,cpuSeconds:t.cpuKnown?Math.round(t.cpu*100)/100:null,rssBytes:t.rssKnown?t.rss:null,unitCount:t.count,roles:[...t.roles].sort()}}function bn(e,t){let n=new Map,r=new Set;for(let t of e){t.pid!==void 0&&r.add(t.pid);let e=t.deviceId!==null&&t.attribution!==`unattributable`,i=e?`device:${t.deviceId}`:`shared:${t.role}`,a=n.get(i)??vn(e?`camera`:`shared`,e?t.deviceId:null);a.count+=1,a.roles.add(t.role),t.cpuSeconds===void 0?a.cpuKnown=!1:a.cpu+=t.cpuSeconds,t.rssBytes===void 0?a.rssKnown=!1:a.rss+=t.rssBytes,n.set(i,a)}let i=[...n.entries()].map(([e,t])=>yn(e,t));if(t===void 0)return i;let a=t.filter(e=>!r.has(e.pid));if(a.length===0)return i;let o=vn(`unclaimed`,null);for(let e of a)o.count+=1,o.rss+=e.memoryRssBytes;return o.cpuKnown=!1,[...i,yn(_n,o)]}var xn=[{family:`decode`,attribution:`measured`,unit:`one forked decode-worker child per decode SESSION`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/session-decode/fork-decode-worker.ts:118`,`packages/addon-pipeline/src/session-decode/fork-decode-worker.ts:131`,`packages/addon-pipeline/src/pipeline-runner/index.ts:2765`,`packages/types/src/process/child-cost-registry.ts:188`]},{family:`transcode`,attribution:`measured`,unit:`one ffmpeg child per (camera, encode plan)`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/stream-broker/stream-broker/egress-transcode-manager.ts:960`,`packages/addon-pipeline/src/stream-broker/stream-broker/transcode-egress.ts:282`,`packages/addon-pipeline/src/stream-broker/stream-broker/transcode-egress.ts:324`,`packages/types/src/ffmpeg/sharing-key.ts:139`]},{family:`recording`,attribution:`measured`,unit:`one passthrough ffmpeg per (camera, profile)`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:33`,`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:217`,`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:279`,`packages/addon-pipeline/src/recorder/addon/recording-controller.ts:1710`]},{family:`detection`,attribution:`accounted`,unit:`a SHARED inference pool per (node, runtime, device) — no per-camera process`,perCamera:!1,wiredToday:!0,missingLink:"Nothing is missing for COUNTING — per-camera inference milliseconds, processed/shed frames and bytes-to-pool are already accumulated. What is missing is any basis for CPU seconds: `deviceId` reaches the pool as a diagnostic label and selects nothing, so cost can only ever be apportioned, never measured. Since 2026-08-27 the pool DECLARES this itself, contributing `deviceId: null` + `attribution: unattributable` rather than leaving an observer to infer it — the renunciation is data, and it is still refused by the chart gate.",evidence:[`packages/addon-pipeline/src/detection-pipeline/provider.ts:540`,`packages/addon-pipeline/src/detection-pipeline/engine/shared-inference-pool.ts:413`,`packages/types/src/interfaces/inference-engine.ts:24`,`packages/addon-pipeline/src/pipeline-runner/timing-sampler.ts:63`,`packages/addon-pipeline/src/pipeline-runner/runner.ts:353`,`packages/addon-pipeline/src/pipeline-runner/runner.ts:849`,`packages/addon-pipeline/src/pipeline-runner/frame-lazy-metrics.ts:100`]},{family:`streaming`,attribution:`measured`,unit:"one StreamBroker per `${deviceId}/${camStreamId}`, with an exact RTP ring byte counter",perCamera:!0,wiredToday:!1,missingLink:"The ffmpeg-backed ingest is now reported per camera, but that is the minority path. `rtpRingBytes` — the exact figure for the in-process case — is maintained on every push and drop and is still private and absent from `getStats()`. The three `EncodedRingBuffer`s track packets and duration and have no byte accumulator at all; the only byte figure they offer is `preRollBudgetBytes`, which is a BUDGET, not an occupancy.",evidence:[`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:2895`,`packages/addon-pipeline/src/stream-broker/rtsp/ffmpeg-push-reader.ts:189`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:494`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:498`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:2505`,`packages/addon-pipeline/src/stream-broker/stream-broker/pre-roll.ts:269`]}];function Sn(e){return e.attribution===`measured`&&e.wiredToday}function Cn(){let e=new Set;for(let t of xn)Sn(t)&&e.add(t.family);return e}var wn=Cn();function Tn(e){return!wn.has(e.role)||e.deviceId===null?!1:e.attribution===`measured`}function En(e){return`${e.addonId}${e.role}${e.unit}${e.pid??`-`}`}function Dn(){return{cpuSeconds:0,cpuKnown:!0,rssBytes:0,rssKnown:!0,unitCount:0,roles:new Set}}function On(e,t,n){if(t.cpuSeconds===void 0)return null;if(e===void 0)return t.startedAtMs===void 0||t.startedAtMs<n?null:t.cpuSeconds;if(e.cpuSeconds===void 0||e.startedAtMs===void 0||t.startedAtMs===void 0||e.startedAtMs!==t.startedAtMs)return null;let r=t.cpuSeconds-e.cpuSeconds;return r<0?null:r}function kn(e){return Math.round(e*10)/10}function An(e,t){let n=t.atMs-e.atMs;if(n<=0)return[];let r=n/1e3,i=new Map;for(let t of e.entries)Tn(t)&&i.set(En(t),t);let a=new Map,o=new Set;for(let n of t.entries){if(!Tn(n)||n.deviceId===null)continue;let t=En(n);o.add(t);let r=a.get(n.deviceId)??Dn();r.unitCount+=1,r.roles.add(n.role);let s=On(i.get(t),n,e.atMs);s===null?r.cpuKnown=!1:r.cpuSeconds+=s,n.rssBytes===void 0?r.rssKnown=!1:r.rssBytes+=n.rssBytes,a.set(n.deviceId,r)}for(let[e,t]of i){if(o.has(e)||t.deviceId===null)continue;let n=a.get(t.deviceId);n!==void 0&&(n.cpuKnown=!1)}return[...a.entries()].map(([e,n])=>({deviceId:e,point:{atMs:t.atMs,cpuPercent:n.cpuKnown?kn(n.cpuSeconds/r*100):null,rssBytes:n.rssKnown?n.rssBytes:null,unitCount:n.unitCount,roles:[...n.roles].toSorted()}}))}function jn(e,t){if(t.length===0)return e;let n=new Map(e);for(let e of t){let t=n.get(e.deviceId),r=t?.points.at(-1);if(r!==void 0&&e.point.atMs<=r.atMs)continue;let i=[...t?.points??[],e.point];n.set(e.deviceId,{deviceId:e.deviceId,points:i.slice(Math.max(0,i.length-720))})}return n}function Mn(e){let t=e=>{for(let t=e.points.length-1;t>=0;t--){let n=e.points[t]?.cpuPercent;if(n!=null)return n}return-1};return[...e.values()].toSorted((e,n)=>{let r=t(n)-t(e);return r===0?e.deviceId-n.deviceId:r})}function Nn(e){let t=e.indexOf(`@`);return t===-1?{addonId:e,nodeId:null}:{addonId:e.slice(0,t),nodeId:e.slice(t+1)}}function Pn(e,t){let n=Nn(e);return n.nodeId===null?t.isHub:n.nodeId===t.nodeId}function Fn(e,t){return e.filter(e=>Pn(e.addonId,t))}s();function In(e){let n=B(`metrics.node-processes-snapshot`,t=>t.nodeId===e.nodeId),r=qe(void 0,{staleTime:1/0,refetchOnWindowFocus:!1}),[i,s]=o(new Map),c=t(null),l=t(r.refetch);l.current=r.refetch;let u=n?.timestamp;a(()=>{u!==void 0&&l.current()},[u]),a(()=>{s(new Map),c.current=null},[e.nodeId,e.isHub]);let d=r.data,f=r.dataUpdatedAt;a(()=>{if(d===void 0||f===0)return;let t={atMs:f,entries:Fn(d,e)},n=c.current;if(c.current=t,n===null)return;let r=An(n,t);r.length!==0&&s(e=>jn(e,r))},[d,f,e.nodeId,e.isHub]);let p=d===void 0?[]:Fn(d,e),m=n?.processes,h=bn(p,m);return{series:Mn(i),unclaimed:h.find(e=>e.kind===`unclaimed`)??null,loading:r.isPending,error:r.error===null?null:r.error.message}}function Ln(e){let t=new Map;for(let n of e){let e=n.name?.trim();e===void 0||e===``||t.set(n.id,e)}return t}var Rn=25,zn=64*1024*1024,Bn=1e4;function Vn({scope:t,cadenceMs:n}){let{t:r}=q(),a=In(t),{data:o=[]}=_e({isCamera:!0,projection:`slim`}),s=Ln(o),c=xe(n??Bn);return e(`section`,{className:`space-y-3`,children:[a.error!==null&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-[11px] text-destructive`,children:[i(T,{className:`h-3 w-3 mt-0.5 shrink-0`}),i(`span`,{children:r(`cameraLoad.readFailed`,`Could not read the load contributions: {{error}}. This is a failed read, NOT an idle cluster.`,{error:a.error})})]}),i(Un,{unclaimed:a.unclaimed}),a.series.length===0&&a.error===null&&i(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:a.loading?r(`cameraLoad.loading`,`Reading what the addons report…`):r(`cameraLoad.waitingWindow`,`No per-camera window yet.`)}),i(`div`,{className:`space-y-3`,children:a.series.map(t=>e(`div`,{className:`rounded-lg border border-border p-3`,children:[e(`div`,{className:`flex items-baseline justify-between gap-2 mb-2`,children:[i(Hn,{deviceId:t.deviceId,name:s.get(t.deviceId)}),i(`span`,{className:`text-[10px] text-foreground-subtle`,children:r(`cameraLoad.unitCount`,`{{count}} unit(s): {{roles}}`,{count:t.points.at(-1)?.unitCount??0,roles:(t.points.at(-1)?.roles??[]).join(`, `)})})]}),e(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[i(Q,{title:r(`cameraLoad.cpuTitle`,`CPU % of one core (delta)`),points:t.points.map(e=>({atMs:e.atMs,value:e.cpuPercent})),formatValue:e=>`${e.toFixed(1)}%`,axisFloor:Rn,gapMs:c,emptyMessage:r(`cameraLoad.cpuUnavailable`,`No measurable window yet.`)}),i(Q,{title:r(`cameraLoad.memoryTitle`,`Memory RSS`),points:t.points.map(e=>({atMs:e.atMs,value:e.rssBytes})),formatValue:J,axisFloor:zn,axisScale:`bytes`,gapMs:c,emptyMessage:r(`cameraLoad.memoryUnavailable`,`No memory reported.`)})]})]},t.deviceId))})]})}function Hn({deviceId:t,name:n}){let{t:r}=q();return n===void 0?i(`span`,{className:`text-xs font-medium text-foreground`,children:r(`cameraLoad.deviceLabel`,`Camera {{deviceId}}`,{deviceId:t})}):e(`span`,{className:`flex items-baseline gap-1.5 min-w-0`,children:[i(`span`,{className:`text-xs font-medium text-foreground truncate`,children:n}),e(`span`,{className:`shrink-0 text-[10px] font-mono text-foreground-subtle`,children:[`#`,t]})]})}function Un({unclaimed:e}){let{t}=q();return e===null||e.unitCount===0?null:i(`div`,{className:`flex items-center gap-2`,children:i(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded-full bg-warning/10 text-warning font-medium tabular-nums`,children:t(`cameraLoad.unclaimedBadge`,`{{count}} unclaimed · {{rss}}`,{count:e.unitCount,rss:e.rssBytes===null?`—`:J(e.rssBytes)})})})}s();var Wn=256*1024*1024,Gn=1e4;function Kn({nodeId:r,isHub:a}){let s=t(null);We(s);let{t:c}=q(),{series:l,sampleCount:u,threadSplitAvailable:d,loadingRetained:p,bucketMs:m,cadenceMs:h}=gn(r),[g,_]=o(``),[v,y]=o(new Set),[b,x]=o(un),S=e=>e.key===`__root__`?c(`clusterLoad.bucketRoot`,`Node supervisor`):e.key===`__unattributed__`?c(`clusterLoad.bucketUnattributed`,`Unattributed processes`):e.key,C=xe(m??h??Gn),w=n(()=>hn(l,{search:g,selectedKeys:v,sort:b},S),[l,g,v,b]),E=e=>{y(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return e(`div`,{className:`space-y-4`,children:[i(qn,{bucketMs:m,cadenceMs:h}),!d&&u>0&&e(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/5 px-3 py-2 text-[11px] text-warning`,children:[i(T,{className:`h-3 w-3 mt-0.5 shrink-0`}),i(`span`,{children:c(`clusterLoad.noThreadSplit`,`No thread-level CPU split on this node — /proc/<pid>/task is Linux-only, and the first sample after a restart has no window to measure. CPU below falls back to the ps lifetime AVERAGE, which is not a rate.`)})]}),u===0&&i(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:p?c(`clusterLoad.loadingRetained`,`Reading the retained series from this node…`):c(`clusterLoad.waitingFirstSample`,`No retained samples for this node — waiting for the next snapshot (up to 20s). The chart needs two to draw a rate.`)}),l.length>0&&e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(`label`,{className:`relative flex-1 min-w-[160px]`,children:[i(f,{className:`pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-foreground-subtle`}),i(U,{ref:s,type:`search`,value:g,onChange:e=>_(e.target.value),placeholder:c(`clusterLoad.searchPlaceholder`,`Find a runner…`),"aria-label":c(`clusterLoad.searchLabel`,`Find a runner`),className:`w-full rounded border border-border bg-background py-1 pl-7 pr-2 text-[11px] text-foreground placeholder:text-foreground-subtle`})]}),i(Jn,{sort:b,onChange:x})]}),e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[l.map(e=>{let t=v.has(e.key);return i(W,{variant:`unstyled`,type:`button`,"aria-pressed":t,onClick:()=>E(e.key),className:`rounded-full border px-2 py-0.5 text-[10px] transition-colors ${t?`border-primary bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground`}`,children:S(e)},e.key)}),v.size>0&&e(W,{variant:`unstyled`,type:`button`,onClick:()=>y(new Set),className:`inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-subtle hover:text-foreground`,children:[i(O,{className:`h-2.5 w-2.5`}),c(`clusterLoad.clearFilter`,`All runners`)]})]})]}),l.length>0&&w.length===0&&i(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:c(`clusterLoad.noMatches`,`No runner matches this search on {{count}} present. The node is reporting — the filter is hiding them.`,{count:l.length})}),i(`div`,{className:`space-y-3`,children:w.map(t=>e(`div`,{className:`rounded-lg border border-border p-3`,children:[e(`div`,{className:`flex items-baseline justify-between gap-2 mb-2`,children:[i(`span`,{className:`text-xs font-medium text-foreground`,children:S(t)}),i(`span`,{className:`text-[10px] text-foreground-subtle`,children:c(`clusterLoad.processCount`,`{{count}} process(es)`,{count:t.points.at(-1)?.processCount??0})})]}),e(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[i($t,{title:d?c(`clusterLoad.cpuTitle`,`CPU % of one core`):c(`clusterLoad.cpuTitleLifetime`,`CPU % (ps lifetime average)`),mainLabel:c(`clusterLoad.seriesMain`,`Main threads`),gcLabel:c(`clusterLoad.seriesGc`,`GC / V8 helpers`),points:t.points.map(e=>({atMs:e.atMs,main:e.cpuMainPercent,gc:e.cpuGcPercent})),formatValue:e=>`${e.toFixed(0)}%`,gapMs:C,emptyMessage:c(`clusterLoad.cpuUnavailable`,`No thread split on this node. Lifetime average: {{avg}}%`,{avg:(t.points.at(-1)?.cpuLifetimePercent??0).toFixed(1)})}),i(Q,{title:c(`clusterLoad.memoryTitle`,`Memory RSS`),points:t.points.map(e=>({atMs:e.atMs,value:e.memoryRssBytes})),formatValue:J,axisFloor:Wn,axisScale:`bytes`,gapMs:C,emptyMessage:c(`clusterLoad.memoryUnavailable`,`No memory samples yet.`)})]})]},t.key))}),i(Vn,{scope:{nodeId:r,isHub:a},cadenceMs:h})]})}function qn({bucketMs:e,cadenceMs:t}){let{t:n}=q();return e===null?null:i(`p`,{className:`text-[10px] text-foreground-subtle`,children:t!==null&&e>t?n(`clusterLoad.captionBucket`,`1 point = {{bucket}}s (bucket MAXIMUM, not a mean)`,{bucket:Math.round(e/1e3)}):n(`clusterLoad.captionRaw`,`1 point = 1 snapshot`)})}function Jn({sort:t,onChange:n}){let{t:r}=q(),a=[{key:`cpu`,label:r(`clusterLoad.sortCpu`,`CPU`)},{key:`memory`,label:r(`clusterLoad.sortMemory`,`Memory`)},{key:`name`,label:r(`clusterLoad.sortName`,`Name`)}];return e(`div`,{className:`flex items-center gap-1`,children:[i(`span`,{className:`text-[10px] text-foreground-subtle`,children:r(`clusterLoad.sortBy`,`Sort by`)}),a.map(r=>{let i=t.key===r.key;return e(W,{variant:`unstyled`,type:`button`,"aria-pressed":i,onClick:()=>n(i?{key:r.key,dir:t.dir===`desc`?`asc`:`desc`}:{key:r.key,dir:r.key===`name`?`asc`:`desc`}),className:`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${i?`border-primary bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground`}`,children:[r.label,i&&(t.dir===`desc`?` ↓`:` ↑`)]},r.key)})]})}var Yn=`No per-node settings on this node. Every other setting these addons expose is one value for the whole cluster — edit those in System → Settings, not here.`;function Xn({nodeId:e,addonIds:t}){let{t:n}=q();return t.length===0?i(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:n(`cluster.nodeDetailSettingsTab.noAddonsOnThisNode`,`No addons on this node`)}):i(`div`,{className:`w-full py-2`,children:i(tt,{nodeId:e,addonIds:t,level:`global`,fieldScope:`perNode`,emptyMessage:Yn,selfTabbed:!0})})}s();function Zn({nodeId:e,addons:t}){let{t:r}=q(),a=c(),{data:o,isLoading:s}=fe({nodeId:e}),l=n(()=>{let e=new Map;for(let n of t)for(let t of n.capabilities){let r=e.get(t)??[];r.push(n.id),e.set(t,r)}return[...e.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({capName:e,providers:t}))},[t]),u=Re({onSuccess:()=>{a.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCapabilityBindings`]]})}});return l.length===0?i(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:r(`cluster.nodeDetailCapabilitiesTab.noCapabilitiesOnThisNode`,`No capabilities on this node`)}):i(G,{columns:[{key:`capName`,header:r(`cluster.nodeDetailCapabilitiesTab.capability`,`Capability`),width:`w-1/2`,sortValue:e=>e.capName,render:e=>i(`span`,{className:`font-medium`,children:e.capName})},{key:`provider`,header:r(`cluster.nodeDetailCapabilitiesTab.boundProvider`,`Bound provider`),render:t=>{let n=o?.[t.capName]??t.providers[0]??``,a=t.providers.length===1;return i(P,{value:n,onChange:n=>u.mutate({nodeId:e,capName:t.capName,addonId:n.target.value}),disabled:a||u.isPending||s,className:`w-full`,title:a?r(`cluster.nodeDetailCapabilitiesTab.onlyOneProviderInstalledChoice`,`Only one provider installed — choice becomes available once a second addon registers this capability`):void 0,children:t.providers.map(e=>i(`option`,{value:e,children:e},e))})}}],rows:l,rowKey:e=>e.capName,minWidthPx:520,maxBodyHeight:le})}s();function Qn(e){if(e==null)return`—`;let t=Math.floor(e/1e3),n=Math.floor(t/86400),r=Math.floor(t%86400/3600),i=Math.floor(t%3600/60);return n>0?`${n}d ${r}h ${i}m`:r>0?`${r}h ${i}m`:`${i}m`}function $n(t){let{t:n}=q(),[r,a]=o(!1),[s,l]=o(t.name),u=c(),d=Ne({onSuccess:()=>{u.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}}),f=(t.localIps??[]).filter(e=>!e.includes(`:`)),p=(t.localIps??[]).filter(e=>e.includes(`:`)),m=async()=>{if(!s.trim()||s===t.name){a(!1);return}try{await d.mutateAsync({nodeId:t.nodeId,name:s.trim()}),a(!1)}catch(e){console.error(`Rename failed:`,e)}},h=[[`Node ID`,i(`span`,{className:`font-mono text-xs`,children:t.nodeId})],[`Display Name`,r?e(`div`,{className:`flex items-center gap-1.5`,children:[i(U,{type:`text`,className:`flex-1 px-2 py-0.5 text-xs border border-border rounded bg-background focus:outline-none focus:ring-1 focus:ring-primary`,value:s,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&m(),e.key===`Escape`&&a(!1)},disabled:d.isPending,autoFocus:!0}),i(W,{variant:`unstyled`,onClick:()=>void m(),disabled:d.isPending,className:`p-0.5 text-success hover:bg-success/10 rounded`,title:n(`common.save`,`Save`),children:i(v,{className:`h-3.5 w-3.5`})}),i(W,{variant:`unstyled`,onClick:()=>a(!1),className:`p-0.5 text-muted-foreground hover:bg-muted rounded`,title:n(`common.cancel`,`Cancel`),children:i(O,{className:`h-3.5 w-3.5`})})]}):e(`div`,{className:`flex items-center gap-1.5`,children:[i(`span`,{className:`text-xs`,children:t.name}),!t.isHub&&i(W,{variant:`unstyled`,onClick:()=>{l(t.name),a(!0)},className:`p-0.5 text-muted-foreground hover:text-primary rounded`,title:n(`cluster.nodeInfoTab.rename`,`Rename`),children:i(E,{className:`h-3 w-3`})})]})],[`Hostname`,i(`span`,{className:`text-xs`,children:t.hostname})],[`Role`,t.isHub?i(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium`,children:n(`cluster.nodeInfoTab.hub`,`Hub`)}):i(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground font-medium`,children:n(`cluster.nodeInfoTab.agent`,`Agent`)})],[`Root Package`,t.rootPackage?e(`span`,{className:`font-mono text-xs`,children:[t.rootPackage.name,`@`,t.rootPackage.version]}):i(`span`,{className:`text-xs text-muted-foreground`,children:`—`})],[`Platform`,e(`span`,{className:`text-xs`,children:[t.platform,` / `,t.arch]})],[`CPU`,e(`span`,{className:`text-xs`,children:[t.cpuModel??`—`,` (`,n(`cluster.nodeInfoTab.cores`,{count:t.cpuCores}),`)`]})],[`Memory`,i(`span`,{className:`text-xs`,children:t.memoryMB>0?n(`cluster.nodeInfoTab.gb`,`{{value1}} GB`,{value1:(t.memoryMB/1024).toFixed(1)}):`—`})],[`Uptime`,i(`span`,{className:`text-xs`,children:Qn(t.uptime)})],[n(`cluster.nodeInfoTab.installedRuntimes`,`Installed runtimes`),t.engines.length>0?i(`div`,{className:`flex flex-wrap gap-1`,title:n(`cluster.nodeInfoTab.installedRuntimesHint`,`Inference runtimes installed on this node. Its live inference devices are on Pipeline → Load balancing.`),children:t.engines.map(e=>i(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:e},e))}):i(`span`,{className:`text-xs text-muted-foreground`,children:`—`})]];return f.length>0&&h.push([`IPv4`,i(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map((e,t)=>i(`span`,{className:`font-mono text-xs px-1.5 py-0.5 rounded bg-muted`,children:e},`${e}-${t}`))})]),p.length>0&&h.push([`IPv6`,i(`div`,{className:`flex flex-wrap gap-1.5`,children:p.map((e,t)=>i(`span`,{className:`font-mono text-[10px] px-1.5 py-0.5 rounded bg-muted truncate max-w-[280px]`,title:e,children:e},`${e}-${t}`))})]),i(`div`,{className:`py-2`,children:i(`table`,{className:`w-full text-sm`,children:i(`tbody`,{children:h.map(([t,n],r)=>e(`tr`,{className:r%2==0?`bg-muted/20`:``,children:[i(`td`,{className:`py-1.5 px-2 text-xs font-medium text-muted-foreground w-28 align-top whitespace-nowrap`,children:t}),i(`td`,{className:`py-1.5 px-2`,children:n})]},t))})})})}s();function er({nodeId:t,value:n,detectedHosts:r,status:s,errorMessage:c,onCommit:l}){let{t:u}=q(),[d,f]=o(n??``);a(()=>{f(n??``)},[n]);let p=r[0],m=p===void 0?`auto-detect`:`auto: ${p}`,h=s===`pending`,g=d.trim(),_=g!==(n??``),y=_&&!h,b=()=>{y&&l(t,g.length>0?g:null)};return e(`div`,{className:`flex items-center gap-1.5`,children:[i(U,{"aria-label":u(`placementBoard.reachableHostInput.reachableHostFor`,`Reachable host for {{nodeId}}`,{nodeId:t}),type:`text`,inputMode:`url`,autoComplete:`off`,spellCheck:!1,placeholder:m,value:d,disabled:h,onChange:e=>f(e.target.value),onBlur:b,onKeyDown:e=>{e.key===`Enter`&&b(),e.key===`Escape`&&f(n??``)},className:`w-36`}),e(W,{variant:`outline`,size:`sm`,onClick:b,disabled:!y,"aria-label":u(`placementBoard.reachableHostInput.saveReachableHostFor`,`Save reachable host for {{nodeId}}`,{nodeId:t}),title:u(`placementBoard.reachableHostInput.saveReachableHost`,`Save reachable host`),children:[h?i(D,{className:`h-3 w-3 animate-spin`,"aria-hidden":`true`}):i(v,{className:`h-3 w-3`,"aria-hidden":`true`}),u(`common.save`,`Save`)]}),!_&&!h&&s===`success`&&i(v,{className:`h-3.5 w-3.5 shrink-0 text-success`,"aria-label":u(`placementBoard.reachableHostInput.saved`,`Saved`),role:`img`}),s===`error`&&i(`span`,{title:c??u(`placementBoard.reachableHostInput.failedToSaveReachableHost`,`Failed to save reachable host`),children:i(N,{className:`h-3.5 w-3.5 shrink-0 text-danger`,"aria-label":c??u(`placementBoard.reachableHostInput.failedToSaveReachableHost`,`Failed to save reachable host`),role:`img`})})]})}s();function tr(e){let t=ne.safeParse(it(e,`color`));return t.success?t.data:null}function nr(e,t){return t.variables?.agentNodeId===e?t.isPending?`pending`:t.isError?`error`:t.isSuccess?`success`:`idle`:`idle`}function rr({nodeId:t,detectedHosts:r}){let{t:a}=q(),o=c(),s=me(void 0),l=Le({onSuccess:()=>rt(o)}),u=Le({onSuccess:()=>rt(o)}),d=n(()=>s.data?.find(e=>e.nodeId===t)?.settings,[s.data,t]),f=tr(d)??(s.isLoading?null:ie(t)),p=nt(d,`reachableHost`),m=nr(t,l),h=m===`error`?at(l.error):null,g=r.filter(e=>!e.includes(`:`)),_=e=>{e!==f&&u.mutate({agentNodeId:t,color:e})};return e(`div`,{className:`rounded-lg border border-border bg-surface/40 divide-y divide-border px-3`,children:[i(V,{label:a(`nodes.general.nodeColour`,`Node colour`),children:i(`div`,{role:`group`,"aria-label":a(`nodes.general.nodeColourGroup`,`Node colour`),className:`flex flex-wrap gap-2`,children:te.map(e=>{let t=f===e;return i(W,{type:`button`,role:`radio`,"aria-checked":t,"aria-label":e,variant:`outline`,size:`sm`,disabled:s.isLoading||u.isPending,title:e,onClick:()=>_(e),className:`h-6 w-6 min-w-6 shrink-0 rounded-full border-0 p-0 ${we(e)} ${t?`ring-2 ring-primary ring-offset-2 ring-offset-background`:`opacity-80 hover:opacity-100`}`,children:i(`span`,{className:`sr-only`,children:e})},e)})})}),i(V,{label:a(`nodes.general.reachableHost`,`Reachable host`),children:i(er,{nodeId:t,value:p,detectedHosts:g,status:m,errorMessage:h,onCommit:(e,t)=>{l.mutate({agentNodeId:e,reachableHost:t})}})})]})}s();var ir=512,ar=65536,or=[[`serverManagement`,`getLaunchOverrides`]];function sr(e){let t=e.trim();if(t===``)return null;if(!/^[0-9]+$/.test(t))return;let n=Number(t);return n>=ir&&n<=ar?n:void 0}var cr=e=>e==null?``:String(e);function lr({node:t}){let{t:n}=q(),r=c(),s=t.isHub?void 0:{nodeId:t.id},l=Ve(s,{enabled:t.isOnline,retry:1}),u=ce({onSuccess:()=>{r.invalidateQueries({queryKey:or})}}),[d,f]=o(``),[p,m]=o(``),[h,g]=o(null),_=l.data;a(()=>{_!==void 0&&(f(cr(_.heapMb)),m(cr(_.rssBudgetMb)))},[_]);let v=async()=>{let e=sr(d),r=t.isHub?sr(p):null;if(e===void 0||r===void 0){g(n(`nodes.launch.invalid`,`Enter a whole number between {{min}} and {{max}} MB, or leave the field empty.`,{min:ir,max:ar}));return}g(null);try{g((await u.mutateAsync({...s,heapMb:e,...t.isHub?{rssBudgetMb:r}:{}})).restartRequired?n(`nodes.launch.saved`,`Saved. Takes effect on restart.`):n(`nodes.launch.savedNow`,`Saved.`))}catch(e){g(e instanceof Error?e.message:n(`nodes.launch.failed`,`Save failed.`))}};return e(`div`,{className:`rounded-lg border border-border bg-surface/40 divide-y divide-border px-3`,children:[i(V,{label:n(`nodes.launch.heap`,`Heap ceiling (MB)`),children:i(U,{type:`number`,inputMode:`numeric`,"aria-label":n(`nodes.launch.heap`,`Heap ceiling (MB)`),placeholder:n(`nodes.launch.default`,`Default`),value:d,onChange:e=>f(e.target.value),disabled:!t.isOnline||l.isLoading})}),t.isHub&&i(V,{label:n(`nodes.launch.rss`,`RSS budget (MB)`),children:i(U,{type:`number`,inputMode:`numeric`,"aria-label":n(`nodes.launch.rss`,`RSS budget (MB)`),placeholder:n(`nodes.launch.default`,`Default`),value:p,onChange:e=>m(e.target.value),disabled:!t.isOnline||l.isLoading})}),i(V,{label:n(`nodes.launch.restartNote`,`Takes effect on restart`),actions:i(W,{type:`button`,size:`sm`,onClick:()=>void v(),disabled:!t.isOnline||u.isPending,children:n(`common.save`,`Save`)}),children:h??``})]})}s();var ur=3*6e4,dr={neutral:`bg-surface-muted text-foreground-subtle`,ok:`bg-success/15 text-success`,info:`bg-info/15 text-info`,warn:`bg-warning/15 text-warning`,error:`bg-danger/15 text-danger`};function fr({desktopApp:t,nodeName:n,routingInput:s,onSettled:c}){let{t:l}=q(),u=k(),f=He({onSettled:c}),[p,m]=o(null),[h,g]=o(!1),[_,v]=o(null);a(()=>{p!=null&&t.version!==p.fromVersion&&(m(null),g(!1))},[t.version,p]),a(()=>{if(p==null)return;let e=Math.max(0,p.startedAtMs+ur-Date.now()),t=setTimeout(()=>g(!0),e);return()=>clearTimeout(t)},[p]);let y=r(e=>{switch(e){case`not-electron`:return l(`serverManagement.desktopRefusedNotElectron`,`This node does not run inside the desktop app.`);case`no-app-state`:return l(`serverManagement.desktopRefusedNoState`,`The desktop app has not reported its state yet.`);case`app-state-stale`:return l(`serverManagement.desktopRefusedStale`,`The desktop app stopped reporting — it is probably not running.`);case`not-downloaded`:return l(`serverManagement.desktopRefusedNotDownloaded`,`No update is downloaded yet.`)}},[l]),b=r(async()=>{if(await u({title:l(`serverManagement.desktopConfirmTitle`,`Install desktop app update`),message:l(`serverManagement.desktopConfirmBody`,`Install {{version}} on "{{node}}" and restart the desktop app? The node is offline while it restarts.`,{version:t.update.version??``,node:n}),confirmLabel:l(`serverManagement.desktopInstallAction`,`Install update & restart`),variant:`warning`})){v(null),g(!1);try{let e=await f.mutateAsync(s);e.accepted?m({fromVersion:t.version,startedAtMs:Date.now()}):e.reason!=null&&v(y(e.reason))}catch(e){v(e instanceof Error?e.message:String(e))}}},[u,t,f,n,y,s,l]),x=p!=null&&!h,{update:S}=t,C=null;t.stale?C={label:l(`serverManagement.desktopStale`,`app state unknown (last seen {{when}})`,{when:$e(t.stateAtMs)}),tone:`warn`}:S.downloaded?C={label:l(`serverManagement.desktopReady`,`update {{version}} ready`,{version:S.version??``}),tone:`ok`}:S.available?C={label:l(`serverManagement.desktopDownloading`,`update {{version}} available — downloading`,{version:S.version??``}),tone:`info`}:S.checking?C={label:l(`serverManagement.stateChecking`,`checking…`),tone:`info`}:S.error??(C={label:l(`serverManagement.stateUpToDate`,`up to date`),tone:`ok`});let w=!t.stale&&S.downloaded&&!x&&!f.isPending;return e(`div`,{className:`space-y-1.5`,children:[e(`div`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-1 text-sm`,children:[e(`span`,{className:`inline-flex items-baseline gap-1`,children:[i(`span`,{className:`text-foreground-subtle`,children:l(`serverManagement.desktopApp`,`Desktop app`)}),i(`span`,{className:`font-mono text-foreground`,children:t.version})]}),C!=null&&i(`span`,{className:`inline-flex items-center rounded px-2 py-0.5 text-[11px] font-medium ${dr[C.tone]}`,children:C.label})]}),!t.stale&&S.error!=null&&i(`p`,{className:`text-xs text-danger`,children:l(`serverManagement.desktopUpdateError`,`Update check failed: {{error}}`,{error:S.error})}),w&&e(W,{size:`sm`,onClick:()=>void b(),children:[i(d,{className:`h-3.5 w-3.5`}),l(`serverManagement.desktopInstallAction`,`Install update & restart`)]}),(f.isPending||x)&&e(`div`,{className:`flex items-center gap-2 text-sm text-warning`,children:[i(D,{className:`h-4 w-4 animate-spin`}),l(`serverManagement.desktopRestarting`,`The desktop app is restarting to install the update…`)]}),p!=null&&h&&i(`p`,{role:`status`,className:`text-xs text-warning`,children:l(`serverManagement.desktopRestartTimeout`,`The desktop app has not come back with a new version after 3 minutes. Check the machine.`)}),_!=null&&i(`p`,{role:`status`,className:`text-xs text-warning`,children:_})]})}s();var pr=[[`serverManagement`,`getServerPackageStatus`]];function mr({label:e,tone:t}){return i(`span`,{className:`inline-flex items-center rounded px-2 py-0.5 text-[11px] font-medium ${{neutral:`bg-surface-muted text-foreground-subtle`,ok:`bg-success/15 text-success`,info:`bg-info/15 text-info`,warn:`bg-warning/15 text-warning`,error:`bg-danger/15 text-danger`}[t]}`,children:e})}function $({label:t,value:n}){return e(`div`,{className:`flex items-center justify-between gap-4 text-sm`,children:[i(`span`,{className:`text-foreground-subtle`,children:t}),i(`span`,{className:`font-mono text-foreground`,children:n??`—`})]})}function hr({runningVersion:t,latestVersion:n,seedVersion:r,nodeRuntimeVersion:a,labelRunning:o,labelLatest:s,labelSeed:c,labelRuntime:l}){return i(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-sm`,children:[{key:`running`,label:o,value:t},{key:`latest`,label:s,value:n},{key:`seed`,label:c,value:r},{key:`runtime`,label:l,value:a}].map(({key:t,label:n,value:r})=>e(`span`,{className:`inline-flex items-baseline gap-1`,children:[i(`span`,{className:`text-foreground-subtle`,children:n}),i(`span`,{className:`font-mono text-foreground`,children:r??`—`})]},t))})}var gr={ok:`border-success/40 bg-success/10 text-success`,warn:`border-warning/40 bg-warning/10 text-warning`,error:`border-danger/40 bg-danger/10 text-danger`};function _r(e){return e.outcome===`failed`?`error`:(e.outcome,e.accepted?`ok`:`warn`)}function vr(e,t){let n=t instanceof Error?t.message:String(t);return`${e(`serverManagement.outcomeDropped`,`The connection dropped and the result could not be confirmed. The node may be restarting — re-check the version above.`)} — ${n}`}function yr({node:t}){let{t:n}=q(),a=c(),s=k(),[l,u]=o(!1),[f,p]=o(null),m=t.isHub?void 0:{nodeId:t.id},h=Be(m,{refetchInterval:1e4,enabled:t.isOnline,retry:1}),g=h.data??null,_=r(()=>{a.invalidateQueries({queryKey:pr})},[a]),v=Se({onSettled:_}),y=Ke({onSettled:_}),b=je({onSettled:_}),x=r(async()=>{if(g?.latestVersion==null){p({tone:`warn`,text:n(`serverManagement.outcomeNoTarget`,`No target version is known for this node — run "Check for update" first.`)});return}if(await s({title:n(`serverManagement.confirmUpdateTitle`,`Update node root package`),message:n(`serverManagement.confirmUpdateBody`,`Install {{pkg}}@{{version}} on "{{node}}" and restart to apply.`,{pkg:g.packageName,version:g.latestVersion,node:t.name}),confirmLabel:n(`serverManagement.confirmUpdateAction`,`Update & restart`)})){p(null);try{let e=await y.mutateAsync({version:g.latestVersion,...m});p({tone:_r(e),text:e.message}),e.restarting&&u(!0)}catch(e){p({tone:`warn`,text:vr(n,e)})}}},[y,s,t.name,m,g,n]),C=r(async()=>{if(await s({title:n(`serverManagement.confirmRestartTitle`,`Restart node`),message:n(`serverManagement.confirmRestartBody`,`Restart "{{node}}"? In-flight requests to this node are dropped.`,{node:t.name}),confirmLabel:n(`serverManagement.confirmRestartAction`,`Restart`),variant:`warning`})){p(null);try{let e=await b.mutateAsync(m);p({tone:_r(e),text:e.message}),e.restarting&&u(!0)}catch(e){p({tone:`warn`,text:vr(n,e)})}}},[s,t.name,b,m,n]),w=()=>{switch(g?.bootMode){case`data-root`:return{label:n(`serverManagement.bootDataRoot`,`runtime-updatable`),tone:`ok`};case`workspace`:return{label:n(`serverManagement.bootWorkspace`,`dev workspace`),tone:`info`};default:return{label:n(`serverManagement.bootBaked`,`baked image seed`),tone:`neutral`}}},T=()=>{if(g==null)return null;switch(g.updateState){case`checking`:return{label:n(`serverManagement.stateChecking`,`checking…`),tone:`info`};case`staging`:return{label:n(`serverManagement.stateStaging`,`updating…`),tone:`info`};case`pending-restart`:return{label:n(`serverManagement.statePending`,`restart pending`),tone:`warn`};default:return g.restartRequired===!0?{label:n(`serverManagement.stateRestartRequired`,`restart required`),tone:`warn`}:g.updateAvailable?{label:n(`serverManagement.stateUpdateAvailable`,`update available`),tone:`warn`}:{label:n(`serverManagement.stateUpToDate`,`up to date`),tone:`ok`}}},E=g?.bootMode===`workspace`,O=t.isOnline&&g!=null&&!E&&g.updateAvailable&&g.updateState===`idle`&&!y.isPending,A=t.isOnline&&g!=null&&g.updateState===`idle`&&!b.isPending,M=t.isOnline?T():null;return e(`div`,{className:`space-y-4 py-2`,children:[e(`div`,{className:`flex items-center justify-between gap-3`,children:[e(`div`,{className:`flex items-center gap-2 min-w-0`,children:[i(`span`,{className:`font-mono text-xs text-foreground-subtle truncate`,children:g?.packageName??t.rootPackage?.name??`@camstack/server`}),t.isOnline&&g!=null&&i(mr,{...w()})]}),M!=null&&i(mr,{...M})]}),!t.isOnline&&i($,{label:n(`serverManagement.lastReportedVersion`,`Last reported version`),value:t.rootPackage?.version??null}),t.isOnline&&h.isLoading&&e(`div`,{className:`flex items-center gap-2 text-sm text-foreground-subtle`,children:[i(D,{className:`h-4 w-4 animate-spin`}),n(`common.loading`,`Loading…`)]}),t.isOnline&&h.isError&&e(`div`,{className:`space-y-1.5`,children:[i(`p`,{className:`text-sm text-danger`,children:n(`serverManagement.loadError`,`Could not load the node root-package status.`)}),t.rootPackage!=null&&i($,{label:n(`serverManagement.lastReportedVersion`,`Last reported version`),value:t.rootPackage.version})]}),t.isOnline&&g!=null&&e(`div`,{className:`space-y-1.5`,children:[i(hr,{runningVersion:g.runningVersion,latestVersion:g.latestVersion,seedVersion:g.seedVersion,nodeRuntimeVersion:g.nodeRuntimeVersion,labelRunning:n(`serverManagement.runningVersionShort`,`Running`),labelLatest:n(`serverManagement.latestVersionShort`,`Latest`),labelSeed:n(`serverManagement.imageSeedShort`,`Seed`),labelRuntime:n(`serverManagement.nodeRuntimeVersionShort`,`Node.js`)}),g.desktopApp!=null&&i(fr,{desktopApp:g.desktopApp,nodeName:t.name,routingInput:m,onSettled:_}),g.pendingVersion!=null&&i($,{label:n(`serverManagement.pendingVersion`,`Staged (applies on restart)`),value:g.pendingVersion}),g.installedVersion!=null&&g.installedVersion!==g.runningVersion&&i($,{label:n(`serverManagement.installedVersion`,`Installed on disk (runs after restart)`),value:g.installedVersion})]}),t.isOnline&&g?.imageContract?.state===`behind-series`&&e(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs leading-relaxed text-danger`,children:[i(`p`,{className:`mb-0.5 font-semibold`,children:n(`serverManagement.imageContractDiverged`,`Container image diverges from the deployment contract`)}),i(`p`,{children:g.imageContract.message})]}),t.isOnline&&E&&i(`p`,{className:`text-xs text-foreground-subtle`,children:n(`serverManagement.workspaceNote`,`Development workspace detected — runtime updates are disabled (the dev loop resolves code from the workspace).`)}),f!=null&&i(`p`,{role:`status`,className:`rounded border px-2 py-1.5 text-xs leading-relaxed ${gr[f.tone]}`,children:f.text}),l&&e(`div`,{className:`flex items-center gap-2 text-sm text-warning`,children:[i(D,{className:`h-4 w-4 animate-spin`}),n(`serverManagement.nodeRestarting`,`The node is restarting to apply the change…`)]}),t.isOnline&&e(`div`,{className:`flex flex-wrap items-center gap-2 pt-1`,children:[e(W,{variant:`unstyled`,type:`button`,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-surface-muted disabled:opacity-50`,disabled:v.isPending||g?.updateState===`staging`,onClick:()=>v.mutate(m),children:[v.isPending?i(D,{className:`h-3.5 w-3.5 animate-spin`}):i(S,{className:`h-3.5 w-3.5`}),n(`serverManagement.checkForUpdate`,`Check for update`)]}),O&&e(W,{variant:`unstyled`,type:`button`,className:`inline-flex items-center gap-1.5 rounded bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50`,onClick:()=>void x(),children:[y.isPending?i(D,{className:`h-3.5 w-3.5 animate-spin`}):i(j,{className:`h-3.5 w-3.5`}),n(`serverManagement.updateTo`,`Update to {{version}}`,{version:g?.latestVersion??``})]}),e(W,{variant:`unstyled`,type:`button`,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-surface-muted disabled:opacity-50`,disabled:!A,onClick:()=>void C(),children:[b.isPending?i(D,{className:`h-3.5 w-3.5 animate-spin`}):i(d,{className:`h-3.5 w-3.5`}),n(`serverManagement.restart`,`Restart`)]})]}),t.isOnline&&g?.lastCheckedAtMs!=null&&e(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(ae,{className:`h-3 w-3`}),n(`serverManagement.lastChecked`,`Last checked: {{when}}`,{when:new Date(g.lastCheckedAtMs).toLocaleString()})]})]})}s();function br(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`reachableHost`);return typeof t==`string`&&t.length>0?t:null}function xr({node:t}){let{t:a}=q(),s=M(),u=c(),d=k(),[f,p]=o(!1),[m,h]=o(`info`),[g,_]=o(!1),[v,b]=o(null),x=t.processes??[],S=t.addons.map(e=>e.id),C=me(void 0),w=n(()=>{let e=C.data?.find(e=>e.nodeId===t.id);return br(e?.settings)},[C.data,t.id]),[T,E]=o(!1),[D,O]=o(null),[j,N]=o(null),P=r(async()=>{if(T||t.isHub)return;let e=Lt(t.localIps??[],w);if(e===null){O(`No LAN IPv4 on this node — open its :4444 URL by hand.`),N(null);return}let n=Bt();E(!0),O(null),N(null);try{let r=Nt(await s.trpcClient.addons.custom.mutate({addonId:`system-config`,action:`mintAgentUiUnlockTicket`,input:{nodeId:t.id,dashboardBaseUrl:Rt(e)}})),i=r===null?null:r.dashboardUrl??zt(e,r.ticket);if(i===null){n?.close(),O(`Hub did not return an unlock ticket.`);return}Vt(n,i)||(N(i),O(`Browser blocked the new tab — click the link below (or allow popups for this site).`))}catch(e){n?.close(),O(e instanceof Error?e.message:String(e))}finally{E(!1)}},[t.id,t.isHub,t.localIps,T,w,s.trpcClient]),F=async()=>{if(!g){_(!0),b(null);try{await s.trpcClient.pipelineOrchestrator.removeAgentSettings.mutate({agentNodeId:t.id}).catch(()=>void 0);let e=await s.trpcClient.clusterNodes.forgetNode.mutate({nodeId:t.id});b({tone:e.stillListed?`warn`:`ok`,text:e.message}),e.stillListed||u.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}catch(e){b({tone:`warn`,text:a(`cluster.nodeCard.forgetFailed`,{error:e instanceof Error?e.message:String(e)})})}finally{_(!1)}}},I=async()=>{if(!f&&await d({title:a(`cluster.nodeCard.unpair`,`Unpair {{name}}`,{name:t.name}),message:a(`cluster.nodeCard.unpairItDisconnectsAndMust`,`Unpair {{name}}? It disconnects and must be paired again.`,{name:t.name}),confirmLabel:a(`cluster.nodeCard.unpair2`,`Unpair`),variant:`danger`})){p(!0),b(null);try{let e=await s.trpcClient.agentPairing.unpairAgent.mutate({nodeId:t.id});b({tone:e.agentNotified?`ok`:`warn`,text:`${e.nodeId}: ${e.next}${e.agentNotified?``:` The agent could not be told; forget the hub on its own page.`}`}),u.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}catch(e){b({tone:`warn`,text:a(`cluster.nodeCard.unpairFailed`,{error:e instanceof Error?e.message:String(e)})})}finally{p(!1)}}},L=t.isHub?null:e(W,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>void I(),disabled:f,title:a(`cluster.nodeCard.unpairThisNodeRevokesIts`,`Unpair this node — revokes its certificates; it must be paired again to rejoin`),children:[i(se,{className:`h-3 w-3`,"aria-hidden":!0}),f?a(`cluster.nodeCard.unpairing`,`Unpairing…`):a(`cluster.nodeCard.unpair2`,`Unpair`)]});return t.isOnline?e(`div`,{className:`border border-border rounded-xl`,children:[e(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3 bg-muted/30 border-b border-border rounded-t-xl`,children:[e(`div`,{className:`flex min-w-0 flex-1 basis-full items-center gap-x-2 gap-y-1 sm:basis-auto sm:flex-initial`,children:[i(`div`,{className:`w-2.5 h-2.5 rounded-full bg-success shrink-0`}),i(Ht,{node:t}),e(`span`,{className:`text-xs text-muted-foreground min-w-0 truncate`,children:[t.cpuModel??t.platform,` ·`,` `,t.memoryMB>0?a(`cluster.nodeCard.gb`,`{{value1}}GB`,{value1:Math.round(t.memoryMB/1024)}):``,` `,`· `,t.arch]})]}),t.engines.map(e=>i(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium shrink-0`,title:a(`cluster.nodeInfoTab.installedRuntimesHint`,`Inference runtimes installed on this node. Its live inference devices are on Pipeline → Load balancing.`),children:e},e)),e(`div`,{className:`flex min-w-0 flex-wrap items-center justify-end gap-x-3 gap-y-1 text-xs text-muted-foreground w-full sm:ml-auto sm:w-auto`,children:[!t.isHub&&e(W,{variant:`unstyled`,type:`button`,onClick:()=>void P(),disabled:T,title:a(`cluster.nodeCard.openThisAgentSStatus`,`Open this agent's status dashboard (unlocks with a short-lived hub ticket)`),className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-xs text-foreground hover:bg-surface-hover disabled:opacity-50`,children:[i(A,{className:`h-3 w-3`}),T?a(`cluster.nodeCard.opening`,`Opening…`):a(`cluster.nodeCard.openDashboard`,`Open dashboard`)]}),L,e(`span`,{className:`flex items-center gap-1`,children:[i(ee,{className:`h-3 w-3`}),` `,t.cpuPercent,`%`]}),e(`span`,{className:`flex items-center gap-1`,children:[i(oe,{className:`h-3 w-3`}),` `,t.memoryPercent===null?a(`cluster.memoryUnknown`):`${t.memoryPercent}%`]})]})]}),v!=null&&i(`p`,{role:`status`,className:`px-4 pt-2 text-xs ${v.tone===`ok`?`text-success`:`text-warning`}`,children:v.text}),(D!==null||j!==null)&&e(`p`,{role:`status`,className:`px-4 pt-2 text-xs text-warning`,children:[D,j!==null&&e(l,{children:[` `,i(`a`,{href:j,target:`_blank`,rel:`noreferrer`,className:`underline text-foreground`,children:a(`cluster.nodeCard.openDashboard`,`Open dashboard`)})]})]}),i(`div`,{className:`sticky top-0 z-20 flex border-b border-border px-4 bg-background overflow-x-auto`,children:[`info`,`forks`,`processes`,`load`,`settings`,`capabilities`].map(e=>i(W,{variant:`unstyled`,onClick:()=>h(e),className:`shrink-0 whitespace-nowrap px-3 py-2 text-xs font-medium border-b-2 transition-colors ${m===e?`border-primary text-primary`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:e===`info`?a(`cluster.nodeCard.general`,`General`):e===`forks`?a(`cluster.nodeCard.forks`,`Forks ({{length}})`,{length:x.length}):e===`processes`?a(`cluster.nodeCard.processes`,`Processes`):e===`load`?a(`cluster.nodeCard.load`,`Load`):e===`settings`?a(`cluster.nodeCard.settings`,`Settings`):a(`cluster.nodeCard.capabilities`,`Capabilities`)},e))}),e(`div`,{className:`px-4 py-2`,children:[m===`info`&&e(`div`,{className:`space-y-3`,children:[i($n,{nodeId:t.id,name:t.name,hostname:t.hostname,platform:t.platform,arch:t.arch,cpuModel:t.cpuModel,cpuCores:t.cpuCores,memoryMB:t.memoryMB,engines:t.engines,isHub:t.isHub,uptime:t.uptime,localIps:t.localIps,rootPackage:t.rootPackage}),i(rr,{nodeId:t.id,detectedHosts:t.localIps??[]}),i(`div`,{className:`border-t border-border pt-1`,children:i(yr,{node:{id:t.id,name:t.name,isHub:t.isHub,isOnline:t.isOnline,rootPackage:t.rootPackage??null}})}),i(lr,{node:{id:t.id,isHub:t.isHub,isOnline:t.isOnline}})]}),m===`forks`&&i(qt,{nodeId:t.id,processes:x}),m===`processes`&&i(Zt,{nodeId:t.id}),m===`load`&&i(Kn,{nodeId:t.id,isHub:t.isHub}),m===`settings`&&i(Xn,{nodeId:t.id,addonIds:S}),m===`capabilities`&&i(Zn,{nodeId:t.id,addons:t.addons})]})]}):e(`div`,{className:`border border-border rounded-xl overflow-hidden opacity-60`,children:[e(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3 bg-muted/30`,children:[i(`div`,{className:`w-2.5 h-2.5 rounded-full bg-destructive shrink-0`}),i(Ht,{node:t}),e(`span`,{className:`text-xs text-muted-foreground min-w-0 truncate`,children:[t.cpuModel??t.platform,` ·`,` `,t.memoryMB>0?a(`cluster.nodeCard.gb`,`{{value1}}GB`,{value1:Math.round(t.memoryMB/1024)}):``,` `,`· `,t.arch]}),t.engines.map(e=>i(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,title:a(`cluster.nodeInfoTab.installedRuntimesHint`,`Inference runtimes installed on this node. Its live inference devices are on Pipeline → Load balancing.`),children:e},e)),t.rootPackage&&e(`span`,{className:`text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:[t.rootPackage.name,`@`,t.rootPackage.version]}),i(`span`,{className:`ml-auto text-xs px-2 py-0.5 rounded-full bg-destructive/10 text-destructive`,children:a(`common.offline`)})]}),e(`div`,{className:`flex items-center justify-between gap-3 px-4 py-3`,children:[e(`span`,{className:`text-xs text-muted-foreground`,children:[t.lastSeen?i(`span`,{className:`mr-1`,children:a(`cluster.nodeCard.lastSeen`,{when:new Date(t.lastSeen).toLocaleString()})}):null,a(`cluster.nodeCard.addonsAssigned`,{count:t.addons.length})]}),e(`div`,{className:`flex shrink-0 items-center gap-2`,children:[L,e(W,{variant:`unstyled`,type:`button`,onClick:()=>void F(),disabled:g,title:a(`cluster.nodeCard.forgetThisNodeRemovesIts`,`Forget this node — removes its saved history and pipeline assignments`),className:`flex items-center gap-1 text-xs px-2 py-1 rounded-md border border-border text-muted-foreground hover:text-destructive hover:border-destructive/50 disabled:opacity-50 transition-colors`,children:[i(y,{className:`h-3 w-3`}),g?a(`cluster.nodeCard.forgetting`,`Forgetting…`):a(`cluster.nodeCard.forgetNode`,`Forget node`)]})]})]}),v!=null&&i(`p`,{role:`status`,className:`px-4 pb-3 text-xs leading-relaxed ${v.tone===`ok`?`text-success`:`text-warning`}`,children:v.text})]})}var Sr=3,Cr=7e3,wr=36,Tr=5e3;function Er(e){return[...e].sort((e,t)=>e.isHub===t.isHub?0:e.isHub?-1:1)}function Dr(e){return e.isHub?{}:{nodeId:e.id}}function Or(e){return e.updateState===`staging`||e.updateState===`pending-restart`||e.pendingVersion!==null?!0:!e.updateAvailable}async function kr(e,t){let n=Dr(e),r=K.t(`helpers.clusterUpdateAll.noAnswer`);for(let i=1;i<=Sr;i+=1)try{let r=await t.readStatus(n);return Or(r)?{nodeId:e.id,nodeName:e.name,outcome:`applied`,detail:K.t(`helpers.clusterUpdateAll.landed`,{state:r.updateState,version:r.runningVersion??K.t(`helpers.clusterUpdateAll.unknown`)})}:{nodeId:e.id,nodeName:e.name,outcome:`failed`,detail:K.t(`helpers.clusterUpdateAll.unchanged`,{version:r.runningVersion??K.t(`helpers.clusterUpdateAll.unknown`)})}}catch(e){r=e instanceof Error?e.message:String(e),i<Sr&&await t.wait(Cr)}return{nodeId:e.id,nodeName:e.name,outcome:`unconfirmed`,detail:K.t(`helpers.clusterUpdateAll.unconfirmed`,{attempts:Sr,error:r})}}function Ar(e){return e.accepted?`applied`:e.outcome===`failed`?`failed`:`refused`}async function jr(e){for(let t=1;t<=wr;t+=1){try{let t=await e.readStatus({});if(!t.updateAvailable&&t.updateState===`idle`&&t.pendingVersion===null)return!0}catch{}t<wr&&await e.wait(Tr)}return!1}function Mr(e,t,n){return{nodeId:e.id,nodeName:e.name,outcome:`skipped`,detail:K.t(`helpers.clusterUpdateAll.skippedAfterHub`,{hub:t.name,why:n})}}async function Nr(e,t){let n=[],r=null;for(let i of Er(e)){if(r!==null){n.push(Mr(i,r.hub,r.why));continue}let a,o=!1;try{let e=await t.apply(Dr(i));o=e.outcome===`already-current`||e.reason===`already-running`,a={nodeId:i.id,nodeName:i.name,outcome:Ar(e),detail:e.message}}catch{a=await kr(i,t)}if(n.push(a),i.isHub){let s=n.length===e.length;o||(a.outcome===`applied`?!s&&!await jr(t)&&(r={hub:i,why:K.t(`helpers.clusterUpdateAll.hubNotSettled`)}):r={hub:i,why:a.outcome})}}return n}s();function Pr(){let{nodes:e,isLoading:t}=Ge(),r=n(()=>e??[],[e]);return{nodes:r,isLoading:t&&r.length===0}}var Fr={applied:`border-success/40 bg-success/10 text-success`,refused:`border-warning/40 bg-warning/10 text-warning`,failed:`border-danger/40 bg-danger/10 text-danger`,unconfirmed:`border-warning/40 bg-warning/10 text-warning`,skipped:`border-warning/40 bg-warning/10 text-warning`};function Ir(){let{t}=q(),s=k(),{nodes:c,isLoading:d}=Pr(),[f,p]=Ze(),{selection:m,selectNode:h}=st(c),g=m.node,_=n(()=>c.filter(e=>e.isOnline),[c]),v=_.length,y=c.filter(e=>!e.isOnline).length,b=Ke(),x=M(),[S,C]=o(!1),[w,T]=o([]),E=f.get(`unlockNode`),O=f.get(`returnTo`),[A,N]=o(null);a(()=>{if(E===null||O===null)return;let e=!1;return(async()=>{try{let t=await x.trpcClient.addons.custom.mutate({addonId:`system-config`,action:`mintAgentUiUnlockTicket`,input:{nodeId:E,dashboardBaseUrl:O}});if(e)return;let n=Nt(t),r=n===null?null:n.dashboardUrl??(()=>{let e=new URL(O);return e.searchParams.set(`ticket`,n.ticket),e.toString()})();if(r===null){N(`Could not mint an unlock ticket.`);return}let i=new URLSearchParams(f);i.delete(`unlockNode`),i.delete(`returnTo`),p(i,{replace:!0}),window.location.assign(r)}catch(t){e||N(t instanceof Error?t.message:String(t))}})(),()=>{e=!0}},[E,O,f,p,x.trpcClient]);let ee=r(async()=>{let e=_.map(e=>({id:e.id,name:e.name,isHub:e.isHub}));if(await s({title:t(`serverManagement.confirmUpdateAllTitle`,`Update all nodes`),message:t(`serverManagement.confirmUpdateAllBody`,`Update and restart every online node, hub first, then the agents once the hub runs the new version. Up-to-date nodes are skipped; this page reconnects when the hub comes back.`),confirmLabel:t(`serverManagement.confirmUpdateAllAction`,`Update all & restart`),variant:`warning`})){C(!0),T([]);try{T(await Nr(e,{apply:e=>b.mutateAsync(e),readStatus:e=>x.trpcClient.serverManagement.getServerPackageStatus.query(e),wait:e=>new Promise(t=>setTimeout(t,e))}))}finally{C(!1)}}},[b,s,_,x,t]);return e(et,{icon:u,title:t(`nav.nodes`,`Nodes`),subtitle:t(`cluster.subtitle`,`One node at a time — topology and packages. Agents join by pairing (certificate, no shared secret).`),actions:e(l,{children:[v>0&&i(`span`,{className:`rounded-full bg-success/10 px-2 py-0.5 text-xs text-success`,children:t(`common.onlineCount`,{count:v})}),y>0&&i(`span`,{className:`rounded-full bg-destructive/10 px-2 py-0.5 text-xs text-destructive`,children:t(`common.offlineCount`,{count:y})}),v>1&&e(W,{type:`button`,size:`sm`,disabled:S,title:t(`serverManagement.updateAllHint`,`Sequenced hub-first, agents after — up-to-date nodes are skipped.`),onClick:()=>void ee(),children:[S?i(D,{className:`h-3.5 w-3.5 animate-spin`}):i(j,{className:`h-3.5 w-3.5`}),t(`serverManagement.updateAll`,`Update all nodes`)]})]}),children:[w.length>0&&i(`ul`,{"aria-label":`update-all-report`,className:`flex flex-col gap-1 text-xs`,children:w.map(t=>e(`li`,{"data-outcome":t.outcome,className:`rounded border px-2 py-1 ${Fr[t.outcome]}`,children:[i(`span`,{className:`font-medium`,children:t.nodeName}),i(`span`,{className:`mx-1 uppercase tracking-wide`,children:t.outcome}),i(`span`,{className:`opacity-80`,children:t.detail})]},t.nodeId))}),A!==null&&e(`p`,{role:`alert`,className:`rounded border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,children:[t(`system.cluster.unlockFromAgentFailed`,`Unlock from agent failed:`),` `,A]}),i(jt,{onOpenNode:h}),d?i(`div`,{className:`flex items-center justify-center py-12 text-muted-foreground`,children:t(`system.cluster.loadingClusterTopology`,`Loading cluster topology...`)}):g===null?i(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-xs text-foreground-subtle`,children:t(`cluster.noNodes`,`No nodes in this cluster yet.`)}):e(`div`,{className:`flex flex-col gap-3`,children:[i(ot,{staleNodeId:m.staleNodeId,shownNodeName:g.name}),i(Oe,{selectedNodeId:g.id,onSelect:h,allowOffline:!0,alwaysShow:!0}),i(xr,{node:g})]})]})}export{Ir as ClusterPage};
|