@camstack/addon-admin-ui 1.2.685 → 1.2.686

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 (81) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/assets/{Addons-V_OCI1hv.js → Addons-3ySgTmpY.js} +1 -1
  3. package/dist/assets/{AdminPage-B-VrKoee.js → AdminPage-CnX4g1T5.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-B42BuqL_.js → AdminSectionedPage-g35Q-Y2m.js} +1 -1
  5. package/dist/assets/{AiProfiles-BrK9gRbv.js → AiProfiles-DYwZNixm.js} +1 -1
  6. package/dist/assets/{BootstrapSettingsForm--qgAUAUt.js → BootstrapSettingsForm-Cp6otL6N.js} +1 -1
  7. package/dist/assets/{Build-ClWnWqDP.js → Build-BHMQT3nj.js} +1 -1
  8. package/dist/assets/{Calendars-UB5Ait-Y.js → Calendars-C5fFB9bh.js} +1 -1
  9. package/dist/assets/{CameraGrids-CijwMJMj.js → CameraGrids-kx6_btHO.js} +1 -1
  10. package/dist/assets/{Cluster-DxFFWVEf.js → Cluster-D7lgp_3H.js} +1 -1
  11. package/dist/assets/{CompositionBlockEditor-RbmTsDBB.js → CompositionBlockEditor-BMUKDIQZ.js} +1 -1
  12. package/dist/assets/{CompositionEditorPage-D75ndX00.js → CompositionEditorPage-Cgz2acUm.js} +1 -1
  13. package/dist/assets/{Data-CMHtWsQV.js → Data-L7OAyBm7.js} +1 -1
  14. package/dist/assets/{DeviceDetail-D7F-oueT.js → DeviceDetail-Dg8P-ST8.js} +1 -1
  15. package/dist/assets/{Devices-DDdRmjnV.js → Devices-C3wsrK5K.js} +1 -1
  16. package/dist/assets/{EmbedDevicePage-Vl6dXhWk.js → EmbedDevicePage-CJWLs0h9.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-B7VvMRlT.js → EmbedPlayerPage-Ugf7qZrN.js} +1 -1
  18. package/dist/assets/{History-C5GCpZqL.js → History-Bkb8SS6s.js} +1 -1
  19. package/dist/assets/{Identity-Bpxbpvi4.js → Identity-YEkh2m1V.js} +1 -1
  20. package/dist/assets/{InstancesTable-Dh2_4hoS.js → InstancesTable-B9vZgE2z.js} +1 -1
  21. package/dist/assets/{IntegrationDetail-48kj7VJ8.js → IntegrationDetail-Eapr8HN5.js} +1 -1
  22. package/dist/assets/{Integrations-BzEJSY-d.js → Integrations-Bm4bpdow.js} +1 -1
  23. package/dist/assets/{Integrations-D8oo1nA6.js → Integrations-DB2t-nuf.js} +1 -1
  24. package/dist/assets/{Library-CoxS99-g.js → Library-CTe2FjiB.js} +1 -1
  25. package/dist/assets/{Locations-BErgqW8Y.js → Locations-DLZ0eCiE.js} +1 -1
  26. package/dist/assets/{Logs-CmeGcTTn.js → Logs-Dan6AcA1.js} +1 -1
  27. package/dist/assets/{MaskShapeCanvas-CACDKrAY.js → MaskShapeCanvas-Cq0wjnK-.js} +1 -1
  28. package/dist/assets/{MotionZonesSettings-D-cGi7xS.js → MotionZonesSettings-B36hgEbv.js} +1 -1
  29. package/dist/assets/{MyAccess-D4_pQL1k.js → MyAccess-BT46dFoa.js} +1 -1
  30. package/dist/assets/{Network-CBxm90JB.js → Network-CYFPVX5D.js} +1 -1
  31. package/dist/assets/{NodeAddonsSettingsPanel-DN7gUj7L.js → NodeAddonsSettingsPanel-C2HPI8cn.js} +1 -1
  32. package/dist/assets/{Notifications-fFvHyxXB.js → Notifications-ByVhaz5L.js} +1 -1
  33. package/dist/assets/{Pipeline-CT_0SD4m.js → Pipeline-C_L_mlb3.js} +1 -1
  34. package/dist/assets/{PrivacyMaskSettings-DvzMSx0p.js → PrivacyMaskSettings-B5pk93YS.js} +1 -1
  35. package/dist/assets/{Recordings-DUVz5eQx.js → Recordings-HRQgg-mT.js} +1 -1
  36. package/dist/assets/{SceneMonitorEditor-CVU6sA7Q.js → SceneMonitorEditor-a_YfV5Ur.js} +1 -1
  37. package/dist/assets/{ServerShell-DzXr0Mh0.js → ServerShell-CdxVT-o4.js} +1 -1
  38. package/dist/assets/{SessionsList-DAQGKUGC.js → SessionsList-CIDhJh-a.js} +1 -1
  39. package/dist/assets/{Showroom-wHl1HK7u.js → Showroom-BOQOATEQ.js} +1 -1
  40. package/dist/assets/{StorageLocationsTable-Dh41YS0-.js → StorageLocationsTable-CbWGX5p5.js} +1 -1
  41. package/dist/assets/{System-DNJDOx6M.js → System-DFXhaqKS.js} +1 -1
  42. package/dist/assets/{Terminal-D7Nhjbnc.js → Terminal-DeTRjM9E.js} +1 -1
  43. package/dist/assets/{TerminalPanel-Bcgp5-JT.js → TerminalPanel-CBZjJ8Dr.js} +1 -1
  44. package/dist/assets/{TrainingProviders-BAX-nOSt.js → TrainingProviders-BGB7X7Yd.js} +1 -1
  45. package/dist/assets/{Viewer-DZS0eS_J.js → Viewer-xOVMdQTo.js} +1 -1
  46. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Bkk3XQdH.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DhWElKZO.js} +1 -1
  47. package/dist/assets/{action-draft-DvJsbt_r.js → action-draft-DOLYOpcx.js} +1 -1
  48. package/dist/assets/{assignment-candidates-Bbrjakbx.js → assignment-candidates-BT4pxrk1.js} +1 -1
  49. package/dist/assets/{authed-media-B60y8z6y.js → authed-media-2LK5_j6R.js} +1 -1
  50. package/dist/assets/{client-CIZUUslj.js → client-BzNa5PJa.js} +42 -42
  51. package/dist/assets/{command-vocab-BgdglkRN.js → command-vocab-DQCoS6kS.js} +1 -1
  52. package/dist/assets/{device-detail-CLbIDEBm.js → device-detail-Bc52Y0_7.js} +1 -1
  53. package/dist/assets/{device-integration-icon-Gpz1pK-n.js → device-integration-icon-YW7LMTlM.js} +1 -1
  54. package/dist/assets/device-picker-model-DMQzZ8k0.js +1 -0
  55. package/dist/assets/{dist-BZSVn1Nz.js → dist-CYOckloN.js} +1 -1
  56. package/dist/assets/dist-DHhIyQ9W.js +1120 -0
  57. package/dist/assets/{hostInit-DePkI2hW.js → hostInit-C2kdHdJb.js} +1 -1
  58. package/dist/assets/{icons-BqNgxZAA.js → icons-DFEHzatv.js} +1 -1
  59. package/dist/assets/{index-DckFE3TL.js → index-B_SQlUTy.js} +3 -3
  60. package/dist/assets/{linked-devices-model-CkHPBSRK.js → linked-devices-model-DxVYGr4v.js} +1 -1
  61. package/dist/assets/{mf-entry-bootstrap-0-df424c13.js → mf-entry-bootstrap-0-f413d948.js} +2 -2
  62. package/dist/assets/mount-DMQzZ8k0.js +1 -0
  63. package/dist/assets/{player-overlays-Db4ByaKk.js → player-overlays-BLoaiapp.js} +1 -1
  64. package/dist/assets/remoteEntry-wJk-wuAb.js +1 -0
  65. package/dist/assets/{src-DtKvvpJE.js → src-B6L3EZPZ.js} +16 -16
  66. package/dist/assets/{step-inspector-model-Db8uzzDx.js → step-inspector-model-C_ZtNeXt.js} +1 -1
  67. package/dist/assets/{use-scenes-feed-89dPSlPa.js → use-scenes-feed-wH8tJH0x.js} +1 -1
  68. package/dist/assets/{use-stationary-objects-Cvd9bU5U.js → use-stationary-objects-CA3H_5u_.js} +1 -1
  69. package/dist/assets/{useAdminDeviceRemoval-CMZQeqPc.js → useAdminDeviceRemoval-C6hXBea3.js} +1 -1
  70. package/dist/assets/useEventInvalidation-DMQzZ8k0.js +1 -0
  71. package/dist/assets/{useNodeUrlSelection-D-ajq0SS.js → useNodeUrlSelection-BgovsIjz.js} +1 -1
  72. package/dist/assets/{useTemplateSave-DIgug-PV.js → useTemplateSave-CqHBkGA2.js} +1 -1
  73. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-C1jcNFwJ.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Qh7JMlhu.js} +2 -2
  74. package/dist/index.html +6 -6
  75. package/dist/server/addon.js +136 -3
  76. package/package.json +2 -2
  77. package/dist/assets/device-picker-model-BBCE1hzF.js +0 -1
  78. package/dist/assets/dist-B4cNGNxv.js +0 -1120
  79. package/dist/assets/mount-BBCE1hzF.js +0 -1
  80. package/dist/assets/remoteEntry-Dthlz3Nd.js +0 -1
  81. package/dist/assets/useEventInvalidation-BBCE1hzF.js +0 -1
@@ -1,4 +1,4 @@
1
- import{C as e,E as t,H as n,J as r,K as i,P as a,R as o,S as s,V as c,Y as l,a as u,et as d,k as f,o as p,t as m,x as h,z as g}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$a as _,Dt as v,Gi as y,Ka as b,Lr as x,Ma as S,Tt as C,Vn as w,Xr as T,Zt as E,ar as D,ct as O,ea as k,ft as A,ir as j,ki as M,la as N,ma as P,ot as F,qn as I,ti as L,tn as R,ur as z,xi as B,yt as ee,za as te,zr as V}from"./player-overlays-Db4ByaKk.js";import{$a as H,$o as ne,Bo as re,Co as U,Do as ie,Eo as ae,Fo as oe,Fr as se,Go as ce,Ho as le,Io as ue,Ir as de,Jo as fe,Ko as pe,Lo as me,Lr as he,Mo as ge,Nc as _e,No as ve,Oo as ye,Pr as be,Qo as xe,Qt as Se,Ro as Ce,Rr as we,Rs as Te,So as Ee,Ta as De,To as Oe,Ts as ke,Uo as Ae,Vo as je,Wo as Me,Xo as Ne,Ya as Pe,Yo as Fe,Zo as Ie,_s as Le,aa as Re,as as ze,ba as Be,es as Ve,fs as He,is as Ue,jo as We,jr as Ge,ko as Ke,ls as qe,ns as Je,oa as Ye,os as Xe,qo as Ze,ra as Qe,ro as $e,rs as et,ss as tt,to as nt,ts as rt,vs as it,zo as at}from"./client-CIZUUslj.js";import{t as ot}from"./chevron-down-CBb-F8DT.js";import{o as st}from"./terminal-DU-tvcEm.js";import{i as ct,n as lt,r as ut,t as dt}from"./variable-Cq3v1-Kt.js";import{$f as ft,$i as pt,$o as mt,Bi as ht,D as gt,Dn as _t,E as vt,Ea as yt,Ep as bt,Fa as xt,Fd as St,Fr as Ct,Gf as wt,Gi as Tt,Hi as Et,Ia as Dt,Id as Ot,Ji as kt,Jo as At,Ki as jt,Ko as Mt,La as Nt,Ld as Pt,Li as Ft,Ls as It,Ma as Lt,Md as Rt,Mr as zt,Na as Bt,Nd as Vt,Nr as Ht,Ns as Ut,Or as Wt,Pd as Gt,Rd as Kt,Ri as qt,S as Jt,Tc as Yt,Ui as Xt,Vi as Zt,Ws as Qt,Xf as W,Zo as $t,_ as en,_f as tn,ad as nn,ap as rn,b as an,ci as G,ct as on,dp as sn,ea as cn,ei as ln,en as un,ff as dn,g as fn,ga as K,gf as pn,h as mn,hc as hn,hr as gn,ip as q,ja as _n,jd as vn,jn as yn,k as bn,kn as xn,ni as Sn,ns as Cn,nt as wn,oc as Tn,pa as En,pr as Dn,q as On,qo as kn,ri as An,rs as jn,rt as Mn,ti as Nn,ts as Pn,ui as Fn,up as In,ut as J,va as Y,vf as Ln,x as Rn,y as zn,ya as Bn,yf as Vn,za as Hn,zi as Un}from"./src-DtKvvpJE.js";import{t as X}from"./i18n-DJdnRrxy.js";import{t as Z}from"./useTranslation-BJr-n0es.js";import{At as Wn,H as Gn,Nt as Kn,b as qn,di as Jn,g as Yn,gi as Xn,h as Zn,mi as Qn,n as $n,t as er,ui as tr}from"./index-DckFE3TL.js";import{t as nr}from"./AdminSectionedPage-B42BuqL_.js";import{n as rr}from"./format-BLZTgKwl.js";import{C as ir,Ct as ar,Ot as or,a as sr,at as cr,b as lr,g as ur,i as dr,kt as fr,n as pr,nt as mr,o as hr,r as gr,w as _r,wt as vr,y as yr}from"./CompositionBlockEditor-RbmTsDBB.js";import{_ as br,a as xr,c as Sr,d as Cr,f as wr,g as Tr,h as Er,i as Dr,l as Or,m as kr,o as Ar,p as jr,r as Mr,s as Nr,t as Pr,u as Fr,v as Ir}from"./useTemplateSave-DIgug-PV.js";import{a as Lr,c as Rr,f as zr,r as Br}from"./command-vocab-BgdglkRN.js";import{a as Vr,i as Hr,n as Ur,o as Wr,r as Gr,s as Kr}from"./action-draft-DvJsbt_r.js";var qr=`const AUTOMATION_RECIPE =`,Jr=`// EJECTED from the visual automation editor — this file is now hand-owned.
1
+ import{C as e,E as t,H as n,J as r,K as i,P as a,R as o,S as s,V as c,Y as l,a as u,et as d,k as f,o as p,t as m,x as h,z as g}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$a as _,Dt as v,Gi as y,Ka as b,Lr as x,Ma as S,Tt as C,Vn as w,Xr as T,Zt as E,ar as D,ct as O,ea as k,ft as A,ir as j,ki as M,la as N,ma as P,ot as F,qn as I,ti as L,tn as R,ur as z,xi as B,yt as ee,za as te,zr as V}from"./player-overlays-BLoaiapp.js";import{$a as H,$o as ne,Bo as re,Co as U,Do as ie,Eo as ae,Fo as oe,Fr as se,Go as ce,Ho as le,Io as ue,Ir as de,Jo as fe,Ko as pe,Lo as me,Lr as he,Mo as ge,Nc as _e,No as ve,Oo as ye,Pr as be,Qo as xe,Qt as Se,Ro as Ce,Rr as we,Rs as Te,So as Ee,Ta as De,To as Oe,Ts as ke,Uo as Ae,Vo as je,Wo as Me,Xo as Ne,Ya as Pe,Yo as Fe,Zo as Ie,_s as Le,aa as Re,as as ze,ba as Be,es as Ve,fs as He,is as Ue,jo as We,jr as Ge,ko as Ke,ls as qe,ns as Je,oa as Ye,os as Xe,qo as Ze,ra as Qe,ro as $e,rs as et,ss as tt,to as nt,ts as rt,vs as it,zo as at}from"./client-BzNa5PJa.js";import{t as ot}from"./chevron-down-CBb-F8DT.js";import{o as st}from"./terminal-DU-tvcEm.js";import{i as ct,n as lt,r as ut,t as dt}from"./variable-Cq3v1-Kt.js";import{$f as ft,$i as pt,$o as mt,Bi as ht,D as gt,Dn as _t,E as vt,Ea as yt,Ep as bt,Fa as xt,Fd as St,Fr as Ct,Gf as wt,Gi as Tt,Hi as Et,Ia as Dt,Id as Ot,Ji as kt,Jo as At,Ki as jt,Ko as Mt,La as Nt,Ld as Pt,Li as Ft,Ls as It,Ma as Lt,Md as Rt,Mr as zt,Na as Bt,Nd as Vt,Nr as Ht,Ns as Ut,Or as Wt,Pd as Gt,Rd as Kt,Ri as qt,S as Jt,Tc as Yt,Ui as Xt,Vi as Zt,Ws as Qt,Xf as W,Zo as $t,_ as en,_f as tn,ad as nn,ap as rn,b as an,ci as G,ct as on,dp as sn,ea as cn,ei as ln,en as un,ff as dn,g as fn,ga as K,gf as pn,h as mn,hc as hn,hr as gn,ip as q,ja as _n,jd as vn,jn as yn,k as bn,kn as xn,ni as Sn,ns as Cn,nt as wn,oc as Tn,pa as En,pr as Dn,q as On,qo as kn,ri as An,rs as jn,rt as Mn,ti as Nn,ts as Pn,ui as Fn,up as In,ut as J,va as Y,vf as Ln,x as Rn,y as zn,ya as Bn,yf as Vn,za as Hn,zi as Un}from"./src-B6L3EZPZ.js";import{t as X}from"./i18n-DJdnRrxy.js";import{t as Z}from"./useTranslation-BJr-n0es.js";import{At as Wn,H as Gn,Nt as Kn,b as qn,di as Jn,g as Yn,gi as Xn,h as Zn,mi as Qn,n as $n,t as er,ui as tr}from"./index-B_SQlUTy.js";import{t as nr}from"./AdminSectionedPage-g35Q-Y2m.js";import{n as rr}from"./format-BLZTgKwl.js";import{C as ir,Ct as ar,Ot as or,a as sr,at as cr,b as lr,g as ur,i as dr,kt as fr,n as pr,nt as mr,o as hr,r as gr,w as _r,wt as vr,y as yr}from"./CompositionBlockEditor-BMUKDIQZ.js";import{_ as br,a as xr,c as Sr,d as Cr,f as wr,g as Tr,h as Er,i as Dr,l as Or,m as kr,o as Ar,p as jr,r as Mr,s as Nr,t as Pr,u as Fr,v as Ir}from"./useTemplateSave-CqHBkGA2.js";import{a as Lr,c as Rr,f as zr,r as Br}from"./command-vocab-DQCoS6kS.js";import{a as Vr,i as Hr,n as Ur,o as Wr,r as Gr,s as Kr}from"./action-draft-DOLYOpcx.js";var qr=`const AUTOMATION_RECIPE =`,Jr=`// EJECTED from the visual automation editor — this file is now hand-owned.
2
2
  // The recipe that produced it was removed with it, on purpose: while it was
3
3
  // here the editor could re-open this block and overwrite everything below.`;function Yr(e){return e.includes(qr)}function Xr(e){return!Yr(e.code)}function Zr(e){let t=e.indexOf(qr);if(t<0)return null;let n=e.indexOf(`{`,t+25);if(n<0)return null;let r=0,i=!1,a=!1;for(let o=n;o<e.length;o+=1){let s=e.charAt(o);if(i){a?a=!1:s===`\\`?a=!0:s===`"`&&(i=!1);continue}if(s===`"`){i=!0;continue}if(s===`{`)r+=1;else if(s===`}`&&(--r,r===0))return{declStart:t,literalEnd:o+1,json:e.slice(n,o+1)}}return null}function Qr(e){let t=Zr(e);if(t===null)return{ok:!1,reason:X.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:X.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=re.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?X.t(`helpers.recipeFromCode.schemaMismatch`):X.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function $r(e){let t=Zr(e);if(t===null)return e;let n=e.slice(t.literalEnd),r=/^\s*as\s+const/.exec(n),i=t.literalEnd+(r===null?0:r[0].length);return`${e.slice(0,t.declStart)}${Jr}${e.slice(i)}`}var ei=e=>e.tags,ti=e=>[e.name],ni=e=>e.tags,ri=e=>[e.name],ii=e=>e.tags,ai=e=>[e.name],oi=e=>e.tags,si=e=>[e.name];d();var ci=`when`;function li(e){return e===void 0||e.trim()===``?null:e}function ui(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function di(e){return e===`ok`?`pass`:e===`error`||e===`failed-continued`||e===`timed-out`?`fail`:`idle`}function fi(e){return e.steps.map(e=>({index:ui(e.path),tone:di(e.outcome),message:li(e.message)}))}function pi(e){let t=e.trigger.outcome===`pass`?`pass`:`fail`,n=li(e.trigger.reason),r=e.conditions.find(e=>e.path===ci);return t===`fail`||r===void 0?{tone:t,reason:n}:r.outcome===`fail`?{tone:`fail`,reason:li(r.reason)??n}:{tone:r.outcome===`pass`?`pass`:`idle`,reason:n}}function mi(e,t){return e.outcome===`ran`?{tone:`pass`,reason:null}:e.outcome===`failed`||e.outcome===`aborted`?{tone:`fail`,reason:t.find(e=>e.tone===`fail`)?.message??null}:{tone:`idle`,reason:li(e.verdict?.reason)}}function hi(e){let t=fi(e);return{when:pi(e),thenBlock:mi(e,t),steps:t}}function gi(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}function _i(e){return e===null?{kind:`unknown`}:{kind:`value`,text:Array.isArray(e)?e.join(`, `):String(e)}}function vi(e){return{kind:e.kind,tone:di(e.outcome),message:li(e.message)}}function yi(e){if(e===void 0)return null;if(e===`else`)return{kind:`else`};let t=Number(e.slice(e.lastIndexOf(`.`)+1));return Number.isInteger(t)?{kind:`branch`,index:t}:null}function bi(e,t){return t===void 0?null:e===void 0?t:`${e}.${t}`}function xi(e){return{vars:Object.entries(e.trigger.vars).map(([e,t])=>({name:e,value:_i(t)})),conditions:e.conditions.map(e=>({path:e.path,depth:e.path.split(`.`).length-1,kind:e.kind,outcome:e.outcome,reason:li(e.reason),subject:bi(e.cap,e.fieldPath),operator:e.operator??null,deviceId:e.deviceId??null,expected:e.expected===void 0?null:_i(e.expected),observed:e.observed===void 0?null:_i(e.observed),rawExpected:e.expected,rawObserved:e.observed})),steps:e.steps.map(e=>({index:ui(e.path),kind:e.kind,tone:di(e.outcome),message:li(e.message),args:Object.entries(e.args??{}).map(([e,t])=>({name:e,value:_i(t)})),devices:(e.devices??[]).map(e=>({deviceId:e.deviceId,tone:e.outcome===`ok`?`pass`:`fail`,message:li(e.message)})),chose:yi(e.branch),nested:(e.steps??[]).map(e=>({...vi(e),chose:yi(e.branch),rounds:e.iterations??null,inner:(e.steps??[]).map(vi)})),rounds:e.iterations??null}))}}function Si(e){let t=xi(e);return{nodes:new Map(t.conditions.map(e=>[e.path,e])),triggerPath:e.trigger.path??null,vars:t.vars}}var Ci=6;function wi(e,t,n){if(typeof e!=`number`||t===void 0||n===void 0)return _i(e);let r=He(e,t,n);return r===void 0?_i(e):{kind:`value`,text:`${String(Number(r.toPrecision(Ci)))} ${n}`}}function Ti(e){let t=e.steps.find(e=>e.outcome===`error`),n=t===void 0?li(e.verdict?.reason)??li(e.trigger.reason):li(t.message);return{stepsRun:e.steps.filter(e=>e.outcome===`ok`).length,stepsTotal:e.steps.length,reason:n}}var Ei={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},Di={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},Oi={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function ki(){let{t:e}=Z();return t=>{switch(t){case`ran`:return e(`flow.runs.outcomeRan`,`Ran`);case`failed`:return e(`flow.runs.outcomeFailed`,`Failed`);case`aborted`:return e(`flow.runs.outcomeAborted`,`Stopped`);case`skipped-trigger`:return e(`flow.runs.outcomeSkippedTrigger`,`Trigger not met`);case`skipped-conditions`:return e(`flow.runs.outcomeSkippedConditions`,`Skipped by conditions`);case`skipped-cooldown`:return e(`flow.runs.outcomeSkippedCooldown`,`Skipped by cooldown`);default:return e(`flow.runs.outcomeSkippedOverlap`,`Skipped by run mode`)}}}var Ai={done:`success`,missed:`warning`,inactive:`neutral`,"condition-false":`neutral`,failed:`danger`,held:`success`,"gave-up":`danger`,overridden:`info`,"suspended-manual":`warning`};function ji(){let{t:e}=Z();return t=>{switch(t){case`done`:return e(`flow.runs.schedulerDone`,`Done`);case`missed`:return e(`flow.runs.schedulerMissed`,`Missed`);case`inactive`:return e(`flow.runs.schedulerInactive`,`Not active`);case`condition-false`:return e(`flow.runs.schedulerConditionFalse`,`Condition not met`);case`failed`:return e(`flow.runs.schedulerFailed`,`Failed`);case`held`:return e(`flow.runs.schedulerHeld`,`Held`);case`gave-up`:return e(`flow.runs.schedulerGaveUp`,`Gave up`);case`overridden`:return e(`flow.runs.schedulerOverridden`,`Changed by hand`);default:return e(`flow.runs.schedulerSuspendedManual`,`Paused by hand`)}}}var Mi=`max-h-64`;function Ni(){let e=sn(),t=In();return e||t}function Pi({expanded:t,onToggle:n}){let{t:r}=Z();return e(W,{variant:`unstyled`,type:`button`,"aria-expanded":t,"data-testid":`runs-toggle`,onClick:n,className:`flex w-full items-center gap-2 px-3 py-2 text-left text-xs text-foreground-muted hover:bg-surface-hover`,children:[s(ft,{expanded:t}),s(`span`,{children:t?r(`flow.runs.hide`,`Hide runs`):r(`flow.runs.show`,`Show runs`)})]})}function Fi({run:t}){let{t:n}=Z(),r=ki(),i=Ti(t);return e(`p`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-border-subtle bg-primary/5 px-3 py-2 text-xs`,"data-testid":`run-summary`,children:[s(Y,{variant:Ei[t.outcome],children:r(t.outcome)}),i.reason!==null&&s(`span`,{className:`min-w-0 break-words text-foreground`,children:i.reason}),i.stepsTotal>0&&s(`span`,{className:`text-foreground-subtle`,children:n(`flow.runs.stepsRan`,`{{run}} of {{total}} steps ran`,{run:i.stepsRun,total:i.stepsTotal})})]})}function Ii({traces:t,selectedId:n,onSelect:r}){let{t:i}=Z(),a=ki(),o=ji(),c=Ni(),[u,d]=l(null),f=u??!c,p=t===void 0?[]:t.toReversed(),m=p.find(e=>e.runId===n)??null;return e(zt,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:T,children:[s(Pi,{expanded:f,onToggle:()=>d(!f)}),f?t===void 0?s(Bn,{className:`m-3 h-16`}):p.length===0?s(pt,{title:i(`flow.runs.emptyTitle`,`No runs yet`),description:i(`flow.runs.emptyDescription`,`Each run appears here with what it decided.`)}):e(h,{children:[s(`ul`,{className:`${Mi} divide-y divide-border-subtle overflow-y-auto`,"data-testid":`runs-panel`,children:p.map(t=>{let i=t.runId===n;return s(`li`,{children:e(W,{variant:`unstyled`,type:`button`,"aria-pressed":i,onClick:()=>r(i?null:t.runId),className:`flex w-full flex-col gap-1 px-3 py-2 text-left hover:bg-surface-hover ${i?`bg-primary/10`:``}`,children:[e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[t.scheduler===void 0?s(Y,{variant:Ei[t.outcome],children:a(t.outcome)}):s(Y,{variant:Ai[t.scheduler],children:o(t.scheduler)}),t.repeat>1&&s(Y,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),s(`span`,{className:`text-xs text-foreground-subtle`,children:rr(t.lastAt)})]}),s(`span`,{className:`truncate text-sm text-foreground`,children:t.trigger.reason})]})},t.runId)})}),m!==null&&s(Fi,{run:m}),s(`p`,{className:`border-t border-border-subtle px-3 py-2 text-xs text-foreground-subtle`,children:i(`flow.runs.hint`,`Select a run to colour the blocks: green passed, red failed, grey not evaluated.`)})]}):m!==null&&s(Fi,{run:m})]})}function Li(e){return Di[e]}var Ri={pass:`border-success/50`,fail:`border-danger/50`,idle:`border-border`};function zi(e){return Ri[e]}function Bi({step:t,title:n,hint:r,trace:i,children:a}){return e(`section`,{className:`rounded-lg border p-3 ${i===null?`border-border bg-surface`:Di[i.tone]}`,"data-testid":`block-${t}`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[s(`h4`,{className:`text-sm font-semibold uppercase tracking-wide`,children:n}),r!==void 0&&s(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i!==null&&i.reason!==null&&s(`p`,{className:`mb-2 text-xs font-medium ${Oi[i.tone]}`,children:i.reason}),s(`div`,{className:`space-y-2`,children:a})]})}var Vi=[`count`,`while`,`until`,`forEach`],Hi=2,Ui=10,Wi={kind:`all`,children:[]};function Gi(e){return e===`count`||e===`while`||e===`until`||e===`forEach`}function Ki(e,t){return Number.isFinite(e)?Math.min(t,Math.max(1,Math.round(e))):1}function qi(e){return Ki(e,20)}function Ji(e){return Ki(e,50)}function Yi(e){switch(e){case`count`:return{by:e,count:Hi};case`while`:case`until`:return{by:e,when:Wi,maxIterations:Ui};case`forEach`:return{by:e,target:{kind:`devices`,ids:[]}}}}function Xi(e,t){if(e.by!==`while`&&e.by!==`until`)return e;let{waitS:n,...r}=e;return t===null?r:{...r,waitS:Ki(t,le)}}function Zi(){return{kind:`repeat`,loop:Yi(`count`),steps:[]}}var Qi=[`s`,`min`,`h`],$i={s:1,min:60,h:3600};function ea(e){return e===`s`||e===`min`||e===`h`}function ta(e){return e%$i.h===0?{value:e/$i.h,unit:`h`}:e%$i.min===0?{value:e/$i.min,unit:`min`}:{value:e,unit:`s`}}function na(e,t){let n=Math.round(e*$i[t]);return Number.isFinite(n)?Math.min(Math.max(n,1),Ae):1}function ra(){return{kind:`wait-until`,when:{kind:`all`,children:[]},timeoutS:600,onTimeout:`continue`}}var ia=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function aa(e){switch(e){case`boolean`:return[`eq`,`ne`];case`number`:return[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`];case`string`:case`enum`:return[`eq`,`ne`,`contains`,`in`];default:return ia}}function oa(e){switch(e){case`eq`:return X.t(`helpers.recipeParts.op_eq`);case`ne`:return X.t(`helpers.recipeParts.op_ne`);case`gt`:return X.t(`helpers.recipeParts.op_gt`);case`gte`:return X.t(`helpers.recipeParts.op_gte`);case`lt`:return X.t(`helpers.recipeParts.op_lt`);case`lte`:return X.t(`helpers.recipeParts.op_lte`);case`contains`:return X.t(`helpers.recipeParts.op_contains`);default:return X.t(`helpers.recipeParts.op_in`)}}function sa(e){return aa(e).map(e=>({value:e,label:oa(e)}))}Ee.filter(e=>U(e).role===`event`),Ee.filter(e=>U(e).role===`state`);function ca(e){return X.t(`${U(e).i18nKey}.label`)}function la(e){return X.t(`${U(e).i18nKey}.description`)}function ua(e){return X.t(`${U(e).i18nKey}.example`)}var da={when:{kind:`all`,children:[]},actions:[]};function fa(e){return Oe(e)}function pa(e){switch(e){case`wait`:return{kind:e,seconds:5};case`code`:return{kind:e,code:`// runs inside this automation, with ctx in scope
4
4
  `};case`action`:return{kind:e,actionId:``};case`stop`:return{kind:e,reason:``,outcome:`ok`};case`set`:return{kind:e,vars:{}};case`wait-until`:return ra();case`parallel`:return{kind:e,steps:[]};case`repeat`:return Zi();case`choose`:return{kind:e,branches:[{if:{kind:`all`,children:[]},steps:[]}]};default:return{kind:`command`,target:{kind:`devices`,ids:[]},actionId:``}}}function Q(e,t,n){return e.map((e,r)=>r===t?n:e)}function ma(e,t){return e.filter((e,n)=>n!==t)}function ha(e,t,n){let r=e[t];if(r===void 0)return e;let i=Math.min(Math.max(n,0),e.length-1);if(i===t)return e;let a=ma(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function ga(e,t){return{...e,actions:[...t]}}var _a={pass:`success`,fail:`danger`,"not-evaluated":`neutral`},va={pass:`success`,fail:`danger`,idle:`neutral`};function ya({value:e}){let{t}=Z();return e.kind===`unknown`?s(`span`,{className:`italic text-foreground-subtle`,"data-testid":`trace-value-unknown`,children:t(`flow.runs.unknownValue`,`unknown`)}):s(`span`,{className:`font-mono text-foreground`,children:e.text})}function ba(){let{t:e}=Z();return t=>t===`pass`?e(`flow.runs.nodePass`,`Passed`):t===`fail`?e(`flow.runs.nodeFail`,`Failed`):e(`flow.runs.nodeNotEvaluated`,`Not evaluated`)}function xa(e){let t=Fe.safeParse(e);return t.success?oa(t.data):e}function Sa({items:t,testId:n}){return t.length===0?null:s(`dl`,{className:`grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-[11px]`,"data-testid":n,children:t.map(t=>e(`div`,{className:`contents`,children:[s(`dt`,{className:`text-foreground-subtle`,children:t.name}),s(`dd`,{className:`break-words`,children:s(ya,{value:t.value})})]},t.name))})}function Ca({node:t,vars:n=[],expected:r,observed:i}){let{t:a}=Z(),o=ba(),c=t.subject===null?null:`${t.subject}${t.operator===null?``:` ${xa(t.operator)}`}`;return e(`div`,{className:`space-y-1 border-t border-border-subtle pt-2 text-xs`,"data-testid":`trace-result`,"data-outcome":t.outcome,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(Y,{variant:_a[t.outcome],children:o(t.outcome)}),t.reason!==null&&s(`span`,{className:`min-w-0 break-words text-foreground`,children:t.reason})]}),c!==null&&s(`div`,{className:`text-[11px] text-foreground-subtle`,children:c}),(r!==null||i!==null)&&e(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[r!==null&&e(`span`,{"data-testid":`trace-expected`,children:[a(`flow.runs.expected`,`Expected`),` `,s(ya,{value:r})]}),i!==null&&e(`span`,{"data-testid":`trace-observed`,children:[a(`flow.runs.observed`,`Observed`),` `,s(ya,{value:i})]})]}),s(Sa,{testId:`trace-vars`,items:n})]})}function wa({step:t,deviceName:n}){let{t:r}=Z(),i=t.tone===`pass`?r(`flow.runs.stepOk`,`OK`):t.tone===`fail`?r(`flow.runs.stepError`,`Error`):r(`flow.runs.stepNotRun`,`Not run`);return e(`div`,{className:`space-y-1 border-t border-border-subtle pt-2 text-xs`,"data-testid":`step-result`,"data-tone":t.tone,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(Y,{variant:va[t.tone],children:i}),t.message!==null&&s(`span`,{className:`min-w-0 break-words text-foreground`,children:t.message})]}),t.chose!==null&&s(`div`,{className:`text-foreground-subtle`,"data-testid":`step-chose`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.nested.length>0&&s(`div`,{className:`text-foreground-subtle`,"data-testid":`step-last-round`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})}),t.nested.length>0&&s(`ol`,{className:`space-y-0.5 text-[11px]`,"data-testid":`step-nested`,children:t.nested.map((t,n)=>e(`li`,{className:`space-y-0.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(Y,{variant:va[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&s(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message}),t.chose!==null&&s(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-chose-${String(n)}`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.inner.length>0&&s(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-rounds-${String(n)}`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})})]}),t.inner.length>0&&s(`ol`,{className:`space-y-0.5 border-l border-border-subtle pl-2`,"data-testid":`nested-inner-${String(n)}`,children:t.inner.map((t,n)=>e(`li`,{className:`flex flex-wrap items-center gap-2`,children:[e(Y,{variant:va[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&s(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},String(n)))})]},String(n)))}),s(Sa,{testId:`step-args`,items:t.args}),t.devices.length>0&&s(`ul`,{className:`space-y-0.5 text-[11px]`,"data-testid":`step-devices`,children:t.devices.map(t=>e(`li`,{className:`flex flex-wrap items-center gap-2`,children:[s(Y,{variant:va[t.tone],children:n(t.deviceId)}),t.message!==null&&s(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},t.deviceId))})]})}d();function $({children:e}){return s(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function Ta(e){let t=Or(e.deviceId);if(t.data!==void 0)return Nr(t.data,e.cap).find(t=>t.path===e.fieldPath)}function Ea({value:t,devices:n,onChange:r}){let{t:i,i18n:a}=Z(),[o,c]=l(!1),u=n.find(e=>e.id===t.deviceId),d=t.deviceId===0?i(`automation.fieldPicker.pickAValue`,`Pick a device value…`):`${u?.name??`#${String(t.deviceId)}`}${t.cap===``?``:` · ${vr(t.cap,t.fieldPath,a.language)}`}`;return e(`div`,{className:`min-w-[14rem] max-w-full flex-[2]`,children:[s($,{children:i(`automation.fieldPicker.value`,`Device value`)}),e(W,{variant:`outline`,className:`w-full min-w-0 justify-between`,"data-testid":`field-picker-open`,onClick:()=>c(!0),children:[s(`span`,{className:`w-0 flex-1 truncate text-left`,children:d}),s(ot,{className:`size-3.5 shrink-0`})]}),o&&s(Da,{value:t,onCancel:()=>c(!1),onConfirm:e=>{c(!1),r(e)}})]})}function Da({value:t,onCancel:n,onConfirm:r}){let{t:i}=Z(),a=It({projection:`slim`}),[o,c]=l(null),[u,d]=l(!1),[f,p]=l(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!u&&a.status===`success`&&(d(!0),c(or(a.data).find(e=>e.id===t.deviceId)??null));let m=i(`automation.fieldPicker.title`,`Device value`);return s(Mn,{open:!0,onClose:n,title:m,width:`xl`,fill:!0,testId:`field-picker-dialog`,footer:e(h,{children:[s(W,{variant:`ghost`,onClick:n,children:i(`common.cancel`,`Cancel`)}),s(W,{disabled:o===null||f===null,"data-testid":`field-picker-confirm`,onClick:()=>{o===null||f===null||r({deviceId:o.id,cap:f.cap,fieldPath:f.path})},children:i(`automation.fieldPicker.use`,`Use this value`)})]}),children:s(cr,{kind:`formula`,intent:`value`,enabled:!0,fillHeight:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:m,pickerTargetKind:null},device:o,field:f,excludeTypes:wr,onDeviceChange:c,onFieldChange:p})})}var Oa=1e4;function ka(e,t,n){let r=Object.fromEntries(Object.entries(e??{}).filter(([e])=>e!==t)),i=n===null?r:{...r,[t]:n};return Object.keys(i).length===0?void 0:i}function Aa(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function ja({step:t,onChange:n}){let{t:r}=Z(),i=Dt({},{refetchInterval:Oa});if(i.data===void 0)return s(Bn,{className:`h-8 w-64`});let a=i.data.find(e=>e.id===t.actionId),o=t.actionId!==``&&a===void 0;return e(`div`,{className:`space-y-2`,"data-testid":`run-action-step`,children:[e(`label`,{className:`block max-w-sm`,children:[s($,{children:r(`automation.runAction.action`,`Action`)}),s(A,{value:t.actionId,onChange:e=>n({kind:`action`,actionId:e.target.value}),options:[{value:``,label:r(`automation.runAction.pick`,`Pick an action`)},...o?[{value:t.actionId,label:r(`automation.runAction.missing`,`Missing action ({{id}})`,{id:t.actionId})}]:[],...i.data.map(e=>({value:e.id,label:e.name}))]})]}),o&&s(`p`,{className:`text-xs text-danger`,children:r(`automation.runAction.missingHint`,`This action no longer exists. Pick another, or the step will fail.`)}),(a?.variables??[]).length>0&&s(`div`,{className:`flex flex-wrap items-end gap-3`,children:(a?.variables??[]).map(e=>s(Ma,{variable:e,value:t.variables?.[e.name],onChange:r=>n(Aa(t,ka(t.variables,e.name,r)))},e.name))})]})}function Ma({variable:t,value:n,onChange:r}){let{t:i}=Z(),a=t.label??t.name,o=t.default===void 0?i(`automation.runAction.required`,`required`):i(`automation.runAction.defaultIs`,`default {{value}}`,{value:String(t.default)});if(t.type===`boolean`||t.type===`select`){let c=t.type===`boolean`?[{value:`true`,label:i(`common.yes`,`Yes`)},{value:`false`,label:i(`common.no`,`No`)}]:(t.options??[]).map(e=>({value:e,label:e}));return e(`label`,{className:`block`,children:[s($,{children:a}),s(kr,{widthClass:`w-40`,value:n===void 0?``:String(n),onChange:e=>{e.target.value===``?r(null):r(t.type===`boolean`?e.target.value===`true`:e.target.value)},options:[{value:``,label:o},...c]})]})}return t.type===`number`?e(`label`,{className:`block`,children:[s($,{children:a}),s(Er,{className:`w-40`,placeholder:o,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[s($,{children:a}),s(q,{className:`w-40`,placeholder:o,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}function Na({onMove:e,label:t,reason:n,testId:r,children:i}){let a=e===null?n:t;return s(`span`,{className:`inline-flex`,title:a,"data-testid":`${r}-wrap`,children:s(W,{variant:`ghost`,disabled:e===null,onClick:e??void 0,"aria-label":t,title:a,"data-testid":r,children:i})})}function Pa({move:t,texts:n}){let{t:r}=Z(),i=n??{up:r(`automation.whenTree.moveUp`,`Move up`),down:r(`automation.whenTree.moveDown`,`Move down`),atFirst:r(`automation.whenTree.alreadyFirst`,`Already first in this block`),atLast:r(`automation.whenTree.alreadyLast`,`Already last in this block`)};return e(h,{children:[s(Na,{onMove:t.up,label:i.up,reason:i.atFirst,testId:`move-up`,children:s(S,{className:`h-3.5 w-3.5`})}),s(Na,{onMove:t.down,label:i.down,reason:i.atLast,testId:`move-down`,children:s(te,{className:`h-3.5 w-3.5`})})]})}var Fa=[`command`,`action`,`wait`,`set`,`stop`],Ia=[`command`,`action`,`wait`];function La(e){return za(e)&&Ia.includes(e.kind)}var Ra={kind:`all`,children:[]};function za(e){return Fa.includes(e.kind)?!(`if`in e)&&!(`else`in e):!1}function Ba(){return{if:Ra,steps:[]}}function Va(e){return e.branches.length<6}function Ha(e){return Va(e)?{...e,branches:[...e.branches,Ba()]}:e}function Ua(e){return e.branches.length>1}function Wa(e,t){return Ua(e)?{...e,branches:e.branches.filter((e,n)=>n!==t)}:e}function Ga(e,t,n){return{...e,branches:e.branches.map((e,r)=>r===t?n:e)}}function Ka(e,t){let{else:n,...r}=e;return t===void 0?r:{...r,else:[...t]}}var qa=[...Fa,`wait-until`,`choose`,`parallel`,`repeat`];function Ja(e){return e<2?qa:Fa}function Ya(e){if(za(e))return!0;switch(e.kind){case`wait-until`:case`parallel`:return!0;case`repeat`:return e.steps.every(za);case`choose`:return e.branches.every(e=>e.steps.every(za))&&(e.else??[]).every(za);default:return!1}}var Xa=[`border-chart-series-a`,`border-chart-series-f`,`border-chart-series-b`,`border-chart-series-d`];function Za(e,t){let n=Xa.length;return(e+1+t%(n-1))%n}function Qa(e,t){let n=0;return e.map(e=>rt(e)?null:Za(t,n++))}function $a(e){return Xa[e%Xa.length]??Xa[0]}function eo(e){let t=[],n=0;return xe(e,e=>{Ve(e)&&(n+=1,e.id!==void 0&&t.push({id:e.id,ordinal:n,leaf:e}))}),t}function to(e){return ne(e.when)?!0:e.actions.some(e=>Me(e).some(e=>ne(e.when)))}function no(e){let t=1;for(;e.has(`t${t}`);)t+=1;return`t${t}`}function ro(e,t){if(rt(e)){if(!Ve(e)||e.id!==void 0)return e;let n=no(t);return t.add(n),{...e,id:n}}if(e.kind===`not`){let n=ro(e.child,t);return n===e.child?e:{...e,child:n}}let n=e.children.map(e=>ro(e,t));return n.every((t,n)=>t===e.children[n])?e:{...e,children:n}}function io(e){if(!to(e))return e;let t=new Set(eo(e.when).map(e=>e.id)),n=ro(e.when,t);return n===e.when?e:{...e,when:n}}function ao(e,t,n){let r=e.leafIds.includes(t)?e.leafIds.filter(e=>e!==t):[...e.leafIds,t];return{kind:`triggered-by`,leafIds:n.filter(e=>r.includes(e))}}function oo(e,t){return e.leafIds.filter(e=>!t.includes(e))}d();var so=[],co=f(null);function lo({when:e,children:t}){let n=i(()=>eo(e),[e]);return s(co.Provider,{value:n,children:t})}function uo(){return g(co)??so}function fo(){return g(co)!==null}var po=[`triggered-by`];function mo(e){return{label:ca(e),description:la(e),example:ua(e)}}function ho({open:e,onOpenChange:t,mode:n,context:r,underNot:i,treeFull:a,current:o,onPick:c}){let{t:l}=Z(),u=fo();return s(zn,{open:e,onOpenChange:t,title:n===`add`?l(`automation.leafPicker.title`,`Add a row`):l(`automation.leafPicker.changeTitle`,`Change the row type`),context:r,underNot:i,treeFull:a,...n===`change`&&o!==void 0?{current:o}:{},...u?{}:{hidden:po},recentKey:`automation-${r}`,textsOf:mo,categoryLabelOf:e=>l(`automation.leafPicker.category.${e}`),reasonOf:e=>l(`automation.leafPicker.reason.${e}`),onPick:e=>{c(e),t(!1)}})}var go=`none`;function _o(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<=0))return Math.round(t*1e3)}function vo({hold:t,modes:n,onChange:r}){let{t:i}=Z(),a={held:i(`automation.hold.held`,`held`),stable:i(`automation.hold.stable`,`stable`)},o=e=>{if(e===go){r(void 0);return}let i=n.find(t=>t===e);if(i===void 0)return;let a=t?.ms??3e4;r(i===`stable`&&t?.tolerance!==void 0?{ms:a,mode:i,tolerance:t.tolerance}:{ms:a,mode:i})};return e(h,{children:[e(`label`,{className:`w-32`,children:[s($,{children:i(`automation.hold.label`,`For`)}),s(A,{value:t?.mode??go,onChange:e=>o(e.target.value),options:[{value:go,label:i(`automation.hold.none`,`no hold`)},...n.map(e=>({value:e,label:a[e]}))]})]}),t!==void 0&&e(`label`,{className:`w-24`,children:[s($,{children:i(`automation.hold.seconds`,`Seconds`)}),s(q,{type:`number`,min:1,value:String(t.ms/1e3),onChange:e=>{let n=_o(e.target.value);r(n===void 0?void 0:{...t,ms:n})}})]}),t?.mode===`stable`&&e(`label`,{className:`w-28`,children:[s($,{children:i(`automation.hold.tolerance`,`± tolerance`)}),s(q,{type:`number`,min:0,step:`any`,value:t.tolerance===void 0?``:String(t.tolerance),placeholder:`0`,onChange:e=>{let n=e.target.value.trim(),i=n===``?NaN:Number(n),{tolerance:a,...o}=t;r(Number.isNaN(i)||i<0?o:{...o,tolerance:i})}})]})]})}function yo({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:o}=Z(),c=Eo(n,r,i);if(n?.kind===`boolean`)return s(A,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:o(`common.true`)},{value:`false`,label:o(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return s(A,{value:String(t),onChange:e=>a(e.target.value),options:n.enumValues.map(e=>({value:e,label:e}))});if(n?.kind===`number`){let n=typeof t==`number`&&c?c.toDisplayValue(t):t;return e(`span`,{className:`inline-flex items-center gap-1`,children:[s(q,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?s(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return s(q,{value:String(t),placeholder:o(`common.valueWord`),onChange:e=>a(e.target.value)})}function bo({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Z(),o=Eo(t,n,r);return s(q,{value:(o?e.map(e=>typeof e==`number`?o.toDisplayValue(e):e):e).join(`, `),placeholder:a(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let n=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);i(t?.kind===`number`?n.map(e=>Number(e)).filter(e=>!Number.isNaN(e)).map(e=>o?o.fromDisplayValue(e):e):n)}})}function xo(e){return typeof e==`object`&&!qe(e)}function So(e){return qe(e)?e.value:xo(e)?e[0]??``:e}function Co(e){return qe(e)?[e.value]:xo(e)?e:typeof e==`boolean`?[]:[e]}function wo(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!_e(t)||t===`none`||t===`device`))return Ke(t).length>0?t:void 0}function To(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Eo(e,t,n){let r=_t(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=Ut({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=_e(s)?s:void 0,l=To(e?.quantity,c);if(l===void 0)return;let u=o?.display;return un({quantity:l,display:u,capName:n,unitPreferences:r})}function Do({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},o=Ta(a),c=sa(o?.kind),l=t.operator===`in`,u=wo(o),d=u===void 0?void 0:ye(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=Oo(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...Co(t.value)]:So(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[s(Ea,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[s($,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),s(A,{value:t.operator,onChange:e=>p(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[s($,{children:i(`automation.conditionRow.value`,`Value`)}),l?s(bo,{value:Co(t.value),field:o,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?s(gt,{quantity:u,storedUnit:d,value:typeof t.value==`number`?t.value:void 0,unit:t.unit,"aria-label":i(`automation.conditionRow.value`,`Value`),onChange:e=>{let n=bn(e,d);r({...t,value:n.value,unit:n.unit})}}):s(yo,{value:So(t.value),field:o,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]}),s(vo,{hold:t.for,modes:[`held`,`stable`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})]})}function Oo(e,t){return t.find(t=>t.value===e)?.value??`eq`}function ko({leaf:t,onChange:n}){let{t:r}=Z();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[s($,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),s(q,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>n({kind:`schedule`,cron:e.target.value})}),s(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:s(tr,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:s(`code`,{})}})})]})}function Ao(){return s(`p`,{className:`text-xs text-foreground-subtle`,children:s(tr,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:s(`strong`,{})}})})}function jo(e,t){return{kind:`device-becomes`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.operator===void 0||t.value===void 0?{}:{operator:t.operator,value:t.value},...t.hold===void 0?{}:{for:t.hold},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function Mo(e){return e.operator===void 0?e.becomes===void 0?`any`:`becomes`:e.operator}var No=[`any`,`becomes`,`gt`,`gte`,`lt`,`lte`,`between`,`outside`];function Po(e){return e===`between`||e===`outside`}function Fo(e){if(e.trim()===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function Io(e){return typeof e==`number`?e:void 0}function Lo({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},o=Ta(a),c=ze(t),l=Mo(t),u=Io(t.value),d=Array.isArray(t.value)?[t.value[0],t.value[1]]:[void 0,void 0],f={...t.becomes===void 0?{}:{becomes:t.becomes},...t.operator===void 0||t.value===void 0?{}:{operator:t.operator,value:t.value},...c===void 0?{}:{hold:c},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}},{becomes:p,operator:m,value:g,..._}=f,v=e=>{if(e===`any`){r(jo(a,_));return}if(e===`becomes`){r(jo(a,{..._,becomes:``}));return}let t=Ue.safeParse(e);t.success&&r(jo(a,{..._,operator:t.data,value:Po(t.data)?[0,0]:0}))},y={any:i(`automation.triggerEditor.anyChange`,`any change`),becomes:i(`automation.triggerEditor.becomesValue`,`becomes a value`),gt:i(`automation.triggerEditor.crossesAbove`,`rises above`),gte:i(`automation.triggerEditor.reachesAtLeast`,`reaches at least`),lt:i(`automation.triggerEditor.dropsBelow`,`drops below`),lte:i(`automation.triggerEditor.reachesAtMost`,`reaches at most`),between:i(`automation.triggerEditor.entersRange`,`enters the range`),outside:i(`automation.triggerEditor.leavesRange`,`leaves the range`),eq:i(`automation.triggerEditor.becomesValue`,`becomes a value`),ne:i(`automation.triggerEditor.stopsBeing`,`stops being`)};return e(h,{children:[s(Ea,{value:a,devices:n,onChange:e=>r(jo(e,f))}),e(`label`,{className:`min-w-[10rem]`,children:[s($,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),s(A,{value:l,onChange:e=>v(e.target.value),options:No.map(e=>({value:e,label:y[e]}))})]}),l===`becomes`&&t.becomes!==void 0&&e(`div`,{className:`min-w-[9rem] flex-1`,children:[s($,{children:i(`automation.conditionRow.value`,`Value`)}),s(yo,{value:t.becomes,field:o,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(jo(a,{...f,becomes:e}))})]}),t.operator!==void 0&&!Po(l)&&e(`label`,{className:`w-28`,children:[s($,{children:i(`automation.conditionRow.value`,`Value`)}),s(q,{type:`number`,step:`any`,value:u===void 0?``:String(u),onChange:e=>{let n=Fo(e.target.value);n!==void 0&&r(jo(a,{...f,operator:t.operator,value:n}))}})]}),t.operator!==void 0&&Po(l)&&[0,1].map(n=>e(`label`,{className:`w-24`,children:[s($,{children:n===0?i(`automation.triggerEditor.rangeFrom`,`From`):i(`automation.triggerEditor.rangeTo`,`To`)}),s(q,{type:`number`,step:`any`,value:d[n]===void 0?``:String(d[n]),onChange:e=>{let i=Fo(e.target.value);if(i===void 0)return;let o=[d[0]??0,d[1]??0];o[n]=i,r(jo(a,{...f,operator:t.operator,value:o}))}})]},n)),s(vo,{hold:c,modes:[`held`,`stable`],onChange:e=>{let{hold:t,...n}=f;r(jo(a,e===void 0?n:{...n,hold:e}))}}),e(`label`,{className:`w-28`,children:[s($,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),s(q,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(jo(a,{...f,debounceMs:Ro(e.target.value)}))})]})]})}function Ro(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function zo({leaf:e,devices:t=[],onChange:n}){return s(`div`,{className:`w-full min-w-0`,children:s(cr,{kind:`event`,shape:`category`,devicePickerTestId:`trigger-event-device`,excludeTypes:wr,deviceId:e.deviceId??null,category:e.category,knownDevices:t.map(e=>({id:e.id,name:e.name,...e.type===void 0?{}:{type:e.type}})),onDeviceChange:t=>n({kind:`device-event`,category:e.category,...t===null?{}:{deviceId:t}}),onCategoryChange:t=>n({kind:`device-event`,category:t,...e.deviceId===void 0?{}:{deviceId:e.deviceId}})})})}function Bo(e,t){let n=e.find(e=>e.id===t.deviceId);return{kind:`global`,sourceStableId:n?.stableId??``,...n?.addonId===void 0?{}:{addonId:n.addonId},cap:t.cap,fieldPath:t.fieldPath}}function Vo(e,t){if(t.addonId!==void 0)return e.find(e=>e.stableId===t.sourceStableId&&e.addonId===t.addonId)?.id??0;let n=e.filter(e=>e.stableId===t.sourceStableId);return n.length===1?n[0]?.id??0:0}var Ho={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Uo({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a=Object.entries(t.bindings),o=e=>{r({...t,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`block`,children:[s(en,{label:i(`automation.expressionLeafRow.expression`,`Expression`),value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),bindings:Object.keys(t.bindings),onChange:e=>r({...t,expr:e})}),s(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.mustEvaluateToTrueOr`,`Must evaluate to true or false. Every name in it has to be bound below — an unbound name is refused when the automation is saved, not when it runs.`)})]}),e(`div`,{className:`space-y-1.5`,children:[a.length===0&&s(`p`,{className:`text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),a.map(([e,r])=>s(Wo,{alias:e,source:r,devices:n,onRename:n=>o(qo(t.bindings,e,n)),onChange:n=>o({...t.bindings,[e]:n}),onRemove:()=>o(Jo(t.bindings,e))},e)),e(W,{variant:`ghost`,onClick:()=>o({...t.bindings,[Ko(t.bindings)]:Ho}),children:[s(j,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]}),s(`div`,{className:`flex flex-wrap items-end gap-2`,children:s(vo,{hold:t.for,modes:[`held`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})})]})}function Wo({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:o}){let{t:c}=Z(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:n.kind===`global`?Vo(r,n):0,cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[s($,{children:c(`automation.expressionLeafRow.name`,`Name`)}),s(q,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[s($,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),s(A,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Ho),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[s($,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),s(q,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Go(e.target.value)})})]}):s(Ea,{value:u,devices:r,onChange:e=>a(Bo(r,e))}),s(W,{variant:`ghost`,onClick:o,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:s(R,{className:`h-3.5 w-3.5`})})]})}function Go(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Ko(e){for(let t=0;t<26;t+=1){let n=String.fromCharCode(97+t);if(!(n in e))return n}return`n${String(Object.keys(e).length)}`}function qo(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Jo(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var Yo=`event-emitter`;function Xo(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`};let t=We.safeParse(e.data);return t.success?{kind:`known`,vocabulary:ke(t.data)}:{kind:`unknown`}}function Zo(e){let t=new Map;for(let n of e)n.source!==void 0&&!t.has(n.source.id)&&t.set(n.source.id,n.source);return[...t.values()]}function Qo(e,t){let n=new Map;for(let r of e)t!==void 0&&r.source?.id!==t||n.has(r.id)||n.set(r.id,r);return[...n.values()]}function $o(e,t){return{kind:`device-fired`,...e.id===void 0?{}:{id:e.id},deviceId:t}}function es(e,t,n){let{sourceIds:r,eventIds:i,...a}=e,o=new Set(Qo(n,t).map(e=>e.id)),s=(i??[]).filter(e=>o.has(e));return{...a,...t===void 0?{}:{sourceIds:[t]},...s.length===0?{}:{eventIds:s}}}function ts(e,t){let{eventIds:n,...r}=e;return{...r,...t===void 0?{}:{eventIds:[t]}}}function ns(e,t){let n=new Set(Zo(t).map(e=>e.id)),r=new Set(t.map(e=>e.id));return{sourceIds:(e.sourceIds??[]).filter(e=>!n.has(e)),eventIds:(e.eventIds??[]).filter(e=>!r.has(e))}}var rs=``,is={caps:[Yo]};function as({leaf:t,hideDevice:n=!1,onChange:r}){let{t:i}=Z(),a=t.deviceId>0,o=hn({deviceId:t.deviceId,capName:Yo},{enabled:a}),c=Xo({status:o.status,data:o.data}),l=c.kind===`known`?c.vocabulary:[],u=Zo(l),d=t.sourceIds?.[0],f=t.eventIds?.[0],p=Qo(l,d),m=c.kind===`known`?ns(t,l):null,g=i(`automation.fired.anyEvent`,`Any event`),_=c.kind===`pending`?i(`automation.fired.loading`,`Reading what this device can fire…`):i(`automation.fired.unknown`,`What this device can fire could not be read.`);return e(h,{children:[!n&&e(`div`,{className:`min-w-[13rem] flex-1`,children:[s($,{children:i(`automation.fired.device`,`Device`)}),s(En,{pick:`device`,requires:is,recentKey:`automation-device-fired`,value:a?{deviceId:t.deviceId}:null,onChange:e=>r($o(t,e?.deviceId??0))})]}),a&&c.kind!==`known`&&s(`p`,{className:`min-w-[13rem] flex-1 text-xs ${c.kind===`unknown`?`text-warning`:`text-foreground-subtle`}`,"data-testid":`fired-vocabulary-${c.kind}`,children:_}),a&&c.kind===`known`&&u.length>0&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[s($,{children:i(`automation.fired.source`,`From`)}),s(A,{"data-testid":`fired-source`,value:d??rs,onChange:e=>r(es(t,e.target.value===rs?void 0:e.target.value,l)),options:[{value:rs,label:i(`automation.fired.anySource`,`Any button`)},...u.map(e=>({value:e.id,label:e.label})),...(m?.sourceIds??[]).map(e=>({value:e,label:i(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),a&&c.kind===`known`&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[s($,{children:i(`automation.fired.event`,`Event`)}),s(A,{"data-testid":`fired-event`,value:f??rs,onChange:e=>r(ts(t,e.target.value===rs?void 0:e.target.value)),options:[{value:rs,label:g},...p.map(e=>({value:e.id,label:e.label})),...(m?.eventIds??[]).map(e=>({value:e,label:i(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),m!==null&&m.sourceIds.length+m.eventIds.length>0&&s(`p`,{className:`basis-full text-xs text-warning`,"data-testid":`fired-stale`,children:i(`automation.fired.staleHint`,`This row names something the device no longer declares, so it will not start a run. Pick again.`)}),(t.kinds!==void 0||t.match!==void 0)&&s(`p`,{className:`basis-full text-xs text-foreground-subtle`,"data-testid":`fired-extra`,children:i(`automation.fired.extraHint`,`This row also carries filters set outside the editor ({{what}}); they are kept as they are.`,{what:[...t.kinds??[],...(t.match??[]).map(e=>`${e.path} = ${String(e.equals)}`)].join(`, `)})})]})}var os=`text-xs text-foreground-subtle`;function ss({children:e}){return s(`span`,{className:os,children:e})}function cs(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function ls({selected:t,onChange:n}){let{t:r}=Z();return e(`div`,{className:`space-y-1`,children:[s(ss,{children:r(`flow.scene.cameras`,`Cameras`)}),s(En,{multiple:!0,pick:`device`,noun:`camera`,fixedTypes:jr,recentKey:`build-cameras`,value:jt(t),testId:`scene-cameras`,onChange:e=>n(Tt(e))})]})}function us({device:t,deviceId:n,selected:r,onToggle:i}){let a=wt({deviceId:n});return a.data===void 0||a.data.length===0?null:e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:os,children:t?.name??`#${String(n)}`}),a.data.map(e=>s(W,{size:`sm`,variant:r.includes(e.id)?`primary`:`outline`,"aria-pressed":r.includes(e.id),onClick:()=>i(e.id),children:e.name},e.id))]})}function ds({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=Z();if(n.length===0)return null;let o=e=>{let t=cs(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[s(ss,{children:a(`flow.scene.zones`,`Zones`)}),s(`div`,{className:`space-y-2`,children:n.map(e=>s(us,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:o},e))}),s(`p`,{className:os,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var fs=[`animal`,`person`,`vehicle`,`package`,`other`];function ps(e){return fs.find(t=>t===e)??`other`}function ms(e){switch(e){case`animal`:return{macro:`animal`};case`person`:return{macro:`person`};case`vehicle`:return{macro:`vehicle`};case`package`:return{macro:`package`};default:return{macro:`other`,className:``}}}function hs(){let{t:e}=Z();return t=>{switch(t){case`person`:return e(`flow.class.person`,`Person`);case`vehicle`:return e(`flow.class.vehicle`,`Vehicle`);case`animal`:return e(`flow.class.animal`,`Animal`);case`package`:return e(`flow.class.package`,`Package`);default:return e(`automation.whenTree.macroOther`,`Other class`)}}}function gs(e,t){let n={kind:`sub-class`,className:t};switch(e){case`animal`:return{macro:e,label:n};case`package`:return{macro:e,label:n};case`vehicle`:return{macro:e,label:n};default:return{macro:`person`}}}var _s=[`automation`,`class-taxonomy`];function vs(){let e=ee();return Se(u({queryKey:_s,retry:!1,staleTime:1/0,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}).data?.taxonomy)}function ys(e,t,n){let r=n?.groups.find(t=>t.key===e),i=r===void 0?tt(e).filter(t=>t!==e).map(e=>({value:e,label:e})):r.options.filter(t=>t.value!==e).map(e=>({value:e.value,label:e.label}));return t!==void 0&&!i.some(e=>e.value===t)?[...i,{value:t,label:t}]:i}function bs({subject:e,onChange:t}){let{t:n}=Z(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=vs(),a=ys(e.macro,r,i);return a.length===0?null:s(A,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:r??``,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...a],onChange:n=>{let r=n.target.value;t(r===``?ms(e.macro):gs(e.macro,r))}})}function xs({onChange:e,subject:t}){let{t:n}=Z(),r=Yt(),i=t.macro===`person`?t.label:void 0,a=r.data??[],o=a.map(e=>({value:e.id,label:e.name}));return i!==void 0&&!a.some(e=>e.id===i.identityId)&&o.push({value:i.identityId,label:i.name}),s(A,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:i?.identityId??``,options:[{value:``,label:n(`automation.whenTree.anyPerson`,`Anyone`)},...o],onChange:t=>{let n=t.target.value,r=o.find(e=>e.value===n);e(n===``||r===void 0?{macro:`person`}:{macro:`person`,label:{kind:`identity`,identityId:n,name:r.label}})}})}var Ss=`plate:`,Cs=`class:`,ws=200;function Ts({onChange:e,subject:t}){let{t:n}=Z(),r=nn({includeCrops:!1,limit:ws}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,o=vs(),c=i?.kind===`sub-class`?i.className:void 0,l=[...new Set((r.data??[]).map(e=>e.text))];a!==void 0&&!l.includes(a)&&l.push(a);let u=a===void 0?c===void 0?``:`${Cs}${c}`:`${Ss}${a}`;return s(A,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:u,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...ys(`vehicle`,c,o).map(e=>({value:`${Cs}${e.value}`,label:e.label})),...l.map(e=>({value:`${Ss}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(Ss)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(Cs)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function Es({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:o}=Z(),c=hs(),l=t.macro===`other`?[]:Xe[t.macro],u=l.some(e=>e.kind===`cap`&&e.label===`identity`),d=l.some(e=>e.kind===`cap`&&e.label===`plate`);return e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`subject-row`,children:[s(`div`,{className:`w-36`,children:s(A,{"aria-label":o(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:fs.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=ps(e.target.value);n!==t.macro&&i(ms(n))}})}),s(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?s(q,{className:`w-40`,"aria-label":o(`automation.whenTree.className`,`Class name`),"data-testid":`subject-class-name`,placeholder:o(`automation.whenTree.classNamePlaceholder`,`Class name`),value:t.className,onChange:e=>i({macro:`other`,className:e.target.value})}):u&&!n?s(`div`,{className:`w-44`,children:s(xs,{subject:t,onChange:i})}):d&&!n?s(`div`,{className:`w-44`,children:s(Ts,{subject:t,onChange:i})}):!u&&s(`div`,{className:`w-44`,children:s(bs,{subject:t,onChange:i})}),a!==null&&s(W,{variant:`ghost`,onClick:a,title:o(`automation.whenTree.removeClass`,`Remove this class`),children:s(R,{className:`h-3.5 w-3.5`})})]})}function Ds({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:o}=Z(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>s(Es,{subject:e,classLabelsOnly:r,verb:n===0?i:o(`automation.whenTree.orSubject`,`or`),onChange:e=>a(t.map((t,r)=>r===n?e:t)),onRemove:c?()=>a(t.filter((e,t)=>t!==n)):null},`${e.macro}-${String(n)}`)),t.length===0&&s(`p`,{className:`text-xs text-foreground-subtle`,children:o(`flow.scene.anyClass`,`None picked: any class counts.`)}),e(W,{variant:`ghost`,size:`sm`,onClick:()=>a([...t,ms(`person`)]),children:[s(j,{className:`h-3.5 w-3.5`}),` `,t.length===0?o(`automation.whenTree.onlySomeClasses`,`Only some classes`):o(`automation.whenTree.addClass`,`Add a class`)]})]})}var Os=100;function ks({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a=Math.round((t.minScore??0)*Os),o=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{minScore:n,...i}=t;r(e<=0?i:{...i,minScore:e/Os})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[s(Ds,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),s(ls,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),s(ds,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:o}),e(`div`,{className:`space-y-1`,children:[s(ss,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/Os).toFixed(2)})}),s(b,{min:0,max:Os,value:a,"aria-label":i(`flow.scene.minScoreAria`,`Minimum score`),className:`block w-full max-w-sm accent-primary`,onChange:e=>c(Number(e.target.value))})]})]})}function As({leaf:t,devices:n,onChange:r}){let{t:i}=Z();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[s(Ds,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.parked`,`object`),onChange:e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})}}),s(ls,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),s(ds,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),s(On,{label:i(`flow.scene.firesWhen`,`Fires when it`),value:t.phase,onChange:e=>r({...t,phase:e}),options:[{value:`appeared`,label:i(`flow.scene.phaseAppeared`,`Stopped (parked)`)},{value:`departed`,label:i(`flow.scene.phaseDeparted`,`Left`)}]})]})}function js({leaf:t,onChange:n}){let{t:r}=Z();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[s(ss,{children:r(`flow.scene.every`,`Every`)}),s(Er,{"aria-label":r(`flow.scene.intervalMinutes`,`Minutes`),className:`w-20`,value:t.minutes,onValue:e=>{e!==null&&n({kind:`interval`,minutes:Math.round(e)})}}),s(ss,{children:r(`flow.scene.minutes`,`minutes`)})]})}function Ms({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},o=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{zones:n,...i}=t;r({...i,deviceId:e})};return e(`div`,{className:`space-y-3`,"data-testid":`stationary-present-fields`,children:[e(`div`,{className:`space-y-1`,children:[s(ss,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),s(En,{pick:`device`,noun:`camera`,fixedTypes:jr,recentKey:`build-cameras`,clearable:!1,value:t.deviceId>0?{deviceId:t.deviceId}:null,testId:`stationary-present-camera`,onChange:e=>{e!==null&&e.deviceId!==t.deviceId&&c(e.deviceId)}})]}),s(Ds,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.isParked`,`is parked`),onChange:a}),e(`div`,{className:`flex items-center gap-2`,children:[s(ss,{children:i(`flow.scene.minCount`,`At least`)}),s(Er,{"aria-label":i(`flow.scene.minCountAria`,`Minimum parked objects`),"data-testid":`stationary-present-min-count`,className:`w-20`,value:t.minCount??1,onValue:e=>{let{minCount:n,...i}=t;r(e===null||e<=1?i:{...i,minCount:Math.floor(e)})}}),s(ss,{children:i(`flow.scene.minCountUnit`,`parked objects`)})]}),s(ds,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:o})]})}var Ns=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],Ps=720,Fs=1440;function Is(){return{name:``,enabled:!0,priority:0,maxLateMs:oe,profiles:[Ls(`profile-1`,`Every day`)]}}function Ls(e,t){return{id:e,name:t,enabled:!0,days:[...Ns],points:[]}}function Rs(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function zs(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function Bs(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function Vs(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,hourCycle:`h23`,hour:`2-digit`,minute:`2-digit`}).formatToParts(new Date(e)),r=e=>Number(n.find(t=>t.type===e)?.value??0);return r(`hour`)*60+r(`minute`)}function Hs(e,t=Date.now()){return Le(t,e.timeZone)}function Us(e,t,n){let r=Bs(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=it(e,n,r);return i===null?null:Vs(i,t.timeZone)}function Ws(e,t,n){return e.kind===`sun`?Us({...e,offsetMin:0},t,n):null}function Gs(e,t,n){if(e.kind===`clock`)return{kind:`clock`,hh:Math.floor(t/60),mm:t%60};if(e.kind===`sun`&&n!==null){let r=Math.max(-720,Math.min(Ps,t-n));return{...e,offsetMin:r}}return e}function Ks(e){let t=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(e);return t===null?null:{kind:`clock`,hh:Number(t[1]),mm:Number(t[2])}}function qs(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function Js(e){return qs(Math.floor(e/60),e%60)}function Ys(e,t,n){let r=e.flatMap(e=>{let r=Us(e.at,t,n);return r===null?[]:[{point:e,minute:r}]}).toSorted((e,t)=>e.minute-t.minute);return r.flatMap((e,t)=>{if(e.point.mode!==`hold`)return[];let n=r[t+1];return[{id:e.point.id,fromMinute:e.minute,toMinute:n===void 0?Fs:n.minute}]})}function Xs(e,t){let n=ue.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=me(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}var Zs=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],Qs=[`sunrise`,`sunset`,`dawn`,`dusk`],$s={from:{kind:`clock`,hh:22,mm:0},to:{kind:`clock`,hh:6,mm:0}};function ec(e,t){return{kind:`time-is`,...e===void 0?{}:{between:e},...t===void 0?{}:{days:[...t]}}}function tc(e){return e.days??Zs}function nc(e,t){let n=tc(e),r=n.includes(t)?n.filter(e=>e!==t):Zs.filter(e=>e===t||n.includes(e)),i=r.length===Zs.length;return ec(e.between,i&&e.between!==void 0?void 0:r)}function rc(e,t){if(t){let t=e.days!==void 0&&e.days.length===Zs.length;return ec(e.between??$s,t?void 0:e.days)}return ec(void 0,tc(e))}function ic(e,t,n){return ec({...e.between??$s,[t]:n},e.days)}function ac(e){return e===`sun`?{kind:`sun`,event:`sunset`,offsetMin:0}:{kind:`clock`,hh:12,mm:0}}function oc(e){return e.kind===`date`?ac(`clock`):e}function sc(e){let t=e.between;return t===void 0||t.from.kind!==`clock`||t.to.kind!==`clock`?!1:t.to.hh*60+t.to.mm<=t.from.hh*60+t.from.mm}function cc(e,t){if(t===void 0)return null;let n=Ce(e,t)[0];return n===void 0?null:`${n.path}: ${n.message}`}function lc({label:t,testId:n,end:r,onChange:i}){let{t:a}=Z(),o=e=>`${t}: ${e}`;return e(`div`,{role:`group`,"aria-label":t,"data-testid":n,children:[s($,{children:t}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(A,{wrapperClassName:`relative w-40`,"aria-label":t,value:r.kind,options:[{value:`clock`,label:a(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:a(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{let t=e.target.value;(t===`clock`||t===`sun`)&&t!==r.kind&&i(ac(t))}}),r.kind===`clock`&&s(q,{type:`time`,className:`w-28`,"aria-label":o(a(`schedulers.point.time`,`Time`)),value:qs(r.hh,r.mm),onChange:e=>{let t=Ks(e.target.value);t!==null&&t.kind===`clock`&&i(t)}}),r.kind===`sun`&&e(h,{children:[s(A,{wrapperClassName:`relative w-40`,"aria-label":o(a(`schedulers.point.sunEvent`,`Sun event`)),value:r.event,options:Qs.map(e=>({value:e,label:a(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Qs.find(t=>t===e.target.value);t!==void 0&&i({...r,event:t})}}),s(Er,{"aria-label":o(a(`schedulers.point.offset`,`Offset (minutes, negative = before)`)),title:a(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-20`,value:r.offsetMin,onValue:e=>{e!==null&&i({...r,offsetMin:Math.round(e)})}})]})]})]})}function uc({leaf:t,onChange:n}){let{t:r}=Z(),i=t.between,a=tc(t);return e(`div`,{className:`flex w-full flex-col gap-2`,"data-testid":`time-is-fields`,children:[e(`div`,{className:`flex flex-wrap items-end gap-x-4 gap-y-2`,children:[e(`label`,{children:[s($,{children:r(`automation.timeIs.window`,`Time of day`)}),s(A,{wrapperClassName:`relative w-40`,"aria-label":r(`automation.timeIs.window`,`Time of day`),value:i===void 0?`whole-day`:`between`,options:[{value:`between`,label:r(`automation.timeIs.between`,`Between two times`)},{value:`whole-day`,label:r(`automation.timeIs.wholeDay`,`The whole day`)}],onChange:e=>n(rc(t,e.target.value===`between`))})]}),i!==void 0&&e(h,{children:[s(lc,{label:r(`automation.timeIs.from`,`From`),testId:`time-is-from`,end:oc(i.from),onChange:e=>n(ic(t,`from`,e))}),s(lc,{label:r(`automation.timeIs.to`,`To`),testId:`time-is-to`,end:oc(i.to),onChange:e=>n(ic(t,`to`,e))})]})]}),e(`div`,{children:[s($,{children:r(`schedulers.profile.days`,`Days`)}),s(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":r(`schedulers.profile.days`,`Days`),children:Zs.map(e=>{let i=a.includes(e);return s(W,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,onClick:()=>n(nc(t,e)),children:r(`schedulers.day.${e}`,e)},e)})}),a.length===0&&s(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`time-is-no-days`,children:r(`automation.timeIs.noDays`,`Pick at least one day.`)}),sc(t)&&s(`p`,{className:`mt-1 text-xs text-foreground-subtle`,"data-testid":`time-is-wraps`,children:r(`automation.timeIs.wraps`,`This window ends the next day. The days are the days it starts on.`)})]})]})}function dc(e,t){let n=e.leaf;if(n.kind!==`device-becomes`&&n.kind!==`device-event`&&n.kind!==`device-fired`)return;let r=t.find(e=>e.id===n.deviceId)?.name;return n.kind===`device-becomes`?r:n.kind===`device-fired`?[r,[...n.sourceIds??[],...n.eventIds??[]].join(` `)].filter(e=>e!==void 0&&e!==``).join(` · `)||void 0:r===void 0?n.category:`${n.category} · ${r}`}function fc({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a=uo(),o=a.map(e=>e.id),c=oo(t,o),l=i(`automation.triggeredBy.triggers`,`Started by`);return e(`div`,{children:[s($,{children:l}),a.length===0?s(`p`,{className:`text-xs text-warning`,"data-testid":`triggered-by-no-rows`,children:i(`automation.triggeredBy.noRows`,`This automation has no trigger row to choose. Add one to the rules first.`)}):s(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":l,children:a.map(e=>{let i=t.leafIds.includes(e.id),a=dc(e,n);return s(W,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,className:`h-auto min-h-8 whitespace-normal py-1 text-left`,onClick:()=>r(ao(t,e.id,o)),children:`${e.ordinal}. ${ca(e.leaf.kind)}${a===void 0?``:` · ${a}`}`},e.id)})}),a.length>0&&t.leafIds.length===0&&s(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-none-picked`,children:i(`automation.triggeredBy.nonePicked`,`Pick at least one trigger.`)}),c.length>0&&s(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-missing`,children:i(`automation.triggeredBy.missing`,{count:c.length,defaultValue_one:`{{count}} chosen trigger no longer exists. Press a trigger to drop it.`,defaultValue_other:`{{count}} chosen triggers no longer exist. Press a trigger to drop them.`})})]})}function pc(e){return e.kind===`all`||e.kind===`any`}function mc(e){return[`when`,...e].join(`.`)}function hc(e){let t=e.when;return pc(t)?t:{kind:`all`,children:[t]}}function gc(e,t){return{...e,when:t}}function _c(e){return gc(e,hc(e))}function vc(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?vc(e.child,r):null;if(rt(e))return null;let i=e.children[n];return i===void 0?null:vc(i,r)}function yc(e,t,n){let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=yc(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(rt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=yc(a,i,n),s=o===null?[...e.children.slice(0,r),...e.children.slice(r+1)]:[...e.children.slice(0,r),o,...e.children.slice(r+1)];return s.length===0?null:{kind:e.kind,children:s}}function bc(e,t,n){let r=hc(e);return gc(e,yc(r,t,n)??{kind:r.kind,children:[]})}function xc(e){return{kind:e,children:[fa(`device-is`)]}}function Sc(e,t,n){return bc(e,t,e=>pc(e)?{kind:e.kind,children:[...e.children,n]}:e)}function Cc(e,t,n){return bc(e,t,()=>n)}function wc(e,t){return bc(e,t,()=>null)}function Tc(e,t,n){return bc(e,t,e=>pc(e)?{kind:n,children:e.children}:e)}function Ec(e,t){return t.length===0?e:bc(e,t,e=>({kind:`not`,child:e}))}function Dc(e,t){return bc(e,t,e=>e.kind===`not`?e.child:e)}function Oc(e,t){if(e.kind===t)return e;if(e.kind===`device-is`&&t===`device-becomes`){let{deviceId:n,cap:r,fieldPath:i,operator:a,value:o}=e,s={kind:t,deviceId:n,cap:r,fieldPath:i};return a===`eq`&&!Array.isArray(o)&&typeof o!=`object`?{...s,becomes:o}:s}if(e.kind===`device-becomes`&&t===`device-is`){let{deviceId:n,cap:r,fieldPath:i,becomes:a}=e;return{kind:t,deviceId:n,cap:r,fieldPath:i,operator:`eq`,value:a??``}}let n=fa(t);return Ve(e)&&e.id!==void 0&&Ve(n)?{...n,id:e.id}:n}function kc(e){let t=hc(e),n=t.children.length===0;return{depth:n?0:et(t),leaves:n?0:Ie(t),depthLimit:4,leafLimit:32}}function Ac(e,t){let n=hc(e),r=1,i=n;for(let e of t){let t=vc(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function jc(e,t,n){let r=t[t.length-1];if(r===void 0)return e;let i=t.slice(0,-1),a=vc(hc(e),i);if(a===null||!pc(a))return e;let o=r+n;return o<0||o>=a.children.length?e:bc(e,i,()=>({kind:a.kind,children:ha(a.children,r,o)}))}function Mc(e,t,n){let r=mc(t),i=mc(n),a=e=>e===r||e.startsWith(`${r}.`)?i+e.slice(r.length):e===i||e.startsWith(`${i}.`)?r+e.slice(i.length):e;return new Set([...e].map(a))}function Nc(e,t){return rt(e)?t(e.kind):e.kind===`not`?`NOT ${Nc(e.child,t)}`:e.children.map(e=>Pc(e,t)).join(` · `)}function Pc(e,t){return pc(e)?`${e.kind.toUpperCase()} (${Nc(e,t)})`:Nc(e,t)}d();function Fc({leaf:t,devices:n,context:r,underNot:i,toneClass:a,result:o,onNegate:c,move:u,onChange:d,onRemove:f}){let{t:p}=Z(),[m,h]=l(!1),g=Ve(t);return e(`div`,{className:`rounded border p-2 ${a}`,"data-testid":`when-row`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`div`,{className:`min-w-[13rem] max-w-xs flex-1`,children:[s($,{children:p(`automation.whenTree.rowType`,`Row type`)}),e(W,{variant:`outline`,"data-testid":`when-row-type`,className:`w-full justify-between`,onClick:()=>h(!0),title:p(`automation.leafPicker.changeType`,`Change type`),children:[s(`span`,{className:`truncate`,children:ca(t.kind)}),s(`span`,{className:`text-foreground-subtle`,children:p(`automation.leafPicker.changeType`,`Change type`)})]}),s(ho,{open:m,onOpenChange:h,mode:`change`,context:r,underNot:i,treeFull:!1,current:t.kind,onPick:e=>{e!==t.kind&&d(Oc(t,e))}})]}),s(Y,{variant:g?`info`:`neutral`,"data-testid":`when-row-nature`,children:g?p(`automation.whenTree.natureEvent`,`Event`):p(`automation.whenTree.natureState`,`State`)}),s(`span`,{className:`flex-1`}),u!==void 0&&s(Pa,{move:u}),c!==null&&s(W,{variant:`ghost`,onClick:c,title:p(`automation.whenTree.negateRow`,`Invert this row (NOT)`),children:`NOT`}),s(W,{variant:`ghost`,onClick:f,title:p(`automation.whenTree.removeRow`,`Remove this row`),children:s(R,{className:`h-3.5 w-3.5`})})]}),s(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:s(Ic,{leaf:t,devices:n,onChange:d})}),o!==void 0&&s(`div`,{className:`mt-2`,children:o})]})}function Ic({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return s(Lo,{leaf:e,devices:t,onChange:n});case`device-event`:return s(zo,{leaf:e,devices:t,onChange:n});case`device-fired`:return s(as,{leaf:e,onChange:n});case`schedule`:return s(ko,{leaf:e,onChange:n});case`interval`:return s(js,{leaf:e,onChange:n});case`manual`:return s(Ao,{});case`detection`:return s(ks,{leaf:e,devices:t,onChange:n});case`stationary`:return s(As,{leaf:e,devices:t,onChange:n});case`device-is`:return s(Do,{leaf:e,devices:t,onChange:n});case`stationary-present`:return s(Ms,{leaf:e,devices:t,onChange:n});case`expression`:return s(Uo,{leaf:e,devices:t,onChange:n});case`time-is`:return s(uc,{leaf:e,onChange:n});case`triggered-by`:return s(fc,{leaf:e,devices:t,onChange:n})}}d();function Lc(e){return e===`any`?`any`:`all`}function Rc(e){return e===`pass`?`pass`:e===`fail`?`fail`:`idle`}function zc(e,t,n=!0){return e===void 0?t:n?Li(Rc(e)):zi(Rc(e))}function Bc(e,t){return e.run?.nodes.get(mc(t))}function Vc({recipe:t,devices:n,onChange:r,run:i=null,hideRule:a=!1,context:o=`trigger`}){let{t:c}=Z(),u=hc(t),d=kc(t),[f,p]=l(()=>new Set),m={leafContext:o,recipe:t,devices:n,run:i,onChange:r,reshape:e=>{p(new Set),r(e)},collapsed:f,toggleCollapsed:e=>{let t=mc(e);p(e=>e.has(t)?new Set([...e].filter(e=>e!==t)):new Set([...e,t]))},moveControls:(e,n)=>{let i=e[e.length-1]??0,a=n=>()=>{let a=[...e.slice(0,-1),i+n];p(t=>Mc(t,e,a)),r(jc(t,e,n))};return{up:i>0?a(-1):null,down:i<n-1?a(1):null}}},h=u.children.length===0;return e(`div`,{className:`space-y-2`,"data-testid":`when-tree`,children:[!a&&s(`p`,{className:`text-xs text-foreground-subtle`,children:c(`automation.whenTree.rule`,`An event starts a run when it happens and everything here is true at that moment. With only states, a run starts when they become true.`)}),s(Xc,{block:u,path:[],ctx:m,underNot:!1,rail:0,budgetText:c(`automation.whenTree.budget`,{depth:d.depth,depthLimit:d.depthLimit,leaves:d.leaves,leafLimit:d.leafLimit}),move:null,emptyHint:h&&!a?c(`automation.whenTree.empty`,`Add a row to say when this runs. Without one nothing can ever start this automation.`):null})]})}function Hc({node:e,path:t,ctx:n,underNot:r,move:i,rail:a}){return rt(e)?s(Uc,{leaf:e,path:t,ctx:n,underNot:r,move:i}):e.kind===`not`?s(Yc,{child:e.child,path:t,ctx:n,move:i,rail:a}):s(Xc,{block:e,path:t,ctx:n,underNot:r,move:i,rail:a,budgetText:null,emptyHint:null})}function Uc({leaf:e,path:t,ctx:n,underNot:r,move:i}){let a=Bc(n,t),o=n.run!==null&&n.run.triggerPath===mc(t)?n.run.vars:void 0;return s(Fc,{leaf:e,devices:n.devices,context:n.leafContext,underNot:r,toneClass:zc(a?.outcome,`border-border`),result:a===void 0?void 0:s(Wc,{leaf:e,node:a,vars:o}),onNegate:r?null:()=>n.reshape(Ec(n.recipe,t)),...i===null?{}:{move:i},onChange:e=>n.onChange(Cc(n.recipe,t,e)),onRemove:()=>n.reshape(wc(n.recipe,t))})}function Wc({leaf:e,node:t,vars:n}){return e.kind===`device-is`&&e.unit!==void 0?s(Gc,{leaf:e,node:t,vars:n}):s(Ca,{node:t,vars:n,expected:t.expected,observed:t.observed})}function Gc({leaf:e,node:t,vars:n}){let r=wo(Ta({deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})),i=r===void 0?void 0:ye(r),a=t=>t===void 0?null:wi(t,i,e.unit);return s(Ca,{node:t,vars:n,expected:a(t.rawExpected),observed:a(t.rawObserved)})}function Kc({node:e}){return e===void 0?null:s(Ca,{node:e,expected:null,observed:null})}function qc({expanded:e,onToggle:t}){let{t:n}=Z(),r=e?n(`automation.whenTree.collapse`,`Collapse this block`):n(`automation.whenTree.expand`,`Expand this block`);return s(W,{variant:`ghost`,"aria-expanded":e,"aria-label":r,title:r,onClick:t,children:s(ft,{expanded:e})})}function Jc({node:e}){let{t}=Z(),n=`${t(`automation.whenTree.rowCount`,{count:Ie(e)})} · ${Nc(e,ca)}`;return s(`p`,{"data-testid":`when-block-summary`,title:n,className:`break-words text-xs text-foreground-muted sm:truncate`,children:n})}function Yc({child:t,path:n,ctx:r,move:i,rail:a}){let{t:o}=Z(),c=!r.collapsed.has(mc(n));return e(`div`,{className:`space-y-1.5 rounded border p-2 ${zc(Bc(r,n)?.outcome,`border-warning/40`,!1)}`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(qc,{expanded:c,onToggle:()=>r.toggleCollapsed(n)}),s(Y,{variant:`warning`,children:`NOT`}),s(`span`,{className:`text-xs text-foreground-subtle`,children:o(`automation.whenTree.notHint`,`True when what is below is not`)}),s(`span`,{className:`flex-1`}),i!==null&&s(Pa,{move:i}),e(W,{variant:`ghost`,onClick:()=>r.reshape(Dc(r.recipe,n)),title:o(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[s(lt,{className:`h-3.5 w-3.5`}),` `,o(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),s(Kc,{node:Bc(r,n)}),c?s(`div`,{className:`pl-3`,children:s(Hc,{node:t,path:[...n,0],ctx:r,underNot:!0,move:null,rail:a})}):s(Jc,{node:t})]})}function Xc({block:t,path:n,ctx:r,underNot:i,move:a,rail:o,budgetText:c,emptyHint:u}){let{t:d}=Z(),f=n.length===0,p=f||!r.collapsed.has(mc(n)),m=Ac(r.recipe,n),[h,g]=l(!1),_=Qa(t.children,o),v=[{value:`all`,label:d(`automation.whenTree.allOf`,`All of (AND)`)},{value:`any`,label:d(`automation.whenTree.anyOf`,`Any of (OR)`)}];return e(`div`,{className:`space-y-2 rounded border p-2 ${zc(Bc(r,n)?.outcome,`border-border`,!1)}`,"data-testid":`when-block`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[!f&&s(qc,{expanded:p,onToggle:()=>r.toggleCollapsed(n)}),s(`div`,{className:`w-40`,children:s(A,{"aria-label":d(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:v,onChange:e=>r.onChange(Tc(r.recipe,n,Lc(e.target.value)))})}),c!==null&&s(`span`,{className:`text-xs text-foreground-subtle`,children:c}),s(`span`,{className:`flex-1`}),a!==null&&s(Pa,{move:a}),!f&&!i&&s(W,{variant:`ghost`,onClick:()=>r.reshape(Ec(r.recipe,n)),title:d(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!f&&s(W,{variant:`ghost`,onClick:()=>r.reshape(wc(r.recipe,n)),title:d(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:s(R,{className:`h-3.5 w-3.5`})})]}),s(Kc,{node:Bc(r,n)}),u!==null&&s(`p`,{className:`text-xs text-foreground-subtle`,children:u}),!p&&s(Jc,{node:t}),p&&t.children.length>0&&s(`div`,{className:`space-y-1.5 border-l-2 pl-3 ${$a(o)}`,"data-testid":`when-block-rail`,"data-rail":o,children:t.children.map((e,i)=>s(Hc,{node:e,path:[...n,i],ctx:r,underNot:!1,move:r.moveControls([...n,i],t.children.length),rail:_[i]??o},mc([...n,i])))}),p&&e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(W,{variant:`outline`,onClick:()=>g(!0),title:d(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[s(j,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addRow`,`Add row`)]}),s(ho,{open:h,onOpenChange:g,mode:`add`,context:r.leafContext,underNot:i,treeFull:Ie(hc(r.recipe))>=32,onPick:e=>r.onChange(Sc(r.recipe,n,fa(e)))}),e(W,{variant:`outline`,disabled:!m,onClick:()=>r.onChange(Sc(r.recipe,n,xc(t.kind===`all`?`any`:`all`))),title:m?d(`automation.whenTree.addBlockTitle`,`Add a nested block of rows`):d(`automation.whenTree.tooDeep`,`The rules nest at most {{max}} levels deep`,{max:kc(r.recipe).depthLimit}),children:[s(j,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addBlock`,`Add block`)]})]})]})}var Zc={kind:`all`,children:[]};function Qc(e){return e.kind===`wait`||e.kind===`command`}function $c(e){return!rt(e)&&e.kind!==`not`&&e.children.length===0?null:Je(e)}function el(e){let{if:t,else:n,...r}=e;return r}function tl({when:t,devices:n,hint:r,onChange:i,children:a}){let{t:o}=Z(),c=t===void 0?null:{when:t,actions:[]},l=t===void 0?null:$c(t);return e(`div`,{className:`space-y-2 border-t border-border-subtle pt-2`,children:[s(G,{checked:t!==void 0,label:o(`automation.stepGuard.if`,`Only if…`),"aria-label":o(`automation.stepGuard.if`,`Only if…`),onCheckedChange:e=>i(e?Zc:void 0)}),c!==null&&e(h,{children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:r}),s(Vc,{hideRule:!0,context:`guard`,recipe:c,devices:n,onChange:e=>i(e.when)}),l!==null&&s(K,{variant:`warning`,message:l}),a]})]})}function nl({step:t,devices:n,devicesState:r,variables:i,onChange:a}){let{t:o}=Z();return e(tl,{when:t.if,devices:n,hint:o(`automation.stepGuard.hint`,`Checked when this step is reached. If a state cannot be read, the step and its else are both skipped.`),onChange:e=>a(e===void 0?el(t):{...t,if:e}),children:[s(G,{checked:t.else!==void 0,label:o(`automation.stepGuard.else`,`Otherwise, run…`),"aria-label":o(`automation.stepGuard.else`,`Otherwise, run…`),onCheckedChange:e=>{if(e)a({...t,else:[]});else{let{else:e,...n}=t;a(n)}}}),t.else!==void 0&&s(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:s(_l,{nested:!0,actions:t.else,devices:n,...r===void 0?{}:{devicesState:r},...i===void 0?{}:{variables:i},allowedKinds:[`command`,`wait`],onChange:e=>a({...t,else:e.filter(Qc)})})})]})}function rl({index:t,step:n,devices:r,devicesState:i,variables:a,depth:o=0,roundDevices:c,onChange:l}){let{t:u}=Z(),d={nested:!0,flowControl:!0,devices:r,depth:o+1,allowedKinds:Ja(o+1),...c===void 0?{}:{roundDevices:c},...i===void 0?{}:{devicesState:i},...a===void 0?{}:{variables:a}};return e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.choose.hint`,`Read top to bottom: the first branch whose condition is true runs, and only that one. If a condition cannot be read, nothing runs.`)}),n.branches.map((i,a)=>{let o={when:i.if,actions:[]},c=$c(i.if);return e(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,"data-testid":`choose-branch-${String(t)}-${String(a)}`,children:[e(`div`,{className:`flex items-center gap-2`,children:[s($,{children:a===0?u(`automation.choose.if`,`If`):u(`automation.choose.elseIf`,`Otherwise, if`)}),s(W,{variant:`ghost`,className:`ml-auto`,disabled:!Ua(n),"data-testid":`choose-remove-${String(t)}-${String(a)}`,onClick:()=>l(Wa(n,a)),title:Ua(n)?u(`automation.choose.removeBranch`,`Remove this branch`):u(`automation.choose.lastBranch`,`A choose keeps at least one branch`),children:s(R,{className:`h-3.5 w-3.5`})})]}),s(Vc,{hideRule:!0,context:`guard`,recipe:o,devices:r,onChange:e=>l(Ga(n,a,{...i,if:e.when}))}),c!==null&&s(K,{variant:`warning`,message:c}),s($,{children:u(`automation.choose.then`,`Then run`)}),s(_l,{...d,actions:i.steps,onChange:e=>l(Ga(n,a,{...i,steps:e.filter(Ya)}))})]},String(a))}),e(W,{variant:`outline`,"data-testid":`choose-add-${String(t)}`,disabled:!Va(n),onClick:()=>l(Ha(n)),title:Va(n)?void 0:u(`automation.choose.maxBranches`,`A choose takes at most 6 branches`),children:[s(j,{className:`h-4 w-4`}),` `,u(`automation.choose.addBranch`,`Add a branch`)]}),s(G,{"data-testid":`choose-else-${String(t)}`,checked:n.else!==void 0,label:u(`automation.choose.else`,`Otherwise, run…`),"aria-label":u(`automation.choose.else`,`Otherwise, run…`),onCheckedChange:e=>l(Ka(n,e?[]:void 0))}),n.else!==void 0&&s(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:s(_l,{...d,actions:n.else,onChange:e=>l(Ka(n,e.filter(Ya)))})})]})}function il(e){return Object.entries(e).map(([e,t])=>({name:e,value:t}))}function al(e){return Object.fromEntries(e.map(e=>[e.name,e.value]))}function ol(e,t,n){let r=il(e);return r.some((e,r)=>r!==t&&e.name===n)?e:al(r.map((e,r)=>r===t?{...e,name:n}:e))}function sl(e,t,n){return al(il(e).map((e,r)=>r===t?{...e,value:n}:e))}function cl(e){return!Object.keys(e).includes(``)}function ll(e){return cl(e)?{...e,"":``}:e}function ul(e,t){return al(il(e).filter((e,n)=>n!==t))}var dl=`{{vars.name}}`;function fl({index:t,vars:n,onChange:r}){let{t:i}=Z();return e(`div`,{className:`space-y-2`,children:[il(n).map((a,o)=>e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-40`,children:[s($,{children:i(`automation.actionList.setName`,`Variable`)}),s(q,{"data-testid":`set-name-${String(t)}-${String(o)}`,value:a.name,spellCheck:!1,onChange:e=>r(ol(n,o,e.target.value))})]}),e(`label`,{className:`min-w-40 flex-1`,children:[s($,{children:i(`automation.actionList.setValue`,`Value`)}),s(q,{"data-testid":`set-value-${String(t)}-${String(o)}`,value:String(a.value),onChange:e=>r(sl(n,o,e.target.value))})]}),s(W,{variant:`ghost`,onClick:()=>r(ul(n,o)),title:i(`automation.actionList.setRemove`,`Remove this variable`),children:s(R,{className:`h-3.5 w-3.5`})})]},String(o))),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(W,{variant:`outline`,"data-testid":`set-add-${String(t)}`,disabled:!cl(n),onClick:()=>r(ll(n)),children:[s(j,{className:`h-4 w-4`}),` `,i(`automation.actionList.setAdd`,`Add a variable`)]}),s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.setHint`,`The steps after this one can use it as {{slot}}.`,{slot:dl,interpolation:{escapeValue:!1}})})]})]})}function pl({index:t,step:n,devices:r,devicesState:i,variables:a,depth:o=0,roundDevices:c,onChange:l}){let{t:u}=Z(),{loop:d}=n,f={count:u(`automation.repeat.byCount`,`A number of times`),while:u(`automation.repeat.byWhile`,`While a condition is true`),until:u(`automation.repeat.byUntil`,`Until a condition is true`),forEach:u(`automation.repeat.byForEach`,`Once for each device`)},p=d.by===`while`||d.by===`until`,m=p?$c(d.when):null,g={name:je,hint:u(`automation.repeat.itemHint`,`the device of this round`)},_=d.by===`forEach`?[...a??[],g]:a,v=d.by===`forEach`?d.target.ids:c;return e(`div`,{className:`space-y-2`,children:[s(`div`,{className:`w-64`,children:s(A,{"data-testid":`repeat-by-${String(t)}`,"aria-label":u(`automation.repeat.by`,`Repeat`),value:d.by,onChange:e=>{let t=e.target.value;Gi(t)&&t!==d.by&&l({...n,loop:Yi(t)})},options:Vi.map(e=>({value:e,label:f[e]}))})}),d.by===`count`&&e(`label`,{className:`block w-24`,children:[s($,{children:u(`automation.repeat.count`,`Times`)}),s(q,{type:`number`,min:1,max:20,"data-testid":`repeat-count-${String(t)}`,value:String(d.count),onChange:e=>l({...n,loop:{...d,count:qi(Number(e.target.value))}})})]}),p&&e(h,{children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:d.by===`while`?u(`automation.repeat.whileHint`,`Read before each round: if it is not true at the start, nothing runs. A condition that cannot be read ends the loop.`):u(`automation.repeat.untilHint`,`Read after each round, so the steps run at least once. A condition that cannot be read ends the loop.`)}),s(Vc,{hideRule:!0,context:`guard`,recipe:{when:d.when,actions:[]},devices:r,onChange:e=>l({...n,loop:{...d,when:e.when}})}),m!==null&&s(K,{variant:`warning`,message:m}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-28`,children:[s($,{children:u(`automation.repeat.max`,`At most (rounds)`)}),s(q,{type:`number`,min:1,max:50,"data-testid":`repeat-max-${String(t)}`,value:String(d.maxIterations),onChange:e=>l({...n,loop:{...d,maxIterations:Ji(Number(e.target.value))}})})]}),e(`label`,{className:`w-40`,children:[s($,{children:u(`automation.repeat.wait`,`Pause between rounds (s)`)}),s(q,{type:`number`,min:1,max:3600,"data-testid":`repeat-wait-${String(t)}`,value:d.waitS===void 0?``:String(d.waitS),placeholder:u(`automation.repeat.noWait`,`none`),onChange:e=>l({...n,loop:Xi(d,e.target.value===``?null:Number(e.target.value))})})]})]}),s(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.maxHint`,`A loop that reaches its maximum stops there, is marked in the run, and the run goes on.`)})]}),d.by===`forEach`&&e(`div`,{className:`space-y-1`,children:[s(En,{multiple:!0,pick:`device`,maxItems:50,value:d.target.ids.map(e=>({deviceId:e})),onChange:e=>l({...n,loop:{...d,target:{kind:`devices`,ids:e.map(e=>e.deviceId)}}})}),s(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.forEachHint`,`One round per device, in this order. In a round the steps read the device as the variable "item".`)})]}),s($,{children:u(`automation.repeat.steps`,`Each time, run`)}),s(`div`,{className:`border-l-2 border-border-subtle pl-3`,"data-testid":`repeat-steps-${String(t)}`,children:s(_l,{nested:!0,flowControl:!0,actions:n.steps,devices:r,depth:o+1,allowedKinds:Ja(o+1),maxSteps:10,...i===void 0?{}:{devicesState:i},..._===void 0?{}:{variables:_},...v===void 0?{}:{roundDevices:v},onChange:e=>l({...n,steps:e.filter(Ya)})})})]})}function ml({index:t,step:n,devices:r,onChange:i}){let{t:a}=Z(),o={when:n.when,actions:[]},c=$c(n.when),l=ta(n.timeoutS),u={s:a(`automation.waitUntil.unitSeconds`,`seconds`),min:a(`automation.waitUntil.unitMinutes`,`minutes`),h:a(`automation.waitUntil.unitHours`,`hours`)};return e(`div`,{className:`space-y-2`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.waitUntil.hint`,`The run pauses here until this is true. A value that cannot be read is not "true": the run keeps waiting.`)}),s(Vc,{hideRule:!0,context:`guard`,recipe:o,devices:r,onChange:e=>i({...n,when:e.when})}),c!==null&&s(K,{variant:`warning`,message:c}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-24`,children:[s($,{children:a(`automation.waitUntil.timeout`,`At most`)}),s(q,{type:`number`,min:1,"data-testid":`wait-until-timeout-${String(t)}`,value:String(l.value),onChange:e=>i({...n,timeoutS:na(Number(e.target.value),l.unit)})})]}),s(`div`,{className:`w-32`,children:s(A,{"data-testid":`wait-until-unit-${String(t)}`,"aria-label":a(`automation.waitUntil.unit`,`Unit`),value:l.unit,onChange:e=>i({...n,timeoutS:na(l.value,ea(e.target.value)?e.target.value:l.unit)}),options:Qi.map(e=>({value:e,label:u[e]}))})}),e(`label`,{className:`min-w-56 flex-1`,children:[s($,{children:a(`automation.waitUntil.onTimeout`,`If it does not happen in time`)}),s(A,{"data-testid":`wait-until-on-timeout-${String(t)}`,value:n.onTimeout,onChange:e=>i({...n,onTimeout:e.target.value===`stop`?`stop`:`continue`}),options:[{value:`continue`,label:a(`automation.waitUntil.continue`,`Go on with the next step`)},{value:`stop`,label:a(`automation.waitUntil.stop`,`Stop the run as a failure`)}]})]})]})]})}var hl=[{value:`command`,labelKey:`automation.actionList.kindCap`},{value:`action`,labelKey:`automation.actionList.kindAction`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`wait-until`,labelKey:`automation.actionList.kindWaitUntil`},{value:`set`,labelKey:`automation.actionList.kindSet`},{value:`stop`,labelKey:`automation.actionList.kindStop`},{value:`choose`,labelKey:`automation.actionList.kindChoose`},{value:`parallel`,labelKey:`automation.actionList.kindParallel`},{value:`repeat`,labelKey:`automation.actionList.kindRepeat`},{value:`code`,labelKey:`automation.actionList.kindCode`}],gl=[`set`,`stop`,`choose`,`wait-until`,`parallel`,`repeat`];function _l({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:o,stepResults:c,nested:l=!1,flowControl:u=!1,maxSteps:d,roundDevices:f,depth:p=0,onChange:m}){let{t:h}=Z(),g=hl.filter(e=>(i===void 0||i.includes(e.value))&&(u||!gl.includes(e.value))),_=h(`automation.actionList.flowGuardHint`,`Checked when this step is reached. If it is false, or a state cannot be read, the step does nothing.`),v={up:h(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),down:h(`automation.actionList.runThisStepLater`,`Run this step later`),atFirst:h(`automation.actionList.alreadyFirstStep`,`This step already runs first`),atLast:h(`automation.actionList.alreadyLastStep`,`This step already runs last`)};return e(`div`,{className:`space-y-2`,children:[t.length===0&&s(`p`,{className:`text-xs text-warning`,children:h(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((i,d)=>e(`div`,{className:`space-y-2 rounded border p-3 ${o===void 0?`border-border`:Li(o[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[s(Y,{variant:`default`,children:d+1}),e(`label`,{className:`w-40`,children:[s($,{children:h(`automation.actionList.step`,`Step`)}),s(A,{"data-testid":`step-kind-${String(d)}`,value:i.kind,onChange:e=>m(Q(t,d,pa(vl(e.target.value)))),options:g.map(e=>({value:e.value,label:h(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[s(Pa,{move:{up:d===0?null:()=>m(ha(t,d,d-1)),down:d===t.length-1?null:()=>m(ha(t,d,d+1))},texts:v}),s(W,{variant:`ghost`,onClick:()=>m(ma(t,d)),title:h(`automation.actionList.removeThisStep`,`Remove this step`),children:s(R,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[s($,{children:h(`automation.actionList.seconds`,`Seconds`)}),s(q,{type:`number`,min:0,max:3600,value:String(i.seconds),onChange:e=>m(Q(t,d,{...i,seconds:Number(e.target.value)}))})]}),i.kind===`stop`&&e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`min-w-48 flex-1`,children:[s($,{children:h(`automation.actionList.stopReason`,`Reason`)}),s(q,{"data-testid":`stop-reason-${String(d)}`,value:i.reason,maxLength:200,onChange:e=>m(Q(t,d,{...i,reason:e.target.value}))})]}),e(`label`,{className:`w-48`,children:[s($,{children:h(`automation.actionList.stopOutcome`,`The run ends as`)}),s(A,{"data-testid":`stop-outcome-${String(d)}`,value:i.outcome,onChange:e=>m(Q(t,d,{...i,outcome:e.target.value===`failed`?`failed`:`ok`})),options:[{value:`ok`,label:h(`automation.actionList.stopOk`,`A success`)},{value:`failed`,label:h(`automation.actionList.stopFailed`,`A failure`)}]})]})]}),i.kind===`set`&&s(fl,{index:d,vars:i.vars,onChange:e=>m(Q(t,d,{...i,vars:e}))}),i.kind===`wait-until`&&s(ml,{index:d,step:i,devices:n,onChange:e=>m(Q(t,d,e))}),i.kind===`repeat`&&s(pl,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Q(t,d,e))}),i.kind===`parallel`&&e(`div`,{className:`space-y-2`,"data-testid":`parallel-steps-${String(d)}`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:h(`automation.parallel.hint`,`These start together and the run goes on when all are done. If one fails, the run fails once the others finished.`)}),s(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:s(_l,{nested:!0,flowControl:!0,actions:i.steps,devices:n,devicesState:r,variables:a,allowedKinds:Ia,depth:p+1,...f===void 0?{}:{roundDevices:f},maxSteps:5,onChange:e=>m(Q(t,d,{...i,steps:e.filter(La)}))})})]}),i.kind===`choose`&&s(rl,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Q(t,d,e))}),!l&&(i.kind===`stop`||i.kind===`set`)&&s(tl,{when:i.if,devices:n,hint:_,onChange:e=>{let{if:n,...r}=i;m(Q(t,d,e===void 0?r:{...r,if:e}))}}),i.kind===`code`&&e(`label`,{className:`block`,children:[s($,{children:h(`automation.actionList.code`,`Code`)}),s(Fn,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:i.code,spellCheck:!1,onChange:e=>m(Q(t,d,{kind:`code`,code:e.target.value}))}),s(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:s(tr,{i18nKey:`automation.actionList.codeHint`,components:{code:s(`code`,{})}})})]}),i.kind===`command`&&s(Cr,{step:i,devices:n,variables:a,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Q(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{},...i.if===void 0?{}:{if:i.if},...i.else===void 0?{}:{else:i.else}}))}),i.kind===`action`&&s(ja,{step:i,onChange:e=>m(Q(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{}}))}),u&&(i.kind===`command`||i.kind===`action`)&&s(G,{"data-testid":`continue-on-error-${String(d)}`,checked:i.continueOnError===!0,label:h(`automation.actionList.continueOnError`,`Continue if this step fails`),"aria-label":h(`automation.actionList.continueOnError`,`Continue if this step fails`),onCheckedChange:e=>{let{continueOnError:n,...r}=i;m(Q(t,d,e?{...r,continueOnError:!0}:r))}}),!l&&(i.kind===`wait`||i.kind===`command`)&&s(nl,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>m(Q(t,d,e))}),c?.[d]!==void 0&&s(wa,{step:c[d],deviceName:e=>n.find(t=>t.id===e)?.name??`#${String(e)}`})]},`${i.kind}-${String(d)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(W,{variant:`outline`,disabled:d!==void 0&&t.length>=d,onClick:()=>m([...t,pa(g[0]?.value??`command`)]),children:[s(j,{className:`h-4 w-4`}),` `,h(`automation.actionList.addStep`)]}),t.length>1&&s(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function vl(e){return hl.find(t=>t.value===e)?.value??`command`}function yl(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function bl(e,t){return ve(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.hintKey??e.name}`,e.description)}))}function xl(e){return e.some(e=>e.required===!0&&e.default===void 0)}function Sl(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function Cl(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function wl(e,t){return e.filter(e=>e.required===!0&&!Cl(t[e.name])).map(e=>e.name)}function Tl(e,t){let n={};for(let r of e){let e=t[r.name];Cl(e)&&(n[r.name]=e)}return n}d();function El({variable:e,value:t,onChange:n}){let{t:r}=Z(),i=e.label??e.name;return e.type===`number`?s(Er,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?s(kr,{widthClass:`w-28`,"aria-label":i,value:t===!0?`yes`:`no`,onChange:e=>n(e.target.value===`yes`),options:[{value:`yes`,label:r(`common.yes`,`Yes`)},{value:`no`,label:r(`common.no`,`No`)}]}):e.type===`select`?s(kr,{widthClass:`w-48`,"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`actions.editor.runDialog.choose`,`Choose…`)},...(e.options??[]).map(e=>({value:e,label:e}))]}):s(q,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function Dl({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:o}=Z(),[c,u]=l(()=>Sl(n)),d=wl(n,c);return s(Ft,{open:!0,onOpenChange:e=>!e&&a(),children:e(Un,{"aria-label":o(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(Et,{children:[s(Xt,{children:o(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),s(ht,{children:o(`actions.editor.runDialog.description`,`Give the variables this run should use.`)})]}),s(`div`,{className:`space-y-3`,"data-testid":`run-variables-form`,children:n.map(t=>e(`label`,{className:`block space-y-1`,children:[e(`span`,{className:`text-xs text-foreground-subtle`,children:[t.label??t.name,t.required===!0?` *`:``]}),s(El,{variable:t,value:c[t.name],onChange:e=>u({...c,[t.name]:e})})]},t.name))}),e(Zt,{className:`flex flex-wrap gap-2`,children:[s(W,{variant:`ghost`,onClick:a,children:o(`common.cancel`,`Cancel`)}),e(W,{disabled:r||d.length>0,onClick:()=>i(Tl(n,c)),children:[r?s(x,{className:`h-4 w-4 animate-spin`}):s(D,{className:`h-4 w-4`}),` `,o(`actions.editor.runNow`,`Run now`)]})]})]})})}var Ol=[`number`,`string`,`boolean`,`select`];function kl(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function Al(e,t){let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``),r=e.default!==void 0&&typeof e.default==`string`&&n.includes(e.default),{default:i,...a}=e;return{...r?e:a,options:n.length===0?[`option`]:n}}function jl(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function Ml(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function Nl({variables:t,onChange:n,onRename:r}){let{t:i}=Z(),a=e=>{switch(e){case`number`:return i(`actions.variables.typeNumber`,`number`);case`string`:return i(`actions.variables.typeText`,`text`);case`boolean`:return i(`actions.variables.typeBoolean`,`yes / no`);default:return i(`actions.variables.typeSelect`,`select`)}},o=(e,r)=>n(t.map((t,n)=>n===e?r:t));return s(zt,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:dt,actions:e(W,{variant:`outline`,size:`sm`,onClick:()=>n([...t,Vr(t)]),children:[s(j,{className:`h-4 w-4`}),` `,i(`actions.variables.add`,`Variable`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[t.map((c,l)=>e(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_8rem_1fr_1.2fr_auto] sm:items-end`,"data-testid":`variable-row`,children:[e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.name`,`Name`)}),s(q,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!Hr(c.name),onChange:e=>r(l,e.target.value)})]}),e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.label`,`Label`)}),s(q,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>o(l,Ml(c,e.target.value))})]}),e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.type`,`Type`)}),s(kr,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:Ol.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=Ol.find(t=>t===e.target.value);t!==void 0&&o(l,kl(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),s(Pl,{variable:c,onChange:e=>o(l,jl(c,e))})]}),e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),s(q,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>o(l,Al(c,e.target.value))})]}),s(W,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:s(R,{className:`h-4 w-4`})})]},`${String(l)}`)),s(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function Pl({variable:e,onChange:t}){let{t:n}=Z(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return s(Er,{"aria-label":r,value:typeof e.default==`number`?e.default:void 0,onValue:t});if(e.type===`boolean`||e.type===`select`){let i=e.type===`boolean`?[{value:`true`,label:n(`common.yes`,`Yes`)},{value:`false`,label:n(`common.no`,`No`)}]:(e.options??[]).map(e=>({value:e,label:e}));return s(kr,{widthClass:`w-full`,"aria-label":r,value:e.default===void 0?``:String(e.default),options:[{value:``,label:n(`actions.variables.noDefault`,`None`)},...i],onChange:n=>{n.target.value===``?t(null):t(e.type===`boolean`?n.target.value===`true`:n.target.value)}})}return s(q,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}d();var Fl=5e3;function Il(e){return e.kind===`command`||e.kind===`wait`}function Ll(e){return e instanceof Error?e.message:String(e)}function Rl(){let{t:e}=Z();return t=>{switch(t.kind){case`name`:return e(`actions.editor.problemName`,`Give the action a name.`);case`no-steps`:return e(`actions.editor.problemNoSteps`,`Add at least one step.`);case`undeclared`:return e(`actions.editor.problemUndeclared`,`A step uses {{name}}, which is not declared under Variables.`,{name:t.name});case`duplicate`:return e(`actions.editor.problemDuplicate`,`The variable {{name}} is declared twice.`,{name:t.name});case`bad-name`:return e(`actions.editor.problemBadName`,`The variable name "{{name}}" must start with a letter and use letters, digits or _.`,{name:t.name});default:return t.message}}}function zl({entry:t,onClose:n,onSaved:a,preset:o=null}){let{t:u}=Z(),d=p(),f=O(),m=Sr(),g=Rl(),[_,v]=l(()=>Gr(t)),y=r(!1);c(()=>{if(t!==null||o!==`trigger-alarm`||y.current)return;let e=m.find(e=>e.type===Te.AlarmPanel);e!==void 0&&(y.current=!0,v(Kr(e.id,u(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[m,t,o,u]);let[b,S]=l(null),[C,w]=l(!1),T=t!==null&&t.readOnly,E=()=>{d.invalidateQueries({queryKey:[[`actions`]]})},k=Lt({onSuccess:e=>{E(),a(e.action.id)}}),A=Hn({onSuccess:E}),j=Bt({onSuccess:()=>{E(),n()}}),M=Nt({onSuccess:E}),N=xt({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Fl}),P=N.data?.traces.find(e=>e.runId===b)??null,F=i(()=>P===null?null:hi(P),[P]),I=i(()=>P===null?null:xi(P).steps,[P]),L=Ur(_),z=i(()=>yl(_.variables,u),[_.variables,u]),B=k.isPending||A.isPending,ee=k.error??A.error??j.error??M.error,te=xl(t?.variables??[]);return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`action-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(V,{className:`h-4 w-4 text-foreground-muted`}),s(q,{"aria-label":u(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:_.name,disabled:T,placeholder:u(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>v({..._,name:e.target.value})}),s(Y,{variant:T?`info`:`primary`,children:T?t?.addonId??``:u(`actions.source.internal`,`Internal`)})]}),!T&&s(fn,{className:`max-w-md`,value:_.tags??[],onChange:e=>v({..._,tags:e}),label:u(`common.tags`,`Tags`)}),T?s(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:u(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(h,{children:[s(Nl,{variables:_.variables,onChange:e=>v({..._,variables:e}),onRename:(e,t)=>v(Wr(_,e,t))}),s(Bi,{step:`steps`,title:u(`actions.editor.steps`,`Steps`),trace:F===null?null:F.thenBlock,children:s(_l,{actions:_.steps,devices:m,allowedKinds:[`command`,`wait`],stepTones:F===null?void 0:_.steps.map((e,t)=>gi(F,t)??`idle`),stepResults:I===null?void 0:_.steps.map((e,t)=>I.find(e=>e.index===t)),variables:z,onChange:e=>v({..._,steps:e.filter(Il)})})})]}),!L.ok&&!T&&_.name!==``&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:g(L.reason)}),ee!==null&&s(K,{message:Ll(ee)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!T&&e(W,{onClick:()=>{L.ok&&(t===null?k.mutate({action:L.input}):A.mutate({actionId:t.id,action:L.input}))},disabled:B||!L.ok,children:[B&&s(x,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),t!==null&&e(W,{variant:`outline`,disabled:M.isPending,onClick:()=>te?w(!0):M.mutate({actionId:t.id}),children:[s(D,{className:`h-4 w-4`}),` `,u(`actions.editor.runNow`,`Run now`)]}),t!==null&&!T&&e(W,{variant:`ghost`,disabled:j.isPending,onClick:()=>{f({title:u(`actions.editor.deleteTitle`,`Delete this action?`),message:u(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:u(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&j.mutate({actionId:t.id})})},children:[s(R,{className:`h-4 w-4`}),` `,u(`common.delete`,`Delete`)]}),s(W,{variant:`ghost`,onClick:n,children:u(`common.close`,`Close`)})]})]}),s(`div`,{className:`order-first lg:order-last`,children:s(Ii,{traces:t===null?[]:N.data?.traces,selectedId:b,onSelect:S})}),C&&t!==null&&s(Dl,{actionName:t.name,variables:t.variables??[],running:M.isPending,onCancel:()=>w(!1),onRun:e=>{M.mutate({actionId:t.id,variables:e}),w(!1)}})]})}d();var Bl=5e3;function Vl(e){return e instanceof Error?e.message:String(e)}function Hl(){let{t:e}=Z();return t=>t.status.isRunning?{variant:`info`,label:e(`actions.status.running`,`Running`)}:t.status.lastError===null?t.status.lastRunAt===null?{variant:`neutral`,label:e(`actions.status.neverRan`,`Never ran`)}:{variant:`success`,label:e(`actions.status.ok`,`OK`)}:{variant:`danger`,label:e(`actions.status.failed`,`Failed`)}}function Ul({createRequested:t=!1,onCreateConsumed:n}){let{t:r}=Z(),[a]=Xn(),o=p(),l=Hl(),{state:u,openNew:d,openEdit:f,close:m}=wn({editKey:`action`,newKey:`new`}),g=Dt({},{refetchInterval:Bl}),_=Nt({onSuccess:()=>void o.invalidateQueries({queryKey:[[`actions`]]})});c(()=>{t&&(d(),n?.())},[t,n,d]);let v=g.data??[],y=u.mode===`edit`?v.find(e=>e.id===u.id)??null:null,b=i(()=>[{key:`name`,header:r(`actions.list.name`,`Name`),render:e=>s(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:r(`actions.list.source`,`Source`),render:e=>e.readOnly?s(Y,{variant:`info`,children:e.addonId}):s(Y,{variant:`primary`,children:r(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:r(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?s(`span`,{className:`text-foreground-subtle`,children:`-`}):rr(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:r(`actions.list.status`,`Status`),render:e=>{let t=l(e);return s(`span`,{title:e.status.lastError??void 0,children:s(Y,{variant:t.variant,children:t.label})})},notSortableReason:r(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(W,{variant:`outline`,size:`sm`,disabled:_.isPending||t.status.isRunning,"aria-label":r(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),_.mutate({actionId:t.id})},children:[s(D,{className:`h-4 w-4`}),` `,r(`actions.list.run`,`Run`)]}),notSortableReason:r(`actions.list.runNotSortable`,`A control`)}],[_,l,r]);return u.mode===`closed`?e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:r(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),_.error!=null&&s(K,{message:Vl(_.error)}),g.data===void 0?g.error==null?s(Bn,{className:`h-24 w-full`}):s(K,{title:r(`actions.list.couldNotRead`,`Could not read the actions`),message:Vl(g.error),onRetry:()=>void g.refetch()}):v.length===0?s(pt,{icon:V,title:r(`actions.list.emptyTitle`,`No actions yet`),description:r(`actions.list.emptyDescription`,`An action is a short list of commands, such as feeding the dog, that you can reuse.`),action:e(W,{onClick:d,children:[s(j,{className:`h-4 w-4`}),` `,r(`actions.list.new`,`New action`)]})}):e(h,{children:[g.error!=null&&s(K,{title:r(`actions.list.couldNotRead`,`Could not read the actions`),message:Vl(g.error),onRetry:()=>void g.refetch()}),s(mn,{section:`actions`,getTags:ni,searchText:ri,searchLabel:r(`actions.list.search`,`Search actions`),columns:b,rows:v,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ct,emptyMessage:r(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>f(e.id)})]})]}):s(zl,{entry:y,onClose:m,onSaved:f,preset:u.mode===`new`?a.get(`preset`):null},y?.id??`new`)}d();function Wl({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:o}=Z(),[c,u]=l(!1),d=O(),f=async()=>{await d({title:o(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:o(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:o(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:o(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(W,{variant:`ghost`,onClick:()=>u(!c),children:[s(c?ot:k,{className:`h-4 w-4`}),o(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),s(`span`,{className:`text-xs text-foreground-subtle`,children:o(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(W,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?o(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):o(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[s(st,{className:`h-4 w-4`}),` `,o(`automation.generatedCodePanel.eject`)]})]}),c&&s(`div`,{className:`border-t border-border p-3`,children:t===null?s(`p`,{className:`text-xs text-warning`,children:n??o(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):s(Wt,{maxHeight:420,children:t})})]})}var Gl=[`single`,`restart`,`queued`,`parallel`,`cooldown`],Kl=2,ql=30;function Jl(e){return e.runMode??{mode:`single`}}function Yl(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function Xl(e){switch(e){case`queued`:return{mode:`queued`,max:Kl};case`parallel`:return{mode:`parallel`,max:Kl};case`cooldown`:return{mode:`cooldown`,minutes:ql};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function Zl(e){return Gl.find(t=>t===e)??`single`}function Ql({value:t,onChange:n}){let{t:r}=Z(),i={single:r(`flow.runMode.single`,`Skip it`),restart:r(`flow.runMode.restart`,`Restart the run`),queued:r(`flow.runMode.queued`,`Queue it`),parallel:r(`flow.runMode.parallel`,`Run at the same time`),cooldown:r(`flow.runMode.cooldown`,`Wait after a run`)},a={single:r(`flow.runMode.singleHint`,`A trigger that arrives during a run is dropped.`),restart:r(`flow.runMode.restartHint`,`The run in progress stops and a new one starts.`),queued:r(`flow.runMode.queuedHint`,`Triggers wait their turn, up to the limit.`),parallel:r(`flow.runMode.parallelHint`,`Runs overlap, up to the limit.`),cooldown:r(`flow.runMode.cooldownHint`,`No new run until this long after the last one began.`)};return e(`div`,{className:`flex flex-wrap items-end gap-3`,"data-testid":`run-mode`,children:[e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.label`,`When it is already running`)}),s(kr,{widthClass:`w-56`,value:t.mode,options:Gl.map(e=>({value:e,label:i[e]})),onChange:e=>n(Xl(Zl(e.target.value)))})]}),(t.mode===`queued`||t.mode===`parallel`)&&e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.max`,`Up to`)}),s(Er,{className:`w-20`,"aria-label":r(`flow.runMode.max`,`Up to`),value:t.max,onValue:e=>{e!==null&&n({mode:t.mode,max:Math.round(e)})}})]}),t.mode===`cooldown`&&e(`label`,{className:`space-y-1`,children:[s(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.minutes`,`Minutes`)}),s(Er,{className:`w-20`,"aria-label":r(`flow.runMode.minutes`,`Minutes`),value:t.minutes,onValue:e=>{e!==null&&n({mode:`cooldown`,minutes:Math.round(e)})}})]}),s(`p`,{className:`basis-full text-xs text-foreground-subtle`,children:a[t.mode]})]})}var $l;function eu(){return $l??=ie(Ge),$l}function tu(e,t=eu()){return ae(e,t)}d();var nu=`hub`,ru=5e3;function iu({existing:t,initialRecipe:n,saving:r,saveError:a,ejecting:o,onSave:c,onEject:u,onCancel:d,onSaveAsTemplate:f,savingAsTemplate:p=!1}){let{t:m}=Z(),[h,g]=l(t?.name??``),[_,v]=l(()=>[...t?.tags??[]]),[y,b]=l(()=>_c(n)),S=e=>b(io(e)),[C,T]=l(!1),[E,D]=l(null),O=$t({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:ru}),k=O.data?.traces.find(e=>e.runId===E)??null,A=i(()=>k===null?null:hi(k),[k]),j=i(()=>bl(y.when,m),[y.when,m]),M=i(()=>k===null?null:Si(k),[k]),N=i(()=>k===null?null:xi(k).steps,[k]),P=Sr(),F=ce(y),I=i(()=>au(y),[y]),L=i(()=>ou(h.trim()===``?`Untitled automation`:h.trim(),y),[h,y]),R=dn().data,z=i(()=>I===null?cc(y,R):null,[y,R,I]),B=h.trim()===``,ee=B||F!==null||I!==null||z!==null||L.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[s(lo,{when:y.when,children:e(`div`,{className:`space-y-4`,children:[e(`label`,{className:`block max-w-md text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:m(`automation.automationEditor.name`,`Name`)}),s(q,{className:`mt-1`,value:h,onChange:e=>g(e.target.value),placeholder:m(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),e(`div`,{className:`max-w-md text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:m(`common.tags`,`Tags`)}),s(fn,{className:`mt-1`,value:_,onChange:v,label:m(`common.tags`,`Tags`)})]}),s(Bi,{step:`when`,title:m(`automation.automationEditor.when`,`When`),trace:A===null?null:A.when,children:s(Vc,{recipe:y,devices:P,run:M,onChange:S})}),s(Bi,{step:`then`,title:m(`automation.automationEditor.then`,`Then`),trace:A===null?null:A.thenBlock,hint:m(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:s(_l,{flowControl:!0,actions:y.actions,devices:P,variables:j,stepTones:A===null?void 0:y.actions.map((e,t)=>gi(A,t)??`idle`),stepResults:N===null?void 0:y.actions.map((e,t)=>N.find(e=>e.index===t)),onChange:e=>S(ga(y,e))})}),s(Bi,{step:`mode`,title:m(`flow.runMode.title`,`Overlap`),trace:null,hint:m(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:s(Ql,{value:Jl(y),onChange:e=>S(Yl(y,e))})}),s(Wl,{code:L.code,error:L.error,canEject:t!==null,ejecting:o,onEject:u}),F!==null&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:F}),F===null&&I!==null&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:I}),F===null&&z!==null&&s(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`automation-site-error`,children:z}),a!==null&&s(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(W,{onClick:()=>{L.code!==null&&c({name:h.trim(),code:L.code,enabled:t?.enabled??!0,placement:nu,tags:_})},disabled:r||ee,children:[r&&s(x,{className:`h-4 w-4 animate-spin`}),` `,m(`common.save`)]}),e(W,{variant:`ghost`,onClick:()=>T(!C),disabled:t===null,title:t===null?m(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):m(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,"aria-expanded":C,children:[s(w,{className:`h-4 w-4`}),` `,m(`common.logs`),` `,s(ft,{expanded:C})]}),f!==void 0&&s(W,{variant:`outline`,disabled:r||p||ee,onClick:()=>f({name:h.trim(),recipe:y}),"data-testid":`automation-save-as-template`,children:m(`build.templates.saveAsTemplate`,`Save as template`)}),s(W,{variant:`ghost`,onClick:d,disabled:r,children:m(`common.close`,`Close`)}),B&&s(Y,{variant:`warning`,children:m(`automation.automationEditor.nameRequired`,`Name required`)})]}),C&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[s(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:s(tr,{i18nKey:`common.logsOf`,values:{id:Qe(t.id)},components:{code:s(`code`,{})}})}),s(Dn,{addonId:Qe(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}),s(`div`,{className:`order-first lg:order-last`,children:s(Ii,{traces:t===null?[]:O.data?.traces,selectedId:E,onSelect:D})})]})}function au(e){let t=re.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?X.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function ou(e,t){let n=tu(t);if(!n.ok)return{code:null,error:n.error};try{return{code:ge({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function su(e){if(!e.enabled)return{tone:`idle`,label:X.t(`helpers.coreBlockStatus.disabled`),detail:X.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:X.t(`helpers.coreBlockStatus.running`),detail:X.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:X.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??X.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:X.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??X.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:X.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??X.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function cu(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function lu(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function uu(e){let t=e=>{let t=su(e).tone;return t===`error`?0:t===`pending`?1:t===`ok`?2:3};return[...e].sort((e,n)=>t(e)-t(n)||e.name.localeCompare(n.name))}function du(e){if(e.length===0)return X.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>su(e).tone===`error`).length,n=e.filter(e=>su(e).tone===`ok`).length,r=[X.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(X.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(X.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var fu=3e4;function pu({block:t,logsOpen:n,unreadable:r,flagged:i=!1}){let a=_(),{t:o}=Z(),c=su(t),l=yn(t.updatedAt,a);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`truncate font-medium`,children:t.name}),s(Y,{variant:cu(c.tone),children:c.label}),i&&s(Y,{variant:`warning`,"data-testid":`automation-flagged-badge`,children:o(`build.templates.flagged`,`Flagged`)}),l!==null&&s(`span`,{className:`text-xs text-foreground-subtle`,children:o(`common.edited`,{when:l})})]}),(c.tone===`error`||c.tone===`pending`)&&s(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:c.detail}),r!==null&&s(`p`,{className:`mt-0.5 text-xs text-warning`,children:o(`automation.editor.listUnreadable`,{reason:r})}),n&&e(`div`,{className:`mt-2 rounded border border-border`,children:[s(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:s(tr,{i18nKey:`common.logsOf`,values:{id:Qe(t.id)},components:{code:s(`code`,{})}})}),s(Dn,{addonId:Qe(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var mu=2;function hu(e){let t=[];if(xe(e.when,e=>{Ve(e)&&t.push(ca(e.kind))}),t.length===0)return Ie(e.when)===0?``:X.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,mu).join(`, `),i=n.length-mu;return i>0?`${r} +${i}`:r}function gu({recipe:e}){let{t}=Z();if(e===null)return s(`span`,{className:`text-foreground-subtle`,children:`-`});let n=hu(e);return n===``?s(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):s(`span`,{children:n})}function _u({blockId:t}){let{t:n}=Z(),r=$t({blockId:t},{refetchInterval:fu});if(r.data===void 0)return r.error===null||r.error===void 0?s(Bn,{className:`h-4 w-16`}):s(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.lastRunUnknown`,`Unknown`)});let i=r.data.traces.findLast(e=>!e.outcome.startsWith(`skipped-`));if(i===void 0)return s(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.neverRan`,`Never ran`)});let a=i.outcome===`failed`||i.outcome===`aborted`;return e(`span`,{className:`inline-flex items-center gap-2`,children:[rr(i.lastAt),a&&s(Y,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function vu({block:e,disabled:t,onToggle:n}){let{t:r}=Z();return s(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:s(G,{checked:e.enabled,disabled:t,onCheckedChange:n,"aria-label":e.enabled?r(`automation.automationList.disableNamed`,`Disable {{name}}`,{name:e.name}):r(`automation.automationList.enableNamed`,`Enable {{name}}`,{name:e.name})})})}function yu({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=Z();return s(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:s(xn,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:z,disabled:e!==null,description:e===null?void 0:i(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),onClick:t},{id:`run`,label:i(`automation.automationList.runActions`,`Run actions`),icon:D,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:w,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:R,danger:!0,separatorBefore:!0,onClick:r}]})})}function bu({onCreate:t}){let{t:n}=Z();return s(pt,{icon:v,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(W,{onClick:t,"data-testid":`automation-empty-new`,children:[s(j,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}d();function xu({open:t,onBlank:n,onTemplate:r,onClose:i}){let{t:a}=Z(),o=Vn({kind:`automation`},{enabled:t}),l=o.data!==void 0&&o.data.length===0;return c(()=>{t&&l&&n()},[t,l,n]),s(Ft,{open:t&&!l,onOpenChange:e=>!e&&i(),children:e(Un,{width:`md`,placement:`sheet-on-mobile`,children:[s(Et,{children:s(Xt,{children:a(`build.templates.newAutomationTitle`,`New automation`)})}),e(qt,{className:`space-y-2`,"data-testid":`new-automation-chooser`,children:[s(W,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:n,"data-testid":`new-automation-blank`,children:e(`span`,{className:`block`,children:[s(`span`,{className:`block font-medium`,children:a(`build.templates.blank`,`Blank`)}),s(`span`,{className:`block text-xs text-foreground-muted`,children:a(`build.templates.blankHint`,`Start from an empty trigger and steps.`)})]})}),o.data===void 0?s(Bn,{className:`h-10 w-full`}):o.data.map(t=>s(W,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>r(t.id),"data-testid":`new-automation-template-${t.id}`,children:e(`span`,{className:`block`,children:[s(`span`,{className:`block font-medium`,children:t.name}),s(`span`,{className:`block text-xs text-foreground-muted`,children:be.safeParse(t.payload).data?.description??a(`build.templates.fromTemplateHint`,`From a template — only its inputs to fill in.`)})]})},t.id))]})]})})}var Su=``;function Cu(e,t){if(e===null)return null;let n=t.roomId?.trim().toLowerCase();return[...e.byId.values()].filter(e=>(t.deviceType===void 0||e.type===t.deviceType)&&(n===void 0||e.location?.trim().toLowerCase()===n)).map(e=>e.id)}var wu=[];function Tu(e,t){let n=_n(),r=e.kind===`devices`?e.ids:e.kind===`domain`?Cu(n,e)??wu:wu,i=fr(r),a=e.kind===`domain`?n!==null&&(r.length===0||i.data!==void 0):i.data!==void 0,o=r.map(e=>{let n=t.find(t=>t.id===e)?.type;return{id:e,caps:i.data?.get(e)??[],...n===void 0?{}:{type:n}}});return{known:a,actions:a?e.kind===`domain`?Tr(o).filter(e=>!br(e)):Ir(o,e,{}):[]}}function Eu({target:t,value:n,onChange:r,devices:i,disabled:a=!1,testId:o=`template-action-select`}){let{t:c,i18n:l}=Z(),u=zr(l.language),{known:d,actions:f}=Tu(t,i),p=n===void 0?void 0:f.find(e=>e.id===n.actionId),m=p===void 0||n===void 0?{}:Rr([p],n)?.values??Lr(p),g=(e,n)=>{let i=f.find(t=>t.id===e);if(i===void 0){r(void 0);return}r(Br(i,t,n??Lr(i)))},_=d?c(`build.templates.choose`,`Choose…`):c(`build.templates.readingActions`,`Reading what these devices can do…`),v=n===void 0?{value:Su,label:_}:{value:n.actionId,label:d?c(`build.templates.actionNotOffered`,`{{id}} (not offered)`,{id:n.actionId}):_};return e(h,{children:[s(A,{"data-testid":o,"aria-label":c(`build.templates.actionLabel`,`Action`),disabled:a||!d,value:n?.actionId??Su,onChange:e=>g(e.target.value,null),options:[...p===void 0?[v]:[],...f.map(e=>({value:e.id,label:e.label[u]}))]}),p!==void 0&&p.openArgs.length>0&&s(Fr,{action:p,deviceId:t.kind===`devices`&&t.ids.length===1?t.ids[0]??null:null,values:m,locale:u,variables:[],onChange:e=>g(p.id,e)})]})}function Du({devices:e,...t}){let{i18n:n}=Z(),r=zr(n.language),i=t=>{let n=Jt(t.target),{known:i,actions:a}=Tu(t.target,e),o=a.find(e=>e.id===t.actionId);return{label:`${o?.label[r]??t.actionId} · ${n}`,warning:i&&o===void 0}};return s(an,{...t,useEntryLabel:i,renderEditor:t=>s(Eu,{...t,devices:e})})}function Ou(e){return Array.isArray(e)?e:[]}function ku(e){return Ou(e).flatMap(e=>{let t=Ne.safeParse(e);return t.success&&t.data.kind===`device-fired`?[t.data]:[]})}function Au(e){return Ou(e).flatMap(e=>{let t=at.safeParse(e);return t.success?[t.data]:[]})}function ju(e){return e.length===0?void 0:e.map(e=>({...e}))}d();var Mu=`s`,Nu=60;function Pu(e){return e!==void 0&&e>=Nu&&e%Nu===0?`min`:Mu}function Fu({value:e,min:t,max:n,disabled:r=!1,"aria-label":i,onChange:a}){let[o,c]=l(()=>Pu(e));return s(gt,{quantity:`duration`,storedUnit:Mu,unit:o,value:e,disabled:r,...t===void 0?{}:{min:t},...n===void 0?{}:{max:n},...i===void 0?{}:{"aria-label":i},onChange:e=>{c(e.unit);try{a(Math.round(bn(e,Mu).value))}catch{a(void 0)}}})}var Iu=`hub`;function Lu(e){switch(e.kind){case`number`:case`duration`:case`text`:case`select`:case`boolean`:return e.default;default:return}}function Ru(e){return{min:e.minRows??(e.optional===!0?0:1),max:e.maxRows??20}}function zu(e){let t={};for(let n of e.inputs){let e=Lu(n);e!==void 0&&(t[n.key]=e)}return t}function Bu(e){let t={};for(let n of e.inputs){if(n.kind===`group`){t[n.key]=Array.from({length:Ru(n).min},()=>zu(n));continue}let e=Lu(n);e!==void 0&&(t[n.key]=e)}return t}function Vu(e){let t={};for(let n of e.inputs){if(n.kind===`group`){t[n.key]=Array.from({length:Ru(n).min},()=>Bu(n));continue}let e=Lu(n);e!==void 0&&(t[n.key]=e)}return t}function Hu(e,t,n){let{[t]:r,...i}=e;return n===void 0?i:{...i,[t]:n}}function Uu(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e)):[]}function Wu(e,t,n,r,i){let a=Uu(e,t).map((e,t)=>{if(t!==n)return e;let{[r]:a,...o}=e;return i===void 0?o:{...o,[r]:i}});return{...e,[t]:a}}function Gu(e,t){let n=Uu(e,t.key);return n.length>=Ru(t).max?e:{...e,[t.key]:[...n,Bu(t)]}}function Ku(e,t,n){let r=Uu(e,t.key);return r.length<=Ru(t).min?e:{...e,[t.key]:r.filter((e,t)=>t!==n)}}function qu(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e)):[]}function Ju(e,t){let n=Uu(e,t.groupKey)[t.index];return n===void 0?[]:qu(n,t.group.key)}function Yu(e,t,n){return Wu(e,t.groupKey,t.index,t.group.key,[...n])}function Xu(e,t,n,r,i){return Yu(e,t,Ju(e,t).map((e,t)=>{if(t!==n)return e;let{[r]:a,...o}=e;return i===void 0?o:{...o,[r]:i}}))}function Zu(e,t){let n=Ju(e,t);return n.length>=Ru(t.group).max?e:Yu(e,t,[...n,zu(t.group)])}function Qu(e,t,n){let r=Ju(e,t);return r.length<=Ru(t.group).min?e:Yu(e,t,r.filter((e,t)=>t!==n))}function $u(e,t){return e.filter(e=>e.input===t)}function ed(e,t){let n=new Set(t.map(e=>e.key));return e.filter(e=>e.input===void 0||!n.has(e.input.split(`.`)[0]??``))}function td(e,t,n){let r=tu(t);if(!r.ok)return{ok:!1,problems:[{code:`invalid-recipe`,detail:r.error}]};try{return{ok:!0,recipe:r.recipe,input:{name:e,code:ge({name:e,recipe:r.recipe}),enabled:n,placement:Iu}}}catch(e){return{ok:!1,problems:[{code:`invalid-recipe`,detail:e instanceof Error?e.message:String(e)}]}}}function nd(e,t,n,r,i){let a=we(e,t,n);return a.ok?td(r,a.recipe,i):a}function rd(e,t,n){return td(t,de(e),n)}d();var id=2;function ad(e){return typeof e==`number`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`number`):[]}function od(e){let t=Ze.safeParse(e);return t.success?t.data:void 0}function sd(e){let t=pe.safeParse(e);return t.success?t.data:void 0}function cd({problems:e}){return e.map(e=>s(`p`,{role:`alert`,className:`basis-full text-xs text-danger`,children:e.detail},`${e.input??``}|${e.detail}`))}function ld({payload:e,values:t,problems:n,disabled:r=!1,onChange:i}){return s(`div`,{className:`space-y-4`,"data-testid":`template-inputs-form`,children:e.inputs.map(e=>e.kind===`group`?s(dd,{group:e,values:t,problems:n,disabled:r,onChange:i},e.key):s(yd,{input:e,siblingValues:t,address:e.key,problems:n,disabled:r,onChange:n=>i(Hu(t,e.key,n))},e.key))})}function ud({noun:t,disabled:n,testId:r,onClick:i}){let{t:a}=Z();return e(W,{size:`sm`,variant:`outline`,disabled:n,onClick:i,"data-testid":r,children:[s(j,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),t===void 0?a(`build.templates.addRow`,`Add row`):a(`build.templates.addNamed`,`Add {{noun}}`,{noun:t})]})}function dd({group:t,values:n,problems:r,disabled:i,onChange:a}){let o=Uu(n,t.key),c=Ru(t);return e(`section`,{className:`space-y-2`,"data-testid":`template-group-${t.key}`,children:[s(`h4`,{className:`text-sm font-medium text-foreground`,children:t.label}),s(cd,{problems:$u(r,t.key)}),o.map((e,l)=>s(gd,{group:t,values:n,row:e,index:l,removable:o.length>c.min,problems:r,disabled:i,onChange:a},l)),s(ud,{noun:t.rowLabel,disabled:i||o.length>=c.max,testId:`template-group-${t.key}-add`,onClick:()=>a(Gu(n,t))})]})}function fd(e,t){let n=e.find(e=>e.kind===`device`);if(n===void 0)return;let r=ad(t[n.key])[0];if(r===void 0)return;let i=e.find(e=>e.kind===`event`&&e.deviceInput===n.key);return{deviceId:r,event:i===void 0?void 0:od(t[i.key])}}function pd(e,t){let n=e.inputs.filter(e=>e.kind!==`group`),r=n.flatMap(e=>e.kind===`entries`&&e.entry===`trigger`?ku(t[e.key]).map(e=>({deviceId:e.deviceId,event:{eventIds:e.eventIds,sourceIds:e.sourceIds}})):[]);if(r.length>0)return r;let i=fd(n,t);if(i!==void 0)return[i];for(let n of e.inputs){if(n.kind!==`group`)continue;let e=qu(t,n.key).map(e=>fd(n.inputs,e)).filter(e=>e!==void 0);if(e.length>0)return e}return[]}function md({entry:e}){let t=yt(e.deviceId,`compact`),n=e.event!==void 0,r=hn({deviceId:e.deviceId,capName:Yo},{enabled:n}),i=Xo({status:r.status,data:r.data}),a=n&&i.kind===`known`?i.vocabulary:[],o=e.event?.sourceIds?.[0],s=e.event?.eventIds?.[0],c=a.find(e=>e.source?.id===o)?.source?.label,l=a.find(e=>e.id===s&&(o===void 0||e.source?.id===o))?.label;return[t,o===void 0?void 0:c??o,s===void 0?void 0:l??s].filter(e=>e!==void 0).join(` · `)}function hd({group:t,row:r}){let{t:i}=Z(),a=pd(t,r);if(a.length===0)return t.rowLabel===void 0?i(`build.templates.newRow`,`New row`):i(`build.templates.newNamed`,`New {{noun}}`,{noun:t.rowLabel});let o=a.slice(0,id),c=a.length-o.length;return e(h,{children:[o.map((t,r)=>e(n,{children:[r>0&&`, `,s(md,{entry:t})]},r)),c>0&&` +${String(c)}`]})}function gd({group:t,values:n,row:r,index:i,removable:a,problems:o,disabled:c,onChange:l}){let{t:u}=Z(),d=`${t.key}.${String(i)}`,f=t.rowLabel;return e(`div`,{className:`space-y-3 rounded-md border border-border bg-surface p-3`,"data-testid":`template-group-${t.key}-row`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[s(`span`,{className:`min-w-0 truncate text-sm font-medium text-foreground`,"data-testid":`template-group-${t.key}-summary`,children:s(hd,{group:t,row:r})}),s(rn,{icon:R,size:`sm`,variant:`ghost`,"aria-label":f===void 0?u(`build.templates.removeRow`,`Remove row`):u(`build.templates.removeNamed`,`Remove {{noun}}`,{noun:f}),disabled:c||!a,onClick:()=>l(Ku(n,t,i))})]}),t.inputs.map(e=>e.kind===`group`?s(_d,{at:{groupKey:t.key,index:i,group:e},rows:qu(r,e.key),address:`${d}.${e.key}`,values:n,problems:o,disabled:c,onChange:l},e.key):s(yd,{input:e,siblingValues:r,address:`${d}.${e.key}`,problems:o,disabled:c,onChange:r=>l(Wu(n,t.key,i,e.key,r))},e.key))]})}function _d({at:t,rows:n,address:r,values:i,problems:a,disabled:o,onChange:c}){let{t:l}=Z(),u=t.group,d=Ru(u),f=u.rowLabel;return e(`div`,{className:`space-y-2`,"data-testid":`template-nested-${r}`,children:[s(`h5`,{className:`text-xs font-medium text-foreground-muted`,children:u.label}),s(cd,{problems:$u(a,r)}),n.map((p,m)=>{let h=`${r}.${String(m)}`;return e(`div`,{className:`flex flex-wrap items-start gap-2`,"data-testid":`template-nested-${r}-row`,children:[u.inputs.map(e=>s(vd,{input:e,row:p,address:`${h}.${e.key}`,disabled:o,onChange:n=>c(Xu(i,t,m,e.key,n))},e.key)),s(rn,{icon:C,size:`sm`,variant:`ghost`,className:`mt-5`,"aria-label":f===void 0?l(`build.templates.removeRow`,`Remove row`):l(`build.templates.removeNamed`,`Remove {{noun}}`,{noun:f}),disabled:o||n.length<=d.min,onClick:()=>c(Qu(i,t,m))}),s(cd,{problems:u.inputs.flatMap(e=>$u(a,`${h}.${e.key}`))})]},m)}),s(ud,{noun:f,disabled:o||n.length>=d.max,testId:`template-nested-${r}-add`,onClick:()=>c(Zu(i,t))})]})}function vd({input:t,row:n,address:r,disabled:i,onChange:a}){let o=s(xd,{input:t,value:n[t.key],siblingValues:n,address:r,disabled:i,inline:!0,onChange:a});return t.kind===`event`||t.kind===`action`||t.kind===`boolean`?o:e(`div`,{className:`min-w-[13rem] flex-1`,children:[s($,{children:t.label}),o]})}function yd({input:e,siblingValues:t,address:n,problems:r,disabled:i,onChange:a}){let o=$u(r,n),c=o.length===0?void 0:o.map(e=>e.detail).join(` `),l=t[e.key];return s(J,{label:e.label,required:e.optional!==!0,...e.description===void 0?{}:{description:e.description},...c===void 0?{}:{error:c},className:`min-w-0`,children:s(xd,{input:e,value:l,siblingValues:t,address:n,disabled:i,onChange:a})})}function bd(e,t,n,r,i,a){let o=e.maxItems;return e.entry===`trigger`?s(Rn,{testId:`template-input-${r}`,recentKey:`template-input-${e.key}`,disabled:n,...o===void 0?{}:{maxItems:o},value:ku(t),onChange:e=>a(ju(e))}):s(Du,{testId:`template-input-${r}`,recentKey:`template-input-${e.key}`,disabled:n,devices:i,...o===void 0?{}:{maxItems:o},value:Au(t),onChange:e=>a(ju(e))})}function xd({input:e,value:t,siblingValues:n,address:r,disabled:i,inline:a=!1,onChange:o}){let{t:c}=Z(),l=Sr();switch(e.kind){case`device`:{let n=e.filter?.capability===void 0?{}:{requires:{caps:[e.filter.capability]}},a=e.filter?.role===void 0?{}:{fixedTypes:[e.filter.role]};if(e.multiple===!0)return s(En,{pick:`device`,multiple:!0,...n,...a,recentKey:`template-input-${e.key}`,testId:`template-input-${r}`,disabled:i,value:ad(t).map(e=>({deviceId:e})),onChange:e=>{let t=e.map(e=>e.deviceId);o(t.length===0?void 0:t)}});let c=ad(t)[0];return s(En,{pick:`device`,...n,...a,recentKey:`template-input-${e.key}`,testId:`template-input-${r}`,disabled:i,value:c===void 0?null:{deviceId:c},onChange:e=>o(e===null?void 0:e.deviceId)})}case`event`:{let i=ad(n[e.deviceInput])[0];if(i===void 0)return s(`p`,{className:`min-w-[11rem] flex-1 py-1.5 text-xs text-foreground-subtle`,"data-testid":`template-input-${r}`,children:c(`build.templates.pickDeviceFirst`,`Pick the device first.`)});let l=od(t),u=s(as,{leaf:{kind:`device-fired`,deviceId:i,...l?.eventIds===void 0?{}:{eventIds:l.eventIds},...l?.sourceIds===void 0?{}:{sourceIds:l.sourceIds},...l?.kinds===void 0?{}:{kinds:l.kinds}},hideDevice:!0,onChange:e=>{let t={...e.eventIds===void 0?{}:{eventIds:e.eventIds},...e.sourceIds===void 0?{}:{sourceIds:e.sourceIds},...e.kinds===void 0?{}:{kinds:e.kinds}};o(Ze.safeParse(t).success?t:void 0)}});return a?u:s(`div`,{className:`flex flex-wrap items-end gap-2`,"data-testid":`template-input-${r}`,children:u})}case`action`:{let a=e.deviceInput===void 0?[]:ad(n[e.deviceInput]);if(e.deviceInput!==void 0&&a.length===0)return s(`p`,{className:`min-w-[11rem] flex-1 py-1.5 text-xs text-foreground-subtle`,"data-testid":`template-input-${r}`,children:c(`build.templates.pickDevicesFirst`,`Pick the devices first.`)});let u={kind:`devices`,ids:[...a]},d=sd(t);return s(Eu,{target:u,devices:l,value:d===void 0?void 0:{kind:`command`,target:u,actionId:d.actionId,...d.args===void 0?{}:{args:d.args}},disabled:i,testId:`template-input-${r}`,onChange:e=>o(e===void 0?void 0:{actionId:e.actionId,...e.args===void 0?{}:{args:e.args}})})}case`entries`:return bd(e,t,i,r,l,o);case`duration`:return s(`span`,{"data-testid":`template-input-${r}`,children:s(Fu,{value:typeof t==`number`?t:void 0,disabled:i,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},"aria-label":e.label,onChange:o})});case`number`:return s(q,{type:`number`,"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`number`?String(t):``,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},onChange:e=>{let t=e.target.value===``?void 0:Number(e.target.value);o(t===void 0||Number.isNaN(t)?void 0:t)}});case`text`:return s(q,{"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`string`?t:``,...e.maxLength===void 0?{}:{maxLength:e.maxLength},onChange:e=>o(e.target.value===``?void 0:e.target.value)});case`select`:return s(A,{"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`string`?t:``,options:[...e.optional===!0||typeof t!=`string`?[{value:``,label:c(`build.templates.choose`,`Choose…`)}]:[],...e.options.map(e=>({value:e.value,label:e.label}))],onChange:e=>o(e.target.value===``?void 0:e.target.value)});case`boolean`:return s(G,{"data-testid":`template-input-${r}`,disabled:i,checked:t===!0,onCheckedChange:e=>o(e),label:e.label});case`time-window`:return s(Sd,{testId:`template-input-${r}`,value:t,disabled:i,onChange:o})}}function Sd({testId:t,value:n,disabled:r,onChange:i}){let{t:a}=Z(),o=fe.safeParse(n),c=o.success?{kind:`time-is`,...o.data}:null;return e(`div`,{className:`flex flex-col gap-2`,"data-testid":t,children:[s(G,{"data-testid":`${t}-limit`,disabled:r,checked:c!==null,onCheckedChange:e=>{if(!e)return i(void 0);let{kind:t,...n}=rc({kind:`time-is`},!0);i(n)},label:a(`build.templates.timeWindow.limit`,`Only run at certain times`)}),c===null?null:s(`fieldset`,{disabled:r,className:`contents`,children:s(uc,{leaf:c,onChange:e=>{if(e.days?.length===0)return;let{kind:t,...n}=e;i(n)}})})]})}d();function Cd({templateId:t,templateName:n,payload:r,existing:a,currentRecipe:o,initialName:c,initialValues:u,storedProblems:d,saving:f,saveError:p,onSave:m,onCancel:h}){let{t:g}=Z(),_=O(),[v,y]=l(c),[b,S]=l(u),[C,w]=l(!1),T=a?.enabled??!0,E=d.length>0,D=i(()=>r===null?null:nd(t,r,b,v.trim(),T),[r,t,b,v,T]),k=C&&D!==null&&!D.ok?D.problems:[],A=v.trim()===``,j=()=>{w(!0),!(D===null||!D.ok||A)&&m(D.input)},M=async()=>{if(o===null||!await _({title:g(`build.templates.convertTitle`,`Convert to a free automation?`),message:g(`build.templates.convertMessage`,`{{name}} keeps running as it is, but stops following the template.`,{name:v.trim()===``?c:v.trim()}),confirmLabel:g(`build.templates.convert`,`Convert to a free automation`)}))return;let e=rd(o,v.trim()===``?c:v.trim(),T);e.ok&&m(e.input)};return e(`div`,{className:`space-y-4`,"data-testid":`template-instance-editor`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-foreground-subtle`,children:[s(`span`,{children:n===null?g(`build.templates.templateGone`,`The template of this automation no longer exists.`):g(`build.templates.fromTemplate`,`From the template {{name}}`,{name:n})}),E&&s(Y,{variant:`warning`,"data-testid":`template-flagged-badge`,children:g(`build.templates.flagged`,`Flagged`)})]}),E&&e(`div`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`template-flagged-problems`,children:[s(`p`,{className:`font-medium`,children:g(`build.templates.flaggedExplain`,`The template changed and these values no longer fit. The automation keeps running as it last did.`)}),s(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:d.map(e=>s(`li`,{children:e.detail},`${e.input??``}:${e.detail}`))})]}),e(`label`,{className:`block max-w-md text-sm`,children:[s(`span`,{className:`text-foreground-subtle`,children:g(`automation.automationEditor.name`,`Name`)}),s(q,{className:`mt-1`,value:v,onChange:e=>y(e.target.value),"data-testid":`template-instance-name`})]}),r!==null&&s(ld,{payload:r,values:b,problems:k,disabled:f,onChange:S}),r!==null&&ed(k,r.inputs).map(e=>s(`p`,{role:`alert`,className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:e.detail},e.detail)),p!==null&&s(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:p}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r!==null&&e(W,{onClick:j,disabled:f||A,"data-testid":`template-instance-save`,children:[f&&s(x,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`,`Save`)]}),a!==null&&o!==null&&s(W,{variant:`outline`,onClick:()=>void M(),disabled:f,"data-testid":`template-instance-convert`,children:g(`build.templates.convert`,`Convert to a free automation`)}),s(W,{variant:`ghost`,onClick:h,disabled:f,children:g(`common.close`,`Close`)}),A&&s(Y,{variant:`warning`,children:g(`automation.automationEditor.nameRequired`,`Name required`)})]})]})}function wd({templateId:e,existing:t,recipe:n,saving:r,saveError:i,onSave:a,onCancel:o}){let{t:c}=Z(),l=Ln({id:e});if(l.status===`error`)return s(K,{title:c(`build.templates.loadFailed`,`Could not read the template`),message:l.error.message,onRetry:()=>void l.refetch()});if(l.data===void 0)return s(Bn,{className:`h-24 w-full`});let u=l.data,d=u===null?null:be.safeParse(u.payload);if(d!==null&&!d.success)return s(K,{title:c(`build.templates.unreadable`,`This template cannot be read`),message:d.error.issues[0]?.message??``});let f=d===null?null:d.data,p=n?.template;return s(Cd,{templateId:e,templateName:u===null?null:u.name,payload:f,existing:t,currentRecipe:n,initialName:t?.name??u?.name??``,initialValues:p?.values??(f===null?{}:Vu(f)),storedProblems:p?.problems??[],saving:r,saveError:i,onSave:a,onCancel:o},t?.id??`new:${e}`)}var Td=`fromTemplate`;d();var Ed=[`coreBlocks`,`list`],Dd=5e3;function Od(e){return e instanceof Error?e.message:String(e)}function kd({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:r}){let{t:a}=Z(),d=ee(),{state:f,openNew:p,openEdit:h,close:g}=wn({editKey:`block`,newKey:`new`}),_=O(),[y,b]=l(null),[x,S]=l(!1),[C,w]=l(null),[T,E]=l(null),[D,k]=Xn(),A=Qn(),j=pn(),M=D.get(Td),N=f.mode!==`closed`;c(()=>{n&&(S(!0),r?.())},[n,r]),c(()=>{M!==null&&(w(M),k(e=>{let t=new URLSearchParams(e);return t.delete(Td),t},{replace:!0}))},[M,k]);let P=o(()=>{S(!1),p()},[p]),F=u({queryKey:Ed,refetchInterval:Dd,queryFn:async()=>(await d.trpcClient.coreBlocks.list.query({})).blocks}),I=()=>{F.refetch()},L=e=>{g(),w(null),I(),Wn({title:a(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},R=m({mutationFn:e=>d.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>L(e.block)}),z=m({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>L(e.block)}),B=m({mutationFn:e=>d.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:I}),te=m({mutationFn:e=>d.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:I}),V=m({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:$r(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{g(),I(),t(e.block.id)}}),H=F.data,ne=uu((H??[]).filter(e=>Yr(e.code))),re=H!==void 0&&ne.length===0,U=f.mode===`edit`?ne.find(e=>e.id===f.id)??null:null,ie=f.mode===`edit`&&H!==void 0&&U===null;c(()=>{ie&&g()},[ie,g]);let ae=U===null?null:Qr(U.code),oe=ae!==null&&ae.ok?ae.recipe.template:void 0,se=async e=>{let{template:t,...n}=e.recipe,r={version:1,body:n,inputs:[],bindings:[]};E(null);try{let t=await j.mutateAsync({kind:`automation`,name:e.name,payload:r});t.status===`refused`?E(t.detail):A($n(t.template.id))}catch(e){E(Od(e))}},ce=R.error===null?z.error===null?V.error===null?null:Od(V.error):Od(z.error):Od(R.error),le=i(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=Qr(e.code);return s(pu,{block:e,logsOpen:y===e.id,unreadable:t.ok?null:t.reason,flagged:t.ok&&t.recipe.template?.problems!==void 0})},sortValue:e=>e.name},{key:`trigger`,header:a(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=Qr(e.code);return s(gu,{recipe:t.ok?t.recipe:null})},notSortableReason:a(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:a(`build.automationsTab.lastRun`,`Last run`),render:e=>s(_u,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>s(vu,{block:e,disabled:te.isPending,onToggle:t=>te.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=Qr(e.code);return s(yu,{unreadable:t.ok?null:t.reason,onEdit:()=>h(e.id),onToggleLogs:()=>b(y===e.id?null:e.id),onDelete:()=>{_({title:a(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:a(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&B.mutate(e.id)})}})}}],[_,y,h,B,te,a]),ue=()=>{R.reset(),z.reset(),w(null),g()};return C!==null&&!N?e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[s(v,{className:`h-4 w-4 text-foreground-muted`}),a(`build.automationsTab.newAutomation`,`New automation`)]}),s(wd,{templateId:C,existing:null,recipe:null,saving:R.isPending,saveError:ce,onSave:e=>R.mutate(e),onCancel:ue})]}):N?f.mode===`edit`&&U===null?s(Bn,{className:`h-24 w-full`}):U!==null&&oe!==void 0&&ae!==null&&ae.ok?e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[s(v,{className:`h-4 w-4 text-foreground-muted`}),a(`build.automationsTab.edit`,`Edit {{name}}`,{name:U.name})]}),s(wd,{templateId:oe.templateId,existing:U,recipe:ae.recipe,saving:z.isPending,saveError:ce,onSave:e=>z.mutate({blockId:U.id,block:e}),onCancel:ue})]}):e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[s(v,{className:`h-4 w-4 text-foreground-muted`}),U===null?a(`build.automationsTab.newAutomation`,`New automation`):a(`build.automationsTab.edit`,`Edit {{name}}`,{name:U.name})]}),s(iu,{existing:U,initialRecipe:ae!==null&&ae.ok?ae.recipe:da,saving:R.isPending||z.isPending,saveError:ce,ejecting:V.isPending,onSave:e=>{U===null?R.mutate(e):z.mutate({blockId:U.id,block:e})},onEject:()=>{U!==null&&V.mutate(U)},onSaveAsTemplate:e=>void se(e),savingAsTemplate:j.isPending,onCancel:()=>{R.reset(),z.reset(),V.reset(),g()}},U?.id??`new`),B.error!=null&&s(K,{message:Od(B.error)}),T!==null&&s(K,{message:T})]}):e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:H===void 0?``:du(ne)}),F.error!=null&&s(K,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Od(F.error),onRetry:I}),re?s(bu,{onCreate:()=>S(!0)}):s(mn,{section:`automations`,getTags:ei,searchText:ti,searchLabel:a(`build.automationsTab.search`,`Search automations`),columns:le,rows:ne,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ct,emptyMessage:H===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>h(e.id)}),B.error!=null&&s(K,{message:Od(B.error)}),te.error!=null&&s(K,{message:Od(te.error)}),s(xu,{open:x,onBlank:P,onTemplate:e=>{S(!1),w(e)},onClose:()=>S(!1)})]})}var Ad={kind:`all`,children:[]};function jd({value:t,devices:n,label:r,onChange:i}){let{t:a}=Z(),o=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[s(G,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?Ad:void 0)}),o!==null&&e(h,{children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.activeWhen.hint`,`Only states count here, such as "someone is home". While they are false, nothing runs and holds pause.`)}),s(Vc,{recipe:o,devices:n,onChange:e=>i(e.when)})]})]})}var Md=[`sunrise`,`sunset`,`dawn`,`dusk`],Nd=6e4;function Pd(e){return e.kind===`command`||e.kind===`wait`}function Fd(e,t){let n={id:e.id,at:e.at,mode:t,steps:t===`release`?[]:e.steps,...e.conditions===void 0?{}:{conditions:e.conditions}};return t===`hold`?{...n,...e.override===void 0?{}:{override:e.override},...e.maxHoldAttempts===void 0?{}:{maxHoldAttempts:e.maxHoldAttempts}}:n}function Id({point:t,devices:n,site:r,localDate:i,issues:a,onChange:o,onRemove:c}){let{t:l}=Z(),u=t.at,d=u.kind===`sun`?Us(u,r,i):null,f=Ws(u,r,i),p=t.override??{mode:`respect`},m=e=>o({...t,at:e});return e(`div`,{className:`space-y-3`,"data-testid":`point-editor`,children:[e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.kind`,`Point type`)}),s(A,{"aria-label":l(`schedulers.point.kind`,`Point type`),value:t.mode,options:[{value:`edge`,label:l(`schedulers.point.edge`,`Edge: run once`)},{value:`hold`,label:l(`schedulers.point.hold`,`Hold: keep true`)},{value:`release`,label:l(`schedulers.point.release`,`Release: end the hold`)}],onChange:e=>{let n=e.target.value;(n===`edge`||n===`hold`||n===`release`)&&o(Fd(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.when`,`When`)}),s(A,{"aria-label":l(`schedulers.point.when`,`When`),value:u.kind===`sun`?`sun`:`clock`,options:[{value:`clock`,label:l(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:l(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{e.target.value===`sun`?m({kind:`sun`,event:`sunset`,offsetMin:0}):m({kind:`clock`,hh:12,mm:0})}})]}),u.kind===`clock`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.time`,`Time`)}),s(q,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:qs(u.hh,u.mm),onChange:e=>{let t=Ks(e.target.value);t!==null&&m(t)}})]}),u.kind===`sun`&&e(h,{children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.sunEvent`,`Sun event`)}),s(A,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:Md.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Md.find(t=>t===e.target.value);t!==void 0&&m({...u,event:t})}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.offset`,`Offset (minutes, negative = before)`)}),s(Er,{"aria-label":l(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-28`,value:u.offsetMin,onValue:e=>{e!==null&&m({...u,offsetMin:Math.round(e)})}})]}),s(`p`,{className:`pb-2 text-xs text-foreground-muted`,"data-testid":`sun-computed`,children:d===null||f===null?l(`schedulers.point.sunUnknown`,`No time today: the site location is not set.`):l(`schedulers.point.sunComputed`,`Today at {{time}} ({{zone}})`,{time:Js(d),zone:r.timeZone})})]}),e(W,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[s(R,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&s(_l,{actions:t.steps,devices:n,allowedKinds:[`command`,`wait`],onChange:e=>o({...t,steps:e.filter(Pd)})}),t.mode===`release`&&s(`p`,{className:`text-xs text-foreground-subtle`,children:l(`schedulers.point.releaseHint`,`A release ends the running hold without doing anything to the devices.`)}),t.mode===`hold`&&e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.override`,`If someone changes it by hand`)}),s(A,{"aria-label":l(`schedulers.point.override`,`If someone changes it by hand`),value:p.mode,options:[{value:`respect`,label:l(`schedulers.point.respect`,`Leave it alone`)},{value:`reassert`,label:l(`schedulers.point.reassert`,`Put the hold back after a while`)}],onChange:e=>o({...t,override:e.target.value===`reassert`?{mode:`reassert`,graceMs:10*Nd}:{mode:`respect`}})})]}),p.mode===`reassert`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[s(`span`,{children:l(`schedulers.point.grace`,`Wait (minutes)`)}),s(Er,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:p.graceMs/Nd,onValue:e=>{e!==null&&o({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*Nd))}})}})]})]}),a.length>0&&s(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:a.map(e=>s(`li`,{children:e.message},`${e.path}:${e.message}`))})]})}d();var Ld=5e3,Rd=600,zd=6e4,Bd={timeZone:`UTC`,location:null};function Vd(e){return e instanceof Error?e.message:String(e)}function Hd(e){if(e===null)return Is();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function Ud(e,t){let[n,r]=l(e);return c(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Wd(e,t){return t(`schedulers.day.${e}`,e)}function Gd({entry:t,onClose:n,onSaved:r}){let{t:a}=Z(),o=p(),c=O(),u=Sr(),d=dn(),f=d.data??Bd,[m,h]=l(()=>Hd(t)),[g,_]=l(()=>m.profiles[0]?.id??``),[v,y]=l(null),[b,S]=l(null),C=()=>{o.invalidateQueries({queryKey:[[`schedulers`]]})},w=Rt({onSuccess:e=>{C(),r(e.scheduler.id)}}),T=Kt({onSuccess:C}),E=Vt({onSuccess:()=>{C(),n()}}),D=St({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:Ld}),k=i(()=>Xs(m,f),[m,f]),A=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),M=Ud(k.ok?k.input:null,Rd),P=vn(M===null?{scheduler:m}:t===null?{scheduler:M}:{scheduler:M,schedulerId:t.id},{enabled:M!==null&&A&&d.data!==void 0}),F=m.profiles.find(e=>e.id===g)??m.profiles[0],I=F===void 0?-1:m.profiles.indexOf(F),L=Hs(f),z=F?.points.find(e=>e.id===v)??null,B=F===void 0||z===null?-1:F.points.indexOf(z),ee=k.ok?[]:k.issues,te=e=>ee.filter(t=>t.path===e||t.path.startsWith(`${e}.`)),V=e=>h({...m,profiles:m.profiles.map((t,n)=>n===I?e:t)}),H=e=>{F!==void 0&&V({...F,points:F.points.map(t=>t.id===e.id?e:t)})},ne=i(()=>F===void 0?[]:F.points.flatMap(e=>{let t=Us(e.at,f,L);if(t===null)return[];let n=e.at.kind===`sun`?`${a(`schedulers.sun.${e.at.event}`,e.at.event)} ${e.at.offsetMin>=0?`+`:``}${String(e.at.offsetMin)} (${Js(t)})`:qs(e.at.hh,e.at.mm);return[{id:e.id,minute:t,label:n,tone:e.mode===`hold`?`success`:e.mode===`release`?`neutral`:`primary`,draggable:e.at.kind===`clock`||e.at.kind===`sun`&&Ws(e.at,f,L)!==null}]}),[F,f,L,a]),re=i(()=>F===void 0?[]:Ys(F.points,f,L),[F,f,L]),U=(e,t)=>{let n=F?.points.find(t=>t.id===e);n!==void 0&&H({...n,at:Gs(n.at,t,Ws(n.at,f,L))})},ie=e=>{if(F===void 0)return;let t=zs(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));V({...F,points:[...F.points,Rs(e,t,720)]}),y(t)},ae=()=>{let e=zs(`profile`,m.profiles.map(e=>e.id));h({...m,profiles:[...m.profiles,Ls(e,a(`schedulers.profile.newName`,`New profile`))]}),_(e),y(null)},oe=w.isPending||T.isPending,se=w.error??T.error??E.error;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`scheduler-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(N,{className:`h-4 w-4 text-foreground-muted`}),s(q,{"aria-label":a(`schedulers.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,placeholder:a(`schedulers.editor.namePlaceholder`,`What this scheduler does`),onChange:e=>h({...m,name:e.target.value})})]}),s(fn,{className:`max-w-md`,value:m.tags??[],onChange:e=>h({...m,tags:e}),label:a(`common.tags`,`Tags`)}),e(zt,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[s(Ht,{label:a(`schedulers.editor.enabled`,`Enabled`),children:s(G,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>h({...m,enabled:e})})}),s(Ht,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:s(Er,{"aria-label":a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),className:`w-24`,value:m.priority,onValue:e=>{e!==null&&h({...m,priority:Math.round(e)})}})}),s(Ht,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:s(Er,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/zd,onValue:e=>{e!==null&&h({...m,maxLateMs:Math.round(e*zd)})}})})]}),e(`div`,{className:`p-3`,children:[s(jd,{value:m.activeWhen,devices:u,label:a(`schedulers.editor.activeWhen`,`Only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=m;h(e===void 0?n:{...n,activeWhen:e})}}),te(`activeWhen`).map(e=>s(`p`,{className:`mt-1 text-xs text-warning`,children:e.message},e.message))]})]}),s(zt,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(W,{variant:`outline`,size:`sm`,onClick:ae,children:[s(j,{className:`h-4 w-4`}),` `,a(`schedulers.profile.add`,`Add profile`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.profile.hint`,`Each day, the first profile in this order whose days and condition hold is the one that runs.`)}),F!==void 0&&e(ln,{value:F.id,onValueChange:e=>{_(e),y(null)},appearance:`pills`,children:[s(Sn,{children:m.profiles.map(e=>s(An,{value:e.id,children:e.name},e.id))}),e(Nn,{value:F.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(q,{"aria-label":a(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:F.name,onChange:e=>V({...F,name:e.target.value})}),s(G,{checked:F.enabled,label:a(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>V({...F,enabled:e})}),m.profiles.length>1&&e(W,{variant:`ghost`,size:`sm`,onClick:()=>{h({...m,profiles:m.profiles.filter(e=>e.id!==F.id)}),_(``),y(null)},children:[s(R,{className:`h-4 w-4`}),` `,a(`schedulers.profile.remove`,`Remove profile`)]})]}),s(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":a(`schedulers.profile.days`,`Days`),children:Ns.map(e=>{let t=F.days.includes(e);return s(W,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>V({...F,days:t?F.days.filter(t=>t!==e):Ns.filter(t=>t===e||F.days.includes(t))}),children:Wd(e,a)},e)})}),te(`profiles.${String(I)}.days`).map(e=>s(`p`,{className:`text-xs text-warning`,children:a(`schedulers.profile.daysNeeded`,`Pick at least one day.`)},e.message)),s(jd,{value:F.activeWhen,devices:u,label:a(`schedulers.profile.activeWhen`,`This profile only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=F;V(e===void 0?n:{...n,activeWhen:e})}}),s(vt,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:ne,bands:re,selectedId:v,onSelect:y,onMove:U}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(W,{variant:`outline`,size:`sm`,onClick:()=>ie(`edge`),children:[s(j,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(W,{variant:`outline`,size:`sm`,onClick:()=>ie(`hold`),children:[s(j,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(W,{variant:`outline`,size:`sm`,onClick:()=>ie(`release`),children:[s(j,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),s(Y,{variant:`neutral`,children:f.timeZone})]}),F.points.length===0&&s(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.timeline.empty`,`Add a point to place something on the day.`)}),z!==null&&s(Id,{point:z,devices:u,site:f,localDate:L,issues:te(`profiles.${String(I)}.points.${String(B)}`),onChange:H,onRemove:()=>{V({...F,points:F.points.filter(e=>e.id!==z.id)}),y(null)}},z.id)]})]})]})}),P.data!==void 0&&P.data.conflicts.length>0&&s(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:P.data.conflicts.map(e=>s(`li`,{children:a(`schedulers.conflict.message`,`{{other}} wants device {{device}} in another state from {{from}} to {{to}} ({{winner}}).`,{other:e.other.schedulerName,device:e.deviceId,from:Js(e.fromMinute),to:Js(e.toMinute),winner:e.winner===`mine`?a(`schedulers.conflict.mine`,`this one wins`):e.winner===`other`?a(`schedulers.conflict.other`,`the other one wins`):a(`schedulers.conflict.tie`,`the one that started first wins`)})},`${e.other.schedulerId}:${e.other.pointId}:${e.mine.pointId}:${String(e.deviceId)}`))}),!k.ok&&m.name!==``&&ee.length>0&&z===null&&s(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:ee.map(e=>s(`li`,{children:e.message},`${e.path}:${e.message}`))}),se!==null&&s(K,{message:Vd(se)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(W,{onClick:()=>{k.ok&&(t===null?w.mutate({scheduler:k.input}):T.mutate({schedulerId:t.id,scheduler:k.input}))},disabled:oe||!k.ok||d.data===void 0,children:[oe&&s(x,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(W,{variant:`ghost`,disabled:E.isPending,onClick:()=>{c({title:a(`schedulers.editor.deleteTitle`,`Delete this scheduler?`),message:a(`schedulers.editor.deleteMessage`,`{{name}} will be deleted and any hold it keeps will stop.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&E.mutate({schedulerId:t.id})})},children:[s(R,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),s(W,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),s(`div`,{className:`order-first lg:order-last`,children:s(Ii,{traces:t===null?[]:D.data?.traces,selectedId:b,onSelect:S})})]})}d();var Kd=5e3;function qd(e){return e instanceof Error?e.message:String(e)}function Jd({createRequested:t=!1,onCreateConsumed:n}){let{t:r}=Z(),a=p(),{state:o,openNew:l,openEdit:u,close:d}=wn({editKey:`scheduler`,newKey:`new`}),f=Ot({},{refetchInterval:Kd}),m=Gt({},{refetchInterval:Kd}),h=Pt({onSuccess:()=>void a.invalidateQueries({queryKey:[[`schedulers`]]})});c(()=>{t&&(l(),n?.())},[t,n,l]);let g=f.data??[],_=o.mode===`edit`?g.find(e=>e.id===o.id)??null:null,v=e=>{if(!e.enabled)return{variant:`neutral`,label:r(`schedulers.status.off`,`Off`)};let t=m.data?.find(t=>t.schedulerId===e.id);return t===void 0?{variant:`neutral`,label:`-`}:t.hold===null?{variant:`neutral`,label:r(`schedulers.status.idle`,`Idle`)}:t.hold.suspendedInactive?{variant:`warning`,label:r(`schedulers.status.paused`,`Paused`)}:t.hold.targets.some(e=>e.status===`gave-up`)?{variant:`danger`,label:r(`schedulers.status.gaveUp`,`Gave up`)}:{variant:`success`,label:r(`schedulers.status.holding`,`Holding`)}},y=i(()=>[{key:`name`,header:r(`schedulers.list.name`,`Name`),render:e=>s(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`enabled`,header:r(`schedulers.list.enabled`,`Enabled`),render:e=>s(`span`,{onClick:e=>e.stopPropagation(),children:s(G,{checked:e.enabled,disabled:h.isPending,"aria-label":r(`schedulers.list.enabledAria`,`Enable {{name}}`,{name:e.name}),onCheckedChange:t=>h.mutate({schedulerId:e.id,enabled:t})})}),sortValue:e=>Number(e.enabled)},{key:`profiles`,header:r(`schedulers.list.profiles`,`Profiles`),render:e=>String(e.profiles.length),sortValue:e=>e.profiles.length},{key:`priority`,header:r(`schedulers.list.priority`,`Priority`),render:e=>String(e.priority),sortValue:e=>e.priority},{key:`status`,header:r(`schedulers.list.status`,`Now`),render:e=>{let t=v(e);return s(Y,{variant:t.variant,children:t.label})},notSortableReason:r(`schedulers.list.statusNotSortable`,`Derived from the live hold`)},{key:`updated`,header:r(`schedulers.list.updated`,`Updated`),render:e=>rr(e.updatedAt),sortValue:e=>e.updatedAt}],[h,m.data,r]);return o.mode===`closed`?e(`div`,{className:`space-y-3`,children:[s(`p`,{className:`text-xs text-foreground-subtle`,children:r(`schedulers.list.hint`,`A scheduler does things over the day: run something at a time or at sunset, or keep a device in a state for a stretch of time.`)}),h.error!=null&&s(K,{message:qd(h.error)}),f.data===void 0?f.error==null?s(Bn,{className:`h-24 w-full`}):s(K,{title:r(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:qd(f.error),onRetry:()=>void f.refetch()}):g.length===0?s(pt,{icon:N,title:r(`schedulers.list.emptyTitle`,`No schedulers yet`),description:r(`schedulers.list.emptyDescription`,`A scheduler turns the garden lights on at sunset and off at 23:00, every day or only on some days.`),action:e(W,{onClick:l,children:[s(j,{className:`h-4 w-4`}),` `,r(`schedulers.list.new`,`New scheduler`)]})}):s(mn,{section:`schedulers`,getTags:ii,searchText:ai,searchLabel:r(`schedulers.list.search`,`Search schedulers`),columns:y,rows:g,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ct,emptyMessage:r(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):s(Gd,{entry:_,onClose:d,onSaved:u},_?.id??`new`)}async function Yd(e,t){let n=`${$e}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var Xd=10,Zd=400;async function Qd(e,t,n=Zd){for(let r=0;r<Xd;r+=1){let r=await Yd(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var $d=`media-player`;function ef(e){return e===Te.MediaPlayer?`media-source`:`none`}function tf(e){return e===Te.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[Te.MediaPlayer],accept:[{cap:$d,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[$d],exclude:[]}:null}function nf(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:$d,fields:{},commands:Object.fromEntries(Object.keys(De()).map(t=>[t,{kind:`forward`,source:e.source,cap:$d,method:t}]))}]}function rf(e,t){let n=e===Te.MediaPlayer?nf(t):[];return{target:{kind:`new`,type:e},features:n}}d();function af({onTitle:t}){let{t:n}=Z(),r=_(),i=Qn(),a=xr(),o=Tn(),u=Qt({addonId:`composer`}),[d,f]=l(Te.Sensor),[p,m]=l(``),[h,g]=l([]),[v,y]=l(null),b=h[0]??null,x=tf(d),S=rf(d,b);c(()=>{t(n(`helper.newDevice`))},[t,n]);let C=async()=>{y(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:S}}),r=await Qd(t.id,async()=>(await u.refetch()).data??u.data);if(r===null){y(n(`helper.devicePending`));return}e!==``&&await o.mutateAsync({deviceId:r,name:e}),i(Zn(r),{replace:!0})}catch(e){y(e instanceof Error?e.message:String(e))}};return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`device-create-form`,children:[e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.targetType`),s(A,{value:d,onChange:e=>{let t=Object.values(Te).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(Te).map(e=>({value:e,label:bt(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),s(q,{"aria-label":n(`compositionEditor.name`),value:p,onChange:e=>m(e.target.value)})]})]}),x!==null&&e(`div`,{className:`flex flex-col gap-1`,"data-testid":`device-create-source`,children:[s(`p`,{className:`text-[11px] text-foreground-muted`,children:n(`helper.deviceSource.${ef(d)}`)}),s(cr,{kind:`members`,request:x,enabled:!0,members:h,onMembersChange:g,onRefuse:()=>void 0})]}),v!==null&&s(`p`,{role:`alert`,className:`text-xs text-danger`,children:v}),s(W,{disabled:a.isPending,onClick:()=>void C(),children:n(`compositionEditor.save`)})]})}d();function of({preset:t,saving:n,onSave:r,onBack:a}){let{t:o,i18n:c}=Z(),u=mr(!0),[d,f]=l({}),[p,m]=l(o(t.nameKey)),[h,g]=l(null),[_,v]=l([]),[y,b]=l(!1),x=i(()=>u.kind===`known`?new Map(u.value.map(e=>[H({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=i(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[H(e)])),[d]),C=i(()=>u.kind===`known`?{kind:`known`,value:ir(u.value,S)}:u,[u,S]),w=gr(t,d),T=u.kind===`known`?_r(u.value,w,!1):null,E=t.build(d),D=dr(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(H(e))??e.stableId;return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`preset-wizard`,children:[s(`p`,{className:`text-[11px] text-foreground-muted`,children:o(t.descriptionKey)}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[o(`preset.name`),s(q,{"aria-label":o(`preset.name`),value:p,onChange:e=>m(e.target.value)})]}),s(`ul`,{className:`flex flex-col gap-2`,"aria-label":o(`preset.slots`),children:t.slots.map(t=>{let n=d[t.key];return e(`li`,{className:`grid grid-cols-1 gap-1 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center`,"data-testid":`preset-slot-${t.key}`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`text-xs text-foreground`,children:[o(t.labelKey),t.optionalGroup===void 0?` *`:``]}),e(`div`,{className:`text-[11px] text-foreground-muted break-words`,children:[ar(t.expectedCap,c.language),t.optionalGroup===void 0?``:` · ${o(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[s(W,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?o(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&s(W,{variant:`ghost`,size:`sm`,onClick:()=>O(t.key,void 0),children:o(`preset.clear`)})]})]},t.key)})}),E===null&&D.length>0&&s(`p`,{className:`text-[11px] text-foreground-muted`,"data-testid":`preset-missing`,children:o(`preset.missing`,{slots:D.map(e=>o(e.labelKey)).join(`, `)})}),E!==null&&e(`section`,{className:`flex flex-col gap-1`,"data-testid":`preset-preview`,children:[s(`h3`,{className:`text-xs font-medium text-foreground`,children:o(`preset.preview`)}),s(`ul`,{className:`flex flex-col gap-1 text-[11px] text-foreground-muted`,children:E.features.map(e=>e.kind===`fields`?s(`li`,{children:o(`preset.previewFeature`,{cap:ar(e.cap,c.language),fields:Object.keys(e.fields).length,commands:Object.keys(e.commands??{}).length+Object.values(e.items??{}).filter(e=>e.reset!==void 0).length})},e.cap):null)})]}),s(hr,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[s(W,{disabled:E===null||n||y,onClick:()=>{E===null||y||(b(!0),r(E,p.trim()).then(e=>{e.kind===`refused`&&v(e.lines)}).finally(()=>b(!1)))},"data-testid":`preset-create`,children:o(`preset.create`)}),s(W,{variant:`ghost`,onClick:a,children:o(`preset.back`)})]}),s(lr,{open:h!==null,title:h===null?``:o(`preset.pickTitle`,{slot:o(h.labelKey)}),selection:`single`,candidates:C,room:T,confirmLabel:()=>o(`preset.pickConfirm`),onConfirm:e=>{let t=e[0],n=h;g(null),t!==void 0&&n!==null&&O(n.key,t.ref)},onClose:()=>g(null)})]})}d();var sf=`preset`;function cf({mode:e,onTitle:t}){return s(e===`helper`?lf:af,{onTitle:t})}function lf({onTitle:e}){let{t}=Z(),n=Qn(),i=xr(),a=Tn(),o=Qt({addonId:`composer`}),[u,d]=l(null),[f,p]=l(!1),[m,h]=Xn(),g=sr(m.get(sf)),_=g===null?uf(u,t):t(g.labelKey);c(()=>{f||e(_)},[e,_,f]);let v=e=>h(t=>{let n=new URLSearchParams(t);return e===null?n.delete(sf):n.set(sf,e),n},{replace:!0}),y=async(e,r)=>{try{let{block:s}=await i.mutateAsync({block:{...r===``?{}:{name:r},enabled:!0,composition:e}}),c=await Qd(s.id,async()=>(await o.refetch()).data??o.data);return c===null?{kind:`refused`,lines:ur(t(`helper.devicePending`))}:(r!==``&&await a.mutateAsync({deviceId:c,name:r}),n(Zn(c),{replace:!0}),{kind:`saved`,deviceId:c})}catch(e){return{kind:`refused`,lines:ur(e instanceof Error?e.message:String(e))}}},b=r(null);return f?s(af,{onTitle:e}):g===null?s(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:s(pr,{fillHeight:!0,onDevice:()=>p(!0),onPreset:v,purpose:`create`,initial:null,start:`template`,saving:i.isPending,onDraftChange:d,onSave:async(e,r)=>{let s=null,c=await yr(e,async(c,l)=>{let u=b.current,d;if(u!==null&&u.draft===e)d=u.blockId;else{let{block:t}=await i.mutateAsync({block:{...l===``?{}:{name:l},enabled:!0,composition:c}});d=t.id,b.current={draft:e,blockId:d}}let f=await Qd(d,async()=>(await o.refetch()).data??o.data);if(f===null)throw Error(t(`helper.devicePending`));s=f,b.current=null,l!==``&&await a.mutateAsync({deviceId:f,name:l}),r===`open`&&n(Yn(f),{replace:!0})}),l=s;return c.length>0||l===null?{kind:`refused`,lines:df(c,t)}:{kind:`saved`,deviceId:l}}})}):s(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:s(of,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function uf(e,t){if(e===null)return t(`helper.newComposed`);if(e.kind===`statistic`)return t(`helper.newTitle.statistic`);if(e.kind===`integral`)return t(`helper.newTitle.integral`);if(e.kind===`arithmetic`)return t(`helper.newTitle.${e.op}`);if(e.kind===`threshold`||e.kind===`expression`||e.kind===`derivative`)return t(`helper.newTitle.${e.kind}`);let n=Be(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function df(e,t){return e.length>0?e:ur(t(`helper.devicePending`))}function ff(e){let t=e.helper;if(t===void 0)return{section:`advanced`,kind:null};switch(t.kind){case`group`:return{section:`group`,kind:t.templateId};case`arithmetic`:return{section:`calculation`,kind:t.op};case`expression`:return{section:`advanced`,kind:`expression`};default:return{section:`calculation`,kind:t.kind}}}function pf(e){return{state:`answered`,byRef:new Map(e.map(e=>[H(e),e]))}}function mf(e,t){if(e.state!==`unanswered`)return e.byRef.get(H(t))??null}function hf(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function gf(e){return nt(e).map(e=>e.source)}function _f(e){let t=e.block.source?.kind===`composition`?e.block.source.composition:null;if(t===null)return[];let n=[];for(let e of t.features){if(e.kind===`passthrough`){n.push(e.source);continue}for(let t of Object.values(e.fields))n.push(...gf(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...gf(e))}let r=new Set;return n.filter(e=>{let t=H(e);return r.has(t)?!1:(r.add(t),!0)})}function vf(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:X.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[X.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[X.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??X.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:X.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function yf(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return vf(e);case`degraded`:return{tone:`pending`,label:X.t(`helpers.compositionRows.degraded`),reason:n??X.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:X.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:X.t(`helpers.compositionRows.failed`),reason:n??X.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:X.t(`helpers.compositionRows.notRunning`),reason:n??X.t(`helpers.compositionRows.notRunningReason`)}}}function bf(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:X.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:X.t(`helpers.compositionRows.unknown`),reason:X.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return yf(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:X.t(`helpers.compositionRows.notReported`),reason:X.t(`helpers.compositionRows.noRecord`,{stored:r})}}function xf(e){return H(e)}function Sf(e,t){let n=mf(t,e);return{key:H(e),label:n?n.name:xf(e),presence:hf(n),deviceId:n?n.id:null}}function Cf(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function wf(e,t){let n=e.block.source?.kind===`composition`?e.block.source.composition:null;if(n===null)return null;let r=n.target,i=r.kind===`existing`?r.device:Pe(e.block.id),a=H(i),o=_f(e).filter(e=>H(e)!==a).map(e=>Sf(e,t)),s=n.features.map(e=>e.enabled===!1?X.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=mf(t,i),l=Cf(e),u=bf(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,origin:ff(n),features:s,state:u,sources:o,reportedDeviceId:l,tags:c?.tags??[]};let d=hf(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:xf(r.device),namePresence:d,type:c?c.type:null,origin:ff(n),features:s,state:u,sources:o,reportedDeviceId:l,tags:c?.tags??[]}}function Tf(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Ef(e,t){return Tf(e)-Tf(t)||e.name.localeCompare(t.name)}function Df(e,t){let n=e.flatMap(e=>{let n=wf(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Ef),customizations:n.filter(e=>e.kind===`customization`).toSorted(Ef)}}d();var Of=1e4;function kf(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Af(){let e=Gn();return e.data===void 0?{state:`unanswered`,reason:e.error==null?X.t(`build.customDeviceTab.deviceListPending`):X.t(`build.customDeviceTab.deviceListUnreadable`,{error:kf(e.error)})}:pf(e.data)}function jf(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Mf({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Z(),[i,a]=Xn(),o=mt({},{refetchInterval:Of}),c=Af(),u=wn({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?jf(i.get(`new`),t):null,p=f!==null,[m,g]=l(``),_=O(),v=Mt(),y=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},b=o.data;return e(h,{children:[Pf(b,o.error,()=>void o.refetch(),c,{onEditComposed:e=>u.openEdit(e),deleting:v.isPending,onDelete:e=>{_({title:r(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`),message:r(`build.customDeviceTab.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:r(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&v.mutate({blockId:e.blockId},{onSuccess:()=>void o.refetch()})})}}),s(Mn,{open:p,onClose:y,title:m||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:P,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&s(cf,{mode:f,onTitle:g},f)}),s(Ar,{blockId:d,onClose:y}),v.error!=null&&s(K,{message:kf(v.error)})]})}function Nf(t){return s(kt,{children:e(`div`,{className:`space-y-1 p-4`,children:[s(`p`,{className:`text-sm text-warning`,children:X.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[X.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Pf(e,t,n,r,i){if(t!=null&&e===void 0)return s(K,{title:X.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:kf(t),onRetry:n});if(e===void 0)return s(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:X.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return Nf(e.reason);let a=t==null?null:kf(t);return s(Ff,{lists:Df(e.views,r),fleet:r,refreshError:a,handlers:i})}function Ff({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Z();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),s(If,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,handlers:i}),s(If,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,handlers:i})]})}function If({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:o,handlers:c}){let{t:l}=Z();return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[s(`h3`,{className:`font-medium`,children:t}),s(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),s(mn,{section:o===`composed`?`composed-devices`:`customizations`,getTags:Lf,searchText:Rf,searchLabel:l(`build.customDeviceTab.search`,`Search {{list}}`,{list:t}),columns:zf(i,o,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:Ct,emptyMessage:a,onRowClick:o===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Lf(e){return e.tags}function Rf(e){return[e.name,e.type??``,...e.features]}function zf(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>s(Vf,{row:e})},{key:`type`,header:X.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>s(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??X.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:X.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>Bf(e.origin,i),render:e=>s(Y,{variant:`default`,"data-testid":`composed-origin-badge`,children:Bf(e.origin,i)})}]:[],{key:`state`,header:X.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[s(Y,{variant:cu(t.state.tone),children:t.state.label}),t.state.reason!==null&&s(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:X.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>s(Uf,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[s(W,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),s(W,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:s(R,{className:`h-4 w-4`})})]})}),a}function Bf(e,t){let n=e.kind===null?null:t(`helper.template.${e.kind}`);return e.section===`group`?t(`helper.badge.group`,{kind:n}):e.section===`calculation`?t(`helper.badge.calculation`,{kind:n}):n===null?t(`helper.badge.advanced`):t(`helper.badge.advancedKind`,{kind:n})}function Vf({row:t}){let{t:n}=Z();return e(`div`,{className:`space-y-0.5`,children:[s(Hf,{row:t}),t.namePresence===`missing`&&s(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),s(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function Hf({row:e}){let{t}=Z(),n=yt(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?s(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):s(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):s(Jn,{to:e.kind===`composed`?Yn(e.reportedDeviceId):Zn(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Uf({sources:t}){let{t:n}=Z();return t.length===0?s(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):s(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?s(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):s(Jn,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&s(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function Wf(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Gf(e){if(Array.isArray(e))return e}function Kf(e,t,n){return(t=tp(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qf(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Jf(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
@@ -1 +1 @@
1
- import{C as e,K as t,R as n,S as r,Y as i,et 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-CEyXHAdg.js";import{Ga as s,ca as c,ea as l,ta as u}from"./player-overlays-Db4ByaKk.js";import{mo as d,po as f}from"./client-CIZUUslj.js";import{Hi as p,Ho as m,Li as h,Ri as g,Ui as _,Uo as v,Vi as y,Vo as b,Wo as x,Xf as S,ip as C,zi as w}from"./src-DtKvvpJE.js";import{t as T}from"./i18n-DJdnRrxy.js";import{t as E}from"./useTranslation-BJr-n0es.js";import{di as D,mt as O,ui as k}from"./index-DckFE3TL.js";import{t as A}from"./AdminPage-B-VrKoee.js";a();function ee(e,t){return e.flatMap(e=>e.instances.map(n=>({addonId:e.addonId,id:n.id,name:n.name,enabled:n.enabled!==!1,providerName:t.get(e.addonId)??e.addonId})))}function te(e,t,n){let r=new Set,i=(e,t)=>`${e}\u0000${t}`,a=e.map(e=>{let a=e.instanceId===void 0?null:t.find(t=>t.addonId===e.providerAddonId&&t.id===e.instanceId)??null;return a!==null&&r.add(i(a.addonId,a.id)),{key:a===null?e.id:`instance:${a.addonId}:${a.id}`,name:e.name,providerName:a?.providerName??n(e),calendar:e,instance:a}});for(let e of t)r.has(i(e.addonId,e.id))||a.push({key:`instance:${e.addonId}:${e.id}`,name:e.name,providerName:e.providerName,calendar:null,instance:e});return a}var j=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function M(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function N(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function P(e){let t=e.getDay();return M(N(e,t===0?-6:1-t))}function F(e,t){if(t===`day`){let t=M(e);return{startMs:t.getTime(),endMs:N(t,1).getTime()}}if(t===`week`){let t=P(e);return{startMs:t.getTime(),endMs:N(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=P(n),a=N(P(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function I(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=P(e),n=N(t,6),r={month:`short`,day:`numeric`};return`${t.toLocaleDateString(void 0,r)} – ${n.toLocaleDateString(void 0,{...r,year:`numeric`})}`}return e.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}function L(e,t,n){return t===`day`?N(e,n):t===`week`?N(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function R(e,t){if(t===void 0)return e;let n=t.calendars[e.id];return n===void 0?e:{...e,visible:n.visible??e.visible,color:n.color??e.defaultColor}}function z(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function B(e){if(e.allDay===!0)return T.t(`systemPage.calendars.allDay`);let t=new Date(e.startMs),n=new Date(e.endMs),r={hour:`2-digit`,minute:`2-digit`};return`${t.toLocaleTimeString([],r)} – ${n.toLocaleTimeString([],r)}`}function V(e){let t=f(e),n=new Date(t.startMs),r=new Date(t.endMs),i={weekday:`short`,year:`numeric`,month:`short`,day:`numeric`};if(e.allDay===!0){let e=M(n),t=N(M(r),-1);return G(e,t)?T.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):T.t(`systemPage.calendars.rangeAllDay`,{from:n.toLocaleDateString(void 0,i),to:t.toLocaleDateString(void 0,i)})}let a={hour:`2-digit`,minute:`2-digit`};return G(n,r)?`${n.toLocaleDateString(void 0,i)} · ${n.toLocaleTimeString([],a)} – ${r.toLocaleTimeString([],a)}`:`${n.toLocaleString(void 0,{...i,...a})} – ${r.toLocaleString(void 0,{...i,...a})}`}function H({label:t,children:n}){return e(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[r(`dt`,{className:`text-foreground-subtle`,children:t}),r(`dd`,{className:`min-w-0 break-words text-foreground`,children:n})]})}function U({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=E();return r(h,{open:!0,onOpenChange:e=>!e&&a(),children:e(w,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(p,{children:e(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[r(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:i},"aria-hidden":!0}),r(_,{className:`min-w-0 break-words`,children:t.title})]})}),r(g,{children:e(`dl`,{className:`space-y-3`,children:[r(H,{label:o(`systemPage.calendars.when`,`When`),children:V(t)}),r(H,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(H,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(H,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(y,{children:r(S,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`common.close`,`Close`)})})]})})}function W(e,t){return e.filter(e=>d(e,t))}function G(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function K({mode:e,onChange:t}){let{t:n}=E(),i=[{id:`month`,label:n(`systemPage.calendars.month`,`Month`)},{id:`week`,label:n(`systemPage.calendars.week`,`Week`)},{id:`day`,label:n(`systemPage.calendars.day`,`Day`)}];return r(`div`,{className:`inline-flex rounded-lg border border-border bg-surface p-0.5`,role:`group`,"aria-label":n(`systemPage.calendars.calendarView`,`Calendar view`),children:i.map(n=>r(S,{variant:`unstyled`,type:`button`,className:e===n.id?`rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground`:`rounded-md px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground`,"aria-pressed":e===n.id,onClick:()=>t(n.id),"data-testid":`calendars-view-${n.id}`,children:n.label},n.id))})}function q({rows:t,onToggleVisible:n,onColorChange:i,busy:a}){let{t:c}=E();return e(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[r(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:c(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>{let l=t.calendar,u=t.instance!==null&&!t.instance.enabled;return e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface ${u?`opacity-60`:``}`,"data-testid":`calendars-row-${t.key}`,children:[l!==null&&!u?e(o,{children:[r(s,{className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:l.visible,disabled:a,onChange:e=>n(l.id,e.target.checked),"aria-label":c(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${l.id}`}),r(C,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:l.color,disabled:a,onChange:e=>i(l.id,e.target.value.toUpperCase()),"aria-label":c(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${l.id}`})]}):null,e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${l?.visible===!0&&!u?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[t.providerName,u?` · ${c(`systemPage.calendars.switchedOff`)}`:``,l!==null&&!l.enabled?` · ${c(`systemPage.calendars.unavailableAtSource`)}`:``]})]})]},t.key)})}),r(D,{to:`/system/integrations?tab=calendars`,className:`block text-[11px] text-primary underline-offset-2 hover:underline`,"data-testid":`calendars-manage-sources`,children:c(`systemPage.calendars.manageSources`,`Manage sources`)})]})}function J({ev:t,color:n,compact:i,onSelect:a}){return r(S,{variant:`unstyled`,type:`button`,className:i?`block w-full truncate rounded px-1 py-0.5 text-left text-[10px] leading-tight text-white hover:brightness-110`:`block w-full rounded-md px-2 py-1.5 text-left text-xs text-white hover:brightness-110`,style:{backgroundColor:n},title:t.title,onClick:()=>a(t),"data-testid":`calendars-event-${t.id}`,children:i?t.title:e(o,{children:[r(`div`,{className:`font-medium`,children:t.title}),r(`div`,{className:`opacity-90`,children:B(t)})]})})}function ne({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=E(),{startMs:c,endMs:l}=F(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=N(e,1))u.push(e);let d=t.getMonth();return e(`div`,{"data-testid":`calendars-month`,children:[r(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:j.map(e=>r(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),r(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(t=>{let c=M(t).getTime(),l=W(n,c),u=t.getMonth()!==d,f=G(t,a);return e(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[r(`div`,{className:f?`mb-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] font-semibold text-primary-foreground`:`mb-1 text-[11px] font-medium text-foreground-subtle`,children:t.getDate()}),e(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>r(J,{ev:e,color:i.get(e.calendarId)??`#64748B`,compact:!0,onSelect:o},e.id)),l.length>3?r(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function re({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=P(t);return r(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-7 sm:gap-px sm:overflow-hidden sm:rounded-lg sm:border sm:border-border sm:bg-border`,"data-testid":`calendars-week`,children:Array.from({length:7},(e,t)=>N(s,t)).map(t=>{let s=M(t).getTime(),c=W(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:G(t,a)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:t.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),r(`div`,{className:`space-y-1`,children:c.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>r(J,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function ie({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=E(),c=W(n,M(t).getTime());return c.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):r(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(t=>r(`li`,{children:e(S,{variant:`unstyled`,type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>o(t),"data-testid":`calendars-event-${t.id}`,children:[r(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:i.get(t.calendarId)??`#64748B`}}),e(`div`,{className:`min-w-0`,children:[r(`div`,{className:`font-medium text-sm text-foreground`,children:t.title}),e(`div`,{className:`text-xs text-foreground-subtle`,children:[B(t),` ·`,` `,a.get(t.calendarId)??t.calendarId]}),t.location!==void 0&&t.location.length>0?r(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.location}):null]})]})},t.id))})}function Y(){let{t:a}=E(),o=m(),s=b({}),d=x(),f=O(`calendar-source`),[p,h]=i(`month`),[g,_]=i(()=>M(new Date)),[y,C]=i(null),w=t(()=>M(new Date),[]),T=o.isSuccess,j=s.isSuccess&&s.data!==void 0?s.data:void 0,N=t(()=>!T||o.data===void 0?[]:o.data.map(e=>R(e,j)),[T,o.data,j]),P=t(()=>N.filter(e=>e.visible),[N]),B=t(()=>P.map(e=>e.id),[P]),V=t(()=>F(g,p),[g,p]),H=v({startMs:V.startMs,endMs:V.endMs,calendarIds:[...B]},{enabled:T&&B.length>0}),W=H.data??[],G=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.color);return e},[N]),J=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.name);return e},[N]),Y=t(()=>te(N,ee(f.holders,f.displayNames),z),[N,f.holders,f.displayNames]),X=n((e,t)=>{d.mutateAsync({calendarId:e,visible:t}).then(()=>s.refetch())},[s,d]),Z=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&d.mutateAsync({calendarId:e,color:t}).then(()=>s.refetch())},[s,d]),ae=n(()=>_(M(new Date)),[]),oe=n(()=>_(e=>L(e,p,-1)),[p]),se=n(()=>_(e=>L(e,p,1)),[p]),Q=`inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border bg-surface text-foreground hover:bg-primary/5 disabled:opacity-50`,$;return $=o.isPending||f.state===`pending`?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):o.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,o.error.message]}):f.state===`error`&&Y.length===0?e(`p`,{className:`text-sm text-danger`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,f.error]}):Y.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(k,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(D,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):B.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(q,{rows:Y,onToggleVisible:X,onColorChange:Z,busy:d.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:N.length===0?a(`systemPage.calendars.allSwitchedOff`):a(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(q,{rows:Y,onToggleVisible:X,onColorChange:Z,busy:d.isPending}),e(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(K,{mode:p,onChange:h}),e(`div`,{className:`flex items-center gap-1`,children:[r(S,{variant:`unstyled`,type:`button`,className:Q,onClick:oe,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(u,{className:`h-4 w-4`})}),r(S,{variant:`unstyled`,type:`button`,className:`inline-flex items-center rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5`,onClick:ae,"data-testid":`calendars-today`,children:a(`systemPage.calendars.today`,`Today`)}),r(S,{variant:`unstyled`,type:`button`,className:Q,onClick:se,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(l,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:I(g,p)})]}),H.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):H.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,H.error.message]}):p===`month`?r(ne,{anchor:g,events:W,colorById:G,today:w,onSelectEvent:C}):p===`week`?r(re,{anchor:g,events:W,colorById:G,today:w,onSelectEvent:C}):r(ie,{anchor:g,events:W,colorById:G,calName:J,onSelectEvent:C})]})]}),e(A,{icon:c,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[f.state===`error`&&Y.length>0?e(`p`,{className:`mb-3 text-sm text-warning`,role:`status`,"data-testid":`calendars-switches-unavailable`,children:[a(`systemPage.calendars.switchesUnavailable`,`The calendar switches could not be loaded, so they are hidden. Calendars switched off are not listed until they load.`),` `,f.error]}):null,$,y===null?null:r(U,{ev:y,calendarName:J.get(y.calendarId)??y.calendarId,color:G.get(y.calendarId)??`#64748B`,onClose:()=>C(null)})]})}export{Y as CalendarsPage,Y as default};
1
+ import{C as e,K as t,R as n,S as r,Y as i,et 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-CEyXHAdg.js";import{Ga as s,ca as c,ea as l,ta as u}from"./player-overlays-BLoaiapp.js";import{mo as d,po as f}from"./client-BzNa5PJa.js";import{Hi as p,Ho as m,Li as h,Ri as g,Ui as _,Uo as v,Vi as y,Vo as b,Wo as x,Xf as S,ip as C,zi as w}from"./src-B6L3EZPZ.js";import{t as T}from"./i18n-DJdnRrxy.js";import{t as E}from"./useTranslation-BJr-n0es.js";import{di as D,mt as O,ui as k}from"./index-B_SQlUTy.js";import{t as A}from"./AdminPage-CnX4g1T5.js";a();function ee(e,t){return e.flatMap(e=>e.instances.map(n=>({addonId:e.addonId,id:n.id,name:n.name,enabled:n.enabled!==!1,providerName:t.get(e.addonId)??e.addonId})))}function te(e,t,n){let r=new Set,i=(e,t)=>`${e}\u0000${t}`,a=e.map(e=>{let a=e.instanceId===void 0?null:t.find(t=>t.addonId===e.providerAddonId&&t.id===e.instanceId)??null;return a!==null&&r.add(i(a.addonId,a.id)),{key:a===null?e.id:`instance:${a.addonId}:${a.id}`,name:e.name,providerName:a?.providerName??n(e),calendar:e,instance:a}});for(let e of t)r.has(i(e.addonId,e.id))||a.push({key:`instance:${e.addonId}:${e.id}`,name:e.name,providerName:e.providerName,calendar:null,instance:e});return a}var j=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function M(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function N(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function P(e){let t=e.getDay();return M(N(e,t===0?-6:1-t))}function F(e,t){if(t===`day`){let t=M(e);return{startMs:t.getTime(),endMs:N(t,1).getTime()}}if(t===`week`){let t=P(e);return{startMs:t.getTime(),endMs:N(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=P(n),a=N(P(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function I(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=P(e),n=N(t,6),r={month:`short`,day:`numeric`};return`${t.toLocaleDateString(void 0,r)} – ${n.toLocaleDateString(void 0,{...r,year:`numeric`})}`}return e.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}function L(e,t,n){return t===`day`?N(e,n):t===`week`?N(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function R(e,t){if(t===void 0)return e;let n=t.calendars[e.id];return n===void 0?e:{...e,visible:n.visible??e.visible,color:n.color??e.defaultColor}}function z(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function B(e){if(e.allDay===!0)return T.t(`systemPage.calendars.allDay`);let t=new Date(e.startMs),n=new Date(e.endMs),r={hour:`2-digit`,minute:`2-digit`};return`${t.toLocaleTimeString([],r)} – ${n.toLocaleTimeString([],r)}`}function V(e){let t=f(e),n=new Date(t.startMs),r=new Date(t.endMs),i={weekday:`short`,year:`numeric`,month:`short`,day:`numeric`};if(e.allDay===!0){let e=M(n),t=N(M(r),-1);return G(e,t)?T.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):T.t(`systemPage.calendars.rangeAllDay`,{from:n.toLocaleDateString(void 0,i),to:t.toLocaleDateString(void 0,i)})}let a={hour:`2-digit`,minute:`2-digit`};return G(n,r)?`${n.toLocaleDateString(void 0,i)} · ${n.toLocaleTimeString([],a)} – ${r.toLocaleTimeString([],a)}`:`${n.toLocaleString(void 0,{...i,...a})} – ${r.toLocaleString(void 0,{...i,...a})}`}function H({label:t,children:n}){return e(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[r(`dt`,{className:`text-foreground-subtle`,children:t}),r(`dd`,{className:`min-w-0 break-words text-foreground`,children:n})]})}function U({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=E();return r(h,{open:!0,onOpenChange:e=>!e&&a(),children:e(w,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(p,{children:e(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[r(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:i},"aria-hidden":!0}),r(_,{className:`min-w-0 break-words`,children:t.title})]})}),r(g,{children:e(`dl`,{className:`space-y-3`,children:[r(H,{label:o(`systemPage.calendars.when`,`When`),children:V(t)}),r(H,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(H,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(H,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(y,{children:r(S,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`common.close`,`Close`)})})]})})}function W(e,t){return e.filter(e=>d(e,t))}function G(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function K({mode:e,onChange:t}){let{t:n}=E(),i=[{id:`month`,label:n(`systemPage.calendars.month`,`Month`)},{id:`week`,label:n(`systemPage.calendars.week`,`Week`)},{id:`day`,label:n(`systemPage.calendars.day`,`Day`)}];return r(`div`,{className:`inline-flex rounded-lg border border-border bg-surface p-0.5`,role:`group`,"aria-label":n(`systemPage.calendars.calendarView`,`Calendar view`),children:i.map(n=>r(S,{variant:`unstyled`,type:`button`,className:e===n.id?`rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground`:`rounded-md px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground`,"aria-pressed":e===n.id,onClick:()=>t(n.id),"data-testid":`calendars-view-${n.id}`,children:n.label},n.id))})}function q({rows:t,onToggleVisible:n,onColorChange:i,busy:a}){let{t:c}=E();return e(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[r(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:c(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>{let l=t.calendar,u=t.instance!==null&&!t.instance.enabled;return e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface ${u?`opacity-60`:``}`,"data-testid":`calendars-row-${t.key}`,children:[l!==null&&!u?e(o,{children:[r(s,{className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:l.visible,disabled:a,onChange:e=>n(l.id,e.target.checked),"aria-label":c(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${l.id}`}),r(C,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:l.color,disabled:a,onChange:e=>i(l.id,e.target.value.toUpperCase()),"aria-label":c(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${l.id}`})]}):null,e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${l?.visible===!0&&!u?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[t.providerName,u?` · ${c(`systemPage.calendars.switchedOff`)}`:``,l!==null&&!l.enabled?` · ${c(`systemPage.calendars.unavailableAtSource`)}`:``]})]})]},t.key)})}),r(D,{to:`/system/integrations?tab=calendars`,className:`block text-[11px] text-primary underline-offset-2 hover:underline`,"data-testid":`calendars-manage-sources`,children:c(`systemPage.calendars.manageSources`,`Manage sources`)})]})}function J({ev:t,color:n,compact:i,onSelect:a}){return r(S,{variant:`unstyled`,type:`button`,className:i?`block w-full truncate rounded px-1 py-0.5 text-left text-[10px] leading-tight text-white hover:brightness-110`:`block w-full rounded-md px-2 py-1.5 text-left text-xs text-white hover:brightness-110`,style:{backgroundColor:n},title:t.title,onClick:()=>a(t),"data-testid":`calendars-event-${t.id}`,children:i?t.title:e(o,{children:[r(`div`,{className:`font-medium`,children:t.title}),r(`div`,{className:`opacity-90`,children:B(t)})]})})}function ne({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=E(),{startMs:c,endMs:l}=F(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=N(e,1))u.push(e);let d=t.getMonth();return e(`div`,{"data-testid":`calendars-month`,children:[r(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:j.map(e=>r(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),r(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(t=>{let c=M(t).getTime(),l=W(n,c),u=t.getMonth()!==d,f=G(t,a);return e(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[r(`div`,{className:f?`mb-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] font-semibold text-primary-foreground`:`mb-1 text-[11px] font-medium text-foreground-subtle`,children:t.getDate()}),e(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>r(J,{ev:e,color:i.get(e.calendarId)??`#64748B`,compact:!0,onSelect:o},e.id)),l.length>3?r(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function re({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=P(t);return r(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-7 sm:gap-px sm:overflow-hidden sm:rounded-lg sm:border sm:border-border sm:bg-border`,"data-testid":`calendars-week`,children:Array.from({length:7},(e,t)=>N(s,t)).map(t=>{let s=M(t).getTime(),c=W(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:G(t,a)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:t.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),r(`div`,{className:`space-y-1`,children:c.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>r(J,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function ie({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=E(),c=W(n,M(t).getTime());return c.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):r(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(t=>r(`li`,{children:e(S,{variant:`unstyled`,type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>o(t),"data-testid":`calendars-event-${t.id}`,children:[r(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:i.get(t.calendarId)??`#64748B`}}),e(`div`,{className:`min-w-0`,children:[r(`div`,{className:`font-medium text-sm text-foreground`,children:t.title}),e(`div`,{className:`text-xs text-foreground-subtle`,children:[B(t),` ·`,` `,a.get(t.calendarId)??t.calendarId]}),t.location!==void 0&&t.location.length>0?r(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.location}):null]})]})},t.id))})}function Y(){let{t:a}=E(),o=m(),s=b({}),d=x(),f=O(`calendar-source`),[p,h]=i(`month`),[g,_]=i(()=>M(new Date)),[y,C]=i(null),w=t(()=>M(new Date),[]),T=o.isSuccess,j=s.isSuccess&&s.data!==void 0?s.data:void 0,N=t(()=>!T||o.data===void 0?[]:o.data.map(e=>R(e,j)),[T,o.data,j]),P=t(()=>N.filter(e=>e.visible),[N]),B=t(()=>P.map(e=>e.id),[P]),V=t(()=>F(g,p),[g,p]),H=v({startMs:V.startMs,endMs:V.endMs,calendarIds:[...B]},{enabled:T&&B.length>0}),W=H.data??[],G=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.color);return e},[N]),J=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.name);return e},[N]),Y=t(()=>te(N,ee(f.holders,f.displayNames),z),[N,f.holders,f.displayNames]),X=n((e,t)=>{d.mutateAsync({calendarId:e,visible:t}).then(()=>s.refetch())},[s,d]),Z=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&d.mutateAsync({calendarId:e,color:t}).then(()=>s.refetch())},[s,d]),ae=n(()=>_(M(new Date)),[]),oe=n(()=>_(e=>L(e,p,-1)),[p]),se=n(()=>_(e=>L(e,p,1)),[p]),Q=`inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border bg-surface text-foreground hover:bg-primary/5 disabled:opacity-50`,$;return $=o.isPending||f.state===`pending`?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):o.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,o.error.message]}):f.state===`error`&&Y.length===0?e(`p`,{className:`text-sm text-danger`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,f.error]}):Y.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(k,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(D,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):B.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(q,{rows:Y,onToggleVisible:X,onColorChange:Z,busy:d.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:N.length===0?a(`systemPage.calendars.allSwitchedOff`):a(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(q,{rows:Y,onToggleVisible:X,onColorChange:Z,busy:d.isPending}),e(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(K,{mode:p,onChange:h}),e(`div`,{className:`flex items-center gap-1`,children:[r(S,{variant:`unstyled`,type:`button`,className:Q,onClick:oe,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(u,{className:`h-4 w-4`})}),r(S,{variant:`unstyled`,type:`button`,className:`inline-flex items-center rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5`,onClick:ae,"data-testid":`calendars-today`,children:a(`systemPage.calendars.today`,`Today`)}),r(S,{variant:`unstyled`,type:`button`,className:Q,onClick:se,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(l,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:I(g,p)})]}),H.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):H.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,H.error.message]}):p===`month`?r(ne,{anchor:g,events:W,colorById:G,today:w,onSelectEvent:C}):p===`week`?r(re,{anchor:g,events:W,colorById:G,today:w,onSelectEvent:C}):r(ie,{anchor:g,events:W,colorById:G,calName:J,onSelectEvent:C})]})]}),e(A,{icon:c,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[f.state===`error`&&Y.length>0?e(`p`,{className:`mb-3 text-sm text-warning`,role:`status`,"data-testid":`calendars-switches-unavailable`,children:[a(`systemPage.calendars.switchesUnavailable`,`The calendar switches could not be loaded, so they are hidden. Calendars switched off are not listed until they load.`),` `,f.error]}):null,$,y===null?null:r(U,{ev:y,calendarName:J.get(y.calendarId)??y.calendarId,color:G.get(y.calendarId)??`#64748B`,onClose:()=>C(null)})]})}export{Y as CalendarsPage,Y as default};
@@ -1 +1 @@
1
- import{S as e}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Hr as t}from"./player-overlays-Db4ByaKk.js";import{t as n}from"./useTranslation-BJr-n0es.js";import{t as r}from"./InstancesTable-Dh2_4hoS.js";function i(){let{t:i}=n();return e(r,{functionCap:`camera-grid-layout`,icon:t,title:i(`cameraGrids.title`,`Camera grids`),subtitle:i(`cameraGrids.subtitle`,`A grid is a composite camera: several cameras composed into one picture, recorded and played back like any other. Create one with a name, then open its camera to lay it out.`),emptyTitle:i(`cameraGrids.empty`,`No camera grids yet`),emptyDescription:i(`cameraGrids.emptyHint`,`Add a grid to compose several cameras into one.`),addLabel:i(`cameraGrids.add`,`Add grid`)})}export{i as CameraGridsPage};
1
+ import{S as e}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Hr as t}from"./player-overlays-BLoaiapp.js";import{t as n}from"./useTranslation-BJr-n0es.js";import{t as r}from"./InstancesTable-B9vZgE2z.js";function i(){let{t:i}=n();return e(r,{functionCap:`camera-grid-layout`,icon:t,title:i(`cameraGrids.title`,`Camera grids`),subtitle:i(`cameraGrids.subtitle`,`A grid is a composite camera: several cameras composed into one picture, recorded and played back like any other. Create one with a name, then open its camera to lay it out.`),emptyTitle:i(`cameraGrids.empty`,`No camera grids yet`),emptyDescription:i(`cameraGrids.emptyHint`,`Add a grid to compose several cameras into one.`),addLabel:i(`cameraGrids.add`,`Add grid`)})}export{i as CameraGridsPage};