@camstack/addon-admin-ui 1.2.457 → 1.2.458
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AddonAssetIcon-BOcwQMt3.js → AddonAssetIcon-arpH1jD8.js} +1 -1
- package/dist/assets/{Addons-BrsHM2rE.js → Addons-HbtgQft-.js} +1 -1
- package/dist/assets/{AdminPage-0E8EpSO9.js → AdminPage-BjrFg6FM.js} +1 -1
- package/dist/assets/{AdminSectionedPage-CxodN1sn.js → AdminSectionedPage-DxQ2pH4Y.js} +1 -1
- package/dist/assets/{AiProfiles-EJziTK6H.js → AiProfiles-BdzPXclT.js} +1 -1
- package/dist/assets/{BrokerForm-Dbs6DDhN.js → BrokerForm-DEL7JPI4.js} +1 -1
- package/dist/assets/Build-DNm-26dy.js +40 -0
- package/dist/assets/{Calendars-DwIn1aCE.js → Calendars-Cw-Q6N0f.js} +1 -1
- package/dist/assets/{Cluster-FzZaIb80.js → Cluster-CUox6xE3.js} +1 -1
- package/dist/assets/ClusterStepModel-BSI39thg.js +1 -0
- package/dist/assets/CompositionEditor-B3e76JM9.js +1 -0
- package/dist/assets/{CompositionEditorPage-I6-ghm-F.js → CompositionEditorPage-DnCUuqEl.js} +1 -1
- package/dist/assets/{Data-CWXYjuUH.js → Data-IEAE-8BN.js} +1 -1
- package/dist/assets/DeviceDetail-MmjrNM7o.js +2 -0
- package/dist/assets/{DeviceDoActionFields-XK5u9sG-.js → DeviceDoActionFields-BRZweXYw.js} +1 -1
- package/dist/assets/{Devices-CPoElWdX.js → Devices-BtjFXXD8.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-CwqeH_Vp.js → EmbedPlayerPage-DmA2dyRs.js} +1 -1
- package/dist/assets/{History-146ywVRO.js → History-Csgt6RnT.js} +1 -1
- package/dist/assets/Identity-DmdFLJiQ.js +1 -0
- package/dist/assets/{IntegrationDetail-CUffTwqo.js → IntegrationDetail-DsIRBJ-F.js} +1 -1
- package/dist/assets/{IntegrationHub-DAndpOVJ.js → IntegrationHub-DTFQyFFN.js} +1 -1
- package/dist/assets/{Integrations-DaNoA1oi.js → Integrations-3Dm1BWSC.js} +1 -1
- package/dist/assets/{Integrations-DrSNiPXr.js → Integrations-CPsVHs77.js} +1 -1
- package/dist/assets/{Library-BMJeDfUP.js → Library-CsCzamEb.js} +1 -1
- package/dist/assets/{Locations-DpWQPPRR.js → Locations-BmYKJdte.js} +2 -2
- package/dist/assets/{Logs-ClfIrCg_.js → Logs-BfeyENDk.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-BACSOVPv.js → MaskShapeCanvas-tNwtlAOM.js} +1 -1
- package/dist/assets/{MotionZonesSettings-C-BWiqKl.js → MotionZonesSettings-C8j_gawX.js} +1 -1
- package/dist/assets/{MyAccess-B2mddc8z.js → MyAccess-CQtGUeMl.js} +1 -1
- package/dist/assets/{Network-CCpscaUS.js → Network-C_cYS-fR.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-J8GvbAOS.js → NodeAddonsSettingsPanel-BgUAqnzo.js} +1 -1
- package/dist/assets/Notifications-Bp7cRi1y.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-_hgbaRHe.js → PrivacyMaskSettings-Dpr5kjzL.js} +1 -1
- package/dist/assets/{Recordings-CmuOayrH.js → Recordings-DEsoK17t.js} +1 -1
- package/dist/assets/{ScanNetworkModal-CHpDtEMN.js → ScanNetworkModal-CHmBk64D.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-DNX5LjxD.js → SceneMonitorEditor-_NtH_gGA.js} +1 -1
- package/dist/assets/{SessionsList-CO2JCtUA.js → SessionsList-CRE59_h3.js} +1 -1
- package/dist/assets/{Showroom-C1Cx5rmM.js → Showroom-CpcQ_noP.js} +1 -1
- package/dist/assets/{System-8QdXWXlv.js → System-Cmlqjd1R.js} +1 -1
- package/dist/assets/{Terminal-D-QqW5OC.js → Terminal-B2_h39vc.js} +1 -1
- package/dist/assets/{Viewer-DEkhIs_o.js → Viewer-BY7zR9zQ.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DXRH_g5-.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BByWRJ1W.js} +1 -1
- package/dist/assets/{addon-icons-context-r4-8qNuL.js → addon-icons-context-C4CUqZFb.js} +1 -1
- package/dist/assets/{archive-CHNksUXE.js → archive-D-IttKbd.js} +1 -1
- package/dist/assets/{authed-media-CLfNNAcR.js → authed-media-BH09w7mx.js} +1 -1
- package/dist/assets/{bell-off-BQUuLgGa.js → bell-off-esSw14-4.js} +1 -1
- package/dist/assets/{board-model-CCKjMnih.js → board-model-CzpY9jow.js} +1 -1
- package/dist/assets/{boxes-OM3WXXCF.js → boxes-DLm9pV7A.js} +1 -1
- package/dist/assets/circle-slash-DUiMT2dc.js +1 -0
- package/dist/assets/client-BI85kkig.js +358 -0
- package/dist/assets/{cloud-upload-DnQzN7Zu.js → cloud-upload-CmlXZ47L.js} +1 -1
- package/dist/assets/crop-DFOEm7GN.js +1 -0
- package/dist/assets/{device-integration-icon-T6DuiFIe.js → device-integration-icon-BBk1BbPA.js} +1 -1
- package/dist/assets/device-picker-model-B-2vVHUA.js +1 -0
- package/dist/assets/dist-DmOQydcE.js +358 -0
- package/dist/assets/{dist-DWpE4F9Y.js → dist-DyazYmMR.js} +1 -1
- package/dist/assets/{eraser-2zvTICay.js → eraser-plwpovOj.js} +1 -1
- package/dist/assets/{hard-drive-download-BuPae4i9.js → hard-drive-download-B8wIgrJR.js} +1 -1
- package/dist/assets/{hostInit-B0H8YgMs.js → hostInit-u9GmPoX9.js} +1 -1
- package/dist/assets/i18n-DCSomJiP.js +1 -0
- package/dist/assets/{icons-Bf1g4TTU.js → icons-Dkn5asvl.js} +1 -1
- package/dist/assets/index-DPvkuJxO.js +4 -0
- package/dist/assets/{key-y1dQIrgn.js → key-CA18pL-8.js} +1 -1
- package/dist/assets/{key-round-PVl1EIeU.js → key-round-C7R-scbw.js} +1 -1
- package/dist/assets/{layers-BvTBL45e.js → layers-BxsydRGi.js} +1 -1
- package/dist/assets/{linked-devices-model-NEAloVak.js → linked-devices-model-BLcQ9yAI.js} +1 -1
- package/dist/assets/{list-ordered-Cy6LNkX7.js → list-ordered-DnwKxGIw.js} +1 -1
- package/dist/assets/{location-owned-usage-COJFqP2Z.js → location-owned-usage-CuK_nCoP.js} +1 -1
- package/dist/assets/{log-in-C8bG6uHT.js → log-in-Bf5RUTf4.js} +1 -1
- package/dist/assets/{memory-stick-DgCbrom_.js → memory-stick-B59QUWgK.js} +1 -1
- package/dist/assets/{message-square-plus-T2Q-JaNP.js → message-square-plus-Ckmg1y08.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-fa03047b.js → mf-entry-bootstrap-0-547cfa14.js} +2 -2
- package/dist/assets/{mic-off-CQXTB132.js → mic-off-CsCgSoDy.js} +1 -1
- package/dist/assets/{monitor-off-CvP-Xwqs.js → monitor-off-BwsLAWve.js} +1 -1
- package/dist/assets/{monitor-smartphone-DgPyh0bq.js → monitor-smartphone-G--2aBuy.js} +1 -1
- package/dist/assets/mount-B-2vVHUA.js +1 -0
- package/dist/assets/notification-schedule-field-C6qs47JN.js +1 -0
- package/dist/assets/{player-overlays-DTcu3p6k.js → player-overlays-BTnXgs6l.js} +1 -1
- package/dist/assets/{recycle-BgfATMDb.js → recycle-f9jOE7g7.js} +1 -1
- package/dist/assets/remoteEntry-BA9oATqv.js +1 -0
- package/dist/assets/{scan-eye-Cw7uLDDg.js → scan-eye-CC4mTfUp.js} +1 -1
- package/dist/assets/{scissors-GZwoMkJz.js → scissors-BNEM1Ztl.js} +1 -1
- package/dist/assets/{search-x-mGDaYxQw.js → search-x-3m2MRtEu.js} +1 -1
- package/dist/assets/{send-B4zTG8IX.js → send-D6irwubo.js} +1 -1
- package/dist/assets/{settings-2-7MkaO5_9.js → settings-2-B_7_TLiY.js} +1 -1
- package/dist/assets/{speaker-iZgcW4qe.js → speaker-CBOD08Ii.js} +1 -1
- package/dist/assets/src-B_ik3sNc.js +67 -0
- package/dist/assets/{timer-reset-CZOKA6Qu.js → timer-reset-BmRk3MOl.js} +1 -1
- package/dist/assets/{ungroup-CmTgkman.js → ungroup-CtlTayH1.js} +1 -1
- package/dist/assets/{unlink-DgTv7GBL.js → unlink-8-ZUzI25.js} +1 -1
- package/dist/assets/{usb-CDpFB3qV.js → usb-DRY8JHaQ.js} +1 -1
- package/dist/assets/{use-scenes-feed-Xf26vjq3.js → use-scenes-feed-Bnlc0umC.js} +1 -1
- package/dist/assets/{use-stationary-objects-piZ9a4go.js → use-stationary-objects-CSaIphB2.js} +1 -1
- package/dist/assets/useEventInvalidation-B-2vVHUA.js +1 -0
- package/dist/assets/{useNodeUrlSelection-Bmr7pzZ8.js → useNodeUrlSelection-UerjxtpH.js} +1 -1
- package/dist/assets/user-round-D65mcWwX.js +1 -0
- package/dist/assets/{user-x-DG-dacDQ.js → user-x-DWSR4aIw.js} +1 -1
- package/dist/assets/{video-DSWn6X4v.js → video-BRH0aO3l.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-9bgJ3bqj.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-VnpYmyAv.js} +2 -2
- package/dist/index.html +10 -10
- package/dist/server/addon.js +78 -199
- package/package.json +1 -1
- package/dist/assets/Build-G3WNIoIu.js +0 -40
- package/dist/assets/ClusterStepModel-BKwbYUSr.js +0 -1
- package/dist/assets/CompositionEditor-Du0918m6.js +0 -1
- package/dist/assets/DeviceDetail-DEN9C3es.js +0 -2
- package/dist/assets/Identity-NsWnwCVn.js +0 -1
- package/dist/assets/Notifications-CJvDmENV.js +0 -1
- package/dist/assets/circle-slash-B-qX3Tzf.js +0 -1
- package/dist/assets/client-Tf7DwHzR.js +0 -358
- package/dist/assets/crop-BXCCBrRT.js +0 -1
- package/dist/assets/device-picker-model-CJDjbyFR.js +0 -1
- package/dist/assets/dist-COc-M7x5.js +0 -358
- package/dist/assets/i18n-dPXh_JKN.js +0 -1
- package/dist/assets/index-k7RW-84l.js +0 -4
- package/dist/assets/mount-CJDjbyFR.js +0 -1
- package/dist/assets/notification-schedule-field-DXLce27m.js +0 -1
- package/dist/assets/remoteEntry-T1NwEQgU.js +0 -1
- package/dist/assets/src-CxF5mieK.js +0 -67
- package/dist/assets/useEventInvalidation-CJDjbyFR.js +0 -1
- package/dist/assets/user-round-XpdQk1Uf.js +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{$ as e,B as t,G as n,J as r,L as i,S as a,a as o,b as s,o as c,q as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{Br as f,Cr as p,D as m,Di as h,En as g,G as _,Gn as v,It as y,J as b,Jn as x,Jr as S,K as C,Kn as w,Li as T,O as E,Ri as D,Rn as O,Si as k,St as ee,T as A,V as j,Vi as te,W as M,Xn as N,Xr as P,Z as ne,Zt as F,_t as I,bn as L,cr as re,dn as R,dt as ie,en as z,ht as B,li as V,lr as ae,m as oe,or as se,ot as H,pi as U,pn as ce,r as le,sa as ue,t as de,ta as W,vn as fe,xn as pe,yn as me,z as he,zn as ge,zr as _e}from"./player-overlays-DTcu3p6k.js";import{Bi as ve,Dn as ye,En as be,Jr as xe,Ln as Se,Lr as Ce,Mr as we,Qn as G,S as Te,Ur as Ee,Vi as De,Vr as Oe,Xr as ke,Zr as K,_n as Ae,bn as je,ci as Me,di as q,f as Ne,fi as J,g as Pe,h as Fe,kn as Ie,m as Le,nr as Re,rr as ze,si as Be,tr as Ve,ui as He,v as Ue,vn as We,xn as Ge,y as Ke,yn as qe,yr as Je}from"./client-Tf7DwHzR.js";import{t as Ye}from"./archive-CHNksUXE.js";import{i as Xe,n as Ze,r as Qe,t as $e}from"./scan-eye-Cw7uLDDg.js";import{t as et}from"./bell-off-BQUuLgGa.js";import{t as tt}from"./boxes-OM3WXXCF.js";import{n as nt}from"./video-DSWn6X4v.js";import{t as rt}from"./circle-slash-B-qX3Tzf.js";import{t as it}from"./layers-BvTBL45e.js";import{$ as at,$n as ot,$u as st,An as ct,Ar as lt,Bc as ut,Br as dt,Bu as ft,Ca as pt,Dn as mt,Dt as ht,Ec as gt,F as _t,Fn as vt,Ft as yt,G as bt,Go as xt,Gt as St,Gu as Ct,Hn as wt,Ht as Tt,Ic as Et,In as Dt,It as Ot,Iu as kt,J as At,Ja as jt,Jr as Mt,Ju as Nt,K as Pt,Kt as Ft,Lc as It,Ln as Lt,Lu as Rt,Mn as zt,Mt as Bt,N as Vt,Ns as Ht,Nt as Ut,Nu as Wt,Oi as Gt,On as Kt,Ou as qt,Pa as Jt,Pn as Yt,Pu as Xt,Qa as Zt,Qn as Qt,Ra as $t,Rc as en,Rn as tn,Rr as nn,Rt as rn,Ru as an,Sa as on,So as sn,Tn as cn,To as ln,Tr as un,Ua as dn,Us as fn,Ut as pn,Vc as mn,Vr as hn,Vs as gn,Vt as _n,Wa as vn,Xa as yn,Xo as bn,Xt as xn,Y as Sn,Yc as Cn,Yo as wn,Yt as Tn,Za as En,Zn as Dn,Zo as On,Zt as kn,_c as An,_r as jn,a as Mn,aa as Nn,an as Pn,ar as Fn,ba as In,br as Ln,bt as Rn,c as zn,cr as Bn,da as Vn,er as Hn,et as Un,fc as Wn,fi as Gn,fn as Kn,fo as qn,fr as Jn,ga as Yn,gc as Xn,gn as Zn,gt as Qn,hr as Y,i as $n,ir as er,jn as tr,jt as nr,kn as rr,kt as ir,l as ar,lr as or,mc as sr,mn as cr,mr as lr,nr as ur,nt as dr,o as fr,oa as pr,oo as mr,or as hr,pc as gr,qa as _r,qt as vr,qu as yr,r as br,ro as xr,rr as Sr,s as Cr,tt as wr,ua as Tr,ul as Er,vr as Dr,wa as Or,wn as kr,xc as Ar,ya as jr,yn as Mr,yo as Nr,yr as Pr,yt as Fr,zc as Ir,zt as Lr}from"./src-CxF5mieK.js";import{t as X}from"./i18n-dPXh_JKN.js";import{t as Z}from"./useTranslation-D3Is_4B6.js";import"./mount-CJDjbyFR.js";import{A as Rr,F as zr,H as Br,I as Vr,J as Hr,K as Ur,M as Wr,N as Gr,P as Kr,Q as qr,U as Jr,V as Yr,W as Xr,X as Zr,Y as Qr,Z as $r,et as ei,g as ti,h as ni,j as ri,nt as ii,p as ai,q as oi,tt as si}from"./index-k7RW-84l.js";import{C as ci,D as li,E as ui,S as di,_ as fi,a as pi,b as mi,c as hi,d as gi,f as _i,g as vi,h as yi,i as bi,l as xi,m as Si,n as Ci,o as wi,p as Ti,r as Ei,s as Di,t as Oi,u as ki,v as Ai,x as ji,y as Mi}from"./CompositionEditor-Du0918m6.js";import{_ as Ni,a as Pi,c as Fi,d as Ii,f as Li,g as Ri,h as zi,i as Bi,l as Vi,m as Hi,n as Ui,o as Wi,p as Gi,s as Ki,t as qi,u as Ji,v as Yi,y as Xi}from"./ClusterStepModel-BKwbYUSr.js";import"./useEventInvalidation-CJDjbyFR.js";import{t as Zi}from"./use-stationary-objects-piZ9a4go.js";import{a as Qi,c as $i,d as ea,f as ta,i as na,l as ra,n as ia,o as aa,p as oa,r as sa,s as ca,t as la,u as ua}from"./linked-devices-model-NEAloVak.js";import{t as da}from"./authed-media-CLfNNAcR.js";e();function fa(e){if(typeof e!=`object`||!e)return null;let t=e,n=t.id,r=t.label;if(typeof n!=`string`||typeof r!=`string`)return null;let i=t.available===!0,a=t.enabled,o=t.unavailableReason;return{id:n,label:r,costWhenOff:typeof t.costWhenOff==`string`?t.costWhenOff:``,on:i&&typeof a==`boolean`?a:null,available:i,unavailableReason:typeof o==`string`?o:null}}function pa(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(fa).filter(e=>e!==null);return n.length===0?null:n}var ma=[[/privacy|mask/i,`privacy`],[/microphone|mic\b/i,`microphone`],[/speaker|broker audio|stream audio/i,`speaker`],[/audio/i,`listening`],[/object|detect/i,`detection`],[/event/i,`archive`],[/record/i,`recording`],[/notif/i,`notifications`],[/stream|broker/i,`stream`]];function ha(e){for(let[t,n]of ma)if(t.test(e))return n;return`generic`}function ga(e){let t=e.filter(e=>e.on===!1).map(e=>e.id),n=e.filter(e=>e.on===null).map(e=>e.id),r=t=>t.map(t=>e.find(e=>e.id===t)?.label??t).join(`, `),i=[];return t.length>0&&i.push(X.t(`helpers.cameraSwitchRows.off`,{list:r(t)})),n.length>0&&i.push(X.t(`helpers.cameraSwitchRows.unknown`,{list:r(n)})),{offIds:t,unknownIds:n,summary:i.length===0?X.t(`helpers.cameraSwitchRows.allOn`):i.join(` · `)}}var _a={stream:pe,detection:$e,privacy:_e,microphone:N,speaker:ee,listening:Ze,archive:Ye,recording:Qe,notifications:T,generic:z};function va({deviceId:e}){let{t}=Z(),n=c(),o=Number.isFinite(e),[s,l]=r(null),[u,f]=r(!1),p=An({deviceId:e},{enabled:o});br([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let m=pa(p.data),h=mn({onError:(t,r)=>{console.error(`[CameraFunctionSwitches] switch write failed — reverting`,{tags:{deviceId:e},meta:{switchId:r.switchId,error:t instanceof Error?t.message:String(t)}}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSwitches`]]}),l({id:r.switchId,message:t instanceof Error?t.message:String(t)})},onSuccess:()=>{l(null),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`]]}),n.invalidateQueries({queryKey:[[`deviceManager`]]}),n.invalidateQueries({queryKey:[[`recording`]]})}}),g=i(t=>{!t.available||t.on===null||h.mutate({deviceId:e,switchId:t.id,enabled:!t.on})},[e,h]);if(m===null)return null;let _=ga(m),v=e=>s?.id===e.id?s.message:null;return a(kt,{open:u,onOpenChange:f,children:[a(an,{"aria-label":t(`device.cameraFunctionSwitches.cameraFunctions`,`Camera functions`),title:_.summary,className:`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors ${s===null?_.offIds.length>0?`border-warning/40 text-warning hover:bg-warning/10`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`:`border-danger/50 text-danger bg-danger/5`}`,children:[d(z,{className:`h-3.5 w-3.5`}),d(`span`,{className:`hidden lg:inline`,children:t(`device.cameraFunctionSwitches.functions`,`Functions`)}),_.offIds.length>0&&d(`span`,{className:`rounded bg-warning/20 px-1 text-[9px] font-semibold uppercase tracking-wide`,children:t(`device.cameraFunctionSwitches.offCount`,{count:_.offIds.length})})]}),a(Rt,{align:`end`,className:`min-w-[240px] max-h-[60vh] overflow-y-auto p-1`,children:[d(`div`,{className:`px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle`,children:t(`device.cameraFunctionSwitches.cameraFunctions`,`Camera functions`)}),d(`ul`,{className:`space-y-0.5`,children:m.map(e=>d(`li`,{children:d(ya,{row:e,failure:v(e),onToggle:()=>g(e)})},e.id))})]})]})}function ya({row:e,failure:t,onToggle:n}){let{t:r}=Z(),i=_a[ha(e.label)],o=e.on===null,s=e.on===!1,c=t===null?o?e.unavailableReason??`The source that owns this did not answer.`:e.costWhenOff:`Write failed: ${t}`,l=t===null?o?e.unavailableReason??`unknown`:null:`write failed`;return a(`button`,{type:`button`,role:`switch`,"aria-label":e.label,"aria-checked":e.on===!0,disabled:!e.available,onClick:n,title:c,className:`flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-[12px] text-foreground transition-colors hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed`,children:[d(i,{className:`h-3.5 w-3.5 shrink-0 ${t===null?o?`text-foreground-subtle/50`:s?`text-warning`:`text-success`:`text-danger`}`}),a(`span`,{className:`flex-1 min-w-0 truncate`,children:[e.label,l!==null&&a(`span`,{className:`ml-1 text-[10px] text-foreground-subtle`,children:[`· `,l]})]}),d(`span`,{className:`shrink-0 rounded px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${o?`bg-surface-hover text-foreground-subtle/60`:s?`bg-warning/20 text-warning`:`bg-success/20 text-success`}`,children:o?`—`:r(s?`common.off`:`common.on`)})]})}function ba({deviceId:e}){let t=rn(H().trpcClient,e);return t===null?null:a(`a`,{href:t.url,target:`_blank`,rel:`noopener noreferrer`,title:`${t.label} — ${t.host}`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[d(f,{className:`h-3.5 w-3.5`}),d(`span`,{className:`hidden sm:inline`,children:t.label})]})}function xa({parentDeviceId:e}){let{t}=Z(),n=ei(),r=H(),{data:i,isLoading:o,isError:s}=Xr(e),{data:c}=_r({deviceId:e},{enabled:Number.isFinite(e)});if(o)return d(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:d(`p`,{className:`text-[10px] text-foreground-subtle`,children:t(`common.loading`,{defaultValue:`Loading…`})})});if(s)return d(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:d(`p`,{className:`text-[10px] text-warning`,children:t(`integrations.childrenLoadError`,{defaultValue:`Failed to load children`})})});let l=(i??[]).filter(e=>e.display?.hidden!==!0);if(l.length===0)return null;let u=Ut(c?.stableId??``,l,c?.childLayout),f=u.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>d(nr,{trpc:r.trpcClient,device:{...t,name:Lr(t,m)},variant:`minimal`,onNavigate:p},e),g=f.some(e=>!!e.role),_=f.some(e=>!e.role),v=g&&!_?t(`device.accessories`,{defaultValue:`Accessories`}):!g&&_?t(`device.adoptedDevices`,{defaultValue:`Adopted devices`}):t(`device.children`,{defaultValue:`Children`}),y=f.length>0?a(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5`,children:v}),d(`div`,{className:`space-y-1`,children:f.map(e=>h(e.id,e))})]}):null,b=u.disabledSection===void 0?null:d(Bt,{title:t(`device.disabledSection`,{defaultValue:`Disabled`}),count:u.disabledSection.children.length,defaultOpen:!1,children:d(`div`,{className:`opacity-60 space-y-1`,children:u.disabledSection.children.map(e=>h(e.id,e))})},u.disabledSection.title);if(u.sections.length===0)return b===null?y:a(`div`,{className:`space-y-2`,children:[y,b]});let x=_&&!g;return a(`div`,{className:`space-y-2`,children:[x?y:null,u.sections.map(e=>d(Bt,{title:e.title,count:e.children.length,defaultOpen:e.defaultOpen,children:e.children.map(e=>h(e.id,e))},e.title)),x?null:y,b]})}function Sa({deviceId:e}){let t=H(),{data:n,isLoading:r}=Jr(e),{data:i,isLoading:a}=Xr(e),o=r||a,s=(i??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,name:e.name,features:e.features,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),c=typeof n?.linkDeviceId==`number`?n.linkDeviceId:null,l=typeof n?.primaryChildEntityId==`string`?n.primaryChildEntityId:null;return o?d(`div`,{className:`h-full min-h-32 w-full animate-pulse rounded-lg bg-surface`,"aria-hidden":`true`}):d(`div`,{className:`flex h-full w-full flex-col`,children:d(_n,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}e();function Ca({dev:e,busy:t,setBusy:n}){let{t:i}=Z(),o=e?.motionTrigger,s=b(e?.state.motionTrigger),[c,l]=r(!1);if(!o)return null;let u=s?.enabled===!0,f=s!==void 0,p=async()=>{if(t||!f)return;let e=!u;n(!0),l(!0);try{await o.setMotionTrigger({enabled:e})}finally{n(!1),l(!1)}},m=c?u?`Disabling…`:`Enabling…`:f?u?`On motion: on`:`On motion: off`:`On motion: …`;return a(`button`,{type:`button`,onClick:()=>{p()},disabled:t||!f,title:f?u?i(`hero.motionTriggerToggle.disableTriggerOnMotion`,`Disable trigger on motion`):i(`hero.motionTriggerToggle.enableTriggerOnMotion`,`Enable trigger on motion`):i(`hero.motionTriggerToggle.awaitingState`,`Awaiting state…`),"aria-pressed":u,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${u?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground`}`,children:[d(W,{className:`h-3 w-3`}),d(`span`,{children:m})]})}e();function Q({deviceId:e,deviceType:t,features:n}){let i=H(),o=St(t)?.HeroCard??Ft,s=C(i.trpcClient,e),c=b(s?.state.deviceStatus),[l,u]=r(!1),f=c!==void 0&&c.online===!1,p=f?c.lastChangedAt:null;return a(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:[f?d(`div`,{className:`flex justify-center`,children:d(pn,{lastChangedAt:p})}):null,d(o,{trpc:i.trpcClient,deviceId:e,features:n}),d(`div`,{className:`flex justify-center`,children:d(Ca,{dev:s,busy:l,setBusy:u})})]})}function wa({deviceId:e,features:t}){return d(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:d(vr,{trpc:H().trpcClient,deviceId:e,features:t})})}function Ta({deviceId:e,features:t}){return d(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:d(Ft,{trpc:H().trpcClient,deviceId:e,features:t})})}function Ea(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function Da(e){if(!e)return null;let t=Ea(e.data);return t===null?e.eventType:X.t(`helpers.eventEmitterFormat.buttonHeadline`,{channel:String(t),eventType:e.eventType})}var Oa=1e3,ka=60*Oa,Aa=60*ka,ja=24*Aa;function Ma(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<Oa?X.t(`helpers.relativeTime.justNow`):n<ka?X.t(`helpers.relativeTime.secondsAgo`,{count:Math.floor(n/Oa)}):n<Aa?X.t(`helpers.relativeTime.minutesAgo`,{count:Math.floor(n/ka)}):n<ja?X.t(`helpers.relativeTime.hoursAgo`,{count:Math.floor(n/Aa)}):X.t(`helpers.relativeTime.daysAgo`,{count:Math.floor(n/ja)})}e();var Na=1500,Pa=15e3,Fa=1e3;function Ia({deviceId:e}){let{t:n}=Z(),i=C(H().trpcClient,e)?.state.eventEmitter,o=b(i);t(()=>{if(!i)return;i.refresh();let e=setInterval(()=>{i.refresh()},Pa);return()=>{clearInterval(e)}},[i]);let s=o?.lastEvent??null,c=s?.seq??null,u=l(null),[f,m]=r(!1);t(()=>{if(c===null)return;let e=u.current;if(u.current=c,e===null||e===c)return;m(!0);let t=setTimeout(()=>{m(!1)},Na);return()=>{clearTimeout(t)}},[c]);let[h,g]=r(()=>Date.now());t(()=>{let e=setInterval(()=>{g(Date.now())},Fa);return()=>{clearInterval(e)}},[]);let _=Da(s),y=o?.eventTypes??[],x=o?.eventCountSinceStart??0,S=o!==void 0,w=Ea(s?.data);return a(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 p-4`,children:[d(`div`,{"data-testid":`event-emitter-indicator`,"data-flashing":String(f),className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${f?`border-primary bg-primary/20 text-primary shadow-lg shadow-primary/30 scale-105`:`border-border bg-surface text-foreground-subtle`}`,"aria-live":`polite`,title:_??n(`hero.eventEmitterHero.noPressRecorded`,`No press recorded`),children:d(f?v:p,{className:`h-10 w-10`})}),a(`div`,{className:`text-center`,children:[w!==null&&d(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-primary`,children:n(`hero.eventEmitterHero.button`,`Button {{value1}}`,{value1:String(w)})}),d(`div`,{"data-testid":`event-emitter-headline`,className:`text-sm font-semibold ${_?`text-foreground`:`text-foreground-subtle`}`,children:_??(S?n(`hero.eventEmitterHero.noPressRecorded`,`No press recorded`):n(`hero.eventEmitterHero.awaitingState`,`Awaiting state…`))}),d(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:s?Ma(s.timestamp,h):n(`hero.eventEmitterHero.waitingForTheFirstEvent`,`Waiting for the first event`)})]}),y.length>0&&d(`div`,{className:`flex max-w-full flex-wrap justify-center gap-1`,children:y.map(e=>d(`span`,{"data-testid":`event-emitter-chip`,className:`rounded-full border px-2 py-0.5 text-[10px] font-medium ${e===s?.eventType?`border-primary bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle`}`,children:e},e))}),d(`div`,{className:`text-[10px] text-foreground-subtle`,children:n(`hero.eventEmitterHero.sinceStart`,{count:x})})]})}function La({deviceName:e,deviceType:t,provider:n,isOnline:r,features:i}){let{t:o}=Z();return a(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface p-6 text-center`,children:[d(Qr,{type:n,size:`lg`}),a(`div`,{children:[d(`div`,{className:`text-sm font-semibold text-foreground`,children:e}),d(`div`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5`,children:t})]}),a(`div`,{className:`flex items-center gap-2 flex-wrap justify-center`,children:[d(dr,{status:r?`online`:`offline`}),i.length>0&&d(Zr,{capabilities:i})]}),d(`div`,{className:`text-[10px] text-foreground-subtle italic max-w-xs mt-1`,children:o(`hero.genericHero.noLiveViewForThis`,`No live view for this device type. Use the Config tab or the shortcut row to interact.`)})]})}e();function Ra({deviceId:e}){let{t}=Z(),r=c(),i=jr({deviceId:e},{refetchInterval:1e4,retry:!1}),o=In({onSuccess:()=>{r.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),r.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),s=n(()=>za(i.data??[]),[i.data]);return a(`div`,{className:`flex h-full w-full flex-col gap-3 p-3 sm:p-4`,children:[a(`div`,{className:`flex flex-wrap items-stretch gap-2 sm:gap-3`,children:[d(Ba,{label:t(`hero.hubHero.discovered`,`Discovered`),value:s.total,icon:d(ge,{className:`h-3.5 w-3.5`})}),d(Ba,{label:t(`hero.hubHero.adopted`,`Adopted`),value:s.adopted,accent:`success`}),d(Ba,{label:t(`hero.hubHero.available`,`Available`),value:s.available,accent:s.available>0?`primary`:void 0}),a(`button`,{type:`button`,onClick:()=>{o.mutateAsync({deviceId:e}).catch(()=>{})},disabled:o.isPending,className:`inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 self-stretch shrink-0`,children:[o.isPending?d(se,{className:`h-3.5 w-3.5 animate-spin`}):d(L,{className:`h-3.5 w-3.5`}),d(`span`,{className:`hidden sm:inline`,children:t(`hero.hubHero.discover`,`Discover`)})]})]}),a(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-foreground-subtle border-t border-border-subtle pt-2`,children:[d(Va,{icon:d(B,{className:`h-3 w-3 text-emerald-500`}),label:t(`hero.hubHero.online`,`{{online}} online`,{online:s.online})}),d(Va,{icon:d(w,{className:`h-3 w-3 text-amber-500`}),label:t(`hero.hubHero.sleeping`,`{{sleeping}} sleeping`,{sleeping:s.sleeping})}),d(Va,{icon:d(I,{className:`h-3 w-3 text-destructive`}),label:t(`hero.hubHero.offline`,`{{offline}} offline`,{offline:s.offline})}),s.unknown>0?d(Va,{icon:d(V,{className:`h-3 w-3 text-foreground-subtle`}),label:t(`hero.hubHero.unknown`,`{{unknown}} unknown`,{unknown:s.unknown})}):null]})]})}function za(e){let t={total:e.length,adopted:0,available:0,online:0,sleeping:0,offline:0,unknown:0};for(let n of e)n.alreadyAdopted?t.adopted+=1:t.available+=1,t[n.status]+=1;return t}function Ba({label:e,value:t,icon:n,accent:r}){return a(`div`,{className:`flex flex-1 basis-[140px] min-w-0 flex-col gap-1 rounded-lg border px-2 py-1.5 sm:px-3 sm:py-2 ${r===`success`?`bg-emerald-500/10 border-emerald-500/30 text-emerald-500`:r===`primary`?`bg-primary/10 border-primary/30 text-primary`:`bg-surface-hover border-border text-foreground`}`,children:[a(`div`,{className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate`,children:[n,d(`span`,{className:`truncate`,children:e})]}),d(`div`,{className:`text-xl sm:text-2xl font-semibold tabular-nums leading-none`,children:t})]})}function Va({icon:e,label:t}){return a(`span`,{className:`inline-flex items-center gap-1`,children:[e,d(`span`,{children:t})]})}var Ha={[J.Switch]:Q,[J.Siren]:Q,[J.Light]:Q,[J.Sensor]:Q,[J.Button]:Q,[J.Hub]:Ra,[J.Cover]:wa,[J.Valve]:Q,[J.Humidifier]:Q,[J.WaterHeater]:Q,[J.Container]:Sa,[J.Lock]:Q,[J.Fan]:Q,[J.Thermostat]:Q,[J.Climate]:Q,[J.MediaPlayer]:Q,[J.Control]:Q,[J.AlarmPanel]:Q,[J.EventEmitter]:Ia,[J.Notifier]:Ta,[J.Script]:Q,[J.Automation]:Q,[J.Presence]:Q,[J.Update]:Q,[J.Vacuum]:Q,[J.LawnMower]:Q,[J.Weather]:Q,[J.Image]:Q,[J.PetFeeder]:Q,[J.Dishwasher]:Q};function Ua(e){return Ha[e]??La}function Wa(e){return d(Ua(e.deviceType),{...e})}function Ga({deviceId:e,widgets:t}){return t.length===0?null:d(`div`,{className:`flex flex-col gap-3 px-3 pb-3 sm:px-4 sm:pb-4`,"data-testid":`device-hero-widgets`,children:t.map(t=>{let n=d(Dn,{widgetId:t.widgetId,deviceId:t.deviceId});return d(`div`,{children:t.deviceId===e?n:d(un,{deviceId:t.deviceId,children:n})},t.widgetId)})})}function Ka(e){return e.sections.filter(e=>e.location===`hero`).flatMap(t=>t.fields.flatMap(n=>{if(typeof n!=`object`||!n)return[];let r=Reflect.get(n,`type`),i=Reflect.get(n,`widgetId`);return r!==`widget`||typeof i!=`string`||i.length===0?[]:[{widgetId:i,deviceId:e.deviceId,order:t.order??0}]}))}function qa(e){let t=Ka(e),n=new Set(t.map(e=>e.widgetId)),r=e.child===void 0?[]:Ka(e.child),i=[...t,...r.filter(e=>!n.has(e.widgetId))],a=new Set;return i.filter(e=>a.has(e.widgetId)?!1:(a.add(e.widgetId),!0)).sort((e,t)=>e.order-t.order)}function Ja(e){return fr(H().trpcClient,e)}e();function Ya(e){let[n,a]=r(`idle`),[o,s]=r(null),c=l(null),u=l(null),d=l(null),f=l(!0),p=bn(),m=wn(),h=On(),g=i(()=>{if(c.current){try{c.current.close()}catch{}c.current=null}if(u.current){for(let e of u.current.getTracks())try{e.stop()}catch{}u.current=null}d.current=null},[]),_=i(async()=>{if(n===`idle`)return;a(`stopping`);let t=d.current;if(t&&e!==null)try{await Promise.race([h.mutateAsync({deviceId:e,sessionId:t}),new Promise((e,t)=>setTimeout(()=>t(Error(`server stopSession timeout`)),2e3))])}catch(e){console.warn(`[intercom] server stopSession failed (continuing teardown)`,e)}g(),f.current&&(a(`idle`),s(null))},[n,e,h,g]),v=i(async()=>{if(e===null||n!==`idle`&&n!==`error`)return;s(null);let t=null,r=null,i=null;try{a(`requesting-mic`),t=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),u.current=t,a(`starting`);let n=await p.mutateAsync({deviceId:e});i=n.sessionId,d.current=i,a(`connecting`),r=new RTCPeerConnection,c.current=r,r.oniceconnectionstatechange=()=>{if(!f.current)return;let e=r.iceConnectionState;e===`connected`||e===`completed`?a(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&f.current&&(s(e===`failed`?`WebRTC connection failed`:null),_())};for(let e of t.getAudioTracks())r.addTrack(e,t);await r.setRemoteDescription({type:`offer`,sdp:n.sdpOffer});let o=await r.createAnswer();await r.setLocalDescription(o);let l=r.localDescription?.sdp??o.sdp??``;await m.mutateAsync({deviceId:e,sessionId:i,sdpAnswer:l})}catch(n){let o=n instanceof Error?n.message:String(n);if(console.warn(`[intercom] start failed`,n),r)try{r.close()}catch{}if(t)for(let e of t.getTracks())try{e.stop()}catch{}if(c.current=null,u.current=null,i!==null)try{await h.mutateAsync({deviceId:e,sessionId:i})}catch{}d.current=null,f.current&&(s(o),a(`error`))}},[e,n,p,m,h,_]);return t(()=>(f.current=!0,()=>{f.current=!1;let t=d.current;if(t!==null&&e!==null&&h.mutate({deviceId:e,sessionId:t}),c.current){try{c.current.close()}catch{}c.current=null}if(u.current){for(let e of u.current.getTracks())try{e.stop()}catch{}u.current=null}d.current=null}),[e]),{state:n,error:o,start:v,stop:_,isTalking:n===`talking`}}e();var Xa=0;function $(){return++Xa}function Za(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function Qa(e){return[``,`Commands`,` help Show this help`,` examples Show usage examples for the current scope`,` context Show every available variable + full API surface`,` clear Clear terminal (also Ctrl+L)`,``,`Shortcuts`,` Enter Execute expression`,` Arrow Up/Down Navigate command history`,` Ctrl+L Clear terminal`,``,`Try: ${{system:` sm.summary() // fleet overview`,device:` device.state.battery.value?.sleeping // sync read`,provider:` devices.map(d => d.name)`,addon:` manifest.version`}[e.type]}`,``,`Top-level objects: sm (SystemMirror), DeviceType, Math, JSON, Date, …`]}function $a(e){switch(e.type){case`device`:return[``,`── State (sync, zero round-trip) ─────────────────────────`,` device.state.battery.value`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,``,`── Actions (async, through wrapper chain) ────────────────`,` await device.snapshot.getSnapshot({})`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.switch.setState({ on: true })`,``,`── Wait for condition ───────────────────────────────────`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`── Subscribe to changes ─────────────────────────────────`,` const off = device.state.battery.subscribe(s => console.log(s))`,``,`── Quick info ───────────────────────────────────────────`,` info.name device name`,` info.addonId owning addon`,` sm.dump(deviceId) full debug dump`];case`system`:return[``,`── Lookups ──────────────────────────────────────────────`,` sm.getDeviceById(8)`,` sm.getDeviceByName('Sala da pranzo')`,` sm.getDevicesByAddon('reolink')`,` sm.getDevicesByType(DeviceType.Camera)`,``,`── Filters (typed query) ────────────────────────────────`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] })`,` sm.query({ name: /^Cam-/ })`,``,`── Cross-device ─────────────────────────────────────────`,` sm.whereState('battery', s => s.percentage < 20).length`,` sm.mapState('battery', s => s.percentage)`,` sm.countByCap('snapshot')`,``,`── Batch action ─────────────────────────────────────────`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,``,`── Listen ───────────────────────────────────────────────`,` sm.listenCap('motion', (id, s) => console.log(id, s))`,` sm.onDeviceAdded((id, info) => console.log('+', info.name))`,``,`── Diagnostics ──────────────────────────────────────────`,` sm.summary()`,` sm.dump(8)`];case`provider`:return[``,` devices.map(d => d.name)`,` await getIntegration()`,` sm.getDevicesByAddon('<this-addon-id>').length`];case`addon`:return[``,` manifest.name`,` manifest.version`,` declaration`]}}function eo(e){let t=[``,`Scope: ${e.type}`,``];switch(e.type){case`system`:return[...t,`Primary API — sm (SystemMirror):`,` sm.getDeviceById(id) DeviceProxy | null (sync)`,` sm.getDeviceByName(name) DeviceProxy | null`,` sm.getDeviceByStableId(sid) DeviceProxy | null`,` sm.getAllDevices() readonly DeviceProxy[]`,` sm.getDeviceInfo(id) DeviceInfo | null`,` sm.summary() fleet stats`,``,`Filters — sm.query({...}):`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] }) // ALL caps required`,` sm.query({ anyCap: ['ptz', 'motion'] }) // ANY cap`,` sm.query({ name: { contains: 'sala' } }) // case-insensitive`,` sm.query({ name: /^Cam-\\d+$/ })`,` sm.query({ type: DeviceType.Camera })`,` sm.query({ parentDeviceId: 8 }) // accessories of cam 8`,` sm.query({ where: (info, dev) => dev.state.battery.value?.sleeping })`,``,`State queries:`,` sm.whereState('battery', s => s.percentage < 20)`,` sm.mapState('battery', s => s.percentage)`,` sm.findState('motion', s => s.detected)`,` sm.countByCap('snapshot')`,``,`Listeners (return unsubscribe fn):`,` sm.listen((id, cap, slice) => …) // every state change`,` sm.listenCap('motion', (id, slice) => …)`,` sm.listenDevice(8, (id, cap, slice) => …)`,` sm.onDeviceAdded((id, info) => …)`,` sm.onDeviceRemoved((id, info) => …)`,``,`Wait primitives:`,` await sm.waitForState(8, 'battery', s => !s.sleeping, 30_000)`,` await sm.waitForDevice(99, 30_000)`,``,`Batch:`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,` await sm.forEachCap('reboot', d => d.reboot.reboot({}))`,``,`Diagnostics:`,` sm.dump(8) debug dump (one device)`,` sm.dump() full fleet dump`,` sm.summary() breakdown by cap/addon/type`,``,`Legacy: deviceRegistry, addonRegistry, eventBus, devices(), addons()`];case`device`:return[...t,`Pre-bound variables:`,` device DeviceProxy for this device (sync state + async methods)`,` deviceId number`,` info DeviceInfo metadata (name, addonId, type, online, …)`,` sm SystemMirror (full cluster view)`,` rawDevice legacy IDevice instance (escape hatch)`,``,`Reactive state (sync, zero round-trip):`,` device.state.battery.value BatteryStatus | undefined`,` device.state.battery.value?.sleeping`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,` device.state.switch.value?.on`,` device.state.brightness.value?.percentage`,` device.state.doorbell.value?.lastPressedAt`,``,`Cap actions (async, through wrapper chain):`,` await device.snapshot.getSnapshot({})`,` await device.snapshot.getSnapshot({ streamId: 'high' })`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.ptz.goToPreset({ presetId: 'home' })`,` await device.switch.setState({ on: true })`,` await device.brightness.setBrightness({ percentage: 60 })`,` await device.reboot.reboot({})`,``,`Subscribe to slice changes:`,` const off = device.state.battery.subscribe(s => console.log(s))`,` // off() to unsubscribe`,``,`Wait for a state condition:`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`Diagnostics:`,` info.name device name`,` info.addonId which addon owns it`,` info.online transport health`,` sm.dump(deviceId) full debug dump (binding + state + info)`];case`provider`:return[...t,`Pre-bound variables:`,` devices Devices belonging to this provider (raw IDevice[])`,` getIntegration() Integration metadata`,``,`For typed device access use the SystemMirror:`,` await getSystemMirror()`,` sm.getDevicesByAddon('this-addon-id')`];case`addon`:return[...t,`Pre-bound variables:`,` manifest { name, version, ... }`,` declaration addon declaration`,` source addon source location`,``,`Examples:`,` manifest.name`,` manifest.version`]}}function to({scope:e,greeting:n,className:o}){let{t:s}=Z(),c=H(),[f,p]=r(()=>{let t=[];return n&&t.push({id:$(),kind:`info`,text:n}),t.push({id:$(),kind:`info`,text:`scope: ${Za(e)} — type help or context for available commands`}),t}),[m,h]=r(``),[g,_]=r([]),[v,y]=r(-1),b=l(null),x=l(null);t(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)},[f]);let S=i(()=>{b.current?.focus()},[]),C=u({mutationFn:t=>c.trpcClient.repl.execute.mutate({code:t,scope:e}),onSuccess:e=>{let t=e??{},n=typeof t.output==`string`?t.output:e==null?`undefined`:typeof e==`string`?e:JSON.stringify(e,null,2),r=t.type===`error`;p(e=>[...e,{id:$(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);p(e=>[...e,{id:$(),kind:`error`,text:t}])}});function w(t){let n=t.trim();if(n){if(n===`clear`){p([{id:$(),kind:`info`,text:`scope: ${Za(e)}`}]),h(``);return}if(n===`help`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},...Qa(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(n===`context`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},...eo(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(n===`examples`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},...$a(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}_(e=>[...e,n]),y(-1),p(e=>[...e,{id:$(),kind:`input`,text:`> ${n}`}]),h(``),C.mutate(n)}}function T(t){if(t.key===`Enter`){t.preventDefault(),w(m);return}if(t.key===`ArrowUp`){if(t.preventDefault(),g.length===0)return;let e=v===-1?g.length-1:Math.max(0,v-1);y(e),h(g[e]??``);return}if(t.key===`ArrowDown`){if(t.preventDefault(),v===-1)return;let e=v+1;e>=g.length?(y(-1),h(``)):(y(e),h(g[e]??``));return}t.ctrlKey&&t.key===`l`&&(t.preventDefault(),p([{id:$(),kind:`info`,text:`scope: ${Za(e)}`}]))}let E={input:`text-zinc-300`,result:`text-emerald-300`,error:`text-red-300`,info:`text-zinc-400`};return a(`div`,{className:`flex flex-col bg-[#0c0a09] rounded-lg border border-border overflow-hidden font-mono text-xs ${o??``}`,onClick:S,children:[a(`div`,{ref:x,className:`flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]`,children:[f.map(e=>d(`pre`,{className:`whitespace-pre-wrap break-words leading-relaxed ${E[e.kind]}`,children:e.text},e.id)),C.isPending&&d(`span`,{className:`text-zinc-500 animate-pulse`,children:s(`shared.replTerminal.thinking`,`…thinking`)})]}),a(`div`,{className:`flex items-center gap-2 border-t border-zinc-800 px-3 py-2 bg-[#0c0a09]`,children:[d(`span`,{className:`text-emerald-400 flex-shrink-0 select-none font-bold`,children:s(`shared.replTerminal.text`,`>`)}),d(`input`,{ref:b,value:m,onChange:e=>h(e.target.value),onKeyDown:T,disabled:C.isPending,placeholder:`device.state.battery.value`,autoFocus:!0,className:`flex-1 bg-transparent text-zinc-100 placeholder:text-zinc-600 focus:outline-none caret-emerald-400 disabled:opacity-50`,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`})]})]})}function no(e,t){return e===null?null:{playbackUrl:e.url,...e.format===void 0?{}:{playbackFormat:e.format},playbackAuthToken:t,...e.label===void 0?{}:{playbackLabel:e.label}}}e();function ro({deviceId:e,intercomAvailable:t=!1}){let r=H(),i=typeof window<`u`?ne():``,a=Number.isFinite(e),o=Ja(a?e:null),c=Zi(a?[e]:[]),l=n(()=>{if(!a)return;let e=[];for(let t of c.rows){let n=Mn(t);n!==null&&e.push(n)}return e},[a,c.rows]),{streams:u,pipelineMetrics:f,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:v,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S}=Kn(r.trpcClient,a?e:null),C=_(a?e:null,{width:co}),w=Ya(a&&t?e:null),T=w.state===`requesting-mic`||w.state===`starting`||w.state===`connecting`||w.state===`stopping`,E=w.isTalking||T,D=()=>{w.state===`idle`||w.state===`error`?w.start():w.state!==`stopping`&&w.stop()},O=le(),k=or(),ee=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,A=no(k.request,ee),j=O.length>0?d(s,{children:O.map(e=>d(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return d(bt,{serverUrl:i,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:v,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S,...A===null?{}:{...A,onExitPlayback:()=>k.clear()},streams:u,pipelineMetrics:f,phase:o.phase,detections:o,...l===void 0?{}:{stationaryObjects:l},defaultShowDetections:!0,defaultShowMotion:!0,showPlayStop:!0,snapshotSrc:C.src,...C.src?{posterUrl:C.src}:{},snapshotLoading:C.loading,onRefreshSnapshot:C.refresh,intercomAvailable:t,intercomShown:E,onIntercomToggle:D,extraOverlay:j,chromeless:!0,className:`h-full`})}function io({deviceId:e,containerDeviceId:t}){let{t:n}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full`,children:d(kn,{...t===void 0?{deviceId:e}:{containerDeviceId:t},limit:50,maxHeight:`max-h-full`,showScope:!1,showFilters:!1})}):d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:n(`device.panelContent.notLoaded`,{id:e})})}function ao({deviceId:e}){let{t}=Z();if(!Number.isFinite(e))return d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})});let n=[`CamStack REPL — device #${e}`,``,` device.state.battery.value sync state read`,` await device.snapshot.getSnapshot({}) cap action`,``,` type 'examples' for more, 'context' for the full API`].join(`
|
|
2
|
-
`);return d(to,{scope:{type:`device`,deviceId:e},greeting:n,className:`h-full border-0 rounded-none`})}function oo({deviceId:e}){let{t}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:d(xn,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})})}function so({deviceId:e}){let{t}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:d(Tn,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})})}var co=960;function lo(e){return new Set(e.filter(e=>{let t=e.nativeAddonId?.trim()??``;return t!==``&&t!==`composer`}).map(e=>e.capName))}function uo(e){return e.kind===`known`?null:e}function fo(e,t){return e.composable.kind===`known`?e.composable.value.has(t)?{kind:`present`,mode:`add`}:{kind:`absent`}:e.composable}function po(e){if(e.deviceType!==J.Camera)return{kind:`absent`};switch(e.cameraSensors){case`pending`:return{kind:`pending`};case`unknown`:return{kind:`unknown`,reason:X.t(`helpers.assignmentAvailability.sensorsUnchecked`)};case`absent`:return{kind:`absent`};case`present`:return{kind:`present`,mode:`add`}}}function mo(e,t){if(e===`motion`)return po(t);let n=uo(t.nativeCaps);if(n!==null)return n;let r=t.nativeCaps.kind===`known`?t.nativeCaps.value:new Set;switch(e){case`doorbell`:return r.has(`doorbell`)?{kind:`absent`}:fo(t,`doorbell`);case`battery`:return r.has(`battery`)?{kind:`present`,mode:`replace`}:fo(t,`battery`);case`consumables`:return r.has(`consumables`)?{kind:`absent`}:fo(t,`consumables`)}}function ho({onAdvanced:e}){let{t}=Z();return e===void 0?null:d(`button`,{type:`button`,className:`rounded text-left text-[11px] text-primary hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary`,onClick:e,children:t(`customize.advancedLink`)})}function go(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??X.t(`helpers.customize.requestFailed`)};let t=e.data;if(t===void 0)return{kind:`pending`};if(t.state===`not-loaded`)return{kind:`not-loaded`,reason:t.reason};if(t.view===null)return{kind:`none`};let n=Ce(t.view.block);return n===null?{kind:`unknown`,reason:X.t(`helpers.customizationRead.notAComposition`,{id:t.view.block.id})}:{kind:`present`,view:t.view,composition:n}}function _o(e){return e.kind===`present`?e.composition:null}function vo(e,t){let{hidden:n,...r}=e??{},i=t?{...r,hidden:!0}:r;return Object.keys(i).length===0?null:i}function yo(e){return typeof e.linkDeviceId==`number`}var bo=new Set(Object.values(q));function xo(e){return bo.has(e)}var So={[J.Switch]:[q.Siren,q.Floodlight,q.Spotlight,q.PirSensor,q.Chime,q.Autotrack,q.Nightvision,q.PrivacyMask,q.BinaryHelper],[J.Light]:[q.Floodlight,q.Spotlight,q.Nightvision],[J.Siren]:[q.Siren],[J.Button]:[q.Doorbell],[J.Sensor]:[q.MotionSensor,q.ContactSensor,q.LeakSensor,q.SmokeSensor,q.COSensor,q.GasSensor,q.TamperSensor,q.VibrationSensor,q.ConnectivitySensor,q.SoundSensor,q.BinarySensor,q.TemperatureSensor,q.HumiditySensor,q.AmbientLightSensor,q.PressureSensor,q.WindSensor,q.RainSensor,q.UvSensor,q.SolarRadiationSensor,q.SoilMoistureSensor,q.PowerSensor,q.EnergySensor,q.VoltageSensor,q.CurrentSensor,q.AirQualitySensor,q.BatterySensor,q.NumericSensor,q.EnumSensor,q.DateTimeSensor,q.GenericSensor],[J.Control]:[q.NumericControl,q.SelectControl,q.TextControl,q.DateTimeControl],[J.Notifier]:[q.MobilePushNotifier,q.MessagingNotifier,q.EmailNotifier,q.GenericNotifier]};function Co(e){for(let t of Object.values(J))if(t===e)return!0;return!1}function wo(e){return Co(e)?So[e]??[]:[]}function To(e,t){let n=wo(t);return e==null||e===``||n.includes(e)?n:[...n,e]}e();function Eo({device:e}){let{t}=Z(),n=ue(),i=c(),[o,s]=r(null),l=()=>s(null),u={onSuccess:()=>{l(),i.invalidateQueries({queryKey:[[`deviceManager`]]})},onError:e=>s(e.message)},f=Nr(),p=qn(),h=e.display?.hidden===!0;return a(`section`,{"aria-label":t(`customize.identity.title`),className:`${E} ${m}`,children:[a(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4`,children:[d(oi,{deviceId:e.id,initialName:e.name,label:t(`customize.identity.name`),layout:`stacked`,onError:s,onSaved:l,onCancel:l}),d(Ur,{deviceId:e.id,initialLocation:e.location,label:t(`customize.identity.room`),layout:`stacked`,onError:s,onSaved:l,onCancel:l}),d(Hr,{label:t(`customize.identity.hidden`),layout:`stacked`,value:d(zt,{"aria-label":t(`deviceDisplay.hideFromLists`),checked:h,disabled:p.isPending,onChange:t=>p.mutate({deviceId:e.id,display:vo(e.display,t.target.checked)},u)})}),d(Hr,{label:t(`customize.identity.role`),layout:`stacked`,value:yo(e)?d(`span`,{children:Do(e.role,t(`customize.identity.noRole`),n)}):d(qt,{"aria-label":t(`customize.identity.role`),value:e.role??``,disabled:f.isPending,options:[{value:``,label:t(`customize.identity.noRole`)},...To(e.role,e.type).map(e=>({value:e,label:Do(e,t(`customize.identity.noRole`),n)}))],onChange:t=>f.mutate({deviceId:e.id,role:t.target.value===``?null:t.target.value},u)})})]}),o!==null&&d(`p`,{role:`alert`,className:`mt-2 text-xs text-danger break-words`,children:o})]})}function Do(e,t,n){return e==null||e===``?t:xo(e)?Ct(e,n).label:e}e();function Oo(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function ko({excludeDeviceIds:e,onSelect:t}){let{t:r}=Z(),i=En({projection:`slim`}),a=i.status===`success`?i.data:null,o=n(()=>{if(a===null)return[];let t=new Set(e);return hi(a).filter(e=>!t.has(e.id))},[a,e]),s=n(()=>new Map(o.map(e=>[e.id,e])),[o]),c=n(()=>o.map(e=>({id:e.id,name:e.name,type:e.type,...e.location===null?{}:{location:e.location}})),[o]);if(i.status===`error`)return d(Jn,{title:r(`customize.picker.devicesFailed`),message:i.error?.message??``});let l=e=>{let n=s.get(e);n!==void 0&&t(n)};return d(_t,{devices:c,listState:Oo(i.status),value:[],onChange:e=>{let t=e.at(-1);t!==void 0&&l(t)},noun:`device`,emptyLabel:r(`customize.assign.none`),showAll:!0,testId:`customize-field-device-picker`})}function Ao({open:e,title:t,targetKind:n,excludeDeviceIds:i,confirmLabel:o,extra:c,extraComplete:l=!0,onConfirm:u,onClose:f}){let{t:p}=Z(),[m,h]=r(null),[g,_]=r(null),v=()=>{h(null),_(null),f()};return d(Qt,{open:e,onOpenChange:e=>e?void 0:v(),children:a(Hn,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[d(Sr,{children:d(er,{children:t})}),d(ot,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:e&&a(s,{children:[a(`section`,{"aria-label":p(`customize.assign.stepDevice`),className:`flex flex-col gap-1`,children:[d(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:p(`customize.assign.stepDevice`)}),m===null?d(ko,{excludeDeviceIds:i,onSelect:h}):a(`p`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[m.name,d(Y,{variant:`ghost`,size:`sm`,onClick:()=>{h(null),_(null)},children:p(`customize.assign.change`)})]})]}),m!==null&&a(`section`,{"aria-label":p(`customize.assign.stepField`),className:`flex flex-col gap-1`,children:[d(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:p(`customize.assign.stepField`)}),d(pi,{device:m,targetKind:n,selected:g===null?null:{cap:g.cap,path:g.path},onPick:_,onBack:()=>{h(null),_(null)}})]}),m!==null&&c!==void 0&&a(`section`,{"aria-label":p(`customize.assign.stepDetails`),className:`flex flex-col gap-1`,children:[d(`h3`,{className:`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:p(`customize.assign.stepDetails`)}),c]})]})}),a(ur,{children:[d(Y,{variant:`ghost`,onClick:v,children:p(`customize.assign.cancel`)}),d(Y,{disabled:g===null||!l,onClick:()=>{g!==null&&(u(g),h(null),_(null))},children:o})]})]})})}function jo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mo(e,t){let n=Di(e,t);return n===void 0?{kind:`absent`}:{kind:`value`,value:n}}function No(e,t,n){return jo(t)?Mo(t,n):e.status===`error`?{kind:`unknown`,reason:e.error?.message??X.t(`helpers.liveValue.unreadable`)}:e.status===`pending`||e.data===void 0?{kind:`pending`}:e.data===null?{kind:`absent`}:Mo(e.data,n)}function Po(e,t,n){let r=e?`active`:`muted`;return t.cap===`contact`&&t.path===`entryOpen`?{text:e?n.open:n.closed,tone:r}:Me[t.cap]===t.path?{text:e?n.active:n.inactive,tone:r}:{text:String(e),tone:`normal`}}function Fo(e,t,n){switch(e.kind){case`pending`:return{text:`…`,tone:`muted`};case`unknown`:return{text:`?`,title:e.reason,tone:`warning`};case`absent`:return{text:`—`,tone:`muted`};case`value`:{let r=e.value;return r===null?{text:`—`,tone:`muted`}:typeof r==`boolean`?Po(r,t,n):typeof r==`number`?{text:t.path===`percentage`?`${Math.round(r)} %`:String(r),tone:`normal`}:typeof r==`string`?{text:r,tone:`normal`}:{text:JSON.stringify(r),tone:`normal`}}}}var Io=0;function Lo(e){let t=H(),n=ln({deviceId:e?.deviceId??Io,capName:e?.cap??``},{enabled:e!==null}),r=Cr(t.trpcClient,e?.deviceId??null,e?.cap??``);return e===null?{kind:`absent`}:No({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}},r,e.path)}var Ro={muted:`text-foreground-subtle`,active:`text-success`,normal:`text-foreground`,warning:`text-warning`};function zo({target:e}){let{t}=Z(),n=Lo(e);return e===null?null:d(Bo,{display:Fo(n,e,{active:t(`customize.assign.value.active`),inactive:t(`customize.assign.value.inactive`),open:t(`customize.assign.value.open`),closed:t(`customize.assign.value.closed`)})})}function Bo({display:e}){return d(`span`,{className:`text-xs ${Ro[e.tone]}`,title:e.title,children:e.text})}function Vo({name:e,detail:t,meta:n,value:r,shown:i,readout:o,problem:s,onRemove:c,removeLabel:l,busy:u=!1}){return a(`li`,{className:`${A} grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)_1.75rem]`,children:[a(`div`,{className:`min-w-0`,children:[d(`div`,{className:`text-xs text-foreground break-words`,children:e}),t!==null&&d(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t}),s!==void 0&&d(`div`,{role:`alert`,className:`text-[11px] text-warning break-words`,children:s})]}),d(`div`,{className:`row-start-2 col-start-1 text-[11px] text-foreground-subtle empty:hidden sm:row-start-auto sm:col-start-auto sm:empty:block`,children:n}),d(`div`,{className:`row-start-3 col-start-1 empty:hidden sm:row-start-auto sm:col-start-auto sm:empty:block`,children:o===void 0?i===void 0?d(zo,{target:r}):i!==null&&d(Bo,{display:i}):o}),d(`div`,{className:`row-start-1 col-start-2 flex justify-end sm:row-start-auto sm:col-start-auto`,children:c!==void 0&&d(Xt,{icon:ie,variant:`ghost`,size:`sm`,"aria-label":l,disabled:u,onClick:c})})]})}function Ho({id:e,...t}){return d(cr,{headingId:`customize-${e}`,...t})}function Uo({id:e,icon:t,title:n,headerControl:r,addLabel:i,onAdd:o,addDisabled:c=!1,notices:l,suggestion:u,children:f}){let{t:p}=Z(),m=o!==void 0&&i!==void 0;return a(Ho,{id:e,icon:t,title:n,actions:a(s,{children:[r,m&&!c&&u!==void 0&&u.count>0&&a(Y,{variant:`ghost`,size:`sm`,onClick:u.onOpen,children:[d(F,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),p(`customize.suggest.hint`,{count:u.count,location:u.location})]}),m&&d(Y,{variant:`outline`,size:`sm`,disabled:c,onClick:o,children:i})]}),children:[l!==void 0&&d(`div`,{className:`flex flex-col gap-1 px-3 pt-2 empty:hidden sm:px-4`,children:l}),d(`ul`,{className:`flex flex-col divide-y divide-border`,children:f})]})}function Wo({availability:e}){let{t}=Z();return e.kind===`pending`?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.assign.checking`)}):e.kind===`unknown`?d(`p`,{role:`alert`,className:`text-xs text-warning`,children:t(`customize.assign.unknown`,{reason:e.reason})}):null}function Go(e,t){if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??X.t(`helpers.customize.requestFailed`)};let n=e.data;return e.status===`pending`||n===void 0?{kind:`pending`}:{kind:`known`,value:t(n)}}function Ko(e,t){let n=st.useQueries(n=>e.map(e=>n.deviceManager.listDeviceIdsByCaps({capNames:[e]},{enabled:t})));return ua(e.map((e,t)=>{let r=n[t];return{cap:e,query:r===void 0?{status:`pending`}:{status:r.status,data:r.data,error:r.error===null?null:{message:r.error.message}}}}))}e();function qo(e,t){let n=ir(e,t);return n.kind===`resolved`?n.integration.name:null}function Jo(e){let t=En({projection:`slim`},{enabled:e}),{data:r}=xt(void 0,{enabled:e}),i=t.error===null||t.error===void 0?null:t.error.message;return n(()=>Go({status:t.status,data:t.data,error:i===null?null:{message:i}},e=>e.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,type:e.type,location:e.location,isCamera:e.isCamera,integration:qo(e,r),parentDeviceId:e.parentDeviceId,primaryChildEntityId:e.primaryChildEntityId??null,role:e.role??null}))),[t.status,t.data,i,r])}function Yo(e){let t=Jo(e.enabled),n=Ko(Be,e.enabled);return t.kind===`unknown`?t:n.kind===`unknown`?n:t.kind===`pending`||n.kind===`pending`?{kind:`pending`}:{kind:`known`,value:oa({devices:t.value,capIndex:n.value,hostId:e.hostId,excludeCameras:e.excludeCameras,assigned:e.assigned,preferredCap:e.preferredCap})}}function Xo(){let{t:e}=Z(),t=lt();return(n,r)=>t({title:e(`customize.assign.removeConfirm.title`),message:r?`${e(`customize.assign.removeConfirm.message`,{what:n})} ${e(`customize.assign.removeConfirm.last`)}`:e(`customize.assign.removeConfirm.message`,{what:n}),confirmLabel:e(`customize.assign.removeConfirm.confirm`),variant:`danger`})}e();function Zo(e){return e===null?null:yi(e,`replace`)?`replace`:yi(e,`add`)?`add`:null}function Qo({device:e,handle:t,availability:n,onAdvanced:i}){let{t:o}=Z(),c=Xo(),[l,u]=r(!1),[f,p]=r(null),m=_o(t.state),h=Mi(m,`battery`),g=Zo(h),_=g===null?null:fi(h?.fields.percentage),v=Jo(_!==null);if(n.kind===`absent`)return null;let y=n.kind===`present`?n.mode:null,b=t.state.kind===`none`||t.state.kind===`present`,x=_===null||v.kind!==`known`?null:v.value.find(e=>K({addonId:e.addonId,stableId:e.stableId})===K(_.source))??null,S=_===null?``:x?.name??K(_.source),C=async e=>{let n=await t.save(e);p(n.kind===`refused`?n.reason:null)},w=async()=>{if(m===null)return;let e=ci(m,`battery`);await c(o(`customize.battery.removeWhat`,{name:S}),e===null)&&await C(e)},T=y!==null&&b&&h===null&&!t.saving;return a(s,{children:[a(Uo,{id:`battery`,icon:te,title:o(`customize.battery.title`),addLabel:o(y===`replace`?`customize.battery.replace`:`customize.battery.add`),onAdd:T?()=>u(!0):void 0,notices:a(s,{children:[d(Wo,{availability:n}),_!==null&&v.kind===`unknown`&&d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:o(`customize.assign.devicesUnreadable`,{reason:v.reason})}),f!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:f})]}),children:[y===`replace`&&b&&d(Vo,{name:o(`customize.battery.native`),detail:null,meta:o(h===null?`customize.assign.native`:`customize.battery.nativeReplaced`),value:h===null?{deviceId:e.id,cap:`battery`,path:`percentage`}:null,removeLabel:``}),h===null&&y===`add`&&b&&d(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:o(`customize.assign.none`)}),_!==null&&d(Vo,{name:S,detail:`${_.cap}.${_.fieldPath}`,meta:o(g===`replace`?`customize.assign.replaces`:`customize.assign.adds`),value:x===null?null:{deviceId:x.id,cap:_.cap,path:_.fieldPath},problem:x===null&&v.kind===`known`?o(`customize.assign.missingKept`):void 0,onRemove:b?()=>void w():void 0,removeLabel:o(`customize.assign.removeNamed`,{name:S}),busy:t.saving}),h!==null&&_===null&&d(Vo,{name:o(`customize.battery.otherFormula`),detail:null,meta:d(ho,{onAdvanced:i}),value:{deviceId:e.id,cap:`battery`,path:`percentage`},removeLabel:``})]}),d(Ao,{open:l,title:o(y===`replace`?`customize.battery.replace`:`customize.battery.add`),targetKind:`number`,excludeDeviceIds:[e.id],confirmLabel:o(`customize.assign.add`),onConfirm:e=>{u(!1);let n=y===null?null:ki({percentage:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},mode:y});n===null?p(o(`customize.assign.pickUnusable`)):C(di(m,t.target,n))},onClose:()=>u(!1)})]})}var $o=`consumables`,es=`items`,ts=Se.shape.items;function ns(e){let t=e.split(`.`).pop()??e,n=t.replace(/Level$/,``);return n===``?t:n}function rs(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function is(e,t){return e.caps.filter(e=>t.has(e.cap)&&e.cap!==`consumables`).flatMap(e=>e.fields.filter(e=>e.item!==!0&&Pr(e)).map(t=>({kind:`field`,key:ns(t.path),cap:e.cap,path:t.path})))}function as(e){switch(e.kind){case`pending`:return{kind:`pending`};case`unknown`:return{kind:`unknown`,reason:e.reason};case`absent`:return{kind:`known`,value:[]};case`value`:{if(e.value===null)return{kind:`known`,value:[]};let t=ts.safeParse(e.value);return t.success?{kind:`known`,value:t.data.map(e=>({kind:`item`,key:e.key,item:e}))}:{kind:`unknown`,reason:t.error.message}}}}function os(e,t,n){if(e.kind!==`known`)return e;if(t.kind!==`known`)return t;let r=is(t.value,e.value);if(!e.value.has(`consumables`)||n===null)return{kind:`known`,value:r};let i=as(n);return i.kind===`known`?{kind:`known`,value:[...r,...i.value]}:i}function ss({deviceId:e,defaults:t}){return t.map(t=>t.kind===`field`?d(cs,{deviceId:e,entry:t},`field:${t.cap}.${t.path}`):d(us,{entry:t},`item:${t.key}`))}function cs({deviceId:e,entry:t}){let{t:n}=Z(),r=Lo({deviceId:e,cap:t.cap,path:t.path});return d(Vo,{name:n(`customize.consumables.fields.${t.key}`,{defaultValue:rs(t.key)}),detail:n(`customize.consumables.builtIn`),meta:n(`customize.assign.native`),value:null,readout:d(ls,{value:r}),removeLabel:``})}function ls({value:e}){switch(e.kind){case`pending`:return d(Bo,{display:{text:`…`,tone:`muted`}});case`unknown`:return d(Bo,{display:{text:`?`,title:e.reason,tone:`warning`}});case`absent`:return d(jn,{level:null,size:`sm`});case`value`:return d(jn,{level:Ln(e.value),size:`sm`})}}function us({entry:e}){let{t}=Z(),{item:n}=e,r=n.level===null?n.status===`replace`?t(`uiLibrary.consumablesPanel.replace`):void 0:`${Math.round(n.level)} %`;return d(Vo,{name:n.label,detail:t(`customize.consumables.builtIn`),meta:t(`customize.assign.native`),value:null,readout:d(jn,{level:Dr(n),label:r,size:`sm`}),removeLabel:``})}e();function ds(e,t){let n=e.source;if(n===null||t.kind!==`known`)return null;let r=K(n.source);return t.value.find(e=>K({addonId:e.addonId,stableId:e.stableId})===r)??null}function fs(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;return Number.isFinite(t)?t:null}function ps({device:e,handle:t,availability:n,onAdvanced:i,defaults:o}){let{t:c}=Z(),l=Xo(),[u,f]=r(!1),[p,m]=r(``),[h,g]=r(`percent`),[_,v]=r(null),y=_o(t.state),b=Mi(y,`consumables`),x=_i(b),S=Jo(x.some(e=>e.source!==null)),C=o.kind===`known`?o.value:[];if(n.kind===`absent`&&C.length===0&&o.kind!==`unknown`)return null;let w=t.state.kind===`none`||t.state.kind===`present`,T=n.kind===`present`&&w&&!t.saving,E=vi(p),D=x.find(e=>e.key===E)??null,k=D!==null,ee=p.trim()!==``&&E===``,A=async e=>{let n=await t.save(e);v(n.kind===`refused`?n.reason:null)},j=()=>{f(!1),m(``),g(`percent`)},te=async e=>{if(b===null||y===null)return;let n=Ai(b,e.key),r=n===null?ci(y,`consumables`):di(y,t.target,n);await l(c(`customize.consumables.removeWhat`,{name:e.label}),r===null)&&await A(r)},M=a(`div`,{className:`flex flex-wrap items-end gap-2`,children:[a(`label`,{className:`flex w-full flex-col gap-1 text-[11px] text-foreground-subtle sm:w-56`,children:[c(`customize.consumables.name`),d(Wt,{"aria-label":c(`customize.consumables.name`),value:p,onChange:e=>m(e.target.value)})]}),a(`label`,{className:`flex w-full flex-col gap-1 text-[11px] text-foreground-subtle sm:w-40`,children:[c(`customize.consumables.unit`),d(qt,{"aria-label":c(`customize.consumables.unit`),value:h,options:xi.map(e=>({value:e,label:c(`customize.consumables.units.${e}`)})),onChange:e=>{let t=xi.find(t=>t===e.target.value);t!==void 0&&g(t)}})]}),k&&d(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:c(`customize.consumables.takenBy`,{name:D.label})}),ee&&d(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:c(`customize.consumables.keyless`)})]});return a(s,{children:[a(Uo,{id:`consumables`,icon:O,title:c(`customize.consumables.title`),addLabel:c(`customize.consumables.add`),onAdd:T?()=>f(!0):void 0,notices:a(s,{children:[d(Wo,{availability:n}),S.kind===`unknown`&&x.some(e=>e.source!==null)&&d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:c(`customize.assign.devicesUnreadable`,{reason:S.reason})}),o.kind===`unknown`&&d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:c(`customize.consumables.builtInUnreadable`,{reason:o.reason})}),_!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:_})]}),children:[d(ss,{deviceId:e.id,defaults:C}),x.map(e=>{let n=e.source;if(e.unit===null||n===null)return d(Vo,{name:e.label,detail:c(`customize.consumables.otherFormula`),meta:d(ho,{onAdvanced:i}),value:null,removeLabel:``},e.key);let r=ds(e,S),a=r?.name??K(n.source);return d(Vo,{name:e.label,detail:`${c(`customize.consumables.units.${e.unit}`)} · ${a}`,meta:`${n.cap}.${n.fieldPath}`,value:r===null?null:{deviceId:r.id,cap:n.cap,path:n.fieldPath},problem:r===null&&S.kind===`known`?c(`customize.assign.missingKept`):void 0,onRemove:w?()=>void te(e):void 0,removeLabel:c(`customize.assign.removeNamed`,{name:e.label}),busy:t.saving},e.key)}),x.length===0&&C.length===0&&o.kind===`known`&&n.kind===`present`&&w&&d(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:c(`customize.assign.none`)})]}),d(Ao,{open:u,title:c(`customize.consumables.pickTitle`),targetKind:`number`,excludeDeviceIds:[e.id],confirmLabel:c(`customize.assign.add`),extra:M,extraComplete:E!==``&&!k,onConfirm:e=>{let n=fs(e.value);if(n!==null&&(n<0||h===`percent`&&n>100)){j(),v(c(`customize.consumables.outOfRange`,{value:n}));return}let r=gi(b,{key:E,label:p,remaining:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},unit:h});j(),r===null?v(c(`customize.assign.pickUnusable`)):A(di(y,t.target,r))},onClose:j})]})}function ms(e,t){if(e.kind!==`known`||typeof t!=`string`||t.length===0)return null;let n=hn(e.value,t),r=new Map(e.value.map(e=>[e.id,e])),i=new Map;for(let e of n){let t=r.get(e)?.parentDeviceId,n=t==null?void 0:r.get(t);n!==void 0&&n.type===`container`&&i.set(e,n.name)}return{location:t,ids:n,containers:i}}function hs(e,t,n){return dt(e,t?.ids??new Set,n)}function gs(e,t){return e?.containers.get(t)??null}function _s(e,t,n){return e.kind===`known`?hs(e.value,t,n).suggested.length:0}function vs(e,t){let n=[t,e.detail].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function ys({location:e,devices:t,action:n,onPick:r,onPickAll:i}){let{t:o}=Z();if(t.length===0)return null;let s=o(`customize.suggest.heading`,{location:e});return a(`section`,{"aria-label":s,className:`flex flex-col gap-1`,children:[a(`div`,{className:`flex min-h-7 items-center gap-2`,children:[d(`h3`,{className:`${j} min-w-0 flex-1`,children:s}),i!==void 0&&t.length>1&&d(Y,{variant:`ghost`,size:`sm`,onClick:i,children:o(`customize.suggest.addAll`,{count:t.length})})]}),d(`ul`,{className:`flex flex-col divide-y divide-border rounded-md border border-border`,children:t.map(e=>{let t=vs(e,e.container===null||e.name.includes(e.container)?null:o(`customize.suggest.in`,{container:e.container}));return a(`li`,{className:`${A} flex items-center gap-3`,children:[a(`div`,{className:`min-w-0 flex-1`,children:[d(`div`,{className:`text-xs text-foreground break-words`,children:e.name}),t!==null&&d(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t})]}),d(Y,{variant:`outline`,size:`sm`,"aria-label":o(n===`add`?`customize.suggest.addNamed`:`customize.suggest.useNamed`,{name:e.name}),onClick:()=>r(e.id),children:o(n===`add`?`customize.suggest.add`:`customize.suggest.use`)})]},e.id)})})]})}e();function bs(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function xs(e){return e.map(e=>({id:e.deviceId,name:e.name,...e.meta===null?{}:{type:e.meta},...e.detail===null?{}:{location:e.detail.includes(` · `)?e.detail.split(` · `).at(-1)??null:e.detail},...e.detail===null?{}:{detail:e.detail}}))}function Ss({open:e,title:i,selection:o,candidates:s,filters:c,room:l=null,confirmLabel:u,onConfirm:f,onClose:p}){let{t:m}=Z(),[h,g]=r(null),[_,v]=r([]),y=c?.find(e=>e.id===h)??c?.[0]??null,b=s.kind===`known`?s.value:[],x=s.kind===`known`?ea(s.value,``,y):[],S=hs(b,l,e=>e.deviceId).suggested,C=hs(x,l,e=>e.deviceId).others,w=n(()=>xs(C),[C]),T=bs(s),E=b.filter(e=>_.includes(e.deviceId));t(()=>{e||(v([]),g(null))},[e]);let D=()=>{v([]),g(null),p()},O=e=>{e.length!==0&&(f(e),v([]),g(null))},k=()=>O(E);return d(Qt,{open:e,onOpenChange:e=>e?void 0:D(),children:a(Hn,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":i,children:[d(Sr,{children:d(er,{children:i})}),a(ot,{className:`flex flex-col gap-2 p-2 sm:p-4`,children:[c!==void 0&&c.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,role:`tablist`,"aria-label":m(`customize.assign.filtersLabel`),children:c.map(e=>d(`button`,{type:`button`,role:`tab`,"aria-selected":(y?.id??null)===e.id,className:`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${(y?.id??null)===e.id?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:bg-surface-hover`}`,onClick:()=>g(e.id),children:m(e.labelKey)},e.id))}),l!==null&&d(ys,{location:l.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:gs(l,e.deviceId),detail:e.detail})),action:`add`,onPick:e=>O(S.filter(t=>t.deviceId===e)),...o===`multi`?{onPickAll:()=>O(S)}:{}}),s.kind===`unknown`?d(`p`,{role:`alert`,className:`text-xs text-warning`,children:m(`customize.assign.unknown`,{reason:s.reason})}):w.length===0&&S.length>0?null:d(_t,{devices:w,listState:T,value:_,onChange:e=>v(o===`single`?e.length>0?[e[e.length-1]]:[]:e),noun:`device`,emptyLabel:m(`customize.assign.none`),showAll:!0,testId:`customize-device-picker`})]}),a(ur,{children:[d(Y,{variant:`ghost`,onClick:D,children:m(`customize.picker.cancel`)}),d(Y,{disabled:E.length===0,onClick:k,children:u(E.length)})]})]})})}function Cs(e){if(e===null)return[];let t=Si(e);return Ti(e).map(e=>{let n=K(e);return{key:n,ref:e,caps:t.filter(e=>K(e.source)===n).map(e=>e.cap)}})}function ws(e,t){let n=Si(e);if(n.length===0)return!1;let{enabled:r,...i}=e,{enabled:a,...o}=je({camera:t,sources:n,enabled:!0});return ji(i,o)}function Ts(e){return e?.enabled!==!1}function Es(e,t,n){let r=[...e===null?[]:Si(e),...n.flatMap(e=>Ge(e.ref,e.caps))];return r.length===0?null:je({camera:t,sources:r,enabled:Ts(e)})}function Ds(e,t,n){let r=Si(e).filter(e=>K(e.source)!==n);return r.length===0?null:je({camera:t,sources:r,enabled:Ts(e)})}function Os(e,t){return{...e,enabled:t}}e();function ks({device:e,handle:t,availability:n,onAdvanced:i}){let{t:o}=Z(),c=Xo(),[l,u]=r(!1),[f,p]=r(null),m=_o(t.state),h=Mi(m,`doorbell`),g=h===null||ws(h,t.target),_=g?Cs(h):[],v=Jo(_.length>0),y=Yo({hostId:e.id,excludeCameras:!1,assigned:new Set(_.map(e=>e.key)),preferredCap:null,enabled:l});if(n.kind===`absent`)return null;let b=t.state.kind===`none`||t.state.kind===`present`,x=b&&!t.saving,S=n.kind===`present`&&x&&g,C=async e=>{let n=e===null?m===null?null:ci(m,`doorbell`):di(m,t.target,e),r=await t.save(n);p(r.kind===`refused`?r.reason:null)},w=async(e,n)=>{if(h===null||m===null)return;let r=Ds(h,t.target,e.key),i=r===null&&ci(m,`doorbell`)===null;await c(o(`customize.doorbell.removeWhat`,{name:n}),i)&&await C(r)},T=e=>v.kind===`known`?v.value.find(t=>K({addonId:t.addonId,stableId:t.stableId})===e.key)??null:null;return a(s,{children:[a(Uo,{id:`doorbell`,icon:D,title:o(`customize.doorbell.title`),headerControl:h===null?void 0:a(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground`,children:[d(zt,{"aria-label":o(`customize.doorbell.active`),checked:h.enabled!==!1,disabled:!x,onChange:e=>void C(Os(h,e.target.checked))}),o(`customize.doorbell.active`)]}),addLabel:o(`customize.doorbell.add`),onAdd:S?()=>u(!0):void 0,notices:a(s,{children:[d(Wo,{availability:n}),v.kind===`unknown`&&d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:o(`customize.assign.devicesUnreadable`,{reason:v.reason})}),f!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:f})]}),children:[_.map(e=>{let n=T(e),r=n?.name??e.key,i=ta(e.caps,null),a=i===null?void 0:Me[i];return d(Vo,{name:r,detail:n===null?null:ra(n.integration,n.location),meta:e.caps.join(`, `),value:n!==null&&i!==null&&a!==void 0?{deviceId:n.id,cap:i,path:a}:null,problem:n===null&&v.kind===`known`?o(`customize.assign.missingKept`):void 0,onRemove:b?()=>void w(e,r):void 0,removeLabel:o(`customize.assign.removeNamed`,{name:r}),busy:t.saving},e.key)}),!g&&d(Vo,{name:o(`customize.doorbell.otherFormula`),detail:null,meta:d(ho,{onAdvanced:i}),value:null,removeLabel:``}),h===null&&n.kind===`present`&&b&&d(`li`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:o(`customize.assign.none`)})]}),d(Ss,{open:l,title:o(`customize.doorbell.pickTitle`),selection:`multi`,candidates:y,confirmLabel:e=>o(`customize.assign.addCount`,{count:e}),onConfirm:e=>{u(!1),C(Es(h,t.target,e.map(e=>({ref:e.ref,caps:e.caps}))))},onClose:()=>u(!1)})]})}e();function As(e,t){let r=typeof e==`string`&&e.length>0,i=Jo(t&&r);return n(()=>t?ms(i,e):null,[t,i,e])}e();function js(e){return e==null?null:e.message}function Ms({device:e}){let t=ue(),{t:n}=Z(),i=c(),o=Xo(),l=Je.includes(e.type),[u,f]=r(!1),[p,m]=r(!1),[h,g]=r(null),_=pt({deviceId:e.id},{enabled:l}),v=sa({status:_.status,data:_.data,error:js(_.error)===null?null:{message:js(_.error)??``}}),y=v.kind===`present`?v.slot.slotRef:``,b=v.kind===`present`?[...ia(v.slot,v.value).map(e=>e.deviceId),...na(v.slot,v.value)]:[],x=Or(),S=Jo(l&&v.kind===`present`&&(u||b.length>0)),C=As(e.location,l&&v.kind===`present`),w=on({deviceId:e.id,slotRef:y},{enabled:(u||C!==null)&&v.kind===`present`});if(!l||v.kind===`absent`)return null;if(v.kind!==`present`)return d(Uo,{id:`linked`,icon:ae,title:n(`customize.linked.title`),notices:v.kind===`pending`?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:n(`customize.assign.checking`)}):d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:n(`customize.assign.unknown`,{reason:v.reason})}),children:null});let T=v.value,E=new Map(S.kind===`known`?S.value.map(e=>[e.id,e]):[]),D=T.trackedDeviceIds!==void 0,O=(e,t)=>{let n=E.get(e.deviceId);return{...e,name:e.name??n?.name??null,type:n?.type??null,detail:n===void 0?null:ra(n.integration,n.location),orphan:t}},k=[...ia(v.slot,T).map(e=>O(e,!1)),...na(v.slot,T).map(e=>O({deviceId:e,name:null,health:`ok`,implied:!1,tracked:!0},!0))],ee=new Set(b),A=S.kind===`unknown`?S:w.status===`error`?{kind:`unknown`,reason:js(w.error)??n(`helpers.customize.requestFailed`)}:S.kind===`pending`||w.status===`pending`||w.data===void 0?{kind:`pending`}:{kind:`known`,value:la(w.data.candidates,E,ee)},j=async t=>{if(p){g(n(`customize.saveInFlight`));return}m(!0),g(null);try{await x.mutateAsync({deviceId:e.id,slotRef:v.slot.slotRef,value:t}),await _.refetch(),await i.invalidateQueries({queryKey:[[`deviceManager`]]})}catch(e){g(e instanceof Error?e.message:String(e))}finally{m(!1)}},te=async e=>{await o(n(`customize.linked.removeWhat`,{name:e.name??`#${e.deviceId}`}),!1)&&await j(ca(T,e.deviceId))},M=[{key:`device`,header:n(`customize.linked.device`),cell:e=>a(`div`,{className:`flex flex-col min-w-0`,children:[d(`span`,{className:`truncate text-xs text-foreground`,children:e.name??`#${e.deviceId}`}),e.detail!==null&&d(`span`,{className:`truncate text-[11px] text-foreground-subtle`,children:e.detail}),e.orphan&&d(`span`,{className:`text-[11px] text-foreground-subtle`,children:n(`customize.linked.notLinked`)}),e.health!==`ok`&&d(`span`,{role:`alert`,className:`text-[11px] text-warning`,children:n(`customize.linked.health.${e.health}`)})]})},{key:`type`,header:n(`customize.linked.type`),headerClassName:`hidden sm:table-cell`,cellClassName:`hidden sm:table-cell text-xs text-foreground-subtle`,cell:e=>e.type===null?`—`:yr(e.type,t).label},{key:`controls`,header:n(`customize.linked.controls`),headerClassName:`hidden md:table-cell`,cellClassName:`hidden md:table-cell text-xs text-foreground-subtle`,cell:e=>e.orphan?`—`:n(`customize.linked.yes`)},...D?[{key:`tracked`,header:n(`customize.linked.tracked`),cellClassName:`text-right`,headerClassName:`text-right`,cell:e=>d(tr,{checked:e.tracked,disabled:p,"aria-label":n(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void j(aa(T,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:d(Xt,{icon:ie,variant:`ghost`,size:`sm`,"aria-label":n(`customize.assign.removeNamed`,{name:e.name??e.deviceId}),disabled:p,onClick:t=>{t.stopPropagation(),te(e)}})}];return a(s,{children:[d(Uo,{id:`linked`,icon:ae,title:n(`customize.linked.title`),addLabel:n(`customize.linked.add`),onAdd:p?void 0:()=>f(!0),...C===null?{}:{suggestion:{count:_s(A,C,e=>e.deviceId),location:C.location,onOpen:()=>f(!0)}},notices:a(s,{children:[S.kind===`unknown`&&d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:n(`customize.assign.devicesUnreadable`,{reason:S.reason})}),h!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:h})]}),children:a(`li`,{className:`list-none px-3 py-2 sm:px-4`,children:[k.length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:n(`customize.assign.none`)}):d(ht,{mode:`generic`,items:k,getKey:e=>String(e.deviceId),getSearchText:e=>[e.name??``,e.detail??``,e.type??``,String(e.deviceId)].join(` `),getFilterType:e=>e.type===null?null:yr(e.type,t).label,columns:M,searchPlaceholder:n(`customize.assign.search`),emptyLabel:n(`customize.assign.none`)}),k.some(e=>!e.orphan)&&d(`p`,{className:`mt-2 text-[10px] text-foreground-subtle`,children:n(`customize.linked.controlsAlways`)}),D&&d(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:n(`customize.linked.trackedHint`)})]})}),d(Ss,{open:u,title:n(`customize.linked.pickTitle`),selection:`multi`,candidates:A,room:C,confirmLabel:e=>n(`customize.assign.addCount`,{count:e}),onConfirm:e=>{f(!1),j(Qi(T,e.map(e=>e.deviceId)))},onClose:()=>f(!1)})]})}function Ns(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.sensors:[]}function Ps(e){return{addonId:e.addonId,stableId:e.stableId,mode:e.mode}}function Fs(e){return e.length===0?null:{sensors:[...e]}}function Is(e,t){let n=new Set(e.map(ze));return Fs([...e.map(Ps),...t.filter(e=>!n.has(ze(e))).map(e=>({...e,mode:Re}))])}function Ls(e,t,n){return Fs(e.map(e=>ze(e)===t?{...Ps(e),mode:n}:Ps(e)))}function Rs(e,t){return Fs(e.filter(e=>ze(e)!==t).map(Ps))}function zs(e){return e?.state===`configured`&&e.cameraMotion!==void 0}function Bs(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.cameraMotion??`always`:`always`}function Vs(e){return e===null||e.state===`unreadable`?!1:e.state===`not-configured`||zs(e)}function Hs(e){return e?.state===`configured`&&(e.notForwarded!==void 0||e.notEnforced!==void 0)}function Us(e,t,n){if(e!==`present`||t===null||n)return{kind:`none`};let r=t.cameraLevel;return r===void 0?{kind:`unknown`}:{kind:`level`,detected:r.detected,atMs:r.atMs}}e();var Ws=5e3;function Gs(e){return e.state===`missing`||e.state===`unreadable`?e.stableId:e.name}function Ks({device:e,availability:n,sensors:i}){let{t:o}=Z(),c=Xo(),u=It(),[f,p]=r(!1),[m,h]=r(null),g=l(!1),[_,v]=r(!1),[y,b]=r(!1),x=i.status,S=l(i.refetch);S.current=i.refetch,t(()=>{let e=setInterval(()=>{g.current||S.current()},Ws);return()=>clearInterval(e)},[]);let C=Ns(x);t(()=>{x!==null&&b(!1)},[x]);let w=i.presence===`present`&&Vs(x)&&!y?C:null,T=Jo(C!==null&&C.length>0),E=Yo({hostId:e.id,excludeCameras:!0,assigned:new Set((C??[]).map(ze)),preferredCap:`motion`,enabled:f});if(n.kind===`absent`)return null;let D=zs(x),O=Hs(x)?`passes`:Bs(x),k=Us(i.presence,x,y),ee=k.kind===`none`?null:k.kind===`unknown`?{text:`?`,tone:`warning`,title:o(`customize.motion.cameraLevelUnknown`)}:{text:o(k.detected?`customize.assign.value.active`:`customize.assign.value.inactive`),tone:k.detected?`active`:`muted`,title:o(`customize.motion.cameraLevelOwn`,{at:new Date(k.atMs).toLocaleTimeString()})},A=_||u.isPending,j=async t=>{if(g.current){h(o(`customize.saveInFlight`));return}g.current=!0,v(!0);try{await u.mutateAsync({deviceId:e.id,config:t}),h(null),await i.refetch()===`failed`&&b(!0)}catch(e){h(e instanceof Error?e.message:String(e))}finally{g.current=!1,v(!1)}},te=async e=>{w!==null&&await c(o(`customize.motion.removeWhat`,{name:Gs(e)}),!1)&&await j(Rs(w,ze(e)))},M=e=>{if(T.kind!==`known`||!(`deviceId`in e))return null;let t=T.value.find(t=>t.id===e.deviceId);return t===void 0?null:ra(t.integration,t.location)};return a(s,{children:[a(Uo,{id:`motion`,icon:W,title:o(`customize.motion.title`),addLabel:o(`customize.motion.add`),onAdd:w!==null&&n.kind===`present`?()=>p(!0):void 0,addDisabled:A,notices:a(s,{children:[d(Wo,{availability:n}),i.presence===`pending`&&n.kind!==`pending`&&d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:o(`customize.motion.reading`)}),x?.state===`unreadable`&&d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:o(`customize.motion.unreadable`,{reason:x.reason})}),x?.state===`configured`&&!Vs(x)&&d(`p`,{role:`alert`,className:`text-xs text-warning`,children:o(`customize.motion.olderOrchestrator`)}),y&&d(`p`,{role:`alert`,className:`text-xs text-warning`,children:o(`customize.motion.refetchFailed`)}),x?.state===`configured`&&x.notForwarded!==void 0&&d(`p`,{role:`alert`,className:`text-xs text-warning`,children:o(`customize.motion.notForwarded.${x.notForwarded}`)}),x?.state===`configured`&&x.notEnforced!==void 0&&d(`p`,{role:`alert`,className:`text-xs text-warning`,children:o(`customize.motion.notEnforced`)}),T.kind===`unknown`&&d(`p`,{role:`alert`,className:`text-xs text-warning break-words`,children:o(`customize.assign.devicesUnreadable`,{reason:T.reason})}),m!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:m})]}),children:[d(Vo,{name:o(`customize.motion.camera`),detail:null,meta:O===null?o(`customize.assign.native`):`${o(`customize.motion.cameraState.${O}`)} · ${o(`customize.assign.native`)}`,value:null,shown:ee,removeLabel:``}),(C??[]).map(e=>{let t=ze(e),n=Gs(e),r=e.state===`ready`?ta(e.caps,`motion`):null,i=r===null?void 0:Me[r];return d(Vo,{name:n,detail:M(e),meta:D&&w!==null?d(qt,{"aria-label":o(`customize.motion.modeFor`,{name:n}),value:e.mode,disabled:A,options:Ve.options.map(e=>({value:e,label:o(`customize.motion.mode.${e}`)})),onChange:e=>{let n=Ve.safeParse(e.target.value);n.success&&w!==null&&j(Ls(w,t,n.data))}}):o(`customize.motion.mode.${e.mode}`),value:r!==null&&i!==void 0&&`deviceId`in e?{deviceId:e.deviceId,cap:r,path:i}:null,problem:e.state===`ready`?void 0:e.reason===e.state?o(`customize.motion.state.${e.state}`):`${o(`customize.motion.state.${e.state}`)}: ${e.reason}`,onRemove:w===null?void 0:()=>void te(e),removeLabel:o(`customize.assign.removeNamed`,{name:n}),busy:A},t)})]}),d(Ss,{open:f,title:o(`customize.motion.pickTitle`),selection:`multi`,candidates:E,filters:$i,confirmLabel:e=>o(`customize.assign.addCount`,{count:e}),onConfirm:e=>{if(p(!1),w===null)return;let t=Is(w,e.map(e=>e.ref));if(t!==null&&t.sensors.length>8){h(o(`customize.motion.tooMany`,{max:8}));return}j(t)},onClose:()=>p(!1)})]})}var qs={"numeric-sensor":{fieldPath:`value`,unitField:`unit`},"temperature-sensor":{fieldPath:`celsius`,unitField:`unit`},"humidity-sensor":{fieldPath:`percent`,unitField:`unit`},"pressure-sensor":{fieldPath:`hpa`,unitField:`unit`},"ambient-light-sensor":{fieldPath:`lux`,unitField:`unit`}},Js=new Set([J.Camera]);function Ys(e){return e.unitField===null?[e.fieldPath]:[e.fieldPath,e.unitField]}function Xs(e,t){if(Js.has(e))return{kind:`absent`};let n=null;for(let[e,r]of Object.entries(qs))if(t.has(e)){n={cap:e,fieldPath:r.fieldPath,unitField:r.unitField};break}let r=null;for(let e of Ae)if(t.has(e)){let t=Me[e];if(t!==void 0){r={cap:e,fieldPath:t};break}}return n===null&&r===null?{kind:`absent`}:{kind:`present`,convert:n,invert:r}}function Zs(e){return ye(e.from,e.to)?We(e):null}function Qs(e){return qe(e)}var $s=/^convert\(v,\s*"[^"]*",\s*"[^"]*"\)$/;function ec(e){return e!==void 0&&$s.test(e.expr)}function tc(e){return e===void 0||e.expr===`!v`||$s.test(e.expr)?!1:e.bindings.v!==void 0}function nc(e){let t=e.expr.trim();if(t===``)return{kind:`refused`,reason:X.t(`helpers.numericTransforms.emptyExpression`)};let n={kind:`expression`,expr:t,bindings:{v:{kind:`from`,source:e.self,cap:e.cap,fieldPath:e.fieldPath}}},r=be({source:n,now:Date.now(),read:()=>({state:`fresh`,value:e.probe})});return r.state===`unavailable`?{kind:`refused`,reason:r.reason}:{kind:`ok`,feature:{kind:`fields`,cap:e.cap,fields:{[e.fieldPath]:n}}}}function rc(e,t,n){if(e===null)return null;let r=Mi(e,n.cap);if(r===null)return e;let i=new Set(Ys(n)),a=Object.fromEntries(Object.entries(r.fields).filter(([e])=>!i.has(e)));return Object.keys(a).length===0?ci(e,n.cap):di(e,t,{kind:`fields`,cap:n.cap,...r.enabled===void 0?{}:{enabled:r.enabled},fields:a,...r.items===void 0?{}:{items:r.items}})}e();function ic(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`unit`);return typeof t==`string`?t:void 0}function ac(e,t){if(typeof e!=`object`||!e)return;let n=Reflect.get(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function oc(e,t){let n=Mi(e,t.cap);if(n===null)return;let r=n.fields[t.fieldPath];return r!==void 0&&r.kind===`expression`?r:void 0}function sc(e,t){let n=oc(e,t);return n===void 0||!ec(n)?null:/^convert\(v,\s*"[^"]*",\s*"([^"]*)"\)$/.exec(n.expr)?.[1]??null}function cc(e,t){let n=oc(e,t);return n===void 0||!tc(n)?null:n.expr}function lc(e,t,n){let r=Mi(e,t);if(r===null)return!1;let i=r.fields[n];return i!==void 0&&i.kind===`expression`&&i.expr===`!v`}function uc(e){return typeof e==`number`||typeof e==`boolean`||typeof e==`string`?String(e):e===null?`null`:JSON.stringify(e)}function dc({device:e,target:t,handle:n,facts:i}){let{t:o}=Z(),s=H(),[c,l]=r(null),[u,f]=r(``),[p,h]=r(null),g=i.nativeCaps.kind===`known`?i.nativeCaps.value:null,_=g===null?null:Xs(e.type,g),v=_?.kind===`present`?_.convert?.cap??``:``,y=Cr(s.trpcClient,e.id,v);if(i.nativeCaps.kind===`pending`)return d(`section`,{className:`${E} ${m}`,children:d(Wo,{availability:{kind:`pending`}})});if(i.nativeCaps.kind===`unknown`)return d(`section`,{className:`${E} ${m}`,children:d(Wo,{availability:{kind:`unknown`,reason:i.nativeCaps.reason}})});if(_===null||_.kind===`absent`)return null;let b=_o(n.state),x=_.convert,S=_.invert,C=x===null?void 0:ic(y),w=C===void 0?void 0:we(C)??C,T=w===void 0?void 0:Ie(w),D=x===null?null:sc(b,x),O=x===null?null:cc(b,x),k=p??O??``,ee=S===null?!1:lc(b,S.cap,S.fieldPath),A=n.state.kind===`none`||n.state.kind===`present`,j=x===null?0:ac(y,x.fieldPath)??0,te=x!==null&&k.trim()!==``?{kind:`expression`,expr:k.trim(),bindings:{v:{kind:`from`,source:t,cap:x.cap,fieldPath:x.fieldPath}}}:null,M=te===null||x===null?null:Ci(te,new Map([[ke(t,x.cap),y===void 0?{kind:`pending`}:{kind:`value`,slice:y}]]),Date.now()),N=async e=>{let t=await n.save(e);l(t.kind===`refused`?t.reason:null)},P=async()=>{if(x===null||w===void 0||u===``)return;let e=Zs({self:t,cap:x.cap,fieldPath:x.fieldPath,from:w,to:u,unitField:x.unitField});if(e===null){l(o(`customize.numericTransforms.convertRefused`));return}h(null),await N(di(b,t,e))},ne=async()=>{x!==null&&(await N(rc(b,t,x)),f(``))},F=async()=>{if(x===null)return;let e=nc({self:t,cap:x.cap,fieldPath:x.fieldPath,expr:k,probe:j});if(e.kind===`refused`){l(e.reason);return}f(``),await N(di(b,t,e.feature))},I=async()=>{x!==null&&(await N(rc(b,t,x)),h(``))},L=async()=>{if(S===null)return;let e=Qs({self:t,cap:S.cap});if(e===null){l(o(`customize.numericTransforms.invertRefused`));return}await N(di(b,t,e))},re=async()=>{S===null||b===null||await N(ci(b,S.cap))};return d(Ho,{id:`numeric-transforms`,icon:Xe,title:o(`customize.numericTransforms.title`),testId:`numeric-transforms-card`,children:a(`div`,{className:`${m} flex flex-col gap-3`,children:[d(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`customize.numericTransforms.blurb`)}),c!==null&&d(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:c}),x!==null&&a(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-convert`,children:[d(`label`,{className:`text-[11px] font-medium text-foreground`,children:o(`customize.numericTransforms.publishUnit`)}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:w===void 0?o(`customize.numericTransforms.fromUnknown`):o(`customize.numericTransforms.fromUnit`,{unit:w})}),d(`div`,{className:`w-full sm:max-w-xs`,children:d(Vt,{dimension:T,value:u===``?D??``:u,onChange:e=>{f(e),e!==``&&h(``)},disabled:!A||n.saving||w===void 0,"aria-label":o(`customize.numericTransforms.toUnit`),inheritLabel:o(`customize.numericTransforms.pickUnit`),emptyReason:o(`customize.numericTransforms.fromUnknown`)})}),a(`div`,{className:`flex flex-wrap gap-2`,children:[d(Y,{size:`sm`,disabled:!A||n.saving||w===void 0||u===``||u===w,onClick:()=>void P(),children:o(`customize.numericTransforms.applyConvert`)}),D!==null&&d(Y,{size:`sm`,variant:`outline`,disabled:!A||n.saving,onClick:()=>void ne(),children:o(`customize.numericTransforms.clearConvert`)})]})]}),x!==null&&a(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-script`,children:[d(Ei,{label:o(`customize.numericTransforms.script`),value:k,bindings:[`v`],onChange:e=>{h(e),e.trim()!==``&&f(``)}}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`customize.numericTransforms.scriptBlurb`)}),M!==null&&d(`p`,{role:`status`,className:`text-[11px] font-mono text-foreground`,"data-testid":`numeric-script-preview`,children:M.kind===`value`?o(`customize.numericTransforms.preview`,{source:uc(j),result:uc(M.value)}):M.kind===`waiting`?o(`customize.numericTransforms.previewWaiting`):M.kind===`unavailable`?o(`customize.numericTransforms.previewError`,{reason:M.reason}):o(`customize.numericTransforms.previewRuntimeOnly`)}),a(`div`,{className:`flex flex-wrap gap-2`,children:[d(Y,{size:`sm`,disabled:!A||n.saving||k.trim()===``,onClick:()=>void F(),children:o(`customize.numericTransforms.applyScript`)}),O!==null&&d(Y,{size:`sm`,variant:`outline`,disabled:!A||n.saving,onClick:()=>void I(),children:o(`customize.numericTransforms.clearScript`)})]})]}),S!==null&&a(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-invert`,children:[d(`label`,{className:`text-[11px] font-medium text-foreground`,children:o(`customize.numericTransforms.invert`)}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`customize.numericTransforms.invertBlurb`)}),d(`div`,{className:`flex flex-wrap gap-2`,children:ee?d(Y,{size:`sm`,variant:`outline`,disabled:!A||n.saving,onClick:()=>void re(),children:o(`customize.numericTransforms.clearInvert`)}):d(Y,{size:`sm`,disabled:!A||n.saving,onClick:()=>void L(),children:o(`customize.numericTransforms.applyInvert`)})})]})]})})}e();function fc(e){return e instanceof Error?e.message:String(e)}function pc(e){let t=Tr({addonId:e.addonId,stableId:e.stableId}),n=Nn(),i=Yn(),a=pr(),o=go({status:t.status,data:t.data,error:t.error===null||t.error===void 0?null:{message:t.error.message}}),{t:s}=Z(),c=l(!1),[u,d]=r(!1),f=async e=>{let r=mi(o,e);try{switch(r.kind){case`refused`:return{kind:`refused`,reason:r.reason};case`noop`:return{kind:`saved`};case`create`:await n.mutateAsync({block:r.input});break;case`update`:await i.mutateAsync({blockId:r.blockId,expectedUpdatedAt:r.expectedUpdatedAt,block:{composition:r.composition}});break;case`delete`:await a.mutateAsync({blockId:r.blockId});break}return await t.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:fc(e)}}};return{target:e,state:o,saving:u||n.isPending||i.isPending||a.isPending,save:async e=>{if(c.current)return{kind:`refused`,reason:s(`customize.saveInFlight`)};c.current=!0,d(!0);try{return await f(e)}finally{c.current=!1,d(!1)}}}}var mc=`pipeline-orchestrator`;function hc(e){return e.status===`pending`?`pending`:e.status===`error`?`unknown`:e.data===void 0?`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function gc(e,t){return e===`absent`?`absent`:hc(t)}async function _c(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function vc(e,t){let n=lr(mc),r=sr({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>_c(r.refetch);return t?{presence:gc(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,refetch:i}:{presence:`absent`,status:null,refetch:i}}function yc(e,t){let n=Vn({deviceType:e.type}),r=vn({deviceId:e.id}),i=yn({deviceId:e.id}),a=Go(n,e=>new Set(e.caps.map(e=>e.cap))),o=Go(r,e=>lo(e.entries)),s=Go(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}function bc(e,t,n){let r=t.kind===`known`&&t.value.has(`consumables`),i=Lo(r?{deviceId:e,cap:$o,path:es}:null);return os(t,n,r?i:null)}function xc(){return{kind:`unknown`,reason:X.t(`helpers.fieldsTableRows.noValue`)}}function Sc(e,t){let n=K(e);return t.get(n)??n}function Cc(e,t,n){let r=n.nativeCaps.has(e.cap)?`replaced`:`added`,i=t.filter(t=>t.cap===e.cap&&t.origin===`composed`);if(e.cap===`doorbell`){let t=Ti(e).map(e=>Sc(e,n.sourceNames)).join(` + `),a=i.find(e=>e.field===`lastPressedAt`);return[{key:`doorbell`,label:X.t(`helpers.whatChangesRows.doorbell`),origin:{kind:r,from:t},value:a?.value??xc()}]}return e.cap===`consumables`?_i(e).map(e=>{let t=t=>xe(Ee,e.key,t),a=i.find(e=>e.field===t(`level`)||e.field===t(`remaining.value`)),o=e.source===null?``:Sc(e.source.source,n.sourceNames);return{key:`consumables.${e.key}`,label:X.t(`helpers.whatChangesRows.consumable`,{name:e.label}),origin:{kind:r,from:o},value:a?.value??xc()}}):i.map(e=>({key:e.key,label:`${e.cap}.${e.field}`,origin:{kind:r,from:e.from},value:e.value}))}function wc(e){let t=bi({composition:e.composition,nativeCaps:e.nativeCaps,state:e.state,nativeFields:new Map,snapshot:null,sourceNames:e.sourceNames});return e.composition.features.flatMap(n=>n.kind===`fields`?Cc(n,t,e):[])}function Tc(e,t){if(e?.state!==`configured`||e.sensors.length===0)return null;let n=e.cameraMotion===`never`?[]:[t.camera],r=e.sensors.map(e=>t.sensor(e.state===`missing`||e.state===`unreadable`?e.stableId:e.name,e.mode));return[...n,...r].join(` + `)}var Ec=`${A} grid grid-cols-1 gap-x-3 gap-y-0.5 items-baseline sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_minmax(0,1.5fr)]`,Dc=`font-mono text-[11px] text-foreground break-words`,Oc=`text-[11px] text-foreground-subtle break-words`,kc=`text-[11px] break-words sm:text-right`;function Ac({device:e,composition:t,state:n,nativeCaps:r,cameraSensors:i}){let{t:o}=Z(),s=t!==null&&n!==null,c=Jo(s),l=new Map(c.kind===`known`?c.value.map(e=>[K({addonId:e.addonId,stableId:e.stableId}),e.name]):[]),u=s&&r.kind===`known`?wc({composition:t,nativeCaps:r.value,state:n,sourceNames:l}):[],f=s&&r.kind===`known`&&u.length===0&&t.features.length>0,p=Tc(i,{camera:o(`customize.changes.motion.camera`),sensor:(e,t)=>o(`customize.changes.motion.${t}`,{name:e})}),m=s&&r.kind!==`known`;return u.length===0&&p===null&&!m&&!f?null:a(Ho,{id:`changes`,icon:re,title:o(`customize.changes.title`),children:[m&&d(`p`,{role:r.kind===`unknown`?`alert`:`status`,className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:r.kind===`unknown`?o(`customize.changes.unknown`,{reason:r.reason}):o(`customize.changes.reading`)}),f&&d(`p`,{className:`px-3 sm:px-4 py-1.5 sm:py-2 text-[11px] text-foreground-subtle`,children:o(`customize.changes.noRows`)}),a(`ul`,{className:`divide-y divide-border`,children:[u.map(e=>a(`li`,{className:Ec,children:[d(`span`,{className:Dc,children:e.label}),d(`span`,{className:Oc,children:c.kind===`known`?o(`customize.changes.origin.${e.origin.kind}`,{from:e.origin.from}):o(`customize.changes.originUnread.${c.kind}`,{kind:o(`customize.changes.kind.${e.origin.kind}`),reason:c.kind===`unknown`?c.reason:``})}),d(`span`,{className:kc,children:d(jc,{value:e.value})})]},e.key)),p!==null&&a(`li`,{className:Ec,children:[d(`span`,{className:Dc,children:o(`common.motionWord`)}),d(`span`,{className:Oc,children:p}),d(`span`,{className:kc,children:d(zo,{target:{deviceId:e.id,cap:`motion`,path:`detected`}})})]})]})]})}function jc({value:e}){let{t}=Z();switch(e.kind){case`value`:return a(`span`,{children:[wi(e.value,!0),e.staleReason!==null&&a(`span`,{className:`text-warning`,children:[` `,`·`,` `,t(`customize.changes.value.stale`,{reason:e.staleReason})]})]});case`unavailable`:return d(`span`,{className:`text-warning`,children:t(`customize.changes.value.unavailable`,{reason:e.reason})});case`unknown`:return d(`span`,{className:`text-foreground-subtle`,children:t(`customize.changes.value.unknown`,{reason:e.reason})});case`off`:return d(`span`,{className:`text-foreground-subtle`,children:t(`customize.status.off`)})}}e();function Mc({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=Z(),i=_r({deviceId:e}),a=i.data;return a==null?i.status===`error`?d(Jn,{title:r(`customize.deviceUnreadable`),message:i.error?.message??``,onRetry:()=>void i.refetch()}):a===null?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.noSuchDevice`,{deviceId:e})}):d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:r(`customize.loadingDevice`)}):a.addonId===`composer`?d(Nc,{device:a}):d(Pc,{device:a,target:{addonId:a.addonId,stableId:a.stableId},activeSubTab:t,onSubTabChange:n})}function Nc({device:e}){let{t}=Z(),n=e.stableId.startsWith(`composed-`)?e.stableId.slice(Oe.length):null;return a(`section`,{className:`${E} ${m} flex flex-col gap-2`,children:[d(`p`,{className:`text-xs text-foreground`,children:t(`customize.composed.body`)}),n!==null&&d(qr,{className:`text-[11px] text-primary hover:underline`,to:ti(n),children:t(`customize.composed.edit`)})]})}function Pc({device:e,target:t,activeSubTab:n,onSubTabChange:r}){let i=pc(t),o=lr(`composer`),{t:s}=Z(),c=vc(e.id,e.type===J.Camera),l=yc(e,_o(i.state)),u=bc(e.id,l.nativeCaps,l.wireable),f={deviceType:e.type,composable:l.composable,nativeCaps:l.nativeCaps,cameraSensors:c.presence},p=()=>r(ai),m=i.state.kind===`none`||i.state.kind===`present`;return n===`advanced`?a(`div`,{className:`flex flex-col gap-3`,children:[d(Ic,{state:i.state}),m&&d(Fc,{device:e,target:t,handle:i,facts:l,onDone:()=>r(`main`)})]}):a(`div`,{className:`flex flex-col gap-3`,children:[d(Eo,{device:e}),o===`absent`&&d(`p`,{role:`alert`,className:`text-xs text-warning`,children:s(`customize.composerAbsent`)}),i.state.kind!==`none`&&d(Ic,{state:i.state}),d(ks,{device:e,handle:i,availability:mo(`doorbell`,f),onAdvanced:p}),d(Ks,{device:e,handle:i,availability:mo(`motion`,f),sensors:c}),d(Qo,{device:e,handle:i,availability:mo(`battery`,f),onAdvanced:p}),d(ps,{device:e,handle:i,availability:mo(`consumables`,f),onAdvanced:p,defaults:u}),d(dc,{device:e,target:t,handle:i,facts:l}),d(Ms,{device:e}),d(Ac,{device:e,composition:_o(i.state),state:i.state.kind===`present`?i.state.view.state:null,nativeCaps:l.nativeCaps,cameraSensors:c.status}),a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[m?d(ho,{onAdvanced:p}):d(`span`,{}),d(Lc,{handle:i})]})]})}function Fc({device:e,target:t,handle:n,facts:r,onDone:i}){let a=n.state.kind===`present`?n.state:null;return d(Oi,{initial:a===null?li(t):ui(a.composition,``),blockId:a===null?null:a.view.block.id,deviceType:e.type,targetName:e.name,nativeCaps:r.nativeCaps,targetFields:r.wireable,onCancel:i,save:async e=>{let t=await n.save(e);return t.kind===`saved`&&i(),t}})}function Ic({state:e}){let{t}=Z();switch(e.kind){case`pending`:return d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.pending`)});case`unknown`:return d(Jn,{title:t(`customize.status.unknownTitle`),message:e.reason});case`not-loaded`:return d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.notLoaded`,{reason:e.reason})});case`none`:return null;case`present`:{let n=e.view.block;return a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(nn,{variant:n.status===`running`?`success`:n.status===`failed`?`danger`:`warning`,children:t(`customize.blockStatus.${n.status}`)}),!n.enabled&&d(nn,{variant:`default`,children:t(`customize.status.off`)}),n.lastError!==void 0&&d(`span`,{className:`text-[11px] text-foreground-muted break-words`,children:n.lastError}),e.view.state.kind===`unreachable`&&d(`span`,{className:`text-[11px] text-warning`,children:t(`customize.status.composerUnreachable`,{reason:e.view.state.error})})]})}}}function Lc({handle:e}){let{t}=Z(),n=lt(),[i,o]=r(null);if(e.state.kind!==`present`)return null;let s=async()=>{if(!await n({title:t(`customize.remove.title`),message:t(`customize.remove.message`),confirmLabel:t(`customize.remove.confirm`),variant:`danger`}))return;let r=await e.save(null);o(r.kind===`refused`?r.reason:null)};return a(`div`,{className:`flex flex-col items-start gap-1`,children:[d(Y,{variant:`danger`,size:`sm`,disabled:e.saving,onClick:()=>void s(),children:t(`customize.remove.button`)}),i!==null&&d(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:i})]})}var Rc=`overview`;function zc(e,t){return e.some(e=>e.id===t)?t:Rc}function Bc({deviceId:e}){let{t}=Z(),n=c(),r=Number.isFinite(e),{data:i}=_r({deviceId:e},{enabled:r}),o=typeof i?.type==`string`?i.type:`camera`;br([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:s,isLoading:l,isError:u,error:f}=vn({deviceId:e},{enabled:r}),{data:p}=Zt({deviceType:o},{enabled:!!o}),m=sn({onSuccess:()=>{n.invalidateQueries({queryKey:[[`deviceManager`,`getBindings`]]})}});if(l)return d(`div`,{className:`p-4`,children:d(`div`,{className:`h-20 rounded-lg border border-border bg-surface animate-pulse`})});if(u)return a(`div`,{className:`p-4 text-xs text-red-400`,children:[t(`device.bindingsTab.failedToLoadBindings`,`Failed to load bindings:`),` `,f instanceof Error?f.message:String(f)]});let h=new Map,g={};for(let e of p??[])g[e.capName]=e.wrappers;for(let e of s?.entries??[])h.set(e.capName,{...e,wrappers:g[e.capName]??[]});for(let e of p??[])h.has(e.capName)||h.set(e.capName,{capName:e.capName,kind:`unbound`,providerAddonId:``,providerNodeId:``,nativeAddonId:``,wrappers:e.wrappers});let _=[...h.values()].toSorted((e,t)=>e.capName.localeCompare(t.capName));if(_.length===0)return a(`div`,{className:`flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle`,children:[d(tt,{className:`h-8 w-8 opacity-40`}),d(`p`,{className:`text-xs`,children:t(`device.bindingsTab.noCapabilityProvidersApplicableTo`,`No capability providers applicable to this device yet.`)}),d(`p`,{className:`text-[10px] opacity-60`,children:t(`device.bindingsTab.nativeProvidersShowUpHere`,`Native providers show up here as soon as the owning addon registers them.`)})]});let v=_.filter(e=>e.kind!==`unbound`).length,y=[{key:`capability`,header:t(`device.bindingsTab.capability`,`Capability`),render:e=>d(`span`,{className:`font-mono text-foreground`,children:e.capName})},{key:`kind`,header:t(`device.bindingsTab.kind`,`Kind`),render:e=>d(Vc,{kind:e.kind})},{key:`provider`,header:t(`device.bindingsTab.activeProvider`,`Active Provider`),render:e=>d(`span`,{className:`font-mono text-foreground-subtle`,children:e.providerAddonId||d(`span`,{className:`opacity-40`,children:`—`})})},{key:`node`,header:t(`device.bindingsTab.node`,`Node`),render:e=>e.providerNodeId?d(Hc,{nodeId:e.providerNodeId}):d(`span`,{className:`text-[10px] opacity-40`,children:`—`})},{key:`native`,header:t(`device.bindingsTab.kindNative`,`Native`),render:e=>d(`span`,{className:`font-mono text-foreground-subtle`,children:e.nativeAddonId||d(`span`,{className:`opacity-40`,children:`—`})})},{key:`wrapper`,header:t(`device.bindingsTab.wrapper`,`Wrapper`),render:t=>{let n=t.kind===`wrapped`?t.providerAddonId:null;return d(Uc,{wrappers:t.wrappers,activeWrapperId:n,disabled:m.isPending,onPick:r=>{let i=n===r;m.mutate({deviceId:e,capName:t.capName,wrapperAddonId:r,active:!i})}})}}];return a(`div`,{className:`flex flex-col gap-3 p-1`,children:[d(`div`,{className:`text-[11px] text-foreground-subtle`,children:d($r,{i18nKey:`device.bindingsTab.boundSummary`,count:_.length,values:{bound:v},components:{b:d(`span`,{className:`font-medium text-foreground`}),em:d(`em`,{})}})}),d(Zn,{columns:y,rows:_,rowKey:e=>e.capName,minWidthPx:720})]})}function Vc({kind:e}){let{t}=Z();return e===`native`?a(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-success/30 text-success bg-success/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[d(R,{className:`h-3 w-3`}),t(`device.bindingsTab.kindNative`)]}):e===`wrapped`?a(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-primary/30 text-primary bg-primary/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[d(it,{className:`h-3 w-3`}),t(`device.bindingsTab.wrapped`)]}):e===`linked`?a(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-warning/30 text-warning bg-warning/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[d(ae,{className:`h-3 w-3`}),t(`device.bindingsTab.linked`)]}):a(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-border text-foreground-subtle/70 px-1.5 py-0.5 text-[10px] font-medium`,children:[d(x,{className:`h-3 w-3`}),t(`common.unbound`)]})}function Hc({nodeId:e}){return d(`span`,{className:`inline-flex items-center rounded-md border border-border px-1.5 py-0.5 font-mono text-[10px] ${e===`hub`?`text-foreground-subtle`:`text-foreground`}`,children:e})}function Uc({wrappers:e,activeWrapperId:t,disabled:n,onPick:r}){let{t:i}=Z();return e.length===0?d(`span`,{className:`text-[10px] opacity-40`,children:i(`device.bindingsTab.noneAvailable`,`none available`)}):d(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>{let o=e===t;return a(`button`,{disabled:n,onClick:()=>r(e),title:o?i(`device.bindingsTab.clickToDeactivateRevertTo`,`Click to deactivate (revert to native)`):i(`device.bindingsTab.activateWrapper`,`Activate wrapper {{wrapperId}}`,{wrapperId:e}),className:`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px] transition-colors disabled:opacity-50 ${o?`border-primary/40 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[d(o?k:me,{className:`h-3 w-3`}),e]},e)})})}function Wc({deviceId:e,activeSubTab:t,onSubTabChange:n,deviceType:r,isAdmin:i}){return a(`div`,{className:`flex flex-col gap-3`,children:[Gr(r,i)&&d(hr,{deviceId:e,readOnly:!0}),d(ri,{deviceId:e,activeSubTab:t,onSubTabChange:n})]})}e();var Gc=[[`pipelineOrchestrator`,`getCameraDetectionSource`]];function Kc(e){let t=c(),n=Wn({deviceId:e},{refetchOnMount:`always`}),a=Et(),[o,s]=r(null),[l,u]=r(null),d=i(async n=>{u(null),s(n);try{await a.mutateAsync({deviceId:e,source:n}),await t.invalidateQueries({queryKey:Gc})}catch(e){u(e instanceof Error?e.message:`Could not change the root detector`),await t.invalidateQueries({queryKey:Gc})}finally{s(null)}},[e,a,t]),f=n.data??null;return{view:f,isLoading:n.isLoading,source:o??f?.source??null,saving:o!==null,error:l,pick:d}}var qc=`object-detection`;function Jc(e){return[e.addonId,...e.children.flatMap(Jc)]}function Yc(e,t){if(e===`pipeline`)return new Set;let n=Xc(t,qc);return n===void 0?new Set:new Set(e===`onboard`?[n.addonId]:Jc(n))}function Xc(e,t){for(let n of e){if(n.addonId===t)return n;let e=Xc(n.children,t);if(e!==void 0)return e}}function Zc(e,t){return e===`onboard`?X.t(`helpers.detectionSourceModel.badgeCameraAi`):t===`object-detection`?X.t(`helpers.detectionSourceModel.badgeNoRoot`):X.t(`helpers.detectionSourceModel.badgeIdle`)}function Qc(e){switch(e){case`pipeline`:return X.t(`helpers.detectionSourceModel.explainPipeline`);case`onboard`:return X.t(`helpers.detectionSourceModel.explainOnboard`);case`none`:return X.t(`helpers.detectionSourceModel.explainNone`)}}function $c(e){switch(e){case`boxed`:return``;case`while-streaming`:return X.t(`helpers.detectionSourceModel.geometryWhileStreaming`);case`flag-only`:return X.t(`helpers.detectionSourceModel.geometryFlagOnly`);case`unknown`:return X.t(`helpers.detectionSourceModel.geometryUnknown`)}}function el(e,t){return e===`onboard`?X.t(`helpers.detectionSourceModel.noticeOnboard`):t===`object-detection`?X.t(`helpers.detectionSourceModel.noticeNoRoot`):X.t(`helpers.detectionSourceModel.noticeIdle`)}function tl({source:e,geometry:t,saving:n,error:r,onPick:i}){let{t:o}=Z(),s=t===`flag-only`,c=$c(t);return a(`section`,{"aria-label":o(`device.detectionSourceControl.rootDetector`,`Root detector`),"aria-busy":n,className:`space-y-1.5 rounded-md border border-border bg-surface px-3 py-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1.5`,children:[d(`h3`,{className:j,children:o(`device.detectionSourceControl.rootDetector`,`Root detector`)}),d(at,{label:o(`device.detectionSourceControl.rootDetector`,`Root detector`),value:e,onChange:t=>{!n&&t!==e&&i(t)},options:[{value:`pipeline`,label:o(`device.detectionSourceControl.thisNode`,`This node`)},{value:`onboard`,label:o(`device.detectionSourceControl.cameraOnboardAi`,`Camera onboard AI`),disabled:s&&e!==`onboard`,reason:c},{value:`none`,label:o(`device.detectionSourceControl.none`,`None`)}]}),n&&d(`span`,{className:`text-[10px] text-foreground-subtle`,children:o(`device.detectionSourceControl.saving`,`Saving…`)})]}),a(`p`,{className:he,children:[Qc(e),` `,o(`device.detectionSourceControl.oneRoot`)]}),c!==``&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:c}),r!==null&&d(`p`,{role:`alert`,className:`text-[11px] text-danger`,children:r})]})}e();var nl=new Set([`package-detection`]);function rl(e){return e?.settings!==void 0&&Object.keys(e.settings).length>0?`accelerator`:`camera`}function il(e){return e===`camera`?X.t(`device.cameraStepInspector.modelSource.camera`):e===`node`?X.t(`device.cameraStepInspector.modelSource.node`):X.t(`device.cameraStepInspector.modelSource.default`)}function al(e){let{stored:t,draft:n,below:r,boundKeys:i}=e,a=n?.modelId===void 0?t?.modelId:n.modelId??void 0,o=Ne(n?.settings??t?.settings,r,i),s={...a===void 0?{}:{modelId:a},...o===void 0?{}:{settings:o}};return Object.keys(s).length>0?s:null}function ol(e,t){return(e?.modelId??null)===(t?.modelId??null)&&Pe(e?.settings??{},t?.settings??{})}function sl({deviceId:e}){let{t}=Z(),i=c(),l=H().trpcClient,u=gr({deviceId:e},{refetchOnMount:`always`}),f=Xn({deviceId:e},{refetchOnMount:`always`}),p=gt(void 0,{refetchOnMount:`always`}),m=G(Mt({addonId:`pipeline-orchestrator`}).data??null);br([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:h}=Nt(),g=n(()=>{let e=new Set((p.data??[]).map(e=>e.nodeId));return h.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[p.data,h]),_=g.map(e=>e.id).join(`,`),v=o({enabled:g.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,_],queryFn:async()=>{let e={};for(let t of g)try{e[t.id]=await l.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),y=o({enabled:g.length>0,queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`],`camera-step`,_],queryFn:async()=>{let e={};for(let t of g)try{e[t.id]=(await l.pipelineOrchestrator.getNodeInferenceDevices.query({nodeId:t.id})).devices}catch{e[t.id]=[]}return e}}),b=()=>{i.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]}),i.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStepOverrides`]]})},x=ut({onSuccess:b}),S=en(),C=Ir(),[w,T]=r(null),[E,D]=r(null),[O,k]=r(null),[ee,A]=r(!1),[te,M]=r(null),N=v.data??{},P=y.data??{},ne=f.data??{},F=u.data??null,I=g.map(e=>N[e.id]).find(e=>e!==void 0)??null,L=n(()=>I?Pt(I):[],[I]),re=n(()=>Vi(L),[L]),R=Kc(e),ie=n(()=>R.source===null?new Set:Yc(R.source,L),[R.source,L]),[z,B]=r(!1),V=n(()=>Wi(g,P,z),[g,P,z]),ae=n(()=>Wi(g,P,!0),[g,P]),oe=n(()=>Wi(g,P).length,[g,P]),se=(e,t)=>Fi(N[e.nodeId],t),U=(e,t)=>ne[e.nodeId]?.[e.deviceKey]?.[t],ce=(e,t)=>Yi(P[e.nodeId]??[],e.deviceKey,t)??{},le=e=>{if(nl.has(e))return{kind:`zone-driven`};let t=Fi(I,e)?.enabledByDefault??!0,n=F?.stepToggles?.[e];return{kind:`gate`,effectiveOn:n??t,defaultOn:t,explicit:n!==void 0}},ue=(e,t,n)=>{let r=n?.stepId===t?n:null;return{node:ce(e,t),camera:r?.camera??F?.stepSettings?.[t],accelerator:r?.perAccelerator[e.id]?.settings??U(e,t)?.settings}},de=(e,t,n)=>{let r=n?.stepId===t?n.perAccelerator[e.id]?.modelId:void 0;return r===void 0?U(e,t)?.modelId:r??void 0},W=(e,t)=>{if(ie.has(e))return{kind:`disabled`};let n=se(t,e),r=le(e),i=Ui(e),a=Ii(N[t.nodeId],t,U(t,`object-detection`)?.modelId),o=ue(t,e,null),s=Fe(o.node,o.camera,o.accelerator);return Ki({addon:n,acc:t,gatedOn:r.kind===`gate`?r.effectiveOn:!0,model:n?Hi(n,t,{nodePin:t.device.steps?.[e]?.modelId,cameraPin:U(t,e)?.modelId}):{modelId:void 0,source:`default`},...zi(e,s,a)&&a?{rootName:a.name}:{},...i?{clusterModelId:m[e]??i.defaultModelId}:{}})},fe=re.map(({node:e})=>({addonId:e.addonId,name:e.addonName,fieldLabels:Gi(Fi(I,e.addonId))}));return p.isLoading||g.length>0&&(v.isLoading||y.isLoading)?d(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.loadingPipeline`,`Loading pipeline…`)}):g.length===0?d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.noPipelineNodeIsOnline`,`No pipeline node is online.`)}):I===null?d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.catalogUnavailable`,`Catalog unavailable.`)}):a(`div`,{className:`space-y-2`,children:[R.view?.onboard.available===!0&&R.source!==null&&d(tl,{source:R.source,geometry:R.view.onboard.geometry,saving:R.saving,error:R.error,onPick:e=>void R.pick(e)}),d(Pi,{tree:L,searchRows:fe,accelerators:V,cellState:W,stepBadge:e=>ie.has(e)&&R.source!==null?d(nn,{variant:`warning`,title:el(R.source,e),children:Zc(R.source,e)}):d(Un,{gate:le(e)}),disabledCount:Ji(Object.fromEntries(g.map(e=>[e.id,P[e.id]??[]]))),showDisabled:z,onShowDisabledChange:B,dirty:w!==null,onDiscard:()=>T(null),summary:d(`span`,{className:he,children:t(`device.cameraStepInspector.balancedAcross`,{count:oe})}),label:t(`device.cameraStepInspector.detectionStepsOfThisCamera`,`Detection steps of this camera`),renderDetail:({stepId:n,accelerator:r,matchedField:i,closeButton:o,onEscape:c,headingRef:l})=>{let u=r??V[0],f=u?se(u,n)??Fi(I,n):null;if(f===null||u===void 0)return d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.noStepSelected`,`No step selected.`)});let p=w?.stepId===n?w:null,m=Dt(f),h=Te(m),g=ue(u,n,p),_=Fe(g.node,g.camera,g.accelerator),v=Ii(N[u.nodeId],u,U(u,`object-detection`)?.modelId),y=Hi(f,u,{nodePin:u.device.steps?.[n]?.modelId,cameraPin:de(u,n,p)}).modelId,P=Fe(g.node,g.camera),ne=Le(g.accelerator,P,h),L=Ui(n),re=le(n),z=m.find(e=>`label`in e&&e.label===i)?.key??null,B=r===null?null:`${n}|${r.id}`,oe=r===null?`camera`:E?.key===B?E.scope:rl(U(r,n)),H=e=>{M(null),T(t=>e(t?.stepId===n?t:{stepId:n,perAccelerator:{}}))},W=(e,t)=>H(n=>({...n,perAccelerator:{...n.perAccelerator,[e.id]:{...n.perAccelerator[e.id],...t}}})),fe=e=>H(t=>{let r=g.accelerator??{},i=Ue(t.camera??F?.stepSettings?.[n],e,r,h),a={...t.perAccelerator};for(let r of ae){let i=t.perAccelerator[r.id]?.settings??U(r,n)?.settings;i!==void 0&&(a[r.id]={...a[r.id],settings:Ke(i,e,h)})}return{...t,camera:i,perAccelerator:a}}),pe=async()=>{if(p!==null){A(!0);try{let t=F?.stepSettings?.[n];p.camera!==void 0&&!Pe(p.camera,t??{})&&await C.mutateAsync({deviceId:e,addonId:n,settings:Object.keys(p.camera).length>0?{...p.camera}:null});let r=p.camera??t;for(let t of ae){let i=p.perAccelerator[t.id];if(i===void 0)continue;let a=U(t,n),o=al({stored:a,draft:i,below:Fe(ce(t,n),r),boundKeys:h});ol(o,a)||await S.mutateAsync({deviceId:e,agentNodeId:t.nodeId,deviceKey:t.deviceKey,addonId:n,patch:o})}T(null),M({kind:`saved`})}catch(e){M({kind:`error`,error:e instanceof Error?e.message:t(`device.cameraStepInspector.saveFailed`)})}finally{A(!1),b()}}},me=p===null?0:+(p.camera!==void 0&&!Pe(p.camera,F?.stepSettings?.[n]??{}))+Object.values(p.perAccelerator).length,ge=e=>{let r=se(e,n)??f,i=de(e,n,p),a=e.device.steps?.[n]?.modelId,o=Hi(r,e,{nodePin:a,cameraPin:i}),c=ue(e,n,p),l=Ii(N[e.nodeId],e,U(e,`object-detection`)?.modelId),u=zi(n,Fe(c.node,c.camera,c.accelerator),l),m=Li(r,e)?u&&l?d(Yt,{rootModel:l,stepModelId:o.modelId}):void 0:d(s,{children:t(`device.cameraStepInspector.noBuild`,{format:e.device.format})});return{label:e.label,format:e.device.format,modelId:o.modelId,source:o.source,sourceLabel:il(o.source),models:wt(r.models??[],e.device.format),defaultModelId:r.defaultModelIdByFormat?.[e.device.format]??r.defaultModelId,expanded:O===e.id,onToggle:()=>k(t=>t===e.id?null:e.id),onChangeModel:t=>W(e,{modelId:t}),...i===void 0?{}:{onReset:()=>W(e,{modelId:null}),resetLabel:a===void 0?`Reset to hardware default`:`Reset to node pin`},...m===void 0?{}:{note:m},changed:p?.perAccelerator[e.id]?.modelId!==void 0}},_e=L===null&&m.length>0?r===null?d(`p`,{className:he,children:t(`device.cameraStepInspector.appliesToAllAcceleratorsOf`,`Applies to: all accelerators of this camera.`)}):a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(`span`,{className:`text-[11px] font-medium text-foreground`,children:t(`device.cameraStepInspector.appliesTo`,`Applies to`)}),d(at,{label:t(`device.cameraStepInspector.settingsApplyTo`,`Settings apply to`),options:[{value:`accelerator`,label:t(`device.cameraStepInspector.thisAccelerator`,`This accelerator`)},{value:`camera`,label:t(`device.cameraStepInspector.allAcceleratorsOfThisCamera`,`All accelerators of this camera`)}],value:oe,onChange:e=>B!==null&&D({key:B,scope:e})})]}):void 0;return d(Sn,{ref:l,title:r===null?t(`device.cameraStepInspector.thisCamera`,`{{name}} · this camera`,{name:f.name}):`${f.name} · ${r.label}`,subtitle:r===null?t(`device.cameraStepInspector.everyAcceleratorThisCameraRuns`,`{{slot}} · every accelerator this camera runs on`,{slot:f.slot}):`${f.slot} · ${r.device.format}`,leading:o,onEscape:c,headerActions:d(wr,{gate:re,busy:x.isPending,onSet:t=>x.mutate({deviceId:e,addonId:n,enabled:t})}),saveBar:{dirtyCount:me,saving:ee,status:te?.kind??null,...te?.error===void 0?{}:{error:te.error},onSave:()=>void pe(),onDiscard:()=>T(null),..._e===void 0?{}:{scope:_e}},children:a(`div`,{className:`space-y-3`,children:[ie.has(n)&&R.source!==null&&d(`p`,{role:`note`,className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-1.5 text-[11px] text-warning`,children:el(R.source,n)}),a(`section`,{className:`space-y-2`,"aria-label":t(`device.cameraStepInspector.model`,`Model`),children:[d(`h3`,{className:j,children:t(`device.cameraStepInspector.model`,`Model`)}),L===null?r===null?d(Ri,{rows:V.map(e=>{let t=Hi(se(e,n)??f,e,{nodePin:e.device.steps?.[n]?.modelId,cameraPin:de(e,n,p)});return{id:e.id,label:e.label,modelId:t.modelId,sourceLabel:il(t.source)}})}):d(At,{...ge(r)},r.id):d(qi,{step:L,engineFormat:u.device.format,runnableModelIds:wt(f.models??[],u.device.format).map(e=>e.id)})]}),L===null&&(m.length>0||v!==void 0)&&d(`section`,{"aria-label":t(`device.cameraStepInspector.settings`,`Settings`),className:`border-t border-border/60 pt-2`,children:d(cl,{addon:f,fields:m,layers:g,scope:oe,viewed:r,modelId:vt(f,y,_,v),root:v,pinned:r===null?[]:ne,highlightKey:z,onChangeCamera:e=>H(t=>({...t,camera:e})),onChangeAccelerator:e=>W(u,{settings:e}),onApplyToAll:fe,onFollowNode:()=>W(u,{settings:ne.reduce((e,t)=>Ke(e,t,h),{...g.accelerator})})})}),d(Ni,{addonId:n,highlightLabel:i})]})})}})]})}function cl({addon:e,fields:t,layers:n,scope:r,viewed:i,modelId:a,root:o,pinned:s,highlightKey:c,onChangeCamera:l,onChangeAccelerator:u,onApplyToAll:f,onFollowNode:p}){let{t:m}=Z();Bi(c===null?null:tn(c));let h=i!==null&&n.accelerator!==void 0;return d(Lt,{addon:e,fields:t,layers:{node:n.node,...n.camera===void 0?{}:{camera:n.camera},...h?{accelerator:n.accelerator}:{}},target:r,labels:{...i===null?{}:{accelerator:`This accelerator`},camera:`All accelerators`,node:`Node`},modelId:a,...o===void 0?{}:{rootModel:o},pinnedKeys:s,highlightKey:c,onChangeLayer:r===`camera`?l:u,...s.length>0?{headerActions:d(`button`,{type:`button`,className:oe,onClick:p,children:m(`device.cameraStepInspector.followNode`,{count:s.length})})}:{},fieldActions:(e,t)=>i!==null&&t===`accelerator`?d(`button`,{type:`button`,className:oe,onClick:()=>f(e),children:m(`device.cameraStepInspector.applyToAllAccelerators`,`Apply to all accelerators`)}):null})}function ll(e,t,n){return{id:e,get label(){return X.t(t)},icon:n}}var ul=[ll(`object-detection`,`helpers.detectionSettingsGroups.objectDetection`,`scan-search`),ll(`tracking`,`helpers.detectionSettingsGroups.tracking`,`route`),ll(`motion`,`helpers.detectionSettingsGroups.motion`,`activity`),ll(`stationary`,`helpers.detectionSettingsGroups.stationary`,`square-parking`),ll(`zones`,`helpers.detectionSettingsGroups.zones`,`shapes`),ll(`audio`,`helpers.detectionSettingsGroups.audio`,`volume-2`),ll(`cluster`,`helpers.detectionSettingsGroups.cluster`,`server`)],dl={"pipeline-object-detection":`object-detection`,"detection-sensitivity":`object-detection`,"onboard-object-detection":`object-detection`,tracking:`tracking`,"tracking-core":`tracking`,"motion-tuning":`motion`,"stationary-objects":`stationary`,occupancy:`stationary`,zones:`zones`,"pipeline-audio":`audio`,"cluster-assignment":`cluster`,"orchestrator-live":`cluster`};function fl(e){return dl[e]??`object-detection`}e();var pl=`steps`,ml=`settings`,hl=new Set([pl,ml]);function gl(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function _l({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=Z();return a(mt,{value:t&&hl.has(t)?t:pl,onValueChange:i(e=>{n?.(e)},[n]),className:`flex flex-col`,children:[a(rr,{className:`flex-shrink-0`,children:[d(ct,{value:pl,children:r(`device.detectionPipelineTab.steps`,`Steps`)}),d(ct,{value:ml,children:r(`device.detectionPipelineTab.settings`,`Settings`)})]}),d(Kt,{value:pl,children:d(sl,{deviceId:e})}),d(Kt,{value:ml,children:d(ri,{deviceId:e,sectionFilter:gl,subTabGrouping:{groupOf:e=>fl(e.id),tabs:ul}})})]})}var vl=`Notifications`,yl={i18nKey:`device.deviceNotificationMute.cameraCostWhenOff`,text:`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`},bl={i18nKey:`device.deviceNotificationMute.deviceCostWhenOff`,text:`This device never notifies — no rule, no target, no alarm.`};function xl(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:vl,on:r===null?null:i??r,available:r!==null,costWhenOff:e.isCamera?yl:bl}}function Sl(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}e();function Cl(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function wl({deviceId:e,isCamera:t}){let{t:n}=Z(),o=c(),s=Number.isFinite(e),[l,u]=r(null),[f,p]=r(null),m=xl({mutedDeviceIds:Cl(gn({},{enabled:s}).data),deviceId:e,isCamera:t,pendingOn:f}),h=n(m.costWhenOff.i18nKey,m.costWhenOff.text),g=fn({onError:t=>{console.error(`[DeviceNotificationMute] mute write failed — reverting`,{tags:{deviceId:e},meta:{error:t instanceof Error?t.message:String(t)}}),p(null),u(t instanceof Error?t.message:String(t)),o.invalidateQueries({queryKey:[[`notificationRules`,`listDeviceMutes`]]})},onSuccess:()=>{u(null),p(null),o.invalidateQueries({queryKey:[[`notificationRules`]]})}}),_=i(()=>{let t=Sl(m,e);t!==null&&(p(!t.muted),g.mutate(t))},[e,g,m]),v=m.on===null,y=m.on===!1,b=y?et:D;return a(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[a(`div`,{className:`border-b border-border px-4 py-2 flex items-center justify-between gap-2`,children:[d(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:n(`device.deviceNotificationMute.notifications`,`Notifications`)}),y&&d(`span`,{className:`rounded bg-warning/20 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-warning`,children:n(`common.muted`)})]}),a(`div`,{className:`px-4 py-3 flex items-start gap-3`,children:[a(`button`,{type:`button`,role:`switch`,"aria-label":m.label,"aria-checked":m.on===!0,disabled:!m.available||g.isPending,onClick:_,title:v?n(`device.deviceNotificationMute.notificationMuteStateUnknownThe`,`Notification mute — state unknown; the notification centre did not answer.`):y?n(`device.deviceNotificationMute.muted`,`Muted. {{costWhenOff}}`,{costWhenOff:h}):n(`device.deviceNotificationMute.notifyingMutingIt`,`Notifying. Muting it: {{costWhenOff}}`,{costWhenOff:h}),className:`inline-flex items-center gap-1.5 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors disabled:cursor-not-allowed ${l===null?v?`border-dashed border-border text-foreground-subtle/50`:y?`border-warning/40 text-warning hover:bg-warning/10`:`border-success/30 text-success hover:bg-success/10`:`border-danger/50 text-danger bg-danger/5`}`,children:[d(b,{className:`h-3.5 w-3.5`}),d(`span`,{children:v?n(`device.deviceNotificationMute.unknown`,`Unknown`):y?n(`device.deviceNotificationMute.muted2`,`Muted`):n(`device.deviceNotificationMute.notifying`,`Notifying`)})]}),d(`p`,{className:`flex-1 text-[11px] leading-relaxed text-foreground-subtle`,children:l===null?v?n(`device.deviceNotificationMute.theNotificationCentreDidNot`,`The notification centre did not answer, so this device’s mute state is unknown.`):h:n(`device.deviceNotificationMute.writeFailed`,`Write failed: {{failure}}`,{failure:l})})]})]})}function Tl(e,t){return{switchId:e,label:ve[e].label,detail:t===void 0||t.length===0?null:t}}function El(e){let t=new Map;for(let n of e.switches)n.deviceId===e.sourceId&&(t.has(n.switchId)||t.set(n.switchId,n));return t}function Dl(e){let t=El(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>Tl(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>Tl(e.switchId,e.detail));return{inheritedId:e.sourceId,retiredId:e.targetId,swapped:e.swapped,verdict:r.length===0?`quiet`:`still-live`,stillLive:r,neverOffered:i}}e();function Ol(e,t){return e.filter(e=>e.isCamera&&e.id!==t).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}function kl({deviceId:e,deviceName:t}){let{t:i}=Z(),o=lt(),[s,c]=r(null),l=En({isCamera:!0,projection:`slim`}),u=xr(),f=l.data!==void 0,p=n(()=>l.data===void 0?[]:Ol(l.data,e),[l.data,e]),m=p.find(e=>e.id===s)??null,h=u.data===void 0?null:Dl(u.data),g=u.error===null?null:u.error.message,_=async()=>{m===null||m.id===e||await o({title:i(`deviceMigrate.confirmTitle`,`Replace “{{source}}” with “{{target}}”?`,{source:t,target:m.name}),message:i(`deviceMigrate.confirmMessage`,`“{{target}}” takes over number {{sourceId}}. That number is what every recording, event, rule, zone and home-automation export of “{{source}}” is filed under, so all of it follows the number to the new hardware and keeps working. “{{source}}” is switched off and handed number {{targetId}} in exchange. This swaps two device identities and cannot be undone from here.`,{source:t,target:m.name,sourceId:e,targetId:m.id}),confirmLabel:i(`deviceMigrate.confirmAction`,`Migrate`),variant:`danger`})&&u.mutate({sourceId:e,targetId:m.id})};return a(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[d(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:i(`deviceMigrate.title`,`Migrate to…`)}),d(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:i(`deviceMigrate.subtitle`,`Replace this camera with other hardware you have already adopted. The new camera inherits number {{deviceId}}, so recordings, rules and integrations follow it.`,{deviceId:e})})]}),a(`div`,{className:`flex shrink-0 items-center gap-2`,children:[a(`select`,{"aria-label":i(`deviceMigrate.pickerLabel`,`Replacement camera`),className:`rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground disabled:opacity-50`,disabled:!f||p.length===0||u.isPending,value:s===null?``:String(s),onChange:e=>{let t=e.target.value;c(t===``?null:Number(t))},children:[d(`option`,{value:``,children:f?i(`deviceMigrate.pickerPlaceholder`,`Select a camera…`):i(`deviceMigrate.pickerPending`,`Reading the fleet…`)}),p.map(e=>a(`option`,{value:String(e.id),children:[e.name,` (#`,e.id,`)`]},e.id))]}),a(`button`,{type:`button`,disabled:m===null||u.isPending,onClick:()=>{_()},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[d(Xe,{className:`h-3 w-3`}),u.isPending?i(`deviceMigrate.running`,`Migrating…`):i(`deviceMigrate.action`,`Migrate`)]})]})]}),f&&p.length===0&&d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:i(`deviceMigrate.noTargets`,`No other camera is adopted, so there is nothing to migrate to.`)}),g!==null&&d(`p`,{className:`mt-2 text-[11px] text-danger`,children:i(`deviceMigrate.failed`,`Migration failed: {{error}}`,{error:g})}),h!==null&&d(Al,{report:h})]})}function Al({report:e}){let{t}=Z(),n=e.verdict===`quiet`;return a(`div`,{className:`mt-3 space-y-2 border-t border-border pt-3`,children:[d(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`deviceMigrate.swapped`,`The replacement now answers on number {{inheritedId}}; the old camera was handed number {{retiredId}}.`,{inheritedId:e.inheritedId,retiredId:e.retiredId})}),n?a(`div`,{className:`flex items-start gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2`,children:[d(U,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-success`}),d(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.quiet`,`Every function on the replaced camera was switched off — the old hardware is quiet.`)})]}):a(`div`,{className:`rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:[a(`div`,{className:`flex items-start gap-2`,children:[d(pe,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),d(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.stillLive`,`The replaced camera could not be reached, so these functions are STILL RUNNING on the old hardware. Nothing here failed to migrate — but until you unplug it or reach it physically, it can still produce data.`)})]}),d(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.stillLive.map(e=>a(`li`,{className:`text-[11px] text-foreground`,children:[d(`span`,{className:`font-medium`,children:e.label}),e.detail!==null&&a(`span`,{className:`text-foreground-subtle`,children:[` — `,e.detail]})]},e.switchId))})]}),e.neverOffered.length>0&&a(`div`,{className:`rounded-md border border-border px-3 py-2`,children:[a(`div`,{className:`flex items-start gap-2`,children:[d(rt,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`deviceMigrate.neverOffered`,`The replaced camera never offered these, so there was nothing to switch off. They are not running.`)})]}),d(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.neverOffered.map(e=>d(`li`,{className:`text-[11px] text-foreground-subtle`,children:e.label},e.switchId))})]})]})}e();function jl({deviceId:e}){let{t}=Z(),[n,i]=r(null),o=Jt({onSuccess:e=>{i(e.changed?`Re-aligned with source — ${e.rebuiltChildren} child${e.rebuiltChildren===1?``:`ren`} rebuilt.`:`Already up to date.`)},onError:e=>i(`Re-sync failed: ${e.message}`)});return a(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[d(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:t(`device.resyncButton.reSync`,`Re-sync`)}),d(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:t(`device.resyncButton.reAlignThisDeviceS`,`Re-align this device's type, role, capabilities and units with its source.`)})]}),a(`button`,{type:`button`,disabled:o.isPending,onClick:()=>{i(null),o.mutate({camDeviceId:e})},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[d(L,{className:`h-3 w-3 ${o.isPending?`animate-spin`:``}`}),o.isPending?t(`device.resyncButton.reSyncing`,`Re-syncing…`):t(`device.resyncButton.reSync`,`Re-sync`)]})]}),n!==null&&d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:n})]})}function Ml(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function Nl({device:e}){let{t}=Z(),n=ei(),r=typeof e.id==`number`?e.id:null,i=String(e.type??``),o=i===J.Camera,s=i===J.Hub,c=e.features??[],l=c.includes(He.Resyncable),{data:u}=Ht({deviceId:r??0},{enabled:r!==null&&o,refetchInterval:5e3}),f=u?.streams??{},p=Object.entries(f),m=c.includes(He.DoorbellButton),h=$n(m?{deviceId:r??void 0,historyLimit:10}:void 0),g=h.latest?Date.now()-h.latest.timestamp<3e4:!1;return a(`div`,{className:`space-y-5`,children:[s&&r!==null&&d(Rn,{deviceId:r,onOpenChild:e=>n(`/devices/${e}`)}),l&&r!==null&&d(jl,{deviceId:r}),o&&r!==null&&d(kl,{deviceId:r,deviceName:String(e.name??``)}),r!==null&&d(wl,{deviceId:r,isCamera:o}),o&&r!==null&&d(Dn,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:r}),m&&d(Fr,{history:h.history,latestIsFresh:g}),o&&r!==null&&d(Dn,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:r}),o&&p.length>0&&a(`div`,{className:`@container rounded-lg border border-border bg-surface overflow-hidden`,style:{containerType:`inline-size`},children:[d(`div`,{className:`border-b border-border px-4 py-2`,children:d(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:t(`device.overviewTab.streamNetwork`,`Stream Network`)})}),d(`div`,{className:`divide-y divide-border`,children:p.map(([e,n])=>a(`div`,{className:`px-4 py-2.5`,children:[a(`div`,{className:`flex items-center gap-2 mb-2`,children:[d(B,{className:`h-3 w-3 text-foreground-subtle`}),d(`span`,{className:`text-[11px] font-medium text-foreground`,children:e})]}),a(`div`,{className:`grid grid-cols-2 @[640px]:grid-cols-4 gap-2`,children:[d(Pl,{label:t(`device.overviewTab.nominal`,`Nominal`),value:Ml(n.nominalBitrateKbps??0)}),d(Pl,{label:t(`device.overviewTab.observed`,`Observed`),value:Ml(n.observedBitrateKbps??0)}),d(Pl,{label:t(`device.overviewTab.peak`,`Peak`),value:Ml(n.peakBitrateKbps??0)}),d(Pl,{label:t(`device.overviewTab.packetLoss`,`Packet Loss`),value:`${(n.packetLossPercent??0).toFixed(2)}%`,warning:(n.packetLossPercent??0)>1})]})]},e))})]}),d(Br,{}),r!==null&&d(Rr,{deviceId:r})]})}function Pl({label:e,value:t,warning:n}){return a(`div`,{children:[d(`p`,{className:`text-[10px] text-foreground-subtle`,children:e}),d(`p`,{className:`text-xs font-medium ${n?`text-warning`:`text-foreground`}`,children:t})]})}var Fl=`history`,Il=[{id:`overview`,labelKey:`helpers.structuralTabs.overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,labelKey:`helpers.structuralTabs.config`,cameraOnly:!1,adminOnly:!1},{id:ni,labelKey:`helpers.structuralTabs.customize`,cameraOnly:!1,adminOnly:!0},{id:Fl,labelKey:`helpers.structuralTabs.history`,cameraOnly:!1,adminOnly:!1},{id:`detection-pipeline`,labelKey:`helpers.structuralTabs.detectionPipeline`,cameraOnly:!0,adminOnly:!1},{id:`bindings`,labelKey:`helpers.structuralTabs.bindings`,cameraOnly:!0,adminOnly:!1}],Ll=new Set([J.Hub,J.Container]);function Rl(e,t){let n=e===J.Camera,r=e===void 0||!Ll.has(e);return Il.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)&&(r||e.id!==`history`)).map(({id:e,labelKey:t})=>({id:e,label:X.t(t)}))}function zl({provider:e,integrationId:t,name:n}){let r=ei(),i=t===null?`/integrations`:`/integrations/${t}`,a=n===null?`Open integrations`:`Open integration ${n}`;return d(`button`,{type:`button`,onClick:()=>r(i),className:`shrink-0 rounded-md transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/50`,title:a,"aria-label":a,children:d(Qr,{type:e,size:`lg`})})}e();var Bl=[{id:`logs`,icon:ce,labelKey:`common.logs`},{id:`repl`,icon:nt,labelKey:`deviceDetail.repl`},{id:`events`,icon:T,labelKey:`common.events`},{id:`state`,icon:S,labelKey:`common.state`}];function Vl(){let{t:e}=Z(),t=si(),o=Number(t.deviceId),u=Number.isFinite(o),f=ei(),p=c(),m=lt(),_=H(),{user:v}=Yr(),b=v?.isAdmin===!0,[x,S]=ii(),C=x.get(`tab`)??`overview`,w=x.get(`sub`),[T,E]=r(`logs`),D=`device-detail.left-col-width-px`,[O,k]=r(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(D),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),ee=l(O);ee.current=O;function A(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??O??0,r=Math.max(330,Math.floor(window.innerWidth*.7)),i=e=>{k(Math.max(280,Math.min(r,n+(e.clientX-t))))},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a);let e=ee.current;if(e!==null)try{window.localStorage.setItem(D,String(Math.round(e)))}catch{}document.body.style.userSelect=``,document.body.style.cursor=``};document.body.style.userSelect=`none`,document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)}let{data:j,isLoading:te,isError:N}=_r({deviceId:o},{enabled:u,refetchInterval:5e3,retry:1}),{data:P}=jt({deviceId:o},{enabled:u}),ne=n(()=>{let e=P?.settings?.sections??[],t=P?.live?.sections??[],n=[...e,...t],r=new Set;for(let e of n)e.location===`top-tab`&&e.tab&&r.add(e.tab===`zones`?`detection-pipeline`:e.tab);return n.some(Vr)&&r.add(Kr),[...r].map(e=>e===`export`?{id:e,label:zr,isAddonContrib:!0}:{id:e,label:De[e]?.label??e,isAddonContrib:!0})},[P]),F=j,I=String(F?.name??t.deviceId??`Device`),re=F?.online===!0,R=re?`online`:`offline`,ie=String(F?.addonId??`rtsp`),z=F?.features??[],B=F?.type,V=B===J.Camera,{data:ae}=Xr(u?o:0),oe=B===J.Container,se=n(()=>(ae??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[ae]),U=n(()=>oe?Tt(se,typeof F?.linkDeviceId==`number`?F.linkDeviceId:null,typeof F?.primaryChildEntityId==`string`?F.primaryChildEntityId:null)?.id??null:null,[oe,se,F?.linkDeviceId,F?.primaryChildEntityId]),{data:ce}=jt({deviceId:U??0},{enabled:U!==null}),le=n(()=>{if(U===null)return[];let e=ce?.settings?.sections??[],t=ce?.live?.sections??[],n=new Set;for(let r of[...e,...t])r.location===`top-tab`&&r.tab&&n.add(r.tab);return[...n].map(e=>({id:e,label:De[e]?.label??e,isAddonContrib:!0,childDeviceId:U}))},[U,ce]),ue=n(()=>qa({sections:[...P?.settings?.sections??[],...P?.live?.sections??[]],deviceId:o,...U===null?{}:{child:{sections:[...ce?.settings?.sections??[],...ce?.live?.sections??[]],deviceId:U}}}),[P,ce,o,U]),W=typeof F?.parentDeviceId==`number`?F.parentDeviceId:null,{data:pe}=_r({deviceId:W??0},{enabled:W!==null}),me=ft(),he=F?.disabled!==!0,ge=n(()=>{let e=P?.settings?.sections??[],t=P?.live?.sections??[];return Wr([...e,...t],B,b,P!==void 0)},[P,B,b]),_e=n(()=>{let e=new Set,t=[];for(let n of[...Rl(B,b),...ne,...le])n.id===`config`&&!ge||e.has(n.id)||(e.add(n.id),t.push(n));return t},[B,b,ne,le,ge]),ve=n(()=>zc(_e,C),[_e,C]),ye=i(e=>{S(t=>{let n=new URLSearchParams(t);e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`);for(let e of Xi)n.delete(e);return n},{replace:!0})},[S]),be=i(e=>{S(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[S]),xe=(ae??[]).length>0,Se=n(()=>Bl.filter(({featureGate:e})=>!e||z.includes(e)),[z]),{data:Ce}=xt(void 0),we=n(()=>F?ir(F,Ce):null,[F,Ce]),G=we?.kind===`resolved`?we.integration:null,Te=G===null?we?.kind===`unknown`?e(`deviceDetail.loadingIntegration`):we?.kind===`orphan`?e(`deviceDetail.missingIntegration`):e(`deviceDetail.noIntegration`):G.name,Ee=G!==null&&G.addonId===ie?G.name:ie,Oe=mr({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]}),f(G?.id?`/integrations/${G.id}`:`/integrations`)}}),ke=dn({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),K=$t({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ae=Er(),je=Gn({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Me=z.includes(He.Rebootable),q=z.includes(He.BatteryOperated),Ne=Ot(_.trpcClient,q&&u?o:null),Pe=yt(_.trpcClient,u?o:null),[Fe,Ie]=r(!1),Le=async()=>{if(!Fe){Ie(!0);try{let e=I.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await da(`${M}/${String(o)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Ie(!1)}}},Re=ke.isPending||K.isPending,{data:ze}=Ar({deviceId:o},{enabled:u&&V,refetchInterval:1e4}),Be=ze?.agentNodeId??null,Ve=typeof Be==`string`&&Be.length>0&&!Be.startsWith(`addon:`)?Be:void 0,{data:Ue}=Cn({deviceId:o,...Ve?{nodeId:Ve}:{}},{enabled:u&&V,refetchInterval:3e3,retry:!1}),{data:We}=Gt({deviceId:o},{enabled:u&&V,refetchInterval:3e3,retry:!1}),Ge=We?.level?.dbfs??null;function Ke(){if(!u)return null;switch(ve){case`overview`:return d(Nl,{device:F??{}});case`config`:return d(Wc,{deviceId:o,activeSubTab:w,onSubTabChange:be,deviceType:B,isAdmin:b});case`detection-pipeline`:return d(_l,{deviceId:o,activeSubTab:w,onSubTabChange:be});case`bindings`:return d(Bc,{deviceId:o});case Fl:return d(ar,{deviceId:o,onNavigate:e=>f(e)});case ni:return d(Mc,{deviceId:o,activeSubTab:w,onSubTabChange:be});default:{let e=ve,t=ne.some(t=>t.id===e),n=le.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??o;if(e===`export`)return d(ri,{deviceId:o,sectionFilter:Vr,activeSubTab:w,onSubTabChange:be});let i=d(ri,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:w,onSubTabChange:be});return n!==void 0&&r!==o?d(un,{deviceId:r,children:i}):i}}}return u?te?a(`div`,{className:`flex flex-col h-full`,children:[a(`div`,{className:`border-b border-border bg-surface px-6 py-4`,children:[d(`div`,{className:`h-4 w-48 rounded bg-surface-hover animate-pulse mb-3`}),d(`div`,{className:`h-8 w-64 rounded bg-surface-hover animate-pulse`})]}),d(`div`,{className:`flex-1 p-6`,children:d(`div`,{className:`h-40 rounded-lg border border-border bg-surface animate-pulse`})})]}):N||!j?a(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[d(`p`,{className:`text-lg font-semibold text-foreground`,children:e(`deviceDetail.deviceNotFound`,`Device not found`)}),d(`p`,{className:`text-xs`,children:d($r,{i18nKey:`deviceDetail.noDeviceWithId`,values:{id:o},components:{code:d(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`})}})}),d(`button`,{onClick:()=>f(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:e(`deviceDetail.backToIntegrations`,`Back to Integrations`)})]}):a(`div`,{className:`absolute inset-0 flex flex-col overflow-clip`,children:[a(`div`,{className:`border-b border-border bg-surface px-6 py-3 flex-shrink-0`,children:[d(`div`,{className:`mb-2`,children:d(Mr,{items:[{label:e(`deviceDetail.integrations`,`Integrations`),onClick:()=>f(`/integrations`)},G===null?{label:Te}:{label:Te,onClick:()=>f(`/integrations/${G.id}`)},{label:I}]})}),a(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[G!==null&&d(zl,{provider:G.addonId,integrationId:G.id,name:G.name}),a(`div`,{className:`min-w-0 flex-1`,children:[a(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[d(`h1`,{className:`text-sm sm:text-base font-semibold text-foreground truncate`,children:I}),d(dr,{status:R}),q&&d(cn,{status:Ne,variant:`full`}),d(kr,{status:Pe})]}),W!==null&&pe&&a(`button`,{type:`button`,onClick:()=>f(`/devices/${W}`),className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1`,title:e(`deviceDetail.openParentDevice`,`Open parent device {{name}}`,{name:pe.name}),children:[d(`span`,{children:`↑`}),d(`span`,{className:`truncate`,children:String(pe.name??`Device #${W}`)})]}),d(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:z.length>0&&d(Zr,{capabilities:z})})]}),Ue&&d(`div`,{className:`hidden lg:flex`,children:d(Hl,{metrics:Ue,dbfs:Ge})}),a(`div`,{className:`flex items-center gap-1 shrink-0`,children:[a(`button`,{onClick:async()=>{he?await m({title:e(`deviceDetail.disable`,`Disable "{{name}}"?`,{name:I}),message:e(`deviceDetail.theDeviceWillStopProcessing`,`The device will stop processing streams and events. You can re-enable it later.`),confirmLabel:e(`common.disable`,`Disable`),variant:`danger`})&&K.mutate({deviceId:o}):ke.mutate({deviceId:o})},disabled:Re,title:he?e(`deviceDetail.disableDevice`,`Disable device`):e(`deviceDetail.enableDevice`,`Enable device`),className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border transition-colors disabled:opacity-50 ${he?`border-success/30 text-success hover:bg-success/10`:`border-border text-foreground-subtle/50 hover:text-foreground hover:bg-surface-hover`}`,children:[d(g,{className:`h-3.5 w-3.5`}),d(`span`,{className:`hidden sm:inline`,children:Re?e(`deviceDetail.updating`,`Updating…`):he?e(`deviceDetail.enabled`,`Enabled`):e(`deviceDetail.disabled`,`Disabled`)})]}),d(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),V&&a(s,{children:[d(va,{deviceId:o}),d(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),d(ba,{deviceId:o}),d(Qn,{triggerClassName:`ml-1`,items:[{id:`snapshot`,label:e(`deviceDetail.takeSnapshot`,`Take snapshot`),description:e(`deviceDetail.fetchAFreshFrameAnd`,`Fetch a fresh frame and download it.`),icon:h,disabled:Fe,onClick:()=>{Le()}},{id:`reboot`,label:e(`deviceDetail.rebootDevice`,`Reboot device`),description:e(`deviceDetail.cameraGoesOfflineFor30`,`Camera goes offline for ~30 seconds.`),icon:fe,hidden:!Me,disabled:Ae.isPending,danger:!0,onClick:async()=>{await m({title:e(`deviceDetail.reboot`,`Reboot "{{name}}"?`,{name:I}),message:e(`deviceDetail.theCameraWillGoOffline`,`The camera will go offline for around 30 seconds while the firmware reboots.`),confirmLabel:e(`deviceDetail.reboot2`,`Reboot`),variant:`danger`})&&Ae.mutate({deviceId:o})}},{id:`restart-addon`,label:e(`deviceDetail.restartAddon`,`Restart addon`),description:e(`deviceDetail.bouncesEveryDeviceServedBy`,`Bounces every device served by {{servingAddonLabel}}.`,{servingAddonLabel:Ee}),icon:L,disabled:je.isPending,danger:!0,onClick:async()=>{await m({title:e(`deviceDetail.restart`,`Restart "{{servingAddonLabel}}"?`,{servingAddonLabel:Ee}),message:e(`deviceDetail.restartingTheAddonWillBriefly`,`Restarting the addon will briefly disconnect every device served by it (not just "{{name}}"). Streams will reconnect automatically.`,{name:I}),confirmLabel:e(`deviceDetail.restart2`,`Restart`),variant:`danger`})&&je.mutate({addonId:ie})}},{id:`delete`,label:e(`deviceDetail.deleteDevice`,`Delete device`),description:e(`deviceDetail.removeTheDeviceAndAll`,`Remove the device and all its settings.`),icon:y,separatorBefore:!0,disabled:Oe.isPending,danger:!0,onClick:async()=>{await m({title:e(`deviceDetail.delete`,`Delete "{{name}}"?`,{name:I}),message:e(`deviceDetail.thisWillRemoveTheDevice`,`This will remove the device and all its settings. This action cannot be undone.`),confirmLabel:e(`common.delete`,`Delete`),variant:`danger`})&&Oe.mutate({deviceId:o})}}]})]})]})]}),d(un,{deviceId:o,device:F??void 0,children:d(Bn,{children:d(Fn,{children:d(de,{children:d(zn,{children:a(`main`,{className:me?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[a(`div`,{className:me?`flex flex-col bg-surface`:`${O===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-y-auto`,style:!me&&O!==null?{width:`${String(O)}px`}:void 0,children:[d(`div`,{className:V?`flex-shrink-0 border-b border-border-subtle bg-black`:me?`flex-shrink-0 border-b border-border-subtle bg-surface`:`shrink-0 border-b border-border-subtle bg-surface`,children:V?d(ro,{deviceId:o,intercomAvailable:z.includes(He.TwoWayAudio)}):a(`div`,{children:[d(Wa,{deviceId:o,deviceName:I,deviceType:B??`unknown`,provider:ie,isOnline:re,features:z}),d(Ga,{deviceId:o,widgets:ue})]})}),V&&ue.length>0&&d(`div`,{className:`flex-shrink-0 border-b border-border-subtle bg-surface pt-3 sm:pt-4`,children:d(Ga,{deviceId:o,widgets:ue})}),a(`div`,{className:me?`flex flex-col border-b border-border`:`flex-1 min-h-64 flex flex-col overflow-hidden`,children:[d(`div`,{className:`flex-shrink-0 border-b border-border-subtle px-2 py-1.5`,children:d(`div`,{className:`flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5`,children:Se.map(({id:t,labelKey:n,icon:r})=>{let i=T===t;return a(`button`,{onClick:()=>E(t),title:e(n),className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${i?`bg-primary/15 text-primary`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[d(r,{className:`h-3 w-3`}),e(n)]},t)})})}),a(`div`,{className:me?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[T===`logs`&&d(io,{deviceId:o,containerDeviceId:B===`container`?o:void 0}),T===`repl`&&d(ao,{deviceId:o}),T===`events`&&d(oo,{deviceId:o}),T===`state`&&d(so,{deviceId:o})]})]})]}),!me&&d(`div`,{role:`separator`,"aria-orientation":`vertical`,title:e(`deviceDetail.dragToResize`,`Drag to resize`),onMouseDown:A,className:`flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10`,children:d(`span`,{className:`absolute inset-y-0 -left-1 -right-1`})}),a(`div`,{className:me?`flex flex-col`:`flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden`,children:[d(`div`,{className:`flex-shrink-0 border-b border-border bg-surface px-4`,children:d(`div`,{className:`flex flex-nowrap overflow-x-auto md:flex-wrap md:overflow-x-visible items-center gap-0`,children:_e.map(e=>{let t=ve===e.id;return a(`button`,{onClick:()=>ye(e.id),className:`relative flex-shrink-0 px-3 py-2 text-xs font-medium transition-colors ${t?`text-primary`:`text-foreground-subtle hover:text-foreground`}`,children:[e.label,t&&d(`span`,{className:`absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary`})]},e.id)})})}),a(`div`,{className:me?`p-3 flex flex-col gap-3`:`flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3`,children:[ve===`overview`&&xe&&d(xa,{parentDeviceId:o}),Ke()]})]})]})})})})})})]}):a(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[d(`p`,{className:`text-lg font-semibold text-foreground`,children:e(`deviceDetail.invalidDeviceId`,`Invalid device id`)}),d(`p`,{className:`text-xs`,children:d($r,{i18nKey:`deviceDetail.invalidSegment`,values:{segment:t.deviceId},components:{code:d(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`})}})}),d(`button`,{onClick:()=>f(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:e(`deviceDetail.backToIntegrations`,`Back to Integrations`)})]})}function Hl({metrics:e,dbfs:t}){let n=ue(),{t:r}=Z(),i=Pn(e.phase??`idle`,n);return a(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[a(`div`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`h-1.5 w-1.5 rounded-full ${i.dotClass}`}),d(`span`,{className:`text-[10px] font-medium ${i.textColor}`,children:i.label})]}),d(`div`,{className:`h-3 w-px bg-border`}),a(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[d(W,{className:`h-3 w-3`}),d(`span`,{className:`text-foreground tabular-nums`,children:(e.actualFps??0).toFixed(1)}),d(`span`,{children:r(`common.fpsWord`)})]}),a(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[d(P,{className:`h-3 w-3`}),d(`span`,{className:`text-foreground tabular-nums`,children:(e.avgInferenceTimeMs??0).toFixed(0)}),d(`span`,{children:`ms`})]}),a(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,title:r(`deviceDetail.currentAudioLevelDbfs`,`Current audio level (dBFS)`),children:[d(ee,{className:`h-3 w-3`}),d(`span`,{className:`text-foreground tabular-nums`,children:t==null?`—`:t.toFixed(0)}),d(`span`,{children:`dB`})]}),(e.queueDepth??0)>0&&a(`span`,{className:`text-[10px] text-warning tabular-nums`,children:[`q:`,e.queueDepth]})]})}export{Vl as DeviceDetailPage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$ as e,B as t,G as n,J as r,L as i,S as a,a as o,b as s,o as c,q as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{$t as f,D as p,Fn as m,Gi as h,It as g,Nt as _,Rr as v,Tt as y,Wr as b,an as x,bn as S,cn as C,dn as w,dt as T,kn as E,lr as D,mi as O,mr as k,or as A,ot as ee,pn as j,rr as M,sa as N,sn as te,xi as P,yi as F}from"./player-overlays-DTcu3p6k.js";import{Gi as I,Ki as ne,c as L,l as R,o as z,qi as re,r as ie,s as ae}from"./client-Tf7DwHzR.js";import{i as oe,n as se,r as ce,t as le}from"./key-y1dQIrgn.js";import{d as B,l as V,s as ue}from"./video-DSWn6X4v.js";import{t as de}from"./key-round-PVl1EIeU.js";import{t as fe}from"./monitor-smartphone-DgPyh0bq.js";import{t as pe}from"./unlink-DgTv7GBL.js";import{$n as me,$u as H,An as he,Ar as U,Au as ge,Ct as _e,Cu as ve,Dn as ye,Mu as be,Nn as xe,Nu as Se,Ou as Ce,Qn as we,Rr as W,Ss as Te,Su as Ee,Xn as De,Za as Oe,_n as ke,_u as Ae,bu as je,cn as Me,dt as Ne,er as Pe,fr as G,fu as Fe,gn as Ie,gr as Le,gu as Re,hn as K,hr as q,hs as ze,hu as Be,ir as Ve,it as He,jn as Ue,jr as We,ju as Ge,kn as Ke,ku as qe,ln as Je,lt as Ye,mn as Xe,mu as Ze,nr as Qe,oi as $e,pr as et,ps as tt,pu as nt,qn as rt,rr as it,rt as at,si as ot,vs as st,vt as ct,vu as lt,wt as ut,xs as dt,xu as ft,yu as pt}from"./src-CxF5mieK.js";import{t as J}from"./i18n-dPXh_JKN.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import{$ as mt,Q as ht,T as gt,V as _t,Z as vt,a as yt,d as bt,et as xt,i as St,l as Ct,nt as wt}from"./index-k7RW-84l.js";import{t as Tt}from"./AdminSectionedPage-CxodN1sn.js";import{t as Et}from"./AdminPage-0E8EpSO9.js";import{A as Dt,C as Ot,D as kt,E as At,O as X,S as jt,T as Mt,a as Nt,b as Pt,c as Ft,d as It,f as Lt,g as Rt,h as zt,i as Bt,k as Vt,l as Ht,m as Ut,n as Wt,o as Gt,p as Kt,s as qt,t as Jt,u as Yt,v as Xt,w as Zt,x as Qt,y as $t}from"./SessionsList-CO2JCtUA.js";import{i as en,n as tn,r as nn,t as rn}from"./IntegrationHub-DAndpOVJ.js";import{n as an,t as on}from"./addon-display-names-BkwMrExv.js";e();function sn(){let{t:e}=Y(),t=U(),i=H.useUtils(),a=Dt(),{data:o,isLoading:s}=lt(),c=n(()=>o??[],[o]),l=H.useQueries(e=>c.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),u=H.auth.listLoginMethods.useQuery(),[f,p]=r(null),m=Ee({onSuccess:()=>void i.userManagement.listExternalIdentities.invalidate(),onError:e=>p(`Remove failed: ${e.message}`)}),h=n(()=>new Map((u.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[u.data]),g=c.flatMap((e,t)=>l[t]?.data??[]),_=g.map(e=>({...jt(e,a),kind:h.get(e.provider)??e.provider})),v=async n=>{let r=g.find(e=>Qt(e)===n.id);r!==void 0&&await t({title:e(`access.externalIdentitiesSection.removeSignInLink`,`Remove sign-in link`),message:e(`access.externalIdentitiesSection.willNoLongerBeAble`,`"{{ownerName}}" will no longer be able to sign in with this {{kind}} account.`,{ownerName:n.ownerName,kind:n.kind}),confirmLabel:e(`common.remove`,`Remove`),variant:`danger`})&&(p(null),m.mutate({userId:r.userId,provider:r.provider,subject:r.subject}))};return d(X,{notice:Vt(f),onDismissNotice:()=>{p(null)},id:`external-identities`,title:e(`access.externalIdentitiesSection.signInLinks`,`Sign-in links`),icon:B,description:e(`access.externalIdentitiesSection.externalAccountsSingleSignOn`,`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`),children:d(Mt,{rows:_,label:`sign-in links`,isLoading:s||l.some(e=>e.isLoading),loadError:l.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:e(`common.remove`,`Remove`),icon:pe,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:m.isPending}})})}e();var cn={key:`access.nouns.linkedApp`};function ln(e){if(e.type===`category`){let t=e.target??``;return t===`device`?J.t(`access.linkedAppsSection.allDevices`):J.t(`access.linkedAppsSection.allTarget`,{target:t})}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function un(){let{t:e}=Y(),t=U(),i=c(),a=Ae(),[o,s]=r(null),l=()=>void i.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),u=je({onSuccess:l,onError:e=>s(`Revoke failed: ${e.message}`)}),f=At(cn,l),p=n(()=>(a.data??[]).map(e=>Ot(e,e.scopes.map(ln).join(`, `))),[a.data]),m=async n=>{await t({title:e(`access.linkedAppsSection.revokeTheLink`,`Revoke the "{{name}}" link?`,{name:n.name}),message:e(`access.linkedAppsSection.losesAccessForOnIts`,`{{name}} loses access for {{ownerName}} on its next call. Linking it again needs the account-link flow from the start.`,{name:n.name,ownerName:n.ownerName}),confirmLabel:e(`access.linkedAppsSection.revoke`,`Revoke`),variant:`danger`})&&(s(null),u.mutate({id:n.id}))},h=u.isPending?u.variables?.id??null:null;return d(X,{notice:Vt(o,f.outcome),onDismissNotice:()=>{s(null),f.dismiss()},id:`linked-apps`,title:e(`access.linkedAppsSection.linkedApps`,`Linked apps`),icon:D,description:e(`access.linkedAppsSection.externalIntegrationsAlexaLinkedTo`,`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call. Already-revoked rows can be selected and removed from the list.`),children:d(Mt,{rows:p,label:e(`access.linkedAppsSection.linkedApps2`,`linked apps`),isLoading:a.isLoading,loadError:a.isError?a.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:e(`access.linkedAppsSection.revoke`,`Revoke`),icon:g,isAvailable:e=>e.status===`active`||e.status===`revoked`,onRun:e=>void m(e),busyId:h,disabled:u.isPending||f.busy},bulk:{revoke:f,noun:cn,isSelectable:e=>e.status===`active`||e.status===`revoked`,quickSelect:[{label:e(`access.linkedAppsSection.selectRevoked`,`Select revoked`),match:e=>e.status===`revoked`}]}})})}e();var dn={key:`access.nouns.session`};function fn(){let{t:e}=Y(),t=U(),i=H.useUtils(),a=Dt(),o=H.auth.listSessions.useQuery(),[s,c]=r(null),l=()=>void i.auth.listSessions.invalidate(),u=H.auth.revokeSessions.useMutation({onSuccess:l,onError:e=>c(`Sign out failed: ${e.message}`)}),f=At(dn,l),p=n(()=>(o.data??[]).map(e=>Zt(e,a,{client:e=>Xt(e).label,method:$t})),[o.data,a]),m=async n=>{await t({title:e(`access.loginSessionsSection.signOutThisSession`,`Sign out this session`),message:e(`access.loginSessionsSection.onWillHaveToSign`,`{{ownerName}} on {{name}} will have to sign in again.`,{ownerName:n.ownerName,name:n.name}),confirmLabel:e(`access.loginSessionsSection.signOut`,`Sign out`),variant:`danger`})&&(c(null),u.mutate({id:n.id}))};return d(X,{notice:Vt(s,f.outcome),onDismissNotice:()=>{c(null),f.dismiss()},id:`login-sessions`,title:e(`access.loginSessionsSection.loginSessions`,`Login sessions`),icon:fe,description:e(`access.loginSessionsSection.everyBrowserAndAppSigned`,`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`),children:d(Mt,{rows:p,label:e(`common.sessionsLabel`),isLoading:o.isLoading,loadError:o.isError?o.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:e(`access.loginSessionsSection.signOut`,`Sign out`),icon:ue,isAvailable:e=>e.status===`active`,onRun:e=>void m(e),busyId:u.isPending&&u.variables!==void 0&&`id`in u.variables?u.variables.id:null,disabled:u.isPending||f.busy},bulk:{revoke:f,noun:dn,isSelectable:e=>e.status===`active`}})})}var pn={"by-id":`helpers.authAuditWording.bulkNoun.credential`,"share-link":`helpers.authAuditWording.bulkNoun.shareLink`,"admin-token":`helpers.authAuditWording.bulkNoun.adminToken`,"login-session":`helpers.authAuditWording.bulkNoun.loginSession`};function Z(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function mn(e,t){let n=Z(e,`tokenId`);return Z(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function Q(e){return e.filter(e=>e!==null)}function hn(e){let t=Z(e,`prefix`);return t===null?null:J.t(`helpers.authAuditWording.prefix`,{prefix:t})}function gn(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:J.t(`helpers.authAuditWording.tokenCreated`,{name:mn(n,t)}),details:Q([hn(n),typeof e==`number`?J.t(`helpers.authAuditWording.expires`,{at:Pt(e)}):null])}}case`admin-token-used`:{let e=Z(n,`path`);return{title:J.t(`helpers.authAuditWording.tokenUsed`,{name:mn(n,t)}),details:Q([hn(n),e===null?null:J.t(`helpers.authAuditWording.call`,{path:e})])}}case`token-minted`:{let e=n.expiresAt;return{title:J.t(`helpers.authAuditWording.tokenMinted`,{name:mn(n,t)}),details:Q([typeof e==`number`?J.t(`helpers.authAuditWording.expires`,{at:Pt(e)}):null])}}case`token-revoked`:return{title:J.t(`helpers.authAuditWording.anyTokenRevoked`,{name:mn(n,t)}),details:[]};case`admin-token-revoked`:return{title:J.t(`helpers.authAuditWording.tokenRevoked`,{name:mn(n,t)}),details:Q([hn(n)])};case`credentials-revoked`:{let e=Z(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=pn[e],a=i===void 0?`${e}s`:J.t(i);return{title:J.t(`helpers.authAuditWording.bulkRevoked`,{n:typeof t==`number`?String(t):`?`,noun:a}),details:Q([typeof r==`number`&&r>0?J.t(`helpers.authAuditWording.skipped`,{count:r}):null,Z(n,`ids`)===null?null:J.t(`helpers.authAuditWording.ids`,{ids:Z(n,`ids`)??``})])}}case`second-factor-skipped`:{let e=Z(n,`method`),t=Z(n,`factors`);return{title:J.t(`helpers.authAuditWording.secondFactorSkipped`),details:Q([e===null?null:J.t(`helpers.authAuditWording.signedInWith`,{method:$t(e)}),t===null?null:J.t(`helpers.authAuditWording.skippedFactors`,{factors:t.split(`,`).join(`, `)})])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}e();var _n=100;function vn(){let{user:e}=_t();return e?.isAdmin?d(bn,{}):null}function yn(){let{data:e}=lt(),{data:t}=H.auth.listTokens.useQuery(void 0);return n(()=>{let n=new Map;for(let t of e??[])n.set(t.id,t.username);let r=new Map;for(let e of t??[])r.set(e.id,e.label);return{userNameById:n,tokenNameById:r}},[e,t])}function bn(){let{t:e}=Y(),t=H.auth.listAuthAudit.useQuery({limit:_n}),{userNameById:n,tokenNameById:r}=yn(),i=t.data??[];return a(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[a(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[d(j,{className:`h-3.5 w-3.5 text-foreground-subtle`}),d(`div`,{className:`text-xs font-semibold text-foreground`,children:e(`auth.authAuditSection.authenticationAudit`,`Authentication audit`)}),d(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:e(`auth.authAuditSection.latest`,{count:_n})})]}),d(`div`,{className:`p-4`,children:t.isLoading?a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),e(`auth.authAuditSection.loadingAuditTrail`,`Loading audit trail…`)]}):t.isError?a(`div`,{className:`text-[11px] text-danger`,children:[e(`auth.authAuditSection.couldNotLoadTheAudit`,`Could not load the audit trail:`),` `,t.error?.message??e(`auth.authAuditSection.requestFailed`,`Request failed`)]}):i.length===0?a(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center space-y-1`,children:[d(`div`,{children:e(`auth.authAuditSection.noAuthenticationEventsRecordedYet`,`No authentication events recorded yet.`)}),d(`div`,{className:`text-[11px] text-foreground-subtle/90`,children:e(`auth.authAuditSection.thisTrailRecordsAdminToken`,`This trail records admin-token create/use/revoke, trusted-network 2FA skips, and credential revokes (including single share-link revoke). Browser password logins are not listed here.`)})]}):d(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:i.map(e=>d(xn,{record:e,userName:e.userId===void 0?null:n.get(e.userId)??e.userId,tokenNameById:r},e.id))})})]})}function xn({record:e,userName:t,tokenNameById:n}){let r=gn(e,n);return a(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[a(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[d(`span`,{className:`font-medium text-foreground`,children:r.title}),d(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Pt(e.at)})]}),a(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[t!==null&&d(`span`,{className:`text-foreground`,children:t}),e.ip!==void 0&&d(`span`,{className:`font-mono`,children:e.ip}),r.details.map(e=>d(`span`,{className:`font-mono`,children:e},e))]})]})}e();var $={loginSessions:`login-sessions`,linkedApps:`linked-apps`,tokens:`tokens`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,externalIdentities:`external-identities`,audit:`auth-audit`},Sn={[$.scopedTokens]:$.tokens,[$.adminTokens]:$.tokens,[$.shareLinks]:$.tokens};function Cn(){return[{id:$.loginSessions,label:J.t(`system.access.loginSessions`,`Login sessions`),icon:fe,render:()=>d(fn,{})},{id:$.linkedApps,label:J.t(`system.access.linkedApps`,`Linked apps`),icon:D,render:()=>d(un,{})},{id:$.tokens,label:J.t(`system.access.tokens`,`Tokens`),icon:de,render:({createRequested:e,onCreateConsumed:t})=>d(zt,{headerOwnsCreate:!0,createRequested:e,onCreateConsumed:t})},{id:$.externalIdentities,label:J.t(`system.access.signInLinks`,`Sign-in links`),icon:B,render:()=>d(sn,{})},{id:$.audit,label:J.t(`system.access.audit`,`Audit`),icon:j,render:()=>d(vn,{})}]}function wn({createRequested:e=!1,onCreateConsumed:t}){let{t:r}=Y(),i=n(()=>Cn(),[]),o=en({ids:n(()=>i.map(e=>e.id),[i]),answered:!0}),s=xt(),[c]=wt(),l=c.get(`integration`),u=l===null?void 0:Sn[l];if(u!==void 0){let e=new URLSearchParams(c);return e.set(`integration`,u),d(mt,{to:`?${e.toString()}`,replace:!0})}let f=i.find(e=>e.id===o.selectedId)??i[0];return a(`div`,{className:`flex flex-col gap-3`,"data-testid":`access-page`,children:[d(ye,{appearance:`pills`,value:f?.id??$.loginSessions,onValueChange:e=>{s(`?${bt(c,e,null,null).toString()}`)},children:d(Ke,{"aria-label":r(`system.access.credentialKinds`,`Credential kinds`),children:i.map(e=>a(he,{value:e.id,"data-testid":`access-kind-${e.id}`,children:[d(e.icon,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":!0}),e.label]},e.id))})}),f===void 0?null:d(`div`,{role:`region`,"aria-label":f.label,"data-testid":`access-kind-body`,children:f.render({createRequested:e&&f.id===$.tokens,onCreateConsumed:t??(()=>void 0)})},f.id)]})}function Tn(e,t){if(e===$.tokens)return a(q,{size:`sm`,type:`button`,"data-testid":`access-new-token`,onClick:t,children:[d(de,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`system.access.newToken`,`New token`)]})}function En(){let[e,t]=r(!1);return{createRequested:e,requestCreate:()=>t(!0),clearCreate:()=>t(!1)}}e();var Dn=[`oidcConnections`,`listConnections`],On=[`oidcConnections`,`connectionFormSchema`],kn={displayName:`OpenID Connect`,icon:`shield-check`,issuerUrl:``,clientId:``,clientSecret:``,redirectUri:``,scopes:`openid profile email`,usernameClaim:`preferred_username`},An=/^[a-z0-9][a-z0-9-]{0,63}$/;function jn(e){return e instanceof Error?e.message:String(e)}function Mn(e,t){if(t)return typeof e==`string`&&e.length>0?e:void 0;if(ne(e))return I;if(typeof e==`string`&&e.length>0)return e;re(e)}function Nn(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Pn({addonId:e}){let{t:f}=Y(),p=ee(),m=c(),h=U(),_=Ye({editKey:`oidcEdit`,newKey:`oidcNew`}),[v,y]=r(!1),[b,x]=r(null),[S,C]=r(``),[w,T]=r({...kn}),D=l(null),O=o({queryKey:[...Dn,e],queryFn:async()=>p.trpcClient.oidcConnections.listConnections.query({})}),k=o({queryKey:On,queryFn:async()=>p.trpcClient.oidcConnections.connectionFormSchema.query({})}),A=O.data??[],j=Nn(k.data)?k.data:void 0,M=_.state,N=M.mode===`edit`?A.find(e=>e.id===M.id)??null:null;t(()=>{if(_.state.mode===`edit`&&N!==null){let e=`edit:${N.id}`;if(D.current===e)return;D.current=e,x(null),C(N.id),T(N.formValues===void 0?{...kn}:{...N.formValues});return}if(_.state.mode===`new`){if(D.current===`new`)return;D.current=`new`,x(null),C(``),T({...kn})}},[N,_.state]);let P=i(async()=>{await m.invalidateQueries({queryKey:Dn})},[m]),F=u({mutationFn:async e=>p.trpcClient.oidcConnections.deleteConnection.mutate({id:e}),onSuccess:async()=>P()}),I=i(async e=>{await h({title:f(`system.oidcSettingsConnections.deleteOidcConnection`,`Delete OIDC connection?`),message:f(`system.oidcSettingsConnections.removeTheLoginButtonAnd`,`Remove “{{displayName}}” ({{id}}). The login button and IdP credentials for this id are dropped.`,{displayName:e.displayName,id:e.id}),confirmLabel:f(`common.delete`,`Delete`),cancelLabel:f(`common.cancel`,`Cancel`),variant:`danger`})&&(await F.mutateAsync(e.id),_.state.mode===`edit`&&_.state.id===e.id&&(_.close(),D.current=null))},[h,F,_,f]),ne=i(async()=>{let e=w.displayName,t=typeof e==`string`&&e.trim()!==``?e.trim():``;if(t===``){x(`Display name is required.`);return}let n=_.state.mode===`new`,r=n?S.trim():N?.id??``;if(n&&!An.test(r)){x(`Instance id must be a lowercase slug (e.g. authentik, google).`);return}if(r===``){x(`That connection is no longer available.`);return}let i=Mn(w.clientSecret,n),a=w.icon,o=w.issuerUrl,s=w.clientId,c=w.redirectUri,l=w.scopes,u=w.usernameClaim,d=u===`email`||u===`sub`?u:`preferred_username`;y(!0),x(null);try{n&&await p.trpcClient.oidcConnections.createConnection.mutate({id:r,displayName:t}),await p.trpcClient.oidcConnections.updateConnection.mutate({id:r,displayName:t,icon:typeof a==`string`?a:`shield-check`,issuerUrl:typeof o==`string`?o:``,clientId:typeof s==`string`?s:``,...i===void 0?{}:{clientSecret:i},redirectUri:typeof c==`string`?c:``,scopes:typeof l==`string`?l:`openid profile email`,usernameClaim:d}),await P(),_.close(),D.current=null}catch(e){x(jn(e))}finally{y(!1)}},[S,N?.id,_,w,P,p]),L=n(()=>[{key:`id`,header:f(`system.oidcSettingsConnections.id`,`Id`),sortValue:e=>e.id,render:e=>d(`span`,{className:`font-mono text-xs text-foreground`,children:e.id})},{key:`name`,header:f(`system.oidcSettingsConnections.name`,`Name`),sortValue:e=>e.displayName,render:e=>d(`span`,{className:`truncate font-medium text-foreground`,children:e.displayName})},{key:`issuer`,header:f(`system.oidcSettingsConnections.issuer`,`Issuer`),sortValue:e=>e.issuerUrl,render:e=>d(`span`,{className:`truncate text-xs text-foreground-muted`,children:e.issuerUrl===``?`—`:e.issuerUrl})},{key:`status`,header:f(`system.oidcSettingsConnections.status`,`Status`),notSortableReason:`Badge`,render:e=>d(W,{variant:e.configured?`success`:`warning`,children:e.configured?f(`system.oidcSettingsConnections.configured`,`Configured`):f(`system.oidcSettingsConnections.notConfigured`,`Not configured`)})},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>a(`div`,{className:`flex justify-end gap-1`,children:[d(q,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),_.openEdit(e.id)},children:f(`common.edit`,`Edit`)}),d(q,{type:`button`,size:`sm`,variant:`ghost`,"aria-label":f(`system.oidcSettingsConnections.delete`,`Delete {{displayName}}`,{displayName:e.displayName}),title:f(`common.delete`,`Delete`),onClick:t=>{t.stopPropagation(),I(e)},children:d(g,{className:`h-3.5 w-3.5 text-danger`})})]})}],[_,I,f]),R=_.state.mode===`new`,z=R||N!==null,re=R?`new`:N===null?`closed`:`edit:${N.id}:${N.configured?`cfg`:`empty`}`;return a(`div`,{className:`flex min-h-0 flex-col gap-3`,"data-testid":`oidc-settings-connections`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.eachRowIsOneIdp`,`Each row is one IdP. Redirect URI:`),` `,d(`span`,{className:`font-mono text-xs`,children:`/addon/${e}/<id>/callback`})]}),a(q,{type:`button`,size:`sm`,"data-testid":`oidc-connections-add`,onClick:()=>_.openNew(),children:[d(E,{className:`h-3.5 w-3.5`}),f(`system.oidcSettingsConnections.addConnection`,`Add connection`)]})]}),O.isError?d(`p`,{className:`text-sm text-danger`,children:f(`system.oidcSettingsConnections.couldNotLoadConnections`,`Could not load connections.`)}):null,O.isPending?d(Le,{className:`h-32 w-full`}):d(Ie,{columns:L,rows:A,rowKey:e=>e.id,pageSize:25,emptyMessage:f(`system.oidcSettingsConnections.noOidcConnectionsYetAdd`,`No OIDC connections yet. Add one to register an IdP.`),onRowClick:e=>_.openEdit(e.id),defaultSort:{columnKey:`name`,dir:`asc`}}),d(Ne,{open:z,onClose:()=>{_.close(),x(null),D.current=null},title:R?f(`system.oidcSettingsConnections.addOidcConnection`,`Add OIDC connection`):f(`system.oidcSettingsConnections.edit`,`Edit {{value1}}`,{value1:N?.displayName??`connection`}),icon:te,width:`xl`,testId:`oidc-connection-editor`,error:b,footer:d(q,{type:`button`,size:`sm`,disabled:v||R&&S.trim()===``,onClick:()=>void ne(),children:v?f(`system.oidcSettingsConnections.saving`,`Saving…`):f(`common.save`,`Save`)}),children:z?a(s,{children:[R?a(`div`,{children:[d(xe,{htmlFor:`oidc-connection-id`,children:f(`system.oidcSettingsConnections.instanceId`,`Instance id`)}),d(Se,{id:`oidc-connection-id`,value:S,onChange:e=>C(e.target.value),placeholder:`authentik`,autoComplete:`off`}),d(`p`,{className:`mt-1 text-xs text-foreground-muted`,children:f(`system.oidcSettingsConnections.urlSlugAppearsInAddon`,`URL slug — appears in /addon/{{addonId}}/<id>/callback. Stable; renaming is not supported after save.`,{addonId:e})})]}):a(`p`,{className:`text-sm text-foreground-muted`,children:[f(`system.oidcSettingsConnections.instanceId2`,`Instance id:`),` `,d(`span`,{className:`font-mono`,children:N?.id})]}),j===void 0?d(`p`,{className:`text-sm text-foreground-muted`,children:f(`system.oidcSettingsConnections.loadingForm`,`Loading form…`)}):d(rt,{schema:j,values:w,onChange:T,bare:!0},re)]}):null})]})}e();var Fn=3e4,In=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],Ln={titleKey:`system.authentication.sectionTitle`,subtitleKey:`system.authentication.sectionSubtitle`,emptyTitleKey:`system.authentication.sectionEmptyTitle`,emptyDescriptionKey:`system.authentication.sectionEmptyDescription`,installLabelKey:`system.authentication.sectionInstall`};function Rn(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:se,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`Scoped tokens, admin tokens and sessions are managed from Identity → Tokens & sessions.`],setupSteps:[`A fresh hub has one account, admin / changeme — the first sign-in asks for a new password. Add users from Users → New user.`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:V,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`Explicit linking only: an IdP account signs in only the CamStack user who linked it from their profile (My access → Linked sign-in accounts). No auto-created users, no email matching.`,`The linked user’s role, scopes and two-factor authentication apply.`],setupSteps:[`Register a web app at your IdP and copy the client_id + client_secret.`,"Choose a stable instance id (slug). Set the IdP redirect URI to `https://<this-hub>/addon/auth-oidc/<id>/callback`.",`In Settings below, Add connection — enter the id, issuer, and credentials; Save.`,`Each user then links their IdP account from My access → Linked sign-in accounts.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:V,bullets:[`Heavier handshake than OIDC — exchange metadata XML with your IdP.`,`Group → role mapping via SAML assertions.`]}:e.startsWith(`auth-webauthn`)||e.startsWith(`auth-passkey`)?{headline:`Passkeys / WebAuthn — passwordless second factor.`,icon:f,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)?{headline:`TOTP — second factor.`,icon:f,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:te,bullets:[`Generic authentication provider. No additional hints registered.`]}}function zn(){let{t:e}=Y(),t=ot({capName:In[0].capName},{refetchInterval:Fn}),r=ot({capName:In[1].capName},{refetchInterval:Fn}),i=$e(void 0,{refetchInterval:Fn}),a=n(()=>on(i.data??[]),[i.data]),o=n(()=>{let e=[],n=[t.data??[],r.data??[]];for(let[t,r]of In.entries())for(let i of n[t]??[])e.push({addonId:i.addonId,displayName:a.get(i.addonId)??i.addonId,isActive:i.isActive,capName:r.capName,stageBadge:r.stageBadge});return e},[t.data,r.data,a]),s=[{id:`authentication`,label:e(`system.authentication.authenticationProviders`,`Authentication providers`),install:{capability:In[0].capName,label:e(Ln.installLabelKey)},entries:o.map(t=>({id:t.addonId,name:t.displayName,fallbackIcon:te,...an(t.isActive),render:()=>d(tn,{addonId:t.addonId,displayName:t.displayName,capName:t.capName,isActive:t.isActive,badges:t.stageBadge===null?null:d(W,{variant:`info`,className:nn,children:t.stageBadge}),settingsContent:t.addonId.startsWith(`auth-oidc`)?d(Pn,{addonId:t.addonId}):void 0,panels:[{id:`about`,title:e(`system.authentication.about`,`About`),icon:Rn(t.addonId).icon,content:d(Bn,{addonId:t.addonId})}]})}))}];return d(rn,{embedded:!0,icon:te,title:e(Ln.titleKey),subtitle:e(Ln.subtitleKey),groups:s,isLoading:t.isLoading||r.isLoading,emptyTitle:e(Ln.emptyTitleKey),emptyDescription:e(Ln.emptyDescriptionKey)})}function Bn({addonId:e}){let{t}=Y(),n=Rn(e),r=n.icon;return a(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[a(`div`,{className:`flex items-start gap-2.5`,children:[d(r,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),d(`div`,{className:`text-xs text-foreground font-medium`,children:n.headline})]}),d(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:n.bullets.map((e,t)=>d(`li`,{children:e},t))}),n.setupSteps&&n.setupSteps.length>0&&a(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[a(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[d(oe,{className:`h-3 w-3`}),t(`system.authentication.setupSteps`,`Setup steps`)]}),d(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:n.setupSteps.map((e,t)=>d(`li`,{children:e},t))})]}),e===`local-auth`&&a(`div`,{className:`rounded-md border border-info/30 bg-info/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[d(k,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),d(`span`,{children:d(vt,{i18nKey:`system.authentication.totpNote`,components:{access:d(ht,{to:`/system/my-access?tab=sign-in`,className:`underline text-primary`}),users:d(ht,{to:`/system/identity?tab=users`,className:`underline text-primary`})}})})]})]})}function Vn({isPending:e,error:t,what:n,onRetry:r,children:i}){let{t:o}=Y();return e?a(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,role:`status`,"data-testid":`query-pending`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),o(`certificates.queryBody.reading`,{what:n})]}):t===null?i:d(G,{title:o(`certificates.queryBody.couldNotRead`,`Could not read {{what}}`,{what:n}),message:t.message.length>0?t.message:o(`certificates.queryBody.requestFailed`,`Request failed`),onRetry:r})}function Hn(){let{t:e}=Y(),t=H.deviceCredentials.getDeviceCaStatus.useQuery({}),n=t.data;return d(X,{id:`device-ca`,title:e(`certificates.deviceCaCard.deviceCertificateAuthority`,`Device certificate authority`),icon:te,description:e(`certificates.deviceCaCard.signsTheCertificateEachPaired`,`Signs the certificate each paired device holds. It is created the first time a device is paired.`),children:d(Vn,{isPending:t.isPending,error:t.error,what:`the device CA`,onRetry:()=>void t.refetch(),children:n!==void 0&&a(`div`,{className:`space-y-1`,"data-testid":`device-ca-status`,children:[a(K,{label:e(`certificates.deviceCaCard.state`,`State`),children:[n.state===`ready`&&d(W,{variant:`success`,children:e(`certificates.deviceCaCard.ready`,`Ready`)}),n.state===`absent`&&d(W,{variant:`default`,children:e(`certificates.deviceCaCard.notCreatedYet`,`Not created yet`)}),n.state===`unavailable`&&d(W,{variant:`danger`,children:e(`certificates.deviceCaCard.unavailable`,`Unavailable`)})]}),n.state===`ready`&&a(s,{children:[d(K,{label:e(`certificates.deviceCaCard.subject`,`Subject`),valueClassName:`font-mono`,children:n.subject}),d(K,{label:e(`certificates.deviceCaCard.fingerprintSha256`,`Fingerprint (SHA-256)`),valueClassName:`font-mono`,children:n.fingerprintSha256}),d(K,{label:e(`certificates.deviceCaCard.validUntil`,`Valid until`),children:n.validTo})]}),n.state===`unavailable`&&d(K,{label:e(`certificates.deviceCaCard.reason`,`Reason`),children:d(`span`,{className:`text-danger`,children:n.reason})})]})})})}e();function Un(){let{t:e}=Y(),t=H.useUtils(),n=H.deviceCredentials.getDeviceCertificateSettings.useQuery({}),[i,o]=r(null),s=H.deviceCredentials.setDeviceCertificateSettings.useMutation({onSuccess:()=>{o(null),t.deviceCredentials.getDeviceCertificateSettings.invalidate()},onError:e=>o(`Could not save: ${e.message}`)});return d(Vn,{isPending:n.isPending,error:n.error,what:`the enrollment setting`,onRetry:()=>void n.refetch(),children:n.data!==void 0&&a(K,{label:e(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),actions:d(Ue,{checked:n.data.selfEnrollment===`allowed`,disabled:s.isPending,"aria-label":e(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),onCheckedChange:e=>s.mutate({selfEnrollment:e?`allowed`:`disabled`})}),children:[d(`span`,{className:`text-[11px] text-foreground-subtle`,children:n.data.selfEnrollment===`allowed`?e(`certificates.deviceSettingsRow.allowedAUserSignedIn`,`Allowed - a user signed in on a phone can keep it signed in. Pairing by QR works either way.`):e(`certificates.deviceSettingsRow.disabledOnlyAnAdminCan`,`Disabled - only an admin can pair a device, with a QR code.`)}),i!==null&&d(`span`,{className:`block text-[11px] text-danger`,children:i})]})})}e();function Wn(e){let[n,i]=r(()=>Date.now());return t(()=>{let t=setInterval(()=>i(Date.now()),e);return()=>clearInterval(t)},[e]),n}e();var Gn=80,Kn=208;function qn({open:e,users:t,onClose:n,onPaired:i}){let{t:o}=Y(),s=H.deviceCredentials.startEnrollment.useMutation({onSuccess:i}),[c,l]=r(``),[u,p]=r(``),m=c===``?t[0]?.id??``:c,h=s.data,g=()=>{s.reset(),p(``),n()};return d(Ne,{open:e,onClose:g,title:o(`certificates.pairDeviceDialog.pairADevice`,`Pair a device`),icon:f,width:`md`,testId:`pair-device-dialog`,error:s.isError?s.error.message:null,footer:h===void 0?a(q,{type:`button`,onClick:()=>{let e=u.trim();m===``||e===``||s.mutate({userId:m,deviceName:e})},disabled:s.isPending||m===``||u.trim()===``,children:[s.isPending&&d(A,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}),o(`certificates.pairDeviceDialog.createPairingCode`,`Create pairing code`)]}):d(q,{type:`button`,variant:`outline`,onClick:g,children:o(`certificates.pairDeviceDialog.done`,`Done`)}),children:h===void 0?a(`div`,{className:`space-y-3`,children:[d(`p`,{className:`text-[11px] text-foreground-subtle`,children:o(`certificates.pairDeviceDialog.createsAOneTimeCode`,`Creates a one-time code for a phone you hold. Scan it with the CamStack app on that phone; the phone then stays signed in as the chosen user until you revoke it.`)}),d(ct,{label:o(`certificates.pairDeviceDialog.user`,`User`),required:!0,children:d(Ce,{value:m,onChange:e=>l(e.target.value),options:t.map(e=>({value:e.id,label:e.username}))})}),d(ct,{label:o(`certificates.pairDeviceDialog.deviceName`,`Device name`),required:!0,description:o(`certificates.pairDeviceDialog.howThisPhoneIsListed`,`How this phone is listed, e.g. Anna's iPhone.`),children:d(Se,{value:u,maxLength:Gn,onChange:e=>p(e.target.value),placeholder:o(`certificates.pairDeviceDialog.annaSIphone`,`Anna's iPhone`),autoFocus:!0})})]}):d(Jn,{enrollUrl:h.enrollUrl,expiresAt:h.expiresAt,hubKnown:h.hubOrigin!==null,onRestart:()=>s.reset()})})}function Jn({enrollUrl:e,expiresAt:t,hubKnown:n,onRestart:r}){let{t:i}=Y(),o=Gt(t,Wn(1e3));return d(`div`,{className:`space-y-3`,"data-testid":`pair-issued`,children:a(`div`,{className:`flex flex-col items-center gap-3 sm:flex-row sm:items-start`,children:[d(`div`,{className:o.expired?`opacity-30`:void 0,children:d(De,{value:e,size:Kn,alt:i(`certificates.pairDeviceDialog.enrollmentQrCode`,`Enrollment QR code`)})}),a(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[d(`p`,{className:`text-[11px] text-foreground-subtle`,children:i(`certificates.pairDeviceDialog.openTheCamstackAppOn`,`Open the CamStack app on the phone and scan this code. It works once.`)}),d(`div`,{className:`text-sm font-semibold tabular-nums text-foreground`,role:`timer`,"data-testid":`pair-countdown`,children:o.expired?i(`certificates.pairDeviceDialog.expiredCreateANewCode`,`Expired - create a new code`):i(`certificates.pairDeviceDialog.expiresIn`,`Expires in {{label}}`,{label:o.label})}),a(`div`,{className:`flex items-center gap-1 rounded-md border border-border bg-background px-2 py-1`,children:[d(`code`,{className:`min-w-0 flex-1 select-all break-all font-mono text-[11px] text-foreground`,children:e}),d(Me,{value:e,srLabel:`Enrollment link`})]}),!n&&a(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[d(_,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),d(`span`,{children:i(`certificates.pairDeviceDialog.theHubCouldNotName`,`The hub could not name an address for this link, so the app must already know it.`)})]}),o.expired&&d(q,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:i(`certificates.pairDeviceDialog.newCode`,`New code`)})]})]})})}e();var Yn={key:`access.nouns.device`};function Xn({pairOpen:e,onPairClose:t}){let{t:i}=Y(),o=U(),s=We(),c=H.useUtils(),l=H.deviceCredentials.listDeviceCredentials.useQuery({includeRevoked:!0}),u=lt(),[p,_]=r(null),[v,y]=r(null),b=()=>void c.deviceCredentials.listDeviceCredentials.invalidate(),x=e=>t=>{y(null),_(`${e} failed: ${t.message}`)},S=()=>{y(null),b()},C=H.deviceCredentials.revokeDeviceCredential.useMutation({onSuccess:S,onError:x(`Revoke`)}),w=H.deviceCredentials.deleteDeviceCredential.useMutation({onSuccess:e=>{e.result!==`deleted`&&_(e.result===`live`?`Only a revoked device can be deleted: revoke it first.`:`That device no longer exists.`),S()},onError:x(`Delete`)}),T=H.deviceCredentials.renameDeviceCredential.useMutation({onSuccess:S,onError:x(`Rename`)}),E=kt(Yn,e=>C.mutateAsync({id:e}),b),D=E.busy||v!==null,O=n(()=>(l.data??[]).map(Wt),[l.data]),k=async e=>{await o({title:i(`certificates.devicesCard.revoke`,`Revoke "{{name}}"?`,{name:e.name}),message:i(`certificates.devicesCard.sDeviceStopsSigningIn`,`{{ownerName}}'s device stops signing in at once and its open sessions end. To use it again it has to be paired anew. This cannot be undone.`,{ownerName:e.ownerName}),confirmLabel:i(`certificates.devicesCard.revoke2`,`Revoke`),variant:`danger`})&&(_(null),y(e.id),C.mutate({id:e.id}))},A=async e=>{await o({title:i(`certificates.devicesCard.delete`,`Delete "{{name}}"?`,{name:e.name}),message:i(`certificates.devicesCard.isRemovedFromTheList`,`{{name}} is removed from the list. The audit trail keeps the revocation.`,{name:e.name}),confirmLabel:i(`common.delete`,`Delete`),variant:`danger`})&&(_(null),y(e.id),w.mutate({id:e.id}))},ee=async e=>{let t=(await s({title:i(`certificates.devicesCard.renameDevice`,`Rename device`),label:i(`certificates.devicesCard.deviceName`,`Device name`),defaultValue:e.name,confirmLabel:i(`certificates.devicesCard.rename`,`Rename`)}))?.trim()??``;t===``||t===e.name||(_(null),y(e.id),T.mutate({id:e.id,deviceName:t}))},j={label:i(`certificates.devicesCard.revoke2`,`Revoke`),icon:h,isAvailable:Nt,onRun:e=>void k(e),busyId:C.isPending?v:null,disabled:D},M=[{label:i(`certificates.devicesCard.rename`,`Rename`),icon:m,tone:`neutral`,isAvailable:()=>!0,onRun:e=>void ee(e),busyId:T.isPending?v:null,disabled:D},{label:i(`common.delete`,`Delete`),icon:g,isAvailable:Bt,onRun:e=>void A(e),busyId:w.isPending?v:null,disabled:D}];return a(X,{id:`devices`,title:i(`certificates.devicesCard.devices`,`Devices`),icon:f,description:i(`certificates.devicesCard.phonesThatStaySignedIn`,`Phones that stay signed in with a certificate instead of a login. Revoking one signs it out at once; it has to be paired again.`),notice:Vt(p,E.outcome),onDismissNotice:()=>{_(null),E.dismiss()},children:[d(Un,{}),d(Mt,{rows:O,label:i(`certificates.devicesCard.label`),isLoading:l.isPending,loadError:l.error===null?null:l.error.message||`Request failed`,emptyText:`No devices paired yet.`,expiresNone:`—`,action:j,extraActions:M,bulk:{revoke:E,noun:Yn,isSelectable:Nt}}),d(qn,{open:e,users:u.data??[],onClose:t,onPaired:b})]})}var Zn=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/,Qn=/-----BEGIN ((?:RSA |EC |ENCRYPTED )?PRIVATE KEY)-----[\s\S]+?-----END \1-----/,$n={certificate:`.pem,.crt,.cer`,privateKey:`.pem,.key`,ca:`.pem,.crt,.cer`};function er(e,t){if(t.trim()===``)return null;if(e===`privateKey`){let e=Qn.exec(t);return e===null?Zn.test(t)?J.t(`helpers.pemFile.isCert`):J.t(`helpers.pemFile.notKey`):e[1]===`ENCRYPTED PRIVATE KEY`?J.t(`helpers.pemFile.encrypted`):null}return Zn.test(t)?e===`certificate`&&Qn.test(t)?J.t(`helpers.pemFile.certHasKey`):null:Qn.test(t)?J.t(`helpers.pemFile.isKey`):J.t(`helpers.pemFile.notCert`)}function tr(e){return e.text()}e();function nr({kind:e,label:t,value:n,onChange:i,rows:o=6}){let{t:s}=Y(),c=l(null),[u,f]=r(null),[p,m]=r(null),h=p??er(e,n),g=`pem-${e}`,_=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t!==void 0){f(t.name);try{let e=await tr(t);m(null),i(e)}catch(e){m(`Could not read ${t.name}: ${e instanceof Error?e.message:String(e)}`)}}};return a(`div`,{className:`space-y-1`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`label`,{htmlFor:g,className:`text-[11px] text-foreground-subtle`,children:t}),a(`div`,{className:`flex min-w-0 items-center gap-2`,children:[u!==null&&d(`span`,{className:`truncate font-mono text-[10px] text-foreground-subtle`,"data-testid":`${g}-file-name`,children:u}),d(`input`,{ref:c,type:`file`,accept:$n[e],onChange:e=>void _(e),className:`hidden`,"data-testid":`${g}-file`}),a(q,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>c.current?.click(),children:[d(ce,{className:`mr-1 h-3 w-3`}),s(`system.pemField.chooseFile`,`Choose file`)]})]})]}),d(`textarea`,{id:g,value:n,onChange:e=>{f(null),m(null),i(e.target.value)},rows:o,"aria-invalid":h!==null,className:`w-full rounded border border-border bg-surface px-2 py-1 font-mono text-[11px]`}),h!==null&&d(`p`,{className:`text-[11px] text-danger`,role:`alert`,children:h})]})}e();var rr=30;function ir(e){let t=Date.parse(e);return!Number.isNaN(t)&&Date.now()-t<rr*864e5}function ar(e){if(e===null||e===``)return`—`;let t=e.replace(/:/g,``);return t.length<=16?e:`${t.slice(0,8)}…${t.slice(-8)}`}function or(){let{t:e}=Y(),t=c(),n=tt(void 0,{refetchInterval:15e3}),i=ze({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),o=st({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),s=Te({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),l=dt({onSuccess:()=>{m(!1),g(``),v(``),b(``),t.invalidateQueries({queryKey:[[`localNetwork`]]})}}),u=n.data,[f,m]=r(!1),[h,g]=r(``),[_,v]=r(``),[y,b]=r(``),S=()=>{if(!u?.caCertPem)return;let e=new Blob([u.caCertPem],{type:`application/x-pem-file`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`camstack-ca.crt`,n.click(),URL.revokeObjectURL(t)},C=u?.mode===`uploaded`?`Uploaded`:u?.mode===`generated`?`Generated local CA`:`TLS disabled`;return d(Xe,{headingId:`local-access-certificate`,title:e(`system.localAccess.certificate`,`Certificate`),icon:x,children:a(`div`,{className:`${p} space-y-3`,children:[n.isError&&d(`p`,{className:`text-xs text-danger`,children:e(`system.localAccess.couldNotReadTlsStatus`,`Could not read TLS status.`)}),u?.reissueError&&d(G,{variant:`warning`,title:e(`system.localAccess.certificateReissue`,`Certificate reissue`),message:u.reissueError}),u?.restartRequired&&d(G,{variant:`warning`,title:e(`system.localAccess.restartRequired`,`Restart required`),message:e(`system.localAccess.theHttpsListenerStillServes`,`The HTTPS listener still serves the previous certificate. Restart the hub to apply it.`)}),u?.caMissing===!0&&d(G,{variant:`warning`,title:e(`system.localAccess.caMissingTitle`,`CA missing - devices cannot trust this hub`),message:e(`system.localAccess.caMissingBody`,"The uploaded certificate was not issued by a public CA and no CA was stored with it, so Download CA has nothing to hand out. Upload the certificate again together with its CA (for mkcert, the rootCA.pem in the folder `mkcert -CAROOT` prints).")}),u?.caReplacedAt!=null&&ir(u.caReplacedAt)&&d(G,{variant:`warning`,title:e(`system.localAccess.caReplacedTitle`,`The local CA was replaced - re-install it on your devices`),message:e(`system.localAccess.caReplacedBody`,`The previous local CA had no name constraints: if its key ever leaked it could vouch for any website. The hub now uses a CA limited to private addresses and local names. Download it again and trust it on every phone and computer that used the old one (replaced {{when}}).`,{when:new Date(u.caReplacedAt).toLocaleString()})}),a(`dl`,{className:`grid grid-cols-1 gap-2 text-xs sm:grid-cols-2`,children:[a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.mode`,`Mode`)}),d(`dd`,{className:`font-medium`,children:C})]}),a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.validTo`,`Valid to`)}),d(`dd`,{className:`font-mono`,children:u?.validTo?new Date(u.validTo).toLocaleString():`—`})]}),a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.leafSha256`,`Leaf SHA-256`)}),d(`dd`,{className:`font-mono`,title:u?.leafFingerprintSha256??void 0,children:ar(u?.leafFingerprintSha256??null)})]}),u?.storedUpload!=null&&a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.storedUpload`,`Stored upload`)}),d(`dd`,{className:`font-medium`,children:e(`system.localAccess.storedUploadValue`,`valid to {{validTo}}, {{ca}}`,{validTo:new Date(u.storedUpload.validTo).toLocaleDateString(),ca:u.storedUpload.hasCa?e(`system.localAccess.storedUploadWithCa`,`with its CA`):e(`system.localAccess.storedUploadNoCa`,`no CA`)})})]}),a(`div`,{children:[d(`dt`,{className:`text-foreground-subtle`,children:e(`system.localAccess.caSha256`,`CA SHA-256`)}),d(`dd`,{className:`font-mono`,title:u?.caFingerprintSha256??void 0,children:u?.mode===`uploaded`&&u.caFingerprintSha256===null?d(`span`,{className:`font-sans text-foreground-subtle`,children:e(`system.localAccess.issuerNotIncludedInThe`,`Issuer not included in the upload (not the local CA)`)}):ar(u?.caFingerprintSha256??null)})]})]}),u&&u.sans.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,children:u.sans.map(e=>d(`span`,{className:`rounded border border-border bg-surface px-1.5 py-0.5 font-mono text-[10px] text-foreground-subtle`,children:e},e))}),a(`div`,{className:`flex flex-wrap gap-2`,children:[d(Je,{label:e(`system.localAccess.regenerate`,`Regenerate`),title:e(`system.localAccess.issueANewLeaf`,`Issue a new leaf?`),description:e(`system.localAccess.issuesANewLeafUnder`,`Issues a new leaf under the current local CA. Clients that trust the CA keep working. The HTTPS listener reloads.`),confirmLabel:e(`system.localAccess.regenerate`,`Regenerate`),disabled:u?.mode===`uploaded`||i.isPending,action:()=>i.mutateAsync({})}),d(q,{size:`sm`,variant:`outline`,onClick:()=>m(e=>!e),children:e(`system.localAccess.upload`,`Upload`)}),u?.caCertPem&&d(q,{size:`sm`,variant:`outline`,onClick:S,children:e(`system.localAccess.downloadCa`,`Download CA`)}),u?.mode===`uploaded`&&d(Je,{label:e(`system.localAccess.revertToGenerated`,`Revert to generated`),title:e(`system.localAccess.revertTitle`,`Switch back to the generated certificate?`),description:e(`system.localAccess.keepsTheUploadedPair`,`Returns to the generated local CA. The uploaded certificate and its CA stay stored here; you can select them again.`),confirmLabel:e(`system.localAccess.revert`,`Revert`),disabled:o.isPending,action:()=>o.mutateAsync({})}),u?.mode===`generated`&&u.storedUpload!=null&&d(Je,{label:e(`system.localAccess.useUploaded`,`Use uploaded certificate`),title:e(`system.localAccess.useUploadedTitle`,`Serve the stored upload again?`),description:e(`system.localAccess.useUploadedDescription`,`The stored uploaded certificate replaces the generated one on the HTTPS listener. The generated certificate stays stored.`),confirmLabel:e(`system.localAccess.useUploaded`,`Use uploaded certificate`),disabled:s.isPending,action:()=>s.mutateAsync(void 0)})]}),f&&a(`div`,{className:`space-y-2 border-t border-border pt-3`,children:[d(nr,{kind:`certificate`,label:e(`system.localAccess.certificateOrFullChainPem`,`Certificate or full chain (PEM)`),value:h,onChange:g}),d(nr,{kind:`privateKey`,label:e(`system.localAccess.privateKeyPem`,`Private key (PEM)`),value:_,onChange:v}),d(nr,{kind:`ca`,label:e(`system.localAccess.caPemRequired`,`CA (PEM) - required unless the certificate comes from a public CA`),value:y,onChange:b,rows:4}),d(q,{size:`sm`,disabled:!h.trim()||!_.trim()||er(`certificate`,h)!==null||er(`privateKey`,_)!==null||er(`ca`,y)!==null||l.isPending,onClick:()=>l.mutate({certPem:h,keyPem:_,...y.trim()?{caPem:y}:{}}),children:e(`system.localAccess.saveCertificate`,`Save certificate`)}),l.isError&&d(`p`,{className:`text-xs text-danger`,children:l.error instanceof Error?l.error.message:e(`system.localAccess.uploadFailed`,`Upload failed`)})]})]})})}var sr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`};function cr(e){let t=e.find(e=>e.isHub);return t?.https.kind===`served`?t.https.status.caFingerprintSha256:null}function lr({https:e,mesh:t,now:n}){let{t:r}=Y(),i=tt().data?.caCertPem??``,o=()=>{if(i===``)return;let e=URL.createObjectURL(new Blob([i],{type:`application/x-pem-file`})),t=document.createElement(`a`);t.href=e,t.download=`camstack-ca.crt`,t.click(),URL.revokeObjectURL(e)},s=t?.ca,c=s?.state===`ready`?Date.parse(s.validTo):null,l=t?.listener;return a(`div`,{className:`space-y-1`,"data-testid":`ca-strip`,children:[d(K,{label:r(`certificates.caStrip.localHttpsCaSha256`,`Local HTTPS CA (SHA-256)`),valueClassName:`font-mono`,children:a(`span`,{className:`flex flex-wrap items-center gap-2`,children:[cr(e)??`—`,i!==``&&a(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:o,children:[d(b,{className:`h-3 w-3`,"aria-hidden":!0}),r(`certificates.caStrip.downloadCa`,`Download CA`)]})]})}),d(K,{label:r(`certificates.caStrip.clusterCaSha256`,`Cluster CA (SHA-256)`),valueClassName:`font-mono`,children:s===void 0?`—`:s.state===`ready`?s.fingerprintSha256:d(`span`,{className:`text-danger`,children:r(`certificates.caStrip.unavailable`,{reason:s.reason})})}),s?.state===`ready`&&a(K,{label:r(`certificates.caStrip.clusterCaValidUntil`,`Cluster CA valid until`),children:[s.validTo,c!==null&&!Number.isNaN(c)&&a(`span`,{className:`ml-2 text-[10px] ${sr[Yt(c,n)]}`,children:[`(`,Ft(c,n),`)`]})]}),l!==void 0&&a(K,{label:r(`certificates.caStrip.nodeListener`,`Node listener`),children:[l.state===`open`&&d(W,{variant:`success`,children:r(`certificates.caStrip.open`,`Open`)}),l.state===`not-started`&&d(W,{variant:`default`,children:r(`certificates.caStrip.notStarted`,`Not started`)}),l.state===`closed`&&a(`span`,{className:`text-danger`,children:[r(`certificates.caStrip.closedSince`,{when:It(l.since)}),` `,l.reason]})]}),t!==void 0&&!t.registryAvailable&&a(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-2.5 py-1.5 text-[11px] text-foreground`,children:[d(_,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),d(`span`,{children:r(`certificates.caStrip.theCertificateRegistryIsNot`,`The certificate registry is not up, so the node list below is incomplete.`)})]})]})}function ur(e,t){let n=new Set;for(let t of e)n.add(t.nodeId);for(let e of t?.nodes??[])n.add(e.nodeId);return[...n].map(n=>{let r=e.find(e=>e.nodeId===n)??null,i=t?.nodes.find(e=>e.nodeId===n)??null;return{nodeId:n,isHub:r?.isHub??n===`hub`,online:r?.online??i?.online??!1,https:r,mesh:i}}).toSorted((e,t)=>Number(t.isHub)-Number(e.isHub)||e.nodeId.localeCompare(t.nodeId))}function dr(e){return e.isHub?J.t(`helpers.nodesModel.hubReissued`):e.mesh===null?J.t(`helpers.nodesModel.noCertRecorded`):e.online?null:J.t(`helpers.certificateModel.nodeOffline`)}function fr(e){return e.isHub||e.mesh===null?dr(e):null}var pr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`},mr={enroll:`Issued at enrollment`,renewal:`Issued by a renewal`,boot:`Issued at boot`,pairing:`Issued at pairing`,observed:`Observed on its connection`},hr={uploaded:`Uploaded`,generated:`Generated`,disabled:`Disabled`};function gr(e){let t=e.https?.https;return t?.kind===`served`?qt(t.status.validTo):null}function _r({ms:e,now:t}){return e===null?d(`span`,{className:`text-foreground-subtle`,children:`—`}):a(`div`,{children:[d(`div`,{children:It(e)}),d(`div`,{className:`text-[10px] ${pr[Yt(e,t)]}`,children:Ft(e,t)})]})}function vr({row:e}){let{t}=Y(),n=e.https?.https;return n===void 0?d(`span`,{className:`text-foreground-subtle`,children:`—`}):n.kind===`served`?a(`div`,{title:n.status.leafFingerprintSha256??``,children:[d(W,{variant:`success`,className:`text-[10px]`,children:t(`certificates.nodesColumns.served`,`Served`)}),d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:hr[n.status.mode]}),d(`div`,{className:`mt-1 font-mono text-[10px] text-foreground-subtle`,children:Kt(n.status.leafFingerprintSha256)}),n.status.sans.length>0&&d(`div`,{className:`mt-0.5 max-w-[14rem] truncate font-mono text-[10px] text-foreground-subtle`,title:n.status.sans.join(`, `),children:n.status.sans.join(`, `)})]}):a(`div`,{className:`max-w-[16rem]`,children:[d(W,{variant:n.kind===`unreadable`?`danger`:`warning`,className:`text-[10px]`,children:n.kind===`unreadable`?t(`certificates.nodesColumns.unreadable`,`Unreadable`):t(`certificates.nodesColumns.notServed`,`Not served`)}),d(`div`,{className:`mt-1 whitespace-normal text-[10px] text-foreground-subtle`,children:n.reason})]})}function yr({row:e}){let{t}=Y(),n=e.mesh?.current??null;if(n===null)return d(`span`,{className:`text-foreground-subtle`,children:t(`certificates.nodesColumns.noneRecorded`,`None recorded`)});let r=e.mesh?.history.length??0;return a(`div`,{children:[d(`div`,{className:`font-mono text-[11px]`,title:n.serial,children:Ut(n.serial)}),d(`div`,{className:`font-mono text-[10px] text-foreground-subtle`,title:n.fingerprintSha256,children:Kt(n.fingerprintSha256)}),a(`div`,{className:`text-[10px] text-foreground-subtle`,children:[mr[n.issuedVia],r>0?` · ${t(`certificates.nodesColumns.earlier`,{count:r})}`:``]})]})}function br({row:e}){let{t}=Y(),n=e.mesh?.presentingCurrent??null;return n===null?d(`span`,{className:`text-foreground-subtle`,children:e.online?`—`:t(`certificates.nodesColumns.offline`,`Offline`)}):n?d(W,{variant:`success`,className:`text-[10px]`,children:t(`common.yes`,`Yes`)}):d(W,{variant:`warning`,className:`text-[10px]`,children:t(`certificates.nodesColumns.noPresentsAnother`,`No - presents another`)})}function xr(e){let t=e.icon;return a(q,{type:`button`,variant:`ghost`,size:`sm`,className:e.danger?`text-danger hover:bg-danger/10`:void 0,disabled:e.reason!==null||e.busy,title:e.reason??void 0,"aria-label":e.ariaLabel,onClick:e.onClick,children:[e.spinning?d(A,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):d(t,{className:`h-3 w-3`,"aria-hidden":!0}),e.label]})}function Sr({reasons:e}){let{t}=Y();return a(ge,{className:`inline-block`,children:[d(be,{children:d(`span`,{className:`cursor-help text-[11px] text-foreground-subtle`,"data-testid":`hub-managed-note`,children:t(`certificates.nodesColumns.managedByTheHub`,`Managed by the hub`)})}),d(Ge,{children:d(`ul`,{className:`max-w-xs space-y-1 whitespace-normal text-left text-[11px]`,children:e.map(e=>d(`li`,{children:e},e))})})]})}function Cr({row:e,o:t}){let{t:n}=Y(),r=e.https===null?`No HTTPS inventory for this node.`:Lt(e.https).reason,i=dr(e),o=fr(e),s=n=>t.running?.nodeId===e.nodeId&&t.running.action===n,c=t=>!e.isHub||t===null,l=[r,i,o].filter((e,t,n)=>e!==null&&n.indexOf(e)===t);return a(`div`,{className:`flex w-44 flex-col items-end gap-1`,children:[a(`div`,{className:`flex flex-col items-end gap-0.5`,children:[c(r)&&d(xr,{label:n(`certificates.nodesColumns.renewHttps`,`Renew HTTPS`),ariaLabel:n(`certificates.nodesColumns.renewTheCertificateOn`,`Renew the certificate on {{nodeId}}`,{nodeId:e.nodeId}),icon:S,reason:r,busy:t.busy,spinning:s(`renew-https`),danger:!1,onClick:()=>t.onRenewHttps(e)}),c(i)&&d(xr,{label:s(`renew-identity`)?n(`certificates.nodesColumns.renewing`,`Renewing…`):n(`certificates.nodesColumns.renewIdentity`,`Renew identity`),ariaLabel:n(`certificates.nodesColumns.renewTheClusterCertificateOf`,`Renew the cluster certificate of {{nodeId}}`,{nodeId:e.nodeId}),icon:S,reason:i,busy:t.busy,spinning:s(`renew-identity`),danger:!1,onClick:()=>t.onRenewIdentity(e)}),c(o)&&d(xr,{label:n(`certificates.nodesColumns.revokeIdentity`,`Revoke identity`),ariaLabel:n(`certificates.nodesColumns.revokeTheClusterCertificateOf`,`Revoke the cluster certificate of {{nodeId}}`,{nodeId:e.nodeId}),icon:h,reason:o,busy:t.busy,spinning:s(`revoke-identity`),danger:!0,onClick:()=>t.onRevokeIdentity(e)})]}),e.isHub&&l.length>0&&d(Sr,{reasons:l}),!e.isHub&&r!==null&&e.https!==null&&d(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`renew-reason-${e.nodeId}`,children:r}),!e.isHub&&i!==null&&d(`div`,{className:`w-full whitespace-normal text-right text-[10px] text-foreground-subtle`,"data-testid":`mesh-reason-${e.nodeId}`,children:i})]})}function wr(e){return[{key:`node`,header:J.t(`certificates.nodesColumns.node`,`Node`),sortValue:e=>e.isHub?``:e.nodeId.toLowerCase(),render:e=>a(`div`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`font-medium text-foreground`,children:e.nodeId}),e.nodeId===`hub`&&d(W,{variant:`info`,className:`text-[10px]`,children:J.t(`common.hubWord`)}),!e.online&&d(W,{variant:`default`,className:`text-[10px]`,children:J.t(`common.offline`)})]})},{key:`https-state`,header:`HTTPS`,notSortableReason:`A state with a reason has no single order.`,render:e=>d(vr,{row:e})},{key:`https-expires`,header:J.t(`certificates.nodesColumns.httpsExpires`,`HTTPS expires`),sortValue:e=>gr(e),render:t=>d(_r,{ms:gr(t),now:e.now})},{key:`identity`,header:J.t(`certificates.nodesColumns.identity`,`Identity`),sortValue:e=>e.mesh?.current?.serial??null,render:e=>d(yr,{row:e})},{key:`identity-expires`,header:J.t(`certificates.nodesColumns.identityExpires`,`Identity expires`),sortValue:e=>e.mesh?.current?.notAfter??null,render:t=>d(_r,{ms:t.mesh?.current?.notAfter??null,now:e.now})},{key:`presenting`,header:J.t(`certificates.nodesColumns.inUse`,`In use`),notSortableReason:`Offline nodes have no answer to order by.`,render:e=>d(br,{row:e})},{key:`actions`,header:J.t(`certificates.nodesColumns.actions`,`Actions`),align:`right`,notSortableReason:`Actions have no order.`,render:t=>d(Cr,{row:t,o:e})}]}e();function Tr(){let{t:e}=Y(),t=U(),i=H.useUtils(),o=Wn(6e4),s=H.certificates.listHttpsCertificates.useQuery(),c=H.certificates.getMeshCertificates.useQuery(),[l,u]=r(null),[f,p]=r(null),[m,h]=r(null),g=()=>{h(null),i.certificates.listHttpsCertificates.invalidate(),i.certificates.getMeshCertificates.invalidate()},_=e=>(t,n)=>{h(null),u(`${n.nodeId}: ${e} - ${t.message}`)},v=H.certificates.renewHttpsOnNode.useMutation({onSuccess:(t,n)=>{p({tone:`success`,message:t.restartRequired?e(`certificates.nodesCard.newCertificateIssuedRestartThe`,`{{nodeId}}: new certificate issued. Restart the node to serve it.`,{nodeId:n.nodeId}):e(`certificates.nodesCard.newCertificateIssuedAndServed`,`{{nodeId}}: new certificate issued and served.`,{nodeId:n.nodeId})}),g()},onError:_(`renewal failed`)}),y=H.certificates.renewMeshOnNode.useMutation({onSuccess:e=>{p(Ht(e)),g()},onError:_(`renewal could not start`)}),b=H.certificates.revokeMeshOnNode.useMutation({onSuccess:e=>{p({tone:`success`,message:`${e.nodeId}: ${e.next}`}),g()},onError:_(`revoke failed`)}),x=v.isPending||y.isPending||b.isPending,S=(e,t)=>{u(null),p(null),h({nodeId:e,action:t})},C=async n=>{await t({title:e(`certificates.nodesCard.renewHttpsOn`,`Renew HTTPS on "{{nodeId}}"?`,{nodeId:n.nodeId}),message:n.isHub?e(`certificates.nodesCard.aNewCertificateIsIssued`,`A new certificate is issued from the local CA. Clients that trust the CA keep working.`):e(`certificates.nodesCard.theNodeMakesANew`,`The node makes a new key, the hub signs it and the node switches over without a restart. It keeps serving what it had if anything fails.`),confirmLabel:e(`certificates.nodesCard.renew`,`Renew`)})&&(S(n.nodeId,`renew-https`),v.mutate({nodeId:n.nodeId}))},T=e=>{S(e.nodeId,`renew-identity`),y.mutate({nodeId:e.nodeId})},E=async n=>{await t({title:e(`certificates.nodesCard.revokeTheIdentityOf`,`Revoke the identity of "{{nodeId}}"?`,{nodeId:n.nodeId}),message:e(`certificates.nodesCard.isDisconnectedAtOnceAnd`,`{{nodeId}} is disconnected at once and can no longer connect. To bring it back it must be paired again from System → Cluster → Agents. It stays in the node list until you forget it on the Cluster page. This cannot be undone.`,{nodeId:n.nodeId}),confirmLabel:e(`certificates.nodesCard.revokeAndDisconnect`,`Revoke and disconnect`),variant:`danger`})&&(S(n.nodeId,`revoke-identity`),b.mutate({nodeId:n.nodeId}))},D=wr({now:o,busy:x,running:m,onRenewHttps:e=>void C(e),onRenewIdentity:T,onRevokeIdentity:e=>void E(e)}),O=n(()=>ur(s.data??[],c.data),[s.data,c.data]),k=c.data?.registryAvailable??!0;return d(X,{id:`nodes`,title:e(`certificates.nodesCard.nodes`,`Nodes`),icon:w,description:e(`certificates.nodesCard.eachNodeHoldsTwoCertificates`,`Each node holds two certificates: one it serves over HTTPS, one that proves its identity to the hub. Renewing replaces a certificate without a gap; revoking an identity cuts the node off until it re-joins.`),notice:Vt(l,f),onDismissNotice:()=>{u(null),p(null)},children:d(Vn,{isPending:s.isPending||c.isPending,error:s.error??c.error,what:`node certificates`,onRetry:()=>{s.refetch(),c.refetch()},children:a(`div`,{className:`space-y-3`,children:[d(lr,{https:s.data??[],mesh:c.data,now:o}),d(Ie,{columns:D,rows:O,rowKey:e=>e.nodeId,minWidthPx:960,maxBodyHeight:ke,defaultSort:{columnKey:`node`,dir:`asc`},emptyMessage:k?e(`certificates.nodesCard.noNodesReported`,`No nodes reported.`):e(`certificates.nodesCard.theCertificateRegistryIsNot`,`The certificate registry is not available yet, so nodes cannot be listed.`)})]})})})}function Er({pairOpen:e,onPairClose:t}){return a(`div`,{className:`space-y-4`,"data-testid":`certificates-page`,children:[d(Xn,{pairOpen:e,onPairClose:t}),d(Hn,{}),d(or,{}),d(Tr,{})]})}function Dr({userId:e,username:t,onClose:n}){let{t:r}=Y(),i=U(),o=H.useUtils(),s=Re({userId:e}),c=H.auth.listLoginMethods.useQuery(),l=Ee({onSuccess:()=>void o.userManagement.listExternalIdentities.invalidate()}),u=new Map((c.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),f=s.data??[],p=async(n,a)=>{await i({title:r(`users.externalIdentitiesModal.removeSignInLink`,`Remove sign-in link`),message:r(`users.externalIdentitiesModal.willNoLongerBeAble`,`"{{username}}" will no longer be able to sign in with this {{label}} account.`,{username:t,label:a}),confirmLabel:r(`common.remove`,`Remove`),variant:`danger`})&&l.mutate({userId:e,provider:n.provider,subject:n.subject})};return d(we,{open:!0,onOpenChange:e=>!e&&n(),children:a(Pe,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[d(it,{children:a(Ve,{className:`flex items-center gap-2`,children:[d(D,{className:`h-4 w-4 text-primary`}),a(`span`,{children:[r(`users.externalIdentitiesModal.linkedSignInAccounts`,`Linked sign-in accounts`),a(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[r(`users.externalIdentitiesModal.user`,`User:`),` `,d(`span`,{className:`font-mono`,children:t})]})]})]})}),d(me,{className:`space-y-3`,children:s.isLoading?a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),r(`common.loading`,`Loading…`)]}):f.length===0?d(`p`,{className:`text-xs text-foreground-subtle`,children:r(`users.externalIdentitiesModal.noLinkedAccountsOnlyThe`,`No linked accounts. Only the user can link one, from their own profile page.`)}):d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:f.map(e=>{let t=u.get(e.provider),n=t??e.provider;return a(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[a(`div`,{className:`flex-1 min-w-0`,children:[a(`div`,{className:`font-medium text-foreground truncate`,children:[n,t===void 0&&d(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:r(`users.externalIdentitiesModal.providerUnavailable`,`provider unavailable`)})]}),a(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[e.label??e.subject,` ·`,` `,new Date(e.linkedAt).toLocaleDateString()]})]}),a(`button`,{onClick:()=>void p(e,n),disabled:l.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[d(pe,{className:`h-3 w-3`}),r(`common.remove`,`Remove`)]})]},`${e.provider}|${e.subject}`)})})}),d(Qe,{children:d(q,{onClick:n,variant:`secondary`,children:r(`common.close`,`Close`)})})]})})}function Or({userId:e,username:t,onClose:n}){let{t:r}=Y(),i=c(),o=U(),l=Be({userId:e}),u=l.data,p=()=>i.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),m=Ze({onSuccess:()=>{p(),n()}}),h=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return d(we,{open:!0,onOpenChange:e=>!e&&n(),children:a(Pe,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[d(it,{children:a(Ve,{className:`flex items-center gap-2`,children:[d(f,{className:`h-4 w-4 text-primary`}),a(`span`,{children:[r(`users.totpModal.twoFactorAuthentication`,`Two-factor authentication`),a(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[r(`users.totpModal.user`,`User:`),` `,d(`span`,{className:`font-mono`,children:t})]})]})]})}),a(me,{className:`space-y-4`,children:[h===`loading`&&a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),r(`users.totpModal.checkingStatus`,`Checking status…`)]}),h===`not_enrolled`&&a(`div`,{className:`rounded-md border border-border bg-surface-hover/30 px-3 py-2.5 flex items-start gap-2.5 text-xs text-foreground-subtle`,children:[d(k,{className:`h-4 w-4 mt-0.5 shrink-0`}),a(`div`,{children:[d(`div`,{className:`font-medium text-foreground`,children:r(`users.totpModal.2faNotEnrolled`,`2FA not enrolled`)}),d(`p`,{className:`mt-0.5`,children:r(`users.totpModal.onlyTheUserThemselvesCan`,`Only the user themselves can enable 2FA, from their own profile page.`)})]})]}),h===`enrolled`&&u&&a(s,{children:[a(`div`,{className:`rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5 flex items-start gap-2.5`,children:[d(O,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),a(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[d(`div`,{className:`font-medium`,children:r(`users.totpModal.2faIsActive`,`2FA is active`)}),d(`div`,{className:`text-foreground-subtle`,children:r(`common.enrolledOn`,{when:u.confirmedAt?new Date(u.confirmedAt).toLocaleString():`—`})})]})]}),d(`div`,{className:`text-[11px] text-foreground-subtle`,children:r(`users.totpModal.removingHereClearsTheServer`,`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`)}),a(`div`,{className:`flex justify-end gap-2`,children:[d(q,{onClick:n,variant:`secondary`,children:r(`common.close`,`Close`)}),a(`button`,{onClick:async()=>{await o({title:r(`users.totpModal.remove2fa`,`Remove 2FA`),message:r(`users.totpModal.removeTwoFactorAuthenticationFor`,`Remove two-factor authentication for "{{username}}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,{username:t}),confirmLabel:r(`common.remove`,`Remove`),variant:`danger`})&&m.mutate({userId:e})},disabled:m.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[m.isPending?d(A,{className:`h-3 w-3 animate-spin`}):d(T,{className:`h-3 w-3`}),r(`users.totpModal.remove2fa`,`Remove 2FA`)]})]})]})]})]})})}e();function kr({userId:e,username:t,onClose:n}){let{t:i}=Y(),{user:o,logout:s}=_t(),c=o?.id===e,l=U(),u=H.useUtils(),f=H.auth.listSessions.useQuery({userId:e}),[p,m]=r(null),h=H.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(c&&`userId`in t){s();return}u.auth.listSessions.invalidate()},onError:e=>m(`Sign out failed: ${e.message}`)}),g=async e=>{await l({title:i(`users.userSessionsModal.signOutThisSession`,`Sign out this session`),message:i(`users.userSessionsModal.onWillHaveToSign`,`"{{username}}" on {{label}} will have to sign in again.`,{username:t,label:Xt(e.client).label}),confirmLabel:i(`users.userSessionsModal.signOut`,`Sign out`),variant:`danger`})&&(m(null),h.mutate({id:e.id}))},_=async()=>{await l({title:i(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),message:c?i(`users.userSessionsModal.everySessionOfYourOwn`,`Every session of your own account ends, this browser included: you will be signed out here too.`):i(`users.userSessionsModal.everySessionOfEndsAt`,`Every session of "{{username}}" ends at once; each device has to sign in again.`,{username:t}),confirmLabel:i(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`),variant:`danger`})&&(m(null),h.mutate({userId:e}))},v=h.isPending&&h.variables!==void 0&&`id`in h.variables?h.variables.id:null;return d(we,{open:!0,onOpenChange:e=>!e&&n(),children:a(Pe,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[d(it,{children:a(Ve,{className:`flex items-center gap-2`,children:[d(fe,{className:`h-4 w-4 text-primary`}),a(`span`,{children:[i(`users.userSessionsModal.activeSessions`,`Active sessions`),a(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[i(`users.userSessionsModal.user`,`User:`),` `,d(`span`,{className:`font-mono`,children:t})]})]})]})}),a(me,{className:`space-y-3`,children:[p!==null&&d(`div`,{className:`text-[11px] text-danger`,children:p}),d(Jt,{sessions:f.data??[],isLoading:f.isLoading,loadError:f.isError?f.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void g(e),revokingId:v})]}),a(Qe,{className:`justify-between`,children:[a(`button`,{onClick:()=>void _(),disabled:h.isPending||(f.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[h.isPending&&v===null?d(A,{className:`h-3 w-3 animate-spin`}):d(ue,{className:`h-3 w-3`}),i(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`)]}),d(q,{onClick:n,variant:`secondary`,children:i(`common.close`,`Close`)})]})]})})}function Ar({icon:e,label:t,count:n,all:r,total:i}){let{t:o}=Y();return a(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[d(e,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),d(`span`,{className:`min-w-0 flex-1 text-foreground-subtle`,children:t}),d(`span`,{className:n===0?`text-foreground-subtle`:`font-medium text-foreground`,children:n===0?o(`common.none`):r?o(`users.scopePreview.all`,`all {{total}}`,{total:i}):o(`users.scopePreview.of`,`{{count}} of {{total}}`,{count:n,total:i})})]})}function jr({scopes:e,isAdmin:t,invalidReason:n}){let{t:r}=Y(),i=ee(),c=o({queryKey:[`auth`,`previewScope`,e,t],enabled:n===null,queryFn:()=>i.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:t})}),{data:l}=Oe({projection:`slim`}),u=l?.length??0;if(n!==null)return d(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:a(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,children:[d(C,{className:`h-3 w-3 shrink-0`}),n]})});if(c.isLoading)return a(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-surface p-3 text-[11px] text-foreground-subtle`,children:[d(A,{className:`h-3 w-3 animate-spin`}),r(`users.scopePreview.resolving`,`Resolving…`)]});if(c.isError||!c.data)return d(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:d(`p`,{className:`text-[11px] text-danger`,children:r(`users.scopePreview.couldNotResolveThisGrant`,`Could not resolve this grant set. Saving is still allowed — the server enforces the same rules either way.`)})});let f=c.data;return d(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:f.isAdmin?a(`p`,{className:`text-[11px] text-foreground`,children:[d(`span`,{className:`font-medium`,children:r(`users.scopePreview.administrator`,`Administrator`)}),` `,r(`users.scopePreview.unrestricted`)]}):a(s,{children:[d(Ar,{icon:v,label:r(`users.scopePreview.devicesTheyCanSee`,`Devices they can see`),count:f.device.view.deviceCount,all:f.device.view.all,total:u}),d(Ar,{icon:m,label:r(`users.scopePreview.devicesTheyCanOperate`,`Devices they can operate`),count:f.device.create.deviceCount,all:f.device.create.all,total:u}),d(Ar,{icon:g,label:r(`users.scopePreview.devicesTheyCanDelete`,`Devices they can delete`),count:f.device.delete.deviceCount,all:f.device.delete.all,total:u}),a(`div`,{className:`border-t border-border pt-2 text-[10px] text-foreground-subtle`,children:[r(`users.scopePreview.systemAccess`,`System access:`),` `,f.system.length===0?r(`common.none`):f.system.join(`, `),f.capabilities.length>0&&a(s,{children:[` `,r(`users.scopePreview.extraCapabilities`,`· Extra capabilities:`),` `,f.capabilities.map(e=>e.name).join(`, `)]}),f.addons.length>0&&a(s,{children:[` `,r(`users.scopePreview.addons`,`· Addons:`),` `,f.addons.map(e=>e.name).join(`, `)]})]}),f.device.view.deviceCount===0&&d(`p`,{className:`text-[10px] text-warning`,children:r(`users.scopePreview.thisUserWillNotBe`,`This user will not be able to see any device.`)})]})})}e();function Mr(e){let t=L(e);return t===null?{mode:e.length===0?`role`:`advanced`,roleId:null,selector:{kind:`all`},includeLinked:!0,advancedScopes:e}:{mode:`role`,roleId:t.roleId,selector:t.selector,includeLinked:t.includeLinked,advancedScopes:e}}function Nr(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:ae({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function Pr({user:e,onClose:t,onSubmit:i,submitting:o,callerScopes:c}){let{t:l}=Y(),u=N(),f=n(()=>Mr(ie(e.scopes??[])),[e.scopes]),[p,m]=r(f),[h,g]=r(f.mode===`advanced`),_=n(()=>Nr(p),[p]),v=!e.isAdmin&&p.mode===`role`&&p.roleId===null,y=n(()=>e.isAdmin?null:p.mode===`role`&&p.roleId===null?l(`users.userAccessModal.pickAccess`):He(_,u),[e.isAdmin,p.mode,p.roleId,_]),b=e=>m({...p,...e});return d(we,{open:!0,onOpenChange:e=>!e&&t(),children:a(Pe,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[a(it,{children:[d(Ve,{children:l(`users.userAccessModal.title`,{name:e.username})}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.isAdmin?l(`users.userAccessModal.thisUserIsAnAdministrator`,`This user is an administrator — they can do everything, and the settings below are ignored.`):l(`users.userAccessModal.chooseWhatTheyCanDo`,`Choose what they can do, then which devices it applies to.`)})]}),a(me,{className:`space-y-4`,children:[v&&a(`div`,{className:`flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 p-3`,children:[d(C,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),a(`p`,{className:`text-[11px] text-foreground`,children:[d(`span`,{className:`font-medium`,children:l(`users.userAccessModal.noAccess`,`No access.`)}),` `,d(`span`,{className:`text-foreground-subtle`,children:l(`users.userAccessModal.cannotSeeAnything`,{name:e.username})})]})]}),a(`section`,{className:`space-y-2`,children:[d(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:l(`users.userAccessModal.1WhatCanTheyDo`,`1 · What can they do`)}),d(`div`,{className:`space-y-1.5`,children:z.map(e=>{let t=p.mode===`role`&&p.roleId===e.id;return a(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 transition-colors ${t?`border-primary bg-primary/5`:`border-border hover:bg-foreground-subtle/5`}`,children:[d(`input`,{type:`radio`,name:`access-role`,checked:t,onChange:()=>b({mode:`role`,roleId:e.id}),className:`mt-0.5 border-border focus:ring-primary`}),a(`span`,{className:`min-w-0`,children:[d(`span`,{className:`block text-[12px] font-medium text-foreground`,children:e.label}),d(`span`,{className:`mt-0.5 block text-[10px] text-foreground-subtle`,children:e.description})]})]},e.id)})}),a(`button`,{type:`button`,onClick:()=>{if(!h){m({...p,mode:`advanced`,advancedScopes:_}),g(!0);return}g(!1),m(Mr(p.advancedScopes))},className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] text-foreground-subtle transition-colors hover:bg-foreground-subtle/10 hover:text-foreground`,children:[d(h?P:F,{className:`h-3 w-3`}),l(`users.userAccessModal.advancedEditRawGrants`,`Advanced — edit raw grants`)]}),h&&a(`div`,{className:`rounded-lg border border-border p-2`,children:[d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:l(`users.userAccessModal.oneRowPerGrantAnything`,`One row per grant. Anything expressible here overrides the three roles above; close this section to go back to them.`)}),d(at,{value:p.advancedScopes,onChange:e=>b({mode:`advanced`,advancedScopes:e}),clampToParent:c,emptyHint:d(s,{children:d(vt,{i18nKey:`users.userAccessModal.noGrants`,values:{name:e.username},components:{b:d(`span`,{className:`font-medium text-foreground`})}})})})]})]}),p.mode===`role`&&a(`section`,{className:`space-y-2`,children:[d(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:l(`users.userAccessModal.2OnWhichDevices`,`2 · On which devices`)}),d(_e,{value:p.selector,onChange:e=>b({selector:e}),includeLinked:p.includeLinked,onIncludeLinkedChange:e=>b({includeLinked:e}),clampToDeviceIds:null})]}),a(`section`,{className:`space-y-2`,children:[d(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:p.mode===`role`?l(`users.userAccessModal.3Result`,`3 · Result`):l(`users.userAccessModal.2Result`,`2 · Result`)}),d(jr,{scopes:_,isAdmin:e.isAdmin,invalidReason:y})]})]}),a(Qe,{children:[d(q,{variant:`outline`,size:`sm`,onClick:t,children:l(`common.cancel`,`Cancel`)}),d(q,{size:`sm`,onClick:()=>i([..._]),disabled:o||y!==null,children:o?d(A,{className:`h-3 w-3 animate-spin`}):l(`users.userAccessModal.saveAccess`,`Save access`)})]})]})})}e();var Fr=8;function Ir(){return{username:``,password:``,isAdmin:!1}}function Lr(e){return{id:e.id,username:e.username,password:``,isAdmin:e.isAdmin}}function Rr(e){return e instanceof Error?e.message:J.t(`admin.system.users.genericError`)}function zr(){let{t:e}=Y(),n=c(),{user:i}=_t(),{state:o,openNew:l,openEdit:u,close:p}=Ye(),[h,_]=r(null),[v,b]=r(null),[x,S]=r(!1),{data:C,isLoading:w,isError:T,error:O,refetch:k}=lt(),ee=U(),j=We(),M=()=>n.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),N=Fe(),P=nt({onSuccess:M}),F=ve({onSuccess:M}),I=pt({onSuccess:M}),ne=ft({onSuccess:()=>{M(),R(null)}}),[L,R]=r(null),[z,re]=r(null),[ae,oe]=r(null),[se,ce]=r(null),B=C??[],V=o.mode===`edit`?B.find(e=>e.id===o.id)??null:null,ue=()=>{_(null),b(null),S(!1),N.reset(),F.reset(),p()};t(()=>{if(o.mode===`closed`){_(null),b(null),S(!1);return}if(o.mode===`new`){_(e=>e!==null&&e.id===void 0?e:Ir());return}if(V===null){w||p();return}_(e=>e?.id===V.id?e:Lr(V))},[o,V,w,p]);let de=o.mode===`new`&&h!==null&&h.id===void 0||o.mode===`edit`&&h!==null&&V!==null;async function pe(t){await ee({title:e(`admin.system.users.deleteUser`,`Delete user`),message:e(`admin.system.users.permanentlyDeleteUserThisCannot`,`Permanently delete user "{{username}}"? This cannot be undone — any active sessions will be revoked on next request.`,{username:t.username}),confirmLabel:e(`common.delete`,`Delete`),variant:`danger`})&&(P.mutate({id:t.id}),o.mode===`edit`&&o.id===t.id&&ue())}async function me(t){let n=await j({title:e(`admin.system.users.resetPassword`,`Reset password`),message:e(`admin.system.users.setANewPasswordFor`,`Set a new password for "{{username}}".`,{username:t.username}),label:e(`admin.system.users.newPassword`,`New password`),inputType:`password`,placeholder:e(`admin.system.users.atLeast8Characters`,`At least 8 characters`),confirmLabel:e(`admin.system.users.continue`,`Continue`),validate:e=>e.length<Fr?J.t(`admin.system.users.passwordTooShort`,{min:Fr}):null});n===null||n.length===0||await ee({title:e(`admin.system.users.resetPassword`,`Reset password`),message:e(`admin.system.users.resetThePasswordForThey`,`Reset the password for "{{username}}"? They will need to use the new password on their next login.`,{username:t.username}),confirmLabel:e(`common.reset`,`Reset`)})&&I.mutate({id:t.id,newPassword:n})}function H(e,t){t!==e.isAdmin&&F.mutate({id:e.id,isAdmin:t})}async function he(){if(h!==null){b(null);try{if(h.id===void 0){let e=h.username.trim();if(e===``||h.password.length<Fr)return;await N.mutateAsync({username:e,password:h.password,isAdmin:h.isAdmin})}else await F.mutateAsync({id:h.id,isAdmin:h.isAdmin});M(),ue()}catch(e){b(Rr(e))}}}function ge(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}let _e=N.isPending||F.isPending,ye=h!==null&&h.id===void 0&&h.username.trim()!==``&&h.password.length>=Fr,be=h!==null&&h.id!==void 0,xe=_e||(h?.id===void 0?!ye:!be),Ce=e=>P.isPending&&P.variables?.id===e.id||F.isPending&&F.variables?.id===e.id||I.isPending&&I.variables?.id===e.id,we=[{key:`username`,header:e(`admin.system.users.username`,`Username`),sortValue:e=>e.username,render:e=>d(`span`,{className:`font-medium text-foreground`,"data-testid":`user-open-${e.id}`,children:e.username})},{key:`isAdmin`,header:e(`admin.system.users.admin`,`Admin`),nowrap:!0,sortValue:e=>+!!e.isAdmin,render:t=>d(`span`,{onClick:e=>e.stopPropagation(),children:a(`label`,{className:`inline-flex items-center gap-1.5 text-xs cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:t.isAdmin,onChange:e=>H(t,e.target.checked),disabled:Ce(t),className:`rounded border-border focus:ring-primary disabled:opacity-50`}),d(`span`,{className:t.isAdmin?`text-primary font-medium`:`text-foreground-subtle`,children:t.isAdmin?e(`admin.system.users.admin`,`Admin`):e(`admin.system.users.regular`,`Regular`)})]})})},{key:`scopes`,header:e(`admin.system.users.access`,`Access`),render:t=>t.isAdmin?d(`span`,{className:`text-[10px] italic text-foreground-subtle`,children:e(`admin.system.users.everythingAdmin`,`everything (admin)`)}):d(`span`,{onClick:e=>e.stopPropagation(),children:a(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>R(t),title:e(`admin.system.users.configureAccess`,`Configure access`),children:[d(te,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),d(Br,{scopes:ie(t.scopes??[])})]})})},{key:`createdAt`,header:e(`admin.system.users.created`,`Created`),nowrap:!0,sortValue:e=>e.createdAt,render:e=>d(`span`,{className:`text-foreground-subtle`,children:ge(e.createdAt)})},{key:`actions`,header:e(`admin.system.users.actions`,`Actions`),align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:t=>{let n=Ce(t),r=t.id!==i?.id&&t.totpEnabled;return a(`div`,{className:`flex items-center justify-end gap-1`,onClick:e=>e.stopPropagation(),children:[a(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>u(t.id),disabled:n,title:e(`admin.system.users.editUser`,`Edit user`),children:[d(m,{className:`h-3 w-3`}),e(`common.edit`,`Edit`)]}),r&&a(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>re(t),disabled:n,title:e(`admin.system.users.removeTwoFactorAuthentication`,`Remove two-factor authentication`),children:[d(f,{className:`h-3 w-3`}),e(`admin.system.users.remove2fa`,`Remove 2FA`)]}),a(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>oe(t),disabled:n,title:e(`admin.system.users.linkedSignInAccounts`,`Linked sign-in accounts`),children:[d(D,{className:`h-3 w-3`}),e(`admin.system.users.signInLinks`,`Sign-in links`)]}),a(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>ce(t),disabled:n,title:e(`admin.system.users.activeSessions`,`Active sessions`),children:[d(fe,{className:`h-3 w-3`}),e(`admin.system.users.sessions`,`Sessions`)]}),a(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void me(t),disabled:n,title:e(`admin.system.users.resetPassword`,`Reset password`),children:[d(le,{className:`h-3 w-3`}),e(`admin.system.users.resetPassword`,`Reset password`)]}),a(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void pe(t),disabled:n,title:e(`admin.system.users.deleteUser`,`Delete user`),className:`text-danger hover:bg-danger/10`,children:[n?d(A,{className:`h-3 w-3 animate-spin`}):d(g,{className:`h-3 w-3`}),e(`common.delete`,`Delete`)]})]})}}];return a(Et,{embedded:!0,icon:y,title:e(`admin.system.users.users`,`Users`),subtitle:e(`admin.system.users.hubAccountsAdminFlagAccess`,`Hub accounts, admin flag, access scopes, sessions and sign-in links.`),actions:a(q,{size:`sm`,type:`button`,onClick:()=>{b(null),l()},children:[d(E,{className:`h-3.5 w-3.5`}),e(`admin.system.users.createUser`,`Create User`)]}),children:[T&&d(G,{title:e(`admin.system.users.couldNotLoadUsers`,`Could not load users`),message:Rr(O),onRetry:()=>void k()}),w&&a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),e(`common.loading`,`Loading…`)]}),!w&&!T&&B.length===0&&d(et,{icon:y,title:e(`admin.system.users.noUsersYet`,`No users yet`),description:e(`admin.system.users.createAUserToGrant`,`Create a user to grant hub access.`)}),!w&&!T&&B.length>0&&d(Ie,{columns:we,rows:B,rowKey:e=>e.id,minWidthPx:560,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>u(e.id)}),d(Ne,{open:de,onClose:ue,title:h?.id===void 0?e(`admin.system.users.createUser`,`Create User`):e(`admin.system.users.edit`,`Edit {{value1}}`,{value1:h.username||`user`}),icon:y,error:v,testId:`user-form-dialog`,footer:d(q,{size:`sm`,type:`button`,disabled:xe,onClick:()=>void he(),children:_e?a(s,{children:[d(A,{className:`h-3.5 w-3.5 animate-spin`}),e(`admin.system.users.saving`,`Saving…`)]}):h?.id===void 0?e(`admin.system.users.create`,`Create`):e(`common.save`,`Save`)}),children:h!==null&&a(`div`,{className:`space-y-3`,children:[d(ct,{label:e(`admin.system.users.username`,`Username`),required:h.id===void 0,children:d(Se,{value:h.username,onChange:e=>_({...h,username:e.target.value}),placeholder:`john`,autoFocus:h.id===void 0,disabled:h.id!==void 0,"data-testid":`user-form-username`})}),h.id===void 0&&d(ct,{label:e(`admin.system.users.password`,`Password`),required:!0,description:e(`admin.system.users.atLeastCharacters`,`At least {{value1}} characters.`,{value1:String(Fr)}),children:d(qe,{value:h.password,onValueChange:e=>_({...h,password:e}),shown:x,onToggleShown:()=>S(e=>!e),placeholder:`••••••••`,"data-testid":`user-form-password`})}),d(ct,{label:e(`admin.system.users.admin`,`Admin`),description:e(`admin.system.users.unrestrictedAccessToEveryCapability`,`Unrestricted access to every capability and device.`),children:a(`label`,{className:`inline-flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:h.isAdmin,onChange:e=>_({...h,isAdmin:e.target.checked}),className:`rounded border-border focus:ring-primary`,"data-testid":`user-form-admin`}),d(`span`,{children:e(`admin.system.users.admin`,`Admin`)})]})}),h.id!==void 0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,children:e(`admin.system.users.toChangeThePasswordUse`,`To change the password, use Reset password on the user's row. Access scopes are configured from the Access column.`)})]})}),z&&d(Or,{userId:z.id,username:z.username,onClose:()=>re(null)}),ae&&d(Dr,{userId:ae.id,username:ae.username,onClose:()=>oe(null)}),se&&d(kr,{userId:se.id,username:se.username,onClose:()=>ce(null)}),L&&d(Vr,{user:L,onClose:()=>R(null),onSubmit:e=>ne.mutate({userId:L.id,scopes:e}),submitting:ne.isPending})]})}function Br({scopes:e}){let{t}=Y(),n=N();if(e.length===0)return d(`span`,{className:`font-medium text-warning`,children:t(`admin.system.users.noAccess`,`No access`)});let r=L(e);return r===null?d(`span`,{className:`text-foreground-subtle`,children:t(`users.customGrants`,{count:e.length})}):a(`span`,{className:`text-foreground-subtle`,children:[d(`span`,{className:`font-medium text-foreground`,children:R(r.roleId).label}),` ·`,` `,ut(r.selector,n)]})}function Vr(e){let{user:t}=_t(),n=t?.isAdmin===!0;return d(Pr,{...e,callerScopes:n?null:t?.scopes??[]})}e();var Hr={"api-keys":$.tokens,"linked-sessions":$.linkedApps},Ur=`certificates`;function Wr(e){return a(q,{size:`sm`,type:`button`,"data-testid":`certificates-pair-device`,onClick:e,children:[d(f,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),J.t(`systemPage.identity.pairADevice`,`Pair a device`)]})}function Gr(){let{t:e}=Y(),[t]=wt(),n=En(),[i,a]=r(!1),o=Hr[t.get(`tab`)??``];if(o!==void 0)return d(mt,{to:Ct(`access`,{integration:o}),replace:!0});let s=gt(`/system/identity`,{t:e,isAdmin:!0})??{icon:M,title:e(`system.identity`,`Identity & Access`)},c=t.get(`tab`)??`users`,l=t.get(`integration`),u=c===yt.access.tab?Tn(l,n.requestCreate):c===`certificates`?Wr(()=>a(!0)):void 0;return d(Tt,{icon:s.icon,title:s.title,defaultSection:`users`,sectionsLabel:`${s.title} sections`,actions:u,sections:[{id:`users`,label:e(`systemPage.identity.users`,`Users`),content:d(zr,{})},{id:yt.access.tab,label:e(`systemPage.identity.tokensSessions`,`Tokens & sessions`),content:d(wn,{createRequested:n.createRequested,onCreateConsumed:n.clearCreate}),ownedParams:St.concat([Rt.token,Rt.scoped,Rt.admin])},{id:Ur,label:e(`systemPage.identity.certificates`,`Certificates`),content:d(Er,{pairOpen:i,onPairClose:()=>a(!1)})},{id:yt.authentication.tab,label:e(`systemPage.identity.authentication`,`Authentication`),content:d(zn,{}),ownedParams:St}]})}export{Gr as IdentityPage};
|