@camstack/addon-admin-ui 1.2.645 → 1.2.647

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 (126) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/assets/Addons-C1rCMYSj.js +5 -0
  3. package/dist/assets/{AdminPage-CgQxV6oS.js → AdminPage-Cve4EeKX.js} +1 -1
  4. package/dist/assets/AdminSectionedPage-V0guU8PD.js +1 -0
  5. package/dist/assets/AiProfiles-COv7z6F-.js +3 -0
  6. package/dist/assets/{BootstrapSettingsForm-BoEmD1zV.js → BootstrapSettingsForm-DtS11lHd.js} +1 -1
  7. package/dist/assets/Build-D5T3SI7b.js +40 -0
  8. package/dist/assets/{Calendars-DJwzxqLu.js → Calendars-BhsUg2gV.js} +1 -1
  9. package/dist/assets/{CameraGrids-BgccN5Pj.js → CameraGrids-CM8Yxxdq.js} +1 -1
  10. package/dist/assets/{Cluster-BsENeR0i.js → Cluster-BP9fRDMS.js} +1 -1
  11. package/dist/assets/CompositionBlockEditor-xQIVx_j0.js +2 -0
  12. package/dist/assets/{CompositionEditorPage-TUBCxwY3.js → CompositionEditorPage-DHUcurin.js} +1 -1
  13. package/dist/assets/Data-DJbrnaPU.js +2 -0
  14. package/dist/assets/DeviceDetail-CaQ51F0f.js +2 -0
  15. package/dist/assets/{Devices-RQLZEgPY.js → Devices-Cf3ZTJ1J.js} +1 -1
  16. package/dist/assets/{EmbedDevicePage-ZLq8d2iA.js → EmbedDevicePage-B9J6ucMX.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-CAIQaXj7.js → EmbedPlayerPage-DP7b5VUK.js} +1 -1
  18. package/dist/assets/History-Dx7eMiJH.js +1 -0
  19. package/dist/assets/Identity-D3MJ59NJ.js +1 -0
  20. package/dist/assets/InstancesTable-bYSuSJuI.js +1 -0
  21. package/dist/assets/IntegrationDetail-c2pjtV64.js +1 -0
  22. package/dist/assets/IntegrationWizard-DpekcaJ2.js +1 -0
  23. package/dist/assets/Integrations-B4MvBXRJ.js +1 -0
  24. package/dist/assets/{Integrations-uNKI4ENy.js → Integrations-Ci8Mqya9.js} +2 -2
  25. package/dist/assets/Library-D0tz7PS_.js +1 -0
  26. package/dist/assets/Locations-BFeQBE-F.js +3 -0
  27. package/dist/assets/Logs-DtjMaCC4.js +1 -0
  28. package/dist/assets/{MaskShapeCanvas-B3zP9xT5.js → MaskShapeCanvas-DsRgL9Jd.js} +1 -1
  29. package/dist/assets/{MotionZonesSettings-DKBKT9aJ.js → MotionZonesSettings-BWECPN2p.js} +1 -1
  30. package/dist/assets/MyAccess-B83bBSQi.js +2 -0
  31. package/dist/assets/Network-BF1ofy4e.js +1 -0
  32. package/dist/assets/NodeAddonsSettingsPanel-BhNHsNDz.js +2 -0
  33. package/dist/assets/Notifications-BDmKjk8l.js +1 -0
  34. package/dist/assets/Pipeline-3BkMMjQC.js +1 -0
  35. package/dist/assets/{PrivacyMaskSettings-CK9hqTRF.js → PrivacyMaskSettings-CxsDkPmw.js} +1 -1
  36. package/dist/assets/Recordings-CdbZm7N3.js +1 -0
  37. package/dist/assets/{RemoteGrid-i8wKPofF.js → RemoteGrid-D9lQtkK4.js} +1 -1
  38. package/dist/assets/{ScanSubnetEditor-DgQG14u4.js → ScanSubnetEditor-D1wWQv5l.js} +1 -1
  39. package/dist/assets/{SceneMonitorEditor-C7BzyuY3.js → SceneMonitorEditor-Bgq5w1mw.js} +1 -1
  40. package/dist/assets/SessionsList-AtYEgm7p.js +2 -0
  41. package/dist/assets/{Showroom-v5DKHm7R.js → Showroom-BCX4Yyt6.js} +1 -1
  42. package/dist/assets/StorageLocationsTable-CInEvHND.js +1 -0
  43. package/dist/assets/{System-jjlBGk9U.js → System-DvinM4KN.js} +1 -1
  44. package/dist/assets/{Templates-DKBo80nE.js → Templates-AolwZ6TI.js} +1 -1
  45. package/dist/assets/{Terminal-CFo4OCRV.js → Terminal-DoBiePC-.js} +5 -5
  46. package/dist/assets/{TrainingProviders-LmHCsEEc.js → TrainingProviders-BKZ0teUD.js} +1 -1
  47. package/dist/assets/{Viewer-KhrX-QoU.js → Viewer-q6dKXR67.js} +1 -1
  48. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BPtmPLBq.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-M59fwoAQ.js} +1 -1
  49. package/dist/assets/{action-draft-Ct8_GVdJ.js → action-draft-DB5j6cca.js} +1 -1
  50. package/dist/assets/{ai-page.helpers-3SnxNBNh.js → ai-page.helpers-CQPhp13c.js} +1 -1
  51. package/dist/assets/{assignment-candidates-CMQomrma.js → assignment-candidates-C5pHZht5.js} +1 -1
  52. package/dist/assets/{authed-media-CS1SYJIb.js → authed-media-Q5YVSoIj.js} +1 -1
  53. package/dist/assets/{board-model-COvoDWAk.js → board-model-CpqXB5lD.js} +1 -1
  54. package/dist/assets/client-Dzzkm60X.js +1114 -0
  55. package/dist/assets/command-vocab-Dk_f6ivd.js +1 -0
  56. package/dist/assets/create-composition-k03FONcQ.js +1 -0
  57. package/dist/assets/device-detail-okAAAxvr.js +1 -0
  58. package/dist/assets/{device-integration-icon-dOu9Eloe.js → device-integration-icon-CzQF4KNa.js} +1 -1
  59. package/dist/assets/device-picker-model-DkSaYUyU.js +1 -0
  60. package/dist/assets/dist-C0Eyz4-R.js +1114 -0
  61. package/dist/assets/{dist-BSIDIvPv.js → dist-Dx1IuG2H.js} +1 -1
  62. package/dist/assets/{format-CnAMMCKO.js → format-BoPK6WDS.js} +1 -1
  63. package/dist/assets/{hostInit-5hZWUgB1.js → hostInit-JJE2ncUY.js} +1 -1
  64. package/dist/assets/i18n-DWUEvjgE.js +1 -0
  65. package/dist/assets/icons-Dhc1mBIs.js +1 -0
  66. package/dist/assets/index-DKKQtgP2.js +4 -0
  67. package/dist/assets/index-DcUA-A3F.css +2 -0
  68. package/dist/assets/{linked-devices-model-C9-KwysR.js → linked-devices-model-XNuspKgG.js} +1 -1
  69. package/dist/assets/{mf-entry-bootstrap-0-da7ca43d.js → mf-entry-bootstrap-0-0cbecd57.js} +2 -2
  70. package/dist/assets/mount-DkSaYUyU.js +1 -0
  71. package/dist/assets/{notification-rule-status-CXntp3K9.js → notification-rule-status-7H1KxBu5.js} +1 -1
  72. package/dist/assets/player-overlays-DpoShe47.js +1 -0
  73. package/dist/assets/remoteEntry-DhUUWtf1.js +1 -0
  74. package/dist/assets/src-CvlhNDJc.js +253 -0
  75. package/dist/assets/step-inspector-model-B1WjzUY-.js +1 -0
  76. package/dist/assets/{use-scenes-feed-BoR1Y-VE.js → use-scenes-feed-Dx37Wfqx.js} +1 -1
  77. package/dist/assets/{use-stationary-objects-DkXKafj7.js → use-stationary-objects-CVyIgKy4.js} +1 -1
  78. package/dist/assets/{useAdminDeviceRemoval-DkVpT6r5.js → useAdminDeviceRemoval-Dfw_WOjy.js} +1 -1
  79. package/dist/assets/useEventInvalidation-DkSaYUyU.js +1 -0
  80. package/dist/assets/{useNodeUrlSelection--lZvqvct.js → useNodeUrlSelection-C7M0t1Bu.js} +1 -1
  81. package/dist/assets/useTemplateSave-BXH2v4XY.js +1 -0
  82. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-T6WBMt1q.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BZIvKvKs.js} +2 -2
  83. package/dist/index.html +8 -8
  84. package/dist/server/addon.js +404 -58
  85. package/package.json +2 -2
  86. package/dist/assets/Addons-CWDe2ysB.js +0 -5
  87. package/dist/assets/AdminSectionedPage-CSjSmB74.js +0 -1
  88. package/dist/assets/AiProfiles-DnluoNPk.js +0 -3
  89. package/dist/assets/Build-DMVoPRyS.js +0 -40
  90. package/dist/assets/CompositionBlockEditor-DudbSZVo.js +0 -2
  91. package/dist/assets/Data-DOpOAfYo.js +0 -2
  92. package/dist/assets/DeviceDetail-CIRWTBj8.js +0 -2
  93. package/dist/assets/History-y3xgB62I.js +0 -1
  94. package/dist/assets/Identity-Dfwm4Ys2.js +0 -1
  95. package/dist/assets/InstancesTable-DB74t0Si.js +0 -1
  96. package/dist/assets/IntegrationDetail-Bg4fgH_7.js +0 -1
  97. package/dist/assets/IntegrationWizard-B_hF-vL9.js +0 -1
  98. package/dist/assets/Integrations-BzHSRaCH.js +0 -1
  99. package/dist/assets/Library-IqKySZef.js +0 -1
  100. package/dist/assets/Locations-BzytI3mX.js +0 -3
  101. package/dist/assets/Logs-BQWbxkE0.js +0 -1
  102. package/dist/assets/MyAccess-t_EwSJ61.js +0 -2
  103. package/dist/assets/Network-w5dWUXr3.js +0 -1
  104. package/dist/assets/NodeAddonsSettingsPanel-Bd8yv-Cb.js +0 -2
  105. package/dist/assets/Notifications-BZPoCLb7.js +0 -1
  106. package/dist/assets/Pipeline-AOTD3jWE.js +0 -1
  107. package/dist/assets/Recordings-Ck1Xvyur.js +0 -1
  108. package/dist/assets/SessionsList-Cg0IcV2U.js +0 -2
  109. package/dist/assets/StorageLocationsTable-Bs0wRBcX.js +0 -1
  110. package/dist/assets/client-BkrADwlo.js +0 -951
  111. package/dist/assets/command-vocab-_m2oGZgY.js +0 -1
  112. package/dist/assets/create-composition-B8m0P0Ka.js +0 -1
  113. package/dist/assets/device-detail-G-NTu_Fh.js +0 -1
  114. package/dist/assets/device-picker-model-Crk-zo39.js +0 -1
  115. package/dist/assets/dist-DD36UXJv.js +0 -951
  116. package/dist/assets/i18n-BArP6ThS.js +0 -1
  117. package/dist/assets/icons-2IlNe3Rh.js +0 -1
  118. package/dist/assets/index-0ukvsxX5.css +0 -2
  119. package/dist/assets/index-B5lClYc_.js +0 -4
  120. package/dist/assets/mount-Crk-zo39.js +0 -1
  121. package/dist/assets/player-overlays-BGlMiuNC.js +0 -1
  122. package/dist/assets/remoteEntry-Oo10s4gX.js +0 -1
  123. package/dist/assets/src-BNDWAXGm.js +0 -230
  124. package/dist/assets/step-inspector-model-DXIzeAZ0.js +0 -1
  125. package/dist/assets/useEventInvalidation-Crk-zo39.js +0 -1
  126. package/dist/assets/useTemplateSave-NBDCe0sx.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{$n as g,Dr as _,Ea as v,Kt as y,Na as b,Ni as x,Nn as S,Qn as C,Wr as w,Yt as T,ba as E,ct as D,gt as O,ir as k,kr as A,ma as j,qi as M,ut as N,wt as P,zi as F,zn as I,zr as L}from"./player-overlays-BGlMiuNC.js";import{Ao as R,Co as z,Do as B,Eo as V,Fa as ee,Gt as H,Io as te,Ji as ne,Mo as re,No as ie,Oo as ae,Po as oe,Pr as se,Ro as ce,So as le,To as ue,Ua as de,Us as fe,Va as pe,Xi as U,Zi as me,_o as he,bo as ge,co as _e,da as ve,go as ye,ho as be,io as xe,jo as Se,ko as Ce,lo as we,mo as Te,oa as Ee,oo as De,os as Oe,po as ke,rc as Ae,ro as je,so as Me,uo as Ne,vo as Pe,wo as Fe,xo as Ie,yo as Le,za as Re}from"./client-BkrADwlo.js";import{t as ze}from"./chevron-down-CBb-F8DT.js";import{t as Be}from"./boxes-k5PsZ3NR.js";import{c as Ve}from"./video-BV-3O_ZC.js";import{n as He,r as Ue,t as We}from"./variable-Cy0obf0C.js";import{Br as Ge,Bu as Ke,Ei as W,En as qe,Gi as Je,Gn as Ye,Gr as Xe,Gu as Ze,Hi as Qe,Hr as $e,Ht as et,Hu as tt,It as nt,K as rt,Ki as it,Kn as at,Kr as ot,Ku as st,Of as ct,Oi as G,Pi as K,Ps as lt,S as ut,Ui as dt,Un as ft,Uo as pt,Ur as mt,Uu as ht,Vt as gt,Vu as _t,Wn as vt,Wr as yt,Wu as bt,Yi as xt,Yr as St,Zd as Ct,_ as wt,af as q,ai as Tt,b as Et,bd as Dt,ci as Ot,cr as kt,df as At,do as jt,dr as Mt,ef as Nt,ei as Pt,es as Ft,ff as It,fo as Lt,fu as Rt,gs as zt,h as Bt,io as Vt,ki as Ht,lo as Ut,lr as Wt,no as Gt,nt as Kt,po as qt,pr as Jt,qi as Yt,qo as Xt,ro as Zt,so as Qt,sr as $t,st as en,tt as tn,ur as nn,w as rn,wn as an,yn as on,zn as sn,zu as cn}from"./src-BNDWAXGm.js";import{t as J}from"./i18n-BArP6ThS.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import{H as ln,Kr as X,Qr as un,Xr as dn,ct as fn,dt as pn,m as mn,p as hn,qr as gn,x as _n}from"./index-B5lClYc_.js";import{t as vn}from"./AdminSectionedPage-CSjSmB74.js";import{n as yn}from"./format-CnAMMCKO.js";import{C as bn,Tt as xn,a as Sn,at as Cn,b as wn,g as Tn,i as En,lt as Dn,n as On,nt as kn,o as An,r as jn,w as Mn,y as Nn}from"./CompositionBlockEditor-DudbSZVo.js";import{a as Pn,c as Z,i as Fn,l as In,n as Ln,o as Rn,r as zn,s as Bn,t as Vn}from"./create-composition-B8m0P0Ka.js";import{a as Hn,i as Un,n as Wn,o as Gn,r as Kn,s as qn}from"./action-draft-Ct8_GVdJ.js";var Jn=`const AUTOMATION_RECIPE =`,Yn=`// 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 Xn(e){return e.includes(Jn)}function Zn(e){let t=e.indexOf(Jn);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 Qn(e){let t=Zn(e);if(t===null)return{ok:!1,reason:J.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:J.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=Le.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?J.t(`helpers.recipeFromCode.schemaMismatch`):J.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function $n(e){let t=Zn(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)}${Yn}${e.slice(i)}`}u();var er=`when`;function tr(e){return e===void 0||e.trim()===``?null:e}function nr(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function rr(e){return e.steps.map(e=>({index:nr(e.path),tone:e.outcome===`ok`?`pass`:e.outcome===`error`?`fail`:`idle`,message:tr(e.message)}))}function ir(e){let t=e.trigger.outcome===`pass`?`pass`:`fail`,n=tr(e.trigger.reason),r=e.conditions.find(e=>e.path===er);return t===`fail`||r===void 0?{tone:t,reason:n}:r.outcome===`fail`?{tone:`fail`,reason:tr(r.reason)??n}:{tone:r.outcome===`pass`?`pass`:`idle`,reason:n}}function ar(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:tr(e.verdict?.reason)}}function or(e){let t=rr(e);return{when:ir(e),thenBlock:ar(e,t),steps:t}}function sr(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}function cr(e){return e===null?{kind:`unknown`}:{kind:`value`,text:Array.isArray(e)?e.join(`, `):String(e)}}function lr(e,t){return t===void 0?null:e===void 0?t:`${e}.${t}`}function ur(e){return{vars:Object.entries(e.trigger.vars).map(([e,t])=>({name:e,value:cr(t)})),conditions:e.conditions.map(e=>({path:e.path,depth:e.path.split(`.`).length-1,kind:e.kind,outcome:e.outcome,reason:tr(e.reason),subject:lr(e.cap,e.fieldPath),operator:e.operator??null,deviceId:e.deviceId??null,expected:e.expected===void 0?null:cr(e.expected),observed:e.observed===void 0?null:cr(e.observed),rawExpected:e.expected,rawObserved:e.observed})),steps:e.steps.map(e=>({index:nr(e.path),kind:e.kind,tone:e.outcome===`ok`?`pass`:e.outcome===`error`?`fail`:`idle`,message:tr(e.message),args:Object.entries(e.args??{}).map(([e,t])=>({name:e,value:cr(t)})),devices:(e.devices??[]).map(e=>({deviceId:e.deviceId,tone:e.outcome===`ok`?`pass`:`fail`,message:tr(e.message)}))}))}}function dr(e){let t=ur(e);return{nodes:new Map(t.conditions.map(e=>[e.path,e])),triggerPath:e.trigger.path??null,vars:t.vars}}var fr=6;function pr(e,t,n){if(typeof e!=`number`||t===void 0||n===void 0)return cr(e);let r=ce(e,t,n);return r===void 0?cr(e):{kind:`value`,text:`${String(Number(r.toPrecision(fr)))} ${n}`}}function mr(e){let t=e.steps.find(e=>e.outcome===`error`),n=t===void 0?tr(e.verdict?.reason)??tr(e.trigger.reason):tr(t.message);return{stepsRun:e.steps.filter(e=>e.outcome===`ok`).length,stepsTotal:e.steps.length,reason:n}}var hr={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},gr={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},_r={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function vr(){let{t:e}=Y();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 yr={done:`success`,missed:`warning`,inactive:`neutral`,"condition-false":`neutral`,failed:`danger`,held:`success`,"gave-up":`danger`,overridden:`info`,"suspended-manual":`warning`};function br(){let{t:e}=Y();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 xr=`max-h-64`;function Sr(){let e=It(),t=At();return e||t}function Cr({expanded:t,onToggle:n}){let{t:r}=Y();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(Nt,{expanded:t}),o(`span`,{children:t?r(`flow.runs.hide`,`Hide runs`):r(`flow.runs.show`,`Show runs`)})]})}function wr({run:t}){let{t:n}=Y(),r=vr(),i=mr(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(G,{variant:hr[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 Tr({traces:t,selectedId:n,onSelect:r}){let{t:i}=Y(),a=vr(),s=br(),l=Sr(),[u,d]=c(null),f=u??!l,p=t===void 0?[]:t.toReversed(),h=p.find(e=>e.runId===n)??null;return e(ft,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:L,children:[o(Cr,{expanded:f,onToggle:()=>d(!f)}),f?t===void 0?o(Ht,{className:`m-3 h-16`}):p.length===0?o(Pt,{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:`${xr} 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(G,{variant:hr[t.outcome],children:a(t.outcome)}):o(G,{variant:yr[t.scheduler],children:s(t.scheduler)}),t.repeat>1&&o(G,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:yn(t.lastAt)})]}),o(`span`,{className:`truncate text-sm text-foreground`,children:t.trigger.reason})]})},t.runId)})}),h!==null&&o(wr,{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(wr,{run:h})]})}function Er(e){return gr[e]}var Dr={pass:`border-success/50`,fail:`border-danger/50`,idle:`border-border`};function Or(e){return Dr[e]}function kr({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`:gr[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 ${_r[i.tone]}`,children:i.reason}),o(`div`,{className:`space-y-2`,children:a})]})}var Ar=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function jr(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 Ar}}function Mr(e){switch(e){case`eq`:return J.t(`helpers.recipeParts.op_eq`);case`ne`:return J.t(`helpers.recipeParts.op_ne`);case`gt`:return J.t(`helpers.recipeParts.op_gt`);case`gte`:return J.t(`helpers.recipeParts.op_gte`);case`lt`:return J.t(`helpers.recipeParts.op_lt`);case`lte`:return J.t(`helpers.recipeParts.op_lte`);case`contains`:return J.t(`helpers.recipeParts.op_contains`);default:return J.t(`helpers.recipeParts.op_in`)}}function Nr(e){return jr(e).map(e=>({value:e,label:Mr(e)}))}je.filter(e=>xe(e).role===`event`),je.filter(e=>xe(e).role===`state`);function Pr(e){return J.t(`${xe(e).i18nKey}.label`)}function Fr(e){return J.t(`${xe(e).i18nKey}.description`)}function Ir(e){return J.t(`${xe(e).i18nKey}.example`)}var Lr={when:{kind:`all`,children:[]},actions:[]};function Rr(e){return De(e)}function zr(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:``};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function Br(e,t,n){return e.map((e,r)=>r===t?n:e)}function Vr(e,t){return e.filter((e,n)=>n!==t)}function Hr(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=Vr(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function Ur(e,t){return{...e,actions:[...t]}}var Wr={pass:`success`,fail:`danger`,"not-evaluated":`neutral`},Gr={pass:`success`,fail:`danger`,idle:`neutral`};function Kr({value:e}){let{t}=Y();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 qr(){let{t:e}=Y();return t=>t===`pass`?e(`flow.runs.nodePass`,`Passed`):t===`fail`?e(`flow.runs.nodeFail`,`Failed`):e(`flow.runs.nodeNotEvaluated`,`Not evaluated`)}function Jr(e){let t=Ie.safeParse(e);return t.success?Mr(t.data):e}function Yr({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(Kr,{value:t.value})})]},t.name))})}function Xr({node:t,vars:n=[],expected:r,observed:i}){let{t:a}=Y(),s=qr(),c=t.subject===null?null:`${t.subject}${t.operator===null?``:` ${Jr(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(G,{variant:Wr[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(Kr,{value:r})]}),i!==null&&e(`span`,{"data-testid":`trace-observed`,children:[a(`flow.runs.observed`,`Observed`),` `,o(Kr,{value:i})]})]}),o(Yr,{testId:`trace-vars`,items:n})]})}function Zr({step:t,deviceName:n}){let{t:r}=Y(),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(G,{variant:Gr[t.tone],children:i}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:t.message})]}),o(Yr,{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(G,{variant:Gr[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 Qr(e){let t=Pn(e.deviceId);if(t.data!==void 0)return zn(t.data,e.cap).find(t=>t.path===e.fieldPath)}function $r({value:t,devices:n,onChange:r}){let{t:i}=Y(),[a,s]=c(!1),l=n.find(e=>e.id===t.deviceId),u=t.deviceId===0?i(`automation.fieldPicker.pickAValue`,`Pick a device value…`):`${l?.name??`#${String(t.deviceId)}`}${t.cap===``?``:` · ${t.cap}.${t.fieldPath}`}`;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:()=>s(!0),children:[o(`span`,{className:`w-0 flex-1 truncate text-left`,children:u}),o(ze,{className:`size-3.5 shrink-0`})]}),a&&o(ei,{value:t,devices:n,onCancel:()=>s(!1),onConfirm:e=>{s(!1),r(e)}})]})}function ei({value:t,devices:n,onCancel:i,onConfirm:a}){let{t:s}=Y(),l=Xt({projection:`slim`}),u=r(()=>new Set(n.map(e=>e.id)),[n]),d=r(()=>e=>u.has(e.id),[u]),[f,p]=c(null),[h,g]=c(!1),[_,v]=c(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!h&&l.status===`success`&&(g(!0),p(xn(l.data).find(e=>e.id===t.deviceId)??null));let y=s(`automation.fieldPicker.title`,`Device value`);return o(Kt,{open:!0,onClose:i,title:y,width:`xl`,fill:!0,testId:`field-picker-dialog`,footer:e(m,{children:[o(K,{variant:`ghost`,onClick:i,children:s(`common.cancel`,`Cancel`)}),o(K,{disabled:f===null||_===null,"data-testid":`field-picker-confirm`,onClick:()=>{f===null||_===null||a({deviceId:f.id,cap:_.cap,fieldPath:_.path})},children:s(`automation.fieldPicker.use`,`Use this value`)})]}),children:o(Cn,{kind:`formula`,enabled:!0,fillHeight:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:y,pickerTargetKind:null},device:f,field:_,deviceFilter:d,onDeviceChange:p,onFieldChange:v})})}var ti=1e4;function ni(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 ri(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function ii({step:t,onChange:n}){let{t:r}=Y(),i=it({},{refetchInterval:ti});if(i.data===void 0)return o(Ht,{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(N,{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(ai,{variable:e,value:t.variables?.[e.name],onChange:r=>n(ri(t,ni(t.variables,e.name,r)))},e.name))})]})}function ai({variable:t,value:n,onChange:r}){let{t:i}=Y(),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(Bn,{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(Z,{className:`w-40`,placeholder:s,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[o(Q,{children:a}),o(q,{className:`w-40`,placeholder:s,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}function oi({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 si({move:t,texts:n}){let{t:r}=Y(),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(oi,{onMove:t.up,label:i.up,reason:i.atFirst,testId:`move-up`,children:o(j,{className:`h-3.5 w-3.5`})}),o(oi,{onMove:t.down,label:i.down,reason:i.atLast,testId:`move-down`,children:o(E,{className:`h-3.5 w-3.5`})})]})}var ci=[`border-chart-series-a`,`border-chart-series-f`,`border-chart-series-b`,`border-chart-series-d`];function li(e,t){let n=ci.length;return(e+1+t%(n-1))%n}function ui(e,t){let n=0;return e.map(e=>V(e)?null:li(t,n++))}function di(e){return ci[e%ci.length]??ci[0]}function fi(e){let t=[],n=0;return z(e,e=>{ue(e)&&(n+=1,e.id!==void 0&&t.push({id:e.id,ordinal:n,leaf:e}))}),t}function pi(e){return Fe(e.when)?!0:e.actions.some(e=>(e.kind===`wait`||e.kind===`cap`)&&e.if!==void 0&&Fe(e.if))}function mi(e){let t=1;for(;e.has(`t${t}`);)t+=1;return`t${t}`}function hi(e,t){if(V(e)){if(!ue(e)||e.id!==void 0)return e;let n=mi(t);return t.add(n),{...e,id:n}}if(e.kind===`not`){let n=hi(e.child,t);return n===e.child?e:{...e,child:n}}let n=e.children.map(e=>hi(e,t));return n.every((t,n)=>t===e.children[n])?e:{...e,children:n}}function gi(e){if(!pi(e))return e;let t=new Set(fi(e.when).map(e=>e.id)),n=hi(e.when,t);return n===e.when?e:{...e,when:n}}function _i(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 vi(e,t){return e.leafIds.filter(e=>!t.includes(e))}u();var yi=[],bi=d(null);function xi({when:e,children:t}){let n=r(()=>fi(e),[e]);return o(bi.Provider,{value:n,children:t})}function Si(){return h(bi)??yi}function Ci(){return h(bi)!==null}var wi=[`triggered-by`];function Ti(e){return{label:Pr(e),description:Fr(e),example:Ir(e)}}function Ei({open:e,onOpenChange:t,mode:n,context:r,underNot:i,treeFull:a,onPick:s}){let{t:c}=Y(),l=Ci();return o(wt,{open:e,onOpenChange:t,title:n===`add`?c(`automation.leafPicker.title`,`Add a row`):c(`automation.leafPicker.changeTitle`,`Change the row type`),context:r,underNot:i,treeFull:a,...l?{}:{hidden:wi},recentKey:`automation-${r}`,textsOf:Ti,categoryLabelOf:e=>c(`automation.leafPicker.category.${e}`),reasonOf:e=>c(`automation.leafPicker.reason.${e}`),onPick:e=>{s(e),t(!1)}})}var Di=`none`;function Oi(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<=0))return Math.round(t*1e3)}function ki({hold:t,modes:n,onChange:r}){let{t:i}=Y(),a={held:i(`automation.hold.held`,`held`),stable:i(`automation.hold.stable`,`stable`)},s=e=>{if(e===Di){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(N,{value:t?.mode??Di,onChange:e=>s(e.target.value),options:[{value:Di,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(q,{type:`number`,min:1,value:String(t.ms/1e3),onChange:e=>{let n=Oi(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(q,{type:`number`,min:0,step:`any`,value:t.tolerance===void 0?``:String(t.tolerance),placeholder:`0`,onChange:e=>{let n=e.target.value.trim(),i=n===``?NaN:Number(n),{tolerance:a,...o}=t;r(Number.isNaN(i)||i<0?o:{...o,tolerance:i})}})]})]})}function Ai({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Y(),c=Li(n,r,i);if(n?.kind===`boolean`)return o(N,{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(N,{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(q,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?o(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return o(q,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function ji({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Y(),s=Li(t,n,r);return o(q,{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 Mi(e){return typeof e==`object`&&!te(e)}function Ni(e){return te(e)?e.value:Mi(e)?e[0]??``:e}function Pi(e){return te(e)?[e.value]:Mi(e)?e:typeof e==`boolean`?[]:[e]}function Fi(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!fe(t)||t===`none`||t===`device`))return Ne(t).length>0?t:void 0}function Ii(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Li(e,t,n){let r=et(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=pt({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=fe(s)?s:void 0,l=Ii(e?.quantity,c);if(l===void 0)return;let u=o?.display;return gt({quantity:l,display:u,capName:n,unitPreferences:r})}function Ri({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Qr(a),c=Nr(s?.kind),l=t.operator===`in`,u=Fi(s),d=u===void 0?void 0:we(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=zi(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...Pi(t.value)]:Ni(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o($r,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[o(Q,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(N,{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(ji,{value:Pi(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?o(ut,{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=rn(e,d);r({...t,value:n.value,unit:n.unit})}}):o(Ai,{value:Ni(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]}),o(ki,{hold:t.for,modes:[`held`,`stable`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})]})}function zi(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Bi=Object.values(Ae).sort((e,t)=>e.localeCompare(t));function Vi({leaf:t,onChange:n}){let{t:r}=Y();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(q,{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(X,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]})}function Hi(){return o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})}function Ui(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 Wi(e){return e.operator===void 0?e.becomes===void 0?`any`:`becomes`:e.operator}var Gi=[`any`,`becomes`,`gt`,`gte`,`lt`,`lte`,`between`,`outside`];function Ki(e){return e===`between`||e===`outside`}function qi(e){if(e.trim()===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function Ji(e){return typeof e==`number`?e:void 0}function Yi({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Qr(a),c=R(t),l=Wi(t),u=Ji(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(Ui(a,_));return}if(e===`becomes`){r(Ui(a,{..._,becomes:``}));return}let t=Ce.safeParse(e);t.success&&r(Ui(a,{..._,operator:t.data,value:Ki(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($r,{value:a,devices:n,onChange:e=>r(Ui(e,f))}),e(`label`,{className:`min-w-[10rem]`,children:[o(Q,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),o(N,{value:l,onChange:e=>v(e.target.value),options:Gi.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(Ai,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(Ui(a,{...f,becomes:e}))})]}),t.operator!==void 0&&!Ki(l)&&e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),o(q,{type:`number`,step:`any`,value:u===void 0?``:String(u),onChange:e=>{let n=qi(e.target.value);n!==void 0&&r(Ui(a,{...f,operator:t.operator,value:n}))}})]}),t.operator!==void 0&&Ki(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(q,{type:`number`,step:`any`,value:d[n]===void 0?``:String(d[n]),onChange:e=>{let i=qi(e.target.value);if(i===void 0)return;let o=[d[0]??0,d[1]??0];o[n]=i,r(Ui(a,{...f,operator:t.operator,value:o}))}})]},n)),o(ki,{hold:c,modes:[`held`,`stable`],onChange:e=>{let{hold:t,...n}=f;r(Ui(a,e===void 0?n:{...n,hold:e}))}}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(q,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(Ui(a,{...f,debounceMs:Xi(e.target.value)}))})]})]})}function Xi(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function Zi({leaf:t,devices:n,onChange:r}){let{t:i}=Y();return e(m,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(N,{value:t.category,onChange:e=>r({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:i(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...Bi.map(e=>({value:e,label:e}))]})]}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(In,{devices:n,selection:`single`,value:t.deviceId===void 0?[]:[t.deviceId],emptyLabel:i(`automation.triggerEditor.anyDevice`,`Any device`),testId:`trigger-event-device`,onChange:e=>r({kind:`device-event`,category:t.category,...e[0]===void 0?{}:{deviceId:e[0]}})})]})]})}function Qi(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 $i(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 ea={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function ta({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),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(Bt,{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(na,{alias:e,source:r,devices:n,onRename:n=>s(aa(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(oa(t.bindings,e))},e)),e(K,{variant:`ghost`,onClick:()=>s({...t.bindings,[ia(t.bindings)]:ea}),children:[o(C,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]}),o(`div`,{className:`flex flex-wrap items-end gap-2`,children:o(ki,{hold:t.for,modes:[`held`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})})]})}function na({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Y(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:n.kind===`global`?$i(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(q,{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(N,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:ea),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(q,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:ra(e.target.value)})})]}):o($r,{value:u,devices:r,onChange:e=>a(Qi(r,e))}),o(K,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(T,{className:`h-3.5 w-3.5`})})]})}function ra(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function ia(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 aa(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function oa(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var sa=`text-xs text-foreground-subtle`;function ca({children:e}){return o(`span`,{className:sa,children:e})}function la(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function ua({devices:t,selected:n,onChange:r}){let{t:i}=Y(),a=t.filter(e=>e.type===Oe.Camera);return e(`div`,{className:`space-y-1`,children:[o(ca,{children:i(`flow.scene.cameras`,`Cameras`)}),o(In,{devices:a,selection:`multiple`,noun:`camera`,value:n,testId:`scene-cameras`,onChange:r})]})}function da({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:sa,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 fa({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=Y();if(n.length===0)return null;let s=e=>{let t=la(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(ca,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(da,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:sa,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var pa=[`animal`,`person`,`vehicle`,`package`,`other`];function ma(e){return pa.find(t=>t===e)??`other`}function ha(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 ga(){let{t:e}=Y();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 _a(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 va=[`automation`,`class-taxonomy`];function ya(){let e=O();return H(l({queryKey:va,retry:!1,staleTime:1/0,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}).data?.taxonomy)}function ba(e,t,n){let r=n?.groups.find(t=>t.key===e),i=r===void 0?oe(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 xa({subject:e,onChange:t}){let{t:n}=Y(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=ya(),a=ba(e.macro,r,i);return a.length===0?null:o(N,{"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===``?ha(e.macro):_a(e.macro,r))}})}function Sa({onChange:e,subject:t}){let{t:n}=Y(),r=lt(),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(N,{"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 Ca=`plate:`,wa=`class:`,Ta=200;function Ea({onChange:e,subject:t}){let{t:n}=Y(),r=Rt({includeCrops:!1,limit:Ta}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,s=ya(),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?``:`${wa}${c}`:`${Ca}${a}`;return o(N,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:u,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...ba(`vehicle`,c,s).map(e=>({value:`${wa}${e.value}`,label:e.label})),...l.map(e=>({value:`${Ca}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(Ca)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(wa)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function Da({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:s}=Y(),c=ga(),l=t.macro===`other`?[]:ie[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(N,{"aria-label":s(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:pa.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=ma(e.target.value);n!==t.macro&&i(ha(n))}})}),o(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?o(q,{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(Sa,{subject:t,onChange:i})}):d&&!n?o(`div`,{className:`w-44`,children:o(Ea,{subject:t,onChange:i})}):!u&&o(`div`,{className:`w-44`,children:o(xa,{subject:t,onChange:i})}),a!==null&&o(K,{variant:`ghost`,onClick:a,title:s(`automation.whenTree.removeClass`,`Remove this class`),children:o(T,{className:`h-3.5 w-3.5`})})]})}function Oa({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:s}=Y(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>o(Da,{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,ha(`person`)]),children:[o(C,{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 ka=100;function Aa({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a=Math.round((t.minScore??0)*ka),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/ka})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(Oa,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),o(ua,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(fa,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(ca,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/ka).toFixed(2)})}),o(v,{min:0,max:ka,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 ja({leaf:t,devices:n,onChange:r}){let{t:i}=Y();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(Oa,{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(ua,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(fa,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(rt,{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 Ma({leaf:t,onChange:n}){let{t:r}=Y();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(ca,{children:r(`flow.scene.every`,`Every`)}),o(Z,{"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(ca,{children:r(`flow.scene.minutes`,`minutes`)})]})}function Na({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a=n.filter(e=>e.type===Oe.Camera),s=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},c=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},l=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(ca,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(In,{devices:a,selection:`single`,noun:`camera`,value:t.deviceId>0?[t.deviceId]:[],testId:`stationary-present-camera`,onChange:e=>{let n=e[0];n!==void 0&&n!==t.deviceId&&l(n)}})]}),o(Oa,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.isParked`,`is parked`),onChange:s}),e(`div`,{className:`flex items-center gap-2`,children:[o(ca,{children:i(`flow.scene.minCount`,`At least`)}),o(Z,{"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(ca,{children:i(`flow.scene.minCountUnit`,`parked objects`)})]}),o(fa,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:c})]})}var Pa=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],Fa=720,Ia=1440;function La(){return{name:``,enabled:!0,priority:0,maxLateMs:ke,profiles:[Ra(`profile-1`,`Every day`)]}}function Ra(e,t){return{id:e,name:t,enabled:!0,days:[...Pa],points:[]}}function za(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function Ba(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function Va(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function Ha(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 Ua(e,t=Date.now()){return Se(t,e.timeZone)}function Wa(e,t,n){let r=Va(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=re(e,n,r);return i===null?null:Ha(i,t.timeZone)}function Ga(e,t,n){return e.kind===`sun`?Wa({...e,offsetMin:0},t,n):null}function Ka(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(Fa,t-n));return{...e,offsetMin:r}}return e}function qa(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 Ja(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function Ya(e){return Ja(Math.floor(e/60),e%60)}function Xa(e,t,n){let r=e.flatMap(e=>{let r=Wa(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?Ia:n.minute}]})}function Za(e,t){let n=Te.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=be(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}var Qa=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],$a=[`sunrise`,`sunset`,`dawn`,`dusk`],eo={from:{kind:`clock`,hh:22,mm:0},to:{kind:`clock`,hh:6,mm:0}};function to(e,t){return{kind:`time-is`,...e===void 0?{}:{between:e},...t===void 0?{}:{days:[...t]}}}function no(e){return e.days??Qa}function ro(e,t){let n=no(e),r=n.includes(t)?n.filter(e=>e!==t):Qa.filter(e=>e===t||n.includes(e)),i=r.length===Qa.length;return to(e.between,i&&e.between!==void 0?void 0:r)}function io(e,t){if(t){let t=e.days!==void 0&&e.days.length===Qa.length;return to(e.between??eo,t?void 0:e.days)}return to(void 0,no(e))}function ao(e,t,n){return to({...e.between??eo,[t]:n},e.days)}function oo(e){return e===`sun`?{kind:`sun`,event:`sunset`,offsetMin:0}:{kind:`clock`,hh:12,mm:0}}function so(e){return e.kind===`date`?oo(`clock`):e}function co(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 lo(e,t){if(t===void 0)return null;let n=ye(e,t)[0];return n===void 0?null:`${n.path}: ${n.message}`}function uo({label:t,testId:n,end:r,onChange:i}){let{t:a}=Y(),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(N,{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(oo(t))}}),r.kind===`clock`&&o(q,{type:`time`,className:`w-28`,"aria-label":s(a(`schedulers.point.time`,`Time`)),value:Ja(r.hh,r.mm),onChange:e=>{let t=qa(e.target.value);t!==null&&t.kind===`clock`&&i(t)}}),r.kind===`sun`&&e(m,{children:[o(N,{wrapperClassName:`relative w-40`,"aria-label":s(a(`schedulers.point.sunEvent`,`Sun event`)),value:r.event,options:$a.map(e=>({value:e,label:a(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=$a.find(t=>t===e.target.value);t!==void 0&&i({...r,event:t})}}),o(Z,{"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 fo({leaf:t,onChange:n}){let{t:r}=Y(),i=t.between,a=no(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(N,{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(io(t,e.target.value===`between`))})]}),i!==void 0&&e(m,{children:[o(uo,{label:r(`automation.timeIs.from`,`From`),testId:`time-is-from`,end:so(i.from),onChange:e=>n(ao(t,`from`,e))}),o(uo,{label:r(`automation.timeIs.to`,`To`),testId:`time-is-to`,end:so(i.to),onChange:e=>n(ao(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:Qa.map(e=>{let i=a.includes(e);return o(K,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,onClick:()=>n(ro(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.`)}),co(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 po(e,t){let n=e.leaf;if(n.kind!==`device-becomes`&&n.kind!==`device-event`)return;let r=t.find(e=>e.id===n.deviceId)?.name;return n.kind===`device-becomes`?r:r===void 0?n.category:`${n.category} · ${r}`}function mo({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a=Si(),s=a.map(e=>e.id),c=vi(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=po(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(_i(t,e.id,s)),children:`${e.ordinal}. ${Pr(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 ho(e){return e.kind===`all`||e.kind===`any`}function go(e){return[`when`,...e].join(`.`)}function _o(e){let t=e.when;return ho(t)?t:{kind:`all`,children:[t]}}function vo(e,t){return{...e,when:t}}function yo(e){return vo(e,_o(e))}function bo(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?bo(e.child,r):null;if(V(e))return null;let i=e.children[n];return i===void 0?null:bo(i,r)}function xo(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=xo(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(V(e))return e;let a=e.children[r];if(a===void 0)return e;let o=xo(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 So(e,t,n){let r=_o(e);return vo(e,xo(r,t,n)??{kind:r.kind,children:[]})}function Co(e){return{kind:e,children:[Rr(`device-is`)]}}function wo(e,t,n){return So(e,t,e=>ho(e)?{kind:e.kind,children:[...e.children,n]}:e)}function To(e,t,n){return So(e,t,()=>n)}function Eo(e,t){return So(e,t,()=>null)}function Do(e,t,n){return So(e,t,e=>ho(e)?{kind:n,children:e.children}:e)}function Oo(e,t){return t.length===0?e:So(e,t,e=>({kind:`not`,child:e}))}function ko(e,t){return So(e,t,e=>e.kind===`not`?e.child:e)}function Ao(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=Rr(t);return ue(e)&&e.id!==void 0&&ue(n)?{...n,id:e.id}:n}function jo(e){let t=_o(e),n=t.children.length===0;return{depth:n?0:ae(t),leaves:n?0:le(t),depthLimit:4,leafLimit:32}}function Mo(e,t){let n=_o(e),r=1,i=n;for(let e of t){let t=bo(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function No(e,t,n){let r=t[t.length-1];if(r===void 0)return e;let i=t.slice(0,-1),a=bo(_o(e),i);if(a===null||!ho(a))return e;let o=r+n;return o<0||o>=a.children.length?e:So(e,i,()=>({kind:a.kind,children:Hr(a.children,r,o)}))}function Po(e,t,n){let r=go(t),i=go(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 Fo(e,t){return V(e)?t(e.kind):e.kind===`not`?`NOT ${Fo(e.child,t)}`:e.children.map(e=>Io(e,t)).join(` · `)}function Io(e,t){return ho(e)?`${e.kind.toUpperCase()} (${Fo(e,t)})`:Fo(e,t)}u();function Lo({leaf:t,devices:n,context:r,underNot:i,toneClass:a,result:s,onNegate:l,move:u,onChange:d,onRemove:f}){let{t:p}=Y(),[m,h]=c(!1),g=ue(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:Pr(t.kind)}),o(`span`,{className:`text-foreground-subtle`,children:p(`automation.leafPicker.changeType`,`Change type`)})]}),o(Ei,{open:m,onOpenChange:h,mode:`change`,context:r,underNot:i,treeFull:!1,onPick:e=>{e!==t.kind&&d(Ao(t,e))}})]}),o(G,{variant:g?`info`:`neutral`,"data-testid":`when-row-nature`,children:g?p(`automation.whenTree.natureEvent`,`Event`):p(`automation.whenTree.natureState`,`State`)}),o(`span`,{className:`flex-1`}),u!==void 0&&o(si,{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(T,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:o(Ro,{leaf:t,devices:n,onChange:d})}),s!==void 0&&o(`div`,{className:`mt-2`,children:s})]})}function Ro({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return o(Yi,{leaf:e,devices:t,onChange:n});case`device-event`:return o(Zi,{leaf:e,devices:t,onChange:n});case`schedule`:return o(Vi,{leaf:e,onChange:n});case`interval`:return o(Ma,{leaf:e,onChange:n});case`manual`:return o(Hi,{});case`detection`:return o(Aa,{leaf:e,devices:t,onChange:n});case`stationary`:return o(ja,{leaf:e,devices:t,onChange:n});case`device-is`:return o(Ri,{leaf:e,devices:t,onChange:n});case`stationary-present`:return o(Na,{leaf:e,devices:t,onChange:n});case`expression`:return o(ta,{leaf:e,devices:t,onChange:n});case`time-is`:return o(fo,{leaf:e,onChange:n});case`triggered-by`:return o(mo,{leaf:e,devices:t,onChange:n})}}u();function zo(e){return e===`any`?`any`:`all`}function Bo(e){return e===`pass`?`pass`:e===`fail`?`fail`:`idle`}function Vo(e,t,n=!0){return e===void 0?t:n?Er(Bo(e)):Or(Bo(e))}function Ho(e,t){return e.run?.nodes.get(go(t))}function Uo({recipe:t,devices:n,onChange:r,run:i=null,hideRule:a=!1,context:s=`trigger`}){let{t:l}=Y(),u=_o(t),d=jo(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=go(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=>Po(t,e,a)),r(No(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(Qo,{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 Wo({node:e,path:t,ctx:n,underNot:r,move:i,rail:a}){return V(e)?o(Go,{leaf:e,path:t,ctx:n,underNot:r,move:i}):e.kind===`not`?o(Zo,{child:e.child,path:t,ctx:n,move:i,rail:a}):o(Qo,{block:e,path:t,ctx:n,underNot:r,move:i,rail:a,budgetText:null,emptyHint:null})}function Go({leaf:e,path:t,ctx:n,underNot:r,move:i}){let a=Ho(n,t),s=n.run!==null&&n.run.triggerPath===go(t)?n.run.vars:void 0;return o(Lo,{leaf:e,devices:n.devices,context:n.leafContext,underNot:r,toneClass:Vo(a?.outcome,`border-border`),result:a===void 0?void 0:o(Ko,{leaf:e,node:a,vars:s}),onNegate:r?null:()=>n.reshape(Oo(n.recipe,t)),...i===null?{}:{move:i},onChange:e=>n.onChange(To(n.recipe,t,e)),onRemove:()=>n.reshape(Eo(n.recipe,t))})}function Ko({leaf:e,node:t,vars:n}){return e.kind===`device-is`&&e.unit!==void 0?o(qo,{leaf:e,node:t,vars:n}):o(Xr,{node:t,vars:n,expected:t.expected,observed:t.observed})}function qo({leaf:e,node:t,vars:n}){let r=Fi(Qr({deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})),i=r===void 0?void 0:we(r),a=t=>t===void 0?null:pr(t,i,e.unit);return o(Xr,{node:t,vars:n,expected:a(t.rawExpected),observed:a(t.rawObserved)})}function Jo({node:e}){return e===void 0?null:o(Xr,{node:e,expected:null,observed:null})}function Yo({expanded:e,onToggle:t}){let{t:n}=Y(),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(Nt,{expanded:e})})}function Xo({node:e}){let{t}=Y(),n=`${t(`automation.whenTree.rowCount`,{count:le(e)})} · ${Fo(e,Pr)}`;return o(`p`,{"data-testid":`when-block-summary`,title:n,className:`break-words text-xs text-foreground-muted sm:truncate`,children:n})}function Zo({child:t,path:n,ctx:r,move:i,rail:a}){let{t:s}=Y(),c=!r.collapsed.has(go(n));return e(`div`,{className:`space-y-1.5 rounded border p-2 ${Vo(Ho(r,n)?.outcome,`border-warning/40`,!1)}`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(Yo,{expanded:c,onToggle:()=>r.toggleCollapsed(n)}),o(G,{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(si,{move:i}),e(K,{variant:`ghost`,onClick:()=>r.reshape(ko(r.recipe,n)),title:s(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[o(He,{className:`h-3.5 w-3.5`}),` `,s(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),o(Jo,{node:Ho(r,n)}),c?o(`div`,{className:`pl-3`,children:o(Wo,{node:t,path:[...n,0],ctx:r,underNot:!0,move:null,rail:a})}):o(Xo,{node:t})]})}function Qo({block:t,path:n,ctx:r,underNot:i,move:a,rail:s,budgetText:l,emptyHint:u}){let{t:d}=Y(),f=n.length===0,p=f||!r.collapsed.has(go(n)),m=Mo(r.recipe,n),[h,g]=c(!1),_=ui(t.children,s),v=[{value:`all`,label:d(`automation.whenTree.allOf`,`All of (AND)`)},{value:`any`,label:d(`automation.whenTree.anyOf`,`Any of (OR)`)}];return e(`div`,{className:`space-y-2 rounded border p-2 ${Vo(Ho(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(Yo,{expanded:p,onToggle:()=>r.toggleCollapsed(n)}),o(`div`,{className:`w-40`,children:o(N,{"aria-label":d(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:v,onChange:e=>r.onChange(Do(r.recipe,n,zo(e.target.value)))})}),l!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:l}),o(`span`,{className:`flex-1`}),a!==null&&o(si,{move:a}),!f&&!i&&o(K,{variant:`ghost`,onClick:()=>r.reshape(Oo(r.recipe,n)),title:d(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!f&&o(K,{variant:`ghost`,onClick:()=>r.reshape(Eo(r.recipe,n)),title:d(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:o(T,{className:`h-3.5 w-3.5`})})]}),o(Jo,{node:Ho(r,n)}),u!==null&&o(`p`,{className:`text-xs text-foreground-subtle`,children:u}),!p&&o(Xo,{node:t}),p&&t.children.length>0&&o(`div`,{className:`space-y-1.5 border-l-2 pl-3 ${di(s)}`,"data-testid":`when-block-rail`,"data-rail":s,children:t.children.map((e,i)=>o(Wo,{node:e,path:[...n,i],ctx:r,underNot:!1,move:r.moveControls([...n,i],t.children.length),rail:_[i]??s},go([...n,i])))}),p&&e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:`outline`,onClick:()=>g(!0),title:d(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[o(C,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addRow`,`Add row`)]}),o(Ei,{open:h,onOpenChange:g,mode:`add`,context:r.leafContext,underNot:i,treeFull:le(_o(r.recipe))>=32,onPick:e=>r.onChange(wo(r.recipe,n,Rr(e)))}),e(K,{variant:`outline`,disabled:!m,onClick:()=>r.onChange(wo(r.recipe,n,Co(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:jo(r.recipe).depthLimit}),children:[o(C,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addBlock`,`Add block`)]})]})]})}var $o={kind:`all`,children:[]};function es(e){return e.kind===`wait`||e.kind===`cap`}function ts(e){return!V(e)&&e.kind!==`not`&&e.children.length===0?null:B(e)}function ns(e){let{if:t,else:n,...r}=e;return r}function rs({step:t,devices:n,devicesState:r,variables:i,onChange:a}){let{t:s}=Y(),c=t.if,l=c===void 0?null:{when:c,actions:[]},u=c===void 0?null:ts(c);return e(`div`,{className:`space-y-2 border-t border-border-subtle pt-2`,children:[o(Mt,{checked:c!==void 0,label:s(`automation.stepGuard.if`,`Only if…`),"aria-label":s(`automation.stepGuard.if`,`Only if…`),onCheckedChange:e=>a(e?{...t,if:$o}:ns(t))}),l!==null&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:s(`automation.stepGuard.hint`,`Checked when this step is reached. If a state cannot be read, the step and its else are both skipped.`)}),o(Uo,{hideRule:!0,context:`guard`,recipe:l,devices:n,onChange:e=>a({...t,if:e.when})}),u!==null&&o(W,{variant:`warning`,message:u}),o(Mt,{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(as,{nested:!0,actions:t.else,devices:n,...r===void 0?{}:{devicesState:r},...i===void 0?{}:{variables:i},allowedKinds:[`cap`,`wait`],onChange:e=>a({...t,else:e.filter(es)})})})]})]})}var is=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`action`,labelKey:`automation.actionList.kindAction`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function as({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:s,stepResults:c,nested:l=!1,onChange:u}){let{t:d}=Y(),f=is.filter(e=>i===void 0||i.includes(e.value)),p={up:d(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),down:d(`automation.actionList.runThisStepLater`,`Run this step later`),atFirst:d(`automation.actionList.alreadyFirstStep`,`This step already runs first`),atLast:d(`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:d(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((i,m)=>e(`div`,{className:`space-y-2 rounded border p-3 ${s===void 0?`border-border`:Er(s[m]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(G,{variant:`default`,children:m+1}),e(`label`,{className:`w-40`,children:[o(Q,{children:d(`automation.actionList.step`,`Step`)}),o(N,{value:i.kind,onChange:e=>u(Br(t,m,zr(os(e.target.value)))),options:f.map(e=>({value:e.value,label:d(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(si,{move:{up:m===0?null:()=>u(Hr(t,m,m-1)),down:m===t.length-1?null:()=>u(Hr(t,m,m+1))},texts:p}),o(K,{variant:`ghost`,onClick:()=>u(Vr(t,m)),title:d(`automation.actionList.removeThisStep`,`Remove this step`),children:o(T,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Q,{children:d(`automation.actionList.seconds`,`Seconds`)}),o(q,{type:`number`,min:0,max:300,value:String(i.seconds),onChange:e=>u(Br(t,m,{...i,seconds:Number(e.target.value)}))})]}),i.kind===`code`&&e(`label`,{className:`block`,children:[o(Q,{children:d(`automation.actionList.code`,`Code`)}),o(Jt,{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=>u(Br(t,m,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),i.kind===`cap`&&o(Rn,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>u(Br(t,m,{...e,...i.if===void 0?{}:{if:i.if},...i.else===void 0?{}:{else:i.else}}))}),i.kind===`action`&&o(ii,{step:i,onChange:e=>u(Br(t,m,e))}),!l&&(i.kind===`wait`||i.kind===`cap`)&&o(rs,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>u(Br(t,m,e))}),c?.[m]!==void 0&&o(Zr,{step:c[m],deviceName:e=>n.find(t=>t.id===e)?.name??`#${String(e)}`})]},`${i.kind}-${String(m)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(K,{variant:`outline`,onClick:()=>u([...t,zr(f[0]?.value??`cap`)]),children:[o(C,{className:`h-4 w-4`}),` `,d(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:d(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function os(e){return is.find(t=>t.value===e)?.value??`cap`}function ss(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function cs(e,t){return Pe(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.hintKey??e.name}`,e.description)}))}function ls(e){return e.some(e=>e.required===!0&&e.default===void 0)}function us(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function ds(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function fs(e,t){return e.filter(e=>e.required===!0&&!ds(t[e.name])).map(e=>e.name)}function ps(e,t){let n={};for(let r of e){let e=t[r.name];ds(e)&&(n[r.name]=e)}return n}u();function ms({variable:e,value:t,onChange:n}){let{t:r}=Y(),i=e.label??e.name;return e.type===`number`?o(Z,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?o(Bn,{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(Bn,{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(q,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function hs({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:s}=Y(),[l,u]=c(()=>us(n)),d=fs(n,l);return o(Ge,{open:!0,onOpenChange:e=>!e&&a(),children:e($e,{"aria-label":s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(Xe,{children:[o(ot,{children:s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),o(mt,{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(ms,{variable:t,value:l[t.name],onChange:e=>u({...l,[t.name]:e})})]},t.name))}),e(yt,{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(ps(n,l)),children:[r?o(_,{className:`h-4 w-4 animate-spin`}):o(g,{className:`h-4 w-4`}),` `,s(`actions.editor.runNow`,`Run now`)]})]})]})})}var gs=[`number`,`string`,`boolean`,`select`];function _s(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function vs(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 ys(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function bs(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function xs({variables:t,onChange:n,onRename:r}){let{t:i}=Y(),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(ft,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:We,actions:e(K,{variant:`outline`,size:`sm`,onClick:()=>n([...t,Hn(t)]),children:[o(C,{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(q,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!Un(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(q,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,bs(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(Bn,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:gs.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=gs.find(t=>t===e.target.value);t!==void 0&&s(l,_s(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(Ss,{variable:c,onChange:e=>s(l,ys(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(q,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>s(l,vs(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(T,{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 Ss({variable:e,onChange:t}){let{t:n}=Y(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(Z,{"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(Bn,{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(q,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var Cs=5e3;function ws(e){return e.kind===`cap`||e.kind===`wait`}function Ts(e){return e instanceof Error?e.message:String(e)}function Es(){let{t:e}=Y();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 Ds({entry:t,onClose:i,onSaved:a,preset:l=null}){let{t:u}=Y(),d=f(),p=D(),h=Fn(),v=Es(),[y,b]=c(()=>Kn(t)),x=n(!1);s(()=>{if(t!==null||l!==`trigger-alarm`||x.current)return;let e=h.find(e=>e.type===Oe.AlarmPanel);e!==void 0&&(x.current=!0,b(qn(e.id,u(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[h,t,l,u]);let[S,C]=c(null),[w,E]=c(!1),O=t!==null&&t.readOnly,k=()=>{d.invalidateQueries({queryKey:[[`actions`]]})},j=Qe({onSuccess:e=>{k(),a(e.action.id)}}),M=xt({onSuccess:k}),N=dt({onSuccess:()=>{k(),i()}}),P=Yt({onSuccess:k}),F=Je({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Cs}),I=F.data?.traces.find(e=>e.runId===S)??null,L=r(()=>I===null?null:or(I),[I]),R=r(()=>I===null?null:ur(I).steps,[I]),z=Wn(y),B=r(()=>ss(y.variables,u),[y.variables,u]),V=j.isPending||M.isPending,ee=j.error??M.error??N.error??P.error,H=ls(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(A,{className:`h-4 w-4 text-foreground-muted`}),o(q,{"aria-label":u(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:y.name,disabled:O,placeholder:u(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>b({...y,name:e.target.value})}),o(G,{variant:O?`info`:`primary`,children:O?t?.addonId??``:u(`actions.source.internal`,`Internal`)})]}),O?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(xs,{variables:y.variables,onChange:e=>b({...y,variables:e}),onRename:(e,t)=>b(Gn(y,e,t))}),o(kr,{step:`steps`,title:u(`actions.editor.steps`,`Steps`),trace:L===null?null:L.thenBlock,children:o(as,{actions:y.steps,devices:h,allowedKinds:[`cap`,`wait`],stepTones:L===null?void 0:y.steps.map((e,t)=>sr(L,t)??`idle`),stepResults:R===null?void 0:y.steps.map((e,t)=>R.find(e=>e.index===t)),variables:B,onChange:e=>b({...y,steps:e.filter(ws)})})})]}),!z.ok&&!O&&y.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:v(z.reason)}),ee!==null&&o(W,{message:Ts(ee)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!O&&e(K,{onClick:()=>{z.ok&&(t===null?j.mutate({action:z.input}):M.mutate({actionId:t.id,action:z.input}))},disabled:V||!z.ok,children:[V&&o(_,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),t!==null&&e(K,{variant:`outline`,disabled:P.isPending,onClick:()=>H?E(!0):P.mutate({actionId:t.id}),children:[o(g,{className:`h-4 w-4`}),` `,u(`actions.editor.runNow`,`Run now`)]}),t!==null&&!O&&e(K,{variant:`ghost`,disabled:N.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&&N.mutate({actionId:t.id})})},children:[o(T,{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(Tr,{traces:t===null?[]:F.data?.traces,selectedId:S,onSelect:C})}),w&&t!==null&&o(hs,{actionName:t.name,variables:t.variables??[],running:P.isPending,onCancel:()=>E(!1),onRun:e=>{P.mutate({actionId:t.id,variables:e}),E(!1)}})]})}u();var Os=5e3;function ks(e){return e instanceof Error?e.message:String(e)}function As(){let{t:e}=Y();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 js({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Y(),[a]=un(),c=f(),l=As(),{state:u,openNew:d,openEdit:p,close:h}=tn({editKey:`action`,newKey:`new`}),_=it({},{refetchInterval:Os}),v=Yt({onSuccess:()=>void c.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(d(),n?.())},[t,n,d]);let y=_.data??[],b=u.mode===`edit`?y.find(e=>e.id===u.id)??null:null,x=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(G,{variant:`info`,children:e.addonId}):o(G,{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:`-`}):yn(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(G,{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:v.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),v.mutate({actionId:t.id})},children:[o(g,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[v,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.`)}),v.error!=null&&o(W,{message:ks(v.error)}),_.data===void 0?_.error==null?o(Ht,{className:`h-24 w-full`}):o(W,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:ks(_.error),onRetry:()=>void _.refetch()}):y.length===0?o(Pt,{icon:A,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(C,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(m,{children:[_.error!=null&&o(W,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:ks(_.error),onRetry:()=>void _.refetch()}),o(Ye,{columns:x,rows:y,rowKey:e=>e.id,pageSize:25,maxBodyHeight:at,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>p(e.id)})]})]}):o(Ds,{entry:b,onClose:h,onSaved:p,preset:u.mode===`new`?a.get(`preset`):null},b?.id??`new`)}u();function Ms({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Y(),[l,u]=c(!1),d=D(),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?ze:F,{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(Ve,{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(sn,{maxHeight:420,children:t})})]})}var Ns=[`single`,`restart`,`queued`,`parallel`,`cooldown`],Ps=2,Fs=30;function Is(e){return e.runMode??{mode:`single`}}function Ls(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function Rs(e){switch(e){case`queued`:return{mode:`queued`,max:Ps};case`parallel`:return{mode:`parallel`,max:Ps};case`cooldown`:return{mode:`cooldown`,minutes:Fs};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function zs(e){return Ns.find(t=>t===e)??`single`}function Bs({value:t,onChange:n}){let{t:r}=Y(),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(Bn,{widthClass:`w-56`,value:t.mode,options:Ns.map(e=>({value:e,label:i[e]})),onChange:e=>n(Rs(zs(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(Z,{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(Z,{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 Vs;function Hs(){return Vs??=_e(se),Vs}function Us(e,t=Hs()){return Me(e,t)}u();var Ws=`hub`,Gs=5e3;function Ks({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=Y(),[p,m]=c(t?.name??``),[h,g]=c(()=>yo(n)),v=e=>g(gi(e)),[y,b]=c(!1),[x,C]=c(null),w=Qt({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:Gs}),T=w.data?.traces.find(e=>e.runId===x)??null,E=r(()=>T===null?null:or(T),[T]),D=r(()=>cs(h.when,f),[h.when,f]),O=r(()=>T===null?null:dr(T),[T]),k=r(()=>T===null?null:ur(T).steps,[T]),A=Fn(),j=ge(h),M=r(()=>qs(h),[h]),N=r(()=>Js(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),P=Dt().data,F=r(()=>M===null?lo(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(xi,{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(q,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(kr,{step:`when`,title:f(`automation.automationEditor.when`,`When`),trace:E===null?null:E.when,children:o(Uo,{recipe:h,devices:A,run:O,onChange:v})}),o(kr,{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(as,{actions:h.actions,devices:A,variables:D,stepTones:E===null?void 0:h.actions.map((e,t)=>sr(E,t)??`idle`),stepResults:k===null?void 0:h.actions.map((e,t)=>k.find(e=>e.index===t)),onChange:e=>v(Ur(h,e))})}),o(kr,{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(Bs,{value:Is(h),onChange:e=>v(Ls(h,e))})}),o(Ms,{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:Ws})},disabled:i||L,children:[i&&o(_,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(K,{variant:`ghost`,onClick:()=>b(!y),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":y,children:[o(S,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,o(Nt,{expanded:y})]}),o(K,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),I&&o(G,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),y&&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(X,{i18nKey:`common.logsOf`,values:{id:ne(t.id)},components:{code:o(`code`,{})}})}),o(an,{addonId:ne(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}),o(`div`,{className:`order-first lg:order-last`,children:o(Tr,{traces:t===null?[]:w.data?.traces,selectedId:x,onSelect:C})})]})}function qs(e){let t=Le.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?J.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Js(e,t){let n=Us(t);if(!n.ok)return{code:null,error:n.error};try{return{code:he({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Ys(e){if(!e.enabled)return{tone:`idle`,label:J.t(`helpers.coreBlockStatus.disabled`),detail:J.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:J.t(`helpers.coreBlockStatus.running`),detail:J.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??J.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??J.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??J.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Xs(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Zs(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Qs(e){let t=e=>{let t=Ys(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 $s(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Ys(e).tone===`error`).length,n=e.filter(e=>Ys(e).tone===`ok`).length,r=[J.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(J.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(J.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var ec=3e4;function tc({block:t,logsOpen:n,unreadable:r}){let i=b(),{t:a}=Y(),s=Ys(t),c=nt(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(G,{variant:Xs(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(X,{i18nKey:`common.logsOf`,values:{id:ne(t.id)},components:{code:o(`code`,{})}})}),o(an,{addonId:ne(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var nc=2;function rc(e){let t=[];if(z(e.when,e=>{ue(e)&&t.push(Pr(e.kind))}),t.length===0)return le(e.when)===0?``:J.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,nc).join(`, `),i=n.length-nc;return i>0?`${r} +${i}`:r}function ic({recipe:e}){let{t}=Y();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=rc(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function ac({blockId:t}){let{t:n}=Y(),r=Qt({blockId:t},{refetchInterval:ec});if(r.data===void 0)return r.error===null||r.error===void 0?o(Ht,{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:[yn(i.lastAt),a&&o(G,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function oc({block:e,disabled:t,onToggle:n}){let{t:r}=Y();return o(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(Mt,{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 sc({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=Y();return o(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(on,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:k,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:g,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:S,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:T,danger:!0,separatorBefore:!0,onClick:r}]})})}function cc({onCreate:t}){let{t:n}=Y();return o(Pt,{icon:P,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(K,{onClick:t,"data-testid":`automation-empty-new`,children:[o(C,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();var lc=[`coreBlocks`,`list`],uc=5e3;function dc(e){return e instanceof Error?e.message:String(e)}function fc({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:a}=Y(),u=O(),{state:d,openNew:f,openEdit:m,close:h}=tn({editKey:`block`,newKey:`new`}),g=D(),[_,v]=c(null),y=d.mode!==`closed`;s(()=>{n&&(f(),i?.())},[n,i,f]);let b=l({queryKey:lc,refetchInterval:uc,queryFn:async()=>(await u.trpcClient.coreBlocks.list.query({})).blocks}),x=()=>{b.refetch()},S=e=>{h(),x(),fn({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)}),T=p({mutationFn:e=>u.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:x}),E=p({mutationFn:e=>u.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:x}),k=p({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:$n(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{h(),x(),t(e.block.id)}}),A=b.data,j=Qs((A??[]).filter(e=>Xn(e.code))),M=A!==void 0&&j.length===0,N=d.mode===`edit`?j.find(e=>e.id===d.id)??null:null,F=d.mode===`edit`&&A!==void 0&&N===null;s(()=>{F&&h()},[F,h]);let I=N===null?null:Qn(N.code),L=C.error===null?w.error===null?k.error===null?null:dc(k.error):dc(w.error):dc(C.error),R=r(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=Qn(e.code);return o(tc,{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=Qn(e.code);return o(ic,{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(ac,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>o(oc,{block:e,disabled:E.isPending,onToggle:t=>E.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=Qn(e.code);return o(sc,{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&&T.mutate(e.id)})}})}}],[g,_,m,T,E,a]);return y?d.mode===`edit`&&N===null?o(Ht,{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(P,{className:`h-4 w-4 text-foreground-muted`}),N===null?a(`build.automationsTab.newAutomation`,`New automation`):a(`build.automationsTab.edit`,`Edit {{name}}`,{name:N.name})]}),o(Ks,{existing:N,initialRecipe:I!==null&&I.ok?I.recipe:Lr,saving:C.isPending||w.isPending,saveError:L,ejecting:k.isPending,onSave:e=>{N===null?C.mutate(e):w.mutate({blockId:N.id,block:e})},onEject:()=>{N!==null&&k.mutate(N)},onCancel:()=>{C.reset(),w.reset(),k.reset(),h()}},N?.id??`new`),T.error!=null&&o(W,{message:dc(T.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:A===void 0?``:$s(j)}),b.error!=null&&o(W,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:dc(b.error),onRetry:x}),M?o(cc,{onCreate:f}):o(Ye,{columns:R,rows:j,rowKey:e=>e.id,pageSize:25,maxBodyHeight:at,emptyMessage:A===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>m(e.id)}),T.error!=null&&o(W,{message:dc(T.error)}),E.error!=null&&o(W,{message:dc(E.error)})]})}var pc={kind:`all`,children:[]};function mc({value:t,devices:n,label:r,onChange:i}){let{t:a}=Y(),s=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[o(Mt,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?pc: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(Uo,{recipe:s,devices:n,onChange:e=>i(e.when)})]})]})}var hc=[`sunrise`,`sunset`,`dawn`,`dusk`],gc=6e4;function _c(e){return e.kind===`cap`||e.kind===`wait`}function vc(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 yc({point:t,devices:n,site:r,localDate:i,issues:a,onChange:s,onRemove:c}){let{t:l}=Y(),u=t.at,d=u.kind===`sun`?Wa(u,r,i):null,f=Ga(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(N,{"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(vc(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.when`,`When`)}),o(N,{"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(q,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:Ja(u.hh,u.mm),onChange:e=>{let t=qa(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(N,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:hc.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=hc.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(Z,{"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:Ya(d),zone:r.timeZone})})]}),e(K,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[o(T,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&o(as,{actions:t.steps,devices:n,allowedKinds:[`cap`,`wait`],onChange:e=>s({...t,steps:e.filter(_c)})}),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(N,{"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*gc}:{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(Z,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:p.graceMs/gc,onValue:e=>{e!==null&&s({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*gc))}})}})]})]}),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 bc=5e3,xc=600,Sc=6e4,Cc={timeZone:`UTC`,location:null};function wc(e){return e instanceof Error?e.message:String(e)}function Tc(e){if(e===null)return La();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function Ec(e,t){let[n,r]=c(e);return s(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Dc(e,t){return t(`schedulers.day.${e}`,e)}function Oc({entry:t,onClose:n,onSaved:i}){let{t:a}=Y(),s=f(),l=D(),u=Fn(),d=Dt(),p=d.data??Cc,[m,h]=c(()=>Tc(t)),[g,v]=c(()=>m.profiles[0]?.id??``),[y,b]=c(null),[x,S]=c(null),w=()=>{s.invalidateQueries({queryKey:[[`schedulers`]]})},E=Ke({onSuccess:e=>{w(),i(e.scheduler.id)}}),O=st({onSuccess:w}),k=_t({onSuccess:()=>{w(),n()}}),A=ht({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:bc}),j=r(()=>Za(m,p),[m,p]),N=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),P=Ec(j.ok?j.input:null,xc),F=cn(P===null?{scheduler:m}:t===null?{scheduler:P}:{scheduler:P,schedulerId:t.id},{enabled:P!==null&&N&&d.data!==void 0}),I=m.profiles.find(e=>e.id===g)??m.profiles[0],L=I===void 0?-1:m.profiles.indexOf(I),R=Ua(p),z=I?.points.find(e=>e.id===y)??null,B=I===void 0||z===null?-1:I.points.indexOf(z),V=j.ok?[]:j.issues,ee=e=>V.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=Wa(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)} (${Ya(t)})`:Ja(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`&&Ga(e.at,p,R)!==null}]}),[I,p,R,a]),re=r(()=>I===void 0?[]:Xa(I.points,p,R),[I,p,R]),ie=(e,t)=>{let n=I?.points.find(t=>t.id===e);n!==void 0&&te({...n,at:Ka(n.at,t,Ga(n.at,p,R))})},ae=e=>{if(I===void 0)return;let t=Ba(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));H({...I,points:[...I.points,za(e,t,720)]}),b(t)},oe=()=>{let e=Ba(`profile`,m.profiles.map(e=>e.id));h({...m,profiles:[...m.profiles,Ra(e,a(`schedulers.profile.newName`,`New profile`))]}),v(e),b(null)},se=E.isPending||O.isPending,ce=E.error??O.error??k.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(M,{className:`h-4 w-4 text-foreground-muted`}),o(q,{"aria-label":a(`schedulers.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,placeholder:a(`schedulers.editor.namePlaceholder`,`What this scheduler does`),onChange:e=>h({...m,name:e.target.value})})]}),e(ft,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[o(vt,{label:a(`schedulers.editor.enabled`,`Enabled`),children:o(Mt,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>h({...m,enabled:e})})}),o(vt,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:o(Z,{"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(vt,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:o(Z,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/Sc,onValue:e=>{e!==null&&h({...m,maxLateMs:Math.round(e*Sc)})}})})]}),e(`div`,{className:`p-3`,children:[o(mc,{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})}}),ee(`activeWhen`).map(e=>o(`p`,{className:`mt-1 text-xs text-warning`,children:e.message},e.message))]})]}),o(ft,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(K,{variant:`outline`,size:`sm`,onClick:oe,children:[o(C,{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($t,{value:I.id,onValueChange:e=>{v(e),b(null)},appearance:`pills`,children:[o(Wt,{children:m.profiles.map(e=>o(nn,{value:e.id,children:e.name},e.id))}),e(kt,{value:I.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(q,{"aria-label":a(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:I.name,onChange:e=>H({...I,name:e.target.value})}),o(Mt,{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(T,{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:Pa.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):Pa.filter(t=>t===e||I.days.includes(t))}),children:Dc(e,a)},e)})}),ee(`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(mc,{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(Et,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:ne,bands:re,selectedId:y,onSelect:b,onMove:ie}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:`outline`,size:`sm`,onClick:()=>ae(`edge`),children:[o(C,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(K,{variant:`outline`,size:`sm`,onClick:()=>ae(`hold`),children:[o(C,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(K,{variant:`outline`,size:`sm`,onClick:()=>ae(`release`),children:[o(C,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),o(G,{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(yc,{point:z,devices:u,site:p,localDate:R,issues:ee(`profiles.${String(L)}.points.${String(B)}`),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:Ya(e.fromMinute),to:Ya(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)}`))}),!j.ok&&m.name!==``&&V.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:V.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))}),ce!==null&&o(W,{message:wc(ce)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(K,{onClick:()=>{j.ok&&(t===null?E.mutate({scheduler:j.input}):O.mutate({schedulerId:t.id,scheduler:j.input}))},disabled:se||!j.ok||d.data===void 0,children:[se&&o(_,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(K,{variant:`ghost`,disabled:k.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&&k.mutate({schedulerId:t.id})})},children:[o(T,{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(Tr,{traces:t===null?[]:A.data?.traces,selectedId:x,onSelect:S})})]})}u();var kc=5e3;function Ac(e){return e instanceof Error?e.message:String(e)}function jc({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Y(),a=f(),{state:c,openNew:l,openEdit:u,close:d}=tn({editKey:`scheduler`,newKey:`new`}),p=bt({},{refetchInterval:kc}),m=tt({},{refetchInterval:kc}),h=Ze({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(Mt,{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(G,{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=>yn(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(W,{message:Ac(h.error)}),p.data===void 0?p.error==null?o(Ht,{className:`h-24 w-full`}):o(W,{title:i(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:Ac(p.error),onRetry:()=>void p.refetch()}):g.length===0?o(Pt,{icon:M,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(C,{className:`h-4 w-4`}),` `,i(`schedulers.list.new`,`New scheduler`)]})}):o(Ye,{columns:y,rows:g,rowKey:e=>e.id,pageSize:25,maxBodyHeight:at,emptyMessage:i(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):o(Oc,{entry:_,onClose:d,onSaved:u},_?.id??`new`)}async function Mc(e,t){let n=`${de}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var Nc=10,Pc=400;async function Fc(e,t,n=Pc){for(let r=0;r<Nc;r+=1){let r=await Mc(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var Ic=`media-player`;function Lc(e){return e===Oe.MediaPlayer?`media-source`:`none`}function Rc(e){return e===Oe.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[Oe.MediaPlayer],accept:[{cap:Ic,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[Ic],exclude:[]}:null}function zc(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:Ic,fields:{},commands:Object.fromEntries(Object.keys(ve()).map(t=>[t,{kind:`forward`,source:e.source,cap:Ic,method:t}]))}]}function Bc(e,t){let n=e===Oe.MediaPlayer?zc(t):[];return{target:{kind:`new`,type:e},features:n}}u();function Vc({onTitle:t}){let{t:n}=Y(),r=b(),i=dn(),a=Vn(),l=zt(),u=Ft({addonId:`composer`}),[d,f]=c(Oe.Sensor),[p,m]=c(``),[h,g]=c([]),[_,v]=c(null),y=h[0]??null,x=Rc(d),S=Bc(d,y);s(()=>{t(n(`helper.newDevice`))},[t,n]);let C=async()=>{v(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:S}}),r=await Fc(t.id,async()=>(await u.refetch()).data??u.data);if(r===null){v(n(`helper.devicePending`));return}e!==``&&await l.mutateAsync({deviceId:r,name:e}),i(hn(r),{replace:!0})}catch(e){v(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(N,{value:d,onChange:e=>{let t=Object.values(Oe).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(Oe).map(e=>({value:e,label:ct(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(q,{"aria-label":n(`compositionEditor.name`),value:p,onChange:e=>m(e.target.value)})]})]}),x!==null&&e(`div`,{className:`flex flex-col gap-1`,"data-testid":`device-create-source`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:n(`helper.deviceSource.${Lc(d)}`)}),o(Cn,{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 Hc({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=Y(),u=kn(!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=>[Re({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[Re(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:bn(u.value,S)}:u,[u,S]),w=jn(t,d),T=u.kind===`known`?Mn(u.value,w,!1):null,E=t.build(d),D=En(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(Re(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(q,{"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:[Dn(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:Dn(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(An,{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(wn,{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 Uc=`preset`;function Wc({mode:e,onTitle:t}){return o(e===`helper`?Gc:Vc,{onTitle:t})}function Gc({onTitle:e}){let{t}=Y(),r=dn(),i=Vn(),a=zt(),l=Ft({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=un(),g=Sn(m.get(Uc)),_=g===null?Kc(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(Uc):n.set(Uc,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 Fc(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:Tn(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(hn(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:Tn(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(Vc,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(On,{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 Nn(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 Fc(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(mn(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:qc(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(Hc,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function Kc(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=Ee(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function qc(e,t){return e.length>0?e:Tn(t(`helper.devicePending`))}function Jc(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 Yc(e){return{state:`answered`,byRef:new Map(e.map(e=>[Re(e),e]))}}function Xc(e,t){if(e.state!==`unanswered`)return e.byRef.get(Re(t))??null}function Zc(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Qc(e){return pe(e).map(e=>e.source)}function $c(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(...Qc(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Qc(e))}let r=new Set;return n.filter(e=>{let t=Re(e);return r.has(t)?!1:(r.add(t),!0)})}function el(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:J.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[J.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[J.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??J.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function tl(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return el(e);case`degraded`:return{tone:`pending`,label:J.t(`helpers.compositionRows.degraded`),reason:n??J.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:J.t(`helpers.compositionRows.failed`),reason:n??J.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:J.t(`helpers.compositionRows.notRunning`),reason:n??J.t(`helpers.compositionRows.notRunningReason`)}}}function nl(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:J.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:J.t(`helpers.compositionRows.unknown`),reason:J.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return tl(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.notReported`),reason:J.t(`helpers.compositionRows.noRecord`,{stored:r})}}function rl(e){return Re(e)}function il(e,t){let n=Xc(t,e);return{key:Re(e),label:n?n.name:rl(e),presence:Zc(n),deviceId:n?n.id:null}}function al(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function ol(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:ee(e.block.id),a=Re(i),o=$c(e).filter(e=>Re(e)!==a).map(e=>il(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Xc(t,i),l=al(e),u=nl(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:Jc(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=Zc(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:rl(r.device),namePresence:d,type:c?c.type:null,origin:Jc(n),features:s,state:u,sources:o,reportedDeviceId:l}}function sl(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function cl(e,t){return sl(e)-sl(t)||e.name.localeCompare(t.name)}function ll(e,t){let n=e.flatMap(e=>{let n=ol(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(cl),customizations:n.filter(e=>e.kind===`customization`).toSorted(cl)}}u();var ul=1e4;function dl(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function fl(){let e=ln();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:dl(e.error)})}:Yc(e.data)}function pl(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function ml({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Y(),[i,a]=un(),s=Ut({},{refetchInterval:ul}),l=fl(),u=tn({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?pl(i.get(`new`),t):null,p=f!==null,[h,g]=c(``),_=D(),v=Gt(),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:[gl(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(Kt,{open:p,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:Be,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(Wc,{mode:f,onTitle:g},f)}),o(Ln,{blockId:d,onClose:y}),v.error!=null&&o(W,{message:dl(v.error)})]})}function hl(t){return o(St,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:J.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[J.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function gl(e,t,n,r,i){if(t!=null&&e===void 0)return o(W,{title:J.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:dl(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:J.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return hl(e.reason);let a=t==null?null:dl(t);return o(_l,{lists:ll(e.views,r),fleet:r,refreshError:a,handlers:i})}function _l({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Y();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(vl,{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(vl,{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 vl({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=Y();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(Ye,{columns:yl(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:at,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function yl(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(xl,{row:e})},{key:`type`,header:J.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??J.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:J.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>bl(e.origin,i),render:e=>o(G,{variant:`default`,"data-testid":`composed-origin-badge`,children:bl(e.origin,i)})}]:[],{key:`state`,header:J.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(G,{variant:Xs(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:J.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(Cl,{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(T,{className:`h-4 w-4`})})]})}),a}function bl(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 xl({row:t}){let{t:n}=Y();return e(`div`,{className:`space-y-0.5`,children:[o(Sl,{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 Sl({row:e}){let{t}=Y(),n=Ot(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(gn,{to:e.kind===`composed`?mn(e.reportedDeviceId):hn(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Cl({sources:t}){let{t:n}=Y();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(gn,{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 wl(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 Tl(e){if(Array.isArray(e))return e}function El(e,t,n){return(t=Fl(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Dl(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 Ol(){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 kl(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 Al(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?kl(Object(n),!0).forEach(function(t){El(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):kl(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function jl(e,t){if(e==null)return{};var n,r,i=Ml(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 Ml(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 Nl(e,t){return Tl(e)||Dl(e,t)||Il(e,t)||Ol()}function Pl(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 Fl(e){var t=Pl(e,`string`);return typeof t==`symbol`?t:t+``}function Il(e,t){if(e){if(typeof e==`string`)return wl(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)?wl(e,t):void 0}}function Ll(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Rl(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 zl(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Rl(Object(n),!0).forEach(function(t){Ll(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Rl(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Bl(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Vl(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 Hl(e){return{}.toString.call(e).includes(`Object`)}function Ul(e){return!Object.keys(e).length}function Wl(e){return typeof e==`function`}function Gl(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Kl(e,t){return Hl(t)||Zl(`changeType`),Object.keys(t).some(function(t){return!Gl(e,t)})&&Zl(`changeField`),t}function ql(e){Wl(e)||Zl(`selectorType`)}function Jl(e){Wl(e)||Hl(e)||Zl(`handlerType`),Hl(e)&&Object.values(e).some(function(e){return!Wl(e)})&&Zl(`handlersType`)}function Yl(e){e||Zl(`initialIsRequired`),Hl(e)||Zl(`initialType`),Ul(e)&&Zl(`initialContent`)}function Xl(e,t){throw Error(e[t]||e.default)}var Zl=Vl(Xl)({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"}),Ql={changes:Kl,selector:ql,handler:Jl,initial:Yl};function $l(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ql.initial(e),Ql.handler(t);var n={current:e},r=Vl(nu)(n,t),i=Vl(tu)(n),a=Vl(Ql.changes)(e),o=Vl(eu)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Ql.selector(e),e(n.current)}function c(e){Bl(r,i,a,o)(e)}return[s,c]}function eu(e,t){return Wl(t)?t(e.current):t}function tu(e,t){return e.current=zl(zl({},e.current),t),t}function nu(e,t,n){return Wl(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var ru={create:$l},iu={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function au(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 ou(e){return{}.toString.call(e).includes(`Object`)}function su(e){return e||du(`configIsRequired`),ou(e)||du(`configType`),e.urls?(cu(),{paths:{vs:e.urls.monacoBase}}):e}function cu(){console.warn(uu.deprecation)}function lu(e,t){throw Error(e[t]||e.default)}var uu={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
- `},du=au(lu)(uu),fu={config:su},pu=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function mu(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],mu(e[n],t[n]))}),Al(Al({},e),t)}var hu={type:`cancelation`,msg:`operation is manually canceled`};function gu(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(hu):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var _u=[`monaco`],vu=Nl(ru.create({config:iu,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),yu=vu[0],bu=vu[1];function xu(e){var t=fu.config(e),n=t.monaco,r=jl(t,_u);bu(function(e){return{config:mu(e.config,r),monaco:n}})}function Su(){var e=yu(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(bu({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),gu(ku);if(window.monaco&&window.monaco.editor)return Du(window.monaco),e.resolve(window.monaco),gu(ku);pu(Cu,Tu)(Eu)}return gu(ku)}function Cu(e){return document.body.appendChild(e)}function wu(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function Tu(e){var t=yu(function(e){return{config:e.config,reject:e.reject}}),n=wu(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function Eu(){var e=yu(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;Du(n),e.resolve(n)},function(t){e.reject(t)})}function Du(e){yu().monaco||bu({monaco:e})}function Ou(){return yu(function(e){return e.monaco})}var ku=new Promise(function(e,t){return bu({resolve:e,reject:t})}),Au={config:xu,init:Su,__getMonacoInstance:Ou};u();var ju={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},Mu={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function Nu({children:e}){return t.createElement(`div`,{style:Mu.container},e)}var Pu=Nu;function Fu({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...ju.wrapper,width:e,height:n},...s},!r&&t.createElement(Pu,null,i),t.createElement(`div`,{ref:a,style:{...ju.fullWidth,...!r&&ju.hide},className:o}))}var Iu=i(Fu);function Lu(e){s(e,[])}var Ru=Lu;function zu(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=zu;function Bu(){}function Vu(e,t,n,r){return Hu(e,r)||Uu(e,t,n,r)}function Hu(e,t){return e.editor.getModel(Wu(e,t))}function Uu(e,t,n,r){return e.editor.createModel(t,n,r?Wu(e,r):void 0)}function Wu(e,t){return e.Uri.parse(t)}function Gu({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=Bu,onMount:S=Bu}){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);Ru(()=>{let e=Au.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=Vu(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=Vu(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=Vu(O.current,e||``,o||i||`text`,u||``),n=Vu(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(Iu,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(Gu);function Ku(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var qu=Ku,Ju=new Map;function Yu({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=Bu,onMount:C=Bu,onChange:w,onValidate:T=Bu}){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=qu(u),R=n(!1),z=n(!1);Ru(()=>{let e=Au.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?V():e.cancel()}),$(()=>{let t=Vu(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&Ju.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(Ju.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 B=a(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=u||i,n=Vu(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(Ju.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&&B()},[O,E,B]),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 V(){F.current?.dispose(),_?g&&Ju.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(Iu,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var Xu=i(Yu);u();function Zu(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 Qu={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function $u(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Qu}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function ed({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,$u(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&&$u(e,r)},[r]),o(Xu,{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 td(e){return e.some(e=>e.severity>=8)}var nd=[{id:`blank`,name:`Blank script`,get description(){return J.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 rd(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 id=nd.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 ad({existing:e,dirty:t,saving:n,restarting:r}){return e===null?J.t(`helpers.restartGate.saveFirstNoProcess`):n?J.t(`helpers.restartGate.saving`):r?J.t(`helpers.restartGate.restarting`):t?J.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:J.t(`helpers.restartGate.disabled`)}u();var od=5e3;function sd(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 cd({blockId:t}){let{t:n}=Y(),i=ne(t),a=Xt({addonId:i,projection:`slim`},{refetchInterval:od}),s=r(()=>sd(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(_,{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(X,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(G,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{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(gn,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(Tt,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(G,{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 ld(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 ud(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 dd(e){switch(e){case`refresh-channel-catalog`:return J.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return J.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return J.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return J.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return J.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return J.t(`build.scriptSettingsPanel.enableUnifi`)}}function fd(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function pd(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function md(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=fd(e);n!==null&&(t[n]=pd(e))}return t}function hd(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function gd({blockId:t}){let{t:n}=Y(),i=O(),s=Zt({blockId:t},{retry:!1}),l=Vt({blockId:t},{refetchInterval:1e4,retry:!1}),u=qt({onSuccess:()=>{l.refetch()}}),d=jt(),f=Lt(),[p,m]=c(null),[h,g]=c(null),[v,y]=c(null),[b,x]=c(!1),S=hd(l.data)?l.data:null,C=r(()=>S===null?{}:md(S),[S]),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]),k=a(async(e,n)=>{if(ld(e)){x(!0),g(null),y(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:ud(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),y(dd(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?y(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?y(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?y(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?y(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&y(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{x(!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(_,{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)]}):S===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(X,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(K,{size:`sm`,variant:`primary`,onClick:D,disabled:!E||u.isPending||b,children:[u.isPending&&o(_,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(pn,{schema:S,values:w,onChange:T,onAction:k}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),v===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:v})]})}u();var _d=`hub`;function vd({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:f,onCancel:h}){let{t:g}=Y(),v=O(),b=D(),{resolvedMode:C}=qe(),w=me({code:t?.code??id,files:t?.files,entry:t?.entry}),[T,E]=c(t?.name??``),[k,A]=c(w.files),[j,M]=c(w.entry),[P,F]=c(w.entry),[L,R]=c(t?.placement??_d),[z,B]=c(t?.integrationId??``),[V,ee]=c([]),[H,te]=c(!1),[re,ie]=c(`blank`),[ae,oe]=c(null),[se,ce]=c(``),le=k[P]??``,ue=e=>{A(t=>({...t,[P]:e}))},de=Object.keys(k).toSorted(),fe=nd.length>1,pe=r(()=>[...n?.libs??[],...Zu(k,P)],[n?.libs,k,P]),U=p({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:k,entry:j})}),he=r(()=>V.filter(e=>e.severity>=8),[V]),ge=td(V),_e=T.trim()===``,ve=t===null?null:me(t),ye=t===null||ve===null||JSON.stringify(k)!==JSON.stringify(ve.files)||j!==ve.entry||T.trim()!==t.name||L!==t.placement||(z.trim()===``?void 0:z.trim())!==t.integrationId,be=()=>{U.reset(),f({name:T.trim(),files:k,entry:j,enabled:t?.enabled??!0,placement:L,...z.trim()===``?{}:{integrationId:z.trim()}})},xe=()=>{let e=rd(Object.keys(k));A(t=>({...t,[e]:``})),F(e),oe(e),ce(e)},Se=e=>{oe(e),ce(e)},Ce=()=>{if(ae===null)return;let e=ae,t=se.trim();if(oe(null),!(t===``||t===e)){if(k[t]!==void 0){F(t);return}A(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),j===e&&M(t),F(t)}},we=async e=>{let t=nd.find(t=>t.id===e);if(t===void 0)return;let n=nd.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(k)===JSON.stringify(n.files)&&j===n.entry)&&!await b({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`})||(ie(e),A({...t.files}),M(t.entry),F(t.entry),(T.trim()===``||re===`blank`)&&E(t.id===`blank`?``:t.name))},Te=t===null?null:Ys(t),Ee=ad({existing:t,dirty:ye,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[Te!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(G,{variant:Xs(Te.tone),children:Te.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(q,{className:`mt-1`,value:T,onChange:e=>E(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(q,{className:`mt-1`,value:z,onChange:e=>B(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&fe&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),o(N,{className:`mt-1 w-full`,value:re,onChange:e=>void we(e.target.value),"data-testid":`script-example-select`,children:nd.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(en,{selectedNodeId:L,onSelect:R,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),L!==_d&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(y,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(X,{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:[de.map(t=>ae===t?o(q,{value:se,onChange:e=>ce(e.target.value),onBlur:()=>Ce(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Ce()),e.key===`Escape`&&(e.preventDefault(),oe(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:()=>Se(t),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===j?` · ${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:xe,"data-testid":`script-file-add`,children:g(`build.blockEditor.file`,`+ file`)}),P!==j&&o(K,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>M(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(ed,{value:le,onChange:ue,path:`file:///${P}`,extraLibs:pe,onDiagnostics:ee,dark:C===`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.`)}),he.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:he.length})}),he.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}`)),he.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:he.length-5})})]}),U.data!==void 0&&(U.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(x,{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:[U.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(U.data.line)})}),U.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),U.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:`),` `,yd(U.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(gd,{blockId:t.id}),o(cd,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:`outline`,onClick:()=>U.mutate(),disabled:U.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[U.isPending&&o(_,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(K,{onClick:be,disabled:a||ge||_e,children:[a&&o(_,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(K,{variant:`outline`,onClick:()=>d?.(),disabled:Ee!==null||d===void 0,title:Ee??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(I,{className:`h-4 w-4 animate-spin`}):o(I,{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(S,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,o(Nt,{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:he.length}),ye&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),_e&&o(G,{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(X,{i18nKey:`build.blockEditor.logsOf`,values:{id:ne(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(an,{addonId:ne(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function yd(e){return e instanceof Error?e.message:String(e)}u();var bd=[`coreBlocks`,`list`],xd=[`coreBlocks`,`getTypeDefs`],Sd=5e3;function Cd(e){return e instanceof Error?e.message:String(e)}function wd({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=b(),{t:f}=Y(),m=O(),{state:h,openNew:g,openEdit:_,close:v}=tn({editKey:`block`,newKey:`new`}),[y,x]=c(null),C=D(),[w,E]=c(null),k=l({queryKey:bd,refetchInterval:Sd,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=h.mode!==`closed`,j=l({queryKey:xd,enabled:A,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),M=()=>{k.refetch()},N=n(null),P=k.data;s(()=>{t===void 0||N.current===t||P?.find(e=>e.id===t&&U(e)===`code`)!==void 0&&(N.current=t,_(t),i?.(t))},[t,P,_,i]),s(()=>{a&&(x(null),g(),i?.(null),u?.())},[a,u,i,g]);let F=p({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),_(e.block.id),i?.(e.block.id),M()}}),L=p({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),_(e.block.id),i?.(e.block.id),M()}}),R=p({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:M}),z=p({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:M}),B=p({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:M}),V=Qs((k.data??[]).filter(e=>U(e)===`code`)),ee=k.data!==void 0&&V.length===0,H=F.isPending||L.isPending,te=F.error===null?L.error===null?null:Cd(L.error):Cd(F.error),re=h.mode===`edit`?V.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,ie=h.mode===`new`||re===null?null:Zs(V,re),ae=r(()=>[{key:`name`,header:f(`build.scriptsTab.name`,`Name`),render:t=>{let n=Ys(t),r=nt(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(G,{variant:Xs(n.tone),children:n.label}),o(G,{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}),w===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(X,{i18nKey:`common.logsOf`,values:{id:ne(t.id)},components:{code:o(`code`,{})}})}),o(an,{addonId:ne(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=z.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(),x(t),_(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(I,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(K,{variant:`ghost`,onClick:e=>{e.stopPropagation(),E(w===t.id?null:t.id)},title:f(`build.scriptsTab.logs`,`Logs`),children:o(S,{className:`h-4 w-4`})}),o(K,{variant:`ghost`,onClick:e=>{e.stopPropagation(),z.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(),C({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(T,{className:`h-4 w-4`})})]})}}],[C,w,i,_,R,B.isPending,B.variables,z,f]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:k.data===void 0?``:$s(V)}),k.error!=null&&o(W,{title:f(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Cd(k.error),onRetry:M}),o(Ye,{columns:ae,rows:V,rowKey:e=>e.id,pageSize:25,maxBodyHeight:at,emptyMessage:ee?f(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):k.data===void 0?f(`build.scriptsTab.loadingScripts`,`Loading scripts…`):f(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{x(e),_(e.id),i?.(e.id)}}),o(Kt,{open:A,onClose:()=>{F.reset(),L.reset(),B.reset(),x(null),v(),i?.(null)},title:ie===null?f(`build.scriptsTab.newScript`,`New script`):f(`build.scriptsTab.edit`,`Edit {{name}}`,{name:ie.name}),icon:Ue,width:`xl`,testId:`script-editor-panel`,children:o(vd,{existing:ie,typeDefs:j.data,typeDefsLoading:j.isLoading,saving:H,saveError:te,restarting:B.isPending,restartError:B.error===null?null:Cd(B.error),onRestart:ie===null?void 0:()=>B.mutate(ie.id),onSave:e=>{let t=ie;t===null?F.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{F.reset(),L.reset(),B.reset(),x(null),v(),i?.(null)}})}),R.error!=null&&o(W,{message:Cd(R.error)}),z.error!=null&&o(W,{message:Cd(z.error)}),B.error!=null&&o(W,{message:Cd(B.error)})]})}var Td=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`];function Ed(e){return e!==null&&Td.some(t=>t===e)}var Dd=[`coreBlocks`,`list`,`build-counts`],Od=[`schedulers`,`list`,`build-counts`],kd=[`actions`,`list`,`build-counts`],Ad=[`block`,`action`,`scheduler`,`create`,`new`];function jd(e){return e.filter(e=>U(e)===`code`).length}function Md(e){return e.filter(e=>Xn(e.code)).length}function Nd(e,t){return t===null?e:`${e} (${String(t)})`}function Pd(){let{t}=Y(),n=O(),[r,i]=un(),a=r.get(`tab`),s=Ed(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:Dd,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:jd(u),f=u===void 0?null:Md(u),p=l({queryKey:kd,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=l({queryKey:Od,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})},T=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},E=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`),D=_n(`/build`,{t,isAdmin:!0})??{icon:w,title:t(`nav.build`,`Build-your-self`)};return o(vn,{icon:D.icon,title:D.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${D.title} sections`,fill:!0,actions:s===`custom-device`?e(K,{type:`button`,onClick:()=>S(`helper`),"data-testid":`build-new-composed`,children:[o(C,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(K,{type:`button`,onClick:x,"data-testid":`build-new`,children:[o(C,{className:`h-4 w-4`}),` `,E]}),sections:[{id:`automations`,label:Nd(t(`build.tabAutomations`,`Automations`),f),ownedParams:Ad,content:o(fc,{onOpenScripts:y,createRequested:s===`automations`&&c,onCreateConsumed:T})},{id:`actions`,label:Nd(t(`build.tabActions`,`Actions`),m),ownedParams:Ad,content:o(js,{createRequested:s===`actions`&&c,onCreateConsumed:T})},{id:`schedulers`,label:Nd(t(`build.tabSchedulers`,`Schedulers`),g),ownedParams:Ad,content:o(jc,{createRequested:s===`schedulers`&&c,onCreateConsumed:T})},{id:`scripts`,label:Nd(t(`build.tabCode`,`Code`),d),ownedParams:Ad,content:o(wd,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:b,createRequested:s===`scripts`&&c,onCreateConsumed:T})},{id:`custom-device`,label:Nd(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:Ad,content:o(ml,{createRequested:s===`custom-device`&&c,onCreateConsumed:T})}]})}export{Pd as BuildPage};