@camstack/addon-admin-ui 1.2.469 → 1.2.471

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.
Files changed (138) hide show
  1. package/dist/assets/{AddonAssetIcon-BN_SqLNB.js → AddonAssetIcon-D4joXvAw.js} +1 -1
  2. package/dist/assets/Addons-BNo3Y3g8.js +4 -0
  3. package/dist/assets/{AdminPage-DpgHJ_lQ.js → AdminPage-92KQDOBy.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-BfaO7MK2.js → AdminSectionedPage-B-MH77Vx.js} +1 -1
  5. package/dist/assets/AiProfiles-CTHbBMUB.js +3 -0
  6. package/dist/assets/{BrokerForm-CR-FYodQ.js → BrokerForm-HjHrcv-P.js} +1 -1
  7. package/dist/assets/Build-Dlf7sJhk.js +40 -0
  8. package/dist/assets/Calendars-YnCFbUE7.js +1 -0
  9. package/dist/assets/Cluster-C4BsKola.js +1 -0
  10. package/dist/assets/CompositionCreateForm-D_Nmi2nG.js +1 -0
  11. package/dist/assets/{CompositionEditorPage-Bi49T0M9.js → CompositionEditorPage-CdJtfEi1.js} +1 -1
  12. package/dist/assets/Data-DkPbjXNV.js +2 -0
  13. package/dist/assets/DeviceDetail-BSWf6l6J.js +2 -0
  14. package/dist/assets/{DeviceDoActionFields-Dj3iwIxJ.js → DeviceDoActionFields-B7UlBxQ0.js} +1 -1
  15. package/dist/assets/{Devices-b30LmB9b.js → Devices-BAfbzc8b.js} +1 -1
  16. package/dist/assets/{EmbedPlayerPage-ChjJRAKP.js → EmbedPlayerPage-CZM7W_SR.js} +1 -1
  17. package/dist/assets/History-BfD8lMf9.js +1 -0
  18. package/dist/assets/Identity-6QdzCJrT.js +1 -0
  19. package/dist/assets/IntegrationDetail-B4X-8vcl.js +1 -0
  20. package/dist/assets/IntegrationHub-DCSIyXBI.js +1 -0
  21. package/dist/assets/Integrations-JcvhEroF.js +1 -0
  22. package/dist/assets/Integrations-XcsYTI2I.js +1 -0
  23. package/dist/assets/{Library-BMuv5B5Y.js → Library-X3g7Mvql.js} +1 -1
  24. package/dist/assets/Locations-C--r0_cW.js +3 -0
  25. package/dist/assets/{Logs-DOCwfH5l.js → Logs-C7Z3D9TY.js} +1 -1
  26. package/dist/assets/{MaskShapeCanvas-CC7FQGtr.js → MaskShapeCanvas-wRO0Yeyg.js} +1 -1
  27. package/dist/assets/{MotionZonesSettings-dcIXFXNn.js → MotionZonesSettings-C8wTUqjQ.js} +1 -1
  28. package/dist/assets/{MyAccess-BAfQ0omi.js → MyAccess-Di7tv0VI.js} +1 -1
  29. package/dist/assets/{Network-CMwPBd3q.js → Network-3FZdyZoe.js} +1 -1
  30. package/dist/assets/NodeAddonsSettingsPanel-ivhHs40k.js +1 -0
  31. package/dist/assets/Notifications-D4LJlejx.js +1 -0
  32. package/dist/assets/{Pipeline-UmUovK0W.js → Pipeline-BMhn1YbR.js} +1 -1
  33. package/dist/assets/{PrivacyMaskSettings-CreIjx4O.js → PrivacyMaskSettings-DTetXxIV.js} +1 -1
  34. package/dist/assets/Recordings-Ct8JWW27.js +1 -0
  35. package/dist/assets/{ScanNetworkModal-CJo685Vl.js → ScanNetworkModal-DPHdPawS.js} +1 -1
  36. package/dist/assets/{SceneMonitorEditor-Dbzxlt43.js → SceneMonitorEditor-KPTdSp1h.js} +1 -1
  37. package/dist/assets/SessionsList-DrklEq9Z.js +2 -0
  38. package/dist/assets/{Showroom-Bpwjw60m.js → Showroom-2gQYW-h2.js} +1 -1
  39. package/dist/assets/{System-C-jh6PsN.js → System-CDHw7Mcx.js} +1 -1
  40. package/dist/assets/{Terminal-Bu3buJrm.js → Terminal-UXpMvEO1.js} +5 -5
  41. package/dist/assets/{Viewer-BOQnbvad.js → Viewer-ukAW_oJQ.js} +1 -1
  42. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BFYsDhiM.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-KG1b6CPN.js} +1 -1
  43. package/dist/assets/{addon-icons-context-BVn71jKb.js → addon-icons-context-gPkLZQ_G.js} +1 -1
  44. package/dist/assets/{archive-CDQuI03w.js → archive-CxbMF2yZ.js} +1 -1
  45. package/dist/assets/{assignment-candidates-grX3ScPd.js → assignment-candidates-CQGwwSSC.js} +1 -1
  46. package/dist/assets/{authed-media-cSR4diHc.js → authed-media-DpHGiSZS.js} +1 -1
  47. package/dist/assets/{bell-off-hTkIlZL4.js → bell-off-CAN5HeZI.js} +1 -1
  48. package/dist/assets/{board-model-Bj95FOjc.js → board-model-C6IplvmC.js} +1 -1
  49. package/dist/assets/{boxes-0BuMQdjm.js → boxes-BIYyTH0E.js} +1 -1
  50. package/dist/assets/circle-slash-BWtbQj2T.js +1 -0
  51. package/dist/assets/client-BnEPcD6s.js +358 -0
  52. package/dist/assets/{cloud-upload-DYU5_O7N.js → cloud-upload-DvGDSWZB.js} +1 -1
  53. package/dist/assets/crop-CDWciXWB.js +1 -0
  54. package/dist/assets/{device-integration-icon-DNoJ6Lw6.js → device-integration-icon-CRiv1vER.js} +1 -1
  55. package/dist/assets/device-picker-model-DPfjZqVB.js +1 -0
  56. package/dist/assets/{dist-dJmkuSsT.js → dist-BeSobRch.js} +1 -1
  57. package/dist/assets/dist-CMwJjIGP.js +358 -0
  58. package/dist/assets/{eraser-BUbQF_qS.js → eraser-CvXO1d9P.js} +1 -1
  59. package/dist/assets/event-targets-CIffOoYs.js +2 -0
  60. package/dist/assets/{format-DftZhYTz.js → format-Cz7vHmZ6.js} +1 -1
  61. package/dist/assets/{hard-drive-download-DP_8o52c.js → hard-drive-download-xDn3u92n.js} +1 -1
  62. package/dist/assets/{hostInit-BlSFN2dH.js → hostInit-Bcdd4neZ.js} +1 -1
  63. package/dist/assets/i18n-DsGcRtAk.js +1 -0
  64. package/dist/assets/{icons-Btlc6YJV.js → icons-Uf4a8HzM.js} +1 -1
  65. package/dist/assets/index-CgxpaFwe.js +4 -0
  66. package/dist/assets/{key-Cacr-75P.js → key-D63R1Jty.js} +1 -1
  67. package/dist/assets/{key-round-DCaU9cAg.js → key-round-BH39VAkM.js} +1 -1
  68. package/dist/assets/{layers-pVEq4fg_.js → layers-Cf6Xk9ts.js} +1 -1
  69. package/dist/assets/{linked-devices-model-C91IolQ1.js → linked-devices-model-DYRAb775.js} +1 -1
  70. package/dist/assets/{list-ordered-CNRSuCVQ.js → list-ordered-9heb6Myu.js} +1 -1
  71. package/dist/assets/{location-owned-usage-O8_VY4bA.js → location-owned-usage-DPBYs4L0.js} +1 -1
  72. package/dist/assets/{log-in-RS8mwxfB.js → log-in-D6jMFDmP.js} +1 -1
  73. package/dist/assets/{memory-stick-CInn2SBD.js → memory-stick-thjjQqgp.js} +1 -1
  74. package/dist/assets/{message-square-plus-DtxzVSIY.js → message-square-plus-RcviJHk6.js} +1 -1
  75. package/dist/assets/{mf-entry-bootstrap-0-a3d5bda4.js → mf-entry-bootstrap-0-cbb0c272.js} +2 -2
  76. package/dist/assets/{mic-off-eN_vb8k3.js → mic-off-DvjWBZuR.js} +1 -1
  77. package/dist/assets/{monitor-off-Eo26fk7G.js → monitor-off-DEBUzb17.js} +1 -1
  78. package/dist/assets/{monitor-smartphone-BXr9qaoG.js → monitor-smartphone-rIimQM0r.js} +1 -1
  79. package/dist/assets/mount-DPfjZqVB.js +1 -0
  80. package/dist/assets/{player-overlays-mwQ6DKjG.js → player-overlays-DDFLUcm1.js} +1 -1
  81. package/dist/assets/{recycle-C6G9GLaW.js → recycle-CaQYaqJP.js} +1 -1
  82. package/dist/assets/remoteEntry-DqDbkZhO.js +1 -0
  83. package/dist/assets/{scan-eye-Er9mPgXz.js → scan-eye-BxF3-BiI.js} +1 -1
  84. package/dist/assets/{scissors-iGcQwqM6.js → scissors-DecmVZUv.js} +1 -1
  85. package/dist/assets/{search-x-qRfGpZh7.js → search-x-CiS8b7vy.js} +1 -1
  86. package/dist/assets/{send-goxSirGI.js → send-9ZOtM3uh.js} +1 -1
  87. package/dist/assets/{settings-2-C2T9KfF-.js → settings-2-DVEGaYSK.js} +1 -1
  88. package/dist/assets/{speaker-DTlU5qdL.js → speaker-BLIN7g-W.js} +1 -1
  89. package/dist/assets/src-CWZRb0ia.js +67 -0
  90. package/dist/assets/step-inspector-model-B6Fs3NZo.js +1 -0
  91. package/dist/assets/{timer-reset-LdV1oKRJ.js → timer-reset-ESt9DRwd.js} +1 -1
  92. package/dist/assets/{ungroup-ClPDFNDo.js → ungroup-uBZnvhmn.js} +1 -1
  93. package/dist/assets/{unlink-CCWMkIgh.js → unlink-BK0Zya0K.js} +1 -1
  94. package/dist/assets/{usb-dwGmFjnn.js → usb--Z_ViOoE.js} +1 -1
  95. package/dist/assets/{use-scenes-feed-ByvAQxt_.js → use-scenes-feed-Dpe5Lc_e.js} +1 -1
  96. package/dist/assets/{use-stationary-objects-VkCTU14h.js → use-stationary-objects-D9diuPzc.js} +1 -1
  97. package/dist/assets/useEventInvalidation-DPfjZqVB.js +1 -0
  98. package/dist/assets/{useNodeUrlSelection-DFVjdzBt.js → useNodeUrlSelection-B-NA_JqT.js} +1 -1
  99. package/dist/assets/user-round-D2ADHRLF.js +1 -0
  100. package/dist/assets/{user-x-BtLDt7oR.js → user-x-HmMRNIMy.js} +1 -1
  101. package/dist/assets/{video-DJjbkBZD.js → video-BISLfAY2.js} +1 -1
  102. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-WuGvWsfR.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-w3oA3S6D.js} +2 -2
  103. package/dist/index.html +9 -9
  104. package/dist/server/addon.js +279 -423
  105. package/package.json +10 -1
  106. package/dist/assets/Addons-D4HEweDl.js +0 -4
  107. package/dist/assets/AiProfiles-4iPHownz.js +0 -3
  108. package/dist/assets/Build-CvxS-6Fl.js +0 -40
  109. package/dist/assets/Calendars-BEL2vZe4.js +0 -1
  110. package/dist/assets/Cluster-DNceBwTk.js +0 -1
  111. package/dist/assets/CompositionCreateForm-DRDUGbPO.js +0 -1
  112. package/dist/assets/Data-DNZ19S8x.js +0 -2
  113. package/dist/assets/DeviceDetail-DLdtY5JV.js +0 -2
  114. package/dist/assets/History-CR49b6FJ.js +0 -1
  115. package/dist/assets/Identity-D7lmTPbJ.js +0 -1
  116. package/dist/assets/IntegrationDetail-CWCcdpCz.js +0 -1
  117. package/dist/assets/IntegrationHub-FpZU6jWS.js +0 -1
  118. package/dist/assets/Integrations-DoyxOos9.js +0 -1
  119. package/dist/assets/Integrations-lVBfHk53.js +0 -1
  120. package/dist/assets/Locations-BgcB7ZnK.js +0 -3
  121. package/dist/assets/NodeAddonsSettingsPanel-Ck7AYA-1.js +0 -1
  122. package/dist/assets/Notifications-Bds4p5-3.js +0 -1
  123. package/dist/assets/Recordings-Cb_VFOLV.js +0 -1
  124. package/dist/assets/SessionsList-DgE-51ju.js +0 -2
  125. package/dist/assets/circle-slash-BNZPoK0U.js +0 -1
  126. package/dist/assets/client-CHpTazh3.js +0 -358
  127. package/dist/assets/crop-DOQmDtnO.js +0 -1
  128. package/dist/assets/device-picker-model-DoeAV03f.js +0 -1
  129. package/dist/assets/dist-CVdvfX2T.js +0 -358
  130. package/dist/assets/event-targets-Cfijpphw.js +0 -2
  131. package/dist/assets/i18n-CQ56JIQj.js +0 -1
  132. package/dist/assets/index-BgKj4CM9.js +0 -4
  133. package/dist/assets/mount-DoeAV03f.js +0 -1
  134. package/dist/assets/remoteEntry-BAoznONo.js +0 -1
  135. package/dist/assets/src-B5lceK9L.js +0 -67
  136. package/dist/assets/step-inspector-model-rJIkKDaR.js +0 -1
  137. package/dist/assets/useEventInvalidation-DoeAV03f.js +0 -1
  138. package/dist/assets/user-round-TUECAUsL.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,Si as O,St as k,T as A,V as j,W as ee,Xn as te,Xr as M,Z as ne,Zt as re,_t as N,bn as ie,dn as ae,dt as P,en as F,ht as oe,li as se,lr as I,or as L,ot as R,pi as z,pn as B,q as ce,r as le,sa as ue,t as de,ta as fe,vn as pe,xn as me,yn as V,z as H,zn as he,zr as ge}from"./player-overlays-mwQ6DKjG.js";import{Di as U,Ei as _e,Gt as ve,Jt as W,Kt as ye,Mn as be,Nn as xe,Oi as G,Pn as K,Pr as Se,Qr as Ce,Wt as we,Yt as Te,aa as Ee,ai as De,fi as q,jn as Oe,oa as ke,qt as Ae,u as je,wi as Me}from"./client-CHpTazh3.js";import{t as Ne}from"./archive-CDQuI03w.js";import{i as Pe,n as Fe,r as Ie,t as Le}from"./scan-eye-Er9mPgXz.js";import{t as Re}from"./bell-off-hTkIlZL4.js";import{t as ze}from"./boxes-0BuMQdjm.js";import{n as Be}from"./video-DJjbkBZD.js";import{t as Ve}from"./circle-slash-BNZPoK0U.js";import{t as He}from"./layers-pVEq4fg_.js";import{$a as Ue,$s as We,Aa as Ge,An as Ke,Ba as qe,Ca as Je,Dn as Ye,Dt as Xe,Ea as Ze,Ec as Qe,Eo as $e,Fi as et,Fn as tt,Ft as nt,Gr as J,Gt as rt,Gu as it,Hn as at,Ht as ot,In as st,Ir as ct,It as lt,J as ut,Jc as dt,Jr as ft,Ju as pt,Kn as mt,Kt as ht,L as gt,Lc as _t,Ln as vt,Mc as yt,Mn as bt,Mt as xt,Nn as St,No as Ct,Nt as wt,Oa as Tt,Oc as Et,On as Dt,Pn as Ot,Q as kt,Rr as Y,Rt as At,Sn as jt,Ta as Mt,Tc as Nt,Us as Pt,Ut as Ft,Vn as It,Vt as Lt,Wa as Rt,Wu as zt,Xa as Bt,Xc as Vt,Xt as Ht,Ya as Ut,Yc as Wt,Yt as Gt,Yu as Kt,Z as qt,Zc as Jt,Zs as Yt,Zt as Xt,Zu as Zt,_a as Qt,_t as $t,a as en,ad as tn,an as nn,ar as rn,as as an,bt as on,c as sn,dr as cn,ei as ln,eo as un,et as dn,fa as fn,fr as pn,ga as mn,gc as hn,gr as gn,hn as _n,hr as vn,i as yn,id as bn,io as xn,ir as Sn,jr as Cn,jt as wn,ka as Tn,kn as En,ko as Dn,kt as On,l as kn,lr as An,nd as jn,no as Mn,nt as Nn,o as Pn,ol as Fn,or as In,os as Ln,pa as Rn,po as zn,pr as Bn,q as Vn,qc as Hn,qr as Un,qt as Wn,qu as Gn,r as Kn,ro as qn,rt as Jn,sr as Yn,ss as Xn,ts as Zn,tt as Qn,uo as $n,ur as er,va as tr,wc as nr,xl as rr,xr as ir,xt as ar,yi as or,yn as sr,yo as cr,yr as lr,zt as ur,zu as dr}from"./src-B5lceK9L.js";import{t as X}from"./i18n-CQ56JIQj.js";import{t as Z}from"./useTranslation-D3Is_4B6.js";import"./mount-DoeAV03f.js";import{A as fr,D as pr,E as mr,M as hr,O as gr,ar as _r,cr as vr,dr as yr,er as br,hr as xr,j as Sr,k as Cr,lr as wr,mr as Tr,nr as Er,or as Dr,p as Or,pr as kr,rr as Ar,sr as jr,tr as Mr,ur as Nr}from"./index-BgKj4CM9.js";import{A as Pr,C as Fr,D as Ir,M as Lr,N as Rr,O as zr,P as Br,S as Vr,T as Hr,_ as Ur,a as Wr,b as Gr,c as Kr,d as qr,f as Jr,g as Yr,h as Xr,i as Zr,j as Qr,k as $r,l as ei,m as ti,n as ni,o as ri,p as ii,r as ai,s as oi,t as si,u as ci,v as li,w as ui,x as di,y as fi}from"./event-targets-Cfijpphw.js";import{r as pi,t as mi}from"./assignment-candidates-grX3ScPd.js";import{_ as hi,b as gi,i as _i,m as vi,o as yi,t as bi}from"./step-inspector-model-rJIkKDaR.js";import"./useEventInvalidation-DoeAV03f.js";import{t as xi}from"./use-stationary-objects-VkCTU14h.js";import{n as Si,t as Ci}from"./format-DftZhYTz.js";import{a as wi,i as Ti,n as Ei,o as Di,r as Oi,s as ki,t as Ai}from"./linked-devices-model-C91IolQ1.js";import{t as ji}from"./authed-media-cSR4diHc.js";e();function Mi(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 Ni(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(Mi).filter(e=>e!==null);return n.length===0?null:n}var Pi=[[/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 Fi(e){for(let[t,n]of Pi)if(t.test(e))return n;return`generic`}function Ii(e){let t=e.filter(e=>e.on===!1).map(e=>e.id),n=e.filter(e=>e.on===null).map(e=>e.id),r=t=>t.map(t=>e.find(e=>e.id===t)?.label??t).join(`, `),i=[];return t.length>0&&i.push(X.t(`helpers.cameraSwitchRows.off`,{list:r(t)})),n.length>0&&i.push(X.t(`helpers.cameraSwitchRows.unknown`,{list:r(n)})),{offIds:t,unknownIds:n,summary:i.length===0?X.t(`helpers.cameraSwitchRows.allOn`):i.join(` · `)}}var Li={stream:me,detection:Le,privacy:ge,microphone:te,speaker:k,listening:Fe,archive:Ne,recording:Ie,notifications:T,generic:F};function Ri({deviceId:e}){let{t}=Z(),n=c(),o=Number.isFinite(e),[s,l]=r(null),[u,f]=r(!1),p=Et({deviceId:e},{enabled:o});Kn([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let m=Ni(p.data),h=Jt({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 _=Ii(m),v=e=>s?.id===e.id?s.message:null;return a(Gn,{open:u,onOpenChange:f,children:[a(Kt,{"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(F,{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(pt,{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(zi,{row:e,failure:v(e),onToggle:()=>g(e)})},e.id))})]})]})}function zi({row:e,failure:t,onToggle:n}){let{t:r}=Z(),i=Li[Fi(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 Bi({deviceId:e}){let t=At(R().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 Vi({parentDeviceId:e}){let{t}=Z(),n=kr(),r=R(),{data:i,isLoading:o,isError:s}=Ar(e),{data:c}=Ue({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=wt(c?.stableId??``,l,c?.childLayout),f=u.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>d(wn,{trpc:r.trpcClient,device:{...t,name:ur(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(xt,{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(xt,{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 Hi({deviceId:e}){let t=R(),{data:n,isLoading:r}=Er(e),{data:i,isLoading:a}=Ar(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(Lt,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}e();function Ui({dev:e,busy:t,setBusy:n}){let{t:i}=Z(),o=e?.motionTrigger,s=b(e?.state.motionTrigger),[c,l]=r(!1);if(!o)return null;let u=s?.enabled===!0,f=s!==void 0,p=async()=>{if(t||!f)return;let e=!u;n(!0),l(!0);try{await o.setMotionTrigger({enabled:e})}finally{n(!1),l(!1)}},m=c?u?`Disabling…`:`Enabling…`:f?u?`On motion: on`:`On motion: off`:`On motion: …`;return a(`button`,{type:`button`,onClick:()=>{p()},disabled:t||!f,title:f?u?i(`hero.motionTriggerToggle.disableTriggerOnMotion`,`Disable trigger on motion`):i(`hero.motionTriggerToggle.enableTriggerOnMotion`,`Enable trigger on motion`):i(`hero.motionTriggerToggle.awaitingState`,`Awaiting state…`),"aria-pressed":u,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${u?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground`}`,children:[d(fe,{className:`h-3 w-3`}),d(`span`,{children:m})]})}e();function Q({deviceId:e,deviceType:t,features:n}){let i=R(),o=rt(t)?.HeroCard??ht,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(Ft,{lastChangedAt:p})}):null,d(o,{trpc:i.trpcClient,deviceId:e,features:n}),d(`div`,{className:`flex justify-center`,children:d(Ui,{dev:s,busy:l,setBusy:u})})]})}function Wi({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(Wn,{trpc:R().trpcClient,deviceId:e,features:t})})}function Gi({deviceId:e,features:t}){return d(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:d(ht,{trpc:R().trpcClient,deviceId:e,features:t})})}function Ki(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function qi(e){if(!e)return null;let t=Ki(e.data);return t===null?e.eventType:X.t(`helpers.eventEmitterFormat.buttonHeadline`,{channel:String(t),eventType:e.eventType})}var Ji=1e3,Yi=60*Ji,Xi=60*Yi,Zi=24*Xi;function Qi(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<Ji?X.t(`helpers.relativeTime.justNow`):n<Yi?X.t(`helpers.relativeTime.secondsAgo`,{count:Math.floor(n/Ji)}):n<Xi?X.t(`helpers.relativeTime.minutesAgo`,{count:Math.floor(n/Yi)}):n<Zi?X.t(`helpers.relativeTime.hoursAgo`,{count:Math.floor(n/Xi)}):X.t(`helpers.relativeTime.daysAgo`,{count:Math.floor(n/Zi)})}e();var $i=1500,ea=15e3,ta=1e3;function na({deviceId:e}){let{t:n}=Z(),i=C(R().trpcClient,e)?.state.eventEmitter,o=b(i);t(()=>{if(!i)return;i.refresh();let e=setInterval(()=>{i.refresh()},ea);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)},$i);return()=>{clearTimeout(t)}},[c]);let[h,g]=r(()=>Date.now());t(()=>{let e=setInterval(()=>{g(Date.now())},ta);return()=>{clearInterval(e)}},[]);let _=qi(s),y=o?.eventTypes??[],x=o?.eventCountSinceStart??0,S=o!==void 0,w=Ki(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?Qi(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 ra({deviceName:e,deviceType:t,provider:n,isOnline:r,features:i}){let{t:o}=Z();return a(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface p-6 text-center`,children:[d(vr,{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(Jn,{status:r?`online`:`offline`}),i.length>0&&d(wr,{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 ia({deviceId:e}){let{t}=Z(),r=c(),i=Mt({deviceId:e},{refetchInterval:1e4,retry:!1}),o=Ze({onSuccess:()=>{r.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),r.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),s=n(()=>aa(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(oa,{label:t(`hero.hubHero.discovered`,`Discovered`),value:s.total,icon:d(he,{className:`h-3.5 w-3.5`})}),d(oa,{label:t(`hero.hubHero.adopted`,`Adopted`),value:s.adopted,accent:`success`}),d(oa,{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(L,{className:`h-3.5 w-3.5 animate-spin`}):d(ie,{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(sa,{icon:d(oe,{className:`h-3 w-3 text-emerald-500`}),label:t(`hero.hubHero.online`,`{{online}} online`,{online:s.online})}),d(sa,{icon:d(w,{className:`h-3 w-3 text-amber-500`}),label:t(`hero.hubHero.sleeping`,`{{sleeping}} sleeping`,{sleeping:s.sleeping})}),d(sa,{icon:d(N,{className:`h-3 w-3 text-destructive`}),label:t(`hero.hubHero.offline`,`{{offline}} offline`,{offline:s.offline})}),s.unknown>0?d(sa,{icon:d(se,{className:`h-3 w-3 text-foreground-subtle`}),label:t(`hero.hubHero.unknown`,`{{unknown}} unknown`,{unknown:s.unknown})}):null]})]})}function aa(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 oa({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 sa({icon:e,label:t}){return a(`span`,{className:`inline-flex items-center gap-1`,children:[e,d(`span`,{children:t})]})}var ca={[G.Switch]:Q,[G.Siren]:Q,[G.Light]:Q,[G.Sensor]:Q,[G.Button]:Q,[G.Hub]:ia,[G.Cover]:Wi,[G.Valve]:Q,[G.Humidifier]:Q,[G.WaterHeater]:Q,[G.Container]:Hi,[G.Lock]:Q,[G.Fan]:Q,[G.Thermostat]:Q,[G.Climate]:Q,[G.MediaPlayer]:Q,[G.Control]:Q,[G.AlarmPanel]:Q,[G.EventEmitter]:na,[G.Notifier]:Gi,[G.Script]:Q,[G.Automation]:Q,[G.Presence]:Q,[G.Update]:Q,[G.Vacuum]:Q,[G.LawnMower]:Q,[G.Weather]:Q,[G.Image]:Q,[G.PetFeeder]:Q,[G.Dishwasher]:Q};function la(e){return ca[e]??ra}function ua({deviceId:e}){let t=ce(R().trpcClient,e,e=>e.runningState);return d(En,{running:t===void 0||t.running===null?null:t.running,since:t?.since??null,phase:t?.phase??null,className:`px-3 pt-2 sm:px-4`})}function da(e){let t=la(e.deviceType);return a(s,{children:[d(ua,{deviceId:e.deviceId}),d(t,{...e})]})}function fa({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(Sn,{widgetId:t.widgetId,deviceId:t.deviceId});return d(`div`,{children:t.deviceId===e?n:d(Cn,{deviceId:t.deviceId,children:n})},t.widgetId)})})}function pa(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 ma(e){let t=pa(e),n=new Set(t.map(e=>e.widgetId)),r=e.child===void 0?[]:pa(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 ha(e){return Pn(R().trpcClient,e)}e();function ga(e){let[n,a]=r(`idle`),[o,s]=r(null),c=l(null),u=l(null),d=l(null),f=l(!0),p=Ln(),m=an(),h=Xn(),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 _a=0;function $(){return++_a}function va(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function ya(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 ba(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 xa(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 Sa({scope:e,greeting:n,className:o}){let{t:s}=Z(),c=R(),[f,p]=r(()=>{let t=[];return n&&t.push({id:$(),kind:`info`,text:n}),t.push({id:$(),kind:`info`,text:`scope: ${va(e)} — type help or context for available commands`}),t}),[m,h]=r(``),[g,_]=r([]),[v,y]=r(-1),b=l(null),x=l(null);t(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)},[f]);let S=i(()=>{b.current?.focus()},[]),C=u({mutationFn:t=>c.trpcClient.repl.execute.mutate({code:t,scope:e}),onSuccess:e=>{let t=e??{},n=typeof t.output==`string`?t.output:e==null?`undefined`:typeof e==`string`?e:JSON.stringify(e,null,2),r=t.type===`error`;p(e=>[...e,{id:$(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);p(e=>[...e,{id:$(),kind:`error`,text:t}])}});function w(t){let n=t.trim();if(n){if(n===`clear`){p([{id:$(),kind:`info`,text:`scope: ${va(e)}`}]),h(``);return}if(n===`help`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},...ya(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(n===`context`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},...xa(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}if(n===`examples`){p(t=>[...t,{id:$(),kind:`input`,text:`> ${n}`},...ba(e).map(e=>({id:$(),kind:`info`,text:e}))]),h(``);return}_(e=>[...e,n]),y(-1),p(e=>[...e,{id:$(),kind:`input`,text:`> ${n}`}]),h(``),C.mutate(n)}}function T(t){if(t.key===`Enter`){t.preventDefault(),w(m);return}if(t.key===`ArrowUp`){if(t.preventDefault(),g.length===0)return;let e=v===-1?g.length-1:Math.max(0,v-1);y(e),h(g[e]??``);return}if(t.key===`ArrowDown`){if(t.preventDefault(),v===-1)return;let e=v+1;e>=g.length?(y(-1),h(``)):(y(e),h(g[e]??``));return}t.ctrlKey&&t.key===`l`&&(t.preventDefault(),p([{id:$(),kind:`info`,text:`scope: ${va(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 Ca(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 wa({deviceId:e,intercomAvailable:t=!1}){let r=R(),i=typeof window<`u`?ne():``,a=Number.isFinite(e),o=ha(a?e:null),c=xi(a?[e]:[]),l=n(()=>{if(!a)return;let e=[];for(let t of c.rows){let n=en(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}=_n(r.trpcClient,a?e:null),C=_(a?e:null,{width:ka}),w=ga(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=gn(),A=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,j=Ca(k.request,A),ee=O.length>0?d(s,{children:O.map(e=>d(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return d(Vn,{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:ee,chromeless:!0,className:`h-full`})}function Ta({deviceId:e,containerDeviceId:t}){let{t:n}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full`,children:d(Xt,{...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 Ea({deviceId:e}){let{t}=Z();if(!Number.isFinite(e))return d(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:t(`device.panelContent.notLoaded`,{id:e})});let n=[`CamStack REPL — device #${e}`,``,` device.state.battery.value sync state read`,` await device.snapshot.getSnapshot({}) cap action`,``,` type 'examples' for more, 'context' for the full API`].join(`
2
- `);return d(Sa,{scope:{type:`device`,deviceId:e},greeting:n,className:`h-full border-0 rounded-none`})}function Da({deviceId:e}){let{t}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:d(Ht,{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 Oa({deviceId:e}){let{t}=Z();return Number.isFinite(e)?d(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:d(Gt,{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 ka=960;function Aa(e,t){let{hidden:n,...r}=e??{},i=t?{...r,hidden:!0}:r;return Object.keys(i).length===0?null:i}function ja(e){return typeof e.linkDeviceId==`number`}var Ma=new Set(Object.values(U));function Na(e){return Ma.has(e)}var Pa={[G.Switch]:[U.Siren,U.Floodlight,U.Spotlight,U.PirSensor,U.Chime,U.Autotrack,U.Nightvision,U.PrivacyMask,U.BinaryHelper],[G.Light]:[U.Floodlight,U.Spotlight,U.Nightvision],[G.Siren]:[U.Siren],[G.Button]:[U.Doorbell],[G.Sensor]:[U.MotionSensor,U.ContactSensor,U.LeakSensor,U.SmokeSensor,U.COSensor,U.GasSensor,U.TamperSensor,U.VibrationSensor,U.ConnectivitySensor,U.SoundSensor,U.BinarySensor,U.TemperatureSensor,U.HumiditySensor,U.AmbientLightSensor,U.PressureSensor,U.WindSensor,U.RainSensor,U.UvSensor,U.SolarRadiationSensor,U.SoilMoistureSensor,U.PowerSensor,U.EnergySensor,U.VoltageSensor,U.CurrentSensor,U.AirQualitySensor,U.BatterySensor,U.NumericSensor,U.EnumSensor,U.DateTimeSensor,U.GenericSensor],[G.Control]:[U.NumericControl,U.SelectControl,U.TextControl,U.DateTimeControl],[G.Notifier]:[U.MobilePushNotifier,U.MessagingNotifier,U.EmailNotifier,U.GenericNotifier]};function Fa(e){for(let t of Object.values(G))if(t===e)return!0;return!1}function Ia(e){return Fa(e)?Pa[e]??[]:[]}function La(e,t){let n=Ia(t);return e==null||e===``||n.includes(e)?n:[...n,e]}e();function Ra({device:e}){let{t}=Z(),n=ue(),i=c(),[o,s]=r(null),l=()=>s(null),u={onSuccess:()=>{l(),i.invalidateQueries({queryKey:[[`deviceManager`]]})},onError:e=>s(e.message)},f=$e(),p=cr(),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(Dr,{deviceId:e.id,initialName:e.name,label:t(`customize.identity.name`),layout:`stacked`,onError:s,onSaved:l,onCancel:l}),d(_r,{deviceId:e.id,initialLocation:e.location,label:t(`customize.identity.room`),layout:`stacked`,onError:s,onSaved:l,onCancel:l}),d(jr,{label:t(`customize.identity.hidden`),layout:`stacked`,value:d(vt,{"aria-label":t(`deviceDisplay.hideFromLists`),checked:h,disabled:p.isPending,onChange:t=>p.mutate({deviceId:e.id,display:Aa(e.display,t.target.checked)},u)})}),d(jr,{label:t(`customize.identity.role`),layout:`stacked`,value:ja(e)?d(`span`,{children:za(e.role,t(`customize.identity.noRole`),n)}):d(dr,{"aria-label":t(`customize.identity.role`),value:e.role??``,disabled:f.isPending,options:[{value:``,label:t(`customize.identity.noRole`)},...La(e.role,e.type).map(e=>({value:e,label:za(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 za(e,t,n){return e==null||e===``?t:Na(e)?jn(e,n).label:e}var Ba={binary:`binary`,switch:`switch`};function Va(e){return Object.hasOwn(K,e)}function Ha(e,t){if(!Va(e))return null;let n=K[e].targets.find(e=>e.id===t);return n===void 0||n.cardinality!==`event`?null:n}function Ua(e,t){let n=Ha(e,t);if(n===null)return[];let r=[];for(let e of n.sources){let t=Ba[e.kind];t!==void 0&&r.push(t)}return r}function Wa(e,t){return t.some(t=>e.includes(t))}function Ga(e,t){let n=Me[t]??null;if(n===null)return null;let r=e.caps.find(e=>e.cap===t);return r===void 0?null:r.fields.some(e=>e.path===n)?n:null}function Ka(e,t,n,r){let i=Ha(t,n);if(i===null)return null;let a=qr(e,null).filter(e=>e.kind===`boolean`);for(let t of a){if(ci(i.sources,t)===null)continue;let n=Ga(e,t.cap);if(!(r===`pulse`&&n===null))return{cap:t.cap,fieldPath:t.path,changedAtField:n}}return null}function qa(e,t,n,r){return e.filter(e=>e.id!==t).filter(e=>!Wa(n.get(e.id)??[],r)).map(e=>e.id)}function Ja(e,t){return e.filter(e=>e.id!==t).map(e=>({id:e.id,name:e.name,type:e.type,...e.location===null?{}:{location:e.location}}))}function Ya(e){let t=be({draft:{kind:`pulse`,cap:e.cap,targetId:e.targetId,enabled:e.enabled,debounceMs:e.debounceMs,sources:e.sources.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath}))},device:e.device,changedAtFields:e.sources.map(e=>e.changedAtField)});return t.ok?t.value:null}function Xa(e){let t=xe({draft:{kind:`span`,cap:e.cap,targetId:e.targetId,timeoutMs:e.timeoutMs,...e.cooldownMs===void 0?{}:{cooldownMs:e.cooldownMs},sources:e.sources.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:e.cap,fieldPath:e.fieldPath,mode:e.mode}))},device:e.device});return t.ok?t.value:null}function Za(e,t){return{deviceId:e,config:t.config}}function Qa(e,t){return{deviceId:e,patch:{motionCooldownMs:t}}}async function $a(e,t,n,r){await n(Za(e,t)),await r(Qa(e,t.timeoutMs))}e();function eo(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function to(e){let{t}=Z(),n=e.mode===`change`?t(`customize.scalar.changeTitle`,{title:e.title}):t(`customize.scalar.addTitle`,{title:e.title});return d(rn,{open:e.open,onOpenChange:t=>!t&&e.onClose(),children:a(Yn,{placement:`sheet-on-mobile`,scroll:`body`,"aria-label":n,children:[d(er,{children:d(cn,{children:n})}),e.open?d(no,{...e}):null]})})}function no(e){let{t,i18n:i}=Z(),o=qn({projection:`slim`}),c=o.status===`success`?Gr(o.data):[],[l,u]=r(ao(e.seed,c)),[f,p]=r(e.debounceMs/1e3),m=Mn({deviceId:l?.id??0}),h=Ct({deviceId:l?.id??0}),g=m.status===`success`?m.data:{caps:[]},_=n(()=>Ua(e.cap,e.targetId),[e.cap,e.targetId]),v=Lr(_,e.open),y=n(()=>v.kind===`known`?qa(c,e.host.id,v.value,_):[],[v,c,e.host.id,_]),b=l===null?null:Ka(g,e.cap,e.targetId,`pulse`),x=l===null||b===null||b.changedAtField===null?null:{addonId:l.addonId,stableId:l.stableId,cap:b.cap,fieldPath:b.fieldPath,changedAtField:b.changedAtField},S=x===null?null:Ya({cap:e.cap,targetId:e.targetId,device:e.target,enabled:e.enabled,debounceMs:Math.round(f*1e3),sources:[x]}),C=typeof e.host.location==`string`&&e.host.location.length>0?e.host.location:null,w=io(h.data,x),T=W(ye,w,Math.round(f*1e3));return a(s,{children:[a(In,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:[d(`p`,{className:`text-[11px] text-foreground-muted`,children:t(`customize.event.pulseBody`)}),d(`section`,{className:`flex flex-col gap-1`,"aria-label":t(`customize.scalar.stepDevice`),children:l===null?o.status===`error`?d(lr,{title:t(`customize.picker.devicesFailed`),message:o.error?.message??``}):d(gt,{devices:Ja(c,e.host.id),listState:eo(o.status),value:[],selection:`single`,...C===null?{}:{groupBy:`location`},lockedIds:y,lockedNote:t(`customize.scalar.fit.kind`),onChange:e=>{let t=e[0],n=t===void 0?void 0:c.find(e=>e.id===t);n!==void 0&&u(n)},noun:`device`,showAll:!0,testId:`event-pulse-picker`}):a(`p`,{className:`flex flex-wrap items-center gap-2 text-xs text-foreground`,children:[l.name,d(Y,{variant:`ghost`,size:`sm`,onClick:()=>u(null),children:t(`customize.scalar.changeDevice`)})]})}),l!==null&&b!==null&&d(`p`,{className:`text-xs text-foreground`,children:zr(b.cap,b.fieldPath,i.language)}),l!==null&&b===null&&m.status===`success`&&d(`p`,{className:`text-xs text-foreground-subtle`,children:t(`customize.scalar.fit.kind`)}),a(`label`,{className:`flex flex-col gap-1 text-[11px] text-foreground`,children:[t(`customize.event.debounce`),d(zt,{type:`number`,"aria-label":t(`customize.event.debounce`),value:Number.isFinite(f)?f:0,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>=0&&p(t)}})]}),d(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:t(ro(w,T.lastPressedAt))})]}),a(An,{className:`flex flex-wrap gap-2`,children:[d(Y,{variant:`ghost`,onClick:e.onClose,children:t(`customize.scalar.cancel`)}),d(Y,{"data-testid":`event-save`,disabled:!e.canSave||S===null,onClick:()=>{S!==null&&e.onSave(S)},children:t(`customize.scalar.save`)})]})]})}function ro(e,t){return e.kind===`unread`?`customize.event.previewWaiting`:e.active&&t===null?`customize.event.previewAlreadyOn`:t===null?`customize.event.previewQuiet`:`customize.event.previewCounted`}function io(e,t){if(e===void 0||t===null)return{kind:`unread`};let n=e[t.cap],r=n===void 0?void 0:fi(n,t.fieldPath),i=Me[t.cap]??t.changedAtField,a=n===void 0?void 0:fi(n,i);return typeof r==`boolean`?{kind:`level`,active:r,changedAt:typeof a==`number`&&Number.isFinite(a)?a:null}:{kind:`unread`}}function ao(e,t){return e===null?null:t.find(t=>t.addonId===e.addonId&&t.stableId===e.stableId)??null}function oo(e,t,n){if(e===`pending`)return{kind:`pending`,seconds:null};if(e===`unknown`||e==null)return{kind:`unknown`,seconds:null};if(!e)return{kind:`quiet`,seconds:null};let r=so(t,n);return r===null?{kind:`unknown`,seconds:null}:{kind:`active`,seconds:r}}function so(e,t){if(e==null||!Number.isFinite(e)||e<Ci)return null;let n=Math.floor((t-e)/1e3);return n<0?0:n}function co(e,t){if(e===`pending`)return{kind:`pending`,lastPressedAt:null,pressCount:null};if(e===`unknown`)return{kind:`unknown`,lastPressedAt:null,pressCount:null};let n=typeof e==`number`&&Number.isFinite(e)&&e>=Ci?e:null,r=typeof t==`number`&&Number.isFinite(t)&&t>=0?t:null;return n===null?{kind:`none`,lastPressedAt:null,pressCount:r}:{kind:`ring`,lastPressedAt:n,pressCount:r}}e();function lo({device:e,handle:t,availability:n,cap:i,title:o,view:c}){let{t:l,i18n:u}=Z(),f=di(),[p,m]=r(!1),[h,g]=r(null),_=$r(t.state),v=Vr(_,i),y=fo(t,v),b=y.kind===`known`&&y.value!==null?Oe({feature:y.value,device:t.target,cap:i,targetId:c.id,timestampPath:c.timestampPath,counterPath:c.counterPath}):null,x=b!==null,S=Qr(x),C=b?.draft.sources[0]??null,w=C===null||S.kind!==`known`?null:S.value.find(e=>q({addonId:e.addonId,stableId:e.stableId})===q(C))??null,T=po(x,S.kind,w!==null),E=we({cap:i,targetId:c.id,device:t.target,timestampPath:c.timestampPath,counterPath:c.counterPath,apply:c.apply,stored:y,sourcePresence:T,sourceUnknownReason:S.kind===`unknown`?S.reason:null}),O=t.state.kind===`none`||t.state.kind===`present`;if(n.kind===`absent`||!c.deviceTypes.includes(e.type))return null;let k=async e=>{let n=await t.save(e);g(n.kind===`refused`?n.reason:null)},A=C===null?null:{addonId:C.addonId,stableId:C.stableId,cap:C.cap,fieldPath:C.fieldPath,changedAtField:b?.changedAtFields[0]??``},j=C===null?``:zr(C.cap,C.fieldPath,u.language),ee=y.kind===`known`&&y.value===null,te=!x&&y.kind===`known`&&y.value!==null;return a(s,{children:[d(Br,{id:i,icon:D,title:o,testId:`event-card-${i}`,actions:a(s,{children:[v!==null&&a(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground`,children:[d(vt,{"aria-label":l(`customize.doorbell.active`),checked:v.enabled!==!1,disabled:!O||t.saving,onChange:e=>{k(ui(_,t.target,{...v,enabled:e.target.checked}))}}),l(`customize.doorbell.active`)]}),d(J,{children:l(si(E.text,E.status.state))})]}),children:d(`div`,{className:`flex flex-col gap-2 px-3 py-2 sm:px-4`,children:n.kind===`pending`||n.kind===`present`&&!O?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:l(`customize.event.checking`)}):n.kind===`unknown`?d(lr,{title:l(`customize.scalar.unreadable`),message:n.reason}):a(s,{children:[x&&C!==null&&d(`p`,{className:`text-xs text-foreground`,children:l(`customize.scalar.override`,{name:w?.name??C.stableId,field:j})}),x&&d(uo,{deviceId:e.id,cap:i,timestampPath:c.timestampPath,counterPath:c.counterPath,startedAt:t.state.kind===`present`?t.state.view.block.createdAt:null}),te&&v!==null&&a(`p`,{className:`text-xs text-foreground flex flex-wrap items-center gap-1`,children:[l(`customize.doorbell.otherFormula`),d(Jr,{handle:t,cap:i,fieldPath:c.counterPath})]}),ee&&d(`p`,{className:`text-xs text-foreground-subtle`,children:l(`customize.scalar.noOverride`)}),h!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:h}),a(`div`,{className:`flex flex-wrap gap-2`,children:[x&&d(Y,{variant:`outline`,size:`sm`,disabled:t.saving,onClick:()=>m(!0),children:l(`customize.scalar.change`)}),x&&d(Y,{variant:`ghost`,size:`sm`,disabled:t.saving,onClick:()=>{if(_===null)return;let t=Hr(_,i);f(l(`customize.doorbell.removeWhat`,{name:w?.name??e.name}),t===null).then(e=>{e&&k(t)})},children:l(`customize.scalar.remove`)}),ee&&d(Y,{variant:`outline`,size:`sm`,"data-testid":`event-add-${i}`,disabled:t.saving,onClick:()=>m(!0),children:l(`customize.scalar.add`)})]})]})})}),d(to,{open:p,mode:x?`change`:`add`,title:o,cap:i,targetId:c.id,host:e,target:t.target,enabled:v?.enabled!==!1,debounceMs:b?.draft.debounceMs??c.debounceMs,seed:A,canSave:O&&!t.saving,onClose:()=>m(!1),onSave:e=>{m(!1),k(ui(_,t.target,e))}})]})}function uo({deviceId:e,cap:t,timestampPath:n,counterPath:r,startedAt:i}){let{t:o}=Z(),s=li({deviceId:e,cap:t,path:n}),c=li({deviceId:e,cap:t,path:r}),l=co(s.kind===`pending`?`pending`:s.kind!==`value`||typeof s.value!=`number`?`unknown`:s.value,c.kind===`value`&&typeof c.value==`number`?c.value:null);return l.kind===`pending`?d(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:o(`customize.event.checking`)}):l.kind===`unknown`?d(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:o(`customize.event.doorbellLast.unknown`)}):l.kind===`none`?a(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:[o(`customize.event.doorbellLast.none`,{when:i===null?``:Si(i)}),l.pressCount===null?``:` · ${o(`customize.event.doorbellCount`,{count:l.pressCount})}`]}):a(`p`,{role:`status`,className:`text-[11px] text-foreground`,children:[o(`customize.event.doorbellLast.ring`,{when:Si(l.lastPressedAt)}),l.pressCount===null?``:` · ${o(`customize.event.doorbellCount`,{count:l.pressCount})}`]})}function fo(e,t){return e.state.kind===`pending`?{kind:`pending`}:e.state.kind===`unknown`||e.state.kind===`not-loaded`?{kind:`unknown`,reason:e.state.reason}:{kind:`known`,value:t}}function po(e,t,n){return e?t===`pending`?`pending`:t===`unknown`?`unknown`:n?`present`:`absent`:`present`}e();var mo=[`in-addition`,`confirm`,`replace`];function ho(e){return e===`pending`?`pending`:e===`error`?`failed`:`answered`}function go(e){let{t}=Z(),n=e.mode===`change`?t(`customize.scalar.changeTitle`,{title:e.title}):t(`customize.scalar.addTitle`,{title:e.title});return d(rn,{open:e.open,onOpenChange:t=>!t&&e.onClose(),children:a(Yn,{placement:`sheet-on-mobile`,scroll:`body`,"aria-label":n,children:[d(er,{children:d(cn,{children:n})}),e.open?d(_o,{...e}):null]})})}function _o(e){let{t,i18n:i}=Z(),o=qn({projection:`slim`}),c=o.status===`success`?Gr(o.data):[],[l,u]=r(e.sources),[f,p]=r(null),[m,h]=r(e.timeoutMs/1e3),[g,_]=r((e.cooldownMs??0)/1e3),v=f===null?null:c.find(e=>e.id===f)??null,y=Mn({deviceId:v?.id??0}),b=y.status===`success`?y.data:{caps:[]},x=n(()=>Ua(e.cap,e.targetId),[e.cap,e.targetId]),S=Lr(x,e.open),C=n(()=>S.kind===`known`?qa(c,e.host.id,S.value,x):[],[S,c,e.host.id,x]),w=v===null?null:Ka(b,e.cap,e.targetId,`span`),T=Xa({cap:e.cap,targetId:e.targetId,device:e.target,timeoutMs:Math.round(m*1e3),cooldownMs:e.cooldownMs===null?void 0:Math.round(g*1e3),sources:l}),E=typeof e.host.location==`string`&&e.host.location.length>0?e.host.location:null,D=()=>{if(v===null||w===null||v.addonId===e.host.addonId&&v.stableId===e.host.stableId)return;let t={addonId:v.addonId,stableId:v.stableId,cap:w.cap,fieldPath:w.fieldPath,mode:`in-addition`,label:v.name};if(l.some(e=>e.addonId===t.addonId&&e.stableId===t.stableId)){p(null);return}u([...l,t]),p(null)};return a(s,{children:[a(In,{className:`flex flex-col gap-3 p-2 sm:p-4`,children:[d(`p`,{className:`text-[11px] text-foreground-muted`,children:t(`customize.event.spanBody`)}),d(`ul`,{className:`flex flex-col gap-2`,children:l.map(n=>a(`li`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[d(`span`,{className:`text-foreground`,children:n.label.length>0?n.label:zr(n.cap,n.fieldPath,i.language)}),e.sourceModes.length>1?d(dr,{"aria-label":t(`customize.motion.modeFor`,{name:n.stableId}),value:n.mode,options:e.sourceModes.map(e=>({value:e,label:t(`customize.motion.mode.${e}`)})),onChange:e=>{let t=vo(e.target.value);t!==null&&u(l.map(e=>e.addonId===n.addonId&&e.stableId===n.stableId?{...e,mode:t}:e))}}):null,d(Y,{variant:`ghost`,size:`sm`,onClick:()=>u(l.filter(e=>e.addonId!==n.addonId||e.stableId!==n.stableId)),children:t(`customize.event.clear`)})]},`${n.addonId}/${n.stableId}`))}),o.status===`error`?d(lr,{title:t(`customize.picker.devicesFailed`),message:o.error?.message??``}):d(gt,{devices:Ja(c,e.host.id),listState:ho(o.status),value:f===null?[]:[f],selection:`single`,...E===null?{}:{groupBy:`location`},lockedIds:C,lockedNote:t(`customize.scalar.fit.kind`),onChange:e=>p(e[0]??null),noun:`device`,showAll:!0,testId:`event-span-picker`}),w!==null&&d(`p`,{className:`text-[11px] text-foreground-subtle`,children:zr(w.cap,w.fieldPath,i.language)}),d(Y,{variant:`secondary`,size:`sm`,disabled:w===null,onClick:D,children:t(`customize.motion.add`)}),d(yo,{label:t(`customize.event.timeout`),value:m,onChange:h}),e.cooldownMs!==null&&d(yo,{label:t(`customize.event.cooldown`),value:g,onChange:_}),v!==null&&w!==null&&d(bo,{deviceId:v.id,cap:w.cap,fieldPath:w.fieldPath,timeoutMs:Math.round(m*1e3)})]}),a(An,{className:`flex flex-wrap gap-2`,children:[d(Y,{variant:`ghost`,onClick:e.onClose,children:t(`customize.scalar.cancel`)}),d(Y,{"data-testid":`event-save`,disabled:!e.canSave||T===null,onClick:()=>{T!==null&&e.onSave(T)},children:t(`customize.scalar.save`)})]})]})}function vo(e){return mo.find(t=>t===e)??null}function yo({label:e,value:t,onChange:n}){return a(`label`,{className:`flex flex-col gap-1 text-[11px] text-foreground`,children:[e,d(zt,{type:`number`,"aria-label":e,value:Number.isFinite(t)?t:0,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>=0&&n(t)}})]})}function bo({deviceId:e,cap:t,fieldPath:n,timeoutMs:r}){let{t:i}=Z(),a=li({deviceId:e,cap:t,path:n}),o=a.kind===`value`&&typeof a.value==`boolean`?{kind:`level`,active:a.value,changedAt:null}:{kind:`unread`};return d(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:i(xo(o,Te(Ae,o,{timeoutMs:r,cooldownMs:0,nowMs:Date.now()}).open))})}function xo(e,t){return e.kind===`unread`?`customize.event.previewWaiting`:t?`customize.event.previewMotionOn`:e.active?`customize.event.previewSensorOn`:`customize.event.previewMotionOff`}e();function So({device:e,availability:t,cap:n,title:i,view:o,sensors:c}){let{t:u}=Z(),f=dt(),p=hn(),m=ln({addonId:`pipeline-orchestrator`,deviceId:e.id,nodeId:`hub`}),[h,g]=r(!1),[_,v]=r(null),y=l(!1),[b,x]=r(!1),S=wo(c),C=ve(o.id,S),w=Eo(hi(m.data).motionCooldownMs,o.timeoutMs);if(t.kind===`absent`||!o.deviceTypes.includes(e.type))return null;let T=b||f.isPending||p.isPending,E=C.writable&&!T&&t.kind===`present`,D=async t=>{if(!C.writable||y.current){v(u(`customize.saveInFlight`));return}y.current=!0,x(!0);try{await $a(e.id,t,async e=>{await f.mutateAsync({deviceId:e.deviceId,config:e.config===null?null:{sensors:e.config.sensors.map(e=>({addonId:e.addonId,stableId:e.stableId,mode:e.mode}))}})},async e=>{let t={motionCooldownMs:e.patch.motionCooldownMs};await p.mutateAsync({deviceId:e.deviceId,patch:t})}),v(null),await c.refetch()===`failed`&&v(u(`customize.motion.refetchFailed`))}catch(e){v(e instanceof Error?e.message:String(e))}finally{y.current=!1,x(!1)}},O=C.rows.map(e=>({addonId:e.addonId,stableId:e.stableId,cap:`binary`,fieldPath:`on`,mode:e.mode,label:e.name}));return a(s,{children:[d(Br,{id:n,icon:fe,title:i,testId:`event-card-${n}`,actions:d(J,{children:u(si(C.text,C.status.state))}),children:d(`div`,{className:`flex flex-col gap-2 px-3 py-2 sm:px-4`,children:t.kind===`pending`||S.kind===`pending`?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:u(`customize.motion.reading`)}):t.kind===`unknown`||S.kind===`unknown`?d(lr,{title:u(`customize.motion.unreadable`,{reason:To(S)}),message:S.kind===`unknown`?S.reason??``:``}):a(s,{children:[d(Co,{deviceId:e.id}),C.rows.length===0?d(`p`,{className:`text-xs text-foreground-subtle`,children:u(`customize.scalar.noOverride`)}):d(`ul`,{className:`flex flex-col gap-1`,children:C.rows.map(e=>a(`li`,{className:`text-xs text-foreground`,children:[e.name,e.reason===null?``:` — ${u(`customize.motion.state.${e.state}`)}`]},e.key))}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`customize.event.timeoutSeconds`,{seconds:w/1e3})}),_!==null&&d(`p`,{role:`alert`,className:`text-xs text-danger break-words`,children:_}),d(`div`,{className:`flex flex-wrap gap-2`,children:d(Y,{variant:`outline`,size:`sm`,"data-testid":`event-add-${n}`,disabled:!E,onClick:()=>g(!0),children:C.rows.length===0?u(`customize.scalar.add`):u(`customize.scalar.change`)})})]})})}),d(go,{open:h,mode:C.rows.length===0?`add`:`change`,title:i,cap:n,targetId:o.id,host:e,target:{addonId:e.addonId,stableId:e.stableId},timeoutMs:w,cooldownMs:o.cooldownMs,sourceModes:o.sourceModes,sources:O,canSave:E,onClose:()=>g(!1),onSave:e=>{g(!1),D(e)}})]})}function Co({deviceId:e}){let{t}=Z(),n=li({deviceId:e,cap:`motion`,path:`detected`}),r=li({deviceId:e,cap:`motion`,path:`lastDetectedAt`}),i=oo(n.kind===`pending`?`pending`:n.kind!==`value`||typeof n.value!=`boolean`?`unknown`:n.value,r.kind===`value`&&typeof r.value==`number`?r.value:null,Date.now());return d(`p`,{role:`status`,className:`text-xs text-foreground`,children:t(i.kind===`active`?`customize.event.motionNow.active`:`customize.event.motionNow.${i.kind}`,i.seconds===null?void 0:{seconds:i.seconds})})}function wo(e){return e.presence===`pending`?{kind:`pending`}:e.status===null?{kind:`unknown`,reason:null}:{kind:`known`,value:e.status}}function To(e){return e.kind===`unknown`?e.reason??``:e.kind===`known`&&e.value.state===`unreadable`?e.value.reason:``}function Eo(e,t){return e!==null&&Number.isFinite(e)?e:t}var Do=K;function Oo(e,t){let n=Do[e];return n===void 0?null:n.targets.find(e=>e.id===t)??null}function ko({device:e,handle:t,facts:n,sensors:r}){let{t:i}=Z();return d(s,{children:ni().map(a=>{let o=a.pulse??a.span;if(o===null||!o.deviceTypes.includes(e.type))return null;let s=Oo(a.cap,o.id);if(s===null)return null;let c=i(a.pulse===null?`customize.motion.title`:`customize.doorbell.title`),l=ii(Xr(a.cap,s),n);return a.pulse===null?a.span===null?null:d(So,{device:e,availability:l,cap:a.cap,title:c,view:a.span,sensors:r},a.cap):d(lo,{device:e,handle:t,availability:l,cap:a.cap,title:c,view:a.pulse},a.cap)})})}function Ao({id:e,icon:t,title:n,headerControl:r,addLabel:i,onAdd:o,addDisabled:c=!1,notices:l,suggestion:u,children:f}){let{t:p}=Z(),m=o!==void 0&&i!==void 0;return a(Br,{id:e,icon:t,title:n,actions:a(s,{children:[r,m&&!c&&u!==void 0&&u.count>0&&a(Y,{variant:`ghost`,size:`sm`,onClick:u.onOpen,children:[d(re,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),p(`customize.suggest.hint`,{count:u.count,location:u.location})]}),m&&d(Y,{variant:`outline`,size:`sm`,disabled:c,onClick:o,children:i})]}),children:[l!==void 0&&d(`div`,{className:`flex flex-col gap-1 px-3 pt-2 empty:hidden sm:px-4`,children:l}),d(`ul`,{className:`flex flex-col divide-y divide-border`,children:f})]})}function jo(e,t){if(e.kind!==`known`||typeof t!=`string`||t.length===0)return null;let n=ft(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 Mo(e,t,n){return Un(e,t?.ids??new Set,n)}function No(e,t){return e?.containers.get(t)??null}function Po(e,t,n){return e.kind===`known`?Mo(e.value,t,n).suggested.length:0}function Fo(e,t){let n=[t,e.detail].filter(e=>e!==null&&e!==``);return n.length===0?null:n.join(` · `)}function Io({location:e,devices:t,action:n,onPick:r,onPickAll:i}){let{t:o}=Z();if(t.length===0)return null;let s=o(`customize.suggest.heading`,{location:e});return a(`section`,{"aria-label":s,className:`flex flex-col gap-1`,children:[a(`div`,{className:`flex min-h-7 items-center gap-2`,children:[d(`h3`,{className:`${j} min-w-0 flex-1`,children:s}),i!==void 0&&t.length>1&&d(Y,{variant:`ghost`,size:`sm`,onClick:i,children:o(`customize.suggest.addAll`,{count:t.length})})]}),d(`ul`,{className:`flex flex-col divide-y divide-border rounded-md border border-border`,children:t.map(e=>{let t=Fo(e,e.container===null||e.name.includes(e.container)?null:o(`customize.suggest.in`,{container:e.container}));return a(`li`,{className:`${A} flex items-center gap-3`,children:[a(`div`,{className:`min-w-0 flex-1`,children:[d(`div`,{className:`text-xs text-foreground break-words`,children:e.name}),t!==null&&d(`div`,{className:`text-[11px] text-foreground-subtle break-words`,children:t})]}),d(Y,{variant:`outline`,size:`sm`,"aria-label":o(n===`add`?`customize.suggest.addNamed`:`customize.suggest.useNamed`,{name:e.name}),onClick:()=>r(e.id),children:o(n===`add`?`customize.suggest.add`:`customize.suggest.use`)})]},e.id)})})]})}e();function Lo(e){return e.kind===`pending`?`pending`:e.kind===`unknown`?`failed`:`answered`}function Ro(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 zo({open:e,title:i,selection:o,candidates:s,filters:c,room:l=null,confirmLabel:u,onConfirm:f,onClose:p}){let{t:m}=Z(),[h,g]=r(null),[_,v]=r([]),y=c?.find(e=>e.id===h)??c?.[0]??null,b=s.kind===`known`?s.value:[],x=s.kind===`known`?pi(s.value,``,y):[],S=Mo(b,l,e=>e.deviceId).suggested,C=Mo(x,l,e=>e.deviceId).others,w=n(()=>Ro(C),[C]),T=Lo(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(rn,{open:e,onOpenChange:e=>e?void 0:D(),children:a(Yn,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"aria-label":i,children:[d(er,{children:d(cn,{children:i})}),a(In,{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(Io,{location:l.location,devices:S.map(e=>({id:e.deviceId,name:e.name,container:No(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(gt,{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(An,{children:[d(Y,{variant:`ghost`,onClick:D,children:m(`customize.picker.cancel`)}),d(Y,{disabled:E.length===0,onClick:k,children:u(E.length)})]})]})})}e();function Bo(e,t){let r=typeof e==`string`&&e.length>0,i=Qr(t&&r);return n(()=>t?jo(i,e):null,[t,i,e])}e();function Vo(e){return e==null?null:e.message}function Ho({device:e}){let t=ue(),{t:n}=Z(),i=c(),o=di(),l=Se.includes(e.type),[u,f]=r(!1),[p,m]=r(!1),[h,g]=r(null),_=Tn({deviceId:e.id},{enabled:l}),v=Oi({status:_.status,data:_.data,error:Vo(_.error)===null?null:{message:Vo(_.error)??``}}),y=v.kind===`present`?v.slot.slotRef:``,b=v.kind===`present`?[...Ei(v.slot,v.value).map(e=>e.deviceId),...Ti(v.slot,v.value)]:[],x=Ge(),S=Qr(l&&v.kind===`present`&&(u||b.length>0)),C=Bo(e.location,l&&v.kind===`present`),w=Tt({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(Ao,{id:`linked`,icon:I,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:mi(n.integration,n.location),orphan:t}},k=[...Ei(v.slot,T).map(e=>O(e,!1)),...Ti(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:Vo(w.error)??n(`helpers.customize.requestFailed`)}:S.kind===`pending`||w.status===`pending`||w.data===void 0?{kind:`pending`}:{kind:`known`,value:Ai(w.data.candidates,E,A)},ee=async t=>{if(p){g(n(`customize.saveInFlight`));return}m(!0),g(null);try{await x.mutateAsync({deviceId:e.id,slotRef:v.slot.slotRef,value:t}),await _.refetch(),await i.invalidateQueries({queryKey:[[`deviceManager`]]})}catch(e){g(e instanceof Error?e.message:String(e))}finally{m(!1)}},te=async e=>{await o(n(`customize.linked.removeWhat`,{name:e.name??`#${e.deviceId}`}),!1)&&await ee(ki(T,e.deviceId))},M=[{key:`device`,header:n(`customize.linked.device`),cell:e=>a(`div`,{className:`flex flex-col min-w-0`,children:[d(`span`,{className:`truncate text-xs text-foreground`,children:e.name??`#${e.deviceId}`}),e.detail!==null&&d(`span`,{className:`truncate text-[11px] text-foreground-subtle`,children:e.detail}),e.orphan&&d(`span`,{className:`text-[11px] text-foreground-subtle`,children:n(`customize.linked.notLinked`)}),e.health!==`ok`&&d(`span`,{role:`alert`,className:`text-[11px] text-warning`,children:n(`customize.linked.health.${e.health}`)})]})},{key:`type`,header:n(`customize.linked.type`),headerClassName:`hidden sm:table-cell`,cellClassName:`hidden sm:table-cell text-xs text-foreground-subtle`,cell:e=>e.type===null?`—`:bn(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(st,{checked:e.tracked,disabled:p,"aria-label":n(`customize.linked.trackFor`,{name:e.name??e.deviceId}),onCheckedChange:t=>void ee(Di(T,e.deviceId,t))})}]:[],{key:`remove`,header:``,cellClassName:`text-right w-10`,cell:e=>e.implied||e.orphan?null:d(it,{icon:P,variant:`ghost`,size:`sm`,"aria-label":n(`customize.assign.removeNamed`,{name:e.name??e.deviceId}),disabled:p,onClick:t=>{t.stopPropagation(),te(e)}})}];return a(s,{children:[d(Ao,{id:`linked`,icon:I,title:n(`customize.linked.title`),addLabel:n(`customize.linked.add`),onAdd:p?void 0:()=>f(!0),...C===null?{}:{suggestion:{count:Po(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(Xe,{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:bn(e.type,t).label,columns:M,searchPlaceholder:n(`customize.assign.search`),emptyLabel:n(`customize.assign.none`)}),k.some(e=>!e.orphan)&&d(`p`,{className:`mt-2 text-[10px] text-foreground-subtle`,children:n(`customize.linked.controlsAlways`)}),D&&d(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:n(`customize.linked.trackedHint`)})]})}),d(zo,{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),ee(wi(T,e.map(e=>e.deviceId)))},onClose:()=>f(!1)})]})}e();function Uo(e){return e instanceof Error?e.message:String(e)}function Wo(e){let t=Qt({addonId:e.addonId,stableId:e.stableId}),n=fn(),i=Je(),a=Rn(),o=Pr({status:t.status,data:t.data,error:t.error===null||t.error===void 0?null:{message:t.error.message}}),{t:s}=Z(),c=l(!1),[u,d]=r(!1),f=async e=>{let r=Fr(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:Uo(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 Go=`pipeline-orchestrator`;function Ko(e){return e.status===`pending`?`pending`:e.status===`error`?`unknown`:e.data===void 0?`pending`:e.data.cameraSensors===void 0?`absent`:`present`}function qo(e,t){return e===`absent`?`absent`:Ko(t)}async function Jo(e){try{return(await e()).isError?`failed`:`answered`}catch{return`failed`}}function Yo(e,t){let n=ir(Go),r=Qe({deviceId:e},{enabled:t&&n!==`absent`}),i=()=>Jo(r.refetch);return t?{presence:qo(n,{status:r.status,data:r.data}),status:r.data?.cameraSensors??null,refetch:i}:{presence:`absent`,status:null,refetch:i}}function Xo(e,t){let n=tr({deviceType:e.type}),r=Bt({deviceId:e.id}),i=Mn({deviceId:e.id}),a=Rr(n,e=>new Set(e.caps.map(e=>e.cap))),o=Rr(r,e=>ti(e.entries)),s=Rr(i,e=>e);return{deviceType:e.type,composable:a,nativeCaps:o,wireable:s,composed:new Set((t?.features??[]).map(e=>e.cap))}}function Zo(e,t,n){let r=t.kind===`known`&&t.value.has(`consumables`),i=li(r?{deviceId:e,cap:Wr,path:ri}:null);return oi(t,n,r?i:null)}e();function Qo(e){return Object.hasOwn(K,e)}function $o({device:e,handle:t}){let{t:i}=Z(),[a,o]=r(!1),s=Bt({deviceId:e.id}),c=Qr(a),l=n(()=>c.kind===`known`?new Map(c.value.map(e=>[q({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[c]),u=n(()=>{if(s.data===void 0)return[];let e=[];for(let t of s.data.entries){let n=t.capName,r=Qo(n)?K[n].advancedParameters:[];for(let t of r)e.push({cap:n,param:t})}return e},[s.data]);return u.length===0?null:d(mt,{expanded:a,onExpandedChange:o,header:d(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`customize-advanced-section-header`,children:i(`customize.advancedSection.title`)}),children:d(`div`,{className:`flex flex-col gap-3 p-3 sm:p-4`,children:u.map(({cap:n,param:r})=>d(Ur,{deviceId:e.id,self:t.target,selfName:e.name,cap:n,fieldPath:r.path,label:r.unit===void 0?r.label:`${r.label} (${r.unit})`,unit:r.unit,valueKind:r.kind,handle:t,names:l},`${n}:${r.path}`))})})}e();function es({device:e}){let{t}=Z(),r=e.stableId.startsWith(`composed-`)?e.stableId.slice(De.length):null,i=mn({blockId:r??``},{enabled:r!==null}),o=Je(),s=n(()=>{let e=new Set;for(let{cap:t}of ei())e.add(t);for(let{cap:t}of Zr())e.add(t);for(let{cap:t}of ni())e.add(t);return e},[]);if(r===null)return d(`p`,{className:`text-xs text-foreground-subtle`,children:t(`customize.composed.missingBlock`)});if(i.status===`pending`)return d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.loadingDevice`)});if(i.status===`error`)return d(lr,{title:t(`customize.composed.loadFailed`),message:i.error.message,onRetry:()=>void i.refetch()});if(i.data.state===`not-loaded`)return d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.notLoaded`,{reason:i.data.reason})});let c=i.data.view;if(c===null)return d(`p`,{className:`text-xs text-foreground-subtle`,children:t(`customize.composed.notFound`)});let l=Ce(c.block);if(l===null)return d(`p`,{className:`text-xs text-foreground-subtle`,children:t(`compositionEditor.notComposition`)});let u={target:{addonId:e.addonId,stableId:e.stableId},state:{kind:`present`,view:c,composition:l},saving:o.isPending,save:async e=>{if(e===null)return{kind:`refused`,reason:t(`customize.composed.noDelete`)};try{return await o.mutateAsync({blockId:c.block.id,expectedUpdatedAt:c.block.updatedAt,block:{composition:e}}),await i.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:e instanceof Error?e.message:String(e)}}}};return a(`div`,{className:`flex flex-col gap-3`,children:[d(Ra,{device:e}),Ir(l)===`incomplete`&&d(J,{variant:`warning`,children:t(`customize.blockStatus.incomplete`)}),d(Yr,{device:e,handle:u,skipCaps:s})]})}e();function ts({deviceId:e}){let{t}=Z(),n=Ue({deviceId:e}),r=n.data;return r==null?n.status===`error`?d(lr,{title:t(`customize.deviceUnreadable`),message:n.error?.message??``,onRetry:()=>void n.refetch()}):r===null?d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.noSuchDevice`,{deviceId:e})}):d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.loadingDevice`)}):r.addonId===`composer`?d(es,{device:r}):d(ns,{device:r,target:{addonId:r.addonId,stableId:r.stableId}})}function ns({device:e,target:t}){let r=Wo(t),i=ir(`composer`),{t:o}=Z(),s=Yo(e.id,e.type===G.Camera),c=Xo(e,$r(r.state)),l=Zo(e.id,c.nativeCaps,c.wireable),u={deviceType:e.type,composable:c.composable,nativeCaps:c.nativeCaps,cameraSensors:s.presence},f=n(()=>{let e=new Set;for(let{cap:t}of ei())e.add(t);for(let{cap:t}of Zr())e.add(t);for(let{cap:t}of ni())e.add(t);return e},[]),p=r.state.kind===`none`||r.state.kind===`present`;return a(`div`,{className:`flex flex-col gap-3`,children:[d(Ra,{device:e}),i===`absent`&&d(`p`,{role:`alert`,className:`text-xs text-warning`,children:o(`customize.composerAbsent`)}),r.state.kind!==`none`&&d(rs,{state:r.state}),d(ko,{device:e,handle:r,facts:u,sensors:s}),d(Kr,{device:e,handle:r,facts:u}),d(ai,{device:e,handle:r,facts:u,defaults:l}),d(Yr,{device:e,handle:r,skipCaps:f}),d(Ho,{device:e}),p&&d($o,{device:e,handle:r})]})}function rs({state:e}){let{t}=Z();switch(e.kind){case`pending`:return d(`p`,{role:`status`,className:`text-xs text-foreground-subtle`,children:t(`customize.status.pending`)});case`unknown`:return d(lr,{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(J,{variant:n.status===`running`?`success`:n.status===`failed`?`danger`:`warning`,children:t(`customize.blockStatus.${n.status}`)}),!n.enabled&&d(J,{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})})]})}}}var is=`overview`;function as(e,t){return e.some(e=>e.id===t)?t:is}function os({deviceId:e}){let{t}=Z(),n=c(),r=Number.isFinite(e),{data:i}=Ue({deviceId:e},{enabled:r}),o=typeof i?.type==`string`?i.type:`camera`;Kn([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:s,isLoading:l,isError:u,error:f}=Bt({deviceId:e},{enabled:r}),{data:p}=xn({deviceType:o},{enabled:!!o}),m=Dn({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(ze,{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(ss,{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(cs,{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(ls,{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(Nr,{i18nKey:`device.bindingsTab.boundSummary`,count:_.length,values:{bound:v},components:{b:d(`span`,{className:`font-medium text-foreground`}),em:d(`em`,{})}})}),d(sr,{columns:y,rows:_,rowKey:e=>e.capName,minWidthPx:720})]})}function ss({kind:e}){let{t}=Z();return e===`native`?a(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-success/30 text-success bg-success/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[d(ae,{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(He,{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(I,{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 cs({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 ls({wrappers:e,activeWrapperId:t,disabled:n,onPick:r}){let{t:i}=Z();return e.length===0?d(`span`,{className:`text-[10px] opacity-40`,children:i(`device.bindingsTab.noneAvailable`,`none available`)}):d(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>{let o=e===t;return a(`button`,{disabled:n,onClick:()=>r(e),title:o?i(`device.bindingsTab.clickToDeactivateRevertTo`,`Click to deactivate (revert to native)`):i(`device.bindingsTab.activateWrapper`,`Activate wrapper {{wrapperId}}`,{wrapperId:e}),className:`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px] transition-colors disabled:opacity-50 ${o?`border-primary/40 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[d(o?O:V,{className:`h-3 w-3`}),e]},e)})})}function us({deviceId:e,activeSubTab:t,onSubTabChange:n,deviceType:r,isAdmin:i}){return a(`div`,{className:`flex flex-col gap-3`,children:[Cr(r,i)&&d(Bn,{deviceId:e,readOnly:!0}),d(pr,{deviceId:e,activeSubTab:t,onSubTabChange:n})]})}e();var ds=[[`pipelineOrchestrator`,`getCameraDetectionSource`]];function fs(e){let t=c(),n=nr({deviceId:e},{refetchOnMount:`always`}),a=Hn(),[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:ds})}catch(e){u(e instanceof Error?e.message:`Could not change the root detector`),await t.invalidateQueries({queryKey:ds})}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 ps=`object-detection`;function ms(e){return[e.addonId,...e.children.flatMap(ms)]}function hs(e,t){if(e===`pipeline`)return new Set;let n=gs(t,ps);return n===void 0?new Set:new Set(e===`onboard`?[n.addonId]:ms(n))}function gs(e,t){for(let n of e){if(n.addonId===t)return n;let e=gs(n.children,t);if(e!==void 0)return e}}function _s(e,t){return e===`onboard`?X.t(`helpers.detectionSourceModel.badgeCameraAi`):t===`object-detection`?X.t(`helpers.detectionSourceModel.badgeNoRoot`):X.t(`helpers.detectionSourceModel.badgeIdle`)}function vs(e){switch(e){case`pipeline`:return X.t(`helpers.detectionSourceModel.explainPipeline`);case`onboard`:return X.t(`helpers.detectionSourceModel.explainOnboard`);case`none`:return X.t(`helpers.detectionSourceModel.explainNone`)}}function ys(e){switch(e){case`boxed`:return``;case`while-streaming`:return X.t(`helpers.detectionSourceModel.geometryWhileStreaming`);case`flag-only`:return X.t(`helpers.detectionSourceModel.geometryFlagOnly`);case`unknown`:return X.t(`helpers.detectionSourceModel.geometryUnknown`)}}function bs(e,t){return e===`onboard`?X.t(`helpers.detectionSourceModel.noticeOnboard`):t===`object-detection`?X.t(`helpers.detectionSourceModel.noticeNoRoot`):X.t(`helpers.detectionSourceModel.noticeIdle`)}var xs=[`pl-2`,`pl-6`,`pl-10`,`pl-14`],Ss={detector:`success`,cropper:`info`,classifier:`primary`,refiner:`warning`,"audio-classifier":`neutral`};function Cs(e){return xs[Math.min(e,xs.length-1)]??`pl-2`}function ws(e){return e.zoneDriven?{kind:`zone-driven`}:{kind:`gate`,effectiveOn:e.ownOn,defaultOn:e.defaultOn,explicit:e.choice!==`auto`}}function Ts(e,t,n){return e.kind===`parent`?n:_s(e.source,t)}function Es({inputs:e,outputs:t}){return e.length===0&&t.length===0?null:a(`span`,{className:`inline-flex flex-wrap items-center gap-1`,children:[e.map(e=>d(J,{size:`sm`,variant:`info`,children:e},`in-${e}`)),e.length>0&&t.length>0&&d(`span`,{className:`text-[10px] text-foreground-subtle`,"aria-hidden":!0,children:`→`}),t.map(e=>d(J,{size:`sm`,variant:`success`,children:e},`out-${e}`))]})}function Ds({rows:e,label:t,selectedId:n,busy:r,onOpen:i,onSet:o}){let{t:s}=Z(),c=e=>{switch(e){case`detector`:return s(`device.cameraStepInspector.kindDetector`,`detector`);case`cropper`:return s(`device.cameraStepInspector.kindCropper`,`cropper`);case`classifier`:return s(`device.cameraStepInspector.kindClassifier`,`classifier`);case`refiner`:return s(`device.cameraStepInspector.kindRefiner`,`refiner`);case`audio-classifier`:return s(`device.cameraStepInspector.kindAudio`,`audio`)}},l=s(`device.cameraStepInspector.offBecauseParent`,`Off because its parent is off`);return d(`ul`,{"aria-label":t,className:`divide-y divide-border rounded-md border border-border`,children:e.map(e=>{let t=e.stepId===n,s=e.blocked===null?null:Ts(e.blocked,e.stepId,l);return a(`li`,{"data-step":e.stepId,"data-runs":e.runs?`yes`:`no`,className:`flex flex-wrap items-center gap-x-2 gap-y-1.5 py-2 pr-2 ${Cs(e.depth)} ${t?`bg-primary/10`:e.runs?``:`bg-muted/40`}`,children:[a(`button`,{type:`button`,"aria-expanded":t,onClick:()=>i(e.stepId),className:`flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1 text-left`,children:[d(`span`,{className:`text-sm font-medium ${e.runs?`text-foreground`:`text-foreground-muted`}`,children:e.name}),d(J,{size:`sm`,variant:Ss[e.kind],children:c(e.kind)}),d(Es,{inputs:e.inputs,outputs:e.outputs}),s!==null&&d(`span`,{className:`text-[11px] text-warning`,children:s})]}),d(Nn,{gate:ws(e),busy:r,onSet:t=>o(e.stepId,t)})]},e.stepId)})})}function Os(e,t){let n=e?.[t];return n===void 0?`auto`:n?`on`:`off`}function ks(e,t){return e===`auto`?t:e===`on`}function As(e,t,n){return e!==`onboard`&&e!==`none`||!n.has(t)?null:{kind:`source`,source:e}}function js(e,t,n,r,i){let a=e.zoneDrivenIds??new Set;return t.flatMap(t=>{let o=a.has(t.addonId),s=Os(e.toggles,t.addonId),c=e.defaults[t.addonId]??!0,l=o||ks(s,c),u=r===null?As(e.source,t.addonId,i):{kind:`parent`,ancestorId:r.stepId},d={stepId:t.addonId,name:t.addonName,kind:t.slot,depth:n,inputs:t.inputClasses,outputs:t.outputClasses,choice:s,defaultOn:c,ownOn:l,runs:u===null&&l,blocked:u,zoneDriven:o},f=l?r:{stepId:t.addonId};return[d,...js(e,t.children,n+1,f,i)]})}function Ms(e){let t=e.source===null?new Set:hs(e.source,e.tree);return js(e,e.tree,0,null,t)}function Ns({source:e,geometry:t,saving:n,error:r,onPick:i}){let{t:o}=Z(),s=t===`flag-only`,c=ys(t);return a(`section`,{"aria-label":o(`device.detectionSourceControl.rootDetector`,`Root detector`),"aria-busy":n,className:`space-y-1.5 rounded-md border border-border bg-surface px-3 py-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1.5`,children:[d(`h3`,{className:j,children:o(`device.detectionSourceControl.rootDetector`,`Root detector`)}),d(Qn,{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:H,children:[vs(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 Ps=new Set([`package-detection`]),Fs=`/system/pipeline?view=nodes`;function Is(e){return Object.fromEntries(e.slots.flatMap(e=>e.addons.map(e=>[e.id,e.enabledByDefault??!0])))}function Ls({deviceId:e}){let{t}=Z(),s=ct(),u=Zt(),f=c(),p=R().trpcClient,m=l(null),h=l(null),g=Nt({deviceId:e},{refetchOnMount:`always`}),_=_t(void 0,{refetchOnMount:`always`});Kn([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:v}=tn(),y=n(()=>{let e=new Set((_.data??[]).map(e=>e.nodeId));return v.filter(t=>t.isOnline&&e.has(t.id)).map(e=>({id:e.id,name:e.name}))},[_.data,v]),b=y.map(e=>e.id).join(`,`),x=o({enabled:y.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`camera-step-schemas`,b],queryFn:async()=>{let e={};for(let t of y)try{e[t.id]=await p.pipelineExecutor.getSchema.query({nodeId:t.id})}catch{}return e}}),S=i(()=>{f.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]})},[f]),C=Vt({onSuccess:S}),w=Wt(),[T,E]=r(null),[D,O]=r(!1),[k,A]=r(null),j=fs(e),ee=x.data??{},te=g.data??null,M=y.map(e=>ee[e.id]).find(e=>e!==void 0)??null,ne=n(()=>M?ut(M):[],[M]),re=n(()=>M===null?[]:Ms({tree:ne,toggles:te?.stepToggles,defaults:Is(M),source:j.source,zoneDrivenIds:Ps}),[ne,M,te?.stepToggles,j.source]),{selection:N,open:ie,close:ae}=vi(n(()=>re.map(e=>e.stepId),[re]),[]),F=y[0]?.id,oe=i(async e=>{if(T!==null){if(!await s({title:t(`stepInspector.stepMatrixFrame.discardUnsavedChanges`,`Discard unsaved changes?`),message:t(`stepInspector.stepMatrixFrame.thisStepHasChangesThat`,`This step has changes that are not saved yet.`),confirmLabel:t(`stepInspector.stepMatrixFrame.discard`,`Discard`),variant:`danger`}))return;E(null)}e()},[s,T,t]),se=e=>{e!==N.stepId&&oe(()=>ie({stepId:e}))},I=()=>{oe(()=>ae())};if(_.isLoading||y.length>0&&x.isLoading)return d(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.loadingPipeline`,`Loading pipeline…`)});if(y.length===0)return d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.noPipelineNodeIsOnline`,`No pipeline node is online.`)});if(M===null)return d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:t(`device.cameraStepInspector.catalogUnavailable`,`Catalog unavailable.`)});let L=e=>_.data?.find(e=>e.nodeId===F)?.settings.stepSettings?.[e]??{},z=re.find(e=>e.stepId===N.stepId)??null,B=z===null?null:_i(M,z.stepId),ce=u?d(kt,{onClick:I}):d(it,{icon:P,variant:`ghost`,size:`sm`,"aria-label":t(`common.close`,`Close`),onClick:I});return a(`div`,{ref:m,className:`space-y-2`,children:[j.view?.onboard.available===!0&&j.source!==null&&d(Ns,{source:j.source,geometry:j.view.onboard.geometry,saving:j.saving,error:j.error,onPick:e=>void j.pick(e)}),d(`p`,{className:H,children:d(Nr,{i18nKey:`device.cameraStepInspector.modelsChosenByAccelerators`,components:{nodes:d(yr,{to:Fs,className:`font-medium text-primary hover:underline`})}})}),N.staleStepId!==null&&d(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-1.5 text-[11px] text-warning`,children:t(`stepInspector.stepMatrixFrame.staleStep`,{id:N.staleStepId})}),d(Ds,{rows:re,label:t(`device.cameraStepInspector.detectionStepsOfThisCamera`,`Detection steps of this camera`),selectedId:N.stepId,busy:C.isPending,onOpen:se,onSet:(t,n)=>C.mutate({deviceId:e,addonId:t,enabled:n})}),d(dn,{open:z!==null&&B!==null,anchor:m,onClose:I,label:t(`stepInspector.stepMatrixFrame.stepSettings`,`Step settings`),children:z!==null&&B!==null&&d(Rs,{addon:B,nodeBag:L(z.stepId),storedCamera:te?.stepSettings?.[z.stepId],draft:T?.stepId===z.stepId?T:null,saving:D,status:k,notice:z.blocked?.kind===`source`?bs(z.blocked.source,z.stepId):null,closeButton:ce,onEscape:I,headingRef:e=>{h.current=e},onDraft:e=>{A(null),E({stepId:z.stepId,camera:e})},onDiscard:()=>E(null),onSave:async n=>{O(!0);try{await w.mutateAsync({deviceId:e,addonId:z.stepId,settings:Object.keys(n).length>0?{...n}:null}),E(null),A({kind:`saved`})}catch(e){A({kind:`error`,error:e instanceof Error?e.message:t(`device.cameraStepInspector.saveFailed`)})}finally{O(!1),S()}}})})]})}function Rs({addon:e,nodeBag:t,storedCamera:n,draft:r,saving:i,status:o,notice:s,closeButton:c,onEscape:l,headingRef:u,onDraft:f,onDiscard:p,onSave:m}){let{t:h}=Z(),g=It(e),_=bi(g),v=yi(g),y=r?.camera??n,b=r!==null&&!je(r.camera,n??{});return d(qt,{ref:u,title:h(`device.cameraStepInspector.thisCamera`,`{{name}} · this camera`,{name:e.name}),subtitle:e.slot,leading:c,onEscape:l,..._.length>0?{saveBar:{dirtyCount:+!!b,saving:i,status:o?.kind??null,...o?.error===void 0?{}:{error:o.error},onSave:()=>void m(r?.camera??n??{}),onDiscard:p,scope:d(`p`,{className:H,children:h(`device.cameraStepInspector.appliesToAllAcceleratorsOf`,`Applies to: all accelerators of this camera.`)})}}:{},children:a(`div`,{className:`space-y-3`,children:[s!==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:s}),_.length>0?d(zs,{addon:e,fields:_,nodeBag:t,cameraBag:y,onChange:f}):d(`p`,{className:H,children:h(`device.cameraStepInspector.noCameraSettings`,`This step has no settings on this camera.`)}),v&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`accelerator-only-thresholds`,children:h(`device.cameraStepInspector.thresholdsAreTheAccelerators`,`Confidence thresholds belong to the model, so they are set on the accelerator that runs it (Pipeline → Nodes), not per camera.`)})]})})}function zs({addon:e,fields:t,nodeBag:n,cameraBag:r,onChange:i}){let{t:a}=Z();return d(at,{addon:e,fields:t,layers:{node:n,...r===void 0?{}:{camera:r}},target:`camera`,labels:{camera:a(`device.cameraStepInspector.layerCamera`,`This camera`),node:a(`device.cameraStepInspector.layerNode`,`Node`)},modelId:e.defaultModelId,onChangeLayer:i})}function Bs(e,t,n){return{id:e,get label(){return X.t(t)},icon:n}}var Vs=[Bs(`object-detection`,`helpers.detectionSettingsGroups.objectDetection`,`scan-search`),Bs(`tracking`,`helpers.detectionSettingsGroups.tracking`,`route`),Bs(`motion`,`helpers.detectionSettingsGroups.motion`,`activity`),Bs(`stationary`,`helpers.detectionSettingsGroups.stationary`,`square-parking`),Bs(`zones`,`helpers.detectionSettingsGroups.zones`,`shapes`),Bs(`audio`,`helpers.detectionSettingsGroups.audio`,`volume-2`),Bs(`cluster`,`helpers.detectionSettingsGroups.cluster`,`server`)],Hs={"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 Us(e){return Hs[e]??`object-detection`}e();var Ws=`steps`,Gs=`settings`,Ks=new Set([Ws,Gs]);function qs(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function Js({deviceId:e,activeSubTab:t,onSubTabChange:n}){let{t:r}=Z();return a(bt,{value:t&&Ks.has(t)?t:Ws,onValueChange:i(e=>{n?.(e)},[n]),className:`flex flex-col`,children:[a(Ot,{className:`flex-shrink-0`,children:[d(tt,{value:Ws,children:r(`device.detectionPipelineTab.steps`,`Steps`)}),d(tt,{value:Gs,children:r(`device.detectionPipelineTab.settings`,`Settings`)})]}),d(St,{value:Ws,children:d(Ls,{deviceId:e})}),d(St,{value:Gs,children:d(pr,{deviceId:e,sectionFilter:qs,subTabGrouping:{groupOf:e=>Us(e.id),tabs:Vs}})})]})}var Ys=`Notifications`,Xs={i18nKey:`device.deviceNotificationMute.cameraCostWhenOff`,text:`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`},Zs={i18nKey:`device.deviceNotificationMute.deviceCostWhenOff`,text:`This device never notifies — no rule, no target, no alarm.`};function Qs(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:Ys,on:r===null?null:i??r,available:r!==null,costWhenOff:e.isCamera?Xs:Zs}}function $s(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}e();function ec(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function tc({deviceId:e,isCamera:t}){let{t:n}=Z(),o=c(),s=Number.isFinite(e),[l,u]=r(null),[f,p]=r(null),m=Qs({mutedDeviceIds:ec(Yt({},{enabled:s}).data),deviceId:e,isCamera:t,pendingOn:f}),h=n(m.costWhenOff.i18nKey,m.costWhenOff.text),g=We({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=$s(m,e);t!==null&&(p(!t.muted),g.mutate(t))},[e,g,m]),v=m.on===null,y=m.on===!1,b=y?Re: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 nc(e,t){return{switchId:e,label:Ee[e].label,detail:t===void 0||t.length===0?null:t}}function rc(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 ic(e){let t=rc(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>nc(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>nc(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 ac(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 oc({deviceId:e,deviceName:t}){let{t:i}=Z(),o=ct(),[s,c]=r(null),l=qn({isCamera:!0,projection:`slim`}),u=$n(),f=l.data!==void 0,p=n(()=>l.data===void 0?[]:ac(l.data,e),[l.data,e]),m=p.find(e=>e.id===s)??null,h=u.data===void 0?null:ic(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(Pe,{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(sc,{report:h})]})}function sc({report:e}){let{t}=Z(),n=e.verdict===`quiet`;return a(`div`,{className:`mt-3 space-y-2 border-t border-border pt-3`,children:[d(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`deviceMigrate.swapped`,`The replacement now answers on number {{inheritedId}}; the old camera was handed number {{retiredId}}.`,{inheritedId:e.inheritedId,retiredId:e.retiredId})}),n?a(`div`,{className:`flex items-start gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2`,children:[d(z,{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(Ve,{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 cc({deviceId:e}){let{t}=Z(),[n,i]=r(null),o=qe({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(ie,{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 lc(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function uc({device:e}){let{t}=Z(),n=kr(),r=typeof e.id==`number`?e.id:null,i=String(e.type??``),o=i===G.Camera,s=i===G.Hub,c=e.features??[],l=c.includes(_e.Resyncable),{data:u}=Pt({deviceId:r??0},{enabled:r!==null&&o,refetchInterval:5e3}),f=u?.streams??{},p=Object.entries(f),m=c.includes(_e.DoorbellButton),h=yn(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(ar,{deviceId:r,onOpenChild:e=>n(`/devices/${e}`)}),l&&r!==null&&d(cc,{deviceId:r}),o&&r!==null&&d(oc,{deviceId:r,deviceName:String(e.name??``)}),r!==null&&d(tc,{deviceId:r,isCamera:o}),o&&r!==null&&d(Sn,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:r}),m&&d(on,{history:h.history,latestIsFresh:g}),o&&r!==null&&d(Sn,{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(oe,{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(dc,{label:t(`device.overviewTab.nominal`,`Nominal`),value:lc(n.nominalBitrateKbps??0)}),d(dc,{label:t(`device.overviewTab.observed`,`Observed`),value:lc(n.observedBitrateKbps??0)}),d(dc,{label:t(`device.overviewTab.peak`,`Peak`),value:lc(n.peakBitrateKbps??0)}),d(dc,{label:t(`device.overviewTab.packetLoss`,`Packet Loss`),value:`${(n.packetLossPercent??0).toFixed(2)}%`,warning:(n.packetLossPercent??0)>1})]})]},e))})]}),d(Mr,{}),r!==null&&d(mr,{deviceId:r})]})}function dc({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 fc=`history`,pc=[{id:`overview`,labelKey:`helpers.structuralTabs.overview`,cameraOnly:!1,adminOnly:!1},{id:`config`,labelKey:`helpers.structuralTabs.config`,cameraOnly:!1,adminOnly:!1},{id:Or,labelKey:`helpers.structuralTabs.customize`,cameraOnly:!1,adminOnly:!0},{id:fc,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}],mc=new Set([G.Hub,G.Container]);function hc(e,t){let n=e===G.Camera,r=e===void 0||!mc.has(e);return pc.filter(e=>(n||!e.cameraOnly)&&(t||!e.adminOnly)&&(r||e.id!==`history`)).map(({id:e,labelKey:t})=>({id:e,label:X.t(t)}))}function gc({provider:e,integrationId:t,name:n}){let r=kr(),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(vr,{type:e,size:`lg`})})}e();var _c=[{id:`logs`,icon:B,labelKey:`common.logs`},{id:`repl`,icon:Be,labelKey:`deviceDetail.repl`},{id:`events`,icon:T,labelKey:`common.events`},{id:`state`,icon:S,labelKey:`common.state`}];function vc(){let{t:e}=Z(),t=ue(),o=Tr(),u=Number(o.deviceId),f=Number.isFinite(u),p=kr(),m=c(),_=ct(),v=R(),{user:b}=br(),x=b?.isAdmin===!0,[S,C]=xr(),w=S.get(`tab`)??`overview`,T=S.get(`sub`),[E,D]=r(`logs`),O=`device-detail.left-col-width-px`,[k,A]=r(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(O),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),j=l(k);j.current=k;function te(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??k??0,r=Math.max(330,Math.floor(window.innerWidth*.7)),i=e=>{A(Math.max(280,Math.min(r,n+(e.clientX-t))))},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a);let e=j.current;if(e!==null)try{window.localStorage.setItem(O,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:ne,isError:re}=Ue({deviceId:u},{enabled:f,refetchInterval:5e3,retry:1}),{data:N}=un({deviceId:u},{enabled:f}),ae=n(()=>{let e=N?.settings?.sections??[],t=N?.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(hr)&&r.add(fr),[...r].map(e=>e===`export`?{id:e,label:Sr,isAddonContrib:!0}:{id:e,label:ke[e]?.label??e,isAddonContrib:!0})},[N]),P=M,F=String(P?.name??o.deviceId??`Device`),oe=P?.online===!0,se=oe?`online`:`offline`,I=String(P?.addonId??`rtsp`),L=P?.features??[],z=P?.type,B=z===G.Camera,{data:le}=Ar(f?u:0),fe=z===G.Container,me=n(()=>(le??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[le]),V=n(()=>fe?ot(me,typeof P?.linkDeviceId==`number`?P.linkDeviceId:null,typeof P?.primaryChildEntityId==`string`?P.primaryChildEntityId:null)?.id??null:null,[fe,me,P?.linkDeviceId,P?.primaryChildEntityId]),{data:H}=un({deviceId:V??0},{enabled:V!==null}),he=n(()=>{if(V===null)return[];let e=H?.settings?.sections??[],t=H?.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:ke[e]?.label??e,isAddonContrib:!0,childDeviceId:V}))},[V,H]),ge=n(()=>ma({sections:[...N?.settings?.sections??[],...N?.live?.sections??[]],deviceId:u,...V===null?{}:{child:{sections:[...H?.settings?.sections??[],...H?.live?.sections??[]],deviceId:V}}}),[N,H,u,V]),U=typeof P?.parentDeviceId==`number`?P.parentDeviceId:null,{data:ve}=Ue({deviceId:U??0},{enabled:U!==null}),W=Zt(),ye=P?.disabled!==!0,be=n(()=>{let e=N?.settings?.sections??[],t=N?.live?.sections??[];return gr([...e,...t],z,x,N!==void 0)},[N,z,x]),xe=n(()=>{let e=new Set,t=[];for(let n of[...hc(z,x),...ae,...he])n.id===`config`&&!be||e.has(n.id)||(e.add(n.id),t.push(n));return t},[z,x,ae,he,be]),K=n(()=>as(xe,w),[xe,w]),Se=i(e=>{C(t=>{let n=new URLSearchParams(t);e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`);for(let e of gi)n.delete(e);return n},{replace:!0})},[C]),Ce=i(e=>{C(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[C]),we=(le??[]).length>0,Te=n(()=>_c.filter(({featureGate:e})=>!e||L.includes(e)),[L]),{data:Ee}=Zn(void 0),De=n(()=>P?On(P,Ee):null,[P,Ee]),q=De?.kind===`resolved`?De.integration:null,Oe=q===null?De?.kind===`unknown`?e(`deviceDetail.loadingIntegration`):De?.kind===`orphan`?e(`deviceDetail.missingIntegration`):e(`deviceDetail.noIntegration`):q.name,Ae=q!==null&&q.addonId===I?q.name:I,je=zn({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]}),p(q?.id?`/integrations/${q.id}`:`/integrations`)}}),Me=Ut({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ne=Rt({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Pe=rr(),Fe=or({onSuccess:()=>{m.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ie=L.includes(_e.Rebootable),Le=L.includes(_e.BatteryOperated),Re=lt(v.trpcClient,Le&&f?u:null),ze=nt(v.trpcClient,f?u:null),Be=ce(v.trpcClient,f?u:null,e=>e.runningState),Ve=Be===void 0||Be.running===null?null:Be.running,He=bn(z??`unknown`,t).icon,[We,Ge]=r(!1),qe=async()=>{if(!We){Ge(!0);try{let e=F.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await ji(`${ee}/${String(u)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Ge(!1)}}},Je=Me.isPending||Ne.isPending,{data:Xe}=yt({deviceId:u},{enabled:f&&B,refetchInterval:1e4}),Ze=Xe?.agentNodeId??null,Qe=typeof Ze==`string`&&Ze.length>0&&!Ze.startsWith(`addon:`)?Ze:void 0,{data:$e}=Fn({deviceId:u,...Qe?{nodeId:Qe}:{}},{enabled:f&&B,refetchInterval:3e3,retry:!1}),{data:tt}=et({deviceId:u},{enabled:f&&B,refetchInterval:3e3,retry:!1}),J=tt?.level?.dbfs??null;function rt(){if(!f)return null;switch(K){case`overview`:return d(uc,{device:P??{}});case`config`:return d(us,{deviceId:u,activeSubTab:T,onSubTabChange:Ce,deviceType:z,isAdmin:x});case`detection-pipeline`:return d(Js,{deviceId:u,activeSubTab:T,onSubTabChange:Ce});case`bindings`:return d(os,{deviceId:u});case fc:return d(kn,{deviceId:u,onNavigate:e=>p(e)});case Or:return d(ts,{deviceId:u});default:{let e=K,t=ae.some(t=>t.id===e),n=he.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??u;if(e===`export`)return d(pr,{deviceId:u,sectionFilter:hr,activeSubTab:T,onSubTabChange:Ce});let i=d(pr,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:T,onSubTabChange:Ce});return n!==void 0&&r!==u?d(Cn,{deviceId:r,children:i}):i}}}return f?ne?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`})})]}):re||!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(Nr,{i18nKey:`deviceDetail.noDeviceWithId`,values:{id:u},components:{code:d(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`})}})}),d(`button`,{onClick:()=>p(`/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(jt,{items:[{label:e(`deviceDetail.integrations`,`Integrations`),onClick:()=>p(`/integrations`)},q===null?{label:Oe}:{label:Oe,onClick:()=>p(`/integrations/${q.id}`)},{label:F}]})}),a(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[q!==null&&d(gc,{provider:q.addonId,integrationId:q.id,name:q.name}),d(Dt,{running:Ve,children:d(He,{className:`h-5 w-5 text-foreground-subtle shrink-0`,"aria-hidden":!0})}),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:F}),d(Jn,{status:se}),Le&&d(Ke,{status:Re,variant:`full`}),d(Ye,{status:ze})]}),U!==null&&ve&&a(`button`,{type:`button`,onClick:()=>p(`/devices/${U}`),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:ve.name}),children:[d(`span`,{children:`↑`}),d(`span`,{className:`truncate`,children:String(ve.name??`Device #${U}`)})]}),d(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:L.length>0&&d(wr,{capabilities:L})})]}),$e&&d(`div`,{className:`hidden lg:flex`,children:d(yc,{metrics:$e,dbfs:J})}),a(`div`,{className:`flex items-center gap-1 shrink-0`,children:[a(`button`,{onClick:async()=>{ye?await _({title:e(`deviceDetail.disable`,`Disable "{{name}}"?`,{name:F}),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`})&&Ne.mutate({deviceId:u}):Me.mutate({deviceId:u})},disabled:Je,title:ye?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 ${ye?`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:Je?e(`deviceDetail.updating`,`Updating…`):ye?e(`deviceDetail.enabled`,`Enabled`):e(`deviceDetail.disabled`,`Disabled`)})]}),d(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),B&&a(s,{children:[d(Ri,{deviceId:u}),d(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),d(Bi,{deviceId:u}),d($t,{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:We,onClick:()=>{qe()}},{id:`reboot`,label:e(`deviceDetail.rebootDevice`,`Reboot device`),description:e(`deviceDetail.cameraGoesOfflineFor30`,`Camera goes offline for ~30 seconds.`),icon:pe,hidden:!Ie,disabled:Pe.isPending,danger:!0,onClick:async()=>{await _({title:e(`deviceDetail.reboot`,`Reboot "{{name}}"?`,{name:F}),message:e(`deviceDetail.theCameraWillGoOffline`,`The camera will go offline for around 30 seconds while the firmware reboots.`),confirmLabel:e(`deviceDetail.reboot2`,`Reboot`),variant:`danger`})&&Pe.mutate({deviceId:u})}},{id:`restart-addon`,label:e(`deviceDetail.restartAddon`,`Restart addon`),description:e(`deviceDetail.bouncesEveryDeviceServedBy`,`Bounces every device served by {{servingAddonLabel}}.`,{servingAddonLabel:Ae}),icon:ie,disabled:Fe.isPending,danger:!0,onClick:async()=>{await _({title:e(`deviceDetail.restart`,`Restart "{{servingAddonLabel}}"?`,{servingAddonLabel:Ae}),message:e(`deviceDetail.restartingTheAddonWillBriefly`,`Restarting the addon will briefly disconnect every device served by it (not just "{{name}}"). Streams will reconnect automatically.`,{name:F}),confirmLabel:e(`deviceDetail.restart2`,`Restart`),variant:`danger`})&&Fe.mutate({addonId:I})}},{id:`delete`,label:e(`deviceDetail.deleteDevice`,`Delete device`),description:e(`deviceDetail.removeTheDeviceAndAll`,`Remove the device and all its settings.`),icon:y,separatorBefore:!0,disabled:je.isPending,danger:!0,onClick:async()=>{await _({title:e(`deviceDetail.delete`,`Delete "{{name}}"?`,{name:F}),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`})&&je.mutate({deviceId:u})}}]})]})]})]}),d(Cn,{deviceId:u,device:P??void 0,children:d(vn,{children:d(pn,{children:d(de,{children:d(sn,{children:a(`main`,{className:W?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[a(`div`,{className:W?`flex flex-col bg-surface`:`${k===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-y-auto`,style:!W&&k!==null?{width:`${String(k)}px`}:void 0,children:[d(`div`,{className:B?`flex-shrink-0 border-b border-border-subtle bg-black`:W?`flex-shrink-0 border-b border-border-subtle bg-surface`:`shrink-0 border-b border-border-subtle bg-surface`,children:B?d(wa,{deviceId:u,intercomAvailable:L.includes(_e.TwoWayAudio)}):a(`div`,{children:[d(da,{deviceId:u,deviceName:F,deviceType:z??`unknown`,provider:I,isOnline:oe,features:L}),d(fa,{deviceId:u,widgets:ge})]})}),B&&ge.length>0&&d(`div`,{className:`flex-shrink-0 border-b border-border-subtle bg-surface pt-3 sm:pt-4`,children:d(fa,{deviceId:u,widgets:ge})}),a(`div`,{className:W?`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:Te.map(({id:t,labelKey:n,icon:r})=>{let i=E===t;return a(`button`,{onClick:()=>D(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:W?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[E===`logs`&&d(Ta,{deviceId:u,containerDeviceId:z===`container`?u:void 0}),E===`repl`&&d(Ea,{deviceId:u}),E===`events`&&d(Da,{deviceId:u}),E===`state`&&d(Oa,{deviceId:u})]})]})]}),!W&&d(`div`,{role:`separator`,"aria-orientation":`vertical`,title:e(`deviceDetail.dragToResize`,`Drag to resize`),onMouseDown:te,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:W?`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:xe.map(e=>{let t=K===e.id;return a(`button`,{onClick:()=>Se(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:W?`p-3 flex flex-col gap-3`:`flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3`,children:[K===`overview`&&we&&d(Vi,{parentDeviceId:u}),rt()]})]})]})})})})})})]}):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(Nr,{i18nKey:`deviceDetail.invalidSegment`,values:{segment:o.deviceId},components:{code:d(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`})}})}),d(`button`,{onClick:()=>p(`/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 yc({metrics:e,dbfs:t}){let n=ue(),{t:r}=Z(),i=nn(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(M,{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(k,{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{vc as DeviceDetailPage};
@@ -1 +0,0 @@
1
- import{$ as e,G as t,J as n,S as r,b as i,i as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{Ci as s,It as c,bn as l,dt as u,hn as d,or as f,ot as p,sa as m,yr as h}from"./player-overlays-mwQ6DKjG.js";import{Oi as g,ar as _}from"./client-CHpTazh3.js";import{A as v,C as y,D as b,E as x,Gr as S,Ir as C,Lr as w,M as T,Ma as E,N as D,O,P as k,Rl as A,Rr as j,S as ee,Sr as M,_ as te,_n as N,_r as P,ad as ne,ar as re,b as F,bn as I,br as L,d as ie,dr as ae,f as oe,h as se,j as ce,ja as le,k as ue,ln as de,lr as fe,m as pe,or as me,ro as R,sr as he,u as ge,un as _e,ur as ve,v as ye,w as be,x as z,xr as xe,yn as B,yr as V}from"./src-B5lceK9L.js";import{t as H}from"./useTranslation-D3Is_4B6.js";import{hr as Se}from"./index-BgKj4CM9.js";import{t as Ce}from"./AdminPage-DpgHJ_lQ.js";e();function U(e,t){return e.scope===``?e.displayName:`${e.displayName} · ${t?.(e)??e.scope}`}function we(e,t,n){let r=[];for(let{device:t,series:i}of e)for(let e of i){let i={subject:{kind:`device`,deviceId:t.id},key:e.key,scope:e.scope};r.push({id:z(i),ref:i,info:e,subjectName:t.name,location:t.location??``,nodeId:``,metric:U(e,n)})}for(let{node:e,series:i}of t)for(let t of i){let i={subject:{kind:`node`,nodeId:e.id},key:t.key,scope:t.scope};r.push({id:z(i),ref:i,info:t,subjectName:e.name,location:``,nodeId:e.id,metric:U(t,n)})}return r}function Te(e){return[e.subjectName,e.location,e.metric,e.info.key,e.info.unit??``,e.nodeId].join(` `)}var Ee=[`energy`,`temperatures`,`nodes`,`storage`],De=new Set([`cap:temperature-sensor.celsius`,`cap:climate-control.currentTemp`]),W=[`addon:metrics-native/node-cpu-percent`,`addon:metrics-native/node-memory-percent`],Oe=`addon:storage-orchestrator/location-used-percent`;function ke(e,t){let n=(e,n)=>{let r=t.filter(e);return F((n?[...r].sort(n):r).map(e=>e.ref))};switch(e){case`energy`:return n(e=>e.ref.subject.kind===`device`&&e.info.key===`derived:energy.kwh`);case`temperatures`:return n(e=>e.ref.subject.kind===`device`&&De.has(e.info.key)&&e.info.scope===``,(e,t)=>e.location.localeCompare(t.location)||e.subjectName.localeCompare(t.subjectName));case`nodes`:return n(e=>e.ref.subject.kind===`node`&&W.includes(e.info.key)&&e.info.scope===``,(e,t)=>W.indexOf(e.info.key)-W.indexOf(t.info.key)||e.subjectName.localeCompare(t.subjectName));case`storage`:return n(e=>e.ref.subject.kind===`node`&&e.info.key===Oe)}}function Ae(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[],i=[],a=[],o=[];for(let t of F(e)){let e=n.get(z(t));if(e===void 0){o.push(t);continue}e.info.key===`derived:energy.kwh`?a.push(e):e.info.kind===`boolean`||e.info.kind===`enum`?i.push(e):r.push(e)}return{lines:r,states:i,energy:a,missing:o}}function G(e){return e.subject.kind===`device`?{deviceId:e.subject.deviceId,key:e.key,scope:e.scope}:{forNodeId:e.subject.nodeId,key:e.key,scope:e.scope}}var K=`history-page`;function q(e){return`${e.subjectName} · ${e.metric}`}function je({part:e,window:n}){let{t:i}=H(),a=m(),c=t(()=>[...e.lines,...e.states,...e.energy],[e]),l=pe(t(()=>c.map(e=>G(e.ref)),[c]),n,!1),u=e=>l.status===`ok`?l.data.current.get(oe(G(e.ref))):void 0,d=e=>{let t=u(e);return t?.ok?t.result:void 0};if(c.length===0)return o(L,{icon:s,title:i(`history.page.emptyTitle`,`Pick series to compare`),description:i(`history.page.emptyHint`,`Choose up to 24 series on the left, or start from a panel above.`)});if(l.status===`error`)return o(V,{title:i(`history.page.readFailed`,`History could not be read`),message:l.error});let f=l.status===`pending`,p=c.map(e=>({c:e,e:u(e)})).filter(e=>e.e?.ok===!1),h=e.lines.map((e,t)=>{let r=d(e),i=b(e.info,r,n.from);return{id:e.id,label:q(e),unit:e.info.unit,colorIndex:t,points:i.points,gapMs:i.gapMs,interpolation:i.held&&r?.resolution===`raw`?`step`:`linear`}}),g=e.states.map((e,t)=>{let r=O(e.info,d(e),n.from,n.to),i=be(e.info.key,a);return{id:e.id,label:q(e),kind:e.info.kind===`boolean`?`boolean`:`enum`,colorIndex:e.info.kind===`boolean`?t:0,states:r.states,segments:r.segments,totals:r.totals,stateLabel:e.info.kind===`boolean`?e=>e===`true`?i.on:i.off:void 0}}),_=e.energy.map(e=>({c:e,...x(d(e))})),v=_[0]?.bucketMs??36e5,y=[...new Set(_.flatMap(e=>e.buckets.map(e=>e.t)))].sort((e,t)=>e-t).map(e=>({t:e,values:_.map(t=>t.buckets.find(t=>t.t===e)?.values[0]??null)}));return r(`div`,{className:`space-y-5 min-w-0`,children:[p.length>0&&o(V,{title:i(`history.page.someFailed`,`Some series could not be read`),message:p.map(e=>`${q(e.c)}: ${e.e.error}`).join(` · `)}),h.length>0&&o(k,{title:i(`history.page.lines`,`Measurements`),series:h,range:n,height:260,syncKey:K,pending:f}),_.length>0&&o(P,{title:i(`history.page.energy`,`Energy`),layers:_.map((e,t)=>({id:e.c.id,label:e.c.subjectName,colorIndex:t})),buckets:y,bucketMs:v,range:n,unit:`kWh`,showTotal:!0,height:160,syncKey:K,pending:f}),g.length>0&&o(D,{title:g.length===1?g[0]?.label??``:i(`history.page.states`,`States`),rows:g,range:n,syncKey:K,pending:f})]})}function Me(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async function Ne(e,t){let n=[];for(let r of Me(e,50))try{let{results:e}=await t(r),i=new Map(e.map(e=>[e.seriesId,e]));for(let e of r)n.push(i.get(e)??{seriesId:e,ok:!1,reason:`not-found`})}catch(e){let t=e instanceof Error?e.message:String(e);for(let e of r)n.push({seriesId:e,ok:!1,reason:`request-failed`,message:t})}return n}function J(e){return e.raw+e[`5m`]+e[`1h`]+e[`1d`]}function Pe(e){return e.reduce((e,t)=>t.ok?{...e,deleted:e.deleted+1,points:e.points+J(t.deleted)}:{...e,refused:e.refused+1},{deleted:0,refused:0,points:0})}function Fe(e,t){let n=new Map(e.map(e=>[e.seriesId,e]));return t.flatMap(e=>{let t=n.get(e.seriesId);return t===void 0?[]:[{series:t,outcome:e}]})}var Y=e=>new Date(e).toLocaleDateString(void 0,{dateStyle:`short`});function X(e,t,n){let r=t.get(e.deviceId);return r===void 0?e.reason===`device-gone`?n(`history.orphans.deviceRemoved`,`#{{id}} (removed)`,{id:e.deviceId}):n(`history.orphans.deviceId`,`#{{id}}`,{id:e.deviceId}):r}function Z(e){let t=e.displayName??e.key;return e.scope===``?t:`${t} · ${e.scope}`}function Q(e,t,n){return{key:`series`,header:n(`history.orphans.colSeries`,`Series`),render:i=>{let a=e(i);return r(`div`,{className:`min-w-0 max-w-[16rem]`,children:[o(`div`,{className:`truncate text-foreground`,title:a.key,children:Z(a)}),o(`div`,{className:`truncate text-[10px] text-foreground-subtle`,children:X(a,t,n)})]})},sortValue:r=>`${X(e(r),t,n)} ${Z(e(r))}`}}var Ie=[`raw`,`5m`,`1h`,`1d`];function Le(e,t){return e===`raw`?t(`history.orphans.colRaw`,`Raw points`):e===`5m`?t(`history.orphans.col5m`,`5 min`):e===`1h`?t(`history.orphans.col1h`,`1 h`):t(`history.orphans.col1d`,`1 day`)}function Re(e,t){return[Q(e=>e,e,t),{key:`reason`,header:t(`history.orphans.colReason`,`Reason`),render:e=>r(`div`,{className:`flex flex-col items-start gap-0.5`,children:[o(S,{variant:e.reason===`device-gone`?`warning`:`neutral`,className:`text-[10px]`,children:e.reason===`device-gone`?t(`history.orphans.deviceGone`,`Device removed`):t(`history.orphans.undeclared`,`No longer declared`)}),e.missingSince!==null&&o(`span`,{className:`text-[10px] text-foreground-subtle`,children:t(`history.orphans.since`,`since {{date}}`,{date:Y(e.missingSince)})})]}),sortValue:e=>e.reason},{key:`span`,header:t(`history.orphans.colSpan`,`Recorded`),render:e=>r(`span`,{className:`tabular-nums text-foreground-muted`,children:[Y(e.firstTs),` → `,Y(e.lastTs)]}),sortValue:e=>e.lastTs},...Ie.map(e=>({key:`rows-${e}`,header:Le(e,t),align:`right`,render:t=>o(`span`,{className:`tabular-nums text-foreground-muted`,children:t.rows[e].toLocaleString()}),sortValue:t=>t.rows[e]}))]}function ze(e,t){if(e.ok)return o(S,{variant:`success`,className:`text-[10px]`,children:t(`history.orphans.deleted`,{count:J(e.deleted),points:J(e.deleted).toLocaleString(),defaultValue_one:`Deleted · {{points}} point`,defaultValue_other:`Deleted · {{points}} points`})});let n=e.reason===`request-failed`?t(`history.orphans.requestFailed`,`Not sent: {{message}}`,{message:e.message}):e.reason===`not-orphan`?t(`history.orphans.refusedNotOrphan`,`Kept: no longer orphan`):e.reason===`not-found`?t(`history.orphans.refusedNotFound`,`Already gone`):t(`history.orphans.refusedFailed`,`The hub could not delete it`);return o(S,{variant:e.reason===`not-found`?`neutral`:`warning`,className:`text-[10px]`,children:n})}function Be(e,t){return[Q(e=>e.series,e,t),{key:`result`,header:t(`history.orphans.colResult`,`Result`),render:e=>ze(e.outcome,t),sortValue:e=>+!e.outcome.ok}]}e();function Ve({open:e,onClose:i,list:a,deviceNames:s,onDelete:u,onRefresh:d,refreshing:p}){let{t:m}=H(),h=C(),[g,_]=n(new Set),[v,y]=n(!1),[b,x]=n([]),S=t(()=>Re(s,m),[s,m]),w=t(()=>Be(s,m),[s,m]),T=t(()=>new Set(a.series.map(e=>String(e.seriesId))),[a.series]),E=[...g].filter(e=>T.has(e)).map(Number),D=Pe(b.map(e=>e.outcome)),O=async()=>{if(await h({title:m(`history.orphans.confirmTitle`,{count:E.length,defaultValue_one:`Delete {{count}} series`,defaultValue_other:`Delete {{count}} series`}),message:m(`history.orphans.confirmMessage`,`Every recorded point of these series is removed from the hub. This cannot be undone.`),confirmLabel:m(`history.orphans.confirmLabel`,`Delete`),variant:`danger`})){y(!0);try{let e=await Ne(E,u);x(Fe(a.series,e)),_(new Set)}finally{y(!1),d()}}};return o(re,{open:e,onOpenChange:e=>!e&&i(),children:r(he,{width:`xl`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`orphan-series-dialog`,children:[o(ve,{children:o(ae,{children:m(`history.orphans.title`,`Series no longer linked to a device`)})}),r(me,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-muted`,children:m(`history.orphans.intro`,`Nothing records into these series any more: their device was removed, or no capability declares them now. Select the ones to delete.`)}),a.truncated&&r(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`orphan-truncated`,children:[o(`p`,{className:`text-xs text-warning`,children:m(`history.orphans.truncated`,`More series are unlinked than are listed here. Delete these, then load the rest.`)}),r(j,{size:`sm`,variant:`outline`,onClick:d,disabled:p,children:[o(l,{className:`h-3 w-3`,"aria-hidden":!0}),m(`history.orphans.loadAgain`,`Load again`)]})]}),b.length>0&&r(`div`,{className:`space-y-2`,"data-testid":`orphan-outcomes`,children:[o(`p`,{className:`text-xs text-foreground`,"aria-live":`polite`,children:m(`history.orphans.summary`,{count:D.deleted,refused:D.refused,points:D.points.toLocaleString(),defaultValue_one:`{{count}} series deleted ({{points}} points), {{refused}} kept.`,defaultValue_other:`{{count}} series deleted ({{points}} points), {{refused}} kept.`})}),o(B,{columns:w,rows:b,rowKey:e=>String(e.series.seriesId),minWidthPx:420,maxBodyHeight:`max-h-[60vh]`,emptyMessage:``})]}),o(B,{columns:S,rows:a.series,rowKey:e=>String(e.seriesId),minWidthPx:760,maxBodyHeight:I,defaultSort:{columnKey:`series`,dir:`asc`},emptyMessage:m(`history.orphans.empty`,`Every series is linked to a device.`),selection:{selected:g,onChange:_,rowLabel:e=>`${Z(e)} — ${X(e,s,m)}`,pageLabel:m(`history.orphans.selectAll`,`Select every listed series`)}})]}),r(fe,{children:[o(`span`,{className:`mr-auto text-[11px] tabular-nums text-foreground`,"aria-live":`polite`,children:m(`history.orphans.selected`,{count:E.length,defaultValue_one:`{{count}} selected`,defaultValue_other:`{{count}} selected`})}),o(j,{variant:`ghost`,size:`sm`,onClick:i,children:m(`history.orphans.close`,`Close`)}),r(j,{variant:`danger`,size:`sm`,disabled:E.length===0||v,onClick:()=>void O(),children:[v?o(f,{className:`h-3 w-3 animate-spin`,"aria-hidden":!0}):o(c,{className:`h-3 w-3`,"aria-hidden":!0}),m(`history.orphans.deleteSelected`,`Delete selected`)]})]})]})})}e();var He=5*6e4;function Ue({enabled:e}){let{t:a}=H(),[s,c]=n(!1),l=E({},{enabled:e,staleTime:He}),u=R({projection:`slim`},{enabled:e}),d=le(),f=t(()=>new Map((u.data??[]).map(e=>[e.id,e.name])),[u.data]),p=e=>d.mutateAsync({seriesIds:[...e]});if(!e||l.status===`pending`)return null;if(l.status===`error`)return o(V,{variant:`warning`,title:a(`history.orphans.checkFailedTitle`,`Could not check for unlinked series`),message:l.error.message,onRetry:()=>void l.refetch()});let m=l.data;if(m.series.length===0&&!s)return null;let h=m.series.length;return r(i,{children:[h>0&&o(V,{variant:`warning`,message:m.truncated?a(`history.orphans.noticeMore`,{count:h,defaultValue_one:`More than {{count}} series are no longer linked to a device.`,defaultValue_other:`More than {{count}} series are no longer linked to a device.`}):a(`history.orphans.notice`,{count:h,defaultValue_one:`{{count}} series is no longer linked to a device.`,defaultValue_other:`{{count}} series are no longer linked to a device.`}),action:o(j,{size:`sm`,variant:`outline`,onClick:()=>c(!0),children:a(`history.orphans.review`,`Review`)})}),o(Ve,{open:s,onClose:()=>c(!1),list:m,deviceNames:f,onDelete:p,onRefresh:()=>void l.refetch(),refreshing:l.isFetching})]})}e();var We=`device`,Ge=`node`;function Ke({catalog:e,selected:n,onChange:i,loading:a}){let{t:s}=H(),c=de(e,{searchText:e=>[Te(e)],facetGroups:[{id:`subject`,value:e=>e.ref.subject.kind===`device`?We:Ge},{id:`room`,value:e=>e.location},{id:`unit`,value:e=>e.info.unit??``}]}),l=t(()=>[{key:`metric`,header:s(`history.picker.series`,`Series`),render:e=>r(`div`,{className:`min-w-0`,children:[o(`div`,{className:`truncate text-foreground`,children:e.metric}),o(`div`,{className:`truncate text-[10px] text-foreground-subtle`,children:e.location===``?e.subjectName:`${e.subjectName} · ${e.location}`})]}),sortValue:e=>`${e.subjectName} ${e.metric}`},{key:`unit`,header:s(`history.picker.unit`,`Unit`),render:e=>o(`span`,{className:`text-foreground-muted`,children:e.info.unit??`—`}),sortValue:e=>e.info.unit??``}],[s]),u=n.size>=24;return r(`div`,{className:`space-y-2 min-w-0`,children:[o(_e,{state:c.state,facets:[],groups:[{...c.groups.find(e=>e.id===`subject`)??{id:`subject`,facets:[],selected:[]},label:s(`history.picker.subject`,`Source`),facetLabel:e=>e===We?s(`history.picker.devices`,`Devices`):s(`history.picker.nodes`,`Nodes`)},{...c.groups.find(e=>e.id===`room`)??{id:`room`,facets:[],selected:[]},label:s(`history.picker.room`,`Room`),facetLabel:e=>e===``?s(`history.picker.noRoom`,`No room`):e},{...c.groups.find(e=>e.id===`unit`)??{id:`unit`,facets:[],selected:[]},label:s(`history.picker.metricType`,`Unit`),facetLabel:e=>e===``?s(`history.picker.noUnit`,`States & counts`):e}],labels:{searchPlaceholder:s(`history.picker.search`,`Search device, room, metric or node…`),searchLabel:s(`history.picker.searchLabel`,`Search series`),facetsLabel:s(`history.picker.facets`,`Filters`),clearLabel:s(`history.picker.clear`,`Clear`)},onSearch:c.setSearch,onToggleFacet:c.toggleFacet,onToggleGroupFacet:c.toggleGroupFacet,onClear:c.clear}),o(`p`,{className:`text-[10px] text-foreground-subtle`,"aria-live":`polite`,children:s(`history.picker.count`,`{{count}} of {{max}} selected`,{count:n.size,max:24})}),o(B,{columns:l,rows:c.rows,rowKey:e=>e.id,maxBodyHeight:I,pageSize:50,defaultSort:{columnKey:`metric`,dir:`asc`},emptyMessage:a?s(`history.picker.loading`,`Reading the series of every device…`):c.active?s(`history.picker.emptyFiltered`,`No series match these filters.`):s(`history.picker.empty`,`Nothing is recorded yet.`),selection:{selected:n,onChange:e=>{let t=[...e].filter(e=>n.has(e)),r=[...e].filter(e=>!n.has(e));i(new Set([...t,...r].slice(0,24)))},isSelectable:e=>n.has(e.id)||!u,rowLabel:e=>`${e.subjectName} · ${e.metric}`,pageLabel:s(`history.picker.selectPage`,`Select every series on this page`)}})]})}e();var qe=new Set([g.Hub,g.Container]),$=5*6e4;function Je(){let{t:e}=H(),n=xe(`device-history`),[i,a]=Se(),c=t(()=>F(i.getAll(`s`).flatMap(e=>{let t=te(e);return t===null?[]:[t]})),[i]),l=i.get(`window`),f=ce(l)?l:`7d`,p=ue(i.get(`range`)),m=(e,t,n)=>{let r=new URLSearchParams;for(let t of F(e))r.append(`s`,ye(t));t!==`7d`&&r.set(`window`,t);let o=n===void 0?i.get(`range`):n;t===`custom`&&o&&r.set(`range`,o),a(r,{replace:!0})},g=Ye(n===`present`),_=T(f,Date.now(),p),b=T(f,ie(Date.now(),_.to-_.from),p),x=t(()=>Ae(c,g.candidates),[c,g.candidates]),S=t(()=>new Set(c.map(z)),[c]),E=ge(),D=w(),O=C(),k=async()=>{let t=await D({title:e(`history.page.saveTitle`,`Save as panel`),label:e(`history.page.saveName`,`Panel name`),confirmLabel:e(`history.page.save`,`Save`)});t===null||t.trim()===``||await E.update(e=>ee(e,{id:`panel-${Date.now().toString(36)}`,name:t.trim().slice(0,80),window:f,selection:[...c]}))},A=async(t,n)=>{await O({title:e(`history.page.deleteTitle`,`Delete panel`),message:e(`history.page.deleteMessage`,`The panel "{{name}}" is removed from your account.`,{name:n}),confirmLabel:e(`history.page.delete`,`Delete`),variant:`danger`})&&await E.update(e=>y(e,t))},P=t=>t===`energy`?e(`history.panels.energy`,`Total energy`):t===`temperatures`?e(`history.panels.temperatures`,`Temperatures by room`):t===`nodes`?e(`history.panels.nodes`,`Cluster nodes`):e(`history.panels.storage`,`Storage locations`);return o(Ce,{icon:s,title:e(`history.page.title`,`History`),subtitle:e(`history.page.subtitle`,`What devices, nodes and storage recorded over time, side by side.`),actions:n===`present`?r(j,{size:`sm`,variant:`outline`,onClick:()=>void k(),disabled:c.length===0||!E.writable,children:[o(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),e(`history.page.saveTitle`,`Save as panel`)]}):void 0,children:n===`pending`?o(M,{className:`h-64 w-full`}):n===`unknown`?o(V,{title:e(`history.page.presenceUnknownTitle`,`Could not reach the hub`),message:e(`history.page.presenceUnknown`,`The hub did not say whether device history is installed. Try again in a moment.`)}):n===`absent`?o(L,{icon:h,title:e(`history.page.absentTitle`,`Device history is not running on this hub`),description:e(`history.page.absent`,`Nothing is recorded until the device-history system addon is enabled.`)}):r(`div`,{className:`space-y-3 sm:space-y-4`,children:[o(Ue,{enabled:n===`present`}),r(`div`,{className:`flex flex-wrap items-center gap-2`,role:`group`,"aria-label":e(`history.page.panels`,`Panels`),children:[Ee.map(e=>o(j,{size:`sm`,variant:`outline`,disabled:g.status!==`ok`,onClick:()=>m(ke(e,g.candidates),f),children:P(e)},e)),E.value.panels.map(t=>r(`span`,{className:`inline-flex items-center`,children:[o(j,{size:`sm`,variant:`secondary`,onClick:()=>m(t.selection,t.window,null),children:t.name}),o(j,{size:`sm`,variant:`ghost`,"aria-label":e(`history.page.deleteNamed`,`Delete panel {{name}}`,{name:t.name}),onClick:()=>void A(t.id,t.name),disabled:!E.writable,children:o(u,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})]},t.id))]}),r(`div`,{className:`grid grid-cols-1 gap-3 sm:gap-4 xl:grid-cols-5`,children:[o(`div`,{className:`min-w-0 xl:col-span-2`,children:o(N,{headingId:`history-picker`,title:e(`history.picker.title`,`Series`),children:o(`div`,{className:`p-2 sm:p-3`,children:g.status===`error`?o(V,{message:g.error}):o(Ke,{catalog:g.candidates,loading:g.status===`pending`,selected:S,onChange:e=>{let t=c.filter(t=>e.has(z(t))),n=g.candidates.filter(t=>e.has(t.id)&&!S.has(t.id)).map(e=>e.ref);m([...t,...n],f)}})})})}),o(`div`,{className:`min-w-0 xl:col-span-3`,children:o(N,{headingId:`history-overlay`,title:e(`history.page.overlay`,`Overlay`),actions:c.length>0?o(j,{size:`sm`,variant:`ghost`,onClick:()=>m([],f),children:e(`history.page.clear`,`Clear`)}):void 0,children:r(`div`,{className:`p-2 sm:p-3 space-y-3 min-w-0`,children:[o(se,{value:f,onChange:e=>m(c,e),custom:p,onCustomChange:e=>m(c,`custom`,v(e))}),g.status===`pending`&&c.length>0?o(M,{className:`h-64 w-full`}):o(je,{part:x,window:b}),x.missing.length>0&&g.status===`ok`&&o(`p`,{className:`text-[11px] text-foreground-subtle`,children:e(`history.page.missing`,{count:x.missing.length,defaultValue_one:`{{count}} selected series is no longer recorded.`,defaultValue_other:`{{count}} selected series are no longer recorded.`})})]})})})]})]})})}function Ye(e){let{t:n}=H(),r=n(`history.picker.wholeFrame`,`Whole frame`),i=p().trpcClient,o=R({projection:`slim`},{enabled:e}),{nodes:s}=ne(),c=t(()=>(o.data??[]).filter(e=>!qe.has(String(e.type))),[o.data]),l=a({queries:c.map(t=>({queryKey:[`device-history`,`listSeries`,t.id],queryFn:()=>i.deviceHistory.listSeries.query({deviceId:t.id}),enabled:e,staleTime:$}))}),u=a({queries:s.map(t=>({queryKey:[`device-history`,`listNodeSeries`,t.id],queryFn:()=>i.deviceHistory.listNodeSeries.query({forNodeId:t.id}),enabled:e,staleTime:$}))}),d=A({},{enabled:e,staleTime:$}),f=t(()=>new Map((d?.data??[]).map(e=>[e.id,e.displayName])),[d?.data]),m=l.map(e=>e.data),h=u.map(e=>e.data),g=t(()=>we(c.flatMap((e,t)=>{let n=m[t];return n===void 0?[]:[{device:{id:e.id,name:e.name,location:e.location??null},series:n}]}),s.flatMap((e,t)=>{let n=h[t];return n===void 0?[]:[{node:{id:e.id,name:e.name},series:n}]}),e=>{if(e.key!==`addon:pipeline-analytics/occupancy`)return f.get(e.scope)??e.scope;let{zoneId:t,className:n}=_(e.scope),i=t===``?r:t;return n===void 0?i:`${i} · ${n}`}),[c,s,f,[...l,...u].map(e=>e.dataUpdatedAt).join(`,`),r]);return o.status===`error`?{status:`error`,error:o.error.message,candidates:[]}:{status:o.status===`pending`||l.some(e=>e.isPending)||u.some(e=>e.isPending)?`pending`:`ok`,error:``,candidates:g}}export{Je as HistoryPage};
@@ -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,sn as N}from"./player-overlays-mwQ6DKjG.js";import{Ai as P,da as F,fa as I,ki as L,o as te,ua as R}from"./client-CHpTazh3.js";import{i as z,n as ne,r as re,t as ie}from"./key-Cacr-75P.js";import{d as ae,l as B,s as oe}from"./video-DJjbkBZD.js";import{t as se}from"./key-round-DCaU9cAg.js";import{t as ce}from"./monitor-smartphone-BXr9qaoG.js";import{t as le}from"./unlink-CCWMkIgh.js";import{Au as ue,Bu as de,Cs as fe,Cu as pe,Du as me,Eu as he,Fn as ge,Gr as V,Hu as _e,In as ve,Ir as H,L as ye,Ln as be,Lr as xe,Mn as Se,Ms as Ce,Mu as we,Nu as Te,Os as Ee,Ou as De,Pn as Oe,Pu as ke,Rn as Ae,Rr as U,Sr as je,Ts as Me,Tu as Ne,Uu as Pe,Vu as Fe,Wu as Ie,_n as Le,ar as Re,bn as ze,br as Be,dn as Ve,dr as He,er as Ue,fn as We,ft as Ge,js as Ke,ju as qe,ku as Je,lr as Ye,mi as Xe,or as Ze,pi as Qe,ro as $e,rr as et,sr as tt,tt as nt,ud as W,ur as rt,ut as it,vn as G,wu as at,yn as ot,yr as K,yt as st,zu as ct}from"./src-B5lceK9L.js";import{t as q}from"./i18n-CQ56JIQj.js";import{t as J}from"./useTranslation-D3Is_4B6.js";import{a as lt,d as ut,dr as dt,er as ft,fr as pt,hr as mt,i as ht,l as gt,pr as _t,ur as vt,x as yt}from"./index-BgKj4CM9.js";import{t as bt}from"./AdminSectionedPage-BfaO7MK2.js";import{t as xt}from"./AdminPage-DpgHJ_lQ.js";import{A as St,C as Ct,D as wt,E as Tt,O as Y,S as Et,T as Dt,a as Ot,b as kt,c as At,d as jt,f as Mt,g as Nt,h as Pt,i as Ft,k as It,l as Lt,m as Rt,n as zt,o as Bt,p as Vt,s as Ht,t as Ut,u as Wt,v as Gt,w as Kt,x as qt,y as Jt}from"./SessionsList-DgE-51ju.js";import{i as Yt,n as Xt,r as Zt,t as Qt}from"./IntegrationHub-FpZU6jWS.js";import{n as $t,t as en}from"./addon-display-names-BkwMrExv.js";e();function tn(){let{t:e}=J(),t=H(),i=W.useUtils(),a=St(),{data:o,isLoading:s}=Je(),c=n(()=>o??[],[o]),l=W.useQueries(e=>c.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),u=W.auth.listLoginMethods.useQuery(),[f,p]=r(null),m=Te({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=>({...Et(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(Y,{notice:It(f),onDismissNotice:()=>{p(null)},id:`external-identities`,title:e(`access.externalIdentitiesSection.signInLinks`,`Sign-in links`),icon:ae,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(Dt,{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:le,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:m.isPending}})})}e();var nn={key:`access.nouns.linkedApp`};function rn(e){if(e.type===`category`){let t=e.target??``;return t===`device`?q.t(`access.linkedAppsSection.allDevices`):q.t(`access.linkedAppsSection.allTarget`,{target:t})}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function an(){let{t:e}=J(),t=H(),i=c(),a=De(),[o,s]=r(null),l=()=>void i.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),u=qe({onSuccess:l,onError:e=>s(`Revoke failed: ${e.message}`)}),f=Tt(nn,l),p=n(()=>(a.data??[]).map(e=>Ct(e,e.scopes.map(rn).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(Y,{notice:It(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(Dt,{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:nn,isSelectable:e=>e.status===`active`||e.status===`revoked`,quickSelect:[{label:e(`access.linkedAppsSection.selectRevoked`,`Select revoked`),match:e=>e.status===`revoked`}]}})})}e();var on={key:`access.nouns.session`};function sn(){let{t:e}=J(),t=H(),i=W.useUtils(),a=St(),o=W.auth.listSessions.useQuery(),[s,c]=r(null),l=()=>void i.auth.listSessions.invalidate(),u=W.auth.revokeSessions.useMutation({onSuccess:l,onError:e=>c(`Sign out failed: ${e.message}`)}),f=Tt(on,l),p=n(()=>(o.data??[]).map(e=>Kt(e,a,{client:e=>Gt(e).label,method:Jt})),[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(Y,{notice:It(s,f.outcome),onDismissNotice:()=>{c(null),f.dismiss()},id:`login-sessions`,title:e(`access.loginSessionsSection.loginSessions`,`Login sessions`),icon:ce,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(Dt,{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:oe,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:on,isSelectable:e=>e.status===`active`}})})}var cn={"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 X(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Z(e,t){let n=X(e,`tokenId`);return X(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function Q(e){return e.filter(e=>e!==null)}function ln(e){let t=X(e,`prefix`);return t===null?null:q.t(`helpers.authAuditWording.prefix`,{prefix:t})}function un(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:q.t(`helpers.authAuditWording.tokenCreated`,{name:Z(n,t)}),details:Q([ln(n),typeof e==`number`?q.t(`helpers.authAuditWording.expires`,{at:kt(e)}):null])}}case`admin-token-used`:{let e=X(n,`path`);return{title:q.t(`helpers.authAuditWording.tokenUsed`,{name:Z(n,t)}),details:Q([ln(n),e===null?null:q.t(`helpers.authAuditWording.call`,{path:e})])}}case`token-minted`:{let e=n.expiresAt;return{title:q.t(`helpers.authAuditWording.tokenMinted`,{name:Z(n,t)}),details:Q([typeof e==`number`?q.t(`helpers.authAuditWording.expires`,{at:kt(e)}):null])}}case`token-revoked`:return{title:q.t(`helpers.authAuditWording.anyTokenRevoked`,{name:Z(n,t)}),details:[]};case`admin-token-revoked`:return{title:q.t(`helpers.authAuditWording.tokenRevoked`,{name:Z(n,t)}),details:Q([ln(n)])};case`credentials-revoked`:{let e=X(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=cn[e],a=i===void 0?`${e}s`:q.t(i);return{title:q.t(`helpers.authAuditWording.bulkRevoked`,{n:typeof t==`number`?String(t):`?`,noun:a}),details:Q([typeof r==`number`&&r>0?q.t(`helpers.authAuditWording.skipped`,{count:r}):null,X(n,`ids`)===null?null:q.t(`helpers.authAuditWording.ids`,{ids:X(n,`ids`)??``})])}}case`second-factor-skipped`:{let e=X(n,`method`),t=X(n,`factors`);return{title:q.t(`helpers.authAuditWording.secondFactorSkipped`),details:Q([e===null?null:q.t(`helpers.authAuditWording.signedInWith`,{method:Jt(e)}),t===null?null:q.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 dn=100;function fn(){let{user:e}=ft();return e?.isAdmin?d(mn,{}):null}function pn(){let{data:e}=Je(),{data:t}=W.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 mn(){let{t:e}=J(),t=W.auth.listAuthAudit.useQuery({limit:dn}),{userNameById:n,tokenNameById:r}=pn(),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:dn})})]}),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(hn,{record:e,userName:e.userId===void 0?null:n.get(e.userId)??e.userId,tokenNameById:r},e.id))})})]})}function hn({record:e,userName:t,tokenNameById:n}){let r=un(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:kt(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`},gn={[$.scopedTokens]:$.tokens,[$.adminTokens]:$.tokens,[$.shareLinks]:$.tokens};function _n(){return[{id:$.loginSessions,label:q.t(`system.access.loginSessions`,`Login sessions`),icon:ce,render:()=>d(sn,{})},{id:$.linkedApps,label:q.t(`system.access.linkedApps`,`Linked apps`),icon:D,render:()=>d(an,{})},{id:$.tokens,label:q.t(`system.access.tokens`,`Tokens`),icon:se,render:({createRequested:e,onCreateConsumed:t})=>d(Pt,{headerOwnsCreate:!0,createRequested:e,onCreateConsumed:t})},{id:$.externalIdentities,label:q.t(`system.access.signInLinks`,`Sign-in links`),icon:ae,render:()=>d(tn,{})},{id:$.audit,label:q.t(`system.access.audit`,`Audit`),icon:j,render:()=>d(fn,{})}]}function vn({createRequested:e=!1,onCreateConsumed:t}){let{t:r}=J(),i=n(()=>_n(),[]),o=Yt({ids:n(()=>i.map(e=>e.id),[i]),answered:!0}),s=_t(),[c]=mt(),l=c.get(`integration`),u=l===null?void 0:gn[l];if(u!==void 0){let e=new URLSearchParams(c);return e.set(`integration`,u),d(pt,{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(Se,{appearance:`pills`,value:f?.id??$.loginSessions,onValueChange:e=>{s(`?${ut(c,e,null,null).toString()}`)},children:d(Oe,{"aria-label":r(`system.access.credentialKinds`,`Credential kinds`),children:i.map(e=>a(ge,{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 yn(e,t){if(e===$.tokens)return a(U,{size:`sm`,type:`button`,"data-testid":`access-new-token`,onClick:t,children:[d(se,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),q.t(`system.access.newToken`,`New token`)]})}function bn(){let[e,t]=r(!1);return{createRequested:e,requestCreate:()=>t(!0),clearCreate:()=>t(!1)}}e();var xn=[`oidcConnections`,`listConnections`],Sn=[`oidcConnections`,`connectionFormSchema`],Cn={displayName:`OpenID Connect`,icon:`shield-check`,issuerUrl:``,clientId:``,clientSecret:``,redirectUri:``,scopes:`openid profile email`,usernameClaim:`preferred_username`},wn=/^[a-z0-9][a-z0-9-]{0,63}$/;function Tn(e){return e instanceof Error?e.message:String(e)}function En(e,t){if(t)return typeof e==`string`&&e.length>0?e:void 0;if(F(e))return R;if(typeof e==`string`&&e.length>0)return e;I(e)}function Dn(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function On({addonId:e}){let{t:f}=J(),p=ee(),m=c(),h=H(),_=it({editKey:`oidcEdit`,newKey:`oidcNew`}),[v,y]=r(!1),[b,x]=r(null),[S,C]=r(``),[w,T]=r({...Cn}),D=l(null),O=o({queryKey:[...xn,e],queryFn:async()=>p.trpcClient.oidcConnections.listConnections.query({})}),k=o({queryKey:Sn,queryFn:async()=>p.trpcClient.oidcConnections.connectionFormSchema.query({})}),A=O.data??[],j=Dn(k.data)?k.data:void 0,M=_.state,P=M.mode===`edit`?A.find(e=>e.id===M.id)??null:null;t(()=>{if(_.state.mode===`edit`&&P!==null){let e=`edit:${P.id}`;if(D.current===e)return;D.current=e,x(null),C(P.id),T(P.formValues===void 0?{...Cn}:{...P.formValues});return}if(_.state.mode===`new`){if(D.current===`new`)return;D.current=`new`,x(null),C(``),T({...Cn})}},[P,_.state]);let F=i(async()=>{await m.invalidateQueries({queryKey:xn})},[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():P?.id??``;if(n&&!wn.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=En(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(Tn(e))}finally{y(!1)}},[S,P?.id,_,w,F,p]),R=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(V,{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(U,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),_.openEdit(e.id)},children:f(`common.edit`,`Edit`)}),d(U,{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]),z=_.state.mode===`new`,ne=z||P!==null,re=z?`new`:P===null?`closed`:`edit:${P.id}:${P.configured?`cfg`:`empty`}`,ie=`/addon/${e}/<id>/callback`;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:ie})]}),a(U,{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(je,{className:`h-32 w-full`}):d(ot,{columns:R,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(Ge,{open:ne,onClose:()=>{_.close(),x(null),D.current=null},title:z?f(`system.oidcSettingsConnections.addOidcConnection`,`Add OIDC connection`):f(`system.oidcSettingsConnections.edit`,`Edit {{value1}}`,{value1:P?.displayName??`connection`}),icon:N,width:`xl`,testId:`oidc-connection-editor`,error:b,footer:d(U,{type:`button`,size:`sm`,disabled:v||z&&S.trim()===``,onClick:()=>void te(),children:v?f(`system.oidcSettingsConnections.saving`,`Saving…`):f(`common.save`,`Save`)}),children:ne?a(s,{children:[z?a(`div`,{children:[d(Ae,{htmlFor:`oidc-connection-id`,children:f(`system.oidcSettingsConnections.instanceId`,`Instance id`)}),d(Ie,{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:P?.id})]}),j===void 0?d(`p`,{className:`text-sm text-foreground-muted`,children:f(`system.oidcSettingsConnections.loadingForm`,`Loading form…`)}):d(Ue,{schema:j,values:w,onChange:T,bare:!0},re)]}):null})]})}e();var kn=3e4,An=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],jn={titleKey:`system.authentication.sectionTitle`,subtitleKey:`system.authentication.sectionSubtitle`,emptyTitleKey:`system.authentication.sectionEmptyTitle`,emptyDescriptionKey:`system.authentication.sectionEmptyDescription`,installLabelKey:`system.authentication.sectionInstall`};function Mn(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:ne,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:B,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:B,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:N,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Nn(){let{t:e}=J(),t=Xe({capName:An[0].capName},{refetchInterval:kn}),r=Xe({capName:An[1].capName},{refetchInterval:kn}),i=Qe(void 0,{refetchInterval:kn}),a=n(()=>en(i.data??[]),[i.data]),o=n(()=>{let e=[],n=[t.data??[],r.data??[]];for(let[t,r]of An.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:An[0].capName,label:e(jn.installLabelKey)},entries:o.map(t=>({id:t.addonId,name:t.displayName,fallbackIcon:N,...$t(t.isActive),render:()=>d(Xt,{addonId:t.addonId,displayName:t.displayName,capName:t.capName,isActive:t.isActive,badges:t.stageBadge===null?null:d(V,{variant:`info`,className:Zt,children:t.stageBadge}),settingsContent:t.addonId.startsWith(`auth-oidc`)?d(On,{addonId:t.addonId}):void 0,panels:[{id:`about`,title:e(`system.authentication.about`,`About`),icon:Mn(t.addonId).icon,content:d(Pn,{addonId:t.addonId})}]})}))}];return d(Qt,{embedded:!0,icon:N,title:e(jn.titleKey),subtitle:e(jn.subtitleKey),groups:s,isLoading:t.isLoading||r.isLoading,emptyTitle:e(jn.emptyTitleKey),emptyDescription:e(jn.emptyDescriptionKey)})}function Pn({addonId:e}){let{t}=J(),n=Mn(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(z,{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(dt,{to:`/system/my-access?tab=sign-in`,className:`underline text-primary`}),users:d(dt,{to:`/system/identity?tab=users`,className:`underline text-primary`})}})})]})]})}function Fn({isPending:e,error:t,what:n,onRetry:r,children:i}){let{t:o}=J();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(K,{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 In(){let{t:e}=J(),t=W.deviceCredentials.getDeviceCaStatus.useQuery({}),n=t.data;return d(Y,{id:`device-ca`,title:e(`certificates.deviceCaCard.deviceCertificateAuthority`,`Device certificate authority`),icon:N,description:e(`certificates.deviceCaCard.signsTheCertificateEachPaired`,`Signs the certificate each paired device holds. It is created the first time a device is paired.`),children:d(Fn,{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(G,{label:e(`certificates.deviceCaCard.state`,`State`),children:[n.state===`ready`&&d(V,{variant:`success`,children:e(`certificates.deviceCaCard.ready`,`Ready`)}),n.state===`absent`&&d(V,{variant:`default`,children:e(`certificates.deviceCaCard.notCreatedYet`,`Not created yet`)}),n.state===`unavailable`&&d(V,{variant:`danger`,children:e(`certificates.deviceCaCard.unavailable`,`Unavailable`)})]}),n.state===`ready`&&a(s,{children:[d(G,{label:e(`certificates.deviceCaCard.subject`,`Subject`),valueClassName:`font-mono`,children:n.subject}),d(G,{label:e(`certificates.deviceCaCard.fingerprintSha256`,`Fingerprint (SHA-256)`),valueClassName:`font-mono`,children:n.fingerprintSha256}),d(G,{label:e(`certificates.deviceCaCard.validUntil`,`Valid until`),children:n.validTo})]}),n.state===`unavailable`&&d(G,{label:e(`certificates.deviceCaCard.reason`,`Reason`),children:d(`span`,{className:`text-danger`,children:n.reason})})]})})})}e();function Ln(){let{t:e}=J(),t=W.useUtils(),n=W.deviceCredentials.getDeviceCertificateSettings.useQuery({}),[i,o]=r(null),s=W.deviceCredentials.setDeviceCertificateSettings.useMutation({onSuccess:()=>{o(null),t.deviceCredentials.getDeviceCertificateSettings.invalidate()},onError:e=>o(`Could not save: ${e.message}`)});return d(Fn,{isPending:n.isPending,error:n.error,what:`the enrollment setting`,onRetry:()=>void n.refetch(),children:n.data!==void 0&&a(G,{label:e(`certificates.deviceSettingsRow.usersCanEnrollTheirOwn`,`Users can enroll their own devices`),actions:d(ve,{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 Rn(e){let[n,i]=r(()=>Date.now());return t(()=>{let t=setInterval(()=>i(Date.now()),e);return()=>clearInterval(t)},[e]),n}e();var zn=80,Bn=208;function Vn({open:e,users:t,onClose:n,onPaired:i}){let{t:o}=J(),s=W.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(Ge,{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(U,{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(U,{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(st,{label:o(`certificates.pairDeviceDialog.user`,`User`),required:!0,children:d(ct,{value:m,onChange:e=>l(e.target.value),options:t.map(e=>({value:e.id,label:e.username}))})}),d(st,{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(Ie,{value:u,maxLength:zn,onChange:e=>p(e.target.value),placeholder:o(`certificates.pairDeviceDialog.annaSIphone`,`Anna's iPhone`),autoFocus:!0})})]}):d(Hn,{enrollUrl:h.enrollUrl,expiresAt:h.expiresAt,hubKnown:h.hubOrigin!==null,onRestart:()=>s.reset()})})}function Hn({enrollUrl:e,expiresAt:t,hubKnown:n,onRestart:r}){let{t:i}=J(),o=Bt(t,Rn(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(et,{value:e,size:Bn,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(Ve,{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(U,{type:`button`,variant:`outline`,size:`sm`,onClick:r,children:i(`certificates.pairDeviceDialog.newCode`,`New code`)})]})]})})}e();var Un={key:`access.nouns.device`};function Wn({pairOpen:e,onPairClose:t}){let{t:i}=J(),o=H(),s=xe(),c=W.useUtils(),l=W.deviceCredentials.listDeviceCredentials.useQuery({includeRevoked:!0}),u=Je(),[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=W.deviceCredentials.revokeDeviceCredential.useMutation({onSuccess:S,onError:x(`Revoke`)}),w=W.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=W.deviceCredentials.renameDeviceCredential.useMutation({onSuccess:S,onError:x(`Rename`)}),E=wt(Un,e=>C.mutateAsync({id:e}),b),D=E.busy||v!==null,O=n(()=>(l.data??[]).map(zt),[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:Ot,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:Ft,onRun:e=>void A(e),busyId:w.isPending?v:null,disabled:D}];return a(Y,{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:It(p,E.outcome),onDismissNotice:()=>{_(null),E.dismiss()},children:[d(Ln,{}),d(Dt,{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:Un,isSelectable:Ot}}),d(Vn,{open:e,users:u.data??[],onClose:t,onPaired:b})]})}var Gn=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/,Kn=/-----BEGIN ((?:RSA |EC |ENCRYPTED )?PRIVATE KEY)-----[\s\S]+?-----END \1-----/,qn={certificate:`.pem,.crt,.cer`,privateKey:`.pem,.key`,ca:`.pem,.crt,.cer`};function Jn(e,t){if(t.trim()===``)return null;if(e===`privateKey`){let e=Kn.exec(t);return e===null?Gn.test(t)?q.t(`helpers.pemFile.isCert`):q.t(`helpers.pemFile.notKey`):e[1]===`ENCRYPTED PRIVATE KEY`?q.t(`helpers.pemFile.encrypted`):null}return Gn.test(t)?e===`certificate`&&Kn.test(t)?q.t(`helpers.pemFile.certHasKey`):null:Kn.test(t)?q.t(`helpers.pemFile.isKey`):q.t(`helpers.pemFile.notCert`)}function Yn(e){return e.text()}e();function Xn({kind:e,label:t,value:n,onChange:i,rows:o=6}){let{t:s}=J(),c=l(null),[u,f]=r(null),[p,m]=r(null),h=p??Jn(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 Yn(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:qn[e],onChange:e=>void _(e),className:`hidden`,"data-testid":`${g}-file`}),a(U,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>c.current?.click(),children:[d(re,{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 Zn=30;function Qn(e){let t=Date.parse(e);return!Number.isNaN(t)&&Date.now()-t<Zn*864e5}function $n(e){if(e===null||e===``)return`—`;let t=e.replace(/:/g,``);return t.length<=16?e:`${t.slice(0,8)}…${t.slice(-8)}`}function er(){let{t:e}=J(),t=c(),n=fe(void 0,{refetchInterval:15e3}),i=Me({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),o=Ee({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),s=Ce({onSuccess:()=>void t.invalidateQueries({queryKey:[[`localNetwork`]]})}),l=Ke({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(Le,{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(K,{variant:`warning`,title:e(`system.localAccess.certificateReissue`,`Certificate reissue`),message:u.reissueError}),u?.restartRequired&&d(K,{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(K,{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&&Qn(u.caReplacedAt)&&d(K,{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:$n(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)`)}):$n(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(We,{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(U,{size:`sm`,variant:`outline`,onClick:()=>m(e=>!e),children:e(`system.localAccess.upload`,`Upload`)}),u?.caCertPem&&d(U,{size:`sm`,variant:`outline`,onClick:S,children:e(`system.localAccess.downloadCa`,`Download CA`)}),u?.mode===`uploaded`&&d(We,{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(We,{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(Xn,{kind:`certificate`,label:e(`system.localAccess.certificateOrFullChainPem`,`Certificate or full chain (PEM)`),value:h,onChange:g}),d(Xn,{kind:`privateKey`,label:e(`system.localAccess.privateKeyPem`,`Private key (PEM)`),value:_,onChange:v}),d(Xn,{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(U,{size:`sm`,disabled:!h.trim()||!_.trim()||Jn(`certificate`,h)!==null||Jn(`privateKey`,_)!==null||Jn(`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 tr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`};function nr(e){let t=e.find(e=>e.isHub);return t?.https.kind===`served`?t.https.status.caFingerprintSha256:null}function rr({https:e,mesh:t,now:n}){let{t:r}=J(),i=fe().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(G,{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:[nr(e)??`—`,i!==``&&a(U,{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(G,{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(G,{label:r(`certificates.caStrip.clusterCaValidUntil`,`Cluster CA valid until`),children:[s.validTo,c!==null&&!Number.isNaN(c)&&a(`span`,{className:`ml-2 text-[10px] ${tr[Wt(c,n)]}`,children:[`(`,At(c,n),`)`]})]}),l!==void 0&&a(G,{label:r(`certificates.caStrip.nodeListener`,`Node listener`),children:[l.state===`open`&&d(V,{variant:`success`,children:r(`certificates.caStrip.open`,`Open`)}),l.state===`not-started`&&d(V,{variant:`default`,children:r(`certificates.caStrip.notStarted`,`Not started`)}),l.state===`closed`&&a(`span`,{className:`text-danger`,children:[r(`certificates.caStrip.closedSince`,{when:jt(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 ir(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 ar(e){return e.isHub?q.t(`helpers.nodesModel.hubReissued`):e.mesh===null?q.t(`helpers.nodesModel.noCertRecorded`):e.online?null:q.t(`helpers.certificateModel.nodeOffline`)}function or(e){return e.isHub||e.mesh===null?ar(e):null}var sr={ok:`text-foreground-subtle`,soon:`text-warning`,expired:`text-danger`,unknown:`text-foreground-subtle`},cr={enroll:`Issued at enrollment`,renewal:`Issued by a renewal`,boot:`Issued at boot`,pairing:`Issued at pairing`,observed:`Observed on its connection`},lr={uploaded:`Uploaded`,generated:`Generated`,disabled:`Disabled`};function ur(e){let t=e.https?.https;return t?.kind===`served`?Ht(t.status.validTo):null}function dr({ms:e,now:t}){return e===null?d(`span`,{className:`text-foreground-subtle`,children:`—`}):a(`div`,{children:[d(`div`,{children:jt(e)}),d(`div`,{className:`text-[10px] ${sr[Wt(e,t)]}`,children:At(e,t)})]})}function fr({row:e}){let{t}=J(),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(V,{variant:`success`,className:`text-[10px]`,children:t(`certificates.nodesColumns.served`,`Served`)}),d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:lr[n.status.mode]}),d(`div`,{className:`mt-1 font-mono text-[10px] text-foreground-subtle`,children:Vt(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(V,{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 pr({row:e}){let{t}=J(),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:Rt(n.serial)}),d(`div`,{className:`font-mono text-[10px] text-foreground-subtle`,title:n.fingerprintSha256,children:Vt(n.fingerprintSha256)}),a(`div`,{className:`text-[10px] text-foreground-subtle`,children:[cr[n.issuedVia],r>0?` · ${t(`certificates.nodesColumns.earlier`,{count:r})}`:``]})]})}function mr({row:e}){let{t}=J(),n=e.mesh?.presentingCurrent??null;return n===null?d(`span`,{className:`text-foreground-subtle`,children:e.online?`—`:t(`certificates.nodesColumns.offline`,`Offline`)}):n?d(V,{variant:`success`,className:`text-[10px]`,children:t(`common.yes`,`Yes`)}):d(V,{variant:`warning`,className:`text-[10px]`,children:t(`certificates.nodesColumns.noPresentsAnother`,`No - presents another`)})}function hr(e){let t=e.icon;return a(U,{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 gr({reasons:e}){let{t}=J();return a(Fe,{className:`inline-block`,children:[d(Pe,{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(_e,{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 _r({row:e,o:t}){let{t:n}=J(),r=e.https===null?`No HTTPS inventory for this node.`:Mt(e.https).reason,i=ar(e),o=or(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(hr,{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(hr,{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(hr,{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(gr,{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 vr(e){return[{key:`node`,header:q.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(V,{variant:`info`,className:`text-[10px]`,children:q.t(`common.hubWord`)}),!e.online&&d(V,{variant:`default`,className:`text-[10px]`,children:q.t(`common.offline`)})]})},{key:`https-state`,header:`HTTPS`,notSortableReason:`A state with a reason has no single order.`,render:e=>d(fr,{row:e})},{key:`https-expires`,header:q.t(`certificates.nodesColumns.httpsExpires`,`HTTPS expires`),sortValue:e=>ur(e),render:t=>d(dr,{ms:ur(t),now:e.now})},{key:`identity`,header:q.t(`certificates.nodesColumns.identity`,`Identity`),sortValue:e=>e.mesh?.current?.serial??null,render:e=>d(pr,{row:e})},{key:`identity-expires`,header:q.t(`certificates.nodesColumns.identityExpires`,`Identity expires`),sortValue:e=>e.mesh?.current?.notAfter??null,render:t=>d(dr,{ms:t.mesh?.current?.notAfter??null,now:e.now})},{key:`presenting`,header:q.t(`certificates.nodesColumns.inUse`,`In use`),notSortableReason:`Offline nodes have no answer to order by.`,render:e=>d(mr,{row:e})},{key:`actions`,header:q.t(`certificates.nodesColumns.actions`,`Actions`),align:`right`,notSortableReason:`Actions have no order.`,render:t=>d(_r,{row:t,o:e})}]}e();function yr(){let{t:e}=J(),t=H(),i=W.useUtils(),o=Rn(6e4),s=W.certificates.listHttpsCertificates.useQuery(),c=W.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=W.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=W.certificates.renewMeshOnNode.useMutation({onSuccess:e=>{p(Lt(e)),g()},onError:_(`renewal could not start`)}),b=W.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=vr({now:o,busy:x,running:m,onRenewHttps:e=>void C(e),onRenewIdentity:T,onRevokeIdentity:e=>void E(e)}),O=n(()=>ir(s.data??[],c.data),[s.data,c.data]),k=c.data?.registryAvailable??!0;return d(Y,{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:It(l,f),onDismissNotice:()=>{u(null),p(null)},children:d(Fn,{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(rr,{https:s.data??[],mesh:c.data,now:o}),d(ot,{columns:D,rows:O,rowKey:e=>e.nodeId,minWidthPx:960,maxBodyHeight:ze,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 br({pairOpen:e,onPairClose:t}){return a(`div`,{className:`space-y-4`,"data-testid":`certificates-page`,children:[d(Wn,{pairOpen:e,onPairClose:t}),d(In,{}),d(er,{}),d(yr,{})]})}function xr({userId:e,username:t,onClose:n}){let{t:r}=J(),i=H(),o=W.useUtils(),s=me({userId:e}),c=W.auth.listLoginMethods.useQuery(),l=Te({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(Re,{open:!0,onOpenChange:e=>!e&&n(),children:a(tt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[d(rt,{children:a(He,{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(Ze,{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(le,{className:`h-3 w-3`}),r(`common.remove`,`Remove`)]})]},`${e.provider}|${e.subject}`)})})}),d(Ye,{children:d(U,{onClick:n,variant:`secondary`,children:r(`common.close`,`Close`)})})]})})}function Sr({userId:e,username:t,onClose:n}){let{t:r}=J(),i=c(),o=H(),l=he({userId:e}),u=l.data,p=()=>i.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),m=Ne({onSuccess:()=>{p(),n()}}),h=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return d(Re,{open:!0,onOpenChange:e=>!e&&n(),children:a(tt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[d(rt,{children:a(He,{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(Ze,{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(U,{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 Cr({userId:e,username:t,onClose:n}){let{t:i}=J(),{user:o,logout:s}=ft(),c=o?.id===e,l=H(),u=W.useUtils(),f=W.auth.listSessions.useQuery({userId:e}),[p,m]=r(null),h=W.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:Gt(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(Re,{open:!0,onOpenChange:e=>!e&&n(),children:a(tt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[d(rt,{children:a(He,{className:`flex items-center gap-2`,children:[d(ce,{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(Ze,{className:`space-y-3`,children:[p!==null&&d(`div`,{className:`text-[11px] text-danger`,children:p}),d(Ut,{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(Ye,{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(oe,{className:`h-3 w-3`}),i(`users.userSessionsModal.signOutEverywhere`,`Sign out everywhere`)]}),d(U,{onClick:n,variant:`secondary`,children:i(`common.close`,`Close`)})]})]})})}function wr({scopes:e,invalidReason:t}){let{t:n}=J(),r=ee(),i=o({queryKey:[`auth`,`previewScope`,e,!1],enabled:t===null,queryFn:()=>r.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:!1})}),{data:s}=$e({projection:`slim`}),c=s?.length??null;if(t!==null)return a(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,"data-testid":`role-preview`,children:[d(C,{className:`h-3 w-3 shrink-0`}),t]});if(i.isLoading)return a(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,"data-testid":`role-preview`,children:[d(A,{className:`h-3 w-3 shrink-0 animate-spin`}),n(`users.rolePreview.resolving`)]});if(i.isError||!i.data)return d(`p`,{className:`text-[11px] text-danger`,"data-testid":`role-preview`,children:n(`users.rolePreview.couldNotResolve`)});let l=i.data.viewableDeviceCount,u=i.data.device.view.all?n(`users.rolePreview.everyDevice`,{count:l}):c===null?n(`users.rolePreview.devicesVisible`,{count:l}):n(`users.rolePreview.devicesVisibleOf`,{count:l,total:c});return a(`p`,{className:`flex items-center gap-1.5 text-[11px] ${l===0?`text-warning`:`text-foreground`}`,"data-testid":`role-preview`,children:[l===0?d(C,{className:`h-3 w-3 shrink-0`}):d(v,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),l===0?n(`users.rolePreview.noDevice`):u]})}function Tr(e){let t=te(e.scopes??[]);if(t===null)return{role:e.isAdmin?`admin`:`viewer`,mode:`except`,pickedIds:[],viewer:L,unconfigured:!e.isAdmin};let n=Mr(t);return{role:e.isAdmin?`admin`:`viewer`,mode:n.mode,pickedIds:n.pickedIds,viewer:Nr(n.mode,n.pickedIds,t.features),unconfigured:!1}}function Er(e,t){return{...e,role:t}}function Dr(e,t){return{...e,mode:t,viewer:Nr(t,e.pickedIds,e.viewer.features)}}function Or(e,t){let n=Pr(t);return{...e,pickedIds:n,viewer:Nr(e.mode,n,e.viewer.features)}}function kr(e,t,n){let r=e.viewer.features.filter(e=>e!==t),i=n?[...r,t]:r;return{...e,viewer:Nr(e.mode,e.pickedIds,i)}}function Ar(e){return e.role===`viewer`&&e.mode===`only`&&e.pickedIds.length===0?`no-allowed-device`:null}function jr(e){return Ar(e)===null?e.role===`admin`?{isAdmin:!0,scopes:[]}:{isAdmin:!1,scopes:[e.viewer]}:null}function Mr(e){if(e.allow===`*`)return{mode:`except`,pickedIds:e.block};let t=new Set(e.block);return{mode:`only`,pickedIds:e.allow.filter(e=>!t.has(e))}}function Nr(e,t,n){let r=Pr(t);return e===`except`?{type:`viewer`,allow:`*`,block:r,features:[...n]}:{type:`viewer`,allow:r,block:[],features:[...n]}}function Pr(e){return[...new Set(e)]}e();var Fr=`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`;function Ir(e,t){return e?`failed`:t===void 0?`pending`:`answered`}function Lr(e){let t=[];for(let n of e)n.parentDeviceId===null&&t.push({id:n.id,name:n.name,type:String(n.type),...n.location===null?{}:{location:n.location}});return t}function Rr({user:e,isSelf:t,onClose:i,onSubmit:o,submitting:c,error:l}){let{t:u}=J(),[f,p]=r(n(()=>Tr(e),[e])),m=$e({projection:`slim`}),h=m.data,g=Ir(m.isError,h),_=n(()=>Lr(h??[]),[h]),v=n(()=>({state:g,devices:g===`answered`?(h??[]).map(e=>({id:e.id,name:e.name})):void 0}),[g,h]),y=Ar(f),b=jr(f),x=y===`no-allowed-device`?u(`users.userAccessModal.pickAllowedDevice`):null,S=e=>{p(Er(f,e))},C=[{value:`except`,label:u(`users.userAccessModal.modeExcept`)},{value:`only`,label:u(`users.userAccessModal.modeOnly`)}];return d(Re,{open:!0,onOpenChange:e=>!e&&i(),children:a(tt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[d(rt,{children:d(He,{children:u(`users.userAccessModal.title`,{name:e.username})})}),a(Ze,{className:`space-y-4`,children:[f.unconfigured&&f.role===`viewer`&&d(K,{variant:`warning`,title:u(`users.userAccessModal.noAccessYet`),message:u(`users.userAccessModal.noAccessYetDetail`,{name:e.username})}),a(`section`,{className:`space-y-2`,children:[d(`h3`,{className:Fr,children:u(`users.userAccessModal.role`)}),a(`div`,{role:`radiogroup`,"aria-label":u(`users.userAccessModal.role`),className:`grid gap-1.5 sm:grid-cols-2`,children:[d(zr,{name:`admin`,checked:f.role===`admin`,label:u(`users.userAccessModal.admin`),description:u(`users.userAccessModal.adminDescription`),onPick:()=>S(`admin`)}),d(zr,{name:`viewer`,checked:f.role===`viewer`,disabled:t,label:u(`users.userAccessModal.viewer`),description:u(t?`users.userAccessModal.cannotDemoteSelf`:`users.userAccessModal.viewerDescription`),onPick:()=>S(`viewer`)})]})]}),f.role===`viewer`&&a(s,{children:[a(`section`,{className:`space-y-3`,children:[d(`h3`,{className:Fr,children:u(`users.userAccessModal.devices`)}),d(nt,{label:u(`users.userAccessModal.whichDevices`),value:f.mode,options:C,onChange:e=>p(Dr(f,e))}),d(ye,{devices:_,listState:g,fleet:v,value:[...f.pickedIds],onChange:e=>p(Or(f,e)),emptyMeansAll:f.mode===`except`,noun:`device`,testId:`viewer-device-picker`}),d(wr,{scopes:b?.scopes??[],invalidReason:x})]}),a(`section`,{className:`space-y-2`,children:[d(`h3`,{className:Fr,children:u(`users.userAccessModal.features`)}),d(`div`,{className:`space-y-1`,children:P.map(e=>a(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-md p-1.5 hover:bg-surface-hover`,children:[d(be,{className:`mt-0.5`,checked:f.viewer.features.includes(e.id),onChange:t=>p(kr(f,e.id,t.target.checked))}),a(`span`,{className:`min-w-0`,children:[d(`span`,{className:`block text-[12px] font-medium text-foreground`,children:u(`users.viewerFeatures.${e.id}.label`,e.label)}),d(`span`,{className:`block text-[10px] text-foreground-subtle`,children:u(`users.viewerFeatures.${e.id}.description`,e.description)})]})]},e.id))})]})]}),l!==null&&d(K,{message:l})]}),a(Ye,{children:[d(U,{variant:`outline`,size:`sm`,onClick:i,children:u(`common.cancel`,`Cancel`)}),d(U,{size:`sm`,onClick:()=>b!==null&&o(b),disabled:c||b===null,children:c?d(A,{className:`h-3 w-3 animate-spin`}):u(`users.userAccessModal.saveAccess`)})]})]})})}function zr({name:e,checked:t,disabled:n=!1,label:r,description:i,onPick:o}){return a(`label`,{className:`flex items-start gap-2 rounded-lg border p-2.5 transition-colors ${t?`border-primary bg-primary/5`:`border-border hover:bg-surface-hover`} ${n?`cursor-not-allowed opacity-60`:`cursor-pointer`}`,children:[d(`input`,{type:`radio`,name:`user-role`,value:e,checked:t,disabled:n,onChange:o,className:`mt-0.5`}),a(`span`,{className:`min-w-0`,children:[d(`span`,{className:`block text-[12px] font-medium text-foreground`,children:r}),d(`span`,{className:`block text-[10px] text-foreground-subtle`,children:i})]})]})}e();var Br=8;function Vr(){return{username:``,password:``,isAdmin:!1}}function Hr(e){return{id:e.id,username:e.username,password:``,isAdmin:e.isAdmin}}function Ur(e){return e instanceof Error?e.message:q.t(`admin.system.users.genericError`)}function Wr(){let{t:e}=J(),n=c(),{user:i}=ft(),{state:o,openNew:l,openEdit:u,close:p}=it(),[h,_]=r(null),[v,b]=r(null),[x,S]=r(!1),{data:C,isLoading:w,isError:T,error:O,refetch:k}=Je(),ee=H(),j=xe(),M=()=>n.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),P=pe(),F=at({onSuccess:M}),I=ke({onSuccess:M}),L=ue({onSuccess:M}),te=we(),[R,z]=r(null),[ne,re]=r(!1),[ae,B]=r(null),[oe,se]=r(null),[le,fe]=r(null),[me,he]=r(null),ge=C??[],V=o.mode===`edit`?ge.find(e=>e.id===o.id)??null:null,_e=()=>{_(null),b(null),S(!1),P.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:Vr());return}if(V===null){w||p();return}_(e=>e?.id===V.id?e:Hr(V))},[o,V,w,p]);let ve=o.mode===`new`&&h!==null&&h.id===void 0||o.mode===`edit`&&h!==null&&V!==null;async function ye(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&&_e())}async function be(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<Br?q.t(`admin.system.users.passwordTooShort`,{min:Br}):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 Se(e){B(null),z(e)}async function Ce(e,t){re(!0),B(null);try{t.isAdmin!==e.isAdmin&&await I.mutateAsync({id:e.id,isAdmin:t.isAdmin}),await te.mutateAsync({userId:e.id,scopes:[...t.scopes]}),z(null)}catch(e){B(Ur(e))}finally{re(!1),M()}}async function Te(){if(h!==null){b(null);try{if(h.id===void 0){let e=h.username.trim();if(e===``||h.password.length<Br)return;await P.mutateAsync({username:e,password:h.password,isAdmin:h.isAdmin})}else await I.mutateAsync({id:h.id,isAdmin:h.isAdmin});M(),_e()}catch(e){b(Ur(e))}}}function Ee(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}let De=P.isPending||I.isPending,Oe=h!==null&&h.id===void 0&&h.username.trim()!==``&&h.password.length>=Br,Ae=h!==null&&h.id!==void 0,je=De||(h?.id===void 0?!Oe:!Ae),Me=e=>F.isPending&&F.variables?.id===e.id||I.isPending&&I.variables?.id===e.id||L.isPending&&L.variables?.id===e.id,Ne=[{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:`scopes`,header:e(`admin.system.users.access`,`Access`),sortValue:e=>Gr(e),render:t=>d(`span`,{onClick:e=>e.stopPropagation(),children:a(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>Se(t),disabled:Me(t),title:e(`admin.system.users.configureAccess`,`Configure access`),"data-testid":`user-access-${t.id}`,children:[d(N,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),d(Kr,{user:t})]})})},{key:`createdAt`,header:e(`admin.system.users.created`,`Created`),nowrap:!0,sortValue:e=>e.createdAt,render:e=>d(`span`,{className:`text-foreground-subtle`,children:Ee(e.createdAt)})},{key:`actions`,header:e(`admin.system.users.actions`,`Actions`),align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:t=>{let n=Me(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(U,{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(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>se(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(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>fe(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(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>he(t),disabled:n,title:e(`admin.system.users.activeSessions`,`Active sessions`),children:[d(ce,{className:`h-3 w-3`}),e(`admin.system.users.sessions`,`Sessions`)]}),a(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void be(t),disabled:n,title:e(`admin.system.users.resetPassword`,`Reset password`),children:[d(ie,{className:`h-3 w-3`}),e(`admin.system.users.resetPassword`,`Reset password`)]}),a(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>void ye(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(xt,{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(U,{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(K,{title:e(`admin.system.users.couldNotLoadUsers`,`Could not load users`),message:Ur(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&&ge.length===0&&d(Be,{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&&ge.length>0&&d(ot,{columns:Ne,rows:ge,rowKey:e=>e.id,minWidthPx:560,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>u(e.id)}),d(Ge,{open:ve,onClose:_e,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(U,{size:`sm`,type:`button`,disabled:je,onClick:()=>void Te(),children:De?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(st,{label:e(`admin.system.users.username`,`Username`),required:h.id===void 0,children:d(Ie,{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(st,{label:e(`admin.system.users.password`,`Password`),required:!0,description:e(`admin.system.users.atLeastCharacters`,`At least {{value1}} characters.`,{value1:String(Br)}),children:d(de,{value:h.password,onValueChange:e=>_({...h,password:e}),shown:x,onToggleShown:()=>S(e=>!e),placeholder:`••••••••`,"data-testid":`user-form-password`})}),d(st,{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.`)})]})}),oe&&d(Sr,{userId:oe.id,username:oe.username,onClose:()=>se(null)}),le&&d(xr,{userId:le.id,username:le.username,onClose:()=>fe(null)}),me&&d(Cr,{userId:me.id,username:me.username,onClose:()=>he(null)}),R&&d(Rr,{user:R,isSelf:R.id===i?.id,onClose:()=>z(null),onSubmit:e=>void Ce(R,e),submitting:ne,error:ae})]})}function Gr(e){let t=Tr(e);return t.role===`admin`?0:t.unconfigured?2:1}function Kr({user:e}){let{t}=J(),n=Tr(e);if(n.role===`admin`)return d(`span`,{className:`font-medium text-foreground`,children:t(`users.accessSummary.admin`)});if(n.unconfigured)return d(`span`,{className:`font-medium text-warning`,children:t(`admin.system.users.noAccess`,`No access`)});let{allow:r,block:i,features:o}=n.viewer,c=r===`*`?t(`users.accessSummary.allDevices`):t(`users.accessSummary.devices`,{count:r.length});return a(`span`,{className:`text-foreground-subtle`,children:[d(`span`,{className:`font-medium text-foreground`,children:t(`users.accessSummary.viewer`)}),` ·`,` `,c,i.length>0&&a(s,{children:[` · `,t(`users.accessSummary.blocked`,{count:i.length})]}),o.length>0&&a(s,{children:[` · `,t(`users.accessSummary.features`,{count:o.length})]})]})}e();var qr={"api-keys":$.tokens,"linked-sessions":$.linkedApps},Jr=`certificates`;function Yr(e){return a(U,{size:`sm`,type:`button`,"data-testid":`certificates-pair-device`,onClick:e,children:[d(f,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),q.t(`systemPage.identity.pairADevice`,`Pair a device`)]})}function Xr(){let{t:e}=J(),[t]=mt(),n=bn(),[i,a]=r(!1),o=qr[t.get(`tab`)??``];if(o!==void 0)return d(pt,{to:gt(`access`,{integration:o}),replace:!0});let s=yt(`/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===lt.access.tab?yn(l,n.requestCreate):c===`certificates`?Yr(()=>a(!0)):void 0;return d(bt,{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(Wr,{})},{id:lt.access.tab,label:e(`systemPage.identity.tokensSessions`,`Tokens & sessions`),ownedParams:ht.concat([Nt.token,Nt.scoped,Nt.admin]),content:d(vn,{createRequested:n.createRequested,onCreateConsumed:n.clearCreate})},{id:Jr,label:e(`systemPage.identity.certificates`,`Certificates`),content:d(br,{pairOpen:i,onPairClose:()=>a(!1)})},{id:lt.authentication.tab,label:e(`systemPage.identity.authentication`,`Authentication`),content:d(Nn,{}),ownedParams:ht}]})}export{Xr as IdentityPage};