@camstack/addon-admin-ui 1.2.458 → 1.2.459
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-arpH1jD8.js → AddonAssetIcon-BJEJ1k08.js} +1 -1
- package/dist/assets/Addons-DHanUVT2.js +4 -0
- package/dist/assets/{AdminPage-BjrFg6FM.js → AdminPage-COkr2pSl.js} +1 -1
- package/dist/assets/{AdminSectionedPage-DxQ2pH4Y.js → AdminSectionedPage-DacqZ038.js} +1 -1
- package/dist/assets/AiProfiles-00eup-gf.js +3 -0
- package/dist/assets/{BrokerForm-DEL7JPI4.js → BrokerForm-BZXEvLK0.js} +1 -1
- package/dist/assets/Build-C-5lgbq3.js +40 -0
- package/dist/assets/{Calendars-Cw-Q6N0f.js → Calendars-BkpP1D2U.js} +1 -1
- package/dist/assets/{Cluster-CUox6xE3.js → Cluster-9x8btsN4.js} +1 -1
- package/dist/assets/CompositionEditor-r0DF2l8O.js +1 -0
- package/dist/assets/{CompositionEditorPage-DnCUuqEl.js → CompositionEditorPage-ZgZUzIco.js} +1 -1
- package/dist/assets/Data-CRUK3PE2.js +2 -0
- package/dist/assets/DeviceDetail-B-WDYuF4.js +2 -0
- package/dist/assets/{DeviceDoActionFields-BRZweXYw.js → DeviceDoActionFields-B6h8uYuA.js} +1 -1
- package/dist/assets/{Devices-BtjFXXD8.js → Devices--JO66DyO.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-DmA2dyRs.js → EmbedPlayerPage-yV8Ghwca.js} +1 -1
- package/dist/assets/{History-Csgt6RnT.js → History-BwlSzH55.js} +1 -1
- package/dist/assets/Identity-BWhaEMdv.js +1 -0
- package/dist/assets/IntegrationDetail-CQTl55bJ.js +1 -0
- package/dist/assets/IntegrationHub-1t9XtENg.js +1 -0
- package/dist/assets/Integrations-BsHioywX.js +1 -0
- package/dist/assets/Integrations-DAZG8yCP.js +1 -0
- package/dist/assets/{Library-CsCzamEb.js → Library-I8I-H4B0.js} +1 -1
- package/dist/assets/Locations-DpID1z6R.js +3 -0
- package/dist/assets/{Logs-BfeyENDk.js → Logs--6yOXDdG.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-tNwtlAOM.js → MaskShapeCanvas-BFRANocL.js} +1 -1
- package/dist/assets/{MotionZonesSettings-C8j_gawX.js → MotionZonesSettings-DAR1lGRc.js} +1 -1
- package/dist/assets/MyAccess-BlPaAQNJ.js +2 -0
- package/dist/assets/{Network-C_cYS-fR.js → Network-68PrEWb3.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-BgUAqnzo.js → NodeAddonsSettingsPanel-BU9D0unj.js} +1 -1
- package/dist/assets/Notifications-BHMdjbhb.js +1 -0
- package/dist/assets/Pipeline-BntRM_Gg.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-Dpr5kjzL.js → PrivacyMaskSettings-CFjaiNPa.js} +1 -1
- package/dist/assets/Recordings-B0PFCiE6.js +1 -0
- package/dist/assets/{ScanNetworkModal-CHmBk64D.js → ScanNetworkModal-KVlo34E_.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-_NtH_gGA.js → SceneMonitorEditor-CtObZ92A.js} +1 -1
- package/dist/assets/SessionsList-BqQzJQzH.js +2 -0
- package/dist/assets/{Showroom-CpcQ_noP.js → Showroom-BpbWCBms.js} +1 -1
- package/dist/assets/System-Bi2UJjp7.js +1 -0
- package/dist/assets/{Terminal-B2_h39vc.js → Terminal-CfhgVSfX.js} +5 -5
- package/dist/assets/{Viewer-BY7zR9zQ.js → Viewer-DOy7SpD5.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BByWRJ1W.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-FGBBI8DM.js} +1 -1
- package/dist/assets/{addon-icons-context-C4CUqZFb.js → addon-icons-context-zSgVMYOT.js} +1 -1
- package/dist/assets/{archive-D-IttKbd.js → archive-CCdQLR92.js} +1 -1
- package/dist/assets/{authed-media-BH09w7mx.js → authed-media-BnRlGkoA.js} +1 -1
- package/dist/assets/{bell-off-esSw14-4.js → bell-off-CqtliYfE.js} +1 -1
- package/dist/assets/{board-model-CzpY9jow.js → board-model-DcXa88Au.js} +1 -1
- package/dist/assets/{boxes-DLm9pV7A.js → boxes-DQn7OALq.js} +1 -1
- package/dist/assets/circle-slash-BqXxDfpK.js +1 -0
- package/dist/assets/client-DUabg_ow.js +358 -0
- package/dist/assets/{cloud-upload-CmlXZ47L.js → cloud-upload-Ds0DBFF4.js} +1 -1
- package/dist/assets/crop-Cfvx74Ee.js +1 -0
- package/dist/assets/{device-integration-icon-BBk1BbPA.js → device-integration-icon-Bb8AOXEF.js} +1 -1
- package/dist/assets/device-picker-model-BtgtDdnV.js +1 -0
- package/dist/assets/dist-BgJn1_Ws.js +358 -0
- package/dist/assets/{dist-DyazYmMR.js → dist-DGtsAF0e.js} +1 -1
- package/dist/assets/{eraser-plwpovOj.js → eraser-CBhjXP5B.js} +1 -1
- package/dist/assets/{hard-drive-download-B8wIgrJR.js → hard-drive-download-Bbqt0BU7.js} +1 -1
- package/dist/assets/{hostInit-u9GmPoX9.js → hostInit-DYH0aGPp.js} +1 -1
- package/dist/assets/i18n-aZ2iCAl5.js +1 -0
- package/dist/assets/{icons-Dkn5asvl.js → icons-CIAj8beD.js} +1 -1
- package/dist/assets/{index-DPvkuJxO.js → index-DKfAHLRf.js} +3 -3
- package/dist/assets/{index-BGRimCPP.css → index-I9On1g0c.css} +1 -1
- package/dist/assets/{key-CA18pL-8.js → key-BrmsyfQ2.js} +1 -1
- package/dist/assets/{key-round-C7R-scbw.js → key-round-DupHhW0i.js} +1 -1
- package/dist/assets/{layers-BxsydRGi.js → layers-jV4_DPMS.js} +1 -1
- package/dist/assets/{linked-devices-model-BLcQ9yAI.js → linked-devices-model-Wflvd004.js} +1 -1
- package/dist/assets/{list-ordered-DnwKxGIw.js → list-ordered-DOEvj-y0.js} +1 -1
- package/dist/assets/{location-owned-usage-CuK_nCoP.js → location-owned-usage-D3Zl9d5o.js} +1 -1
- package/dist/assets/{log-in-Bf5RUTf4.js → log-in-CcPfrqgr.js} +1 -1
- package/dist/assets/{memory-stick-B59QUWgK.js → memory-stick-q_w6rp-t.js} +1 -1
- package/dist/assets/{message-square-plus-Ckmg1y08.js → message-square-plus-9n6eNHhb.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-547cfa14.js → mf-entry-bootstrap-0-44ebd2c3.js} +2 -2
- package/dist/assets/{mic-off-CsCgSoDy.js → mic-off-D8Z3zvJC.js} +1 -1
- package/dist/assets/{monitor-off-BwsLAWve.js → monitor-off-ChiwdYm2.js} +1 -1
- package/dist/assets/{monitor-smartphone-G--2aBuy.js → monitor-smartphone-5A2YPeJg.js} +1 -1
- package/dist/assets/mount-BtgtDdnV.js +1 -0
- package/dist/assets/notification-schedule-field-BGziM8ff.js +1 -0
- package/dist/assets/{player-overlays-BTnXgs6l.js → player-overlays-B2uKzPiF.js} +1 -1
- package/dist/assets/{recycle-f9jOE7g7.js → recycle-lkNup4GK.js} +1 -1
- package/dist/assets/remoteEntry-DwoMnkvg.js +1 -0
- package/dist/assets/{scan-eye-CC4mTfUp.js → scan-eye-CJpdZenM.js} +1 -1
- package/dist/assets/{scissors-BNEM1Ztl.js → scissors-v8FUfmH0.js} +1 -1
- package/dist/assets/{search-x-3m2MRtEu.js → search-x-CJx173bU.js} +1 -1
- package/dist/assets/{send-D6irwubo.js → send-XYAWcADm.js} +1 -1
- package/dist/assets/{settings-2-B_7_TLiY.js → settings-2-Bgu4fxha.js} +1 -1
- package/dist/assets/{speaker-CBOD08Ii.js → speaker-ofUzLdUT.js} +1 -1
- package/dist/assets/src-N0x0aMoc.js +67 -0
- package/dist/assets/step-inspector-model-C7JCmVfz.js +1 -0
- package/dist/assets/{timer-reset-BmRk3MOl.js → timer-reset-D-5iU9l-.js} +1 -1
- package/dist/assets/{ungroup-CtlTayH1.js → ungroup-DD3pb37b.js} +1 -1
- package/dist/assets/{unlink-8-ZUzI25.js → unlink-xgj0DHXA.js} +1 -1
- package/dist/assets/{usb-DRY8JHaQ.js → usb-COQJ7FVk.js} +1 -1
- package/dist/assets/{use-scenes-feed-Bnlc0umC.js → use-scenes-feed-Cr8WJGCC.js} +1 -1
- package/dist/assets/{use-stationary-objects-CSaIphB2.js → use-stationary-objects-kiH5Q2gT.js} +1 -1
- package/dist/assets/useEventInvalidation-BtgtDdnV.js +1 -0
- package/dist/assets/{useNodeUrlSelection-UerjxtpH.js → useNodeUrlSelection-DpqDFKVD.js} +1 -1
- package/dist/assets/user-round-Dy1LJO0f.js +1 -0
- package/dist/assets/{user-x-DWSR4aIw.js → user-x-CBuwxTd8.js} +1 -1
- package/dist/assets/{video-BRH0aO3l.js → video-CCbgIO_h.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-VnpYmyAv.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CxTajz7L.js} +2 -2
- package/dist/index.html +11 -11
- package/dist/server/addon.js +93 -8
- package/package.json +1 -1
- package/dist/assets/Addons-HbtgQft-.js +0 -4
- package/dist/assets/AiProfiles-BdzPXclT.js +0 -3
- package/dist/assets/Build-DNm-26dy.js +0 -40
- package/dist/assets/ClusterStepModel-BSI39thg.js +0 -1
- package/dist/assets/CompositionEditor-B3e76JM9.js +0 -1
- package/dist/assets/Data-IEAE-8BN.js +0 -2
- package/dist/assets/DeviceDetail-MmjrNM7o.js +0 -2
- package/dist/assets/Identity-DmdFLJiQ.js +0 -1
- package/dist/assets/IntegrationDetail-DsIRBJ-F.js +0 -1
- package/dist/assets/IntegrationHub-DTFQyFFN.js +0 -1
- package/dist/assets/Integrations-3Dm1BWSC.js +0 -1
- package/dist/assets/Integrations-CPsVHs77.js +0 -1
- package/dist/assets/Locations-BmYKJdte.js +0 -3
- package/dist/assets/MyAccess-CQtGUeMl.js +0 -2
- package/dist/assets/Notifications-Bp7cRi1y.js +0 -1
- package/dist/assets/Recordings-DEsoK17t.js +0 -1
- package/dist/assets/SessionsList-CRE59_h3.js +0 -2
- package/dist/assets/System-Cmlqjd1R.js +0 -1
- package/dist/assets/circle-slash-DUiMT2dc.js +0 -1
- package/dist/assets/client-BI85kkig.js +0 -358
- package/dist/assets/crop-DFOEm7GN.js +0 -1
- package/dist/assets/device-picker-model-B-2vVHUA.js +0 -1
- package/dist/assets/dist-DmOQydcE.js +0 -358
- package/dist/assets/i18n-DCSomJiP.js +0 -1
- package/dist/assets/mount-B-2vVHUA.js +0 -1
- package/dist/assets/notification-schedule-field-C6qs47JN.js +0 -1
- package/dist/assets/remoteEntry-BA9oATqv.js +0 -1
- package/dist/assets/src-B_ik3sNc.js +0 -67
- package/dist/assets/useEventInvalidation-B-2vVHUA.js +0 -1
- package/dist/assets/user-round-D65mcWwX.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 A,T as j,V as M,Vi as N,W as P,Xn as F,Xr as I,Z as ee,Zt as L,_t as R,bn as te,cr as ne,dn as re,dt as ie,en as z,ht as B,li as ae,lr as oe,or as se,ot as V,pi as ce,pn as H,r as le,sa as ue,t as de,ta as fe,vn as pe,xn as me,yn as he,z as U,zn as ge,zr as _e}from"./player-overlays-BTnXgs6l.js";import{$n as ve,Ar as ye,Bi as be,Dn as xe,Fn as Se,Fr as Ce,Jr as we,Kr as Te,Tn as Ee,Vr as W,Xn as De,Yr as G,_n as Oe,_r as ke,ai as Ae,ci as je,er as Me,gn as Ne,hn as Pe,li as K,m as Fe,oi as Ie,p as Le,tr as Re,ui as q,vn as ze,wn as Be,yn as Ve,zi as He,zr as Ue}from"./client-BI85kkig.js";import{t as We}from"./archive-D-IttKbd.js";import{i as Ge,n as Ke,r as qe,t as Je}from"./scan-eye-CC4mTfUp.js";import{t as Ye}from"./bell-off-esSw14-4.js";import{t as Xe}from"./boxes-DLm9pV7A.js";import{n as Ze}from"./video-BRH0aO3l.js";import{t as Qe}from"./circle-slash-DUiMT2dc.js";import{t as $e}from"./layers-BxsydRGi.js";import{$ as et,$n as tt,$u as nt,An as rt,Ar as it,Bc as at,Br as ot,Bu as st,Ca as ct,Dn as lt,Dt as ut,Ec as dt,F as ft,Fn as pt,Ft as mt,G as ht,Go as gt,Gt as _t,Gu as vt,Hn as yt,Ht as bt,Ic as xt,In as St,It as Ct,Iu as wt,Ja as Tt,Jr as Et,Ju as Dt,K as Ot,Kt as kt,Lc as At,Ln as jt,Lu as Mt,Mn as Nt,Mt as Pt,N as Ft,Ns as It,Nt as Lt,Nu as Rt,Oi as zt,On as Bt,Ou as Vt,Pa as Ht,Pu as Ut,Qa as Wt,Qn as Gt,Ra as Kt,Rc as qt,Rn as Jt,Rr as Yt,Rt as Xt,Ru as Zt,Sa as Qt,So as $t,Tn as en,To as tn,Tr as nn,Ua as rn,Us as an,Ut as on,Vr as sn,Vs as cn,Vt as ln,Wa as un,Xa as dn,Xo as fn,Xt as pn,Y as mn,Yc as hn,Yo as gn,Yt as _n,Za as vn,Zn as yn,Zo as bn,Zt as xn,_c as Sn,_r as Cn,a as wn,aa as Tn,an as En,ar as Dn,ba as On,br as kn,bt as An,c as jn,cr as Mn,da as Nn,er as Pn,et as Fn,fi as In,fn as Ln,fo as Rn,fr as zn,ga as Bn,gn as Vn,gt as Hn,hc as Un,hr as J,i as Wn,ir as Gn,jn as Kn,jt as qn,kn as Jn,kt as Yn,l as Xn,lr as Zn,mc as Qn,mn as $n,mr as er,nr as tr,nt as nr,o as rr,oa as ir,oo as ar,or,pc as sr,qa as cr,qt as lr,qu as ur,r as dr,ro as fr,rr as pr,s as mr,tt as hr,ua as gr,ul as _r,vr,wa as yr,wn as br,xc as xr,ya as Sr,yn as Cr,yo as wr,yr as Tr,yt as Er,zc as Dr,zt as Or}from"./src-B_ik3sNc.js";import{t as Y}from"./i18n-DCSomJiP.js";import{t as X}from"./useTranslation-D3Is_4B6.js";import"./mount-B-2vVHUA.js";import{A as kr,F as Ar,H as jr,I as Mr,J as Nr,K as Pr,M as Fr,N as Ir,P as Lr,Q as Rr,U as zr,V as Br,W as Vr,X as Hr,Y as Ur,Z as Wr,et as Gr,g as Kr,h as qr,j as Jr,nt as Yr,p as Xr,q as Zr,tt as Qr}from"./index-DPvkuJxO.js";import{C as $r,D as ei,E as ti,S as ni,_ as ri,a as ii,b as ai,c as oi,d as si,f as ci,g as li,h as ui,i as di,l as fi,m as pi,n as mi,o as hi,p as gi,r as _i,s as vi,t as yi,u as bi,v as xi,x as Si,y as Ci}from"./CompositionEditor-B3e76JM9.js";import{_ as wi,a as Ti,b as Ei,c as Di,d as Oi,f as ki,g as Ai,h as ji,i as Mi,l as Ni,m as Pi,n as Fi,o as Ii,p as Li,s as Ri,t as zi,u as Bi,v as Vi,x as Hi,y as Ui}from"./ClusterStepModel-BSI39thg.js";import"./useEventInvalidation-B-2vVHUA.js";import{t as Wi}from"./use-stationary-objects-CSaIphB2.js";import{a as Gi,c as Ki,d as qi,f as Ji,i as Yi,l as Xi,n as Zi,o as Qi,p as $i,r as ea,s as ta,t as na,u as ra}from"./linked-devices-model-BLcQ9yAI.js";import{t as ia}from"./authed-media-BH09w7mx.js";e();function aa(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 oa(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(aa).filter(e=>e!==null);return n.length===0?null:n}var sa=[[/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 ca(e){for(let[t,n]of sa)if(t.test(e))return n;return`generic`}function la(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(Y.t(`helpers.cameraSwitchRows.off`,{list:r(t)})),n.length>0&&i.push(Y.t(`helpers.cameraSwitchRows.unknown`,{list:r(n)})),{offIds:t,unknownIds:n,summary:i.length===0?Y.t(`helpers.cameraSwitchRows.allOn`):i.join(` · `)}}var ua={stream:me,detection:Je,privacy:_e,microphone:F,speaker:A,listening:Ke,archive:We,recording:qe,notifications:T,generic:z};function da({deviceId:e}){let{t}=X(),n=c(),o=Number.isFinite(e),[s,l]=r(null),[u,f]=r(!1),p=Sn({deviceId:e},{enabled:o});dr([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let m=oa(p.data),h=at({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 _=la(m),v=e=>s?.id===e.id?s.message:null;return a(wt,{open:u,onOpenChange:f,children:[a(Zt,{"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(Mt,{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(fa,{row:e,failure:v(e),onToggle:()=>g(e)})},e.id))})]})]})}function fa({row:e,failure:t,onToggle:n}){let{t:r}=X(),i=ua[ca(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 pa({deviceId:e}){let t=Xt(V().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 ma({parentDeviceId:e}){let{t}=X(),n=Gr(),r=V(),{data:i,isLoading:o,isError:s}=Vr(e),{data:c}=cr({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=Lt(c?.stableId??``,l,c?.childLayout),f=u.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>d(qn,{trpc:r.trpcClient,device:{...t,name:Or(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(Pt,{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(Pt,{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 ha({deviceId:e}){let t=V(),{data:n,isLoading:r}=zr(e),{data:i,isLoading:a}=Vr(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(ln,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}e();function ga({dev:e,busy:t,setBusy:n}){let{t:i}=X(),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(fe,{className:`h-3 w-3`}),d(`span`,{children:m})]})}e();function Z({deviceId:e,deviceType:t,features:n}){let i=V(),o=_t(t)?.HeroCard??kt,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(on,{lastChangedAt:p})}):null,d(o,{trpc:i.trpcClient,deviceId:e,features:n}),d(`div`,{className:`flex justify-center`,children:d(ga,{dev:s,busy:l,setBusy:u})})]})}function _a({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(lr,{trpc:V().trpcClient,deviceId:e,features:t})})}function va({deviceId:e,features:t}){return d(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:d(kt,{trpc:V().trpcClient,deviceId:e,features:t})})}function ya(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function ba(e){if(!e)return null;let t=ya(e.data);return t===null?e.eventType:Y.t(`helpers.eventEmitterFormat.buttonHeadline`,{channel:String(t),eventType:e.eventType})}var xa=1e3,Sa=60*xa,Ca=60*Sa,wa=24*Ca;function Ta(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<xa?Y.t(`helpers.relativeTime.justNow`):n<Sa?Y.t(`helpers.relativeTime.secondsAgo`,{count:Math.floor(n/xa)}):n<Ca?Y.t(`helpers.relativeTime.minutesAgo`,{count:Math.floor(n/Sa)}):n<wa?Y.t(`helpers.relativeTime.hoursAgo`,{count:Math.floor(n/Ca)}):Y.t(`helpers.relativeTime.daysAgo`,{count:Math.floor(n/wa)})}e();var Ea=1500,Da=15e3,Oa=1e3;function ka({deviceId:e}){let{t:n}=X(),i=C(V().trpcClient,e)?.state.eventEmitter,o=b(i);t(()=>{if(!i)return;i.refresh();let e=setInterval(()=>{i.refresh()},Da);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)},Ea);return()=>{clearTimeout(t)}},[c]);let[h,g]=r(()=>Date.now());t(()=>{let e=setInterval(()=>{g(Date.now())},Oa);return()=>{clearInterval(e)}},[]);let _=ba(s),y=o?.eventTypes??[],x=o?.eventCountSinceStart??0,S=o!==void 0,w=ya(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?Ta(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 Aa({deviceName:e,deviceType:t,provider:n,isOnline:r,features:i}){let{t:o}=X();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(Ur,{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(nr,{status:r?`online`:`offline`}),i.length>0&&d(Hr,{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 ja({deviceId:e}){let{t}=X(),r=c(),i=Sr({deviceId:e},{refetchInterval:1e4,retry:!1}),o=On({onSuccess:()=>{r.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),r.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),s=n(()=>Ma(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(Na,{label:t(`hero.hubHero.discovered`,`Discovered`),value:s.total,icon:d(ge,{className:`h-3.5 w-3.5`})}),d(Na,{label:t(`hero.hubHero.adopted`,`Adopted`),value:s.adopted,accent:`success`}),d(Na,{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(te,{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(Pa,{icon:d(B,{className:`h-3 w-3 text-emerald-500`}),label:t(`hero.hubHero.online`,`{{online}} online`,{online:s.online})}),d(Pa,{icon:d(w,{className:`h-3 w-3 text-amber-500`}),label:t(`hero.hubHero.sleeping`,`{{sleeping}} sleeping`,{sleeping:s.sleeping})}),d(Pa,{icon:d(R,{className:`h-3 w-3 text-destructive`}),label:t(`hero.hubHero.offline`,`{{offline}} offline`,{offline:s.offline})}),s.unknown>0?d(Pa,{icon:d(ae,{className:`h-3 w-3 text-foreground-subtle`}),label:t(`hero.hubHero.unknown`,`{{unknown}} unknown`,{unknown:s.unknown})}):null]})]})}function Ma(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 Na({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 Pa({icon:e,label:t}){return a(`span`,{className:`inline-flex items-center gap-1`,children:[e,d(`span`,{children:t})]})}var Fa={[q.Switch]:Z,[q.Siren]:Z,[q.Light]:Z,[q.Sensor]:Z,[q.Button]:Z,[q.Hub]:ja,[q.Cover]:_a,[q.Valve]:Z,[q.Humidifier]:Z,[q.WaterHeater]:Z,[q.Container]:ha,[q.Lock]:Z,[q.Fan]:Z,[q.Thermostat]:Z,[q.Climate]:Z,[q.MediaPlayer]:Z,[q.Control]:Z,[q.AlarmPanel]:Z,[q.EventEmitter]:ka,[q.Notifier]:va,[q.Script]:Z,[q.Automation]:Z,[q.Presence]:Z,[q.Update]:Z,[q.Vacuum]:Z,[q.LawnMower]:Z,[q.Weather]:Z,[q.Image]:Z,[q.PetFeeder]:Z,[q.Dishwasher]:Z};function Ia(e){return Fa[e]??Aa}function La(e){return d(Ia(e.deviceType),{...e})}function Ra({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(yn,{widgetId:t.widgetId,deviceId:t.deviceId});return d(`div`,{children:t.deviceId===e?n:d(nn,{deviceId:t.deviceId,children:n})},t.widgetId)})})}function za(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 Ba(e){let t=za(e),n=new Set(t.map(e=>e.widgetId)),r=e.child===void 0?[]:za(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 Va(e){return rr(V().trpcClient,e)}e();function Ha(e){let[n,a]=r(`idle`),[o,s]=r(null),c=l(null),u=l(null),d=l(null),f=l(!0),p=fn(),m=gn(),h=bn(),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 Ua=0;function Q(){return++Ua}function Wa(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function Ga(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 Ka(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 qa(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 Ja({scope:e,greeting:n,className:o}){let{t:s}=X(),c=V(),[f,p]=r(()=>{let t=[];return n&&t.push({id:Q(),kind:`info`,text:n}),t.push({id:Q(),kind:`info`,text:`scope: ${Wa(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:Q(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);p(e=>[...e,{id:Q(),kind:`error`,text:t}])}});function w(t){let n=t.trim();if(n){if(n===`clear`){p([{id:Q(),kind:`info`,text:`scope: ${Wa(e)}`}]),h(``);return}if(n===`help`){p(t=>[...t,{id:Q(),kind:`input`,text:`> ${n}`},...Ga(e).map(e=>({id:Q(),kind:`info`,text:e}))]),h(``);return}if(n===`context`){p(t=>[...t,{id:Q(),kind:`input`,text:`> ${n}`},...qa(e).map(e=>({id:Q(),kind:`info`,text:e}))]),h(``);return}if(n===`examples`){p(t=>[...t,{id:Q(),kind:`input`,text:`> ${n}`},...Ka(e).map(e=>({id:Q(),kind:`info`,text:e}))]),h(``);return}_(e=>[...e,n]),y(-1),p(e=>[...e,{id:Q(),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:Q(),kind:`info`,text:`scope: ${Wa(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 Ya(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 Xa({deviceId:e,intercomAvailable:t=!1}){let r=V(),i=typeof window<`u`?ee():``,a=Number.isFinite(e),o=Va(a?e:null),c=Wi(a?[e]:[]),l=n(()=>{if(!a)return;let e=[];for(let t of c.rows){let n=wn(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}=Ln(r.trpcClient,a?e:null),C=_(a?e:null,{width:to}),w=Ha(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=Zn(),A=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,j=Ya(k.request,A),M=O.length>0?d(s,{children:O.map(e=>d(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return d(ht,{serverUrl:i,createSession:p,sendAnswer:m,handleOffer:h,getIceServers:g,addIceCandidate:v,getIceCandidates:y,closeSession:b,getSessionState:x,applyDownlinkProbe:S,...j===null?{}:{...j,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:M,chromeless:!0,className:`h-full`})}function Za({deviceId:e,containerDeviceId:t}){let{t:n}=X();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full`,children:d(xn,{...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 Qa({deviceId:e}){let{t}=X();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(Ja,{scope:{type:`device`,deviceId:e},greeting:n,className:`h-full border-0 rounded-none`})}function $a({deviceId:e}){let{t}=X();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:d(pn,{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 eo({deviceId:e}){let{t}=X();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:d(_n,{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 to=960;function no(e){return new Set(e.filter(e=>{let t=e.nativeAddonId?.trim()??``;return t!==``&&t!==`composer`}).map(e=>e.capName))}function ro(e){return e.kind===`known`?null:e}function io(e,t){return e.composable.kind===`known`?e.composable.value.has(t)?{kind:`present`,mode:`add`}:{kind:`absent`}:e.composable}function ao(e){if(e.deviceType!==q.Camera)return{kind:`absent`};switch(e.cameraSensors){case`pending`:return{kind:`pending`};case`unknown`:return{kind:`unknown`,reason:Y.t(`helpers.assignmentAvailability.sensorsUnchecked`)};case`absent`:return{kind:`absent`};case`present`:return{kind:`present`,mode:`add`}}}function oo(e,t){if(e===`motion`)return ao(t);let n=ro(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`}:io(t,`doorbell`);case`battery`:return r.has(`battery`)?{kind:`present`,mode:`replace`}:io(t,`battery`);case`consumables`:return r.has(`consumables`)?{kind:`absent`}:io(t,`consumables`)}}function so({onAdvanced:e}){let{t}=X();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 co(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??Y.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:Y.t(`helpers.customizationRead.notAComposition`,{id:t.view.block.id})}:{kind:`present`,view:t.view,composition:n}}function lo(e){return e.kind===`present`?e.composition:null}function uo(e,t){let{hidden:n,...r}=e??{},i=t?{...r,hidden:!0}:r;return Object.keys(i).length===0?null:i}function fo(e){return typeof e.linkDeviceId==`number`}var po=new Set(Object.values(K));function mo(e){return po.has(e)}var ho={[q.Switch]:[K.Siren,K.Floodlight,K.Spotlight,K.PirSensor,K.Chime,K.Autotrack,K.Nightvision,K.PrivacyMask,K.BinaryHelper],[q.Light]:[K.Floodlight,K.Spotlight,K.Nightvision],[q.Siren]:[K.Siren],[q.Button]:[K.Doorbell],[q.Sensor]:[K.MotionSensor,K.ContactSensor,K.LeakSensor,K.SmokeSensor,K.COSensor,K.GasSensor,K.TamperSensor,K.VibrationSensor,K.ConnectivitySensor,K.SoundSensor,K.BinarySensor,K.TemperatureSensor,K.HumiditySensor,K.AmbientLightSensor,K.PressureSensor,K.WindSensor,K.RainSensor,K.UvSensor,K.SolarRadiationSensor,K.SoilMoistureSensor,K.PowerSensor,K.EnergySensor,K.VoltageSensor,K.CurrentSensor,K.AirQualitySensor,K.BatterySensor,K.NumericSensor,K.EnumSensor,K.DateTimeSensor,K.GenericSensor],[q.Control]:[K.NumericControl,K.SelectControl,K.TextControl,K.DateTimeControl],[q.Notifier]:[K.MobilePushNotifier,K.MessagingNotifier,K.EmailNotifier,K.GenericNotifier]};function go(e){for(let t of Object.values(q))if(t===e)return!0;return!1}function _o(e){return go(e)?ho[e]??[]:[]}function vo(e,t){let n=_o(t);return e==null||e===``||n.includes(e)?n:[...n,e]}e();function yo({device:e}){let{t}=X(),n=ue(),i=c(),[o,s]=r(null),l=()=>s(null),u={onSuccess:()=>{l(),i.invalidateQueries({queryKey:[[`deviceManager`]]})},onError:e=>s(e.message)},f=wr(),p=Rn(),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(Zr,{deviceId:e.id,initialName:e.name,label:t(`customize.identity.name`),layout:`stacked`,onError:s,onSaved:l,onCancel:l}),d(Pr,{deviceId:e.id,initialLocation:e.location,label:t(`customize.identity.room`),layout:`stacked`,onError:s,onSaved:l,onCancel:l}),d(Nr,{label:t(`customize.identity.hidden`),layout:`stacked`,value:d(Nt,{"aria-label":t(`deviceDisplay.hideFromLists`),checked:h,disabled:p.isPending,onChange:t=>p.mutate({deviceId:e.id,display:uo(e.display,t.target.checked)},u)})}),d(Nr,{label:t(`customize.identity.role`),layout:`stacked`,value:fo(e)?d(`span`,{children:bo(e.role,t(`customize.identity.noRole`),n)}):d(Vt,{"aria-label":t(`customize.identity.role`),value:e.role??``,disabled:f.isPending,options:[{value:``,label:t(`customize.identity.noRole`)},...vo(e.role,e.type).map(e=>({value:e,label:bo(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 bo(e,t,n){return e==null||e===``?t:mo(e)?vt(e,n).label:e}e();function xo(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function So({excludeDeviceIds:e,onSelect:t}){let{t:r}=X(),i=vn({projection:`slim`}),a=i.status===`success`?i.data:null,o=n(()=>{if(a===null)return[];let t=new Set(e);return oi(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(zn,{title:r(`customize.picker.devicesFailed`),message:i.error?.message??``});let l=e=>{let n=s.get(e);n!==void 0&&t(n)};return d(ft,{devices:c,listState:xo(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 Co({open:e,title:t,targetKind:n,excludeDeviceIds:i,confirmLabel:o,extra:c,extraComplete:l=!0,onConfirm:u,onClose:f}){let{t:p}=X(),[m,h]=r(null),[g,_]=r(null),v=()=>{h(null),_(null),f()};return d(Gt,{open:e,onOpenChange:e=>e?void 0:v(),children:a(Pn,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":t,children:[d(pr,{children:d(Gn,{children:t})}),d(tt,{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(So,{excludeDeviceIds:i,onSelect:h}):a(`p`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[m.name,d(J,{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(ii,{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(tr,{children:[d(J,{variant:`ghost`,onClick:v,children:p(`customize.assign.cancel`)}),d(J,{disabled:g===null||!l,onClick:()=>{g!==null&&(u(g),h(null),_(null))},children:o})]})]})})}function wo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function To(e,t){let n=vi(e,t);return n===void 0?{kind:`absent`}:{kind:`value`,value:n}}function Eo(e,t,n){return wo(t)?To(t,n):e.status===`error`?{kind:`unknown`,reason:e.error?.message??Y.t(`helpers.liveValue.unreadable`)}:e.status===`pending`||e.data===void 0?{kind:`pending`}:e.data===null?{kind:`absent`}:To(e.data,n)}function Do(e,t,n){let r=e?`active`:`muted`;return t.cap===`contact`&&t.path===`entryOpen`?{text:e?n.open:n.closed,tone:r}:Ie[t.cap]===t.path?{text:e?n.active:n.inactive,tone:r}:{text:String(e),tone:`normal`}}function Oo(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`?Do(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 ko=0;function Ao(e){let t=V(),n=tn({deviceId:e?.deviceId??ko,capName:e?.cap??``},{enabled:e!==null}),r=mr(t.trpcClient,e?.deviceId??null,e?.cap??``);return e===null?{kind:`absent`}:Eo({status:n.status,data:n.data,error:n.error===null||n.error===void 0?null:{message:n.error.message}},r,e.path)}var jo={muted:`text-foreground-subtle`,active:`text-success`,normal:`text-foreground`,warning:`text-warning`};function Mo({target:e}){let{t}=X(),n=Ao(e);return e===null?null:d(No,{display:Oo(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 No({display:e}){return d(`span`,{className:`text-xs ${jo[e.tone]}`,title:e.title,children:e.text})}function $({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:`${j} 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(Mo,{target:r}):i!==null&&d(No,{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(Ut,{icon:ie,variant:`ghost`,size:`sm`,"aria-label":l,disabled:u,onClick:c})})]})}function Po({id:e,...t}){return d($n,{headingId:`customize-${e}`,...t})}function Fo({id:e,icon:t,title:n,headerControl:r,addLabel:i,onAdd:o,addDisabled:c=!1,notices:l,suggestion:u,children:f}){let{t:p}=X(),m=o!==void 0&&i!==void 0;return a(Po,{id:e,icon:t,title:n,actions:a(s,{children:[r,m&&!c&&u!==void 0&&u.count>0&&a(J,{variant:`ghost`,size:`sm`,onClick:u.onOpen,children:[d(L,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),p(`customize.suggest.hint`,{count:u.count,location:u.location})]}),m&&d(J,{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 Io({availability:e}){let{t}=X();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 Lo(e,t){if(e.status===`error`)return{kind:`unknown`,reason:e.error?.message??Y.t(`helpers.customize.requestFailed`)};let n=e.data;return e.status===`pending`||n===void 0?{kind:`pending`}:{kind:`known`,value:t(n)}}function Ro(e,t){let n=nt.useQueries(n=>e.map(e=>n.deviceManager.listDeviceIdsByCaps({capNames:[e]},{enabled:t})));return ra(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 zo(e,t){let n=Yn(e,t);return n.kind===`resolved`?n.integration.name:null}function Bo(e){let t=vn({projection:`slim`},{enabled:e}),{data:r}=gt(void 0,{enabled:e}),i=t.error===null||t.error===void 0?null:t.error.message;return n(()=>Lo({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:zo(e,r),parentDeviceId:e.parentDeviceId,primaryChildEntityId:e.primaryChildEntityId??null,role:e.role??null}))),[t.status,t.data,i,r])}function Vo(e){let t=Bo(e.enabled),n=Ro(Ae,e.enabled);return t.kind===`unknown`?t:n.kind===`unknown`?n:t.kind===`pending`||n.kind===`pending`?{kind:`pending`}:{kind:`known`,value:$i({devices:t.value,capIndex:n.value,hostId:e.hostId,excludeCameras:e.excludeCameras,assigned:e.assigned,preferredCap:e.preferredCap})}}function Ho(){let{t:e}=X(),t=it();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 Uo(e){return e===null?null:ui(e,`replace`)?`replace`:ui(e,`add`)?`add`:null}function Wo({device:e,handle:t,availability:n,onAdvanced:i}){let{t:o}=X(),c=Ho(),[l,u]=r(!1),[f,p]=r(null),m=lo(t.state),h=Ci(m,`battery`),g=Uo(h),_=g===null?null:ri(h?.fields.percentage),v=Bo(_!==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=>G({addonId:e.addonId,stableId:e.stableId})===G(_.source))??null,S=_===null?``:x?.name??G(_.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=$r(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(Fo,{id:`battery`,icon:N,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(Io,{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($,{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($,{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($,{name:o(`customize.battery.otherFormula`),detail:null,meta:d(so,{onAdvanced:i}),value:{deviceId:e.id,cap:`battery`,path:`percentage`},removeLabel:``})]}),d(Co,{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:bi({percentage:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},mode:y});n===null?p(o(`customize.assign.pickUnusable`)):C(ni(m,t.target,n))},onClose:()=>u(!1)})]})}var Go=`consumables`,Ko=`items`,qo=Se.shape.items;function Jo(e){let t=e.split(`.`).pop()??e,n=t.replace(/Level$/,``);return n===``?t:n}function Yo(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function Xo(e,t){return e.caps.filter(e=>t.has(e.cap)&&e.cap!==`consumables`).flatMap(e=>e.fields.filter(e=>e.item!==!0&&Tr(e)).map(t=>({kind:`field`,key:Jo(t.path),cap:e.cap,path:t.path})))}function Zo(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=qo.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 Qo(e,t,n){if(e.kind!==`known`)return e;if(t.kind!==`known`)return t;let r=Xo(t.value,e.value);if(!e.value.has(`consumables`)||n===null)return{kind:`known`,value:r};let i=Zo(n);return i.kind===`known`?{kind:`known`,value:[...r,...i.value]}:i}function $o({deviceId:e,defaults:t}){return t.map(t=>t.kind===`field`?d(es,{deviceId:e,entry:t},`field:${t.cap}.${t.path}`):d(ns,{entry:t},`item:${t.key}`))}function es({deviceId:e,entry:t}){let{t:n}=X(),r=Ao({deviceId:e,cap:t.cap,path:t.path});return d($,{name:n(`customize.consumables.fields.${t.key}`,{defaultValue:Yo(t.key)}),detail:n(`customize.consumables.builtIn`),meta:n(`customize.assign.native`),value:null,readout:d(ts,{value:r}),removeLabel:``})}function ts({value:e}){switch(e.kind){case`pending`:return d(No,{display:{text:`…`,tone:`muted`}});case`unknown`:return d(No,{display:{text:`?`,title:e.reason,tone:`warning`}});case`absent`:return d(Cn,{level:null,size:`sm`});case`value`:return d(Cn,{level:kn(e.value),size:`sm`})}}function ns({entry:e}){let{t}=X(),{item:n}=e,r=n.level===null?n.status===`replace`?t(`uiLibrary.consumablesPanel.replace`):void 0:`${Math.round(n.level)} %`;return d($,{name:n.label,detail:t(`customize.consumables.builtIn`),meta:t(`customize.assign.native`),value:null,readout:d(Cn,{level:vr(n),label:r,size:`sm`}),removeLabel:``})}e();function rs(e,t){let n=e.source;if(n===null||t.kind!==`known`)return null;let r=G(n.source);return t.value.find(e=>G({addonId:e.addonId,stableId:e.stableId})===r)??null}function is(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):NaN;return Number.isFinite(t)?t:null}function as({device:e,handle:t,availability:n,onAdvanced:i,defaults:o}){let{t:c}=X(),l=Ho(),[u,f]=r(!1),[p,m]=r(``),[h,g]=r(`percent`),[_,v]=r(null),y=lo(t.state),b=Ci(y,`consumables`),x=ci(b),S=Bo(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=li(p),D=x.find(e=>e.key===E)??null,k=D!==null,A=p.trim()!==``&&E===``,j=async e=>{let n=await t.save(e);v(n.kind===`refused`?n.reason:null)},M=()=>{f(!1),m(``),g(`percent`)},N=async e=>{if(b===null||y===null)return;let n=xi(b,e.key),r=n===null?$r(y,`consumables`):ni(y,t.target,n);await l(c(`customize.consumables.removeWhat`,{name:e.label}),r===null)&&await j(r)},P=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(Rt,{"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(Vt,{"aria-label":c(`customize.consumables.unit`),value:h,options:fi.map(e=>({value:e,label:c(`customize.consumables.units.${e}`)})),onChange:e=>{let t=fi.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})}),A&&d(`p`,{role:`alert`,className:`basis-full text-xs text-warning`,children:c(`customize.consumables.keyless`)})]});return a(s,{children:[a(Fo,{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(Io,{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($o,{deviceId:e.id,defaults:C}),x.map(e=>{let n=e.source;if(e.unit===null||n===null)return d($,{name:e.label,detail:c(`customize.consumables.otherFormula`),meta:d(so,{onAdvanced:i}),value:null,removeLabel:``},e.key);let r=rs(e,S),a=r?.name??G(n.source);return d($,{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 N(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(Co,{open:u,title:c(`customize.consumables.pickTitle`),targetKind:`number`,excludeDeviceIds:[e.id],confirmLabel:c(`customize.assign.add`),extra:P,extraComplete:E!==``&&!k,onConfirm:e=>{let n=is(e.value);if(n!==null&&(n<0||h===`percent`&&n>100)){M(),v(c(`customize.consumables.outOfRange`,{value:n}));return}let r=si(b,{key:E,label:p,remaining:{source:e.ref,cap:e.cap,fieldPath:e.path,kind:e.kind},unit:h});M(),r===null?v(c(`customize.assign.pickUnusable`)):j(ni(y,t.target,r))},onClose:M})]})}function os(e,t){if(e.kind!==`known`||typeof t!=`string`||t.length===0)return null;let n=sn(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 ss(e,t,n){return ot(e,t?.ids??new Set,n)}function cs(e,t){return e?.containers.get(t)??null}function ls(e,t,n){return e.kind===`known`?ss(e.value,t,n).suggested.length:0}function us(e,t){let n=[t,e.detail].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function ds({location:e,devices:t,action:n,onPick:r,onPickAll:i}){let{t:o}=X();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:`${M} min-w-0 flex-1`,children:s}),i!==void 0&&t.length>1&&d(J,{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=us(e,e.container===null||e.name.includes(e.container)?null:o(`customize.suggest.in`,{container:e.container}));return a(`li`,{className:`${j} 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(J,{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 fs(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function ps(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 ms({open:e,title:i,selection:o,candidates:s,filters:c,room:l=null,confirmLabel:u,onConfirm:f,onClose:p}){let{t:m}=X(),[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`?qi(s.value,``,y):[],S=ss(b,l,e=>e.deviceId).suggested,C=ss(x,l,e=>e.deviceId).others,w=n(()=>ps(C),[C]),T=fs(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(Gt,{open:e,onOpenChange:e=>e?void 0:D(),children:a(Pn,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":i,children:[d(pr,{children:d(Gn,{children:i})}),a(tt,{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(ds,{location:l.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:cs(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(ft,{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(tr,{children:[d(J,{variant:`ghost`,onClick:D,children:m(`customize.picker.cancel`)}),d(J,{disabled:E.length===0,onClick:k,children:u(E.length)})]})]})})}function hs(e){if(e===null)return[];let t=pi(e);return gi(e).map(e=>{let n=G(e);return{key:n,ref:e,caps:t.filter(e=>G(e.source)===n).map(e=>e.cap)}})}function gs(e,t){let n=pi(e);if(n.length===0)return!1;let{enabled:r,...i}=e,{enabled:a,...o}=ze({camera:t,sources:n,enabled:!0});return Si(i,o)}function _s(e){return e?.enabled!==!1}function vs(e,t,n){let r=[...e===null?[]:pi(e),...n.flatMap(e=>Ve(e.ref,e.caps))];return r.length===0?null:ze({camera:t,sources:r,enabled:_s(e)})}function ys(e,t,n){let r=pi(e).filter(e=>G(e.source)!==n);return r.length===0?null:ze({camera:t,sources:r,enabled:_s(e)})}function bs(e,t){return{...e,enabled:t}}e();function xs({device:e,handle:t,availability:n,onAdvanced:i}){let{t:o}=X(),c=Ho(),[l,u]=r(!1),[f,p]=r(null),m=lo(t.state),h=Ci(m,`doorbell`),g=h===null||gs(h,t.target),_=g?hs(h):[],v=Bo(_.length>0),y=Vo({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:$r(m,`doorbell`):ni(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=ys(h,t.target,e.key),i=r===null&&$r(m,`doorbell`)===null;await c(o(`customize.doorbell.removeWhat`,{name:n}),i)&&await C(r)},T=e=>v.kind===`known`?v.value.find(t=>G({addonId:t.addonId,stableId:t.stableId})===e.key)??null:null;return a(s,{children:[a(Fo,{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(Nt,{"aria-label":o(`customize.doorbell.active`),checked:h.enabled!==!1,disabled:!x,onChange:e=>void C(bs(h,e.target.checked))}),o(`customize.doorbell.active`)]}),addLabel:o(`customize.doorbell.add`),onAdd:S?()=>u(!0):void 0,notices:a(s,{children:[d(Io,{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=Ji(e.caps,null),a=i===null?void 0:Ie[i];return d($,{name:r,detail:n===null?null:Xi(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($,{name:o(`customize.doorbell.otherFormula`),detail:null,meta:d(so,{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(ms,{open:l,title:o(`customize.doorbell.pickTitle`),selection:`multi`,candidates:y,confirmLabel:e=>o(`customize.assign.addCount`,{count:e}),onConfirm:e=>{u(!1),C(vs(h,t.target,e.map(e=>({ref:e.ref,caps:e.caps}))))},onClose:()=>u(!1)})]})}e();function Ss(e,t){let r=typeof e==`string`&&e.length>0,i=Bo(t&&r);return n(()=>t?os(i,e):null,[t,i,e])}e();function Cs(e){return e==null?null:e.message}function ws({device:e}){let t=ue(),{t:n}=X(),i=c(),o=Ho(),l=ke.includes(e.type),[u,f]=r(!1),[p,m]=r(!1),[h,g]=r(null),_=ct({deviceId:e.id},{enabled:l}),v=ea({status:_.status,data:_.data,error:Cs(_.error)===null?null:{message:Cs(_.error)??``}}),y=v.kind===`present`?v.slot.slotRef:``,b=v.kind===`present`?[...Zi(v.slot,v.value).map(e=>e.deviceId),...Yi(v.slot,v.value)]:[],x=yr(),S=Bo(l&&v.kind===`present`&&(u||b.length>0)),C=Ss(e.location,l&&v.kind===`present`),w=Qt({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(Fo,{id:`linked`,icon:oe,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:Xi(n.integration,n.location),orphan:t}},k=[...Zi(v.slot,T).map(e=>O(e,!1)),...Yi(v.slot,T).map(e=>O({deviceId:e,name:null,health:`ok`,implied:!1,tracked:!0},!0))],A=new Set(b),j=S.kind===`unknown`?S:w.status===`error`?{kind:`unknown`,reason:Cs(w.error)??n(`helpers.customize.requestFailed`)}:S.kind===`pending`||w.status===`pending`||w.data===void 0?{kind:`pending`}:{kind:`known`,value:na(w.data.candidates,E,A)},M=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)}},N=async e=>{await o(n(`customize.linked.removeWhat`,{name:e.name??`#${e.deviceId}`}),!1)&&await M(ta(T,e.deviceId))},P=[{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?`—`:ur(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(Kn,{checked:e.tracked,disabled:p,"aria-label":n(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void M(Qi(T,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:d(Ut,{icon:ie,variant:`ghost`,size:`sm`,"aria-label":n(`customize.assign.removeNamed`,{name:e.name??e.deviceId}),disabled:p,onClick:t=>{t.stopPropagation(),N(e)}})}];return a(s,{children:[d(Fo,{id:`linked`,icon:oe,title:n(`customize.linked.title`),addLabel:n(`customize.linked.add`),onAdd:p?void 0:()=>f(!0),...C===null?{}:{suggestion:{count:ls(j,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(ut,{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:ur(e.type,t).label,columns:P,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(ms,{open:u,title:n(`customize.linked.pickTitle`),selection:`multi`,candidates:j,room:C,confirmLabel:e=>n(`customize.assign.addCount`,{count:e}),onConfirm:e=>{f(!1),M(Gi(T,e.map(e=>e.deviceId)))},onClose:()=>f(!1)})]})}function Ts(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.sensors:[]}function Es(e){return{addonId:e.addonId,stableId:e.stableId,mode:e.mode}}function Ds(e){return e.length===0?null:{sensors:[...e]}}function Os(e,t){let n=new Set(e.map(Re));return Ds([...e.map(Es),...t.filter(e=>!n.has(Re(e))).map(e=>({...e,mode:Me}))])}function ks(e,t,n){return Ds(e.map(e=>Re(e)===t?{...Es(e),mode:n}:Es(e)))}function As(e,t){return Ds(e.filter(e=>Re(e)!==t).map(Es))}function js(e){return e?.state===`configured`&&e.cameraMotion!==void 0}function Ms(e){return e===null||e.state===`unreadable`?null:e.state===`configured`?e.cameraMotion??`always`:`always`}function Ns(e){return e===null||e.state===`unreadable`?!1:e.state===`not-configured`||js(e)}function Ps(e){return e?.state===`configured`&&(e.notForwarded!==void 0||e.notEnforced!==void 0)}function Fs(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 Is=5e3;function Ls(e){return e.state===`missing`||e.state===`unreadable`?e.stableId:e.name}function Rs({device:e,availability:n,sensors:i}){let{t:o}=X(),c=Ho(),u=At(),[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()},Is);return()=>clearInterval(e)},[]);let C=Ts(x);t(()=>{x!==null&&b(!1)},[x]);let w=i.presence===`present`&&Ns(x)&&!y?C:null,T=Bo(C!==null&&C.length>0),E=Vo({hostId:e.id,excludeCameras:!0,assigned:new Set((C??[]).map(Re)),preferredCap:`motion`,enabled:f});if(n.kind===`absent`)return null;let D=js(x),O=Ps(x)?`passes`:Ms(x),k=Fs(i.presence,x,y),A=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()})},j=_||u.isPending,M=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)}},N=async e=>{w!==null&&await c(o(`customize.motion.removeWhat`,{name:Ls(e)}),!1)&&await M(As(w,Re(e)))},P=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:Xi(t.integration,t.location)};return a(s,{children:[a(Fo,{id:`motion`,icon:fe,title:o(`customize.motion.title`),addLabel:o(`customize.motion.add`),onAdd:w!==null&&n.kind===`present`?()=>p(!0):void 0,addDisabled:j,notices:a(s,{children:[d(Io,{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`&&!Ns(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($,{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:A,removeLabel:``}),(C??[]).map(e=>{let t=Re(e),n=Ls(e),r=e.state===`ready`?Ji(e.caps,`motion`):null,i=r===null?void 0:Ie[r];return d($,{name:n,detail:P(e),meta:D&&w!==null?d(Vt,{"aria-label":o(`customize.motion.modeFor`,{name:n}),value:e.mode,disabled:j,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&&M(ks(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 N(e),removeLabel:o(`customize.assign.removeNamed`,{name:n}),busy:j},t)})]}),d(ms,{open:f,title:o(`customize.motion.pickTitle`),selection:`multi`,candidates:E,filters:Ki,confirmLabel:e=>o(`customize.assign.addCount`,{count:e}),onConfirm:e=>{if(p(!1),w===null)return;let t=Os(w,e.map(e=>e.ref));if(t!==null&&t.sensors.length>8){h(o(`customize.motion.tooMany`,{max:8}));return}M(t)},onClose:()=>p(!1)})]})}var zs={"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`}},Bs=new Set([q.Camera]);function Vs(e){return e.unitField===null?[e.fieldPath]:[e.fieldPath,e.unitField]}function Hs(e,t){if(Bs.has(e))return{kind:`absent`};let n=null;for(let[e,r]of Object.entries(zs))if(t.has(e)){n={cap:e,fieldPath:r.fieldPath,unitField:r.unitField};break}let r=null;for(let e of Pe)if(t.has(e)){let t=Ie[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 Us(e){return Ee(e.from,e.to)?Ne(e):null}function Ws(e){return Oe(e)}var Gs=/^convert\(v,\s*"[^"]*",\s*"[^"]*"\)$/;function Ks(e){return e!==void 0&&Gs.test(e.expr)}function qs(e){return e===void 0||e.expr===`!v`||Gs.test(e.expr)?!1:e.bindings.v!==void 0}function Js(e){let t=e.expr.trim();if(t===``)return{kind:`refused`,reason:Y.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 Ys(e,t,n){if(e===null)return null;let r=Ci(e,n.cap);if(r===null)return e;let i=new Set(Vs(n)),a=Object.fromEntries(Object.entries(r.fields).filter(([e])=>!i.has(e)));return Object.keys(a).length===0?$r(e,n.cap):ni(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 Xs(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`unit`);return typeof t==`string`?t:void 0}function Zs(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 Qs(e,t){let n=Ci(e,t.cap);if(n===null)return;let r=n.fields[t.fieldPath];return r!==void 0&&r.kind===`expression`?r:void 0}function $s(e,t){let n=Qs(e,t);return n===void 0||!Ks(n)?null:/^convert\(v,\s*"[^"]*",\s*"([^"]*)"\)$/.exec(n.expr)?.[1]??null}function ec(e,t){let n=Qs(e,t);return n===void 0||!qs(n)?null:n.expr}function tc(e,t,n){let r=Ci(e,t);if(r===null)return!1;let i=r.fields[n];return i!==void 0&&i.kind===`expression`&&i.expr===`!v`}function nc(e){return typeof e==`number`||typeof e==`boolean`||typeof e==`string`?String(e):e===null?`null`:JSON.stringify(e)}function rc({device:e,target:t,handle:n,facts:i}){let{t:o}=X(),s=V(),[c,l]=r(null),[u,f]=r(``),[p,h]=r(null),g=i.nativeCaps.kind===`known`?i.nativeCaps.value:null,_=g===null?null:Hs(e.type,g),v=_?.kind===`present`?_.convert?.cap??``:``,y=mr(s.trpcClient,e.id,v);if(i.nativeCaps.kind===`pending`)return d(`section`,{className:`${E} ${m}`,children:d(Io,{availability:{kind:`pending`}})});if(i.nativeCaps.kind===`unknown`)return d(`section`,{className:`${E} ${m}`,children:d(Io,{availability:{kind:`unknown`,reason:i.nativeCaps.reason}})});if(_===null||_.kind===`absent`)return null;let b=lo(n.state),x=_.convert,S=_.invert,C=x===null?void 0:Xs(y),w=C===void 0?void 0:ye(C)??C,T=w===void 0?void 0:xe(w),D=x===null?null:$s(b,x),O=x===null?null:ec(b,x),k=p??O??``,A=S===null?!1:tc(b,S.cap,S.fieldPath),j=n.state.kind===`none`||n.state.kind===`present`,M=x===null?0:Zs(y,x.fieldPath)??0,N=x!==null&&k.trim()!==``?{kind:`expression`,expr:k.trim(),bindings:{v:{kind:`from`,source:t,cap:x.cap,fieldPath:x.fieldPath}}}:null,P=N===null||x===null?null:mi(N,new Map([[we(t,x.cap),y===void 0?{kind:`pending`}:{kind:`value`,slice:y}]]),Date.now()),F=async e=>{let t=await n.save(e);l(t.kind===`refused`?t.reason:null)},I=async()=>{if(x===null||w===void 0||u===``)return;let e=Us({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 F(ni(b,t,e))},ee=async()=>{x!==null&&(await F(Ys(b,t,x)),f(``))},L=async()=>{if(x===null)return;let e=Js({self:t,cap:x.cap,fieldPath:x.fieldPath,expr:k,probe:M});if(e.kind===`refused`){l(e.reason);return}f(``),await F(ni(b,t,e.feature))},R=async()=>{x!==null&&(await F(Ys(b,t,x)),h(``))},te=async()=>{if(S===null)return;let e=Ws({self:t,cap:S.cap});if(e===null){l(o(`customize.numericTransforms.invertRefused`));return}await F(ni(b,t,e))},ne=async()=>{S===null||b===null||await F($r(b,S.cap))};return d(Po,{id:`numeric-transforms`,icon:Ge,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(Ft,{dimension:T,value:u===``?D??``:u,onChange:e=>{f(e),e!==``&&h(``)},disabled:!j||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(J,{size:`sm`,disabled:!j||n.saving||w===void 0||u===``||u===w,onClick:()=>void I(),children:o(`customize.numericTransforms.applyConvert`)}),D!==null&&d(J,{size:`sm`,variant:`outline`,disabled:!j||n.saving,onClick:()=>void ee(),children:o(`customize.numericTransforms.clearConvert`)})]})]}),x!==null&&a(`div`,{className:`flex flex-col gap-2`,"data-testid":`numeric-script`,children:[d(_i,{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`)}),P!==null&&d(`p`,{role:`status`,className:`text-[11px] font-mono text-foreground`,"data-testid":`numeric-script-preview`,children:P.kind===`value`?o(`customize.numericTransforms.preview`,{source:nc(M),result:nc(P.value)}):P.kind===`waiting`?o(`customize.numericTransforms.previewWaiting`):P.kind===`unavailable`?o(`customize.numericTransforms.previewError`,{reason:P.reason}):o(`customize.numericTransforms.previewRuntimeOnly`)}),a(`div`,{className:`flex flex-wrap gap-2`,children:[d(J,{size:`sm`,disabled:!j||n.saving||k.trim()===``,onClick:()=>void L(),children:o(`customize.numericTransforms.applyScript`)}),O!==null&&d(J,{size:`sm`,variant:`outline`,disabled:!j||n.saving,onClick:()=>void R(),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:A?d(J,{size:`sm`,variant:`outline`,disabled:!j||n.saving,onClick:()=>void ne(),children:o(`customize.numericTransforms.clearInvert`)}):d(J,{size:`sm`,disabled:!j||n.saving,onClick:()=>void te(),children:o(`customize.numericTransforms.applyInvert`)})})]})]})})}e();function ic(e){return e instanceof Error?e.message:String(e)}function ac(e){let t=gr({addonId:e.addonId,stableId:e.stableId}),n=Tn(),i=Bn(),a=ir(),o=co({status:t.status,data:t.data,error:t.error===null||t.error===void 0?null:{message:t.error.message}}),{t:s}=X(),c=l(!1),[u,d]=r(!1),f=async e=>{let r=ai(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:ic(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 oc=`pipeline-orchestrator`;function sc(e){return e.status===`pending`?`pending`:e.status===`error`?`unknown`:e.data===void 0?`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function cc(e,t){return e===`absent`?`absent`:sc(t)}async function lc(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function uc(e,t){let n=er(oc),r=Un({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>lc(r.refetch);return t?{presence:cc(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,refetch:i}:{presence:`absent`,status:null,refetch:i}}function dc(e,t){let n=Nn({deviceType:e.type}),r=un({deviceId:e.id}),i=dn({deviceId:e.id}),a=Lo(n,e=>new Set(e.caps.map(e=>e.cap))),o=Lo(r,e=>no(e.entries)),s=Lo(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}function fc(e,t,n){let r=t.kind===`known`&&t.value.has(`consumables`),i=Ao(r?{deviceId:e,cap:Go,path:Ko}:null);return Qo(t,n,r?i:null)}function pc(){return{kind:`unknown`,reason:Y.t(`helpers.fieldsTableRows.noValue`)}}function mc(e,t){let n=G(e);return t.get(n)??n}function hc(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=gi(e).map(e=>mc(e,n.sourceNames)).join(` + `),a=i.find(e=>e.field===`lastPressedAt`);return[{key:`doorbell`,label:Y.t(`helpers.whatChangesRows.doorbell`),origin:{kind:r,from:t},value:a?.value??pc()}]}return e.cap===`consumables`?ci(e).map(e=>{let t=t=>Te(W,e.key,t),a=i.find(e=>e.field===t(`level`)||e.field===t(`remaining.value`)),o=e.source===null?``:mc(e.source.source,n.sourceNames);return{key:`consumables.${e.key}`,label:Y.t(`helpers.whatChangesRows.consumable`,{name:e.label}),origin:{kind:r,from:o},value:a?.value??pc()}}):i.map(e=>({key:e.key,label:`${e.cap}.${e.field}`,origin:{kind:r,from:e.from},value:e.value}))}function gc(e){let t=di({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`?hc(n,t,e):[])}function _c(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 vc=`${j} 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)]`,yc=`font-mono text-[11px] text-foreground break-words`,bc=`text-[11px] text-foreground-subtle break-words`,xc=`text-[11px] break-words sm:text-right`;function Sc({device:e,composition:t,state:n,nativeCaps:r,cameraSensors:i}){let{t:o}=X(),s=t!==null&&n!==null,c=Bo(s),l=new Map(c.kind===`known`?c.value.map(e=>[G({addonId:e.addonId,stableId:e.stableId}),e.name]):[]),u=s&&r.kind===`known`?gc({composition:t,nativeCaps:r.value,state:n,sourceNames:l}):[],f=s&&r.kind===`known`&&u.length===0&&t.features.length>0,p=_c(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(Po,{id:`changes`,icon:ne,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:vc,children:[d(`span`,{className:yc,children:e.label}),d(`span`,{className:bc,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:xc,children:d(Cc,{value:e.value})})]},e.key)),p!==null&&a(`li`,{className:vc,children:[d(`span`,{className:yc,children:o(`common.motionWord`)}),d(`span`,{className:bc,children:p}),d(`span`,{className:xc,children:d(Mo,{target:{deviceId:e.id,cap:`motion`,path:`detected`}})})]})]})]})}function Cc({value:e}){let{t}=X();switch(e.kind){case`value`:return a(`span`,{children:[hi(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 wc({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=X(),i=cr({deviceId:e}),a=i.data;return a==null?i.status===`error`?d(zn,{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(Tc,{device:a}):d(Ec,{device:a,target:{addonId:a.addonId,stableId:a.stableId},activeSubTab:t,onSubTabChange:n})}function Tc({device:e}){let{t}=X(),n=e.stableId.startsWith(`composed-`)?e.stableId.slice(Ue.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(Rr,{className:`text-[11px] text-primary hover:underline`,to:Kr(n),children:t(`customize.composed.edit`)})]})}function Ec({device:e,target:t,activeSubTab:n,onSubTabChange:r}){let i=ac(t),o=er(`composer`),{t:s}=X(),c=uc(e.id,e.type===q.Camera),l=dc(e,lo(i.state)),u=fc(e.id,l.nativeCaps,l.wireable),f={deviceType:e.type,composable:l.composable,nativeCaps:l.nativeCaps,cameraSensors:c.presence},p=()=>r(Xr),m=i.state.kind===`none`||i.state.kind===`present`;return n===`advanced`?a(`div`,{className:`flex flex-col gap-3`,children:[d(Oc,{state:i.state}),m&&d(Dc,{device:e,target:t,handle:i,facts:l,onDone:()=>r(`main`)})]}):a(`div`,{className:`flex flex-col gap-3`,children:[d(yo,{device:e}),o===`absent`&&d(`p`,{role:`alert`,className:`text-xs text-warning`,children:s(`customize.composerAbsent`)}),i.state.kind!==`none`&&d(Oc,{state:i.state}),d(xs,{device:e,handle:i,availability:oo(`doorbell`,f),onAdvanced:p}),d(Rs,{device:e,handle:i,availability:oo(`motion`,f),sensors:c}),d(Wo,{device:e,handle:i,availability:oo(`battery`,f),onAdvanced:p}),d(as,{device:e,handle:i,availability:oo(`consumables`,f),onAdvanced:p,defaults:u}),d(rc,{device:e,target:t,handle:i,facts:l}),d(ws,{device:e}),d(Sc,{device:e,composition:lo(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(so,{onAdvanced:p}):d(`span`,{}),d(kc,{handle:i})]})]})}function Dc({device:e,target:t,handle:n,facts:r,onDone:i}){let a=n.state.kind===`present`?n.state:null;return d(yi,{initial:a===null?ei(t):ti(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 Oc({state:e}){let{t}=X();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(zn,{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(Yt,{variant:n.status===`running`?`success`:n.status===`failed`?`danger`:`warning`,children:t(`customize.blockStatus.${n.status}`)}),!n.enabled&&d(Yt,{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 kc({handle:e}){let{t}=X(),n=it(),[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(J,{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 Ac=`overview`;function jc(e,t){return e.some(e=>e.id===t)?t:Ac}function Mc({deviceId:e}){let{t}=X(),n=c(),r=Number.isFinite(e),{data:i}=cr({deviceId:e},{enabled:r}),o=typeof i?.type==`string`?i.type:`camera`;dr([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:s,isLoading:l,isError:u,error:f}=un({deviceId:e},{enabled:r}),{data:p}=Wt({deviceType:o},{enabled:!!o}),m=$t({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(Xe,{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(Nc,{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(Pc,{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(Fc,{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(Wr,{i18nKey:`device.bindingsTab.boundSummary`,count:_.length,values:{bound:v},components:{b:d(`span`,{className:`font-medium text-foreground`}),em:d(`em`,{})}})}),d(Vn,{columns:y,rows:_,rowKey:e=>e.capName,minWidthPx:720})]})}function Nc({kind:e}){let{t}=X();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(re,{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($e,{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(oe,{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 Pc({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 Fc({wrappers:e,activeWrapperId:t,disabled:n,onPick:r}){let{t:i}=X();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:he,{className:`h-3 w-3`}),e]},e)})})}function Ic({deviceId:e,activeSubTab:t,onSubTabChange:n,deviceType:r,isAdmin:i}){return a(`div`,{className:`flex flex-col gap-3`,children:[Ir(r,i)&&d(or,{deviceId:e,readOnly:!0}),d(Jr,{deviceId:e,activeSubTab:t,onSubTabChange:n})]})}e();var Lc=[[`pipelineOrchestrator`,`getCameraDetectionSource`]];function Rc(e){let t=c(),n=sr({deviceId:e},{refetchOnMount:`always`}),a=xt(),[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:Lc})}catch(e){u(e instanceof Error?e.message:`Could not change the root detector`),await t.invalidateQueries({queryKey:Lc})}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 zc=`object-detection`;function Bc(e){return[e.addonId,...e.children.flatMap(Bc)]}function Vc(e,t){if(e===`pipeline`)return new Set;let n=Hc(t,zc);return n===void 0?new Set:new Set(e===`onboard`?[n.addonId]:Bc(n))}function Hc(e,t){for(let n of e){if(n.addonId===t)return n;let e=Hc(n.children,t);if(e!==void 0)return e}}function Uc(e,t){return e===`onboard`?Y.t(`helpers.detectionSourceModel.badgeCameraAi`):t===`object-detection`?Y.t(`helpers.detectionSourceModel.badgeNoRoot`):Y.t(`helpers.detectionSourceModel.badgeIdle`)}function Wc(e){switch(e){case`pipeline`:return Y.t(`helpers.detectionSourceModel.explainPipeline`);case`onboard`:return Y.t(`helpers.detectionSourceModel.explainOnboard`);case`none`:return Y.t(`helpers.detectionSourceModel.explainNone`)}}function Gc(e){switch(e){case`boxed`:return``;case`while-streaming`:return Y.t(`helpers.detectionSourceModel.geometryWhileStreaming`);case`flag-only`:return Y.t(`helpers.detectionSourceModel.geometryFlagOnly`);case`unknown`:return Y.t(`helpers.detectionSourceModel.geometryUnknown`)}}function Kc(e,t){return e===`onboard`?Y.t(`helpers.detectionSourceModel.noticeOnboard`):t===`object-detection`?Y.t(`helpers.detectionSourceModel.noticeNoRoot`):Y.t(`helpers.detectionSourceModel.noticeIdle`)}function qc({source:e,geometry:t,saving:n,error:r,onPick:i}){let{t:o}=X(),s=t===`flag-only`,c=Gc(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:M,children:o(`device.detectionSourceControl.rootDetector`,`Root detector`)}),d(et,{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:U,children:[Wc(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 Jc=new Set([`package-detection`]);function Yc(e){return e===`node`?Y.t(`device.cameraStepInspector.modelSource.node`):Y.t(`device.cameraStepInspector.modelSource.default`)}function Xc({deviceId:e}){let{t}=X(),i=c(),s=V().trpcClient,l=Qn({deviceId:e},{refetchOnMount:`always`}),u=dt(void 0,{refetchOnMount:`always`}),f=De(Et({addonId:`pipeline-orchestrator`}).data??null);dr([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:p}=Dt(),m=n(()=>{let e=new Set((u.data??[]).map(e=>e.nodeId));return p.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[u.data,p]),h=m.map(e=>e.id).join(`,`),g=o({enabled:m.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,h],queryFn:async()=>{let e={};for(let t of m)try{e[t.id]=await s.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),_=o({enabled:m.length>0,queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`],`camera-step`,h],queryFn:async()=>{let e={};for(let t of m)try{e[t.id]=(await s.pipelineOrchestrator.getNodeInferenceDevices.query({nodeId:t.id})).devices}catch{e[t.id]=[]}return e}}),v=()=>{i.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]})},y=Dr({onSuccess:v}),b=qt(),[x,S]=r(null),[C,w]=r(!1),[T,E]=r(null),D=g.data??{},O=_.data??{},k=l.data??null,A=m.map(e=>D[e.id]).find(e=>e!==void 0)??null,j=n(()=>A?Ot(A):[],[A]),N=n(()=>Bi(j),[j]),P=Rc(e),F=n(()=>P.source===null?new Set:Vc(P.source,j),[P.source,j]),[I,ee]=r(!1),L=n(()=>Ii(m,O,I),[m,O,I]),R=n(()=>Ii(m,O).length,[m,O]),te=(e,t)=>Ni(D[e.nodeId],t),ne=(e,t)=>Ei(O[e.nodeId]??[],e.deviceKey,t,u.data?.find(t=>t.nodeId===e.nodeId)?.settings.stepSettings)??{},re=(e,t,n)=>Ai(e,t,{nodePin:t.device.steps?.[n]?.modelId}),ie=e=>{if(Jc.has(e))return{kind:`zone-driven`};let t=Ni(A,e)?.enabledByDefault??!0,n=k?.stepToggles?.[e];return{kind:`gate`,effectiveOn:n??t,defaultOn:t,explicit:n!==void 0}},z=(e,t,n)=>({node:ne(e,t),camera:n?.stepId===t?n.camera:k?.stepSettings?.[t]}),B=(e,t)=>{if(F.has(e))return{kind:`disabled`};let n=te(t,e),r=ie(e),i=Fi(e),a=Li(D[t.nodeId],t),o=z(t,e,null),s=Le(o.node,o.camera);return Di({addon:n,acc:t,gatedOn:r.kind===`gate`?r.effectiveOn:!0,model:n?re(n,t,e):{modelId:void 0,source:`default`},...wi(e,s,a)&&a?{rootName:a.name}:{},...i?{clusterModelId:f[e]??i.defaultModelId}:{}})},ae=N.map(({node:e})=>({addonId:e.addonId,name:e.addonName,fieldLabels:ji(Ni(A,e.addonId))}));return u.isLoading||m.length>0&&(g.isLoading||_.isLoading)?d(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.loadingPipeline`,`Loading pipeline…`)}):m.length===0?d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.noPipelineNodeIsOnline`,`No pipeline node is online.`)}):A===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:[P.view?.onboard.available===!0&&P.source!==null&&d(qc,{source:P.source,geometry:P.view.onboard.geometry,saving:P.saving,error:P.error,onPick:e=>void P.pick(e)}),d(Ti,{tree:j,searchRows:ae,accelerators:L,cellState:B,stepBadge:e=>F.has(e)&&P.source!==null?d(Yt,{variant:`warning`,title:Kc(P.source,e),children:Uc(P.source,e)}):d(Fn,{gate:ie(e)}),disabledCount:ki(Object.fromEntries(m.map(e=>[e.id,O[e.id]??[]]))),showDisabled:I,onShowDisabledChange:ee,dirty:x!==null,onDiscard:()=>S(null),summary:d(`span`,{className:U,children:t(`device.cameraStepInspector.balancedAcross`,{count:R})}),label:t(`device.cameraStepInspector.detectionStepsOfThisCamera`,`Detection steps of this camera`),renderDetail:({stepId:n,accelerator:r,matchedField:i,closeButton:o,onEscape:s,headingRef:c})=>{let l=r??L[0],u=l?te(l,n)??Ni(A,n):null;if(u===null||l===void 0)return d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.noStepSelected`,`No step selected.`)});let f=x?.stepId===n?x:null,p=St(u),m=Ri(p),h=Oi(p),g=z(l,n,f),_=Le(g.node,g.camera),O=Li(D[l.nodeId],l),j=re(u,l,n).modelId,N=Fi(n),I=ie(n),ee=m.find(e=>`label`in e&&e.label===i)?.key??null,R=async()=>{if(f!==null){w(!0);try{let t=k?.stepSettings?.[n];Fe(f.camera,t??{})||await b.mutateAsync({deviceId:e,addonId:n,settings:Object.keys(f.camera).length>0?{...f.camera}:null}),S(null),E({kind:`saved`})}catch(e){E({kind:`error`,error:e instanceof Error?e.message:t(`device.cameraStepInspector.saveFailed`)})}finally{w(!1),v()}}},ne=+(f!==null&&!Fe(f.camera,k?.stepSettings?.[n]??{})),B=(r===null?L:[r]).map(e=>{let r=te(e,n)??u,i=re(r,e,n);return{id:e.id,label:e.label,modelId:Pi(r,e)?i.modelId:void 0,sourceLabel:Pi(r,e)?Yc(i.source):t(`device.cameraStepInspector.noBuild`,{format:e.device.format})}});return d(mn,{ref:c,title:r===null?t(`device.cameraStepInspector.thisCamera`,`{{name}} · this camera`,{name:u.name}):`${u.name} · ${r.label}`,subtitle:r===null?t(`device.cameraStepInspector.everyAcceleratorThisCameraRuns`,`{{slot}} · every accelerator this camera runs on`,{slot:u.slot}):`${u.slot} · ${r.device.format}`,leading:o,onEscape:s,headerActions:d(hr,{gate:I,busy:y.isPending,onSet:t=>y.mutate({deviceId:e,addonId:n,enabled:t})}),saveBar:{dirtyCount:ne,saving:C,status:T?.kind??null,...T?.error===void 0?{}:{error:T.error},onSave:()=>void R(),onDiscard:()=>S(null),...N===null&&m.length>0?{scope:d(`p`,{className:U,children:t(`device.cameraStepInspector.appliesToAllAcceleratorsOf`,`Applies to: all accelerators of this camera.`)})}:{}},children:a(`div`,{className:`space-y-3`,children:[F.has(n)&&P.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:Kc(P.source,n)}),a(`section`,{className:`space-y-2`,"aria-label":t(`device.cameraStepInspector.model`,`Model`),children:[d(`h3`,{className:M,children:t(`device.cameraStepInspector.model`,`Model`)}),N===null?d(Vi,{rows:B,hint:t(`device.cameraStepInspector.modelIsTheAccelerators`,`A model is chosen by the accelerator that runs it: change it under Pipeline → Nodes.`)}):d(zi,{step:N,engineFormat:l.device.format,runnableModelIds:yt(u.models??[],l.device.format).map(e=>e.id)})]}),N===null&&(m.length>0||O!==void 0||h)&&a(`section`,{"aria-label":t(`device.cameraStepInspector.settings`,`Settings`),className:`space-y-2 border-t border-border/60 pt-2`,children:[(m.length>0||O!==void 0)&&d(Zc,{addon:u,fields:m,layers:g,modelId:pt(u,j,_,O),root:O,highlightKey:ee,onChange:e=>{E(null),S({stepId:n,camera:e})}}),h&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`accelerator-only-thresholds`,children:t(`device.cameraStepInspector.thresholdsAreTheAccelerators`,`Confidence thresholds belong to the model, so they are set on the accelerator that runs it (Pipeline → Nodes), not per camera.`)})]}),d(Ui,{addonId:n,highlightLabel:i})]})})}})]})}function Zc({addon:e,fields:t,layers:n,modelId:r,root:i,highlightKey:a,onChange:o}){return Mi(a===null?null:Jt(a)),d(jt,{addon:e,fields:t,layers:{node:n.node,...n.camera===void 0?{}:{camera:n.camera}},target:`camera`,labels:{camera:`This camera`,node:`Node`},modelId:r,...i===void 0?{}:{rootModel:i},highlightKey:a,onChangeLayer:o})}function Qc(e,t,n){return{id:e,get label(){return Y.t(t)},icon:n}}var $c=[Qc(`object-detection`,`helpers.detectionSettingsGroups.objectDetection`,`scan-search`),Qc(`tracking`,`helpers.detectionSettingsGroups.tracking`,`route`),Qc(`motion`,`helpers.detectionSettingsGroups.motion`,`activity`),Qc(`stationary`,`helpers.detectionSettingsGroups.stationary`,`square-parking`),Qc(`zones`,`helpers.detectionSettingsGroups.zones`,`shapes`),Qc(`audio`,`helpers.detectionSettingsGroups.audio`,`volume-2`),Qc(`cluster`,`helpers.detectionSettingsGroups.cluster`,`server`)],el={"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 tl(e){return el[e]??`object-detection`}e();var nl=`steps`,rl=`settings`,il=new Set([nl,rl]);function al(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function ol({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=X();return a(lt,{value:t&&il.has(t)?t:nl,onValueChange:i(e=>{n?.(e)},[n]),className:`flex flex-col`,children:[a(Jn,{className:`flex-shrink-0`,children:[d(rt,{value:nl,children:r(`device.detectionPipelineTab.steps`,`Steps`)}),d(rt,{value:rl,children:r(`device.detectionPipelineTab.settings`,`Settings`)})]}),d(Bt,{value:nl,children:d(Xc,{deviceId:e})}),d(Bt,{value:rl,children:d(Jr,{deviceId:e,sectionFilter:al,subTabGrouping:{groupOf:e=>tl(e.id),tabs:$c}})})]})}var sl=`Notifications`,cl={i18nKey:`device.deviceNotificationMute.cameraCostWhenOff`,text:`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`},ll={i18nKey:`device.deviceNotificationMute.deviceCostWhenOff`,text:`This device never notifies — no rule, no target, no alarm.`};function ul(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:sl,on:r===null?null:i??r,available:r!==null,costWhenOff:e.isCamera?cl:ll}}function dl(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}e();function fl(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function pl({deviceId:e,isCamera:t}){let{t:n}=X(),o=c(),s=Number.isFinite(e),[l,u]=r(null),[f,p]=r(null),m=ul({mutedDeviceIds:fl(cn({},{enabled:s}).data),deviceId:e,isCamera:t,pendingOn:f}),h=n(m.costWhenOff.i18nKey,m.costWhenOff.text),g=an({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=dl(m,e);t!==null&&(p(!t.muted),g.mutate(t))},[e,g,m]),v=m.on===null,y=m.on===!1,b=y?Ye: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 ml(e,t){return{switchId:e,label:He[e].label,detail:t===void 0||t.length===0?null:t}}function hl(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 gl(e){let t=hl(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>ml(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>ml(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 _l(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 vl({deviceId:e,deviceName:t}){let{t:i}=X(),o=it(),[s,c]=r(null),l=vn({isCamera:!0,projection:`slim`}),u=fr(),f=l.data!==void 0,p=n(()=>l.data===void 0?[]:_l(l.data,e),[l.data,e]),m=p.find(e=>e.id===s)??null,h=u.data===void 0?null:gl(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(Ge,{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(yl,{report:h})]})}function yl({report:e}){let{t}=X(),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(ce,{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(me,{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(Qe,{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 bl({deviceId:e}){let{t}=X(),[n,i]=r(null),o=Ht({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(te,{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 xl(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function Sl({device:e}){let{t}=X(),n=Gr(),r=typeof e.id==`number`?e.id:null,i=String(e.type??``),o=i===q.Camera,s=i===q.Hub,c=e.features??[],l=c.includes(je.Resyncable),{data:u}=It({deviceId:r??0},{enabled:r!==null&&o,refetchInterval:5e3}),f=u?.streams??{},p=Object.entries(f),m=c.includes(je.DoorbellButton),h=Wn(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(An,{deviceId:r,onOpenChild:e=>n(`/devices/${e}`)}),l&&r!==null&&d(bl,{deviceId:r}),o&&r!==null&&d(vl,{deviceId:r,deviceName:String(e.name??``)}),r!==null&&d(pl,{deviceId:r,isCamera:o}),o&&r!==null&&d(yn,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:r}),m&&d(Er,{history:h.history,latestIsFresh:g}),o&&r!==null&&d(yn,{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(Cl,{label:t(`device.overviewTab.nominal`,`Nominal`),value:xl(n.nominalBitrateKbps??0)}),d(Cl,{label:t(`device.overviewTab.observed`,`Observed`),value:xl(n.observedBitrateKbps??0)}),d(Cl,{label:t(`device.overviewTab.peak`,`Peak`),value:xl(n.peakBitrateKbps??0)}),d(Cl,{label:t(`device.overviewTab.packetLoss`,`Packet Loss`),value:`${(n.packetLossPercent??0).toFixed(2)}%`,warning:(n.packetLossPercent??0)>1})]})]},e))})]}),d(jr,{}),r!==null&&d(kr,{deviceId:r})]})}function Cl({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 wl=`history`,Tl=[{id:`overview`,labelKey:`helpers.structuralTabs.overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,labelKey:`helpers.structuralTabs.config`,cameraOnly:!1,adminOnly:!1},{id:qr,labelKey:`helpers.structuralTabs.customize`,cameraOnly:!1,adminOnly:!0},{id:wl,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}],El=new Set([q.Hub,q.Container]);function Dl(e,t){let n=e===q.Camera,r=e===void 0||!El.has(e);return Tl.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)&&(r||e.id!==`history`)).map(({id:e,labelKey:t})=>({id:e,label:Y.t(t)}))}function Ol({provider:e,integrationId:t,name:n}){let r=Gr(),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(Ur,{type:e,size:`lg`})})}e();var kl=[{id:`logs`,icon:H,labelKey:`common.logs`},{id:`repl`,icon:Ze,labelKey:`deviceDetail.repl`},{id:`events`,icon:T,labelKey:`common.events`},{id:`state`,icon:S,labelKey:`common.state`}];function Al(){let{t:e}=X(),t=Qr(),o=Number(t.deviceId),u=Number.isFinite(o),f=Gr(),p=c(),m=it(),_=V(),{user:v}=Br(),b=v?.isAdmin===!0,[x,S]=Yr(),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}),A=l(O);A.current=O;function j(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=A.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:M,isLoading:N,isError:F}=cr({deviceId:o},{enabled:u,refetchInterval:5e3,retry:1}),{data:I}=Tt({deviceId:o},{enabled:u}),ee=n(()=>{let e=I?.settings?.sections??[],t=I?.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(Mr)&&r.add(Lr),[...r].map(e=>e===`export`?{id:e,label:Ar,isAddonContrib:!0}:{id:e,label:be[e]?.label??e,isAddonContrib:!0})},[I]),L=M,R=String(L?.name??t.deviceId??`Device`),ne=L?.online===!0,re=ne?`online`:`offline`,ie=String(L?.addonId??`rtsp`),z=L?.features??[],B=L?.type,ae=B===q.Camera,{data:oe}=Vr(u?o:0),se=B===q.Container,ce=n(()=>(oe??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[oe]),H=n(()=>se?bt(ce,typeof L?.linkDeviceId==`number`?L.linkDeviceId:null,typeof L?.primaryChildEntityId==`string`?L.primaryChildEntityId:null)?.id??null:null,[se,ce,L?.linkDeviceId,L?.primaryChildEntityId]),{data:le}=Tt({deviceId:H??0},{enabled:H!==null}),ue=n(()=>{if(H===null)return[];let e=le?.settings?.sections??[],t=le?.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:be[e]?.label??e,isAddonContrib:!0,childDeviceId:H}))},[H,le]),fe=n(()=>Ba({sections:[...I?.settings?.sections??[],...I?.live?.sections??[]],deviceId:o,...H===null?{}:{child:{sections:[...le?.settings?.sections??[],...le?.live?.sections??[]],deviceId:H}}}),[I,le,o,H]),me=typeof L?.parentDeviceId==`number`?L.parentDeviceId:null,{data:he}=cr({deviceId:me??0},{enabled:me!==null}),U=st(),ge=L?.disabled!==!0,_e=n(()=>{let e=I?.settings?.sections??[],t=I?.live?.sections??[];return Fr([...e,...t],B,b,I!==void 0)},[I,B,b]),ve=n(()=>{let e=new Set,t=[];for(let n of[...Dl(B,b),...ee,...ue])n.id===`config`&&!_e||e.has(n.id)||(e.add(n.id),t.push(n));return t},[B,b,ee,ue,_e]),ye=n(()=>jc(ve,C),[ve,C]),xe=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 Hi)n.delete(e);return n},{replace:!0})},[S]),Se=i(e=>{S(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[S]),Ce=(oe??[]).length>0,we=n(()=>kl.filter(({featureGate:e})=>!e||z.includes(e)),[z]),{data:Te}=gt(void 0),Ee=n(()=>L?Yn(L,Te):null,[L,Te]),W=Ee?.kind===`resolved`?Ee.integration:null,De=W===null?Ee?.kind===`unknown`?e(`deviceDetail.loadingIntegration`):Ee?.kind===`orphan`?e(`deviceDetail.missingIntegration`):e(`deviceDetail.noIntegration`):W.name,G=W!==null&&W.addonId===ie?W.name:ie,Oe=ar({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]}),f(W?.id?`/integrations/${W.id}`:`/integrations`)}}),ke=rn({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ae=Kt({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Me=_r(),Ne=In({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Pe=z.includes(je.Rebootable),K=z.includes(je.BatteryOperated),Fe=Ct(_.trpcClient,K&&u?o:null),Ie=mt(_.trpcClient,u?o:null),[Le,Re]=r(!1),ze=async()=>{if(!Le){Re(!0);try{let e=R.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await ia(`${P}/${String(o)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Re(!1)}}},Be=ke.isPending||Ae.isPending,{data:Ve}=xr({deviceId:o},{enabled:u&&ae,refetchInterval:1e4}),He=Ve?.agentNodeId??null,Ue=typeof He==`string`&&He.length>0&&!He.startsWith(`addon:`)?He:void 0,{data:We}=hn({deviceId:o,...Ue?{nodeId:Ue}:{}},{enabled:u&&ae,refetchInterval:3e3,retry:!1}),{data:Ge}=zt({deviceId:o},{enabled:u&&ae,refetchInterval:3e3,retry:!1}),Ke=Ge?.level?.dbfs??null;function qe(){if(!u)return null;switch(ye){case`overview`:return d(Sl,{device:L??{}});case`config`:return d(Ic,{deviceId:o,activeSubTab:w,onSubTabChange:Se,deviceType:B,isAdmin:b});case`detection-pipeline`:return d(ol,{deviceId:o,activeSubTab:w,onSubTabChange:Se});case`bindings`:return d(Mc,{deviceId:o});case wl:return d(Xn,{deviceId:o,onNavigate:e=>f(e)});case qr:return d(wc,{deviceId:o,activeSubTab:w,onSubTabChange:Se});default:{let e=ye,t=ee.some(t=>t.id===e),n=ue.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??o;if(e===`export`)return d(Jr,{deviceId:o,sectionFilter:Mr,activeSubTab:w,onSubTabChange:Se});let i=d(Jr,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:w,onSubTabChange:Se});return n!==void 0&&r!==o?d(nn,{deviceId:r,children:i}):i}}}return u?N?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`})})]}):F||!M?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(Wr,{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(Cr,{items:[{label:e(`deviceDetail.integrations`,`Integrations`),onClick:()=>f(`/integrations`)},W===null?{label:De}:{label:De,onClick:()=>f(`/integrations/${W.id}`)},{label:R}]})}),a(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[W!==null&&d(Ol,{provider:W.addonId,integrationId:W.id,name:W.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:R}),d(nr,{status:re}),K&&d(en,{status:Fe,variant:`full`}),d(br,{status:Ie})]}),me!==null&&he&&a(`button`,{type:`button`,onClick:()=>f(`/devices/${me}`),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:he.name}),children:[d(`span`,{children:`↑`}),d(`span`,{className:`truncate`,children:String(he.name??`Device #${me}`)})]}),d(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:z.length>0&&d(Hr,{capabilities:z})})]}),We&&d(`div`,{className:`hidden lg:flex`,children:d(jl,{metrics:We,dbfs:Ke})}),a(`div`,{className:`flex items-center gap-1 shrink-0`,children:[a(`button`,{onClick:async()=>{ge?await m({title:e(`deviceDetail.disable`,`Disable "{{name}}"?`,{name:R}),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`})&&Ae.mutate({deviceId:o}):ke.mutate({deviceId:o})},disabled:Be,title:ge?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 ${ge?`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:Be?e(`deviceDetail.updating`,`Updating…`):ge?e(`deviceDetail.enabled`,`Enabled`):e(`deviceDetail.disabled`,`Disabled`)})]}),d(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),ae&&a(s,{children:[d(da,{deviceId:o}),d(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),d(pa,{deviceId:o}),d(Hn,{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:Le,onClick:()=>{ze()}},{id:`reboot`,label:e(`deviceDetail.rebootDevice`,`Reboot device`),description:e(`deviceDetail.cameraGoesOfflineFor30`,`Camera goes offline for ~30 seconds.`),icon:pe,hidden:!Pe,disabled:Me.isPending,danger:!0,onClick:async()=>{await m({title:e(`deviceDetail.reboot`,`Reboot "{{name}}"?`,{name:R}),message:e(`deviceDetail.theCameraWillGoOffline`,`The camera will go offline for around 30 seconds while the firmware reboots.`),confirmLabel:e(`deviceDetail.reboot2`,`Reboot`),variant:`danger`})&&Me.mutate({deviceId:o})}},{id:`restart-addon`,label:e(`deviceDetail.restartAddon`,`Restart addon`),description:e(`deviceDetail.bouncesEveryDeviceServedBy`,`Bounces every device served by {{servingAddonLabel}}.`,{servingAddonLabel:G}),icon:te,disabled:Ne.isPending,danger:!0,onClick:async()=>{await m({title:e(`deviceDetail.restart`,`Restart "{{servingAddonLabel}}"?`,{servingAddonLabel:G}),message:e(`deviceDetail.restartingTheAddonWillBriefly`,`Restarting the addon will briefly disconnect every device served by it (not just "{{name}}"). Streams will reconnect automatically.`,{name:R}),confirmLabel:e(`deviceDetail.restart2`,`Restart`),variant:`danger`})&&Ne.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:R}),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(nn,{deviceId:o,device:L??void 0,children:d(Mn,{children:d(Dn,{children:d(de,{children:d(jn,{children:a(`main`,{className:U?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[a(`div`,{className:U?`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:!U&&O!==null?{width:`${String(O)}px`}:void 0,children:[d(`div`,{className:ae?`flex-shrink-0 border-b border-border-subtle bg-black`:U?`flex-shrink-0 border-b border-border-subtle bg-surface`:`shrink-0 border-b border-border-subtle bg-surface`,children:ae?d(Xa,{deviceId:o,intercomAvailable:z.includes(je.TwoWayAudio)}):a(`div`,{children:[d(La,{deviceId:o,deviceName:R,deviceType:B??`unknown`,provider:ie,isOnline:ne,features:z}),d(Ra,{deviceId:o,widgets:fe})]})}),ae&&fe.length>0&&d(`div`,{className:`flex-shrink-0 border-b border-border-subtle bg-surface pt-3 sm:pt-4`,children:d(Ra,{deviceId:o,widgets:fe})}),a(`div`,{className:U?`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:we.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:U?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[T===`logs`&&d(Za,{deviceId:o,containerDeviceId:B===`container`?o:void 0}),T===`repl`&&d(Qa,{deviceId:o}),T===`events`&&d($a,{deviceId:o}),T===`state`&&d(eo,{deviceId:o})]})]})]}),!U&&d(`div`,{role:`separator`,"aria-orientation":`vertical`,title:e(`deviceDetail.dragToResize`,`Drag to resize`),onMouseDown:j,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:U?`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:ve.map(e=>{let t=ye===e.id;return a(`button`,{onClick:()=>xe(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:U?`p-3 flex flex-col gap-3`:`flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3`,children:[ye===`overview`&&Ce&&d(ma,{parentDeviceId:o}),qe()]})]})]})})})})})})]}):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(Wr,{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 jl({metrics:e,dbfs:t}){let n=ue(),{t:r}=X(),i=En(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(fe,{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(I,{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(A,{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{Al 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 P,xi as F,yi as I}from"./player-overlays-BTnXgs6l.js";import{Gi as L,Ki as te,Wi as ne,c as R,l as z,o as re,r as ie,s as ae}from"./client-BI85kkig.js";import{i as oe,n as se,r as ce,t as le}from"./key-CA18pL-8.js";import{d as B,l as V,s as ue}from"./video-BRH0aO3l.js";import{t as de}from"./key-round-C7R-scbw.js";import{t as fe}from"./monitor-smartphone-G--2aBuy.js";import{t as pe}from"./unlink-8-ZUzI25.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-B_ik3sNc.js";import{t as J}from"./i18n-DCSomJiP.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-DPvkuJxO.js";import{t as Tt}from"./AdminSectionedPage-DxQ2pH4Y.js";import{t as Et}from"./AdminPage-BjrFg6FM.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-CRE59_h3.js";import{i as en,n as tn,r as nn,t as rn}from"./IntegrationHub-DTFQyFFN.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(L(e))return ne;if(typeof e==`string`&&e.length>0)return e;te(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 F=i(async()=>{await m.invalidateQueries({queryKey:Dn})},[m]),I=u({mutationFn:async e=>p.trpcClient.oidcConnections.deleteConnection.mutate({id:e}),onSuccess:async()=>F()}),L=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 I.mutateAsync(e.id),_.state.mode===`edit`&&_.state.id===e.id&&(_.close(),D.current=null))},[h,I,_,f]),te=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 F(),_.close(),D.current=null}catch(e){x(jn(e))}finally{y(!1)}},[S,N?.id,_,w,F,p]),ne=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(),L(e)},children:d(g,{className:`h-3.5 w-3.5 text-danger`})})]})}],[_,L,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:ne,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:P,width:`xl`,testId:`oidc-connection-editor`,error:b,footer:d(q,{type:`button`,size:`sm`,disabled:v||R&&S.trim()===``,onClick:()=>void te(),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:P,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:P,...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:P,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:P,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=R(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:re.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?F:I,{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(),F=nt({onSuccess:M}),I=ve({onSuccess:M}),L=pt({onSuccess:M}),te=ft({onSuccess:()=>{M(),R(null)}}),[ne,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(),I.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`})&&(F.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`)})&&L.mutate({id:t.id,newPassword:n})}function H(e,t){t!==e.isAdmin&&I.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 I.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||I.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=>F.isPending&&F.variables?.id===e.id||I.isPending&&I.variables?.id===e.id||L.isPending&&L.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(P,{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)}),ne&&d(Vr,{user:ne,onClose:()=>R(null),onSubmit:e=>te.mutate({userId:ne.id,scopes:e}),submitting:te.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=R(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:z(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};
|