@camstack/addon-admin-ui 1.2.660 → 1.2.661

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 (127) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/assets/Addons-Dd01MZDq.js +5 -0
  3. package/dist/assets/{AdminPage-CERAT6OE.js → AdminPage-Cr4Mgq6E.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-Br7kOiVH.js → AdminSectionedPage-BT0D5Z5E.js} +1 -1
  5. package/dist/assets/AiProfiles-CQC25jwp.js +3 -0
  6. package/dist/assets/{BootstrapSettingsForm-BKRohQp4.js → BootstrapSettingsForm-AwY0YIsh.js} +1 -1
  7. package/dist/assets/Build-BxBtb1pa.js +42 -0
  8. package/dist/assets/Calendars-CUwxuhjS.js +1 -0
  9. package/dist/assets/{CameraGrids-BL9IJLpe.js → CameraGrids-jGWuONma.js} +1 -1
  10. package/dist/assets/Cluster-BsxCN2Ee.js +1 -0
  11. package/dist/assets/CompositionBlockEditor-ePXZVSiz.js +2 -0
  12. package/dist/assets/{CompositionEditorPage-CPPeSp5g.js → CompositionEditorPage-Bs6PP5S0.js} +1 -1
  13. package/dist/assets/Data-CFXuZX2p.js +2 -0
  14. package/dist/assets/DeviceDetail-B7hrPP0Q.js +2 -0
  15. package/dist/assets/Devices-DmAIsMCu.js +1 -0
  16. package/dist/assets/{EmbedDevicePage-DvRASgDw.js → EmbedDevicePage-igDGWLlu.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-DHSr3Tl_.js → EmbedPlayerPage-CRe4aMxN.js} +1 -1
  18. package/dist/assets/History-CkGkYHIQ.js +1 -0
  19. package/dist/assets/Identity-BOuV0PJp.js +1 -0
  20. package/dist/assets/InstancesTable-B4YAqBGO.js +1 -0
  21. package/dist/assets/IntegrationDetail-DRtu4AI8.js +1 -0
  22. package/dist/assets/Integrations-B0NJiQCE.js +1 -0
  23. package/dist/assets/{Integrations-SQZl5xUE.js → Integrations-Cr2CqMEa.js} +2 -2
  24. package/dist/assets/Library-iu7KepLq.js +1 -0
  25. package/dist/assets/Locations-DaOJoHB_.js +3 -0
  26. package/dist/assets/{Logs-BUIyFNHB.js → Logs-B7Y7BGWA.js} +1 -1
  27. package/dist/assets/{MaskShapeCanvas-B4cgdl3M.js → MaskShapeCanvas-BITNuLal.js} +1 -1
  28. package/dist/assets/{MotionZonesSettings-E62PigxG.js → MotionZonesSettings-BDiBCvY5.js} +1 -1
  29. package/dist/assets/MyAccess-BCmi5v1l.js +2 -0
  30. package/dist/assets/Network-DqeqHMP6.js +1 -0
  31. package/dist/assets/NodeAddonsSettingsPanel-CxbHY55W.js +2 -0
  32. package/dist/assets/Notifications-C8QeVMgl.js +1 -0
  33. package/dist/assets/Pipeline-GX33Dr8E.js +1 -0
  34. package/dist/assets/{PrivacyMaskSettings-CY_ePn_3.js → PrivacyMaskSettings-BXQOKceN.js} +1 -1
  35. package/dist/assets/Recordings-D0HsC6x1.js +1 -0
  36. package/dist/assets/SceneMonitorEditor-CZ_BFOG7.js +1 -0
  37. package/dist/assets/SessionsList-DLEV9_gs.js +2 -0
  38. package/dist/assets/Showroom-2AKsy64i.js +1 -0
  39. package/dist/assets/StorageLocationsTable-BgrUmv1n.js +1 -0
  40. package/dist/assets/{System-GaBMCDXq.js → System-DaWWeXtH.js} +1 -1
  41. package/dist/assets/{Terminal-bEPuP-Ni.js → Terminal-CJ4WgYjd.js} +5 -5
  42. package/dist/assets/{TrainingProviders-CKnVaSy5.js → TrainingProviders-B7k0ZtE0.js} +1 -1
  43. package/dist/assets/{Viewer-D6N_FDoi.js → Viewer-CjsGjUB-.js} +1 -1
  44. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-xQ6ZAyO5.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-D8PmgRp8.js} +1 -1
  45. package/dist/assets/{action-draft-BFWQOcD-.js → action-draft-DnNIEmvI.js} +1 -1
  46. package/dist/assets/{ai-page.helpers-B5WcoTGx.js → ai-page.helpers-CGjpeisw.js} +1 -1
  47. package/dist/assets/{assignment-candidates-BCi2Ds6Z.js → assignment-candidates-naQrL3dO.js} +1 -1
  48. package/dist/assets/{authed-media-C7-SuZfk.js → authed-media-DTuPnK89.js} +1 -1
  49. package/dist/assets/{board-model-Dtuzj7p0.js → board-model-Bd0emGWd.js} +1 -1
  50. package/dist/assets/client-CdF3TYeB.js +1115 -0
  51. package/dist/assets/{command-vocab-D8O8h9Nx.js → command-vocab-DjcG_iEx.js} +1 -1
  52. package/dist/assets/{device-detail-CNETUEYQ.js → device-detail-BakcTqag.js} +1 -1
  53. package/dist/assets/device-integration-icon-Cyq0fBL5.js +1 -0
  54. package/dist/assets/device-picker-model-Ciov4ggQ.js +1 -0
  55. package/dist/assets/{dist-D2wqGzzP.js → dist-7-KeEy8F.js} +1 -1
  56. package/dist/assets/dist-7sm4pyDQ.js +1115 -0
  57. package/dist/assets/{format-DQPwm2LA.js → format-DdSyVeZV.js} +1 -1
  58. package/dist/assets/{hostInit-BjmW5lpD.js → hostInit-CHSexcMQ.js} +1 -1
  59. package/dist/assets/i18n-CfxLCMD-.js +1 -0
  60. package/dist/assets/icons-DCgN8JXc.js +1 -0
  61. package/dist/assets/index-BxZnZO1J.js +4 -0
  62. package/dist/assets/{index-CoqQ1LfI.css → index-CK-FKuHu.css} +1 -1
  63. package/dist/assets/{linked-devices-model-CeeIdQcU.js → linked-devices-model-_6nOgrEe.js} +1 -1
  64. package/dist/assets/{mf-entry-bootstrap-0-1178bf74.js → mf-entry-bootstrap-0-a2f86924.js} +2 -2
  65. package/dist/assets/mount-Ciov4ggQ.js +1 -0
  66. package/dist/assets/{notification-rule-status-CoQzv8bD.js → notification-rule-status-DYX3kx8s.js} +1 -1
  67. package/dist/assets/{player-overlays-BT0TXPfb.js → player-overlays-D6PvO1EY.js} +1 -1
  68. package/dist/assets/remoteEntry-BRIrNkYL.js +1 -0
  69. package/dist/assets/src-BZ76tsZe.js +263 -0
  70. package/dist/assets/sso-popup-CRva85Eh.js +1 -0
  71. package/dist/assets/{step-inspector-model-Bs29Quj-.js → step-inspector-model-CGMSXxPh.js} +1 -1
  72. package/dist/assets/{terminal-BSZfUawf.js → terminal-DK_9A3Rq.js} +1 -1
  73. package/dist/assets/{use-scenes-feed-DjWk3U0s.js → use-scenes-feed-DE611aYH.js} +1 -1
  74. package/dist/assets/{use-stationary-objects-D8_FnyFC.js → use-stationary-objects-zZxmRKHa.js} +1 -1
  75. package/dist/assets/{useAdminDeviceRemoval-DgZKyG5k.js → useAdminDeviceRemoval-C1c-5Iqt.js} +1 -1
  76. package/dist/assets/useEventInvalidation-Ciov4ggQ.js +1 -0
  77. package/dist/assets/{useNodeUrlSelection-CdgZ2vRL.js → useNodeUrlSelection-pGeSjWQO.js} +1 -1
  78. package/dist/assets/useTemplateSave-1_ofWdl6.js +1 -0
  79. package/dist/assets/variable-Cq3v1-Kt.js +1 -0
  80. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-B3VWqHa8.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-UBhz1_JR.js} +2 -2
  81. package/dist/index.html +10 -9
  82. package/dist/server/addon.js +516 -51
  83. package/package.json +2 -2
  84. package/dist/assets/Addons-BKyuLQDW.js +0 -5
  85. package/dist/assets/AiProfiles-CBSjTujs.js +0 -3
  86. package/dist/assets/Build-DDQsUqm9.js +0 -40
  87. package/dist/assets/Calendars-BCrXW6ev.js +0 -1
  88. package/dist/assets/Cluster-B9ANo52_.js +0 -1
  89. package/dist/assets/CompositionBlockEditor-DCCYb3Al.js +0 -2
  90. package/dist/assets/Data-DbJLrZGB.js +0 -2
  91. package/dist/assets/DeviceDetail-D40ZWxPY.js +0 -2
  92. package/dist/assets/Devices-Ci3mDEu7.js +0 -1
  93. package/dist/assets/History-C8ol6H76.js +0 -1
  94. package/dist/assets/Identity-CEJnvsoZ.js +0 -1
  95. package/dist/assets/InstancesTable-FBx9JRZk.js +0 -1
  96. package/dist/assets/IntegrationDetail-BEK8Sry_.js +0 -1
  97. package/dist/assets/IntegrationWizard-CcNLdn4m.js +0 -1
  98. package/dist/assets/Integrations-ET87lqxO.js +0 -1
  99. package/dist/assets/Library-goz2bc6M.js +0 -1
  100. package/dist/assets/Locations-2rJZmR7V.js +0 -3
  101. package/dist/assets/MyAccess-BWDAey7o.js +0 -2
  102. package/dist/assets/Network-CKKRKQ-O.js +0 -1
  103. package/dist/assets/NodeAddonsSettingsPanel-Cst9sv6D.js +0 -2
  104. package/dist/assets/Notifications-C5328Lom.js +0 -1
  105. package/dist/assets/Pipeline-vIZNfSae.js +0 -1
  106. package/dist/assets/Recordings-DFKQYs1C.js +0 -1
  107. package/dist/assets/ScanSubnetEditor-BQ7H3hHG.js +0 -1
  108. package/dist/assets/SceneMonitorEditor-DXSSscj5.js +0 -1
  109. package/dist/assets/SessionsList-PNK9JpXa.js +0 -2
  110. package/dist/assets/Showroom-DobzkfjB.js +0 -1
  111. package/dist/assets/StorageLocationsTable-D_AWqrcu.js +0 -1
  112. package/dist/assets/Templates-BPfFAYcv.js +0 -1
  113. package/dist/assets/client-rKDh78PS.js +0 -1115
  114. package/dist/assets/create-composition-BDLBjShb.js +0 -1
  115. package/dist/assets/device-integration-icon-DgV2s6G7.js +0 -1
  116. package/dist/assets/device-picker-model-DoWv_-il.js +0 -1
  117. package/dist/assets/dist-XuKhSZmU.js +0 -1115
  118. package/dist/assets/framework-packages-B0ugw-Ay.js +0 -1
  119. package/dist/assets/i18n-a_osePOH.js +0 -1
  120. package/dist/assets/icons-BIkHFZKC.js +0 -1
  121. package/dist/assets/index-GTPwIjSa.js +0 -4
  122. package/dist/assets/mount-DoWv_-il.js +0 -1
  123. package/dist/assets/remoteEntry-BAhwoqOT.js +0 -1
  124. package/dist/assets/src-BJEmpxo2.js +0 -263
  125. package/dist/assets/useEventInvalidation-DoWv_-il.js +0 -1
  126. package/dist/assets/useTemplateSave-OvjvioSD.js +0 -1
  127. package/dist/assets/variable-Cy0obf0C.js +0 -1
@@ -1,40 +0,0 @@
1
- import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,k as d,o as f,t as p,x as m,z as h}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$t as g,Bi as _,Ga as v,Gr as y,Ji as b,Ln as x,Mr as S,Pr as C,Ra as w,Tt as T,Un as E,Xr as D,Yt as O,_t as k,ct as A,er as j,ja as M,na as N,or as P,tr as F,ut as I,wa as L}from"./player-overlays-BT0TXPfb.js";import{Ao as R,Bi as z,Bo as ee,Co as B,Do as V,Eo as H,Er as te,Fa as ne,Fo as re,Ho as U,Io as ie,La as ae,Mo as oe,Na as W,No as se,Oo as ce,Po as le,Ri as ue,Ro as de,So as fe,To as pe,Vi as me,Wo as he,Yt as ge,_o as _e,aa as ve,ao as ye,bo as be,co as xe,do as Se,ea as Ce,fo as we,gc as Te,go as Ee,ho as De,jo as Oe,ka as ke,ko as Ae,lo as je,nc as Me,no as Ne,oo as Pe,po as Fe,ro as Ie,so as Le,vo as Re,vs as ze,wo as Be,xo as Ve,yo as He,zo as Ue}from"./client-rKDh78PS.js";import{t as We}from"./chevron-down-CBb-F8DT.js";import{t as Ge}from"./boxes-k5PsZ3NR.js";import{o as Ke}from"./terminal-BSZfUawf.js";import{n as qe,r as Je,t as Ye}from"./variable-Cy0obf0C.js";import{Br as Xe,Bs as Ze,Cf as G,Ci as Qe,Cr as $e,Di as et,Do as tt,Ef as nt,Ei as rt,Eo as it,Ff as K,Fo as at,Gd as ot,H as st,Hr as ct,Ht as lt,Io as ut,Jr as dt,Js as ft,Lo as pt,Mi as mt,No as ht,Oi as gt,Oo as _t,Pi as vt,Q as yt,Rf as bt,Ru as xt,S as St,Sf as Ct,Sr as wt,Tf as q,Ti as Tt,Tr as Et,Uf as J,Ur as Dt,Vr as Ot,Vt as kt,Wi as At,Xf as jt,Xr as Mt,Yf as Nt,Z as Pt,_ as Ft,_a as It,_d as Lt,_s as Rt,ar as zt,bn as Bt,da as Vt,dd as Ht,dp as Ut,fa as Wt,fd as Gt,ga as Kt,gd as qt,h as Jt,ha as Yt,hd as Xt,ic as Zt,ji as Qt,jo as $t,ki as en,md as tn,pa as nn,pd as rn,ps as an,qi as on,qt as sn,rr as cn,rt as ln,ud as un,vr as dn,w as fn,wr as pn,ws as mn,x as hn,ya as gn,zi as _n}from"./src-BJEmpxo2.js";import{t as Y}from"./i18n-a_osePOH.js";import{t as X}from"./useTranslation-BJr-n0es.js";import{H as vn,Kr as yn,Qr as bn,Xr as xn,ct as Sn,dt as Cn,m as wn,p as Tn,qr as En,x as Dn}from"./index-GTPwIjSa.js";import{t as On}from"./AdminSectionedPage-Br7kOiVH.js";import{n as kn}from"./format-DQPwm2LA.js";import{C as An,Et as jn,St as Mn,a as Nn,at as Pn,b as Fn,g as In,i as Ln,n as Rn,nt as zn,o as Bn,r as Vn,w as Hn,xt as Un,y as Wn}from"./CompositionBlockEditor-DCCYb3Al.js";import{a as Gn,c as Kn,i as qn,l as Jn,n as Yn,o as Xn,r as Zn,s as Qn,t as $n,u as er}from"./create-composition-BDLBjShb.js";import{a as tr,i as nr,n as rr,o as ir,r as ar,s as or}from"./action-draft-BFWQOcD-.js";var sr=`const AUTOMATION_RECIPE =`,cr=`// EJECTED from the visual automation editor — this file is now hand-owned.
2
- // The recipe that produced it was removed with it, on purpose: while it was
3
- // here the editor could re-open this block and overwrite everything below.`;function lr(e){return e.includes(sr)}function ur(e){let t=e.indexOf(sr);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 dr(e){let t=ur(e);if(t===null)return{ok:!1,reason:Y.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:Y.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=He.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Y.t(`helpers.recipeFromCode.schemaMismatch`):Y.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function fr(e){let t=ur(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)}${cr}${e.slice(i)}`}u();var pr=`when`;function mr(e){return e===void 0||e.trim()===``?null:e}function hr(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function gr(e){return e===`ok`?`pass`:e===`error`||e===`failed-continued`||e===`timed-out`?`fail`:`idle`}function _r(e){return e.steps.map(e=>({index:hr(e.path),tone:gr(e.outcome),message:mr(e.message)}))}function vr(e){let t=e.trigger.outcome===`pass`?`pass`:`fail`,n=mr(e.trigger.reason),r=e.conditions.find(e=>e.path===pr);return t===`fail`||r===void 0?{tone:t,reason:n}:r.outcome===`fail`?{tone:`fail`,reason:mr(r.reason)??n}:{tone:r.outcome===`pass`?`pass`:`idle`,reason:n}}function yr(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:mr(e.verdict?.reason)}}function br(e){let t=_r(e);return{when:vr(e),thenBlock:yr(e,t),steps:t}}function xr(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}function Sr(e){return e===null?{kind:`unknown`}:{kind:`value`,text:Array.isArray(e)?e.join(`, `):String(e)}}function Cr(e){return{kind:e.kind,tone:gr(e.outcome),message:mr(e.message)}}function wr(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 Tr(e,t){return t===void 0?null:e===void 0?t:`${e}.${t}`}function Er(e){return{vars:Object.entries(e.trigger.vars).map(([e,t])=>({name:e,value:Sr(t)})),conditions:e.conditions.map(e=>({path:e.path,depth:e.path.split(`.`).length-1,kind:e.kind,outcome:e.outcome,reason:mr(e.reason),subject:Tr(e.cap,e.fieldPath),operator:e.operator??null,deviceId:e.deviceId??null,expected:e.expected===void 0?null:Sr(e.expected),observed:e.observed===void 0?null:Sr(e.observed),rawExpected:e.expected,rawObserved:e.observed})),steps:e.steps.map(e=>({index:hr(e.path),kind:e.kind,tone:gr(e.outcome),message:mr(e.message),args:Object.entries(e.args??{}).map(([e,t])=>({name:e,value:Sr(t)})),devices:(e.devices??[]).map(e=>({deviceId:e.deviceId,tone:e.outcome===`ok`?`pass`:`fail`,message:mr(e.message)})),chose:wr(e.branch),nested:(e.steps??[]).map(e=>({...Cr(e),chose:wr(e.branch),rounds:e.iterations??null,inner:(e.steps??[]).map(Cr)})),rounds:e.iterations??null}))}}function Dr(e){let t=Er(e);return{nodes:new Map(t.conditions.map(e=>[e.path,e])),triggerPath:e.trigger.path??null,vars:t.vars}}var Or=6;function kr(e,t,n){if(typeof e!=`number`||t===void 0||n===void 0)return Sr(e);let r=he(e,t,n);return r===void 0?Sr(e):{kind:`value`,text:`${String(Number(r.toPrecision(Or)))} ${n}`}}function Ar(e){let t=e.steps.find(e=>e.outcome===`error`),n=t===void 0?mr(e.verdict?.reason)??mr(e.trigger.reason):mr(t.message);return{stepsRun:e.steps.filter(e=>e.outcome===`ok`).length,stepsTotal:e.steps.length,reason:n}}var jr={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},Mr={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},Nr={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function Pr(){let{t:e}=X();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 Fr={done:`success`,missed:`warning`,inactive:`neutral`,"condition-false":`neutral`,failed:`danger`,held:`success`,"gave-up":`danger`,overridden:`info`,"suspended-manual":`warning`};function Ir(){let{t:e}=X();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 Lr=`max-h-64`;function Rr(){let e=jt(),t=Nt();return e||t}function zr({expanded:t,onToggle:n}){let{t:r}=X();return e(K,{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:[o(bt,{expanded:t}),o(`span`,{children:t?r(`flow.runs.hide`,`Hide runs`):r(`flow.runs.show`,`Show runs`)})]})}function Br({run:t}){let{t:n}=X(),r=Pr(),i=Ar(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:[o(q,{variant:jr[t.outcome],children:r(t.outcome)}),i.reason!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:i.reason}),i.stepsTotal>0&&o(`span`,{className:`text-foreground-subtle`,children:n(`flow.runs.stepsRan`,`{{run}} of {{total}} steps ran`,{run:i.stepsRun,total:i.stepsTotal})})]})}function Vr({traces:t,selectedId:n,onSelect:r}){let{t:i}=X(),a=Pr(),s=Ir(),l=Rr(),[u,d]=c(null),f=u??!l,p=t===void 0?[]:t.toReversed(),h=p.find(e=>e.runId===n)??null;return e(wt,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:y,children:[o(zr,{expanded:f,onToggle:()=>d(!f)}),f?t===void 0?o(nt,{className:`m-3 h-16`}):p.length===0?o(_n,{title:i(`flow.runs.emptyTitle`,`No runs yet`),description:i(`flow.runs.emptyDescription`,`Each run appears here with what it decided.`)}):e(m,{children:[o(`ul`,{className:`${Lr} divide-y divide-border-subtle overflow-y-auto`,"data-testid":`runs-panel`,children:p.map(t=>{let i=t.runId===n;return o(`li`,{children:e(K,{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?o(q,{variant:jr[t.outcome],children:a(t.outcome)}):o(q,{variant:Fr[t.scheduler],children:s(t.scheduler)}),t.repeat>1&&o(q,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:kn(t.lastAt)})]}),o(`span`,{className:`truncate text-sm text-foreground`,children:t.trigger.reason})]})},t.runId)})}),h!==null&&o(Br,{run:h}),o(`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.`)})]}):h!==null&&o(Br,{run:h})]})}function Hr(e){return Mr[e]}var Ur={pass:`border-success/50`,fail:`border-danger/50`,idle:`border-border`};function Wr(e){return Ur[e]}function Gr({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`:Mr[i.tone]}`,"data-testid":`block-${t}`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`h4`,{className:`text-sm font-semibold uppercase tracking-wide`,children:n}),r!==void 0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i!==null&&i.reason!==null&&o(`p`,{className:`mb-2 text-xs font-medium ${Nr[i.tone]}`,children:i.reason}),o(`div`,{className:`space-y-2`,children:a})]})}var Kr=[`count`,`while`,`until`,`forEach`],qr=2,Jr=10,Yr={kind:`all`,children:[]};function Xr(e){return e===`count`||e===`while`||e===`until`||e===`forEach`}function Zr(e,t){return Number.isFinite(e)?Math.min(t,Math.max(1,Math.round(e))):1}function Qr(e){return Zr(e,20)}function $r(e){return Zr(e,50)}function ei(e){switch(e){case`count`:return{by:e,count:qr};case`while`:case`until`:return{by:e,when:Yr,maxIterations:Jr};case`forEach`:return{by:e,target:{kind:`devices`,ids:[]}}}}function ti(e,t){if(e.by!==`while`&&e.by!==`until`)return e;let{waitS:n,...r}=e;return t===null?r:{...r,waitS:Zr(t,Ve)}}function ni(){return{kind:`repeat`,loop:ei(`count`),steps:[]}}var ri=[`s`,`min`,`h`],ii={s:1,min:60,h:3600};function ai(e){return e===`s`||e===`min`||e===`h`}function oi(e){return e%ii.h===0?{value:e/ii.h,unit:`h`}:e%ii.min===0?{value:e/ii.min,unit:`min`}:{value:e,unit:`s`}}function si(e,t){let n=Math.round(e*ii[t]);return Number.isFinite(n)?Math.min(Math.max(n,1),fe):1}function ci(){return{kind:`wait-until`,when:{kind:`all`,children:[]},timeoutS:600,onTimeout:`continue`}}var li=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function ui(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 li}}function di(e){switch(e){case`eq`:return Y.t(`helpers.recipeParts.op_eq`);case`ne`:return Y.t(`helpers.recipeParts.op_ne`);case`gt`:return Y.t(`helpers.recipeParts.op_gt`);case`gte`:return Y.t(`helpers.recipeParts.op_gte`);case`lt`:return Y.t(`helpers.recipeParts.op_lt`);case`lte`:return Y.t(`helpers.recipeParts.op_lte`);case`contains`:return Y.t(`helpers.recipeParts.op_contains`);default:return Y.t(`helpers.recipeParts.op_in`)}}function fi(e){return ui(e).map(e=>({value:e,label:di(e)}))}Ne.filter(e=>Ie(e).role===`event`),Ne.filter(e=>Ie(e).role===`state`);function pi(e){return Y.t(`${Ie(e).i18nKey}.label`)}function mi(e){return Y.t(`${Ie(e).i18nKey}.description`)}function hi(e){return Y.t(`${Ie(e).i18nKey}.example`)}var gi={when:{kind:`all`,children:[]},actions:[]};function _i(e){return ye(e)}function vi(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
- `};case`action`:return{kind:e,actionId:``};case`stop`:return{kind:e,reason:``,outcome:`ok`};case`set`:return{kind:e,vars:{}};case`wait-until`:return ci();case`parallel`:return{kind:e,steps:[]};case`repeat`:return ni();case`choose`:return{kind:e,branches:[{if:{kind:`all`,children:[]},steps:[]}]};default:return{kind:`command`,target:{kind:`devices`,ids:[]},actionId:``}}}function Z(e,t,n){return e.map((e,r)=>r===t?n:e)}function yi(e,t){return e.filter((e,n)=>n!==t)}function bi(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=yi(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function xi(e,t){return{...e,actions:[...t]}}var Si={pass:`success`,fail:`danger`,"not-evaluated":`neutral`},Ci={pass:`success`,fail:`danger`,idle:`neutral`};function wi({value:e}){let{t}=X();return e.kind===`unknown`?o(`span`,{className:`italic text-foreground-subtle`,"data-testid":`trace-value-unknown`,children:t(`flow.runs.unknownValue`,`unknown`)}):o(`span`,{className:`font-mono text-foreground`,children:e.text})}function Ti(){let{t:e}=X();return t=>t===`pass`?e(`flow.runs.nodePass`,`Passed`):t===`fail`?e(`flow.runs.nodeFail`,`Failed`):e(`flow.runs.nodeNotEvaluated`,`Not evaluated`)}function Ei(e){let t=pe.safeParse(e);return t.success?di(t.data):e}function Di({items:t,testId:n}){return t.length===0?null:o(`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:[o(`dt`,{className:`text-foreground-subtle`,children:t.name}),o(`dd`,{className:`break-words`,children:o(wi,{value:t.value})})]},t.name))})}function Oi({node:t,vars:n=[],expected:r,observed:i}){let{t:a}=X(),s=Ti(),c=t.subject===null?null:`${t.subject}${t.operator===null?``:` ${Ei(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:[o(q,{variant:Si[t.outcome],children:s(t.outcome)}),t.reason!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:t.reason})]}),c!==null&&o(`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`),` `,o(wi,{value:r})]}),i!==null&&e(`span`,{"data-testid":`trace-observed`,children:[a(`flow.runs.observed`,`Observed`),` `,o(wi,{value:i})]})]}),o(Di,{testId:`trace-vars`,items:n})]})}function ki({step:t,deviceName:n}){let{t:r}=X(),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:[o(q,{variant:Ci[t.tone],children:i}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:t.message})]}),t.chose!==null&&o(`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&&o(`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&&o(`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(q,{variant:Ci[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message}),t.chose!==null&&o(`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&&o(`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&&o(`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(q,{variant:Ci[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},String(n)))})]},String(n)))}),o(Di,{testId:`step-args`,items:t.args}),t.devices.length>0&&o(`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:[o(q,{variant:Ci[t.tone],children:n(t.deviceId)}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},t.deviceId))})]})}u();function Q({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function Ai(e){let t=Gn(e.deviceId);if(t.data!==void 0)return Zn(t.data,e.cap).find(t=>t.path===e.fieldPath)}function ji({value:t,devices:n,onChange:r}){let{t:i,i18n:a}=X(),[s,l]=c(!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===``?``:` · ${Mn(t.cap,t.fieldPath,a.language)}`}`;return e(`div`,{className:`min-w-[14rem] max-w-full flex-[2]`,children:[o(Q,{children:i(`automation.fieldPicker.value`,`Device value`)}),e(K,{variant:`outline`,className:`w-full min-w-0 justify-between`,"data-testid":`field-picker-open`,onClick:()=>l(!0),children:[o(`span`,{className:`w-0 flex-1 truncate text-left`,children:d}),o(We,{className:`size-3.5 shrink-0`})]}),s&&o(Mi,{value:t,onCancel:()=>l(!1),onConfirm:e=>{l(!1),r(e)}})]})}function Mi({value:t,onCancel:n,onConfirm:r}){let{t:i}=X(),a=Rt({projection:`slim`}),[s,l]=c(null),[u,d]=c(!1),[f,p]=c(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!u&&a.status===`success`&&(d(!0),l(jn(a.data).find(e=>e.id===t.deviceId)??null));let h=i(`automation.fieldPicker.title`,`Device value`);return o(yt,{open:!0,onClose:n,title:h,width:`xl`,fill:!0,testId:`field-picker-dialog`,footer:e(m,{children:[o(K,{variant:`ghost`,onClick:n,children:i(`common.cancel`,`Cancel`)}),o(K,{disabled:s===null||f===null,"data-testid":`field-picker-confirm`,onClick:()=>{s===null||f===null||r({deviceId:s.id,cap:f.cap,fieldPath:f.path})},children:i(`automation.fieldPicker.use`,`Use this value`)})]}),children:o(Pn,{kind:`formula`,intent:`value`,enabled:!0,fillHeight:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:h,pickerTargetKind:null},device:s,field:f,excludeTypes:Qn,onDeviceChange:l,onFieldChange:p})})}var Ni=1e4;function Pi(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 Fi(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function Ii({step:t,onChange:n}){let{t:r}=X(),i=Kt({},{refetchInterval:Ni});if(i.data===void 0)return o(nt,{className:`h-8 w-64`});let a=i.data.find(e=>e.id===t.actionId),s=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:[o(Q,{children:r(`automation.runAction.action`,`Action`)}),o(I,{value:t.actionId,onChange:e=>n({kind:`action`,actionId:e.target.value}),options:[{value:``,label:r(`automation.runAction.pick`,`Pick an action`)},...s?[{value:t.actionId,label:r(`automation.runAction.missing`,`Missing action ({{id}})`,{id:t.actionId})}]:[],...i.data.map(e=>({value:e.id,label:e.name}))]})]}),s&&o(`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&&o(`div`,{className:`flex flex-wrap items-end gap-3`,children:(a?.variables??[]).map(e=>o(Li,{variable:e,value:t.variables?.[e.name],onChange:r=>n(Fi(t,Pi(t.variables,e.name,r)))},e.name))})]})}function Li({variable:t,value:n,onChange:r}){let{t:i}=X(),a=t.label??t.name,s=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:[o(Q,{children:a}),o(Jn,{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:s},...c]})]})}return t.type===`number`?e(`label`,{className:`block`,children:[o(Q,{children:a}),o(er,{className:`w-40`,placeholder:s,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[o(Q,{children:a}),o(J,{className:`w-40`,placeholder:s,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}function Ri({onMove:e,label:t,reason:n,testId:r,children:i}){let a=e===null?n:t;return o(`span`,{className:`inline-flex`,title:a,"data-testid":`${r}-wrap`,children:o(K,{variant:`ghost`,disabled:e===null,onClick:e??void 0,"aria-label":t,title:a,"data-testid":r,children:i})})}function zi({move:t,texts:n}){let{t:r}=X(),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(m,{children:[o(Ri,{onMove:t.up,label:i.up,reason:i.atFirst,testId:`move-up`,children:o(L,{className:`h-3.5 w-3.5`})}),o(Ri,{onMove:t.down,label:i.down,reason:i.atLast,testId:`move-down`,children:o(M,{className:`h-3.5 w-3.5`})})]})}var Bi=[`command`,`action`,`wait`,`set`,`stop`],Vi=[`command`,`action`,`wait`];function Hi(e){return Wi(e)&&Vi.includes(e.kind)}var Ui={kind:`all`,children:[]};function Wi(e){return Bi.includes(e.kind)?!(`if`in e)&&!(`else`in e):!1}function Gi(){return{if:Ui,steps:[]}}function Ki(e){return e.branches.length<6}function qi(e){return Ki(e)?{...e,branches:[...e.branches,Gi()]}:e}function Ji(e){return e.branches.length>1}function Yi(e,t){return Ji(e)?{...e,branches:e.branches.filter((e,n)=>n!==t)}:e}function Xi(e,t,n){return{...e,branches:e.branches.map((e,r)=>r===t?n:e)}}function Zi(e,t){let{else:n,...r}=e;return t===void 0?r:{...r,else:[...t]}}var Qi=[...Bi,`wait-until`,`choose`,`parallel`,`repeat`];function $i(e){return e<2?Qi:Bi}function ea(e){if(Wi(e))return!0;switch(e.kind){case`wait-until`:case`parallel`:return!0;case`repeat`:return e.steps.every(Wi);case`choose`:return e.branches.every(e=>e.steps.every(Wi))&&(e.else??[]).every(Wi);default:return!1}}var ta=[`border-chart-series-a`,`border-chart-series-f`,`border-chart-series-b`,`border-chart-series-d`];function na(e,t){let n=ta.length;return(e+1+t%(n-1))%n}function ra(e,t){let n=0;return e.map(e=>R(e)?null:na(t,n++))}function ia(e){return ta[e%ta.length]??ta[0]}function aa(e){let t=[],n=0;return V(e,e=>{Ae(e)&&(n+=1,e.id!==void 0&&t.push({id:e.id,ordinal:n,leaf:e}))}),t}function oa(e){return ce(e.when)?!0:e.actions.some(e=>B(e).some(e=>ce(e.when)))}function sa(e){let t=1;for(;e.has(`t${t}`);)t+=1;return`t${t}`}function ca(e,t){if(R(e)){if(!Ae(e)||e.id!==void 0)return e;let n=sa(t);return t.add(n),{...e,id:n}}if(e.kind===`not`){let n=ca(e.child,t);return n===e.child?e:{...e,child:n}}let n=e.children.map(e=>ca(e,t));return n.every((t,n)=>t===e.children[n])?e:{...e,children:n}}function la(e){if(!oa(e))return e;let t=new Set(aa(e.when).map(e=>e.id)),n=ca(e.when,t);return n===e.when?e:{...e,when:n}}function ua(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 da(e,t){return e.leafIds.filter(e=>!t.includes(e))}u();var fa=[],pa=d(null);function ma({when:e,children:t}){let n=r(()=>aa(e),[e]);return o(pa.Provider,{value:n,children:t})}function ha(){return h(pa)??fa}function ga(){return h(pa)!==null}var _a=[`triggered-by`];function va(e){return{label:pi(e),description:mi(e),example:hi(e)}}function ya({open:e,onOpenChange:t,mode:n,context:r,underNot:i,treeFull:a,current:s,onPick:c}){let{t:l}=X(),u=ga();return o(Ft,{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`&&s!==void 0?{current:s}:{},...u?{}:{hidden:_a},recentKey:`automation-${r}`,textsOf:va,categoryLabelOf:e=>l(`automation.leafPicker.category.${e}`),reasonOf:e=>l(`automation.leafPicker.reason.${e}`),onPick:e=>{c(e),t(!1)}})}var ba=`none`;function xa(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<=0))return Math.round(t*1e3)}function Sa({hold:t,modes:n,onChange:r}){let{t:i}=X(),a={held:i(`automation.hold.held`,`held`),stable:i(`automation.hold.stable`,`stable`)},s=e=>{if(e===ba){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(m,{children:[e(`label`,{className:`w-32`,children:[o(Q,{children:i(`automation.hold.label`,`For`)}),o(I,{value:t?.mode??ba,onChange:e=>s(e.target.value),options:[{value:ba,label:i(`automation.hold.none`,`no hold`)},...n.map(e=>({value:e,label:a[e]}))]})]}),t!==void 0&&e(`label`,{className:`w-24`,children:[o(Q,{children:i(`automation.hold.seconds`,`Seconds`)}),o(J,{type:`number`,min:1,value:String(t.ms/1e3),onChange:e=>{let n=xa(e.target.value);r(n===void 0?void 0:{...t,ms:n})}})]}),t?.mode===`stable`&&e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.hold.tolerance`,`± tolerance`)}),o(J,{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 Ca({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=X(),c=Aa(n,r,i);if(n?.kind===`boolean`)return o(I,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:s(`common.true`)},{value:`false`,label:s(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return o(I,{value:String(t),onChange:e=>a(e.target.value),options:n.enumValues.map(e=>({value:e,label:e}))});if(n?.kind===`number`){let n=typeof t==`number`&&c?c.toDisplayValue(t):t;return e(`span`,{className:`inline-flex items-center gap-1`,children:[o(J,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?o(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return o(J,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function wa({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=X(),s=Aa(t,n,r);return o(J,{value:(s?e.map(e=>typeof e==`number`?s.toDisplayValue(e):e):e).join(`, `),placeholder:a(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let n=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);i(t?.kind===`number`?n.map(e=>Number(e)).filter(e=>!Number.isNaN(e)).map(e=>s?s.fromDisplayValue(e):e):n)}})}function Ta(e){return typeof e==`object`&&!U(e)}function Ea(e){return U(e)?e.value:Ta(e)?e[0]??``:e}function Da(e){return U(e)?[e.value]:Ta(e)?e:typeof e==`boolean`?[]:[e]}function Oa(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!Me(t)||t===`none`||t===`device`))return je(t).length>0?t:void 0}function ka(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Aa(e,t,n){let r=lt(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=an({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=Me(s)?s:void 0,l=ka(e?.quantity,c);if(l===void 0)return;let u=o?.display;return kt({quantity:l,display:u,capName:n,unitPreferences:r})}function ja({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Ai(a),c=fi(s?.kind),l=t.operator===`in`,u=Oa(s),d=u===void 0?void 0:xe(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=Ma(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...Da(t.value)]:Ea(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(ji,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[o(Q,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(I,{value:t.operator,onChange:e=>p(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(wa,{value:Da(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?o(St,{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=fn(e,d);r({...t,value:n.value,unit:n.unit})}}):o(Ca,{value:Ea(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]}),o(Sa,{hold:t.for,modes:[`held`,`stable`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})]})}function Ma(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Na=Object.values(Te).sort((e,t)=>e.localeCompare(t));function Pa({leaf:t,onChange:n}){let{t:r}=X();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(J,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>n({kind:`schedule`,cron:e.target.value})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]})}function Fa(){return o(`p`,{className:`text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})}function Ia(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 La(e){return e.operator===void 0?e.becomes===void 0?`any`:`becomes`:e.operator}var Ra=[`any`,`becomes`,`gt`,`gte`,`lt`,`lte`,`between`,`outside`];function za(e){return e===`between`||e===`outside`}function Ba(e){if(e.trim()===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function Va(e){return typeof e==`number`?e:void 0}function Ha({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Ai(a),c=le(t),l=La(t),u=Va(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:h,value:g,..._}=f,v=e=>{if(e===`any`){r(Ia(a,_));return}if(e===`becomes`){r(Ia(a,{..._,becomes:``}));return}let t=se.safeParse(e);t.success&&r(Ia(a,{..._,operator:t.data,value:za(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(m,{children:[o(ji,{value:a,devices:n,onChange:e=>r(Ia(e,f))}),e(`label`,{className:`min-w-[10rem]`,children:[o(Q,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),o(I,{value:l,onChange:e=>v(e.target.value),options:Ra.map(e=>({value:e,label:y[e]}))})]}),l===`becomes`&&t.becomes!==void 0&&e(`div`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),o(Ca,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(Ia(a,{...f,becomes:e}))})]}),t.operator!==void 0&&!za(l)&&e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),o(J,{type:`number`,step:`any`,value:u===void 0?``:String(u),onChange:e=>{let n=Ba(e.target.value);n!==void 0&&r(Ia(a,{...f,operator:t.operator,value:n}))}})]}),t.operator!==void 0&&za(l)&&[0,1].map(n=>e(`label`,{className:`w-24`,children:[o(Q,{children:n===0?i(`automation.triggerEditor.rangeFrom`,`From`):i(`automation.triggerEditor.rangeTo`,`To`)}),o(J,{type:`number`,step:`any`,value:d[n]===void 0?``:String(d[n]),onChange:e=>{let i=Ba(e.target.value);if(i===void 0)return;let o=[d[0]??0,d[1]??0];o[n]=i,r(Ia(a,{...f,operator:t.operator,value:o}))}})]},n)),o(Sa,{hold:c,modes:[`held`,`stable`],onChange:e=>{let{hold:t,...n}=f;r(Ia(a,e===void 0?n:{...n,hold:e}))}}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(J,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(Ia(a,{...f,debounceMs:Ua(e.target.value)}))})]})]})}function Ua(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function Wa({leaf:t,onChange:n}){let{t:r}=X();return e(m,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.eventCategory`,`Event category`)}),o(I,{value:t.category,onChange:e=>n({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:r(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...Na.map(e=>({value:e,label:e}))]})]}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.fromDevice`,`From device`)}),o(Vt,{pick:`device`,excludeTypes:Qn,recentKey:`build-targets`,value:t.deviceId===void 0?null:{deviceId:t.deviceId},placeholder:r(`automation.triggerEditor.anyDevice`,`Any device`),testId:`trigger-event-device`,onChange:e=>n({kind:`device-event`,category:t.category,...e===null?{}:{deviceId:e.deviceId}})})]})]})}function Ga(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 Ka(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 qa={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Ja({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=Object.entries(t.bindings),s=e=>{r({...t,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`block`,children:[o(Jt,{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})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.mustEvaluateToTrueOr`,`Must evaluate to true or false. Every name in it has to be bound below — an unbound name is refused when the automation is saved, not when it runs.`)})]}),e(`div`,{className:`space-y-1.5`,children:[a.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),a.map(([e,r])=>o(Ya,{alias:e,source:r,devices:n,onRename:n=>s(Qa(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s($a(t.bindings,e))},e)),e(K,{variant:`ghost`,onClick:()=>s({...t.bindings,[Za(t.bindings)]:qa}),children:[o(j,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]}),o(`div`,{className:`flex flex-wrap items-end gap-2`,children:o(Sa,{hold:t.for,modes:[`held`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})})]})}function Ya({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=X(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:n.kind===`global`?Ka(r,n):0,cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[o(Q,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(J,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Q,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(I,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:qa),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(J,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Xa(e.target.value)})})]}):o(ji,{value:u,devices:r,onChange:e=>a(Ga(r,e))}),o(K,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(g,{className:`h-3.5 w-3.5`})})]})}function Xa(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Za(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 Qa(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function $a(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var eo=`event-emitter`;function to(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`};let t=Se.safeParse(e.data);return t.success?{kind:`known`,vocabulary:de(t.data)}:{kind:`unknown`}}function no(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 ro(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 io(e,t){return{kind:`device-fired`,...e.id===void 0?{}:{id:e.id},deviceId:t}}function ao(e,t,n){let{sourceIds:r,eventIds:i,...a}=e,o=new Set(ro(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 oo(e,t){let{eventIds:n,...r}=e;return{...r,...t===void 0?{}:{eventIds:[t]}}}function so(e,t){let n=new Set(no(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 co=``,lo={caps:[eo]};function uo({leaf:t,onChange:n}){let{t:r}=X(),i=t.deviceId>0,a=ft({deviceId:t.deviceId,capName:eo},{enabled:i}),s=to({status:a.status,data:a.data}),c=s.kind===`known`?s.vocabulary:[],l=no(c),u=t.sourceIds?.[0],d=t.eventIds?.[0],f=ro(c,u),p=s.kind===`known`?so(t,c):null,h=r(`automation.fired.anyEvent`,`Any event`),g=s.kind===`pending`?r(`automation.fired.loading`,`Reading what this device can fire…`):r(`automation.fired.unknown`,`What this device can fire could not be read.`);return e(m,{children:[e(`div`,{className:`min-w-[13rem] flex-1`,children:[o(Q,{children:r(`automation.fired.device`,`Device`)}),o(Vt,{pick:`device`,requires:lo,recentKey:`automation-device-fired`,value:i?{deviceId:t.deviceId}:null,onChange:e=>n(io(t,e?.deviceId??0))})]}),i&&s.kind!==`known`&&o(`p`,{className:`min-w-[13rem] flex-1 text-xs ${s.kind===`unknown`?`text-warning`:`text-foreground-subtle`}`,"data-testid":`fired-vocabulary-${s.kind}`,children:g}),i&&s.kind===`known`&&l.length>0&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:r(`automation.fired.source`,`From`)}),o(I,{"data-testid":`fired-source`,value:u??co,onChange:e=>n(ao(t,e.target.value===co?void 0:e.target.value,c)),options:[{value:co,label:r(`automation.fired.anySource`,`Any button`)},...l.map(e=>({value:e.id,label:e.label})),...(p?.sourceIds??[]).map(e=>({value:e,label:r(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),i&&s.kind===`known`&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:r(`automation.fired.event`,`Event`)}),o(I,{"data-testid":`fired-event`,value:d??co,onChange:e=>n(oo(t,e.target.value===co?void 0:e.target.value)),options:[{value:co,label:h},...f.map(e=>({value:e.id,label:e.label})),...(p?.eventIds??[]).map(e=>({value:e,label:r(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),p!==null&&p.sourceIds.length+p.eventIds.length>0&&o(`p`,{className:`basis-full text-xs text-warning`,"data-testid":`fired-stale`,children:r(`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)&&o(`p`,{className:`basis-full text-xs text-foreground-subtle`,"data-testid":`fired-extra`,children:r(`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 fo=`text-xs text-foreground-subtle`;function po({children:e}){return o(`span`,{className:fo,children:e})}function mo(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function ho({selected:t,onChange:n}){let{t:r}=X();return e(`div`,{className:`space-y-1`,children:[o(po,{children:r(`flow.scene.cameras`,`Cameras`)}),o(Vt,{multiple:!0,pick:`device`,noun:`camera`,fixedTypes:Kn,recentKey:`build-cameras`,value:mt(t),testId:`scene-cameras`,onChange:e=>n(Qt(e))})]})}function go({device:t,deviceId:n,selected:r,onToggle:i}){let a=Ct({deviceId:n});return a.data===void 0||a.data.length===0?null:e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:fo,children:t?.name??`#${String(n)}`}),a.data.map(e=>o(K,{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 _o({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=X();if(n.length===0)return null;let s=e=>{let t=mo(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(po,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(go,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:fo,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var vo=[`animal`,`person`,`vehicle`,`package`,`other`];function yo(e){return vo.find(t=>t===e)??`other`}function bo(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 xo(){let{t:e}=X();return t=>{switch(t){case`person`:return e(`flow.class.person`,`Person`);case`vehicle`:return e(`flow.class.vehicle`,`Vehicle`);case`animal`:return e(`flow.class.animal`,`Animal`);case`package`:return e(`flow.class.package`,`Package`);default:return e(`automation.whenTree.macroOther`,`Other class`)}}}function So(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 Co=[`automation`,`class-taxonomy`];function wo(){let e=k();return ge(l({queryKey:Co,retry:!1,staleTime:1/0,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}).data?.taxonomy)}function To(e,t,n){let r=n?.groups.find(t=>t.key===e),i=r===void 0?ee(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 Eo({subject:e,onChange:t}){let{t:n}=X(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=wo(),a=To(e.macro,r,i);return a.length===0?null:o(I,{"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===``?bo(e.macro):So(e.macro,r))}})}function Do({onChange:e,subject:t}){let{t:n}=X(),r=Zt(),i=t.macro===`person`?t.label:void 0,a=r.data??[],s=a.map(e=>({value:e.id,label:e.name}));return i!==void 0&&!a.some(e=>e.id===i.identityId)&&s.push({value:i.identityId,label:i.name}),o(I,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:i?.identityId??``,options:[{value:``,label:n(`automation.whenTree.anyPerson`,`Anyone`)},...s],onChange:t=>{let n=t.target.value,r=s.find(e=>e.value===n);e(n===``||r===void 0?{macro:`person`}:{macro:`person`,label:{kind:`identity`,identityId:n,name:r.label}})}})}var Oo=`plate:`,ko=`class:`,Ao=200;function jo({onChange:e,subject:t}){let{t:n}=X(),r=xt({includeCrops:!1,limit:Ao}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,s=wo(),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?``:`${ko}${c}`:`${Oo}${a}`;return o(I,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:u,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...To(`vehicle`,c,s).map(e=>({value:`${ko}${e.value}`,label:e.label})),...l.map(e=>({value:`${Oo}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(Oo)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(ko)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function Mo({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:s}=X(),c=xo(),l=t.macro===`other`?[]:Ue[t.macro],u=l.some(e=>e.kind===`cap`&&e.label===`identity`),d=l.some(e=>e.kind===`cap`&&e.label===`plate`);return e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`subject-row`,children:[o(`div`,{className:`w-36`,children:o(I,{"aria-label":s(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:vo.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=yo(e.target.value);n!==t.macro&&i(bo(n))}})}),o(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?o(J,{className:`w-40`,"aria-label":s(`automation.whenTree.className`,`Class name`),"data-testid":`subject-class-name`,placeholder:s(`automation.whenTree.classNamePlaceholder`,`Class name`),value:t.className,onChange:e=>i({macro:`other`,className:e.target.value})}):u&&!n?o(`div`,{className:`w-44`,children:o(Do,{subject:t,onChange:i})}):d&&!n?o(`div`,{className:`w-44`,children:o(jo,{subject:t,onChange:i})}):!u&&o(`div`,{className:`w-44`,children:o(Eo,{subject:t,onChange:i})}),a!==null&&o(K,{variant:`ghost`,onClick:a,title:s(`automation.whenTree.removeClass`,`Remove this class`),children:o(g,{className:`h-3.5 w-3.5`})})]})}function No({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:s}=X(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>o(Mo,{subject:e,classLabelsOnly:r,verb:n===0?i:s(`automation.whenTree.orSubject`,`or`),onChange:e=>a(t.map((t,r)=>r===n?e:t)),onRemove:c?()=>a(t.filter((e,t)=>t!==n)):null},`${e.macro}-${String(n)}`)),t.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:s(`flow.scene.anyClass`,`None picked: any class counts.`)}),e(K,{variant:`ghost`,size:`sm`,onClick:()=>a([...t,bo(`person`)]),children:[o(j,{className:`h-3.5 w-3.5`}),` `,t.length===0?s(`automation.whenTree.onlySomeClasses`,`Only some classes`):s(`automation.whenTree.addClass`,`Add a class`)]})]})}var Po=100;function Fo({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=Math.round((t.minScore??0)*Po),s=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{minScore:n,...i}=t;r(e<=0?i:{...i,minScore:e/Po})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(No,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),o(ho,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(_o,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(po,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/Po).toFixed(2)})}),o(w,{min:0,max:Po,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 Io({leaf:t,devices:n,onChange:r}){let{t:i}=X();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(No,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.parked`,`object`),onChange:e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})}}),o(ho,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(_o,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(st,{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 Lo({leaf:t,onChange:n}){let{t:r}=X();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(po,{children:r(`flow.scene.every`,`Every`)}),o(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)})}}),o(po,{children:r(`flow.scene.minutes`,`minutes`)})]})}function Ro({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},s=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:[o(po,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(Vt,{pick:`device`,noun:`camera`,fixedTypes:Kn,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)}})]}),o(No,{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:[o(po,{children:i(`flow.scene.minCount`,`At least`)}),o(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)})}}),o(po,{children:i(`flow.scene.minCountUnit`,`parked objects`)})]}),o(_o,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:s})]})}var zo=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],Bo=720,Vo=1440;function Ho(){return{name:``,enabled:!0,priority:0,maxLateMs:De,profiles:[Uo(`profile-1`,`Every day`)]}}function Uo(e,t){return{id:e,name:t,enabled:!0,days:[...zo],points:[]}}function Wo(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function Go(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function Ko(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function qo(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 Jo(e,t=Date.now()){return re(t,e.timeZone)}function Yo(e,t,n){let r=Ko(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=ie(e,n,r);return i===null?null:qo(i,t.timeZone)}function Xo(e,t,n){return e.kind===`sun`?Yo({...e,offsetMin:0},t,n):null}function Zo(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(Bo,t-n));return{...e,offsetMin:r}}return e}function Qo(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 $o(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function es(e){return $o(Math.floor(e/60),e%60)}function ts(e,t,n){let r=e.flatMap(e=>{let r=Yo(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?Vo:n.minute}]})}function ns(e,t){let n=Ee.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=_e(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}var rs=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],is=[`sunrise`,`sunset`,`dawn`,`dusk`],as={from:{kind:`clock`,hh:22,mm:0},to:{kind:`clock`,hh:6,mm:0}};function os(e,t){return{kind:`time-is`,...e===void 0?{}:{between:e},...t===void 0?{}:{days:[...t]}}}function ss(e){return e.days??rs}function cs(e,t){let n=ss(e),r=n.includes(t)?n.filter(e=>e!==t):rs.filter(e=>e===t||n.includes(e)),i=r.length===rs.length;return os(e.between,i&&e.between!==void 0?void 0:r)}function ls(e,t){if(t){let t=e.days!==void 0&&e.days.length===rs.length;return os(e.between??as,t?void 0:e.days)}return os(void 0,ss(e))}function us(e,t,n){return os({...e.between??as,[t]:n},e.days)}function ds(e){return e===`sun`?{kind:`sun`,event:`sunset`,offsetMin:0}:{kind:`clock`,hh:12,mm:0}}function fs(e){return e.kind===`date`?ds(`clock`):e}function ps(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 ms(e,t){if(t===void 0)return null;let n=Re(e,t)[0];return n===void 0?null:`${n.path}: ${n.message}`}function hs({label:t,testId:n,end:r,onChange:i}){let{t:a}=X(),s=e=>`${t}: ${e}`;return e(`div`,{role:`group`,"aria-label":t,"data-testid":n,children:[o(Q,{children:t}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(I,{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(ds(t))}}),r.kind===`clock`&&o(J,{type:`time`,className:`w-28`,"aria-label":s(a(`schedulers.point.time`,`Time`)),value:$o(r.hh,r.mm),onChange:e=>{let t=Qo(e.target.value);t!==null&&t.kind===`clock`&&i(t)}}),r.kind===`sun`&&e(m,{children:[o(I,{wrapperClassName:`relative w-40`,"aria-label":s(a(`schedulers.point.sunEvent`,`Sun event`)),value:r.event,options:is.map(e=>({value:e,label:a(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=is.find(t=>t===e.target.value);t!==void 0&&i({...r,event:t})}}),o(er,{"aria-label":s(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 gs({leaf:t,onChange:n}){let{t:r}=X(),i=t.between,a=ss(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:[o(Q,{children:r(`automation.timeIs.window`,`Time of day`)}),o(I,{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(ls(t,e.target.value===`between`))})]}),i!==void 0&&e(m,{children:[o(hs,{label:r(`automation.timeIs.from`,`From`),testId:`time-is-from`,end:fs(i.from),onChange:e=>n(us(t,`from`,e))}),o(hs,{label:r(`automation.timeIs.to`,`To`),testId:`time-is-to`,end:fs(i.to),onChange:e=>n(us(t,`to`,e))})]})]}),e(`div`,{children:[o(Q,{children:r(`schedulers.profile.days`,`Days`)}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":r(`schedulers.profile.days`,`Days`),children:rs.map(e=>{let i=a.includes(e);return o(K,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,onClick:()=>n(cs(t,e)),children:r(`schedulers.day.${e}`,e)},e)})}),a.length===0&&o(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`time-is-no-days`,children:r(`automation.timeIs.noDays`,`Pick at least one day.`)}),ps(t)&&o(`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 _s(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 vs({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=ha(),s=a.map(e=>e.id),c=da(t,s),l=i(`automation.triggeredBy.triggers`,`Started by`);return e(`div`,{children:[o(Q,{children:l}),a.length===0?o(`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.`)}):o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":l,children:a.map(e=>{let i=t.leafIds.includes(e.id),a=_s(e,n);return o(K,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,className:`h-auto min-h-8 whitespace-normal py-1 text-left`,onClick:()=>r(ua(t,e.id,s)),children:`${e.ordinal}. ${pi(e.leaf.kind)}${a===void 0?``:` · ${a}`}`},e.id)})}),a.length>0&&t.leafIds.length===0&&o(`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&&o(`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 ys(e){return e.kind===`all`||e.kind===`any`}function bs(e){return[`when`,...e].join(`.`)}function xs(e){let t=e.when;return ys(t)?t:{kind:`all`,children:[t]}}function Ss(e,t){return{...e,when:t}}function Cs(e){return Ss(e,xs(e))}function ws(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?ws(e.child,r):null;if(R(e))return null;let i=e.children[n];return i===void 0?null:ws(i,r)}function Ts(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=Ts(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(R(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Ts(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 Es(e,t,n){let r=xs(e);return Ss(e,Ts(r,t,n)??{kind:r.kind,children:[]})}function Ds(e){return{kind:e,children:[_i(`device-is`)]}}function Os(e,t,n){return Es(e,t,e=>ys(e)?{kind:e.kind,children:[...e.children,n]}:e)}function ks(e,t,n){return Es(e,t,()=>n)}function As(e,t){return Es(e,t,()=>null)}function js(e,t,n){return Es(e,t,e=>ys(e)?{kind:n,children:e.children}:e)}function Ms(e,t){return t.length===0?e:Es(e,t,e=>({kind:`not`,child:e}))}function Ns(e,t){return Es(e,t,e=>e.kind===`not`?e.child:e)}function Ps(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=_i(t);return Ae(e)&&e.id!==void 0&&Ae(n)?{...n,id:e.id}:n}function Fs(e){let t=xs(e),n=t.children.length===0;return{depth:n?0:oe(t),leaves:n?0:H(t),depthLimit:4,leafLimit:32}}function Is(e,t){let n=xs(e),r=1,i=n;for(let e of t){let t=ws(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function Ls(e,t,n){let r=t[t.length-1];if(r===void 0)return e;let i=t.slice(0,-1),a=ws(xs(e),i);if(a===null||!ys(a))return e;let o=r+n;return o<0||o>=a.children.length?e:Es(e,i,()=>({kind:a.kind,children:bi(a.children,r,o)}))}function Rs(e,t,n){let r=bs(t),i=bs(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 zs(e,t){return R(e)?t(e.kind):e.kind===`not`?`NOT ${zs(e.child,t)}`:e.children.map(e=>Bs(e,t)).join(` · `)}function Bs(e,t){return ys(e)?`${e.kind.toUpperCase()} (${zs(e,t)})`:zs(e,t)}u();function Vs({leaf:t,devices:n,context:r,underNot:i,toneClass:a,result:s,onNegate:l,move:u,onChange:d,onRemove:f}){let{t:p}=X(),[m,h]=c(!1),_=Ae(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:[o(Q,{children:p(`automation.whenTree.rowType`,`Row type`)}),e(K,{variant:`outline`,"data-testid":`when-row-type`,className:`w-full justify-between`,onClick:()=>h(!0),title:p(`automation.leafPicker.changeType`,`Change type`),children:[o(`span`,{className:`truncate`,children:pi(t.kind)}),o(`span`,{className:`text-foreground-subtle`,children:p(`automation.leafPicker.changeType`,`Change type`)})]}),o(ya,{open:m,onOpenChange:h,mode:`change`,context:r,underNot:i,treeFull:!1,current:t.kind,onPick:e=>{e!==t.kind&&d(Ps(t,e))}})]}),o(q,{variant:_?`info`:`neutral`,"data-testid":`when-row-nature`,children:_?p(`automation.whenTree.natureEvent`,`Event`):p(`automation.whenTree.natureState`,`State`)}),o(`span`,{className:`flex-1`}),u!==void 0&&o(zi,{move:u}),l!==null&&o(K,{variant:`ghost`,onClick:l,title:p(`automation.whenTree.negateRow`,`Invert this row (NOT)`),children:`NOT`}),o(K,{variant:`ghost`,onClick:f,title:p(`automation.whenTree.removeRow`,`Remove this row`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:o(Hs,{leaf:t,devices:n,onChange:d})}),s!==void 0&&o(`div`,{className:`mt-2`,children:s})]})}function Hs({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return o(Ha,{leaf:e,devices:t,onChange:n});case`device-event`:return o(Wa,{leaf:e,onChange:n});case`device-fired`:return o(uo,{leaf:e,onChange:n});case`schedule`:return o(Pa,{leaf:e,onChange:n});case`interval`:return o(Lo,{leaf:e,onChange:n});case`manual`:return o(Fa,{});case`detection`:return o(Fo,{leaf:e,devices:t,onChange:n});case`stationary`:return o(Io,{leaf:e,devices:t,onChange:n});case`device-is`:return o(ja,{leaf:e,devices:t,onChange:n});case`stationary-present`:return o(Ro,{leaf:e,devices:t,onChange:n});case`expression`:return o(Ja,{leaf:e,devices:t,onChange:n});case`time-is`:return o(gs,{leaf:e,onChange:n});case`triggered-by`:return o(vs,{leaf:e,devices:t,onChange:n})}}u();function Us(e){return e===`any`?`any`:`all`}function Ws(e){return e===`pass`?`pass`:e===`fail`?`fail`:`idle`}function Gs(e,t,n=!0){return e===void 0?t:n?Hr(Ws(e)):Wr(Ws(e))}function Ks(e,t){return e.run?.nodes.get(bs(t))}function qs({recipe:t,devices:n,onChange:r,run:i=null,hideRule:a=!1,context:s=`trigger`}){let{t:l}=X(),u=xs(t),d=Fs(t),[f,p]=c(()=>new Set),m={leafContext:s,recipe:t,devices:n,run:i,onChange:r,reshape:e=>{p(new Set),r(e)},collapsed:f,toggleCollapsed:e=>{let t=bs(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=>Rs(t,e,a)),r(Ls(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&&o(`p`,{className:`text-xs text-foreground-subtle`,children:l(`automation.whenTree.rule`,`An event starts a run when it happens and everything here is true at that moment. With only states, a run starts when they become true.`)}),o(nc,{block:u,path:[],ctx:m,underNot:!1,rail:0,budgetText:l(`automation.whenTree.budget`,{depth:d.depth,depthLimit:d.depthLimit,leaves:d.leaves,leafLimit:d.leafLimit}),move:null,emptyHint:h&&!a?l(`automation.whenTree.empty`,`Add a row to say when this runs. Without one nothing can ever start this automation.`):null})]})}function Js({node:e,path:t,ctx:n,underNot:r,move:i,rail:a}){return R(e)?o(Ys,{leaf:e,path:t,ctx:n,underNot:r,move:i}):e.kind===`not`?o(tc,{child:e.child,path:t,ctx:n,move:i,rail:a}):o(nc,{block:e,path:t,ctx:n,underNot:r,move:i,rail:a,budgetText:null,emptyHint:null})}function Ys({leaf:e,path:t,ctx:n,underNot:r,move:i}){let a=Ks(n,t),s=n.run!==null&&n.run.triggerPath===bs(t)?n.run.vars:void 0;return o(Vs,{leaf:e,devices:n.devices,context:n.leafContext,underNot:r,toneClass:Gs(a?.outcome,`border-border`),result:a===void 0?void 0:o(Xs,{leaf:e,node:a,vars:s}),onNegate:r?null:()=>n.reshape(Ms(n.recipe,t)),...i===null?{}:{move:i},onChange:e=>n.onChange(ks(n.recipe,t,e)),onRemove:()=>n.reshape(As(n.recipe,t))})}function Xs({leaf:e,node:t,vars:n}){return e.kind===`device-is`&&e.unit!==void 0?o(Zs,{leaf:e,node:t,vars:n}):o(Oi,{node:t,vars:n,expected:t.expected,observed:t.observed})}function Zs({leaf:e,node:t,vars:n}){let r=Oa(Ai({deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})),i=r===void 0?void 0:xe(r),a=t=>t===void 0?null:kr(t,i,e.unit);return o(Oi,{node:t,vars:n,expected:a(t.rawExpected),observed:a(t.rawObserved)})}function Qs({node:e}){return e===void 0?null:o(Oi,{node:e,expected:null,observed:null})}function $s({expanded:e,onToggle:t}){let{t:n}=X(),r=e?n(`automation.whenTree.collapse`,`Collapse this block`):n(`automation.whenTree.expand`,`Expand this block`);return o(K,{variant:`ghost`,"aria-expanded":e,"aria-label":r,title:r,onClick:t,children:o(bt,{expanded:e})})}function ec({node:e}){let{t}=X(),n=`${t(`automation.whenTree.rowCount`,{count:H(e)})} · ${zs(e,pi)}`;return o(`p`,{"data-testid":`when-block-summary`,title:n,className:`break-words text-xs text-foreground-muted sm:truncate`,children:n})}function tc({child:t,path:n,ctx:r,move:i,rail:a}){let{t:s}=X(),c=!r.collapsed.has(bs(n));return e(`div`,{className:`space-y-1.5 rounded border p-2 ${Gs(Ks(r,n)?.outcome,`border-warning/40`,!1)}`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o($s,{expanded:c,onToggle:()=>r.toggleCollapsed(n)}),o(q,{variant:`warning`,children:`NOT`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.whenTree.notHint`,`True when what is below is not`)}),o(`span`,{className:`flex-1`}),i!==null&&o(zi,{move:i}),e(K,{variant:`ghost`,onClick:()=>r.reshape(Ns(r.recipe,n)),title:s(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[o(qe,{className:`h-3.5 w-3.5`}),` `,s(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),o(Qs,{node:Ks(r,n)}),c?o(`div`,{className:`pl-3`,children:o(Js,{node:t,path:[...n,0],ctx:r,underNot:!0,move:null,rail:a})}):o(ec,{node:t})]})}function nc({block:t,path:n,ctx:r,underNot:i,move:a,rail:s,budgetText:l,emptyHint:u}){let{t:d}=X(),f=n.length===0,p=f||!r.collapsed.has(bs(n)),m=Is(r.recipe,n),[h,_]=c(!1),v=ra(t.children,s),y=[{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 ${Gs(Ks(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&&o($s,{expanded:p,onToggle:()=>r.toggleCollapsed(n)}),o(`div`,{className:`w-40`,children:o(I,{"aria-label":d(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:y,onChange:e=>r.onChange(js(r.recipe,n,Us(e.target.value)))})}),l!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:l}),o(`span`,{className:`flex-1`}),a!==null&&o(zi,{move:a}),!f&&!i&&o(K,{variant:`ghost`,onClick:()=>r.reshape(Ms(r.recipe,n)),title:d(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!f&&o(K,{variant:`ghost`,onClick:()=>r.reshape(As(r.recipe,n)),title:d(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(Qs,{node:Ks(r,n)}),u!==null&&o(`p`,{className:`text-xs text-foreground-subtle`,children:u}),!p&&o(ec,{node:t}),p&&t.children.length>0&&o(`div`,{className:`space-y-1.5 border-l-2 pl-3 ${ia(s)}`,"data-testid":`when-block-rail`,"data-rail":s,children:t.children.map((e,i)=>o(Js,{node:e,path:[...n,i],ctx:r,underNot:!1,move:r.moveControls([...n,i],t.children.length),rail:v[i]??s},bs([...n,i])))}),p&&e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:`outline`,onClick:()=>_(!0),title:d(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[o(j,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addRow`,`Add row`)]}),o(ya,{open:h,onOpenChange:_,mode:`add`,context:r.leafContext,underNot:i,treeFull:H(xs(r.recipe))>=32,onPick:e=>r.onChange(Os(r.recipe,n,_i(e)))}),e(K,{variant:`outline`,disabled:!m,onClick:()=>r.onChange(Os(r.recipe,n,Ds(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:Fs(r.recipe).depthLimit}),children:[o(j,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addBlock`,`Add block`)]})]})]})}var rc={kind:`all`,children:[]};function ic(e){return e.kind===`wait`||e.kind===`command`}function ac(e){return!R(e)&&e.kind!==`not`&&e.children.length===0?null:Oe(e)}function oc(e){let{if:t,else:n,...r}=e;return r}function sc({when:t,devices:n,hint:r,onChange:i,children:a}){let{t:s}=X(),c=t===void 0?null:{when:t,actions:[]},l=t===void 0?null:ac(t);return e(`div`,{className:`space-y-2 border-t border-border-subtle pt-2`,children:[o(dt,{checked:t!==void 0,label:s(`automation.stepGuard.if`,`Only if…`),"aria-label":s(`automation.stepGuard.if`,`Only if…`),onCheckedChange:e=>i(e?rc:void 0)}),c!==null&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:r}),o(qs,{hideRule:!0,context:`guard`,recipe:c,devices:n,onChange:e=>i(e.when)}),l!==null&&o(G,{variant:`warning`,message:l}),a]})]})}function cc({step:t,devices:n,devicesState:r,variables:i,onChange:a}){let{t:s}=X();return e(sc,{when:t.if,devices:n,hint:s(`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?oc(t):{...t,if:e}),children:[o(dt,{checked:t.else!==void 0,label:s(`automation.stepGuard.else`,`Otherwise, run…`),"aria-label":s(`automation.stepGuard.else`,`Otherwise, run…`),onCheckedChange:e=>{if(e)a({...t,else:[]});else{let{else:e,...n}=t;a(n)}}}),t.else!==void 0&&o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(Cc,{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(ic)})})})]})}function lc({index:t,step:n,devices:r,devicesState:i,variables:a,depth:s=0,roundDevices:c,onChange:l}){let{t:u}=X(),d={nested:!0,flowControl:!0,devices:r,depth:s+1,allowedKinds:$i(s+1),...c===void 0?{}:{roundDevices:c},...i===void 0?{}:{devicesState:i},...a===void 0?{}:{variables:a}};return e(`div`,{className:`space-y-3`,children:[o(`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 s={when:i.if,actions:[]},c=ac(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:[o(Q,{children:a===0?u(`automation.choose.if`,`If`):u(`automation.choose.elseIf`,`Otherwise, if`)}),o(K,{variant:`ghost`,className:`ml-auto`,disabled:!Ji(n),"data-testid":`choose-remove-${String(t)}-${String(a)}`,onClick:()=>l(Yi(n,a)),title:Ji(n)?u(`automation.choose.removeBranch`,`Remove this branch`):u(`automation.choose.lastBranch`,`A choose keeps at least one branch`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(qs,{hideRule:!0,context:`guard`,recipe:s,devices:r,onChange:e=>l(Xi(n,a,{...i,if:e.when}))}),c!==null&&o(G,{variant:`warning`,message:c}),o(Q,{children:u(`automation.choose.then`,`Then run`)}),o(Cc,{...d,actions:i.steps,onChange:e=>l(Xi(n,a,{...i,steps:e.filter(ea)}))})]},String(a))}),e(K,{variant:`outline`,"data-testid":`choose-add-${String(t)}`,disabled:!Ki(n),onClick:()=>l(qi(n)),title:Ki(n)?void 0:u(`automation.choose.maxBranches`,`A choose takes at most 6 branches`),children:[o(j,{className:`h-4 w-4`}),` `,u(`automation.choose.addBranch`,`Add a branch`)]}),o(dt,{"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(Zi(n,e?[]:void 0))}),n.else!==void 0&&o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(Cc,{...d,actions:n.else,onChange:e=>l(Zi(n,e.filter(ea)))})})]})}function uc(e){return Object.entries(e).map(([e,t])=>({name:e,value:t}))}function dc(e){return Object.fromEntries(e.map(e=>[e.name,e.value]))}function fc(e,t,n){let r=uc(e);return r.some((e,r)=>r!==t&&e.name===n)?e:dc(r.map((e,r)=>r===t?{...e,name:n}:e))}function pc(e,t,n){return dc(uc(e).map((e,r)=>r===t?{...e,value:n}:e))}function mc(e){return!Object.keys(e).includes(``)}function hc(e){return mc(e)?{...e,"":``}:e}function gc(e,t){return dc(uc(e).filter((e,n)=>n!==t))}var _c=`{{vars.name}}`;function vc({index:t,vars:n,onChange:r}){let{t:i}=X();return e(`div`,{className:`space-y-2`,children:[uc(n).map((a,s)=>e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-40`,children:[o(Q,{children:i(`automation.actionList.setName`,`Variable`)}),o(J,{"data-testid":`set-name-${String(t)}-${String(s)}`,value:a.name,spellCheck:!1,onChange:e=>r(fc(n,s,e.target.value))})]}),e(`label`,{className:`min-w-40 flex-1`,children:[o(Q,{children:i(`automation.actionList.setValue`,`Value`)}),o(J,{"data-testid":`set-value-${String(t)}-${String(s)}`,value:String(a.value),onChange:e=>r(pc(n,s,e.target.value))})]}),o(K,{variant:`ghost`,onClick:()=>r(gc(n,s)),title:i(`automation.actionList.setRemove`,`Remove this variable`),children:o(g,{className:`h-3.5 w-3.5`})})]},String(s))),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:`outline`,"data-testid":`set-add-${String(t)}`,disabled:!mc(n),onClick:()=>r(hc(n)),children:[o(j,{className:`h-4 w-4`}),` `,i(`automation.actionList.setAdd`,`Add a variable`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.setHint`,`The steps after this one can use it as {{slot}}.`,{slot:_c,interpolation:{escapeValue:!1}})})]})]})}function yc({index:t,step:n,devices:r,devicesState:i,variables:a,depth:s=0,roundDevices:c,onChange:l}){let{t:u}=X(),{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`,h=p?ac(d.when):null,g={name:be,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:[o(`div`,{className:`w-64`,children:o(I,{"data-testid":`repeat-by-${String(t)}`,"aria-label":u(`automation.repeat.by`,`Repeat`),value:d.by,onChange:e=>{let t=e.target.value;Xr(t)&&t!==d.by&&l({...n,loop:ei(t)})},options:Kr.map(e=>({value:e,label:f[e]}))})}),d.by===`count`&&e(`label`,{className:`block w-24`,children:[o(Q,{children:u(`automation.repeat.count`,`Times`)}),o(J,{type:`number`,min:1,max:20,"data-testid":`repeat-count-${String(t)}`,value:String(d.count),onChange:e=>l({...n,loop:{...d,count:Qr(Number(e.target.value))}})})]}),p&&e(m,{children:[o(`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.`)}),o(qs,{hideRule:!0,context:`guard`,recipe:{when:d.when,actions:[]},devices:r,onChange:e=>l({...n,loop:{...d,when:e.when}})}),h!==null&&o(G,{variant:`warning`,message:h}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-28`,children:[o(Q,{children:u(`automation.repeat.max`,`At most (rounds)`)}),o(J,{type:`number`,min:1,max:50,"data-testid":`repeat-max-${String(t)}`,value:String(d.maxIterations),onChange:e=>l({...n,loop:{...d,maxIterations:$r(Number(e.target.value))}})})]}),e(`label`,{className:`w-40`,children:[o(Q,{children:u(`automation.repeat.wait`,`Pause between rounds (s)`)}),o(J,{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:ti(d,e.target.value===``?null:Number(e.target.value))})})]})]}),o(`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:[o(Vt,{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)}}})}),o(`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".`)})]}),o(Q,{children:u(`automation.repeat.steps`,`Each time, run`)}),o(`div`,{className:`border-l-2 border-border-subtle pl-3`,"data-testid":`repeat-steps-${String(t)}`,children:o(Cc,{nested:!0,flowControl:!0,actions:n.steps,devices:r,depth:s+1,allowedKinds:$i(s+1),maxSteps:10,...i===void 0?{}:{devicesState:i},..._===void 0?{}:{variables:_},...v===void 0?{}:{roundDevices:v},onChange:e=>l({...n,steps:e.filter(ea)})})})]})}function bc({index:t,step:n,devices:r,onChange:i}){let{t:a}=X(),s={when:n.when,actions:[]},c=ac(n.when),l=oi(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:[o(`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.`)}),o(qs,{hideRule:!0,context:`guard`,recipe:s,devices:r,onChange:e=>i({...n,when:e.when})}),c!==null&&o(G,{variant:`warning`,message:c}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-24`,children:[o(Q,{children:a(`automation.waitUntil.timeout`,`At most`)}),o(J,{type:`number`,min:1,"data-testid":`wait-until-timeout-${String(t)}`,value:String(l.value),onChange:e=>i({...n,timeoutS:si(Number(e.target.value),l.unit)})})]}),o(`div`,{className:`w-32`,children:o(I,{"data-testid":`wait-until-unit-${String(t)}`,"aria-label":a(`automation.waitUntil.unit`,`Unit`),value:l.unit,onChange:e=>i({...n,timeoutS:si(l.value,ai(e.target.value)?e.target.value:l.unit)}),options:ri.map(e=>({value:e,label:u[e]}))})}),e(`label`,{className:`min-w-56 flex-1`,children:[o(Q,{children:a(`automation.waitUntil.onTimeout`,`If it does not happen in time`)}),o(I,{"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 xc=[{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`}],Sc=[`set`,`stop`,`choose`,`wait-until`,`parallel`,`repeat`];function Cc({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:s,stepResults:c,nested:l=!1,flowControl:u=!1,maxSteps:d,roundDevices:f,depth:p=0,onChange:m}){let{t:h}=X(),_=xc.filter(e=>(i===void 0||i.includes(e.value))&&(u||!Sc.includes(e.value))),v=h(`automation.actionList.flowGuardHint`,`Checked when this step is reached. If it is false, or a state cannot be read, the step does nothing.`),y={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&&o(`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 ${s===void 0?`border-border`:Hr(s[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(q,{variant:`default`,children:d+1}),e(`label`,{className:`w-40`,children:[o(Q,{children:h(`automation.actionList.step`,`Step`)}),o(I,{"data-testid":`step-kind-${String(d)}`,value:i.kind,onChange:e=>m(Z(t,d,vi(wc(e.target.value)))),options:_.map(e=>({value:e.value,label:h(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(zi,{move:{up:d===0?null:()=>m(bi(t,d,d-1)),down:d===t.length-1?null:()=>m(bi(t,d,d+1))},texts:y}),o(K,{variant:`ghost`,onClick:()=>m(yi(t,d)),title:h(`automation.actionList.removeThisStep`,`Remove this step`),children:o(g,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Q,{children:h(`automation.actionList.seconds`,`Seconds`)}),o(J,{type:`number`,min:0,max:3600,value:String(i.seconds),onChange:e=>m(Z(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:[o(Q,{children:h(`automation.actionList.stopReason`,`Reason`)}),o(J,{"data-testid":`stop-reason-${String(d)}`,value:i.reason,maxLength:200,onChange:e=>m(Z(t,d,{...i,reason:e.target.value}))})]}),e(`label`,{className:`w-48`,children:[o(Q,{children:h(`automation.actionList.stopOutcome`,`The run ends as`)}),o(I,{"data-testid":`stop-outcome-${String(d)}`,value:i.outcome,onChange:e=>m(Z(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`&&o(vc,{index:d,vars:i.vars,onChange:e=>m(Z(t,d,{...i,vars:e}))}),i.kind===`wait-until`&&o(bc,{index:d,step:i,devices:n,onChange:e=>m(Z(t,d,e))}),i.kind===`repeat`&&o(yc,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Z(t,d,e))}),i.kind===`parallel`&&e(`div`,{className:`space-y-2`,"data-testid":`parallel-steps-${String(d)}`,children:[o(`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.`)}),o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(Cc,{nested:!0,flowControl:!0,actions:i.steps,devices:n,devicesState:r,variables:a,allowedKinds:Vi,depth:p+1,...f===void 0?{}:{roundDevices:f},maxSteps:5,onChange:e=>m(Z(t,d,{...i,steps:e.filter(Hi)}))})})]}),i.kind===`choose`&&o(lc,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Z(t,d,e))}),!l&&(i.kind===`stop`||i.kind===`set`)&&o(sc,{when:i.if,devices:n,hint:v,onChange:e=>{let{if:n,...r}=i;m(Z(t,d,e===void 0?r:{...r,if:e}))}}),i.kind===`code`&&e(`label`,{className:`block`,children:[o(Q,{children:h(`automation.actionList.code`,`Code`)}),o(Mt,{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(Z(t,d,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),i.kind===`command`&&o(Xn,{step:i,devices:n,variables:a,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Z(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`&&o(Ii,{step:i,onChange:e=>m(Z(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{}}))}),u&&(i.kind===`command`||i.kind===`action`)&&o(dt,{"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(Z(t,d,e?{...r,continueOnError:!0}:r))}}),!l&&(i.kind===`wait`||i.kind===`command`)&&o(cc,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>m(Z(t,d,e))}),c?.[d]!==void 0&&o(ki,{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(K,{variant:`outline`,disabled:d!==void 0&&t.length>=d,onClick:()=>m([...t,vi(_[0]?.value??`command`)]),children:[o(j,{className:`h-4 w-4`}),` `,h(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function wc(e){return xc.find(t=>t.value===e)?.value??`command`}function Tc(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function Ec(e,t){return Fe(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.hintKey??e.name}`,e.description)}))}function Dc(e){return e.some(e=>e.required===!0&&e.default===void 0)}function Oc(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function kc(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function Ac(e,t){return e.filter(e=>e.required===!0&&!kc(t[e.name])).map(e=>e.name)}function jc(e,t){let n={};for(let r of e){let e=t[r.name];kc(e)&&(n[r.name]=e)}return n}u();function Mc({variable:e,value:t,onChange:n}){let{t:r}=X(),i=e.label??e.name;return e.type===`number`?o(er,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?o(Jn,{widthClass:`w-28`,"aria-label":i,value:t===!0?`yes`:`no`,onChange:e=>n(e.target.value===`yes`),options:[{value:`yes`,label:r(`common.yes`,`Yes`)},{value:`no`,label:r(`common.no`,`No`)}]}):e.type===`select`?o(Jn,{widthClass:`w-48`,"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`actions.editor.runDialog.choose`,`Choose…`)},...(e.options??[]).map(e=>({value:e,label:e}))]}):o(J,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function Nc({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:s}=X(),[l,u]=c(()=>Oc(n)),d=Ac(n,l);return o(Qe,{open:!0,onOpenChange:e=>!e&&a(),children:e(Tt,{"aria-label":s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(gt,{children:[o(en,{children:s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),o(rt,{children:s(`actions.editor.runDialog.description`,`Give the variables this run should use.`)})]}),o(`div`,{className:`space-y-3`,"data-testid":`run-variables-form`,children:n.map(t=>e(`label`,{className:`block space-y-1`,children:[e(`span`,{className:`text-xs text-foreground-subtle`,children:[t.label??t.name,t.required===!0?` *`:``]}),o(Mc,{variable:t,value:l[t.name],onChange:e=>u({...l,[t.name]:e})})]},t.name))}),e(et,{className:`flex flex-wrap gap-2`,children:[o(K,{variant:`ghost`,onClick:a,children:s(`common.cancel`,`Cancel`)}),e(K,{disabled:r||d.length>0,onClick:()=>i(jc(n,l)),children:[r?o(S,{className:`h-4 w-4 animate-spin`}):o(F,{className:`h-4 w-4`}),` `,s(`actions.editor.runNow`,`Run now`)]})]})]})})}var Pc=[`number`,`string`,`boolean`,`select`];function Fc(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function Ic(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 Lc(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function Rc(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function zc({variables:t,onChange:n,onRename:r}){let{t:i}=X(),a=e=>{switch(e){case`number`:return i(`actions.variables.typeNumber`,`number`);case`string`:return i(`actions.variables.typeText`,`text`);case`boolean`:return i(`actions.variables.typeBoolean`,`yes / no`);default:return i(`actions.variables.typeSelect`,`select`)}},s=(e,r)=>n(t.map((t,n)=>n===e?r:t));return o(wt,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:Ye,actions:e(K,{variant:`outline`,size:`sm`,onClick:()=>n([...t,tr(t)]),children:[o(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:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.name`,`Name`)}),o(J,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!nr(c.name),onChange:e=>r(l,e.target.value)})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.label`,`Label`)}),o(J,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,Rc(c,e.target.value))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.type`,`Type`)}),o(Jn,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:Pc.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=Pc.find(t=>t===e.target.value);t!==void 0&&s(l,Fc(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(Bc,{variable:c,onChange:e=>s(l,Lc(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(J,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>s(l,Ic(c,e.target.value))})]}),o(K,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(g,{className:`h-4 w-4`})})]},`${String(l)}`)),o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function Bc({variable:e,onChange:t}){let{t:n}=X(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(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 o(Jn,{widthClass:`w-full`,"aria-label":r,value:e.default===void 0?``:String(e.default),options:[{value:``,label:n(`actions.variables.noDefault`,`None`)},...i],onChange:n=>{n.target.value===``?t(null):t(e.type===`boolean`?n.target.value===`true`:n.target.value)}})}return o(J,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var Vc=5e3;function Hc(e){return e.kind===`command`||e.kind===`wait`}function Uc(e){return e instanceof Error?e.message:String(e)}function Wc(){let{t:e}=X();return t=>{switch(t.kind){case`name`:return e(`actions.editor.problemName`,`Give the action a name.`);case`no-steps`:return e(`actions.editor.problemNoSteps`,`Add at least one step.`);case`undeclared`:return e(`actions.editor.problemUndeclared`,`A step uses {{name}}, which is not declared under Variables.`,{name:t.name});case`duplicate`:return e(`actions.editor.problemDuplicate`,`The variable {{name}} is declared twice.`,{name:t.name});case`bad-name`:return e(`actions.editor.problemBadName`,`The variable name "{{name}}" must start with a letter and use letters, digits or _.`,{name:t.name});default:return t.message}}}function Gc({entry:t,onClose:i,onSaved:a,preset:l=null}){let{t:u}=X(),d=f(),p=A(),h=qn(),_=Wc(),[v,y]=c(()=>ar(t)),b=n(!1);s(()=>{if(t!==null||l!==`trigger-alarm`||b.current)return;let e=h.find(e=>e.type===ze.AlarmPanel);e!==void 0&&(b.current=!0,y(or(e.id,u(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[h,t,l,u]);let[x,w]=c(null),[T,E]=c(!1),D=t!==null&&t.readOnly,O=()=>{d.invalidateQueries({queryKey:[[`actions`]]})},k=Wt({onSuccess:e=>{O(),a(e.action.id)}}),j=gn({onSuccess:O}),M=nn({onSuccess:()=>{O(),i()}}),N=It({onSuccess:O}),P=Yt({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Vc}),I=P.data?.traces.find(e=>e.runId===x)??null,L=r(()=>I===null?null:br(I),[I]),R=r(()=>I===null?null:Er(I).steps,[I]),z=rr(v),ee=r(()=>Tc(v.variables,u),[v.variables,u]),B=k.isPending||j.isPending,V=k.error??j.error??M.error??N.error,H=Dc(t?.variables??[]);return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`action-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(C,{className:`h-4 w-4 text-foreground-muted`}),o(J,{"aria-label":u(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:v.name,disabled:D,placeholder:u(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>y({...v,name:e.target.value})}),o(q,{variant:D?`info`:`primary`,children:D?t?.addonId??``:u(`actions.source.internal`,`Internal`)})]}),D?o(`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(m,{children:[o(zc,{variables:v.variables,onChange:e=>y({...v,variables:e}),onRename:(e,t)=>y(ir(v,e,t))}),o(Gr,{step:`steps`,title:u(`actions.editor.steps`,`Steps`),trace:L===null?null:L.thenBlock,children:o(Cc,{actions:v.steps,devices:h,allowedKinds:[`command`,`wait`],stepTones:L===null?void 0:v.steps.map((e,t)=>xr(L,t)??`idle`),stepResults:R===null?void 0:v.steps.map((e,t)=>R.find(e=>e.index===t)),variables:ee,onChange:e=>y({...v,steps:e.filter(Hc)})})})]}),!z.ok&&!D&&v.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:_(z.reason)}),V!==null&&o(G,{message:Uc(V)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!D&&e(K,{onClick:()=>{z.ok&&(t===null?k.mutate({action:z.input}):j.mutate({actionId:t.id,action:z.input}))},disabled:B||!z.ok,children:[B&&o(S,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),t!==null&&e(K,{variant:`outline`,disabled:N.isPending,onClick:()=>H?E(!0):N.mutate({actionId:t.id}),children:[o(F,{className:`h-4 w-4`}),` `,u(`actions.editor.runNow`,`Run now`)]}),t!==null&&!D&&e(K,{variant:`ghost`,disabled:M.isPending,onClick:()=>{p({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&&M.mutate({actionId:t.id})})},children:[o(g,{className:`h-4 w-4`}),` `,u(`common.delete`,`Delete`)]}),o(K,{variant:`ghost`,onClick:i,children:u(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Vr,{traces:t===null?[]:P.data?.traces,selectedId:x,onSelect:w})}),T&&t!==null&&o(Nc,{actionName:t.name,variables:t.variables??[],running:N.isPending,onCancel:()=>E(!1),onRun:e=>{N.mutate({actionId:t.id,variables:e}),E(!1)}})]})}u();var Kc=5e3;function qc(e){return e instanceof Error?e.message:String(e)}function Jc(){let{t:e}=X();return t=>t.status.isRunning?{variant:`info`,label:e(`actions.status.running`,`Running`)}:t.status.lastError===null?t.status.lastRunAt===null?{variant:`neutral`,label:e(`actions.status.neverRan`,`Never ran`)}:{variant:`success`,label:e(`actions.status.ok`,`OK`)}:{variant:`danger`,label:e(`actions.status.failed`,`Failed`)}}function Yc({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=X(),[a]=bn(),c=f(),l=Jc(),{state:u,openNew:d,openEdit:p,close:h}=Pt({editKey:`action`,newKey:`new`}),g=Kt({},{refetchInterval:Kc}),_=It({onSuccess:()=>void c.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(d(),n?.())},[t,n,d]);let v=g.data??[],y=u.mode===`edit`?v.find(e=>e.id===u.id)??null:null,b=r(()=>[{key:`name`,header:i(`actions.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:i(`actions.list.source`,`Source`),render:e=>e.readOnly?o(q,{variant:`info`,children:e.addonId}):o(q,{variant:`primary`,children:i(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:i(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?o(`span`,{className:`text-foreground-subtle`,children:`-`}):kn(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:i(`actions.list.status`,`Status`),render:e=>{let t=l(e);return o(`span`,{title:e.status.lastError??void 0,children:o(q,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(K,{variant:`outline`,size:`sm`,disabled:_.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),_.mutate({actionId:t.id})},children:[o(F,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[_,l,i]);return u.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),_.error!=null&&o(G,{message:qc(_.error)}),g.data===void 0?g.error==null?o(nt,{className:`h-24 w-full`}):o(G,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:qc(g.error),onRetry:()=>void g.refetch()}):v.length===0?o(_n,{icon:C,title:i(`actions.list.emptyTitle`,`No actions yet`),description:i(`actions.list.emptyDescription`,`An action is a short list of commands, such as feeding the dog, that you can reuse.`),action:e(K,{onClick:d,children:[o(j,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(m,{children:[g.error!=null&&o(G,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:qc(g.error),onRetry:()=>void g.refetch()}),o(pn,{columns:b,rows:v,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Et,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>p(e.id)})]})]}):o(Gc,{entry:y,onClose:h,onSaved:p,preset:u.mode===`new`?a.get(`preset`):null},y?.id??`new`)}u();function Xc({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=X(),[l,u]=c(!1),d=A(),f=async()=>{await d({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(K,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?We:b,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(K,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[o(Ke,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),l&&o(`div`,{className:`border-t border-border p-3`,children:t===null?o(`p`,{className:`text-xs text-warning`,children:n??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):o(dn,{maxHeight:420,children:t})})]})}var Zc=[`single`,`restart`,`queued`,`parallel`,`cooldown`],Qc=2,$c=30;function el(e){return e.runMode??{mode:`single`}}function tl(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function nl(e){switch(e){case`queued`:return{mode:`queued`,max:Qc};case`parallel`:return{mode:`parallel`,max:Qc};case`cooldown`:return{mode:`cooldown`,minutes:$c};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function rl(e){return Zc.find(t=>t===e)??`single`}function il({value:t,onChange:n}){let{t:r}=X(),i={single:r(`flow.runMode.single`,`Skip it`),restart:r(`flow.runMode.restart`,`Restart the run`),queued:r(`flow.runMode.queued`,`Queue it`),parallel:r(`flow.runMode.parallel`,`Run at the same time`),cooldown:r(`flow.runMode.cooldown`,`Wait after a run`)},a={single:r(`flow.runMode.singleHint`,`A trigger that arrives during a run is dropped.`),restart:r(`flow.runMode.restartHint`,`The run in progress stops and a new one starts.`),queued:r(`flow.runMode.queuedHint`,`Triggers wait their turn, up to the limit.`),parallel:r(`flow.runMode.parallelHint`,`Runs overlap, up to the limit.`),cooldown:r(`flow.runMode.cooldownHint`,`No new run until this long after the last one began.`)};return e(`div`,{className:`flex flex-wrap items-end gap-3`,"data-testid":`run-mode`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.label`,`When it is already running`)}),o(Jn,{widthClass:`w-56`,value:t.mode,options:Zc.map(e=>({value:e,label:i[e]})),onChange:e=>n(nl(rl(e.target.value)))})]}),(t.mode===`queued`||t.mode===`parallel`)&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.max`,`Up to`)}),o(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:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.minutes`,`Minutes`)}),o(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)})}})]}),o(`p`,{className:`basis-full text-xs text-foreground-subtle`,children:a[t.mode]})]})}var al;function ol(){return al??=Le(te),al}function sl(e,t=ol()){return Pe(e,t)}u();var cl=`hub`,ll=5e3;function ul({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=X(),[p,m]=c(t?.name??``),[h,g]=c(()=>Cs(n)),_=e=>g(la(e)),[v,y]=c(!1),[b,C]=c(null),w=$t({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:ll}),T=w.data?.traces.find(e=>e.runId===b)??null,E=r(()=>T===null?null:br(T),[T]),D=r(()=>Ec(h.when,f),[h.when,f]),O=r(()=>T===null?null:Dr(T),[T]),k=r(()=>T===null?null:Er(T).steps,[T]),A=qn(),j=Be(h),M=r(()=>dl(h),[h]),N=r(()=>fl(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),P=ot().data,F=r(()=>M===null?ms(h,P):null,[h,P,M]),I=p.trim()===``,L=I||j!==null||M!==null||F!==null||N.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[o(ma,{when:h.when,children:e(`div`,{className:`space-y-4`,children:[e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(J,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Gr,{step:`when`,title:f(`automation.automationEditor.when`,`When`),trace:E===null?null:E.when,children:o(qs,{recipe:h,devices:A,run:O,onChange:_})}),o(Gr,{step:`then`,title:f(`automation.automationEditor.then`,`Then`),trace:E===null?null:E.thenBlock,hint:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(Cc,{flowControl:!0,actions:h.actions,devices:A,variables:D,stepTones:E===null?void 0:h.actions.map((e,t)=>xr(E,t)??`idle`),stepResults:k===null?void 0:h.actions.map((e,t)=>k.find(e=>e.index===t)),onChange:e=>_(xi(h,e))})}),o(Gr,{step:`mode`,title:f(`flow.runMode.title`,`Overlap`),trace:null,hint:f(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:o(il,{value:el(h),onChange:e=>_(tl(h,e))})}),o(Xc,{code:N.code,error:N.error,canEject:t!==null,ejecting:s,onEject:u}),j!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:j}),j===null&&M!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:M}),j===null&&F!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`automation-site-error`,children:F}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{onClick:()=>{N.code!==null&&l({name:p.trim(),code:N.code,enabled:t?.enabled??!0,placement:cl})},disabled:i||L,children:[i&&o(S,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(K,{variant:`ghost`,onClick:()=>y(!v),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,"aria-expanded":v,children:[o(x,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,o(bt,{expanded:v})]}),o(K,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),I&&o(q,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),v&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`common.logsOf`,values:{id:ue(t.id)},components:{code:o(`code`,{})}})}),o(cn,{addonId:ue(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}),o(`div`,{className:`order-first lg:order-last`,children:o(Vr,{traces:t===null?[]:w.data?.traces,selectedId:b,onSelect:C})})]})}function dl(e){let t=He.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Y.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function fl(e,t){let n=sl(t);if(!n.ok)return{code:null,error:n.error};try{return{code:we({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function pl(e){if(!e.enabled)return{tone:`idle`,label:Y.t(`helpers.coreBlockStatus.disabled`),detail:Y.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Y.t(`helpers.coreBlockStatus.running`),detail:Y.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function ml(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function hl(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function gl(e){let t=e=>{let t=pl(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 _l(e){if(e.length===0)return Y.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>pl(e).tone===`error`).length,n=e.filter(e=>pl(e).tone===`ok`).length,r=[Y.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Y.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Y.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var vl=3e4;function yl({block:t,logsOpen:n,unreadable:r}){let i=v(),{t:a}=X(),s=pl(t),c=sn(t.updatedAt,i);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(q,{variant:ml(s.tone),children:s.label}),c!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.edited`,{when:c})})]}),(s.tone===`error`||s.tone===`pending`)&&o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:s.detail}),r!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:a(`automation.editor.listUnreadable`,{reason:r})}),n&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`common.logsOf`,values:{id:ue(t.id)},components:{code:o(`code`,{})}})}),o(cn,{addonId:ue(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var bl=2;function xl(e){let t=[];if(V(e.when,e=>{Ae(e)&&t.push(pi(e.kind))}),t.length===0)return H(e.when)===0?``:Y.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,bl).join(`, `),i=n.length-bl;return i>0?`${r} +${i}`:r}function Sl({recipe:e}){let{t}=X();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=xl(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function Cl({blockId:t}){let{t:n}=X(),r=$t({blockId:t},{refetchInterval:vl});if(r.data===void 0)return r.error===null||r.error===void 0?o(nt,{className:`h-4 w-16`}):o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.lastRunUnknown`,`Unknown`)});let i=r.data.traces.findLast(e=>!e.outcome.startsWith(`skipped-`));if(i===void 0)return o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.neverRan`,`Never ran`)});let a=i.outcome===`failed`||i.outcome===`aborted`;return e(`span`,{className:`inline-flex items-center gap-2`,children:[kn(i.lastAt),a&&o(q,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function wl({block:e,disabled:t,onToggle:n}){let{t:r}=X();return o(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(dt,{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 Tl({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=X();return o(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(Bt,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:P,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:F,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:x,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:g,danger:!0,separatorBefore:!0,onClick:r}]})})}function El({onCreate:t}){let{t:n}=X();return o(_n,{icon:T,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(K,{onClick:t,"data-testid":`automation-empty-new`,children:[o(j,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();var Dl=[`coreBlocks`,`list`],Ol=5e3;function kl(e){return e instanceof Error?e.message:String(e)}function Al({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:a}=X(),u=k(),{state:d,openNew:f,openEdit:m,close:h}=Pt({editKey:`block`,newKey:`new`}),g=A(),[_,v]=c(null),y=d.mode!==`closed`;s(()=>{n&&(f(),i?.())},[n,i,f]);let b=l({queryKey:Dl,refetchInterval:Ol,queryFn:async()=>(await u.trpcClient.coreBlocks.list.query({})).blocks}),x=()=>{b.refetch()},S=e=>{h(),x(),Sn({title:a(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},C=p({mutationFn:e=>u.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>S(e.block)}),w=p({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>S(e.block)}),E=p({mutationFn:e=>u.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:x}),D=p({mutationFn:e=>u.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:x}),O=p({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:fr(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{h(),x(),t(e.block.id)}}),j=b.data,M=gl((j??[]).filter(e=>lr(e.code))),N=j!==void 0&&M.length===0,P=d.mode===`edit`?M.find(e=>e.id===d.id)??null:null,F=d.mode===`edit`&&j!==void 0&&P===null;s(()=>{F&&h()},[F,h]);let I=P===null?null:dr(P.code),L=C.error===null?w.error===null?O.error===null?null:kl(O.error):kl(w.error):kl(C.error),R=r(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=dr(e.code);return o(yl,{block:e,logsOpen:_===e.id,unreadable:t.ok?null:t.reason})},sortValue:e=>e.name},{key:`trigger`,header:a(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=dr(e.code);return o(Sl,{recipe:t.ok?t.recipe:null})},notSortableReason:a(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:a(`build.automationsTab.lastRun`,`Last run`),render:e=>o(Cl,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>o(wl,{block:e,disabled:D.isPending,onToggle:t=>D.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=dr(e.code);return o(Tl,{unreadable:t.ok?null:t.reason,onEdit:()=>m(e.id),onToggleLogs:()=>v(_===e.id?null:e.id),onDelete:()=>{g({title:a(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:a(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&E.mutate(e.id)})}})}}],[g,_,m,E,D,a]);return y?d.mode===`edit`&&P===null?o(nt,{className:`h-24 w-full`}):e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[o(T,{className:`h-4 w-4 text-foreground-muted`}),P===null?a(`build.automationsTab.newAutomation`,`New automation`):a(`build.automationsTab.edit`,`Edit {{name}}`,{name:P.name})]}),o(ul,{existing:P,initialRecipe:I!==null&&I.ok?I.recipe:gi,saving:C.isPending||w.isPending,saveError:L,ejecting:O.isPending,onSave:e=>{P===null?C.mutate(e):w.mutate({blockId:P.id,block:e})},onEject:()=>{P!==null&&O.mutate(P)},onCancel:()=>{C.reset(),w.reset(),O.reset(),h()}},P?.id??`new`),E.error!=null&&o(G,{message:kl(E.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:j===void 0?``:_l(M)}),b.error!=null&&o(G,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:kl(b.error),onRetry:x}),N?o(El,{onCreate:f}):o(pn,{columns:R,rows:M,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Et,emptyMessage:j===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>m(e.id)}),E.error!=null&&o(G,{message:kl(E.error)}),D.error!=null&&o(G,{message:kl(D.error)})]})}var jl={kind:`all`,children:[]};function Ml({value:t,devices:n,label:r,onChange:i}){let{t:a}=X(),s=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[o(dt,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?jl:void 0)}),s!==null&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.activeWhen.hint`,`Only states count here, such as "someone is home". While they are false, nothing runs and holds pause.`)}),o(qs,{recipe:s,devices:n,onChange:e=>i(e.when)})]})]})}var Nl=[`sunrise`,`sunset`,`dawn`,`dusk`],Pl=6e4;function Fl(e){return e.kind===`command`||e.kind===`wait`}function Il(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 Ll({point:t,devices:n,site:r,localDate:i,issues:a,onChange:s,onRemove:c}){let{t:l}=X(),u=t.at,d=u.kind===`sun`?Yo(u,r,i):null,f=Xo(u,r,i),p=t.override??{mode:`respect`},h=e=>s({...t,at:e});return e(`div`,{className:`space-y-3`,"data-testid":`point-editor`,children:[e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.kind`,`Point type`)}),o(I,{"aria-label":l(`schedulers.point.kind`,`Point type`),value:t.mode,options:[{value:`edge`,label:l(`schedulers.point.edge`,`Edge: run once`)},{value:`hold`,label:l(`schedulers.point.hold`,`Hold: keep true`)},{value:`release`,label:l(`schedulers.point.release`,`Release: end the hold`)}],onChange:e=>{let n=e.target.value;(n===`edge`||n===`hold`||n===`release`)&&s(Il(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.when`,`When`)}),o(I,{"aria-label":l(`schedulers.point.when`,`When`),value:u.kind===`sun`?`sun`:`clock`,options:[{value:`clock`,label:l(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:l(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{e.target.value===`sun`?h({kind:`sun`,event:`sunset`,offsetMin:0}):h({kind:`clock`,hh:12,mm:0})}})]}),u.kind===`clock`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.time`,`Time`)}),o(J,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:$o(u.hh,u.mm),onChange:e=>{let t=Qo(e.target.value);t!==null&&h(t)}})]}),u.kind===`sun`&&e(m,{children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.sunEvent`,`Sun event`)}),o(I,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:Nl.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Nl.find(t=>t===e.target.value);t!==void 0&&h({...u,event:t})}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.offset`,`Offset (minutes, negative = before)`)}),o(er,{"aria-label":l(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-28`,value:u.offsetMin,onValue:e=>{e!==null&&h({...u,offsetMin:Math.round(e)})}})]}),o(`p`,{className:`pb-2 text-xs text-foreground-muted`,"data-testid":`sun-computed`,children:d===null||f===null?l(`schedulers.point.sunUnknown`,`No time today: the site location is not set.`):l(`schedulers.point.sunComputed`,`Today at {{time}} ({{zone}})`,{time:es(d),zone:r.timeZone})})]}),e(K,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[o(g,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&o(Cc,{actions:t.steps,devices:n,allowedKinds:[`command`,`wait`],onChange:e=>s({...t,steps:e.filter(Fl)})}),t.mode===`release`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:l(`schedulers.point.releaseHint`,`A release ends the running hold without doing anything to the devices.`)}),t.mode===`hold`&&e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.override`,`If someone changes it by hand`)}),o(I,{"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=>s({...t,override:e.target.value===`reassert`?{mode:`reassert`,graceMs:10*Pl}:{mode:`respect`}})})]}),p.mode===`reassert`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.grace`,`Wait (minutes)`)}),o(er,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:p.graceMs/Pl,onValue:e=>{e!==null&&s({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*Pl))}})}})]})]}),a.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:a.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))})]})}u();var Rl=5e3,zl=600,Bl=6e4,Vl={timeZone:`UTC`,location:null};function Hl(e){return e instanceof Error?e.message:String(e)}function Ul(e){if(e===null)return Ho();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function Wl(e,t){let[n,r]=c(e);return s(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Gl(e,t){return t(`schedulers.day.${e}`,e)}function Kl({entry:t,onClose:n,onSaved:i}){let{t:a}=X(),s=f(),l=A(),u=qn(),d=ot(),p=d.data??Vl,[m,h]=c(()=>Ul(t)),[_,v]=c(()=>m.profiles[0]?.id??``),[y,b]=c(null),[x,C]=c(null),w=()=>{s.invalidateQueries({queryKey:[[`schedulers`]]})},T=Ht({onSuccess:e=>{w(),i(e.scheduler.id)}}),E=Lt({onSuccess:w}),D=Gt({onSuccess:()=>{w(),n()}}),O=tn({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:Rl}),k=r(()=>ns(m,p),[m,p]),M=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),P=Wl(k.ok?k.input:null,zl),F=un(P===null?{scheduler:m}:t===null?{scheduler:P}:{scheduler:P,schedulerId:t.id},{enabled:P!==null&&M&&d.data!==void 0}),I=m.profiles.find(e=>e.id===_)??m.profiles[0],L=I===void 0?-1:m.profiles.indexOf(I),R=Jo(p),z=I?.points.find(e=>e.id===y)??null,ee=I===void 0||z===null?-1:I.points.indexOf(z),B=k.ok?[]:k.issues,V=e=>B.filter(t=>t.path===e||t.path.startsWith(`${e}.`)),H=e=>h({...m,profiles:m.profiles.map((t,n)=>n===L?e:t)}),te=e=>{I!==void 0&&H({...I,points:I.points.map(t=>t.id===e.id?e:t)})},ne=r(()=>I===void 0?[]:I.points.flatMap(e=>{let t=Yo(e.at,p,R);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)} (${es(t)})`:$o(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`&&Xo(e.at,p,R)!==null}]}),[I,p,R,a]),re=r(()=>I===void 0?[]:ts(I.points,p,R),[I,p,R]),U=(e,t)=>{let n=I?.points.find(t=>t.id===e);n!==void 0&&te({...n,at:Zo(n.at,t,Xo(n.at,p,R))})},ie=e=>{if(I===void 0)return;let t=Go(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));H({...I,points:[...I.points,Wo(e,t,720)]}),b(t)},ae=()=>{let e=Go(`profile`,m.profiles.map(e=>e.id));h({...m,profiles:[...m.profiles,Uo(e,a(`schedulers.profile.newName`,`New profile`))]}),v(e),b(null)},oe=T.isPending||E.isPending,W=T.error??E.error??D.error;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`scheduler-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(N,{className:`h-4 w-4 text-foreground-muted`}),o(J,{"aria-label":a(`schedulers.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,placeholder:a(`schedulers.editor.namePlaceholder`,`What this scheduler does`),onChange:e=>h({...m,name:e.target.value})})]}),e(wt,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[o($e,{label:a(`schedulers.editor.enabled`,`Enabled`),children:o(dt,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>h({...m,enabled:e})})}),o($e,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:o(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)})}})}),o($e,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:o(er,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/Bl,onValue:e=>{e!==null&&h({...m,maxLateMs:Math.round(e*Bl)})}})})]}),e(`div`,{className:`p-3`,children:[o(Ml,{value:m.activeWhen,devices:u,label:a(`schedulers.editor.activeWhen`,`Only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=m;h(e===void 0?n:{...n,activeWhen:e})}}),V(`activeWhen`).map(e=>o(`p`,{className:`mt-1 text-xs text-warning`,children:e.message},e.message))]})]}),o(wt,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(K,{variant:`outline`,size:`sm`,onClick:ae,children:[o(j,{className:`h-4 w-4`}),` `,a(`schedulers.profile.add`,`Add profile`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.profile.hint`,`Each day, the first profile in this order whose days and condition hold is the one that runs.`)}),I!==void 0&&e(Xe,{value:I.id,onValueChange:e=>{v(e),b(null)},appearance:`pills`,children:[o(ct,{children:m.profiles.map(e=>o(Dt,{value:e.id,children:e.name},e.id))}),e(Ot,{value:I.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(J,{"aria-label":a(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:I.name,onChange:e=>H({...I,name:e.target.value})}),o(dt,{checked:I.enabled,label:a(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>H({...I,enabled:e})}),m.profiles.length>1&&e(K,{variant:`ghost`,size:`sm`,onClick:()=>{h({...m,profiles:m.profiles.filter(e=>e.id!==I.id)}),v(``),b(null)},children:[o(g,{className:`h-4 w-4`}),` `,a(`schedulers.profile.remove`,`Remove profile`)]})]}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":a(`schedulers.profile.days`,`Days`),children:zo.map(e=>{let t=I.days.includes(e);return o(K,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>H({...I,days:t?I.days.filter(t=>t!==e):zo.filter(t=>t===e||I.days.includes(t))}),children:Gl(e,a)},e)})}),V(`profiles.${String(L)}.days`).map(e=>o(`p`,{className:`text-xs text-warning`,children:a(`schedulers.profile.daysNeeded`,`Pick at least one day.`)},e.message)),o(Ml,{value:I.activeWhen,devices:u,label:a(`schedulers.profile.activeWhen`,`This profile only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=I;H(e===void 0?n:{...n,activeWhen:e})}}),o(hn,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:ne,bands:re,selectedId:y,onSelect:b,onMove:U}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:`outline`,size:`sm`,onClick:()=>ie(`edge`),children:[o(j,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(K,{variant:`outline`,size:`sm`,onClick:()=>ie(`hold`),children:[o(j,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(K,{variant:`outline`,size:`sm`,onClick:()=>ie(`release`),children:[o(j,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),o(q,{variant:`neutral`,children:p.timeZone})]}),I.points.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.timeline.empty`,`Add a point to place something on the day.`)}),z!==null&&o(Ll,{point:z,devices:u,site:p,localDate:R,issues:V(`profiles.${String(L)}.points.${String(ee)}`),onChange:te,onRemove:()=>{H({...I,points:I.points.filter(e=>e.id!==z.id)}),b(null)}},z.id)]})]})]})}),F.data!==void 0&&F.data.conflicts.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:F.data.conflicts.map(e=>o(`li`,{children:a(`schedulers.conflict.message`,`{{other}} wants device {{device}} in another state from {{from}} to {{to}} ({{winner}}).`,{other:e.other.schedulerName,device:e.deviceId,from:es(e.fromMinute),to:es(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!==``&&B.length>0&&z===null&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:B.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))}),W!==null&&o(G,{message:Hl(W)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(K,{onClick:()=>{k.ok&&(t===null?T.mutate({scheduler:k.input}):E.mutate({schedulerId:t.id,scheduler:k.input}))},disabled:oe||!k.ok||d.data===void 0,children:[oe&&o(S,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(K,{variant:`ghost`,disabled:D.isPending,onClick:()=>{l({title:a(`schedulers.editor.deleteTitle`,`Delete this scheduler?`),message:a(`schedulers.editor.deleteMessage`,`{{name}} will be deleted and any hold it keeps will stop.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&D.mutate({schedulerId:t.id})})},children:[o(g,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(K,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Vr,{traces:t===null?[]:O.data?.traces,selectedId:x,onSelect:C})})]})}u();var ql=5e3;function Jl(e){return e instanceof Error?e.message:String(e)}function Yl({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=X(),a=f(),{state:c,openNew:l,openEdit:u,close:d}=Pt({editKey:`scheduler`,newKey:`new`}),p=Xt({},{refetchInterval:ql}),m=rn({},{refetchInterval:ql}),h=qt({onSuccess:()=>void a.invalidateQueries({queryKey:[[`schedulers`]]})});s(()=>{t&&(l(),n?.())},[t,n,l]);let g=p.data??[],_=c.mode===`edit`?g.find(e=>e.id===c.id)??null:null,v=e=>{if(!e.enabled)return{variant:`neutral`,label:i(`schedulers.status.off`,`Off`)};let t=m.data?.find(t=>t.schedulerId===e.id);return t===void 0?{variant:`neutral`,label:`-`}:t.hold===null?{variant:`neutral`,label:i(`schedulers.status.idle`,`Idle`)}:t.hold.suspendedInactive?{variant:`warning`,label:i(`schedulers.status.paused`,`Paused`)}:t.hold.targets.some(e=>e.status===`gave-up`)?{variant:`danger`,label:i(`schedulers.status.gaveUp`,`Gave up`)}:{variant:`success`,label:i(`schedulers.status.holding`,`Holding`)}},y=r(()=>[{key:`name`,header:i(`schedulers.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`enabled`,header:i(`schedulers.list.enabled`,`Enabled`),render:e=>o(`span`,{onClick:e=>e.stopPropagation(),children:o(dt,{checked:e.enabled,disabled:h.isPending,"aria-label":i(`schedulers.list.enabledAria`,`Enable {{name}}`,{name:e.name}),onCheckedChange:t=>h.mutate({schedulerId:e.id,enabled:t})})}),sortValue:e=>Number(e.enabled)},{key:`profiles`,header:i(`schedulers.list.profiles`,`Profiles`),render:e=>String(e.profiles.length),sortValue:e=>e.profiles.length},{key:`priority`,header:i(`schedulers.list.priority`,`Priority`),render:e=>String(e.priority),sortValue:e=>e.priority},{key:`status`,header:i(`schedulers.list.status`,`Now`),render:e=>{let t=v(e);return o(q,{variant:t.variant,children:t.label})},notSortableReason:i(`schedulers.list.statusNotSortable`,`Derived from the live hold`)},{key:`updated`,header:i(`schedulers.list.updated`,`Updated`),render:e=>kn(e.updatedAt),sortValue:e=>e.updatedAt}],[h,m.data,i]);return c.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`schedulers.list.hint`,`A scheduler does things over the day: run something at a time or at sunset, or keep a device in a state for a stretch of time.`)}),h.error!=null&&o(G,{message:Jl(h.error)}),p.data===void 0?p.error==null?o(nt,{className:`h-24 w-full`}):o(G,{title:i(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:Jl(p.error),onRetry:()=>void p.refetch()}):g.length===0?o(_n,{icon:N,title:i(`schedulers.list.emptyTitle`,`No schedulers yet`),description:i(`schedulers.list.emptyDescription`,`A scheduler turns the garden lights on at sunset and off at 23:00, every day or only on some days.`),action:e(K,{onClick:l,children:[o(j,{className:`h-4 w-4`}),` `,i(`schedulers.list.new`,`New scheduler`)]})}):o(pn,{columns:y,rows:g,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Et,emptyMessage:i(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):o(Kl,{entry:_,onClose:d,onSaved:u},_?.id??`new`)}async function Xl(e,t){let n=`${ae}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var Zl=10,Ql=400;async function $l(e,t,n=Ql){for(let r=0;r<Zl;r+=1){let r=await Xl(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var eu=`media-player`;function tu(e){return e===ze.MediaPlayer?`media-source`:`none`}function nu(e){return e===ze.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[ze.MediaPlayer],accept:[{cap:eu,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[eu],exclude:[]}:null}function ru(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:eu,fields:{},commands:Object.fromEntries(Object.keys(ve()).map(t=>[t,{kind:`forward`,source:e.source,cap:eu,method:t}]))}]}function iu(e,t){let n=e===ze.MediaPlayer?ru(t):[];return{target:{kind:`new`,type:e},features:n}}u();function au({onTitle:t}){let{t:n}=X(),r=v(),i=xn(),a=$n(),l=Ze(),u=mn({addonId:`composer`}),[d,f]=c(ze.Sensor),[p,m]=c(``),[h,g]=c([]),[_,y]=c(null),b=h[0]??null,x=nu(d),S=iu(d,b);s(()=>{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 $l(t.id,async()=>(await u.refetch()).data??u.data);if(r===null){y(n(`helper.devicePending`));return}e!==``&&await l.mutateAsync({deviceId:r,name:e}),i(Tn(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`),o(I,{value:d,onChange:e=>{let t=Object.values(ze).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(ze).map(e=>({value:e,label:Ut(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(J,{"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:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:n(`helper.deviceSource.${tu(d)}`)}),o(Pn,{kind:`members`,request:x,enabled:!0,members:h,onMembersChange:g,onRefuse:()=>void 0})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(K,{disabled:a.isPending,onClick:()=>void C(),children:n(`compositionEditor.save`)})]})}u();function ou({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=X(),u=zn(!0),[d,f]=c({}),[p,m]=c(s(t.nameKey)),[h,g]=c(null),[_,v]=c([]),[y,b]=c(!1),x=r(()=>u.kind===`known`?new Map(u.value.map(e=>[W({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[W(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:An(u.value,S)}:u,[u,S]),w=Vn(t,d),T=u.kind===`known`?Hn(u.value,w,!1):null,E=t.build(d),D=Ln(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(W(e))??e.stableId;return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`preset-wizard`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:s(t.descriptionKey)}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[s(`preset.name`),o(J,{"aria-label":s(`preset.name`),value:p,onChange:e=>m(e.target.value)})]}),o(`ul`,{className:`flex flex-col gap-2`,"aria-label":s(`preset.slots`),children:t.slots.map(t=>{let n=d[t.key];return e(`li`,{className:`grid grid-cols-1 gap-1 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center`,"data-testid":`preset-slot-${t.key}`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`text-xs text-foreground`,children:[s(t.labelKey),t.optionalGroup===void 0?` *`:``]}),e(`div`,{className:`text-[11px] text-foreground-muted break-words`,children:[Un(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(K,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(K,{variant:`ghost`,size:`sm`,onClick:()=>O(t.key,void 0),children:s(`preset.clear`)})]})]},t.key)})}),E===null&&D.length>0&&o(`p`,{className:`text-[11px] text-foreground-muted`,"data-testid":`preset-missing`,children:s(`preset.missing`,{slots:D.map(e=>s(e.labelKey)).join(`, `)})}),E!==null&&e(`section`,{className:`flex flex-col gap-1`,"data-testid":`preset-preview`,children:[o(`h3`,{className:`text-xs font-medium text-foreground`,children:s(`preset.preview`)}),o(`ul`,{className:`flex flex-col gap-1 text-[11px] text-foreground-muted`,children:E.features.map(e=>e.kind===`fields`?o(`li`,{children:s(`preset.previewFeature`,{cap:Un(e.cap,l.language),fields:Object.keys(e.fields).length,commands:Object.keys(e.commands??{}).length+Object.values(e.items??{}).filter(e=>e.reset!==void 0).length})},e.cap):null)})]}),o(Bn,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(K,{disabled:E===null||n||y,onClick:()=>{E===null||y||(b(!0),i(E,p.trim()).then(e=>{e.kind===`refused`&&v(e.lines)}).finally(()=>b(!1)))},"data-testid":`preset-create`,children:s(`preset.create`)}),o(K,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o(Fn,{open:h!==null,title:h===null?``:s(`preset.pickTitle`,{slot:s(h.labelKey)}),selection:`single`,candidates:C,room:T,confirmLabel:()=>s(`preset.pickConfirm`),onConfirm:e=>{let t=e[0],n=h;g(null),t!==void 0&&n!==null&&O(n.key,t.ref)},onClose:()=>g(null)})]})}u();var su=`preset`;function cu({mode:e,onTitle:t}){return o(e===`helper`?lu:au,{onTitle:t})}function lu({onTitle:e}){let{t}=X(),r=xn(),i=$n(),a=Ze(),l=mn({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=bn(),g=Nn(m.get(su)),_=g===null?uu(u,t):t(g.labelKey);s(()=>{f||e(_)},[e,_,f]);let v=e=>h(t=>{let n=new URLSearchParams(t);return e===null?n.delete(su):n.set(su,e),n},{replace:!0}),y=async(e,n)=>{try{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:e}}),s=await $l(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:In(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(Tn(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:In(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(au,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Rn,{fillHeight:!0,onDevice:()=>p(!0),onPreset:v,purpose:`create`,initial:null,start:`template`,saving:i.isPending,onDraftChange:d,onSave:async(e,n)=>{let o=null,s=await Wn(e,async(s,c)=>{let u=b.current,d;if(u!==null&&u.draft===e)d=u.blockId;else{let{block:t}=await i.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:s}});d=t.id,b.current={draft:e,blockId:d}}let f=await $l(d,async()=>(await l.refetch()).data??l.data);if(f===null)throw Error(t(`helper.devicePending`));o=f,b.current=null,c!==``&&await a.mutateAsync({deviceId:f,name:c}),n===`open`&&r(wn(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:du(s,t)}:{kind:`saved`,deviceId:c}}})}):o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(ou,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function uu(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=Ce(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function du(e,t){return e.length>0?e:In(t(`helper.devicePending`))}function fu(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 pu(e){return{state:`answered`,byRef:new Map(e.map(e=>[W(e),e]))}}function mu(e,t){if(e.state!==`unanswered`)return e.byRef.get(W(t))??null}function hu(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function gu(e){return ne(e).map(e=>e.source)}function _u(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(...gu(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...gu(e))}let r=new Set;return n.filter(e=>{let t=W(e);return r.has(t)?!1:(r.add(t),!0)})}function vu(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:Y.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Y.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Y.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Y.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function yu(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return vu(e);case`degraded`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.degraded`),reason:n??Y.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Y.t(`helpers.compositionRows.failed`),reason:n??Y.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Y.t(`helpers.compositionRows.notRunning`),reason:n??Y.t(`helpers.compositionRows.notRunningReason`)}}}function bu(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Y.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Y.t(`helpers.compositionRows.unknown`),reason:Y.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return yu(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.notReported`),reason:Y.t(`helpers.compositionRows.noRecord`,{stored:r})}}function xu(e){return W(e)}function Su(e,t){let n=mu(t,e);return{key:W(e),label:n?n.name:xu(e),presence:hu(n),deviceId:n?n.id:null}}function Cu(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function wu(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:ke(e.block.id),a=W(i),o=_u(e).filter(e=>W(e)!==a).map(e=>Su(e,t)),s=n.features.map(e=>e.enabled===!1?Y.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=mu(t,i),l=Cu(e),u=bu(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:fu(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=hu(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:xu(r.device),namePresence:d,type:c?c.type:null,origin:fu(n),features:s,state:u,sources:o,reportedDeviceId:l}}function Tu(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Eu(e,t){return Tu(e)-Tu(t)||e.name.localeCompare(t.name)}function Du(e,t){let n=e.flatMap(e=>{let n=wu(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Eu),customizations:n.filter(e=>e.kind===`customization`).toSorted(Eu)}}u();var Ou=1e4;function ku(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Au(){let e=vn();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Y.t(`build.customDeviceTab.deviceListPending`):Y.t(`build.customDeviceTab.deviceListUnreadable`,{error:ku(e.error)})}:pu(e.data)}function ju(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Mu({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=X(),[i,a]=bn(),s=ht({},{refetchInterval:Ou}),l=Au(),u=Pt({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?ju(i.get(`new`),t):null,p=f!==null,[h,g]=c(``),_=A(),v=it(),y=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},b=s.data;return e(m,{children:[Pu(b,s.error,()=>void s.refetch(),l,{onEditComposed:e=>u.openEdit(e),deleting:v.isPending,onDelete:e=>{_({title:r(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`),message:r(`build.customDeviceTab.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:r(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&v.mutate({blockId:e.blockId},{onSuccess:()=>void s.refetch()})})}}),o(yt,{open:p,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:Ge,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(cu,{mode:f,onTitle:g},f)}),o(Yn,{blockId:d,onClose:y}),v.error!=null&&o(G,{message:ku(v.error)})]})}function Nu(t){return o(vt,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Y.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Y.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Pu(e,t,n,r,i){if(t!=null&&e===void 0)return o(G,{title:Y.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:ku(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Y.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return Nu(e.reason);let a=t==null?null:ku(t);return o(Fu,{lists:Du(e.views,r),fleet:r,refreshError:a,handlers:i})}function Fu({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=X();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(Iu,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,handlers:i}),o(Iu,{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 Iu({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=X();return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(pn,{columns:Lu(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:Et,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Lu(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(zu,{row:e})},{key:`type`,header:Y.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Y.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:Y.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>Ru(e.origin,i),render:e=>o(q,{variant:`default`,"data-testid":`composed-origin-badge`,children:Ru(e.origin,i)})}]:[],{key:`state`,header:Y.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(q,{variant:ml(t.state.tone),children:t.state.label}),t.state.reason!==null&&o(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:Y.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(Vu,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[o(K,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(K,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:o(g,{className:`h-4 w-4`})})]})}),a}function Ru(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 zu({row:t}){let{t:n}=X();return e(`div`,{className:`space-y-0.5`,children:[o(Bu,{row:t}),t.namePresence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),o(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function Bu({row:e}){let{t}=X(),n=on(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):o(En,{to:e.kind===`composed`?wn(e.reportedDeviceId):Tn(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Vu({sources:t}){let{t:n}=X();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(En,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function Hu(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 Uu(e){if(Array.isArray(e))return e}function Wu(e,t,n){return(t=$u(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Gu(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 Ku(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
5
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ju(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?qu(Object(n),!0).forEach(function(t){Wu(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):qu(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Yu(e,t){if(e==null)return{};var n,r,i=Xu(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Xu(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Zu(e,t){return Uu(e)||Gu(e,t)||ed(e,t)||Ku()}function Qu(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function $u(e){var t=Qu(e,`string`);return typeof t==`symbol`?t:t+``}function ed(e,t){if(e){if(typeof e==`string`)return Hu(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Hu(e,t):void 0}}function td(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function nd(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function rd(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?nd(Object(n),!0).forEach(function(t){td(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):nd(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function id(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function ad(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function od(e){return{}.toString.call(e).includes(`Object`)}function sd(e){return!Object.keys(e).length}function cd(e){return typeof e==`function`}function ld(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ud(e,t){return od(t)||hd(`changeType`),Object.keys(t).some(function(t){return!ld(e,t)})&&hd(`changeField`),t}function dd(e){cd(e)||hd(`selectorType`)}function fd(e){cd(e)||od(e)||hd(`handlerType`),od(e)&&Object.values(e).some(function(e){return!cd(e)})&&hd(`handlersType`)}function pd(e){e||hd(`initialIsRequired`),od(e)||hd(`initialType`),sd(e)&&hd(`initialContent`)}function md(e,t){throw Error(e[t]||e.default)}var hd=ad(md)({initialIsRequired:`initial state is required`,initialType:`initial state should be an object`,initialContent:`initial state shouldn't be an empty object`,handlerType:`handler should be an object or a function`,handlersType:`all handlers should be a functions`,selectorType:`selector should be a function`,changeType:`provided value of changes should be an object`,changeField:`it seams you want to change a field in the state which is not specified in the "initial" state`,default:"an unknown error accured in `state-local` package"}),gd={changes:ud,selector:dd,handler:fd,initial:pd};function _d(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};gd.initial(e),gd.handler(t);var n={current:e},r=ad(bd)(n,t),i=ad(yd)(n),a=ad(gd.changes)(e),o=ad(vd)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return gd.selector(e),e(n.current)}function c(e){id(r,i,a,o)(e)}return[s,c]}function vd(e,t){return cd(t)?t(e.current):t}function yd(e,t){return e.current=rd(rd({},e.current),t),t}function bd(e,t,n){return cd(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var xd={create:_d},Sd={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Cd(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function wd(e){return{}.toString.call(e).includes(`Object`)}function Td(e){return e||kd(`configIsRequired`),wd(e)||kd(`configType`),e.urls?(Ed(),{paths:{vs:e.urls.monacoBase}}):e}function Ed(){console.warn(Od.deprecation)}function Dd(e,t){throw Error(e[t]||e.default)}var Od={configIsRequired:`the configuration object is required`,configType:`the configuration object should be an object`,default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
6
- You are using deprecated way of configuration.
7
-
8
- Instead of using
9
- monaco.config({ urls: { monacoBase: '...' } })
10
- use
11
- monaco.config({ paths: { vs: '...' } })
12
-
13
- For more please check the link https://github.com/suren-atoyan/monaco-loader#config
14
- `},kd=Cd(Dd)(Od),Ad={config:Td},jd=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Md(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Md(e[n],t[n]))}),Ju(Ju({},e),t)}var Nd={type:`cancelation`,msg:`operation is manually canceled`};function Pd(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Nd):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var Fd=[`monaco`],Id=Zu(xd.create({config:Sd,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),Ld=Id[0],Rd=Id[1];function zd(e){var t=Ad.config(e),n=t.monaco,r=Yu(t,Fd);Rd(function(e){return{config:Md(e.config,r),monaco:n}})}function Bd(){var e=Ld(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(Rd({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Pd(qd);if(window.monaco&&window.monaco.editor)return Gd(window.monaco),e.resolve(window.monaco),Pd(qd);jd(Vd,Ud)(Wd)}return Pd(qd)}function Vd(e){return document.body.appendChild(e)}function Hd(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function Ud(e){var t=Ld(function(e){return{config:e.config,reject:e.reject}}),n=Hd(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function Wd(){var e=Ld(function(e){return{config:e.config,resolve:e.resolve,reject:e.reject}}),t=window.require;t.config(e.config),t([`vs/editor/editor.main`],function(t){var n=t.m||t;Gd(n),e.resolve(n)},function(t){e.reject(t)})}function Gd(e){Ld().monaco||Rd({monaco:e})}function Kd(){return Ld(function(e){return e.monaco})}var qd=new Promise(function(e,t){return Rd({resolve:e,reject:t})}),Jd={config:zd,init:Bd,__getMonacoInstance:Kd};u();var Yd={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},Xd={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function Zd({children:e}){return t.createElement(`div`,{style:Xd.container},e)}var Qd=Zd;function $d({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...Yd.wrapper,width:e,height:n},...s},!r&&t.createElement(Qd,null,i),t.createElement(`div`,{ref:a,style:{...Yd.fullWidth,...!r&&Yd.hide},className:o}))}var ef=i($d);function tf(e){s(e,[])}var nf=tf;function rf(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=rf;function af(){}function of(e,t,n,r){return sf(e,r)||cf(e,t,n,r)}function sf(e,t){return e.editor.getModel(lf(e,t))}function cf(e,t,n,r){return e.editor.createModel(t,n,r?lf(e,r):void 0)}function lf(e,t){return e.Uri.parse(t)}function uf({original:e,modified:r,language:i,originalLanguage:o,modifiedLanguage:l,originalModelPath:u,modifiedModelPath:d,keepCurrentOriginalModel:f=!1,keepCurrentModifiedModel:p=!1,theme:m=`light`,loading:h=`Loading...`,options:g={},height:_=`100%`,width:v=`100%`,className:y,wrapperProps:b={},beforeMount:x=af,onMount:S=af}){let[C,w]=c(!1),[T,E]=c(!0),D=n(null),O=n(null),k=n(null),A=n(S),j=n(x),M=n(!1);nf(()=>{let e=Jd.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?F():e.cancel()}),$(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=of(O.current,e||``,o||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=of(O.current,r||``,l||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(r||``):r!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:r||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[r],C),$(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||i||`text`),O.current.editor.setModelLanguage(t,l||i||`text`)},[i,o,l],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=a(()=>{if(!O.current)return;j.current(O.current);let t=of(O.current,e||``,o||i||`text`,u||``),n=of(O.current,r||``,l||i||`text`,d||``);D.current?.setModel({original:t,modified:n})},[i,r,l,e,o,u,d]),P=a(()=>{!M.current&&k.current&&(D.current=O.current.editor.createDiffEditor(k.current,{automaticLayout:!0,...g}),N(),O.current?.editor.setTheme(m),w(!0),M.current=!0)},[g,m,N]);s(()=>{C&&A.current(D.current,O.current)},[C]),s(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return t.createElement(ef,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(uf);function df(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var ff=df,pf=new Map;function mf({defaultValue:e,defaultLanguage:r,defaultPath:i,value:o,language:l,path:u,theme:d=`light`,line:f,loading:p=`Loading...`,options:m={},overrideServices:h={},saveViewState:g=!0,keepCurrentModel:_=!1,width:v=`100%`,height:y=`100%`,className:b,wrapperProps:x={},beforeMount:S=af,onMount:C=af,onChange:w,onValidate:T=af}){let[E,D]=c(!1),[O,k]=c(!0),A=n(null),j=n(null),M=n(null),N=n(C),P=n(S),F=n(),I=n(o),L=ff(u),R=n(!1),z=n(!1);nf(()=>{let e=Jd.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?B():e.cancel()}),$(()=>{let t=of(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&pf.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(pf.get(u)))},[u],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&l&&A.current?.editor.setModelLanguage(e,l)},[l],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let ee=a(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=u||i,n=of(A.current,o||e||``,r||l||``,t||``);j.current=A.current?.editor.create(M.current,{model:n,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(pf.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,r,i,o,l,u,m,h,g,d,f]);s(()=>{E&&N.current(j.current,A.current)},[E]),s(()=>{!O&&!E&&ee()},[O,E,ee]),I.current=o,s(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),s(()=>{if(E){let e=A.current.editor.onDidChangeMarkers(e=>{let t=j.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=A.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function B(){F.current?.dispose(),_?g&&pf.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(ef,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var hf=i(mf);u();function gf(e,t){let n=[];for(let[r,i]of Object.entries(e))r!==t&&(n.push({filePath:`file:///${r}`,content:i}),r.endsWith(`.ts`)&&n.push({filePath:`file:///${r.slice(0,-3)}.js`,content:i}));return n}var _f={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function vf(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),..._f}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function yf({value:e,onChange:t,extraLibs:r=[],path:i=`file:///block.ts`,onDiagnostics:c,readOnly:l=!1,heightPx:u=420,dark:d=!0}){let f=n(null),p=a((e,t)=>{if(f.current=t,vf(t,r),c===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{c(t.editor.getModelMarkers({resource:n.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(i),i()},[r,c]);return s(()=>{let e=f.current;e!==null&&vf(e,r)},[r]),o(hf,{height:u,defaultLanguage:`typescript`,path:i,theme:d?`vs-dark`:`vs`,value:e,onChange:e=>t(e??``),onMount:p,options:{readOnly:l,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function bf(e){return e.some(e=>e.severity>=8)}var xf=[{id:`blank`,name:`Blank script`,get description(){return Y.t(`helpers.buildExamples.blankDescription`)},entry:`main.ts`,files:{"main.ts":`import type { AddonContext } from '@camstack/types'
15
-
16
- /**
17
- * A core block. Runs in its own process, with the same \`ctx\` an addon gets.
18
- * Return a function to release whatever you took (timers, sockets, listeners).
19
- *
20
- * Declaring devices: import { reconcileBlockDevices, exposeBlockDevices } from
21
- * '@camstack/types' and hang them off the shared Blocks integration.
22
- */
23
- export default function block(ctx: AddonContext) {
24
- ctx.logger.info('hello from a core block')
25
-
26
- const timer = setInterval(() => {
27
- ctx.logger.info('tick')
28
- }, 60_000)
29
-
30
- return () => {
31
- clearInterval(timer)
32
- }
33
- }
34
- `}}];function Sf(e){let t=e instanceof Set?e:new Set(e);if(!t.has(`file.ts`))return`file.ts`;let n=2;for(;t.has(`file-${String(n)}.ts`);)n+=1;return`file-${String(n)}.ts`}var Cf=xf.find(e=>e.id===`blank`)?.files[`main.ts`]??`import type { AddonContext } from '@camstack/types'
35
-
36
- export default function block(ctx: AddonContext) {
37
- ctx.logger.info('hello from a core block')
38
- return () => undefined
39
- }
40
- `;function wf({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Y.t(`helpers.restartGate.saveFirstNoProcess`):n?Y.t(`helpers.restartGate.saving`):r?Y.t(`helpers.restartGate.restarting`):t?Y.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Y.t(`helpers.restartGate.disabled`)}u();var Tf=5e3;function Ef(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=Reflect.get(n,`id`),r=Reflect.get(n,`name`),i=Reflect.get(n,`type`),a=Reflect.get(n,`stableId`);typeof e!=`number`||typeof r!=`string`||typeof i!=`string`||t.push({id:e,name:r,type:i,...typeof a==`string`?{stableId:a}:{}})}return t}function Df({blockId:t}){let{t:n}=X(),i=ue(t),a=Rt({addonId:i,projection:`slim`},{refetchInterval:Tf}),s=r(()=>Ef(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(S,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(q,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:o(`code`,{})}})}):o(`ul`,{className:`space-y-3`,children:s.map(t=>o(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${t.id}`,children:e(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[o(En,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(At,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(q,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,o(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}u();function Of(e){return e===`refresh-channel-catalog`||e===`send-tv-schedule-now`||e===`refresh-nordvpn-catalog`||e===`probe-nordvpn-italy`||e===`test-nordvpn-endpoint`||e===`refresh-unifi-catalog`}function kf(e){let t=Date.now();switch(e){case`refresh-channel-catalog`:return{channelCatalogRefreshAt:t};case`send-tv-schedule-now`:return{sendNowAt:t};case`refresh-nordvpn-catalog`:return{nordVpnCatalogRefreshAt:t};case`probe-nordvpn-italy`:return{nordVpnProbeAt:t};case`test-nordvpn-endpoint`:return{nordVpnTestAt:t};case`refresh-unifi-catalog`:return{unifiCatalogRefreshAt:t}}}function Af(e){switch(e){case`refresh-channel-catalog`:return Y.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Y.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Y.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Y.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Y.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Y.t(`build.scriptSettingsPanel.enableUnifi`)}}function jf(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Mf(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Nf(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=jf(e);n!==null&&(t[n]=Mf(e))}return t}function Pf(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Ff({blockId:t}){let{t:n}=X(),i=k(),s=tt({blockId:t},{retry:!1}),l=_t({blockId:t},{refetchInterval:1e4,retry:!1}),u=pt({onSuccess:()=>{l.refetch()}}),d=at(),f=ut(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=Pf(l.data)?l.data:null,C=r(()=>x===null?{}:Nf(x),[x]),w=p??C,T=a(e=>{m(e)},[]),E=p!==null,D=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),O=a(async(e,n)=>{if(Of(e)){b(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:kf(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(Af(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{b(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(S,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):x===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(K,{size:`sm`,variant:`primary`,onClick:D,disabled:!E||u.isPending||y,children:[u.isPending&&o(S,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(Cn,{schema:x,values:w,onChange:T,onAction:O}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var If=`hub`;function Lf({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:f,onCancel:h}){let{t:g}=X(),v=k(),y=A(),{resolvedMode:b}=zt(),C=me({code:t?.code??Cf,files:t?.files,entry:t?.entry}),[w,T]=c(t?.name??``),[D,j]=c(C.files),[M,N]=c(C.entry),[P,F]=c(C.entry),[L,R]=c(t?.placement??If),[z,ee]=c(t?.integrationId??``),[B,V]=c([]),[H,te]=c(!1),[ne,re]=c(`blank`),[U,ie]=c(null),[ae,oe]=c(``),W=D[P]??``,se=e=>{j(t=>({...t,[P]:e}))},ce=Object.keys(D).toSorted(),le=xf.length>1,de=r(()=>[...n?.libs??[],...gf(D,P)],[n?.libs,D,P]),fe=p({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:D,entry:M})}),pe=r(()=>B.filter(e=>e.severity>=8),[B]),he=bf(B),ge=w.trim()===``,_e=t===null?null:me(t),ve=t===null||_e===null||JSON.stringify(D)!==JSON.stringify(_e.files)||M!==_e.entry||w.trim()!==t.name||L!==t.placement||(z.trim()===``?void 0:z.trim())!==t.integrationId,ye=()=>{fe.reset(),f({name:w.trim(),files:D,entry:M,enabled:t?.enabled??!0,placement:L,...z.trim()===``?{}:{integrationId:z.trim()}})},be=()=>{let e=Sf(Object.keys(D));j(t=>({...t,[e]:``})),F(e),ie(e),oe(e)},xe=e=>{ie(e),oe(e)},Se=()=>{if(U===null)return;let e=U,t=ae.trim();if(ie(null),!(t===``||t===e)){if(D[t]!==void 0){F(t);return}j(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),M===e&&N(t),F(t)}},Ce=async e=>{let t=xf.find(t=>t.id===e);if(t===void 0)return;let n=xf.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(D)===JSON.stringify(n.files)&&M===n.entry)&&!await y({title:g(`build.blockEditor.loadExample`,`Load example`),message:g(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:g(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(re(e),j({...t.files}),N(t.entry),F(t.entry),(w.trim()===``||ne===`blank`)&&T(t.id===`blank`?``:t.name))},we=t===null?null:pl(t),Te=wf({existing:t,dirty:ve,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[we!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(q,{variant:ml(we.tone),children:we.label})}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.name`,`Name`)}),o(J,{className:`mt-1`,value:w,onChange:e=>T(e.target.value),placeholder:g(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(J,{className:`mt-1`,value:z,onChange:e=>ee(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&le&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),o(I,{className:`mt-1 w-full`,value:ne,onChange:e=>void Ce(e.target.value),"data-testid":`script-example-select`,children:xf.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(ln,{selectedNodeId:L,onSelect:R,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),L!==If&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(O,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(yn,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[ce.map(t=>U===t?o(J,{value:ae,onChange:e=>oe(e.target.value),onBlur:()=>Se(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Se()),e.key===`Escape`&&(e.preventDefault(),ie(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":g(`build.blockEditor.renameFile`,`Rename file`)},t):e(K,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs ${t===P?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>F(t),onDoubleClick:()=>xe(t),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===M?` · ${g(`build.blockEditor.entry`)}`:``]},t)),o(K,{variant:`unstyled`,type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:be,"data-testid":`script-file-add`,children:g(`build.blockEditor.file`,`+ file`)}),P!==M&&o(K,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>N(P),title:g(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:g(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:g(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(yf,{value:W,onChange:se,path:`file:///${P}`,extraLibs:de,onDiagnostics:V,dark:b===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:g(`build.blockEditor.theNodeReturnedNoType`,`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`)}),pe.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:g(`build.blockEditor.errorsCannotSave`,{count:pe.length})}),pe.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:g(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),pe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:pe.length-5})})]}),fe.data!==void 0&&(fe.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(_,{className:`h-3.5 w-3.5`}),` `,g(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[fe.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(fe.data.line)})}),fe.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),fe.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[g(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,Rf(fe.error)]}),s!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),t!==null&&e(`div`,{className:`space-y-3`,children:[o(Ff,{blockId:t.id}),o(Df,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:`outline`,onClick:()=>fe.mutate(),disabled:fe.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[fe.isPending&&o(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(K,{onClick:ye,disabled:a||he||ge,children:[a&&o(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(K,{variant:`outline`,onClick:()=>d?.(),disabled:Te!==null||d===void 0,title:Te??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(E,{className:`h-4 w-4 animate-spin`}):o(E,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),e(K,{variant:`ghost`,onClick:()=>te(!H),title:g(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,"aria-expanded":H,children:[o(x,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,o(bt,{expanded:H})]}),o(K,{variant:`ghost`,onClick:h,disabled:a,children:g(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[g(`build.blockEditor.errorsCount`,{count:pe.length}),ve&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),ge&&o(q,{variant:`warning`,children:g(`build.blockEditor.nameRequired`,`Name required`)})]}),H&&e(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:t===null?g(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(m,{children:o(yn,{i18nKey:`build.blockEditor.logsOf`,values:{id:ue(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(cn,{addonId:ue(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Rf(e){return e instanceof Error?e.message:String(e)}u();var zf=[`coreBlocks`,`list`],Bf=[`coreBlocks`,`getTypeDefs`],Vf=5e3;function Hf(e){return e instanceof Error?e.message:String(e)}function Uf({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=v(),{t:f}=X(),m=k(),{state:h,openNew:_,openEdit:y,close:b}=Pt({editKey:`block`,newKey:`new`}),[S,C]=c(null),w=A(),[T,D]=c(null),O=l({queryKey:zf,refetchInterval:Vf,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),j=h.mode!==`closed`,M=l({queryKey:Bf,enabled:j,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),N=()=>{O.refetch()},P=n(null),F=O.data;s(()=>{t===void 0||P.current===t||F?.find(e=>e.id===t&&z(e)===`code`)!==void 0&&(P.current=t,y(t),i?.(t))},[t,F,y,i]),s(()=>{a&&(C(null),_(),i?.(null),u?.())},[a,u,i,_]);let I=p({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{C(e.block),y(e.block.id),i?.(e.block.id),N()}}),L=p({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{C(e.block),y(e.block.id),i?.(e.block.id),N()}}),R=p({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:N}),ee=p({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:N}),B=p({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:N}),V=gl((O.data??[]).filter(e=>z(e)===`code`)),H=O.data!==void 0&&V.length===0,te=I.isPending||L.isPending,ne=I.error===null?L.error===null?null:Hf(L.error):Hf(I.error),re=h.mode===`edit`?V.find(e=>e.id===h.id)??(S!==null&&S.id===h.id?S:null):null,U=h.mode===`new`||re===null?null:hl(V,re),ie=r(()=>[{key:`name`,header:f(`build.scriptsTab.name`,`Name`),render:t=>{let n=pl(t),r=sn(t.updatedAt,d);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(q,{variant:ml(n.tone),children:n.label}),o(q,{variant:`info`,children:t.placement}),r!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:f(`common.edited`,{when:r})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:n.detail}),T===t.id&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(yn,{i18nKey:`common.logsOf`,values:{id:ue(t.id)},components:{code:o(`code`,{})}})}),o(cn,{addonId:ue(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:t=>{let n=ee.isPending||R.isPending,r=B.isPending&&B.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[o(K,{variant:`ghost`,onClick:e=>{e.stopPropagation(),C(t),y(t.id),i?.(t.id)},title:f(`common.edit`,`Edit`),children:f(`common.edit`,`Edit`)}),o(K,{variant:`ghost`,onClick:e=>{e.stopPropagation(),B.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?f(`build.scriptsTab.restart`,`Restart`):f(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(E,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(K,{variant:`ghost`,onClick:e=>{e.stopPropagation(),D(T===t.id?null:t.id)},title:f(`build.scriptsTab.logs`,`Logs`),children:o(x,{className:`h-4 w-4`})}),o(K,{variant:`ghost`,onClick:e=>{e.stopPropagation(),ee.mutate({blockId:t.id,enabled:!t.enabled})},disabled:n,title:t.enabled?f(`common.disable`,`Disable`):f(`common.enable`,`Enable`),children:t.enabled?f(`common.disable`,`Disable`):f(`common.enable`,`Enable`)}),o(K,{variant:`ghost`,onClick:e=>{e.stopPropagation(),w({title:f(`build.scriptsTab.deleteThisScript`,`Delete this script?`),message:f(`build.scriptsTab.deleteMessage`,`{{name}} and its source will be deleted. This cannot be undone.`,{name:t.name}),confirmLabel:f(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&R.mutate(t.id)})},title:f(`common.delete`,`Delete`),children:o(g,{className:`h-4 w-4`})})]})}}],[w,T,i,y,R,B.isPending,B.variables,ee,f]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:O.data===void 0?``:_l(V)}),O.error!=null&&o(G,{title:f(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Hf(O.error),onRetry:N}),o(pn,{columns:ie,rows:V,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Et,emptyMessage:H?f(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):O.data===void 0?f(`build.scriptsTab.loadingScripts`,`Loading scripts…`):f(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{C(e),y(e.id),i?.(e.id)}}),o(yt,{open:j,onClose:()=>{I.reset(),L.reset(),B.reset(),C(null),b(),i?.(null)},title:U===null?f(`build.scriptsTab.newScript`,`New script`):f(`build.scriptsTab.edit`,`Edit {{name}}`,{name:U.name}),icon:Je,width:`xl`,testId:`script-editor-panel`,children:o(Lf,{existing:U,typeDefs:M.data,typeDefsLoading:M.isLoading,saving:te,saveError:ne,restarting:B.isPending,restartError:B.error===null?null:Hf(B.error),onRestart:U===null?void 0:()=>B.mutate(U.id),onSave:e=>{let t=U;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),B.reset(),C(null),b(),i?.(null)}})}),R.error!=null&&o(G,{message:Hf(R.error)}),ee.error!=null&&o(G,{message:Hf(ee.error)}),B.error!=null&&o(G,{message:Hf(B.error)})]})}var Wf=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`];function Gf(e){return e!==null&&Wf.some(t=>t===e)}var Kf=[`coreBlocks`,`list`,`build-counts`],qf=[`schedulers`,`list`,`build-counts`],Jf=[`actions`,`list`,`build-counts`],Yf=[`block`,`action`,`scheduler`,`create`,`new`];function Xf(e){return e.filter(e=>z(e)===`code`).length}function Zf(e){return e.filter(e=>lr(e.code)).length}function Qf(e,t){return t===null?e:`${e} (${String(t)})`}function $f(){let{t}=X(),n=k(),[r,i]=bn(),a=r.get(`tab`),s=Gf(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:Kf,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:Xf(u),f=u===void 0?null:Zf(u),p=l({queryKey:Jf,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=l({queryKey:qf,refetchInterval:1e4,queryFn:async()=>n.trpcClient.schedulers.list.query({})}),g=h.data===void 0?null:h.data.length,_=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),v=_.data?.state===`loaded`?_.data.views.length:null,y=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},b=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},x=()=>{i(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},S=e=>{i(()=>{let t=new URLSearchParams(window.location.search);return t.set(`tab`,`custom-device`),t.delete(`block`),t.delete(`create`),t.set(`new`,e),t},{replace:!0})},C=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},w=s===`automations`?t(`build.newAutomation`,`New automation`):s===`actions`?t(`build.newAction`,`New action`):s===`schedulers`?t(`build.newScheduler`,`New scheduler`):t(`build.newScript`,`New script`),T=Dn(`/build`,{t,isAdmin:!0})??{icon:D,title:t(`nav.build`,`Build-your-self`)};return o(On,{icon:T.icon,title:T.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${T.title} sections`,fill:!0,actions:s===`custom-device`?e(K,{type:`button`,onClick:()=>S(`helper`),"data-testid":`build-new-composed`,children:[o(j,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(K,{type:`button`,onClick:x,"data-testid":`build-new`,children:[o(j,{className:`h-4 w-4`}),` `,w]}),sections:[{id:`automations`,label:Qf(t(`build.tabAutomations`,`Automations`),f),ownedParams:Yf,content:o(Al,{onOpenScripts:y,createRequested:s===`automations`&&c,onCreateConsumed:C})},{id:`actions`,label:Qf(t(`build.tabActions`,`Actions`),m),ownedParams:Yf,content:o(Yc,{createRequested:s===`actions`&&c,onCreateConsumed:C})},{id:`schedulers`,label:Qf(t(`build.tabSchedulers`,`Schedulers`),g),ownedParams:Yf,content:o(Yl,{createRequested:s===`schedulers`&&c,onCreateConsumed:C})},{id:`scripts`,label:Qf(t(`build.tabCode`,`Code`),d),ownedParams:Yf,content:o(Uf,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:b,createRequested:s===`scripts`&&c,onCreateConsumed:C})},{id:`custom-device`,label:Qf(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:Yf,content:o(Mu,{createRequested:s===`custom-device`&&c,onCreateConsumed:C})}]})}export{$f as BuildPage};
@@ -1 +0,0 @@
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{Ji as s,La as c,Yi as l}from"./player-overlays-BT0TXPfb.js";import{Ja as u,qa as d}from"./client-rKDh78PS.js";import{_ as f}from"./terminal-BSZfUawf.js";import{Ci as p,Co as m,Di as h,Ff as g,Oi as _,So as v,Ti as y,Uf as b,ki as x,wi as S,wo as C,xo as w}from"./src-BJEmpxo2.js";import{t as T}from"./i18n-a_osePOH.js";import{t as E}from"./useTranslation-BJr-n0es.js";import{Kr as D,Z as O,qr as k}from"./index-GTPwIjSa.js";import{t as A}from"./AdminPage-CERAT6OE.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=d(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(p,{open:!0,onOpenChange:e=>!e&&a(),children:e(y,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(_,{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(x,{className:`min-w-0 break-words`,children:t.title})]})}),r(S,{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(h,{children:r(g,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`common.close`,`Close`)})})]})})}function W(e,t){return e.filter(e=>u(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(g,{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:s}=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:s(`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(c,{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":s(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${l.id}`}),r(b,{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":s(`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?` · ${s(`systemPage.calendars.switchedOff`)}`:``,l!==null&&!l.enabled?` · ${s(`systemPage.calendars.unavailableAtSource`)}`:``]})]})]},t.key)})}),r(k,{to:`/system/integrations?tab=calendars`,className:`block text-[11px] text-primary underline-offset-2 hover:underline`,"data-testid":`calendars-manage-sources`,children:s(`systemPage.calendars.manageSources`,`Manage sources`)})]})}function J({ev:t,color:n,compact:i,onSelect:a}){return r(g,{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(g,{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=v(),c=w({}),u=C(),d=O(`calendar-source`),[p,h]=i(`month`),[_,y]=i(()=>M(new Date)),[b,x]=i(null),S=t(()=>M(new Date),[]),T=o.isSuccess,j=c.isSuccess&&c.data!==void 0?c.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(_,p),[_,p]),H=m({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(d.holders,d.displayNames),z),[N,d.holders,d.displayNames]),X=n((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>c.refetch())},[c,u]),Z=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>c.refetch())},[c,u]),ae=n(()=>y(M(new Date)),[]),oe=n(()=>y(e=>L(e,p,-1)),[p]),se=n(()=>y(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||d.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]}):d.state===`error`&&Y.length===0?e(`p`,{className:`text-sm text-danger`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,d.error]}):Y.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(D,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(k,{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:u.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:u.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(g,{variant:`unstyled`,type:`button`,className:Q,onClick:oe,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(l,{className:`h-4 w-4`})}),r(g,{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(g,{variant:`unstyled`,type:`button`,className:Q,onClick:se,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(s,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:I(_,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:_,events:W,colorById:G,today:S,onSelectEvent:x}):p===`week`?r(re,{anchor:_,events:W,colorById:G,today:S,onSelectEvent:x}):r(ie,{anchor:_,events:W,colorById:G,calName:J,onSelectEvent:x})]})]}),e(A,{icon:f,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[d.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.`),` `,d.error]}):null,$,b===null?null:r(U,{ev:b,calendarName:J.get(b.calendarId)??b.calendarId,color:G.get(b.calendarId)??`#64748B`,onClose:()=>x(null)})]})}export{Y as CalendarsPage,Y as default};