@camstack/addon-admin-ui 1.2.663 → 1.2.664
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/assets/{Addons-D2U4ey8S.js → Addons-DbT3ta8z.js} +1 -1
- package/dist/assets/{AdminSectionedPage-BqMR6wyl.js → AdminSectionedPage-C7aZLZRh.js} +1 -1
- package/dist/assets/{AiProfiles-XvV90DK3.js → AiProfiles-C-ql511o.js} +1 -1
- package/dist/assets/{BootstrapSettingsForm-CBdNwCCB.js → BootstrapSettingsForm-bkltsyDh.js} +1 -1
- package/dist/assets/{Build-CWApU8jt.js → Build-CyKLuVmF.js} +8 -8
- package/dist/assets/{Calendars-B-sr3hd4.js → Calendars-CMSCqf10.js} +1 -1
- package/dist/assets/{CameraGrids-Dnw1ycx3.js → CameraGrids-DN3Ls5A4.js} +1 -1
- package/dist/assets/{Cluster-CUH-kWFy.js → Cluster-D24Q3gsy.js} +1 -1
- package/dist/assets/{CompositionBlockEditor-B_U-lZo_.js → CompositionBlockEditor-Cko2VX5-.js} +1 -1
- package/dist/assets/{CompositionEditorPage-DArHtJ30.js → CompositionEditorPage-Cq76qdLa.js} +1 -1
- package/dist/assets/{Data-Bq2G-Uze.js → Data-CI6UgZZY.js} +1 -1
- package/dist/assets/{DeviceDetail-CK68F92F.js → DeviceDetail-D2CGNOL1.js} +1 -1
- package/dist/assets/{Devices-Cj93aFIl.js → Devices-BuYYfNPu.js} +1 -1
- package/dist/assets/{EmbedDevicePage-BlGF9SaW.js → EmbedDevicePage-BQ1tRNUp.js} +1 -1
- package/dist/assets/{History-DCad05vk.js → History-D9RNBn7H.js} +1 -1
- package/dist/assets/{Identity-63cDUcMM.js → Identity-Dum55imC.js} +1 -1
- package/dist/assets/{InstancesTable-BUXMnTHA.js → InstancesTable-Bza_hcOv.js} +1 -1
- package/dist/assets/{IntegrationDetail-B_L61hTc.js → IntegrationDetail-DT-ZanyO.js} +1 -1
- package/dist/assets/{Integrations-CyPlJq32.js → Integrations-BpkEEhcd.js} +1 -1
- package/dist/assets/{Integrations-CS_hfw55.js → Integrations-Y0x6acKZ.js} +1 -1
- package/dist/assets/{Library-BpbE62zy.js → Library-CqniXzi0.js} +1 -1
- package/dist/assets/{Locations-BCqBr8Y4.js → Locations-BnLjl50_.js} +1 -1
- package/dist/assets/{Logs-BaL7iQaB.js → Logs-D3qUktnv.js} +1 -1
- package/dist/assets/{MyAccess-DwAiEYQA.js → MyAccess-tguGEp30.js} +1 -1
- package/dist/assets/{Network-B1z2excG.js → Network-C9GshUgl.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-BA50qJvF.js → NodeAddonsSettingsPanel-YGDDqLon.js} +1 -1
- package/dist/assets/{Notifications-BV8kZeYz.js → Notifications-CpQ7WD8S.js} +1 -1
- package/dist/assets/{Pipeline-C69mgXSD.js → Pipeline-sfp8tOti.js} +1 -1
- package/dist/assets/{Recordings-BmjYMUQX.js → Recordings-zL4BQ-AD.js} +1 -1
- package/dist/assets/{SessionsList-BI5DltIM.js → SessionsList-B8py_Z_Y.js} +1 -1
- package/dist/assets/{Showroom-CDGZHhu6.js → Showroom-Bq-MxPxP.js} +1 -1
- package/dist/assets/{StorageLocationsTable-BIgDfpUt.js → StorageLocationsTable-D1ZfEmZ0.js} +1 -1
- package/dist/assets/{System-pCE1e3j7.js → System-C_sm8J4x.js} +1 -1
- package/dist/assets/{Terminal-CcYgnG1P.js → Terminal-DRqgGpAj.js} +1 -1
- package/dist/assets/{TrainingProviders-BMv4jEVZ.js → TrainingProviders-BT4K0RVZ.js} +1 -1
- package/dist/assets/{ai-page.helpers-PQz3JLhJ.js → ai-page.helpers-F__brMbl.js} +1 -1
- package/dist/assets/{assignment-candidates-COgEdwyJ.js → assignment-candidates-CJqDXIFp.js} +1 -1
- package/dist/assets/{board-model-CXsiRbho.js → board-model-DnTtSG-0.js} +1 -1
- package/dist/assets/{device-detail-CfLN0J2f.js → device-detail-DHAwENUJ.js} +1 -1
- package/dist/assets/{device-integration-icon-DcscyG13.js → device-integration-icon-DTlSLQS_.js} +1 -1
- package/dist/assets/{format-qhRLJ6Rp.js → format-DVsAf4qU.js} +1 -1
- package/dist/assets/i18n-CThuXMc5.js +1 -0
- package/dist/assets/{index-BniGMyKF.js → index-DUv1kIQf.js} +3 -3
- package/dist/assets/{linked-devices-model-Db-1_th5.js → linked-devices-model-En6xpQk8.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-40b6c80a.js → mf-entry-bootstrap-0-f1ce1aba.js} +1 -1
- package/dist/assets/{notification-rule-status-E-DNTawC.js → notification-rule-status-_SY1WA7F.js} +1 -1
- package/dist/assets/{sso-popup-B7XNcrVl.js → sso-popup-DyR-aOS2.js} +1 -1
- package/dist/assets/{step-inspector-model-CbZrtlrQ.js → step-inspector-model-BAZSRIbI.js} +1 -1
- package/dist/assets/{useAdminDeviceRemoval-DCzeccST.js → useAdminDeviceRemoval-BKtAsw-I.js} +1 -1
- package/dist/assets/{useNodeUrlSelection-B0QLSXzh.js → useNodeUrlSelection-CH8FI53M.js} +1 -1
- package/dist/assets/{useTemplateSave-teQXGJWi.js → useTemplateSave-B9ob9RKz.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/server/addon.js +1 -1
- package/package.json +2 -2
- package/dist/assets/i18n-B-GVs9dW.js +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,k as d,o as f,t as p,x as m,z as h}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$t as g,Ei as _,Gn as v,Hi as y,Ia as b,Ir as x,Pr as S,Qr as C,Tt as w,Ua as T,Xa as E,Yt as D,Zi as O,_t as k,cr as A,ct as j,da as M,ka as N,nr as P,oa as F,ot as I,qr as L,rr as R,ut as z,vi as B,zn as V}from"./player-overlays-D-xr6JNm.js";import{Ao as ee,Ar as H,Ba as U,Bo as te,Co as ne,Do as W,Dr as re,Ds as G,Ec as ie,Eo as ae,Fo as oe,Gi as se,Go as ce,Ha as le,Ho as ue,Ia as de,Io as fe,Ji as pe,Lo as me,Mo as he,Mr as ge,No as _e,Nr as ve,Oo as ye,Po as be,Pr as xe,Ro as Se,So as Ce,To as we,Uo as Te,Vo as Ee,Wa as De,Wo as Oe,Yo as ke,Yt as Ae,as as je,bo as Me,cs as Ne,dc as Pe,fa as Fe,fo as Ie,go as Le,ho as Re,jo as ze,jr as Be,ko as Ve,lo as He,mo as Ue,os as We,po as Ge,qi as Ke,qo as qe,sa as Je,uo as Ye,vo as Xe,wo as Ze,yo as Qe,zo as $e}from"./client-DbkHdobd.js";import{t as et}from"./chevron-down-CBb-F8DT.js";import{o as tt}from"./terminal-DU-tvcEm.js";import{i as nt,n as rt,r as it,t as at}from"./variable-Cq3v1-Kt.js";import{$d as ot,$f as st,Af as ct,Ai as lt,Ao as ut,Bi as dt,Bo as ft,Ca as pt,Cr as mt,Df as ht,Di as gt,Ei as _t,Er as vt,Fi as yt,Fo as bt,Gi as xt,Gt as St,H as Ct,Hf as wt,Hr as Tt,Hu as Et,Jf as Dt,Ji as Ot,Kt as kt,Lo as At,Mi as jt,Mo as Mt,Ni as Nt,Oi as Pt,Os as Ft,Q as It,Qs as Lt,S as Rt,Sn as zt,Ti as Bt,Tr as Vt,Ur as Ht,Vo as Ut,Vr as Wt,Wr as Gt,Ws as Kt,Yd as qt,Yr as Jt,Z as Yt,Zr as Xt,_ as Zt,_a as Qt,_d as $t,_s as en,at as K,ba as tn,bd as nn,bn as rn,cc as an,ef as on,ep as sn,fa as q,ga as cn,gd as ln,h as un,hd as dn,hp as fn,ir as pn,jo as mn,kf as J,ki as hn,la as gn,md as _n,nf as vn,or as yn,qf as Y,rt as bn,tf as xn,vd as Sn,w as Cn,wi as wn,wr as Tn,x as En,xa as Dn,xd as On,xs as kn,ya as An,yd as jn,yr as Mn,zf as X,zo as Nn}from"./src-CxMNFQ7c.js";import{t as Z}from"./i18n-
|
|
1
|
+
import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,k as d,o as f,t as p,x as m,z as h}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$t as g,Ei as _,Gn as v,Hi as y,Ia as b,Ir as x,Pr as S,Qr as C,Tt as w,Ua as T,Xa as E,Yt as D,Zi as O,_t as k,cr as A,ct as j,da as M,ka as N,nr as P,oa as F,ot as I,qr as L,rr as R,ut as z,vi as B,zn as V}from"./player-overlays-D-xr6JNm.js";import{Ao as ee,Ar as H,Ba as U,Bo as te,Co as ne,Do as W,Dr as re,Ds as G,Ec as ie,Eo as ae,Fo as oe,Gi as se,Go as ce,Ha as le,Ho as ue,Ia as de,Io as fe,Ji as pe,Lo as me,Mo as he,Mr as ge,No as _e,Nr as ve,Oo as ye,Po as be,Pr as xe,Ro as Se,So as Ce,To as we,Uo as Te,Vo as Ee,Wa as De,Wo as Oe,Yo as ke,Yt as Ae,as as je,bo as Me,cs as Ne,dc as Pe,fa as Fe,fo as Ie,go as Le,ho as Re,jo as ze,jr as Be,ko as Ve,lo as He,mo as Ue,os as We,po as Ge,qi as Ke,qo as qe,sa as Je,uo as Ye,vo as Xe,wo as Ze,yo as Qe,zo as $e}from"./client-DbkHdobd.js";import{t as et}from"./chevron-down-CBb-F8DT.js";import{o as tt}from"./terminal-DU-tvcEm.js";import{i as nt,n as rt,r as it,t as at}from"./variable-Cq3v1-Kt.js";import{$d as ot,$f as st,Af as ct,Ai as lt,Ao as ut,Bi as dt,Bo as ft,Ca as pt,Cr as mt,Df as ht,Di as gt,Ei as _t,Er as vt,Fi as yt,Fo as bt,Gi as xt,Gt as St,H as Ct,Hf as wt,Hr as Tt,Hu as Et,Jf as Dt,Ji as Ot,Kt as kt,Lo as At,Mi as jt,Mo as Mt,Ni as Nt,Oi as Pt,Os as Ft,Q as It,Qs as Lt,S as Rt,Sn as zt,Ti as Bt,Tr as Vt,Ur as Ht,Vo as Ut,Vr as Wt,Wr as Gt,Ws as Kt,Yd as qt,Yr as Jt,Z as Yt,Zr as Xt,_ as Zt,_a as Qt,_d as $t,_s as en,at as K,ba as tn,bd as nn,bn as rn,cc as an,ef as on,ep as sn,fa as q,ga as cn,gd as ln,h as un,hd as dn,hp as fn,ir as pn,jo as mn,kf as J,ki as hn,la as gn,md as _n,nf as vn,or as yn,qf as Y,rt as bn,tf as xn,vd as Sn,w as Cn,wi as wn,wr as Tn,x as En,xa as Dn,xd as On,xs as kn,ya as An,yd as jn,yr as Mn,zf as X,zo as Nn}from"./src-CxMNFQ7c.js";import{t as Z}from"./i18n-CThuXMc5.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import{Ot as Pn,V as Fn,b as In,ci as Ln,fi as Rn,g as zn,h as Bn,jt as Vn,li as Hn,mi as Un,n as Wn,t as Gn}from"./index-DUv1kIQf.js";import{t as Kn}from"./AdminSectionedPage-C7aZLZRh.js";import{n as qn}from"./format-DVsAf4qU.js";import{C as Jn,Et as Yn,St as Xn,a as Zn,at as Qn,b as $n,g as er,i as tr,n as nr,nt as rr,o as ir,r as ar,w as or,xt as sr,y as cr}from"./CompositionBlockEditor-Cko2VX5-.js";import{a as lr,c as ur,d as dr,f as fr,i as pr,l as mr,m as hr,o as gr,p as _r,r as vr,s as yr,t as br,u as xr}from"./useTemplateSave-B9ob9RKz.js";import{a as Sr,i as Cr,n as wr,o as Tr,r as Er,s as Dr}from"./action-draft-BjuURFtz.js";var Or=`const AUTOMATION_RECIPE =`,kr=`// EJECTED from the visual automation editor — this file is now hand-owned.
|
|
2
2
|
// The recipe that produced it was removed with it, on purpose: while it was
|
|
3
3
|
// here the editor could re-open this block and overwrite everything below.`;function Ar(e){return e.includes(Or)}function jr(e){let t=e.indexOf(Or);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 Mr(e){let t=jr(e);if(t===null)return{ok:!1,reason:Z.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:Z.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=ae.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Z.t(`helpers.recipeFromCode.schemaMismatch`):Z.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function Nr(e){let t=jr(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)}${kr}${e.slice(i)}`}u();var Pr=`when`;function Fr(e){return e===void 0||e.trim()===``?null:e}function Ir(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function Lr(e){return e===`ok`?`pass`:e===`error`||e===`failed-continued`||e===`timed-out`?`fail`:`idle`}function Rr(e){return e.steps.map(e=>({index:Ir(e.path),tone:Lr(e.outcome),message:Fr(e.message)}))}function zr(e){let t=e.trigger.outcome===`pass`?`pass`:`fail`,n=Fr(e.trigger.reason),r=e.conditions.find(e=>e.path===Pr);return t===`fail`||r===void 0?{tone:t,reason:n}:r.outcome===`fail`?{tone:`fail`,reason:Fr(r.reason)??n}:{tone:r.outcome===`pass`?`pass`:`idle`,reason:n}}function Br(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:Fr(e.verdict?.reason)}}function Vr(e){let t=Rr(e);return{when:zr(e),thenBlock:Br(e,t),steps:t}}function Hr(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}function Ur(e){return e===null?{kind:`unknown`}:{kind:`value`,text:Array.isArray(e)?e.join(`, `):String(e)}}function Wr(e){return{kind:e.kind,tone:Lr(e.outcome),message:Fr(e.message)}}function Gr(e){if(e===void 0)return null;if(e===`else`)return{kind:`else`};let t=Number(e.slice(e.lastIndexOf(`.`)+1));return Number.isInteger(t)?{kind:`branch`,index:t}:null}function Kr(e,t){return t===void 0?null:e===void 0?t:`${e}.${t}`}function qr(e){return{vars:Object.entries(e.trigger.vars).map(([e,t])=>({name:e,value:Ur(t)})),conditions:e.conditions.map(e=>({path:e.path,depth:e.path.split(`.`).length-1,kind:e.kind,outcome:e.outcome,reason:Fr(e.reason),subject:Kr(e.cap,e.fieldPath),operator:e.operator??null,deviceId:e.deviceId??null,expected:e.expected===void 0?null:Ur(e.expected),observed:e.observed===void 0?null:Ur(e.observed),rawExpected:e.expected,rawObserved:e.observed})),steps:e.steps.map(e=>({index:Ir(e.path),kind:e.kind,tone:Lr(e.outcome),message:Fr(e.message),args:Object.entries(e.args??{}).map(([e,t])=>({name:e,value:Ur(t)})),devices:(e.devices??[]).map(e=>({deviceId:e.deviceId,tone:e.outcome===`ok`?`pass`:`fail`,message:Fr(e.message)})),chose:Gr(e.branch),nested:(e.steps??[]).map(e=>({...Wr(e),chose:Gr(e.branch),rounds:e.iterations??null,inner:(e.steps??[]).map(Wr)})),rounds:e.iterations??null}))}}function Jr(e){let t=qr(e);return{nodes:new Map(t.conditions.map(e=>[e.path,e])),triggerPath:e.trigger.path??null,vars:t.vars}}var Yr=6;function Xr(e,t,n){if(typeof e!=`number`||t===void 0||n===void 0)return Ur(e);let r=ke(e,t,n);return r===void 0?Ur(e):{kind:`value`,text:`${String(Number(r.toPrecision(Yr)))} ${n}`}}function Zr(e){let t=e.steps.find(e=>e.outcome===`error`),n=t===void 0?Fr(e.verdict?.reason)??Fr(e.trigger.reason):Fr(t.message);return{stepsRun:e.steps.filter(e=>e.outcome===`ok`).length,stepsTotal:e.steps.length,reason:n}}var Qr={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},$r={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},ei={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function ti(){let{t:e}=Q();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 ni={done:`success`,missed:`warning`,inactive:`neutral`,"condition-false":`neutral`,failed:`danger`,held:`success`,"gave-up":`danger`,overridden:`info`,"suspended-manual":`warning`};function ri(){let{t:e}=Q();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 ii=`max-h-64`;function ai(){let e=sn(),t=st();return e||t}function oi({expanded:t,onToggle:n}){let{t:r}=Q();return e(X,{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(wt,{expanded:t}),o(`span`,{children:t?r(`flow.runs.hide`,`Hide runs`):r(`flow.runs.show`,`Show runs`)})]})}function si({run:t}){let{t:n}=Q(),r=ti(),i=Zr(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(J,{variant:Qr[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 ci({traces:t,selectedId:n,onSelect:r}){let{t:i}=Q(),a=ti(),s=ri(),l=ai(),[u,d]=c(null),f=u??!l,p=t===void 0?[]:t.toReversed(),h=p.find(e=>e.runId===n)??null;return e(mt,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:L,children:[o(oi,{expanded:f,onToggle:()=>d(!f)}),f?t===void 0?o(ct,{className:`m-3 h-16`}):p.length===0?o(dt,{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:`${ii} 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(X,{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(J,{variant:Qr[t.outcome],children:a(t.outcome)}):o(J,{variant:ni[t.scheduler],children:s(t.scheduler)}),t.repeat>1&&o(J,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:qn(t.lastAt)})]}),o(`span`,{className:`truncate text-sm text-foreground`,children:t.trigger.reason})]})},t.runId)})}),h!==null&&o(si,{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(si,{run:h})]})}function li(e){return $r[e]}var ui={pass:`border-success/50`,fail:`border-danger/50`,idle:`border-border`};function di(e){return ui[e]}function fi({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`:$r[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 ${ei[i.tone]}`,children:i.reason}),o(`div`,{className:`space-y-2`,children:a})]})}var pi=[`count`,`while`,`until`,`forEach`],mi=2,hi=10,gi={kind:`all`,children:[]};function _i(e){return e===`count`||e===`while`||e===`until`||e===`forEach`}function vi(e,t){return Number.isFinite(e)?Math.min(t,Math.max(1,Math.round(e))):1}function yi(e){return vi(e,20)}function bi(e){return vi(e,50)}function xi(e){switch(e){case`count`:return{by:e,count:mi};case`while`:case`until`:return{by:e,when:gi,maxIterations:hi};case`forEach`:return{by:e,target:{kind:`devices`,ids:[]}}}}function Si(e,t){if(e.by!==`while`&&e.by!==`until`)return e;let{waitS:n,...r}=e;return t===null?r:{...r,waitS:vi(t,ye)}}function Ci(){return{kind:`repeat`,loop:xi(`count`),steps:[]}}var wi=[`s`,`min`,`h`],Ti={s:1,min:60,h:3600};function Ei(e){return e===`s`||e===`min`||e===`h`}function Di(e){return e%Ti.h===0?{value:e/Ti.h,unit:`h`}:e%Ti.min===0?{value:e/Ti.min,unit:`min`}:{value:e,unit:`s`}}function Oi(e,t){let n=Math.round(e*Ti[t]);return Number.isFinite(n)?Math.min(Math.max(n,1),Ve):1}function ki(){return{kind:`wait-until`,when:{kind:`all`,children:[]},timeoutS:600,onTimeout:`continue`}}var Ai=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function ji(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 Ai}}function Mi(e){switch(e){case`eq`:return Z.t(`helpers.recipeParts.op_eq`);case`ne`:return Z.t(`helpers.recipeParts.op_ne`);case`gt`:return Z.t(`helpers.recipeParts.op_gt`);case`gte`:return Z.t(`helpers.recipeParts.op_gte`);case`lt`:return Z.t(`helpers.recipeParts.op_lt`);case`lte`:return Z.t(`helpers.recipeParts.op_lte`);case`contains`:return Z.t(`helpers.recipeParts.op_contains`);default:return Z.t(`helpers.recipeParts.op_in`)}}function Ni(e){return ji(e).map(e=>({value:e,label:Mi(e)}))}He.filter(e=>Ye(e).role===`event`),He.filter(e=>Ye(e).role===`state`);function Pi(e){return Z.t(`${Ye(e).i18nKey}.label`)}function Fi(e){return Z.t(`${Ye(e).i18nKey}.description`)}function Ii(e){return Z.t(`${Ye(e).i18nKey}.example`)}var Li={when:{kind:`all`,children:[]},actions:[]};function Ri(e){return Ie(e)}function zi(e){switch(e){case`wait`:return{kind:e,seconds:5};case`code`:return{kind:e,code:`// runs inside this automation, with ctx in scope
|
|
4
|
-
`};case`action`:return{kind:e,actionId:``};case`stop`:return{kind:e,reason:``,outcome:`ok`};case`set`:return{kind:e,vars:{}};case`wait-until`:return ki();case`parallel`:return{kind:e,steps:[]};case`repeat`:return Ci();case`choose`:return{kind:e,branches:[{if:{kind:`all`,children:[]},steps:[]}]};default:return{kind:`command`,target:{kind:`devices`,ids:[]},actionId:``}}}function Bi(e,t,n){return e.map((e,r)=>r===t?n:e)}function Vi(e,t){return e.filter((e,n)=>n!==t)}function Hi(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=Vi(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function Ui(e,t){return{...e,actions:[...t]}}var Wi={pass:`success`,fail:`danger`,"not-evaluated":`neutral`},Gi={pass:`success`,fail:`danger`,idle:`neutral`};function Ki({value:e}){let{t}=Q();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 qi(){let{t:e}=Q();return t=>t===`pass`?e(`flow.runs.nodePass`,`Passed`):t===`fail`?e(`flow.runs.nodeFail`,`Failed`):e(`flow.runs.nodeNotEvaluated`,`Not evaluated`)}function Ji(e){let t=he.safeParse(e);return t.success?Mi(t.data):e}function Yi({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(Ki,{value:t.value})})]},t.name))})}function Xi({node:t,vars:n=[],expected:r,observed:i}){let{t:a}=Q(),s=qi(),c=t.subject===null?null:`${t.subject}${t.operator===null?``:` ${Ji(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(J,{variant:Wi[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(Ki,{value:r})]}),i!==null&&e(`span`,{"data-testid":`trace-observed`,children:[a(`flow.runs.observed`,`Observed`),` `,o(Ki,{value:i})]})]}),o(Yi,{testId:`trace-vars`,items:n})]})}function Zi({step:t,deviceName:n}){let{t:r}=Q(),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(J,{variant:Gi[t.tone],children:i}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:t.message})]}),t.chose!==null&&o(`div`,{className:`text-foreground-subtle`,"data-testid":`step-chose`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.nested.length>0&&o(`div`,{className:`text-foreground-subtle`,"data-testid":`step-last-round`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})}),t.nested.length>0&&o(`ol`,{className:`space-y-0.5 text-[11px]`,"data-testid":`step-nested`,children:t.nested.map((t,n)=>e(`li`,{className:`space-y-0.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:Gi[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message}),t.chose!==null&&o(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-chose-${String(n)}`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.inner.length>0&&o(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-rounds-${String(n)}`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})})]}),t.inner.length>0&&o(`ol`,{className:`space-y-0.5 border-l border-border-subtle pl-2`,"data-testid":`nested-inner-${String(n)}`,children:t.inner.map((t,n)=>e(`li`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:Gi[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},String(n)))})]},String(n)))}),o(Yi,{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(J,{variant:Gi[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 $({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function Qi(e){let t=mr(e.deviceId);if(t.data!==void 0)return yr(t.data,e.cap).find(t=>t.path===e.fieldPath)}function $i({value:t,devices:n,onChange:r}){let{t:i,i18n:a}=Q(),[s,l]=c(!1),u=n.find(e=>e.id===t.deviceId),d=t.deviceId===0?i(`automation.fieldPicker.pickAValue`,`Pick a device value…`):`${u?.name??`#${String(t.deviceId)}`}${t.cap===``?``:` · ${Xn(t.cap,t.fieldPath,a.language)}`}`;return e(`div`,{className:`min-w-[14rem] max-w-full flex-[2]`,children:[o($,{children:i(`automation.fieldPicker.value`,`Device value`)}),e(X,{variant:`outline`,className:`w-full min-w-0 justify-between`,"data-testid":`field-picker-open`,onClick:()=>l(!0),children:[o(`span`,{className:`w-0 flex-1 truncate text-left`,children:d}),o(et,{className:`size-3.5 shrink-0`})]}),s&&o(ea,{value:t,onCancel:()=>l(!1),onConfirm:e=>{l(!1),r(e)}})]})}function ea({value:t,onCancel:n,onConfirm:r}){let{t:i}=Q(),a=kn({projection:`slim`}),[s,l]=c(null),[u,d]=c(!1),[f,p]=c(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!u&&a.status===`success`&&(d(!0),l(Yn(a.data).find(e=>e.id===t.deviceId)??null));let h=i(`automation.fieldPicker.title`,`Device value`);return o(It,{open:!0,onClose:n,title:h,width:`xl`,fill:!0,testId:`field-picker-dialog`,footer:e(m,{children:[o(X,{variant:`ghost`,onClick:n,children:i(`common.cancel`,`Cancel`)}),o(X,{disabled:s===null||f===null,"data-testid":`field-picker-confirm`,onClick:()=>{s===null||f===null||r({deviceId:s.id,cap:f.cap,fieldPath:f.path})},children:i(`automation.fieldPicker.use`,`Use this value`)})]}),children:o(Qn,{kind:`formula`,intent:`value`,enabled:!0,fillHeight:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:h,pickerTargetKind:null},device:s,field:f,excludeTypes:dr,onDeviceChange:l,onFieldChange:p})})}var ta=1e4;function na(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 ra(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function ia({step:t,onChange:n}){let{t:r}=Q(),i=tn({},{refetchInterval:ta});if(i.data===void 0)return o(ct,{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($,{children:r(`automation.runAction.action`,`Action`)}),o(z,{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(aa,{variable:e,value:t.variables?.[e.name],onChange:r=>n(ra(t,na(t.variables,e.name,r)))},e.name))})]})}function aa({variable:t,value:n,onChange:r}){let{t:i}=Q(),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($,{children:a}),o(_r,{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($,{children:a}),o(hr,{className:`w-40`,placeholder:s,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[o($,{children:a}),o(Y,{className:`w-40`,placeholder:s,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}function oa({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(X,{variant:`ghost`,disabled:e===null,onClick:e??void 0,"aria-label":t,title:a,"data-testid":r,children:i})})}function sa({move:t,texts:n}){let{t:r}=Q(),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(oa,{onMove:t.up,label:i.up,reason:i.atFirst,testId:`move-up`,children:o(N,{className:`h-3.5 w-3.5`})}),o(oa,{onMove:t.down,label:i.down,reason:i.atLast,testId:`move-down`,children:o(b,{className:`h-3.5 w-3.5`})})]})}var ca=[`command`,`action`,`wait`,`set`,`stop`],la=[`command`,`action`,`wait`];function ua(e){return fa(e)&&la.includes(e.kind)}var da={kind:`all`,children:[]};function fa(e){return ca.includes(e.kind)?!(`if`in e)&&!(`else`in e):!1}function pa(){return{if:da,steps:[]}}function ma(e){return e.branches.length<6}function ha(e){return ma(e)?{...e,branches:[...e.branches,pa()]}:e}function ga(e){return e.branches.length>1}function _a(e,t){return ga(e)?{...e,branches:e.branches.filter((e,n)=>n!==t)}:e}function va(e,t,n){return{...e,branches:e.branches.map((e,r)=>r===t?n:e)}}function ya(e,t){let{else:n,...r}=e;return t===void 0?r:{...r,else:[...t]}}var ba=[...ca,`wait-until`,`choose`,`parallel`,`repeat`];function xa(e){return e<2?ba:ca}function Sa(e){if(fa(e))return!0;switch(e.kind){case`wait-until`:case`parallel`:return!0;case`repeat`:return e.steps.every(fa);case`choose`:return e.branches.every(e=>e.steps.every(fa))&&(e.else??[]).every(fa);default:return!1}}var Ca=[`border-chart-series-a`,`border-chart-series-f`,`border-chart-series-b`,`border-chart-series-d`];function wa(e,t){let n=Ca.length;return(e+1+t%(n-1))%n}function Ta(e,t){let n=0;return e.map(e=>me(e)?null:wa(t,n++))}function Ea(e){return Ca[e%Ca.length]??Ca[0]}function Da(e){let t=[],n=0;return be(e,e=>{fe(e)&&(n+=1,e.id!==void 0&&t.push({id:e.id,ordinal:n,leaf:e}))}),t}function Oa(e){return oe(e.when)?!0:e.actions.some(e=>ee(e).some(e=>oe(e.when)))}function ka(e){let t=1;for(;e.has(`t${t}`);)t+=1;return`t${t}`}function Aa(e,t){if(me(e)){if(!fe(e)||e.id!==void 0)return e;let n=ka(t);return t.add(n),{...e,id:n}}if(e.kind===`not`){let n=Aa(e.child,t);return n===e.child?e:{...e,child:n}}let n=e.children.map(e=>Aa(e,t));return n.every((t,n)=>t===e.children[n])?e:{...e,children:n}}function ja(e){if(!Oa(e))return e;let t=new Set(Da(e.when).map(e=>e.id)),n=Aa(e.when,t);return n===e.when?e:{...e,when:n}}function Ma(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 Na(e,t){return e.leafIds.filter(e=>!t.includes(e))}u();var Pa=[],Fa=d(null);function Ia({when:e,children:t}){let n=r(()=>Da(e),[e]);return o(Fa.Provider,{value:n,children:t})}function La(){return h(Fa)??Pa}function Ra(){return h(Fa)!==null}var za=[`triggered-by`];function Ba(e){return{label:Pi(e),description:Fi(e),example:Ii(e)}}function Va({open:e,onOpenChange:t,mode:n,context:r,underNot:i,treeFull:a,current:s,onPick:c}){let{t:l}=Q(),u=Ra();return o(Zt,{open:e,onOpenChange:t,title:n===`add`?l(`automation.leafPicker.title`,`Add a row`):l(`automation.leafPicker.changeTitle`,`Change the row type`),context:r,underNot:i,treeFull:a,...n===`change`&&s!==void 0?{current:s}:{},...u?{}:{hidden:za},recentKey:`automation-${r}`,textsOf:Ba,categoryLabelOf:e=>l(`automation.leafPicker.category.${e}`),reasonOf:e=>l(`automation.leafPicker.reason.${e}`),onPick:e=>{c(e),t(!1)}})}var Ha=`none`;function Ua(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<=0))return Math.round(t*1e3)}function Wa({hold:t,modes:n,onChange:r}){let{t:i}=Q(),a={held:i(`automation.hold.held`,`held`),stable:i(`automation.hold.stable`,`stable`)},s=e=>{if(e===Ha){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($,{children:i(`automation.hold.label`,`For`)}),o(z,{value:t?.mode??Ha,onChange:e=>s(e.target.value),options:[{value:Ha,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($,{children:i(`automation.hold.seconds`,`Seconds`)}),o(Y,{type:`number`,min:1,value:String(t.ms/1e3),onChange:e=>{let n=Ua(e.target.value);r(n===void 0?void 0:{...t,ms:n})}})]}),t?.mode===`stable`&&e(`label`,{className:`w-28`,children:[o($,{children:i(`automation.hold.tolerance`,`± tolerance`)}),o(Y,{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 Ga({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Q(),c=Qa(n,r,i);if(n?.kind===`boolean`)return o(z,{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(z,{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(Y,{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(Y,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Ka({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Q(),s=Qa(t,n,r);return o(Y,{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 qa(e){return typeof e==`object`&&!qe(e)}function Ja(e){return qe(e)?e.value:qa(e)?e[0]??``:e}function Ya(e){return qe(e)?[e.value]:qa(e)?e:typeof e==`boolean`?[]:[e]}function Xa(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!Pe(t)||t===`none`||t===`device`))return Le(t).length>0?t:void 0}function Za(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Qa(e,t,n){let r=kt(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=en({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=Pe(s)?s:void 0,l=Za(e?.quantity,c);if(l===void 0)return;let u=o?.display;return St({quantity:l,display:u,capName:n,unitPreferences:r})}function $a({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Qi(a),c=Ni(s?.kind),l=t.operator===`in`,u=Xa(s),d=u===void 0?void 0:Re(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=eo(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...Ya(t.value)]:Ja(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o($i,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[o($,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(z,{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($,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Ka,{value:Ya(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?o(Rt,{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=Cn(e,d);r({...t,value:n.value,unit:n.unit})}}):o(Ga,{value:Ja(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]}),o(Wa,{hold:t.for,modes:[`held`,`stable`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})]})}function eo(e,t){return t.find(t=>t.value===e)?.value??`eq`}var to=Object.values(ie).sort((e,t)=>e.localeCompare(t));function no({leaf:t,onChange:n}){let{t:r}=Q();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[o($,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(Y,{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(Ln,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]})}function ro(){return o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Ln,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})}function io(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 ao(e){return e.operator===void 0?e.becomes===void 0?`any`:`becomes`:e.operator}var oo=[`any`,`becomes`,`gt`,`gte`,`lt`,`lte`,`between`,`outside`];function so(e){return e===`between`||e===`outside`}function co(e){if(e.trim()===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function lo(e){return typeof e==`number`?e:void 0}function uo({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Qi(a),c=Ee(t),l=ao(t),u=lo(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(io(a,_));return}if(e===`becomes`){r(io(a,{..._,becomes:``}));return}let t=te.safeParse(e);t.success&&r(io(a,{..._,operator:t.data,value:so(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($i,{value:a,devices:n,onChange:e=>r(io(e,f))}),e(`label`,{className:`min-w-[10rem]`,children:[o($,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),o(z,{value:l,onChange:e=>v(e.target.value),options:oo.map(e=>({value:e,label:y[e]}))})]}),l===`becomes`&&t.becomes!==void 0&&e(`div`,{className:`min-w-[9rem] flex-1`,children:[o($,{children:i(`automation.conditionRow.value`,`Value`)}),o(Ga,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(io(a,{...f,becomes:e}))})]}),t.operator!==void 0&&!so(l)&&e(`label`,{className:`w-28`,children:[o($,{children:i(`automation.conditionRow.value`,`Value`)}),o(Y,{type:`number`,step:`any`,value:u===void 0?``:String(u),onChange:e=>{let n=co(e.target.value);n!==void 0&&r(io(a,{...f,operator:t.operator,value:n}))}})]}),t.operator!==void 0&&so(l)&&[0,1].map(n=>e(`label`,{className:`w-24`,children:[o($,{children:n===0?i(`automation.triggerEditor.rangeFrom`,`From`):i(`automation.triggerEditor.rangeTo`,`To`)}),o(Y,{type:`number`,step:`any`,value:d[n]===void 0?``:String(d[n]),onChange:e=>{let i=co(e.target.value);if(i===void 0)return;let o=[d[0]??0,d[1]??0];o[n]=i,r(io(a,{...f,operator:t.operator,value:o}))}})]},n)),o(Wa,{hold:c,modes:[`held`,`stable`],onChange:e=>{let{hold:t,...n}=f;r(io(a,e===void 0?n:{...n,hold:e}))}}),e(`label`,{className:`w-28`,children:[o($,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(Y,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(io(a,{...f,debounceMs:fo(e.target.value)}))})]})]})}function fo(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function po({leaf:t,onChange:n}){let{t:r}=Q();return e(m,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o($,{children:r(`automation.triggerEditor.eventCategory`,`Event category`)}),o(z,{value:t.category,onChange:e=>n({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:r(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...to.map(e=>({value:e,label:e}))]})]}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o($,{children:r(`automation.triggerEditor.fromDevice`,`From device`)}),o(gn,{pick:`device`,excludeTypes:dr,recentKey:`build-targets`,value:t.deviceId===void 0?null:{deviceId:t.deviceId},placeholder:r(`automation.triggerEditor.anyDevice`,`Any device`),testId:`trigger-event-device`,onChange:e=>n({kind:`device-event`,category:t.category,...e===null?{}:{deviceId:e.deviceId}})})]})]})}function mo(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 ho(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 go={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function _o({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),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(un,{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(vo,{alias:e,source:r,devices:n,onRename:n=>s(xo(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(So(t.bindings,e))},e)),e(X,{variant:`ghost`,onClick:()=>s({...t.bindings,[bo(t.bindings)]:go}),children:[o(P,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]}),o(`div`,{className:`flex flex-wrap items-end gap-2`,children:o(Wa,{hold:t.for,modes:[`held`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})})]})}function vo({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Q(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:n.kind===`global`?ho(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($,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(Y,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o($,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(z,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:go),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($,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(Y,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:yo(e.target.value)})})]}):o($i,{value:u,devices:r,onChange:e=>a(mo(r,e))}),o(X,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(g,{className:`h-3.5 w-3.5`})})]})}function yo(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function bo(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 xo(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function So(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var Co=`event-emitter`;function wo(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`};let t=Xe.safeParse(e.data);return t.success?{kind:`known`,vocabulary:Ne(t.data)}:{kind:`unknown`}}function To(e){let t=new Map;for(let n of e)n.source!==void 0&&!t.has(n.source.id)&&t.set(n.source.id,n.source);return[...t.values()]}function Eo(e,t){let n=new Map;for(let r of e)t!==void 0&&r.source?.id!==t||n.has(r.id)||n.set(r.id,r);return[...n.values()]}function Do(e,t){return{kind:`device-fired`,...e.id===void 0?{}:{id:e.id},deviceId:t}}function Oo(e,t,n){let{sourceIds:r,eventIds:i,...a}=e,o=new Set(Eo(n,t).map(e=>e.id)),s=(i??[]).filter(e=>o.has(e));return{...a,...t===void 0?{}:{sourceIds:[t]},...s.length===0?{}:{eventIds:s}}}function ko(e,t){let{eventIds:n,...r}=e;return{...r,...t===void 0?{}:{eventIds:[t]}}}function Ao(e,t){let n=new Set(To(t).map(e=>e.id)),r=new Set(t.map(e=>e.id));return{sourceIds:(e.sourceIds??[]).filter(e=>!n.has(e)),eventIds:(e.eventIds??[]).filter(e=>!r.has(e))}}var jo=``,Mo={caps:[Co]};function No({leaf:t,hideDevice:n=!1,onChange:r}){let{t:i}=Q(),a=t.deviceId>0,s=Lt({deviceId:t.deviceId,capName:Co},{enabled:a}),c=wo({status:s.status,data:s.data}),l=c.kind===`known`?c.vocabulary:[],u=To(l),d=t.sourceIds?.[0],f=t.eventIds?.[0],p=Eo(l,d),h=c.kind===`known`?Ao(t,l):null,g=i(`automation.fired.anyEvent`,`Any event`),_=c.kind===`pending`?i(`automation.fired.loading`,`Reading what this device can fire…`):i(`automation.fired.unknown`,`What this device can fire could not be read.`);return e(m,{children:[!n&&e(`div`,{className:`min-w-[13rem] flex-1`,children:[o($,{children:i(`automation.fired.device`,`Device`)}),o(gn,{pick:`device`,requires:Mo,recentKey:`automation-device-fired`,value:a?{deviceId:t.deviceId}:null,onChange:e=>r(Do(t,e?.deviceId??0))})]}),a&&c.kind!==`known`&&o(`p`,{className:`min-w-[13rem] flex-1 text-xs ${c.kind===`unknown`?`text-warning`:`text-foreground-subtle`}`,"data-testid":`fired-vocabulary-${c.kind}`,children:_}),a&&c.kind===`known`&&u.length>0&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[o($,{children:i(`automation.fired.source`,`From`)}),o(z,{"data-testid":`fired-source`,value:d??jo,onChange:e=>r(Oo(t,e.target.value===jo?void 0:e.target.value,l)),options:[{value:jo,label:i(`automation.fired.anySource`,`Any button`)},...u.map(e=>({value:e.id,label:e.label})),...(h?.sourceIds??[]).map(e=>({value:e,label:i(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),a&&c.kind===`known`&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[o($,{children:i(`automation.fired.event`,`Event`)}),o(z,{"data-testid":`fired-event`,value:f??jo,onChange:e=>r(ko(t,e.target.value===jo?void 0:e.target.value)),options:[{value:jo,label:g},...p.map(e=>({value:e.id,label:e.label})),...(h?.eventIds??[]).map(e=>({value:e,label:i(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),h!==null&&h.sourceIds.length+h.eventIds.length>0&&o(`p`,{className:`basis-full text-xs text-warning`,"data-testid":`fired-stale`,children:i(`automation.fired.staleHint`,`This row names something the device no longer declares, so it will not start a run. Pick again.`)}),(t.kinds!==void 0||t.match!==void 0)&&o(`p`,{className:`basis-full text-xs text-foreground-subtle`,"data-testid":`fired-extra`,children:i(`automation.fired.extraHint`,`This row also carries filters set outside the editor ({{what}}); they are kept as they are.`,{what:[...t.kinds??[],...(t.match??[]).map(e=>`${e.path} = ${String(e.equals)}`)].join(`, `)})})]})}var Po=`text-xs text-foreground-subtle`;function Fo({children:e}){return o(`span`,{className:Po,children:e})}function Io(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function Lo({selected:t,onChange:n}){let{t:r}=Q();return e(`div`,{className:`space-y-1`,children:[o(Fo,{children:r(`flow.scene.cameras`,`Cameras`)}),o(gn,{multiple:!0,pick:`device`,noun:`camera`,fixedTypes:fr,recentKey:`build-cameras`,value:Nt(t),testId:`scene-cameras`,onChange:e=>n(jt(e))})]})}function Ro({device:t,deviceId:n,selected:r,onToggle:i}){let a=ht({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:Po,children:t?.name??`#${String(n)}`}),a.data.map(e=>o(X,{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 zo({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=Q();if(n.length===0)return null;let s=e=>{let t=Io(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(Fo,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(Ro,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:Po,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var Bo=[`animal`,`person`,`vehicle`,`package`,`other`];function Vo(e){return Bo.find(t=>t===e)??`other`}function Ho(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 Uo(){let{t:e}=Q();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 Wo(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 Go=[`automation`,`class-taxonomy`];function Ko(){let e=k();return Ae(l({queryKey:Go,retry:!1,staleTime:1/0,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}).data?.taxonomy)}function qo(e,t,n){let r=n?.groups.find(t=>t.key===e),i=r===void 0?ce(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 Jo({subject:e,onChange:t}){let{t:n}=Q(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=Ko(),a=qo(e.macro,r,i);return a.length===0?null:o(z,{"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===``?Ho(e.macro):Wo(e.macro,r))}})}function Yo({onChange:e,subject:t}){let{t:n}=Q(),r=an(),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(z,{"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 Xo=`plate:`,Zo=`class:`,Qo=200;function $o({onChange:e,subject:t}){let{t:n}=Q(),r=Et({includeCrops:!1,limit:Qo}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,s=Ko(),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?``:`${Zo}${c}`:`${Xo}${a}`;return o(z,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:u,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...qo(`vehicle`,c,s).map(e=>({value:`${Zo}${e.value}`,label:e.label})),...l.map(e=>({value:`${Xo}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(Xo)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(Zo)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function es({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:s}=Q(),c=Uo(),l=t.macro===`other`?[]:Oe[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(z,{"aria-label":s(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:Bo.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=Vo(e.target.value);n!==t.macro&&i(Ho(n))}})}),o(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?o(Y,{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(Yo,{subject:t,onChange:i})}):d&&!n?o(`div`,{className:`w-44`,children:o($o,{subject:t,onChange:i})}):!u&&o(`div`,{className:`w-44`,children:o(Jo,{subject:t,onChange:i})}),a!==null&&o(X,{variant:`ghost`,onClick:a,title:s(`automation.whenTree.removeClass`,`Remove this class`),children:o(g,{className:`h-3.5 w-3.5`})})]})}function ts({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:s}=Q(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>o(es,{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(X,{variant:`ghost`,size:`sm`,onClick:()=>a([...t,Ho(`person`)]),children:[o(P,{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 ns=100;function rs({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=Math.round((t.minScore??0)*ns),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/ns})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(ts,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),o(Lo,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(zo,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(Fo,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/ns).toFixed(2)})}),o(T,{min:0,max:ns,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 is({leaf:t,devices:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(ts,{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(Lo,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(zo,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(Ct,{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 as({leaf:t,onChange:n}){let{t:r}=Q();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(Fo,{children:r(`flow.scene.every`,`Every`)}),o(hr,{"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(Fo,{children:r(`flow.scene.minutes`,`minutes`)})]})}function os({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},s=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{zones:n,...i}=t;r({...i,deviceId:e})};return e(`div`,{className:`space-y-3`,"data-testid":`stationary-present-fields`,children:[e(`div`,{className:`space-y-1`,children:[o(Fo,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(gn,{pick:`device`,noun:`camera`,fixedTypes:fr,recentKey:`build-cameras`,clearable:!1,value:t.deviceId>0?{deviceId:t.deviceId}:null,testId:`stationary-present-camera`,onChange:e=>{e!==null&&e.deviceId!==t.deviceId&&c(e.deviceId)}})]}),o(ts,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.isParked`,`is parked`),onChange:a}),e(`div`,{className:`flex items-center gap-2`,children:[o(Fo,{children:i(`flow.scene.minCount`,`At least`)}),o(hr,{"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(Fo,{children:i(`flow.scene.minCountUnit`,`parked objects`)})]}),o(zo,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:s})]})}var ss=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],cs=720,ls=1440;function us(){return{name:``,enabled:!0,priority:0,maxLateMs:Ce,profiles:[ds(`profile-1`,`Every day`)]}}function ds(e,t){return{id:e,name:t,enabled:!0,days:[...ss],points:[]}}function fs(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function ps(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function ms(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function hs(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 gs(e,t=Date.now()){return ue(t,e.timeZone)}function _s(e,t,n){let r=ms(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=Te(e,n,r);return i===null?null:hs(i,t.timeZone)}function vs(e,t,n){return e.kind===`sun`?_s({...e,offsetMin:0},t,n):null}function ys(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(cs,t-n));return{...e,offsetMin:r}}return e}function bs(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 xs(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function Ss(e){return xs(Math.floor(e/60),e%60)}function Cs(e,t,n){let r=e.flatMap(e=>{let r=_s(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?ls:n.minute}]})}function ws(e,t){let n=ne.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=Ze(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}var Ts=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],Es=[`sunrise`,`sunset`,`dawn`,`dusk`],Ds={from:{kind:`clock`,hh:22,mm:0},to:{kind:`clock`,hh:6,mm:0}};function Os(e,t){return{kind:`time-is`,...e===void 0?{}:{between:e},...t===void 0?{}:{days:[...t]}}}function ks(e){return e.days??Ts}function As(e,t){let n=ks(e),r=n.includes(t)?n.filter(e=>e!==t):Ts.filter(e=>e===t||n.includes(e)),i=r.length===Ts.length;return Os(e.between,i&&e.between!==void 0?void 0:r)}function js(e,t){if(t){let t=e.days!==void 0&&e.days.length===Ts.length;return Os(e.between??Ds,t?void 0:e.days)}return Os(void 0,ks(e))}function Ms(e,t,n){return Os({...e.between??Ds,[t]:n},e.days)}function Ns(e){return e===`sun`?{kind:`sun`,event:`sunset`,offsetMin:0}:{kind:`clock`,hh:12,mm:0}}function Ps(e){return e.kind===`date`?Ns(`clock`):e}function Fs(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 Is(e,t){if(t===void 0)return null;let n=we(e,t)[0];return n===void 0?null:`${n.path}: ${n.message}`}function Ls({label:t,testId:n,end:r,onChange:i}){let{t:a}=Q(),s=e=>`${t}: ${e}`;return e(`div`,{role:`group`,"aria-label":t,"data-testid":n,children:[o($,{children:t}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(z,{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(Ns(t))}}),r.kind===`clock`&&o(Y,{type:`time`,className:`w-28`,"aria-label":s(a(`schedulers.point.time`,`Time`)),value:xs(r.hh,r.mm),onChange:e=>{let t=bs(e.target.value);t!==null&&t.kind===`clock`&&i(t)}}),r.kind===`sun`&&e(m,{children:[o(z,{wrapperClassName:`relative w-40`,"aria-label":s(a(`schedulers.point.sunEvent`,`Sun event`)),value:r.event,options:Es.map(e=>({value:e,label:a(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Es.find(t=>t===e.target.value);t!==void 0&&i({...r,event:t})}}),o(hr,{"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 Rs({leaf:t,onChange:n}){let{t:r}=Q(),i=t.between,a=ks(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($,{children:r(`automation.timeIs.window`,`Time of day`)}),o(z,{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(js(t,e.target.value===`between`))})]}),i!==void 0&&e(m,{children:[o(Ls,{label:r(`automation.timeIs.from`,`From`),testId:`time-is-from`,end:Ps(i.from),onChange:e=>n(Ms(t,`from`,e))}),o(Ls,{label:r(`automation.timeIs.to`,`To`),testId:`time-is-to`,end:Ps(i.to),onChange:e=>n(Ms(t,`to`,e))})]})]}),e(`div`,{children:[o($,{children:r(`schedulers.profile.days`,`Days`)}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":r(`schedulers.profile.days`,`Days`),children:Ts.map(e=>{let i=a.includes(e);return o(X,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,onClick:()=>n(As(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.`)}),Fs(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 zs(e,t){let n=e.leaf;if(n.kind!==`device-becomes`&&n.kind!==`device-event`&&n.kind!==`device-fired`)return;let r=t.find(e=>e.id===n.deviceId)?.name;return n.kind===`device-becomes`?r:n.kind===`device-fired`?[r,[...n.sourceIds??[],...n.eventIds??[]].join(` `)].filter(e=>e!==void 0&&e!==``).join(` · `)||void 0:r===void 0?n.category:`${n.category} · ${r}`}function Bs({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=La(),s=a.map(e=>e.id),c=Na(t,s),l=i(`automation.triggeredBy.triggers`,`Started by`);return e(`div`,{children:[o($,{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=zs(e,n);return o(X,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,className:`h-auto min-h-8 whitespace-normal py-1 text-left`,onClick:()=>r(Ma(t,e.id,s)),children:`${e.ordinal}. ${Pi(e.leaf.kind)}${a===void 0?``:` · ${a}`}`},e.id)})}),a.length>0&&t.leafIds.length===0&&o(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-none-picked`,children:i(`automation.triggeredBy.nonePicked`,`Pick at least one trigger.`)}),c.length>0&&o(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-missing`,children:i(`automation.triggeredBy.missing`,{count:c.length,defaultValue_one:`{{count}} chosen trigger no longer exists. Press a trigger to drop it.`,defaultValue_other:`{{count}} chosen triggers no longer exist. Press a trigger to drop them.`})})]})}function Vs(e){return e.kind===`all`||e.kind===`any`}function Hs(e){return[`when`,...e].join(`.`)}function Us(e){let t=e.when;return Vs(t)?t:{kind:`all`,children:[t]}}function Ws(e,t){return{...e,when:t}}function Gs(e){return Ws(e,Us(e))}function Ks(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?Ks(e.child,r):null;if(me(e))return null;let i=e.children[n];return i===void 0?null:Ks(i,r)}function qs(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=qs(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(me(e))return e;let a=e.children[r];if(a===void 0)return e;let o=qs(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 Js(e,t,n){let r=Us(e);return Ws(e,qs(r,t,n)??{kind:r.kind,children:[]})}function Ys(e){return{kind:e,children:[Ri(`device-is`)]}}function Xs(e,t,n){return Js(e,t,e=>Vs(e)?{kind:e.kind,children:[...e.children,n]}:e)}function Zs(e,t,n){return Js(e,t,()=>n)}function Qs(e,t){return Js(e,t,()=>null)}function $s(e,t,n){return Js(e,t,e=>Vs(e)?{kind:n,children:e.children}:e)}function ec(e,t){return t.length===0?e:Js(e,t,e=>({kind:`not`,child:e}))}function tc(e,t){return Js(e,t,e=>e.kind===`not`?e.child:e)}function nc(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=Ri(t);return fe(e)&&e.id!==void 0&&fe(n)?{...n,id:e.id}:n}function rc(e){let t=Us(e),n=t.children.length===0;return{depth:n?0:$e(t),leaves:n?0:_e(t),depthLimit:4,leafLimit:32}}function ic(e,t){let n=Us(e),r=1,i=n;for(let e of t){let t=Ks(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function ac(e,t,n){let r=t[t.length-1];if(r===void 0)return e;let i=t.slice(0,-1),a=Ks(Us(e),i);if(a===null||!Vs(a))return e;let o=r+n;return o<0||o>=a.children.length?e:Js(e,i,()=>({kind:a.kind,children:Hi(a.children,r,o)}))}function oc(e,t,n){let r=Hs(t),i=Hs(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 sc(e,t){return me(e)?t(e.kind):e.kind===`not`?`NOT ${sc(e.child,t)}`:e.children.map(e=>cc(e,t)).join(` · `)}function cc(e,t){return Vs(e)?`${e.kind.toUpperCase()} (${sc(e,t)})`:sc(e,t)}u();function lc({leaf:t,devices:n,context:r,underNot:i,toneClass:a,result:s,onNegate:l,move:u,onChange:d,onRemove:f}){let{t:p}=Q(),[m,h]=c(!1),_=fe(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($,{children:p(`automation.whenTree.rowType`,`Row type`)}),e(X,{variant:`outline`,"data-testid":`when-row-type`,className:`w-full justify-between`,onClick:()=>h(!0),title:p(`automation.leafPicker.changeType`,`Change type`),children:[o(`span`,{className:`truncate`,children:Pi(t.kind)}),o(`span`,{className:`text-foreground-subtle`,children:p(`automation.leafPicker.changeType`,`Change type`)})]}),o(Va,{open:m,onOpenChange:h,mode:`change`,context:r,underNot:i,treeFull:!1,current:t.kind,onPick:e=>{e!==t.kind&&d(nc(t,e))}})]}),o(J,{variant:_?`info`:`neutral`,"data-testid":`when-row-nature`,children:_?p(`automation.whenTree.natureEvent`,`Event`):p(`automation.whenTree.natureState`,`State`)}),o(`span`,{className:`flex-1`}),u!==void 0&&o(sa,{move:u}),l!==null&&o(X,{variant:`ghost`,onClick:l,title:p(`automation.whenTree.negateRow`,`Invert this row (NOT)`),children:`NOT`}),o(X,{variant:`ghost`,onClick:f,title:p(`automation.whenTree.removeRow`,`Remove this row`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:o(uc,{leaf:t,devices:n,onChange:d})}),s!==void 0&&o(`div`,{className:`mt-2`,children:s})]})}function uc({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return o(uo,{leaf:e,devices:t,onChange:n});case`device-event`:return o(po,{leaf:e,onChange:n});case`device-fired`:return o(No,{leaf:e,onChange:n});case`schedule`:return o(no,{leaf:e,onChange:n});case`interval`:return o(as,{leaf:e,onChange:n});case`manual`:return o(ro,{});case`detection`:return o(rs,{leaf:e,devices:t,onChange:n});case`stationary`:return o(is,{leaf:e,devices:t,onChange:n});case`device-is`:return o($a,{leaf:e,devices:t,onChange:n});case`stationary-present`:return o(os,{leaf:e,devices:t,onChange:n});case`expression`:return o(_o,{leaf:e,devices:t,onChange:n});case`time-is`:return o(Rs,{leaf:e,onChange:n});case`triggered-by`:return o(Bs,{leaf:e,devices:t,onChange:n})}}u();function dc(e){return e===`any`?`any`:`all`}function fc(e){return e===`pass`?`pass`:e===`fail`?`fail`:`idle`}function pc(e,t,n=!0){return e===void 0?t:n?li(fc(e)):di(fc(e))}function mc(e,t){return e.run?.nodes.get(Hs(t))}function hc({recipe:t,devices:n,onChange:r,run:i=null,hideRule:a=!1,context:s=`trigger`}){let{t:l}=Q(),u=Us(t),d=rc(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=Hs(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=>oc(t,e,a)),r(ac(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(wc,{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 gc({node:e,path:t,ctx:n,underNot:r,move:i,rail:a}){return me(e)?o(_c,{leaf:e,path:t,ctx:n,underNot:r,move:i}):e.kind===`not`?o(Cc,{child:e.child,path:t,ctx:n,move:i,rail:a}):o(wc,{block:e,path:t,ctx:n,underNot:r,move:i,rail:a,budgetText:null,emptyHint:null})}function _c({leaf:e,path:t,ctx:n,underNot:r,move:i}){let a=mc(n,t),s=n.run!==null&&n.run.triggerPath===Hs(t)?n.run.vars:void 0;return o(lc,{leaf:e,devices:n.devices,context:n.leafContext,underNot:r,toneClass:pc(a?.outcome,`border-border`),result:a===void 0?void 0:o(vc,{leaf:e,node:a,vars:s}),onNegate:r?null:()=>n.reshape(ec(n.recipe,t)),...i===null?{}:{move:i},onChange:e=>n.onChange(Zs(n.recipe,t,e)),onRemove:()=>n.reshape(Qs(n.recipe,t))})}function vc({leaf:e,node:t,vars:n}){return e.kind===`device-is`&&e.unit!==void 0?o(yc,{leaf:e,node:t,vars:n}):o(Xi,{node:t,vars:n,expected:t.expected,observed:t.observed})}function yc({leaf:e,node:t,vars:n}){let r=Xa(Qi({deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})),i=r===void 0?void 0:Re(r),a=t=>t===void 0?null:Xr(t,i,e.unit);return o(Xi,{node:t,vars:n,expected:a(t.rawExpected),observed:a(t.rawObserved)})}function bc({node:e}){return e===void 0?null:o(Xi,{node:e,expected:null,observed:null})}function xc({expanded:e,onToggle:t}){let{t:n}=Q(),r=e?n(`automation.whenTree.collapse`,`Collapse this block`):n(`automation.whenTree.expand`,`Expand this block`);return o(X,{variant:`ghost`,"aria-expanded":e,"aria-label":r,title:r,onClick:t,children:o(wt,{expanded:e})})}function Sc({node:e}){let{t}=Q(),n=`${t(`automation.whenTree.rowCount`,{count:_e(e)})} · ${sc(e,Pi)}`;return o(`p`,{"data-testid":`when-block-summary`,title:n,className:`break-words text-xs text-foreground-muted sm:truncate`,children:n})}function Cc({child:t,path:n,ctx:r,move:i,rail:a}){let{t:s}=Q(),c=!r.collapsed.has(Hs(n));return e(`div`,{className:`space-y-1.5 rounded border p-2 ${pc(mc(r,n)?.outcome,`border-warning/40`,!1)}`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(xc,{expanded:c,onToggle:()=>r.toggleCollapsed(n)}),o(J,{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(sa,{move:i}),e(X,{variant:`ghost`,onClick:()=>r.reshape(tc(r.recipe,n)),title:s(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[o(rt,{className:`h-3.5 w-3.5`}),` `,s(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),o(bc,{node:mc(r,n)}),c?o(`div`,{className:`pl-3`,children:o(gc,{node:t,path:[...n,0],ctx:r,underNot:!0,move:null,rail:a})}):o(Sc,{node:t})]})}function wc({block:t,path:n,ctx:r,underNot:i,move:a,rail:s,budgetText:l,emptyHint:u}){let{t:d}=Q(),f=n.length===0,p=f||!r.collapsed.has(Hs(n)),m=ic(r.recipe,n),[h,_]=c(!1),v=Ta(t.children,s),y=[{value:`all`,label:d(`automation.whenTree.allOf`,`All of (AND)`)},{value:`any`,label:d(`automation.whenTree.anyOf`,`Any of (OR)`)}];return e(`div`,{className:`space-y-2 rounded border p-2 ${pc(mc(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(xc,{expanded:p,onToggle:()=>r.toggleCollapsed(n)}),o(`div`,{className:`w-40`,children:o(z,{"aria-label":d(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:y,onChange:e=>r.onChange($s(r.recipe,n,dc(e.target.value)))})}),l!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:l}),o(`span`,{className:`flex-1`}),a!==null&&o(sa,{move:a}),!f&&!i&&o(X,{variant:`ghost`,onClick:()=>r.reshape(ec(r.recipe,n)),title:d(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!f&&o(X,{variant:`ghost`,onClick:()=>r.reshape(Qs(r.recipe,n)),title:d(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(bc,{node:mc(r,n)}),u!==null&&o(`p`,{className:`text-xs text-foreground-subtle`,children:u}),!p&&o(Sc,{node:t}),p&&t.children.length>0&&o(`div`,{className:`space-y-1.5 border-l-2 pl-3 ${Ea(s)}`,"data-testid":`when-block-rail`,"data-rail":s,children:t.children.map((e,i)=>o(gc,{node:e,path:[...n,i],ctx:r,underNot:!1,move:r.moveControls([...n,i],t.children.length),rail:v[i]??s},Hs([...n,i])))}),p&&e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:`outline`,onClick:()=>_(!0),title:d(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[o(P,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addRow`,`Add row`)]}),o(Va,{open:h,onOpenChange:_,mode:`add`,context:r.leafContext,underNot:i,treeFull:_e(Us(r.recipe))>=32,onPick:e=>r.onChange(Xs(r.recipe,n,Ri(e)))}),e(X,{variant:`outline`,disabled:!m,onClick:()=>r.onChange(Xs(r.recipe,n,Ys(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:rc(r.recipe).depthLimit}),children:[o(P,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addBlock`,`Add block`)]})]})]})}var Tc={kind:`all`,children:[]};function Ec(e){return e.kind===`wait`||e.kind===`command`}function Dc(e){return!me(e)&&e.kind!==`not`&&e.children.length===0?null:Se(e)}function Oc(e){let{if:t,else:n,...r}=e;return r}function kc({when:t,devices:n,hint:r,onChange:i,children:a}){let{t:s}=Q(),c=t===void 0?null:{when:t,actions:[]},l=t===void 0?null:Dc(t);return e(`div`,{className:`space-y-2 border-t border-border-subtle pt-2`,children:[o(Jt,{checked:t!==void 0,label:s(`automation.stepGuard.if`,`Only if…`),"aria-label":s(`automation.stepGuard.if`,`Only if…`),onCheckedChange:e=>i(e?Tc:void 0)}),c!==null&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:r}),o(hc,{hideRule:!0,context:`guard`,recipe:c,devices:n,onChange:e=>i(e.when)}),l!==null&&o(q,{variant:`warning`,message:l}),a]})]})}function Ac({step:t,devices:n,devicesState:r,variables:i,onChange:a}){let{t:s}=Q();return e(kc,{when:t.if,devices:n,hint:s(`automation.stepGuard.hint`,`Checked when this step is reached. If a state cannot be read, the step and its else are both skipped.`),onChange:e=>a(e===void 0?Oc(t):{...t,if:e}),children:[o(Jt,{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(Gc,{nested:!0,actions:t.else,devices:n,...r===void 0?{}:{devicesState:r},...i===void 0?{}:{variables:i},allowedKinds:[`command`,`wait`],onChange:e=>a({...t,else:e.filter(Ec)})})})]})}function jc({index:t,step:n,devices:r,devicesState:i,variables:a,depth:s=0,roundDevices:c,onChange:l}){let{t:u}=Q(),d={nested:!0,flowControl:!0,devices:r,depth:s+1,allowedKinds:xa(s+1),...c===void 0?{}:{roundDevices:c},...i===void 0?{}:{devicesState:i},...a===void 0?{}:{variables:a}};return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.choose.hint`,`Read top to bottom: the first branch whose condition is true runs, and only that one. If a condition cannot be read, nothing runs.`)}),n.branches.map((i,a)=>{let s={when:i.if,actions:[]},c=Dc(i.if);return e(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,"data-testid":`choose-branch-${String(t)}-${String(a)}`,children:[e(`div`,{className:`flex items-center gap-2`,children:[o($,{children:a===0?u(`automation.choose.if`,`If`):u(`automation.choose.elseIf`,`Otherwise, if`)}),o(X,{variant:`ghost`,className:`ml-auto`,disabled:!ga(n),"data-testid":`choose-remove-${String(t)}-${String(a)}`,onClick:()=>l(_a(n,a)),title:ga(n)?u(`automation.choose.removeBranch`,`Remove this branch`):u(`automation.choose.lastBranch`,`A choose keeps at least one branch`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(hc,{hideRule:!0,context:`guard`,recipe:s,devices:r,onChange:e=>l(va(n,a,{...i,if:e.when}))}),c!==null&&o(q,{variant:`warning`,message:c}),o($,{children:u(`automation.choose.then`,`Then run`)}),o(Gc,{...d,actions:i.steps,onChange:e=>l(va(n,a,{...i,steps:e.filter(Sa)}))})]},String(a))}),e(X,{variant:`outline`,"data-testid":`choose-add-${String(t)}`,disabled:!ma(n),onClick:()=>l(ha(n)),title:ma(n)?void 0:u(`automation.choose.maxBranches`,`A choose takes at most 6 branches`),children:[o(P,{className:`h-4 w-4`}),` `,u(`automation.choose.addBranch`,`Add a branch`)]}),o(Jt,{"data-testid":`choose-else-${String(t)}`,checked:n.else!==void 0,label:u(`automation.choose.else`,`Otherwise, run…`),"aria-label":u(`automation.choose.else`,`Otherwise, run…`),onCheckedChange:e=>l(ya(n,e?[]:void 0))}),n.else!==void 0&&o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(Gc,{...d,actions:n.else,onChange:e=>l(ya(n,e.filter(Sa)))})})]})}function Mc(e){return Object.entries(e).map(([e,t])=>({name:e,value:t}))}function Nc(e){return Object.fromEntries(e.map(e=>[e.name,e.value]))}function Pc(e,t,n){let r=Mc(e);return r.some((e,r)=>r!==t&&e.name===n)?e:Nc(r.map((e,r)=>r===t?{...e,name:n}:e))}function Fc(e,t,n){return Nc(Mc(e).map((e,r)=>r===t?{...e,value:n}:e))}function Ic(e){return!Object.keys(e).includes(``)}function Lc(e){return Ic(e)?{...e,"":``}:e}function Rc(e,t){return Nc(Mc(e).filter((e,n)=>n!==t))}var zc=`{{vars.name}}`;function Bc({index:t,vars:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`space-y-2`,children:[Mc(n).map((a,s)=>e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-40`,children:[o($,{children:i(`automation.actionList.setName`,`Variable`)}),o(Y,{"data-testid":`set-name-${String(t)}-${String(s)}`,value:a.name,spellCheck:!1,onChange:e=>r(Pc(n,s,e.target.value))})]}),e(`label`,{className:`min-w-40 flex-1`,children:[o($,{children:i(`automation.actionList.setValue`,`Value`)}),o(Y,{"data-testid":`set-value-${String(t)}-${String(s)}`,value:String(a.value),onChange:e=>r(Fc(n,s,e.target.value))})]}),o(X,{variant:`ghost`,onClick:()=>r(Rc(n,s)),title:i(`automation.actionList.setRemove`,`Remove this variable`),children:o(g,{className:`h-3.5 w-3.5`})})]},String(s))),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:`outline`,"data-testid":`set-add-${String(t)}`,disabled:!Ic(n),onClick:()=>r(Lc(n)),children:[o(P,{className:`h-4 w-4`}),` `,i(`automation.actionList.setAdd`,`Add a variable`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.setHint`,`The steps after this one can use it as {{slot}}.`,{slot:zc,interpolation:{escapeValue:!1}})})]})]})}function Vc({index:t,step:n,devices:r,devicesState:i,variables:a,depth:s=0,roundDevices:c,onChange:l}){let{t:u}=Q(),{loop:d}=n,f={count:u(`automation.repeat.byCount`,`A number of times`),while:u(`automation.repeat.byWhile`,`While a condition is true`),until:u(`automation.repeat.byUntil`,`Until a condition is true`),forEach:u(`automation.repeat.byForEach`,`Once for each device`)},p=d.by===`while`||d.by===`until`,h=p?Dc(d.when):null,g={name:W,hint:u(`automation.repeat.itemHint`,`the device of this round`)},_=d.by===`forEach`?[...a??[],g]:a,v=d.by===`forEach`?d.target.ids:c;return e(`div`,{className:`space-y-2`,children:[o(`div`,{className:`w-64`,children:o(z,{"data-testid":`repeat-by-${String(t)}`,"aria-label":u(`automation.repeat.by`,`Repeat`),value:d.by,onChange:e=>{let t=e.target.value;_i(t)&&t!==d.by&&l({...n,loop:xi(t)})},options:pi.map(e=>({value:e,label:f[e]}))})}),d.by===`count`&&e(`label`,{className:`block w-24`,children:[o($,{children:u(`automation.repeat.count`,`Times`)}),o(Y,{type:`number`,min:1,max:20,"data-testid":`repeat-count-${String(t)}`,value:String(d.count),onChange:e=>l({...n,loop:{...d,count:yi(Number(e.target.value))}})})]}),p&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:d.by===`while`?u(`automation.repeat.whileHint`,`Read before each round: if it is not true at the start, nothing runs. A condition that cannot be read ends the loop.`):u(`automation.repeat.untilHint`,`Read after each round, so the steps run at least once. A condition that cannot be read ends the loop.`)}),o(hc,{hideRule:!0,context:`guard`,recipe:{when:d.when,actions:[]},devices:r,onChange:e=>l({...n,loop:{...d,when:e.when}})}),h!==null&&o(q,{variant:`warning`,message:h}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-28`,children:[o($,{children:u(`automation.repeat.max`,`At most (rounds)`)}),o(Y,{type:`number`,min:1,max:50,"data-testid":`repeat-max-${String(t)}`,value:String(d.maxIterations),onChange:e=>l({...n,loop:{...d,maxIterations:bi(Number(e.target.value))}})})]}),e(`label`,{className:`w-40`,children:[o($,{children:u(`automation.repeat.wait`,`Pause between rounds (s)`)}),o(Y,{type:`number`,min:1,max:3600,"data-testid":`repeat-wait-${String(t)}`,value:d.waitS===void 0?``:String(d.waitS),placeholder:u(`automation.repeat.noWait`,`none`),onChange:e=>l({...n,loop:Si(d,e.target.value===``?null:Number(e.target.value))})})]})]}),o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.maxHint`,`A loop that reaches its maximum stops there, is marked in the run, and the run goes on.`)})]}),d.by===`forEach`&&e(`div`,{className:`space-y-1`,children:[o(gn,{multiple:!0,pick:`device`,maxItems:50,value:d.target.ids.map(e=>({deviceId:e})),onChange:e=>l({...n,loop:{...d,target:{kind:`devices`,ids:e.map(e=>e.deviceId)}}})}),o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.forEachHint`,`One round per device, in this order. In a round the steps read the device as the variable "item".`)})]}),o($,{children:u(`automation.repeat.steps`,`Each time, run`)}),o(`div`,{className:`border-l-2 border-border-subtle pl-3`,"data-testid":`repeat-steps-${String(t)}`,children:o(Gc,{nested:!0,flowControl:!0,actions:n.steps,devices:r,depth:s+1,allowedKinds:xa(s+1),maxSteps:10,...i===void 0?{}:{devicesState:i},..._===void 0?{}:{variables:_},...v===void 0?{}:{roundDevices:v},onChange:e=>l({...n,steps:e.filter(Sa)})})})]})}function Hc({index:t,step:n,devices:r,onChange:i}){let{t:a}=Q(),s={when:n.when,actions:[]},c=Dc(n.when),l=Di(n.timeoutS),u={s:a(`automation.waitUntil.unitSeconds`,`seconds`),min:a(`automation.waitUntil.unitMinutes`,`minutes`),h:a(`automation.waitUntil.unitHours`,`hours`)};return e(`div`,{className:`space-y-2`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.waitUntil.hint`,`The run pauses here until this is true. A value that cannot be read is not "true": the run keeps waiting.`)}),o(hc,{hideRule:!0,context:`guard`,recipe:s,devices:r,onChange:e=>i({...n,when:e.when})}),c!==null&&o(q,{variant:`warning`,message:c}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-24`,children:[o($,{children:a(`automation.waitUntil.timeout`,`At most`)}),o(Y,{type:`number`,min:1,"data-testid":`wait-until-timeout-${String(t)}`,value:String(l.value),onChange:e=>i({...n,timeoutS:Oi(Number(e.target.value),l.unit)})})]}),o(`div`,{className:`w-32`,children:o(z,{"data-testid":`wait-until-unit-${String(t)}`,"aria-label":a(`automation.waitUntil.unit`,`Unit`),value:l.unit,onChange:e=>i({...n,timeoutS:Oi(l.value,Ei(e.target.value)?e.target.value:l.unit)}),options:wi.map(e=>({value:e,label:u[e]}))})}),e(`label`,{className:`min-w-56 flex-1`,children:[o($,{children:a(`automation.waitUntil.onTimeout`,`If it does not happen in time`)}),o(z,{"data-testid":`wait-until-on-timeout-${String(t)}`,value:n.onTimeout,onChange:e=>i({...n,onTimeout:e.target.value===`stop`?`stop`:`continue`}),options:[{value:`continue`,label:a(`automation.waitUntil.continue`,`Go on with the next step`)},{value:`stop`,label:a(`automation.waitUntil.stop`,`Stop the run as a failure`)}]})]})]})]})}var Uc=[{value:`command`,labelKey:`automation.actionList.kindCap`},{value:`action`,labelKey:`automation.actionList.kindAction`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`wait-until`,labelKey:`automation.actionList.kindWaitUntil`},{value:`set`,labelKey:`automation.actionList.kindSet`},{value:`stop`,labelKey:`automation.actionList.kindStop`},{value:`choose`,labelKey:`automation.actionList.kindChoose`},{value:`parallel`,labelKey:`automation.actionList.kindParallel`},{value:`repeat`,labelKey:`automation.actionList.kindRepeat`},{value:`code`,labelKey:`automation.actionList.kindCode`}],Wc=[`set`,`stop`,`choose`,`wait-until`,`parallel`,`repeat`];function Gc({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:s,stepResults:c,nested:l=!1,flowControl:u=!1,maxSteps:d,roundDevices:f,depth:p=0,onChange:m}){let{t:h}=Q(),_=Uc.filter(e=>(i===void 0||i.includes(e.value))&&(u||!Wc.includes(e.value))),v=h(`automation.actionList.flowGuardHint`,`Checked when this step is reached. If it is false, or a state cannot be read, the step does nothing.`),y={up:h(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),down:h(`automation.actionList.runThisStepLater`,`Run this step later`),atFirst:h(`automation.actionList.alreadyFirstStep`,`This step already runs first`),atLast:h(`automation.actionList.alreadyLastStep`,`This step already runs last`)};return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:h(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((i,d)=>e(`div`,{className:`space-y-2 rounded border p-3 ${s===void 0?`border-border`:li(s[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(J,{variant:`default`,children:d+1}),e(`label`,{className:`w-40`,children:[o($,{children:h(`automation.actionList.step`,`Step`)}),o(z,{"data-testid":`step-kind-${String(d)}`,value:i.kind,onChange:e=>m(Bi(t,d,zi(Kc(e.target.value)))),options:_.map(e=>({value:e.value,label:h(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(sa,{move:{up:d===0?null:()=>m(Hi(t,d,d-1)),down:d===t.length-1?null:()=>m(Hi(t,d,d+1))},texts:y}),o(X,{variant:`ghost`,onClick:()=>m(Vi(t,d)),title:h(`automation.actionList.removeThisStep`,`Remove this step`),children:o(g,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o($,{children:h(`automation.actionList.seconds`,`Seconds`)}),o(Y,{type:`number`,min:0,max:3600,value:String(i.seconds),onChange:e=>m(Bi(t,d,{...i,seconds:Number(e.target.value)}))})]}),i.kind===`stop`&&e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`min-w-48 flex-1`,children:[o($,{children:h(`automation.actionList.stopReason`,`Reason`)}),o(Y,{"data-testid":`stop-reason-${String(d)}`,value:i.reason,maxLength:200,onChange:e=>m(Bi(t,d,{...i,reason:e.target.value}))})]}),e(`label`,{className:`w-48`,children:[o($,{children:h(`automation.actionList.stopOutcome`,`The run ends as`)}),o(z,{"data-testid":`stop-outcome-${String(d)}`,value:i.outcome,onChange:e=>m(Bi(t,d,{...i,outcome:e.target.value===`failed`?`failed`:`ok`})),options:[{value:`ok`,label:h(`automation.actionList.stopOk`,`A success`)},{value:`failed`,label:h(`automation.actionList.stopFailed`,`A failure`)}]})]})]}),i.kind===`set`&&o(Bc,{index:d,vars:i.vars,onChange:e=>m(Bi(t,d,{...i,vars:e}))}),i.kind===`wait-until`&&o(Hc,{index:d,step:i,devices:n,onChange:e=>m(Bi(t,d,e))}),i.kind===`repeat`&&o(Vc,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Bi(t,d,e))}),i.kind===`parallel`&&e(`div`,{className:`space-y-2`,"data-testid":`parallel-steps-${String(d)}`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:h(`automation.parallel.hint`,`These start together and the run goes on when all are done. If one fails, the run fails once the others finished.`)}),o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(Gc,{nested:!0,flowControl:!0,actions:i.steps,devices:n,devicesState:r,variables:a,allowedKinds:la,depth:p+1,...f===void 0?{}:{roundDevices:f},maxSteps:5,onChange:e=>m(Bi(t,d,{...i,steps:e.filter(ua)}))})})]}),i.kind===`choose`&&o(jc,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Bi(t,d,e))}),!l&&(i.kind===`stop`||i.kind===`set`)&&o(kc,{when:i.if,devices:n,hint:v,onChange:e=>{let{if:n,...r}=i;m(Bi(t,d,e===void 0?r:{...r,if:e}))}}),i.kind===`code`&&e(`label`,{className:`block`,children:[o($,{children:h(`automation.actionList.code`,`Code`)}),o(Xt,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:i.code,spellCheck:!1,onChange:e=>m(Bi(t,d,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(Ln,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),i.kind===`command`&&o(xr,{step:i,devices:n,variables:a,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Bi(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{},...i.if===void 0?{}:{if:i.if},...i.else===void 0?{}:{else:i.else}}))}),i.kind===`action`&&o(ia,{step:i,onChange:e=>m(Bi(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{}}))}),u&&(i.kind===`command`||i.kind===`action`)&&o(Jt,{"data-testid":`continue-on-error-${String(d)}`,checked:i.continueOnError===!0,label:h(`automation.actionList.continueOnError`,`Continue if this step fails`),"aria-label":h(`automation.actionList.continueOnError`,`Continue if this step fails`),onCheckedChange:e=>{let{continueOnError:n,...r}=i;m(Bi(t,d,e?{...r,continueOnError:!0}:r))}}),!l&&(i.kind===`wait`||i.kind===`command`)&&o(Ac,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>m(Bi(t,d,e))}),c?.[d]!==void 0&&o(Zi,{step:c[d],deviceName:e=>n.find(t=>t.id===e)?.name??`#${String(e)}`})]},`${i.kind}-${String(d)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(X,{variant:`outline`,disabled:d!==void 0&&t.length>=d,onClick:()=>m([...t,zi(_[0]?.value??`command`)]),children:[o(P,{className:`h-4 w-4`}),` `,h(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function Kc(e){return Uc.find(t=>t.value===e)?.value??`command`}function qc(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function Jc(e,t){return Me(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.hintKey??e.name}`,e.description)}))}function Yc(e){return e.some(e=>e.required===!0&&e.default===void 0)}function Xc(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function Zc(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function Qc(e,t){return e.filter(e=>e.required===!0&&!Zc(t[e.name])).map(e=>e.name)}function $c(e,t){let n={};for(let r of e){let e=t[r.name];Zc(e)&&(n[r.name]=e)}return n}u();function el({variable:e,value:t,onChange:n}){let{t:r}=Q(),i=e.label??e.name;return e.type===`number`?o(hr,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?o(_r,{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(_r,{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(Y,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function tl({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:s}=Q(),[l,u]=c(()=>Xc(n)),d=Qc(n,l);return o(wn,{open:!0,onOpenChange:e=>!e&&a(),children:e(_t,{"aria-label":s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(hn,{children:[o(lt,{children:s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),o(gt,{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(el,{variable:t,value:l[t.name],onChange:e=>u({...l,[t.name]:e})})]},t.name))}),e(Pt,{className:`flex flex-wrap gap-2`,children:[o(X,{variant:`ghost`,onClick:a,children:s(`common.cancel`,`Cancel`)}),e(X,{disabled:r||d.length>0,onClick:()=>i($c(n,l)),children:[r?o(S,{className:`h-4 w-4 animate-spin`}):o(R,{className:`h-4 w-4`}),` `,s(`actions.editor.runNow`,`Run now`)]})]})]})})}var nl=[`number`,`string`,`boolean`,`select`];function rl(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function il(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 al(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function ol(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function sl({variables:t,onChange:n,onRename:r}){let{t:i}=Q(),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(mt,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:at,actions:e(X,{variant:`outline`,size:`sm`,onClick:()=>n([...t,Sr(t)]),children:[o(P,{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(Y,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!Cr(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(Y,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,ol(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(_r,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:nl.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=nl.find(t=>t===e.target.value);t!==void 0&&s(l,rl(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(cl,{variable:c,onChange:e=>s(l,al(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(Y,{"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,il(c,e.target.value))})]}),o(X,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(g,{className:`h-4 w-4`})})]},`${String(l)}`)),o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function cl({variable:e,onChange:t}){let{t:n}=Q(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(hr,{"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(_r,{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(Y,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var ll=5e3;function ul(e){return e.kind===`command`||e.kind===`wait`}function dl(e){return e instanceof Error?e.message:String(e)}function fl(){let{t:e}=Q();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 pl({entry:t,onClose:i,onSaved:a,preset:l=null}){let{t:u}=Q(),d=f(),p=j(),h=ur(),_=fl(),[v,y]=c(()=>Er(t)),b=n(!1);s(()=>{if(t!==null||l!==`trigger-alarm`||b.current)return;let e=h.find(e=>e.type===G.AlarmPanel);e!==void 0&&(b.current=!0,y(Dr(e.id,u(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[h,t,l,u]);let[C,w]=c(null),[T,E]=c(!1),D=t!==null&&t.readOnly,O=()=>{d.invalidateQueries({queryKey:[[`actions`]]})},k=cn({onSuccess:e=>{O(),a(e.action.id)}}),A=pt({onSuccess:O}),M=Qt({onSuccess:()=>{O(),i()}}),N=Dn({onSuccess:O}),P=An({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:ll}),F=P.data?.traces.find(e=>e.runId===C)??null,I=r(()=>F===null?null:Vr(F),[F]),L=r(()=>F===null?null:qr(F).steps,[F]),z=wr(v),B=r(()=>qc(v.variables,u),[v.variables,u]),V=k.isPending||A.isPending,ee=k.error??A.error??M.error??N.error,H=Yc(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(x,{className:`h-4 w-4 text-foreground-muted`}),o(Y,{"aria-label":u(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:v.name,disabled:D,placeholder:u(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>y({...v,name:e.target.value})}),o(J,{variant:D?`info`:`primary`,children:D?t?.addonId??``:u(`actions.source.internal`,`Internal`)})]}),D?o(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:u(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(m,{children:[o(sl,{variables:v.variables,onChange:e=>y({...v,variables:e}),onRename:(e,t)=>y(Tr(v,e,t))}),o(fi,{step:`steps`,title:u(`actions.editor.steps`,`Steps`),trace:I===null?null:I.thenBlock,children:o(Gc,{actions:v.steps,devices:h,allowedKinds:[`command`,`wait`],stepTones:I===null?void 0:v.steps.map((e,t)=>Hr(I,t)??`idle`),stepResults:L===null?void 0:v.steps.map((e,t)=>L.find(e=>e.index===t)),variables:B,onChange:e=>y({...v,steps:e.filter(ul)})})})]}),!z.ok&&!D&&v.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:_(z.reason)}),ee!==null&&o(q,{message:dl(ee)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!D&&e(X,{onClick:()=>{z.ok&&(t===null?k.mutate({action:z.input}):A.mutate({actionId:t.id,action:z.input}))},disabled:V||!z.ok,children:[V&&o(S,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),t!==null&&e(X,{variant:`outline`,disabled:N.isPending,onClick:()=>H?E(!0):N.mutate({actionId:t.id}),children:[o(R,{className:`h-4 w-4`}),` `,u(`actions.editor.runNow`,`Run now`)]}),t!==null&&!D&&e(X,{variant:`ghost`,disabled:M.isPending,onClick:()=>{p({title:u(`actions.editor.deleteTitle`,`Delete this action?`),message:u(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:u(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&M.mutate({actionId:t.id})})},children:[o(g,{className:`h-4 w-4`}),` `,u(`common.delete`,`Delete`)]}),o(X,{variant:`ghost`,onClick:i,children:u(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(ci,{traces:t===null?[]:P.data?.traces,selectedId:C,onSelect:w})}),T&&t!==null&&o(tl,{actionName:t.name,variables:t.variables??[],running:N.isPending,onCancel:()=>E(!1),onRun:e=>{N.mutate({actionId:t.id,variables:e}),E(!1)}})]})}u();var ml=5e3;function hl(e){return e instanceof Error?e.message:String(e)}function gl(){let{t:e}=Q();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 _l({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),[a]=Un(),c=f(),l=gl(),{state:u,openNew:d,openEdit:p,close:h}=Yt({editKey:`action`,newKey:`new`}),g=tn({},{refetchInterval:ml}),_=Dn({onSuccess:()=>void c.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(d(),n?.())},[t,n,d]);let v=g.data??[],y=u.mode===`edit`?v.find(e=>e.id===u.id)??null:null,b=r(()=>[{key:`name`,header:i(`actions.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:i(`actions.list.source`,`Source`),render:e=>e.readOnly?o(J,{variant:`info`,children:e.addonId}):o(J,{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:`-`}):qn(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(J,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(X,{variant:`outline`,size:`sm`,disabled:_.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),_.mutate({actionId:t.id})},children:[o(R,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[_,l,i]);return u.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),_.error!=null&&o(q,{message:hl(_.error)}),g.data===void 0?g.error==null?o(ct,{className:`h-24 w-full`}):o(q,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:hl(g.error),onRetry:()=>void g.refetch()}):v.length===0?o(dt,{icon:x,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(X,{onClick:d,children:[o(P,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(m,{children:[g.error!=null&&o(q,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:hl(g.error),onRetry:()=>void g.refetch()}),o(Vt,{columns:b,rows:v,rowKey:e=>e.id,pageSize:25,maxBodyHeight:vt,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>p(e.id)})]})]}):o(pl,{entry:y,onClose:h,onSaved:p,preset:u.mode===`new`?a.get(`preset`):null},y?.id??`new`)}u();function vl({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Q(),[l,u]=c(!1),d=j(),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(X,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?et:O,{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(X,{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(tt,{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(Mn,{maxHeight:420,children:t})})]})}var yl=[`single`,`restart`,`queued`,`parallel`,`cooldown`],bl=2,xl=30;function Sl(e){return e.runMode??{mode:`single`}}function Cl(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function wl(e){switch(e){case`queued`:return{mode:`queued`,max:bl};case`parallel`:return{mode:`parallel`,max:bl};case`cooldown`:return{mode:`cooldown`,minutes:xl};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function Tl(e){return yl.find(t=>t===e)??`single`}function El({value:t,onChange:n}){let{t:r}=Q(),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(_r,{widthClass:`w-56`,value:t.mode,options:yl.map(e=>({value:e,label:i[e]})),onChange:e=>n(wl(Tl(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(hr,{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(hr,{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 Dl;function Ol(){return Dl??=Ue(re),Dl}function kl(e,t=Ol()){return Ge(e,t)}u();var Al=`hub`,jl=5e3;function Ml({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d,onSaveAsTemplate:f,savingAsTemplate:p=!1}){let{t:m}=Q(),[h,g]=c(t?.name??``),[_,v]=c(()=>Gs(n)),y=e=>v(ja(e)),[b,x]=c(!1),[C,w]=c(null),T=bt({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:jl}),E=T.data?.traces.find(e=>e.runId===C)??null,D=r(()=>E===null?null:Vr(E),[E]),O=r(()=>Jc(_.when,m),[_.when,m]),k=r(()=>E===null?null:Jr(E),[E]),A=r(()=>E===null?null:qr(E).steps,[E]),j=ur(),M=ze(_),N=r(()=>Nl(_),[_]),P=r(()=>Pl(h.trim()===``?`Untitled automation`:h.trim(),_),[h,_]),F=qt().data,I=r(()=>N===null?Is(_,F):null,[_,F,N]),L=h.trim()===``,R=L||M!==null||N!==null||I!==null||P.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[o(Ia,{when:_.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:m(`automation.automationEditor.name`,`Name`)}),o(Y,{className:`mt-1`,value:h,onChange:e=>g(e.target.value),placeholder:m(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(fi,{step:`when`,title:m(`automation.automationEditor.when`,`When`),trace:D===null?null:D.when,children:o(hc,{recipe:_,devices:j,run:k,onChange:y})}),o(fi,{step:`then`,title:m(`automation.automationEditor.then`,`Then`),trace:D===null?null:D.thenBlock,hint:m(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(Gc,{flowControl:!0,actions:_.actions,devices:j,variables:O,stepTones:D===null?void 0:_.actions.map((e,t)=>Hr(D,t)??`idle`),stepResults:A===null?void 0:_.actions.map((e,t)=>A.find(e=>e.index===t)),onChange:e=>y(Ui(_,e))})}),o(fi,{step:`mode`,title:m(`flow.runMode.title`,`Overlap`),trace:null,hint:m(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:o(El,{value:Sl(_),onChange:e=>y(Cl(_,e))})}),o(vl,{code:P.code,error:P.error,canEject:t!==null,ejecting:s,onEject:u}),M!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:M}),M===null&&N!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:N}),M===null&&I!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`automation-site-error`,children:I}),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(X,{onClick:()=>{P.code!==null&&l({name:h.trim(),code:P.code,enabled:t?.enabled??!0,placement:Al})},disabled:i||R,children:[i&&o(S,{className:`h-4 w-4 animate-spin`}),` `,m(`common.save`)]}),e(X,{variant:`ghost`,onClick:()=>x(!b),disabled:t===null,title:t===null?m(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):m(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,"aria-expanded":b,children:[o(V,{className:`h-4 w-4`}),` `,m(`common.logs`),` `,o(wt,{expanded:b})]}),f!==void 0&&o(X,{variant:`outline`,disabled:i||p||R,onClick:()=>f({name:h.trim(),recipe:_}),"data-testid":`automation-save-as-template`,children:m(`build.templates.saveAsTemplate`,`Save as template`)}),o(X,{variant:`ghost`,onClick:d,disabled:i,children:m(`common.close`,`Close`)}),L&&o(J,{variant:`warning`,children:m(`automation.automationEditor.nameRequired`,`Name required`)})]}),b&&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(Ln,{i18nKey:`common.logsOf`,values:{id:se(t.id)},components:{code:o(`code`,{})}})}),o(pn,{addonId:se(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}),o(`div`,{className:`order-first lg:order-last`,children:o(ci,{traces:t===null?[]:T.data?.traces,selectedId:C,onSelect:w})})]})}function Nl(e){let t=ae.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Z.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Pl(e,t){let n=kl(t);if(!n.ok)return{code:null,error:n.error};try{return{code:Qe({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Fl(e){if(!e.enabled)return{tone:`idle`,label:Z.t(`helpers.coreBlockStatus.disabled`),detail:Z.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Z.t(`helpers.coreBlockStatus.running`),detail:Z.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Z.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Z.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Z.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Il(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Ll(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Rl(e){let t=e=>{let t=Fl(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 zl(e){if(e.length===0)return Z.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Fl(e).tone===`error`).length,n=e.filter(e=>Fl(e).tone===`ok`).length,r=[Z.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Z.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Z.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var Bl=3e4;function Vl({block:t,logsOpen:n,unreadable:r,flagged:i=!1}){let a=E(),{t:s}=Q(),c=Fl(t),l=zt(t.updatedAt,a);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(J,{variant:Il(c.tone),children:c.label}),i&&o(J,{variant:`warning`,"data-testid":`automation-flagged-badge`,children:s(`build.templates.flagged`,`Flagged`)}),l!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`common.edited`,{when:l})})]}),(c.tone===`error`||c.tone===`pending`)&&o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:c.detail}),r!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:s(`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(Ln,{i18nKey:`common.logsOf`,values:{id:se(t.id)},components:{code:o(`code`,{})}})}),o(pn,{addonId:se(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var Hl=2;function Ul(e){let t=[];if(be(e.when,e=>{fe(e)&&t.push(Pi(e.kind))}),t.length===0)return _e(e.when)===0?``:Z.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,Hl).join(`, `),i=n.length-Hl;return i>0?`${r} +${i}`:r}function Wl({recipe:e}){let{t}=Q();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=Ul(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function Gl({blockId:t}){let{t:n}=Q(),r=bt({blockId:t},{refetchInterval:Bl});if(r.data===void 0)return r.error===null||r.error===void 0?o(ct,{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:[qn(i.lastAt),a&&o(J,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function Kl({block:e,disabled:t,onToggle:n}){let{t:r}=Q();return o(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(Jt,{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 ql({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=Q();return o(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(rn,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:A,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:R,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:V,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:g,danger:!0,separatorBefore:!0,onClick:r}]})})}function Jl({onCreate:t}){let{t:n}=Q();return o(dt,{icon:w,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(X,{onClick:t,"data-testid":`automation-empty-new`,children:[o(P,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();function Yl({open:t,onBlank:n,onTemplate:r,onClose:i}){let{t:a}=Q(),c=vn({kind:`automation`},{enabled:t}),l=c.data!==void 0&&c.data.length===0;return s(()=>{t&&l&&n()},[t,l,n]),o(wn,{open:t&&!l,onOpenChange:e=>!e&&i(),children:e(_t,{width:`md`,placement:`sheet-on-mobile`,children:[o(hn,{children:o(lt,{children:a(`build.templates.newAutomationTitle`,`New automation`)})}),e(Bt,{className:`space-y-2`,"data-testid":`new-automation-chooser`,children:[o(X,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:n,"data-testid":`new-automation-blank`,children:e(`span`,{className:`block`,children:[o(`span`,{className:`block font-medium`,children:a(`build.templates.blank`,`Blank`)}),o(`span`,{className:`block text-xs text-foreground-muted`,children:a(`build.templates.blankHint`,`Start from an empty trigger and steps.`)})]})}),c.data===void 0?o(ct,{className:`h-10 w-full`}):c.data.map(t=>o(X,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>r(t.id),"data-testid":`new-automation-template-${t.id}`,children:e(`span`,{className:`block`,children:[o(`span`,{className:`block font-medium`,children:t.name}),o(`span`,{className:`block text-xs text-foreground-muted`,children:H.safeParse(t.payload).data?.description??a(`build.templates.fromTemplateHint`,`From a template — only its inputs to fill in.`)})]})},t.id))]})]})})}u();var Xl=`s`,Zl=60;function Ql(e){return e!==void 0&&e>=Zl&&e%Zl===0?`min`:Xl}function $l({value:e,min:t,max:n,disabled:r=!1,"aria-label":i,onChange:a}){let[s,l]=c(()=>Ql(e));return o(Rt,{quantity:`duration`,storedUnit:Xl,unit:s,value:e,disabled:r,...t===void 0?{}:{min:t},...n===void 0?{}:{max:n},...i===void 0?{}:{"aria-label":i},onChange:e=>{l(e.unit);try{a(Math.round(Cn(e,Xl).value))}catch{a(void 0)}}})}var eu=`hub`;function tu(e){switch(e.kind){case`number`:case`duration`:case`text`:case`select`:case`boolean`:return e.default;default:return}}function nu(e){let t={};for(let n of e.inputs){let e=tu(n);e!==void 0&&(t[n.key]=e)}return t}function ru(e){return{min:e.minRows??(e.optional===!0?0:1),max:e.maxRows??20}}function iu(e){let t={};for(let n of e.inputs){if(n.kind===`group`){t[n.key]=Array.from({length:ru(n).min},()=>nu(n));continue}let e=tu(n);e!==void 0&&(t[n.key]=e)}return t}function au(e,t,n){let{[t]:r,...i}=e;return n===void 0?i:{...i,[t]:n}}function ou(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e)):[]}function su(e,t,n,r,i){let a=ou(e,t).map((e,t)=>{if(t!==n)return e;let{[r]:a,...o}=e;return i===void 0?o:{...o,[r]:i}});return{...e,[t]:a}}function cu(e,t){let n=ou(e,t.key);return n.length>=ru(t).max?e:{...e,[t.key]:[...n,nu(t)]}}function lu(e,t,n){let r=ou(e,t.key);return r.length<=ru(t).min?e:{...e,[t.key]:r.filter((e,t)=>t!==n)}}function uu(e,t){return e.filter(e=>e.input===t)}function du(e,t){let n=new Set(t.map(e=>e.key));return e.filter(e=>e.input===void 0||!n.has(e.input.split(`.`)[0]??``))}function fu(e,t,n){let r=kl(t);if(!r.ok)return{ok:!1,problems:[{code:`invalid-recipe`,detail:r.error}]};try{return{ok:!0,recipe:r.recipe,input:{name:e,code:Qe({name:e,recipe:r.recipe}),enabled:n,placement:eu}}}catch(e){return{ok:!1,problems:[{code:`invalid-recipe`,detail:e instanceof Error?e.message:String(e)}]}}}function pu(e,t,n,r,i){let a=xe(e,t,n);return a.ok?fu(r,a.recipe,i):a}function mu(e,t,n){return fu(t,ge(e),n)}function hu(e){return typeof e==`number`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`number`):[]}function gu(e){let t=We.safeParse(e);return t.success?t.data:void 0}function _u(e){let t=je.safeParse(e);return t.success?t.data:void 0}function vu({payload:e,values:t,problems:n,disabled:r=!1,onChange:i}){return o(`div`,{className:`space-y-4`,"data-testid":`template-inputs-form`,children:e.inputs.map(a=>a.kind===`group`?o(yu,{group:a,values:t,problems:n,disabled:r,onChange:i},a.key):o(bu,{input:a,siblings:a.kind===`event`||a.kind===`action`?e.inputs:[],siblingValues:t,address:a.key,problems:n,disabled:r,onChange:e=>i(au(t,a.key,e))},a.key))})}function yu({group:t,values:n,problems:r,disabled:i,onChange:a}){let{t:s}=Q(),c=ou(n,t.key),l=ru(t),u=uu(r,t.key);return e(`section`,{className:`space-y-2`,"data-testid":`template-group-${t.key}`,children:[o(`h4`,{className:`text-sm font-medium text-foreground`,children:t.label}),u.map(e=>o(`p`,{role:`alert`,className:`text-xs text-danger`,children:e.detail},e.detail)),c.map((u,d)=>e(`div`,{className:`space-y-3 rounded-md border border-border bg-surface p-3`,"data-testid":`template-group-${t.key}-row`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[o(`span`,{className:`text-xs font-medium text-foreground-muted`,children:s(`build.templates.row`,`Row {{n}}`,{n:d+1})}),o(Dt,{icon:g,size:`sm`,variant:`ghost`,"aria-label":s(`build.templates.removeRow`,`Remove row`),disabled:i||c.length<=l.min,onClick:()=>a(lu(n,t,d))})]}),o(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:t.inputs.map(e=>o(bu,{input:e,siblings:t.inputs,siblingValues:u,address:`${t.key}.${String(d)}.${e.key}`,problems:r,disabled:i,onChange:r=>a(su(n,t.key,d,e.key,r))},e.key))})]},d)),e(X,{size:`sm`,variant:`outline`,disabled:i||c.length>=l.max,onClick:()=>a(cu(n,t)),"data-testid":`template-group-${t.key}-add`,children:[o(P,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),s(`build.templates.addRow`,`Add row`)]})]})}function bu({input:e,siblingValues:t,address:n,problems:r,disabled:i,onChange:a}){let s=uu(r,n),c=s.length===0?void 0:s.map(e=>e.detail).join(` `),l=t[e.key];return o(K,{label:e.label,required:e.optional!==!0,...e.description===void 0?{}:{description:e.description},...c===void 0?{}:{error:c},className:`min-w-0`,children:o(xu,{input:e,value:l,siblingValues:t,address:n,disabled:i,onChange:a})})}function xu({input:e,value:t,siblingValues:n,address:r,disabled:i,onChange:a}){let{t:s}=Q(),c=ur();switch(e.kind){case`device`:{let n=e.filter?.capability===void 0?{}:{requires:{caps:[e.filter.capability]}},s=e.filter?.role===void 0?{}:{fixedTypes:[e.filter.role]};if(e.multiple===!0)return o(gn,{pick:`device`,multiple:!0,...n,...s,recentKey:`template-input-${e.key}`,testId:`template-input-${r}`,disabled:i,value:hu(t).map(e=>({deviceId:e})),onChange:e=>{let t=e.map(e=>e.deviceId);a(t.length===0?void 0:t)}});let c=hu(t)[0];return o(gn,{pick:`device`,...n,...s,recentKey:`template-input-${e.key}`,testId:`template-input-${r}`,disabled:i,value:c===void 0?null:{deviceId:c},onChange:e=>a(e===null?void 0:e.deviceId)})}case`event`:{let i=hu(n[e.deviceInput])[0];if(i===void 0)return o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`template-input-${r}`,children:s(`build.templates.pickDeviceFirst`,`Pick the device first.`)});let c=gu(t),l={kind:`device-fired`,deviceId:i,...c?.eventIds===void 0?{}:{eventIds:c.eventIds},...c?.sourceIds===void 0?{}:{sourceIds:c.sourceIds},...c?.kinds===void 0?{}:{kinds:c.kinds}};return o(`div`,{className:`flex flex-wrap items-end gap-2`,"data-testid":`template-input-${r}`,children:o(No,{leaf:l,hideDevice:!0,onChange:e=>{let t={...e.eventIds===void 0?{}:{eventIds:e.eventIds},...e.sourceIds===void 0?{}:{sourceIds:e.sourceIds},...e.kinds===void 0?{}:{kinds:e.kinds}};a(We.safeParse(t).success?t:void 0)}})})}case`action`:{let i=e.deviceInput===void 0?[]:hu(n[e.deviceInput]);if(e.deviceInput!==void 0&&i.length===0)return o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`template-input-${r}`,children:s(`build.templates.pickDevicesFirst`,`Pick the devices first.`)});let l=_u(t);return o(`div`,{"data-testid":`template-input-${r}`,children:o(xr,{autoOpen:!1,devices:c,variables:[],step:{kind:`command`,target:{kind:`devices`,ids:[...i]},actionId:l?.actionId??``,...l?.args===void 0?{}:{args:l.args}},onChange:e=>a({actionId:e.actionId,...e.args===void 0?{}:{args:e.args}})})})}case`duration`:return o(`span`,{"data-testid":`template-input-${r}`,children:o($l,{value:typeof t==`number`?t:void 0,disabled:i,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},"aria-label":e.label,onChange:a})});case`number`:return o(Y,{type:`number`,"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`number`?String(t):``,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},onChange:e=>{let t=e.target.value===``?void 0:Number(e.target.value);a(t===void 0||Number.isNaN(t)?void 0:t)}});case`text`:return o(Y,{"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`string`?t:``,...e.maxLength===void 0?{}:{maxLength:e.maxLength},onChange:e=>a(e.target.value===``?void 0:e.target.value)});case`select`:return o(z,{"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`string`?t:``,options:[...e.optional===!0||typeof t!=`string`?[{value:``,label:s(`build.templates.choose`,`Choose…`)}]:[],...e.options.map(e=>({value:e.value,label:e.label}))],onChange:e=>a(e.target.value===``?void 0:e.target.value)});case`boolean`:return o(Jt,{"data-testid":`template-input-${r}`,disabled:i,checked:t===!0,onCheckedChange:e=>a(e),label:e.label})}}u();function Su({templateId:t,templateName:n,payload:i,existing:a,currentRecipe:s,initialName:l,initialValues:u,storedProblems:d,saving:f,saveError:p,onSave:m,onCancel:h}){let{t:g}=Q(),_=j(),[v,y]=c(l),[b,x]=c(u),[C,w]=c(!1),T=a?.enabled??!0,E=d.length>0,D=r(()=>i===null?null:pu(t,i,b,v.trim(),T),[i,t,b,v,T]),O=C&&D!==null&&!D.ok?D.problems:[],k=v.trim()===``,A=()=>{w(!0),!(D===null||!D.ok||k)&&m(D.input)},M=async()=>{if(s===null||!await _({title:g(`build.templates.convertTitle`,`Convert to a free automation?`),message:g(`build.templates.convertMessage`,`{{name}} keeps running as it is, but stops following the template.`,{name:v.trim()===``?l:v.trim()}),confirmLabel:g(`build.templates.convert`,`Convert to a free automation`)}))return;let e=mu(s,v.trim()===``?l:v.trim(),T);e.ok&&m(e.input)};return e(`div`,{className:`space-y-4`,"data-testid":`template-instance-editor`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-foreground-subtle`,children:[o(`span`,{children:n===null?g(`build.templates.templateGone`,`The template of this automation no longer exists.`):g(`build.templates.fromTemplate`,`From the template {{name}}`,{name:n})}),E&&o(J,{variant:`warning`,"data-testid":`template-flagged-badge`,children:g(`build.templates.flagged`,`Flagged`)})]}),E&&e(`div`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`template-flagged-problems`,children:[o(`p`,{className:`font-medium`,children:g(`build.templates.flaggedExplain`,`The template changed and these values no longer fit. The automation keeps running as it last did.`)}),o(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:d.map(e=>o(`li`,{children:e.detail},`${e.input??``}:${e.detail}`))})]}),e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`automation.automationEditor.name`,`Name`)}),o(Y,{className:`mt-1`,value:v,onChange:e=>y(e.target.value),"data-testid":`template-instance-name`})]}),i!==null&&o(vu,{payload:i,values:b,problems:O,disabled:f,onChange:x}),i!==null&&du(O,i.inputs).map(e=>o(`p`,{role:`alert`,className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:e.detail},e.detail)),p!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:p}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i!==null&&e(X,{onClick:A,disabled:f||k,"data-testid":`template-instance-save`,children:[f&&o(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`,`Save`)]}),a!==null&&s!==null&&o(X,{variant:`outline`,onClick:()=>void M(),disabled:f,"data-testid":`template-instance-convert`,children:g(`build.templates.convert`,`Convert to a free automation`)}),o(X,{variant:`ghost`,onClick:h,disabled:f,children:g(`common.close`,`Close`)}),k&&o(J,{variant:`warning`,children:g(`automation.automationEditor.nameRequired`,`Name required`)})]})]})}function Cu({templateId:e,existing:t,recipe:n,saving:r,saveError:i,onSave:a,onCancel:s}){let{t:c}=Q(),l=xn({id:e});if(l.status===`error`)return o(q,{title:c(`build.templates.loadFailed`,`Could not read the template`),message:l.error.message,onRetry:()=>void l.refetch()});if(l.data===void 0)return o(ct,{className:`h-24 w-full`});let u=l.data,d=u===null?null:H.safeParse(u.payload);if(d!==null&&!d.success)return o(q,{title:c(`build.templates.unreadable`,`This template cannot be read`),message:d.error.issues[0]?.message??``});let f=d===null?null:d.data,p=n?.template;return o(Su,{templateId:e,templateName:u===null?null:u.name,payload:f,existing:t,currentRecipe:n,initialName:t?.name??u?.name??``,initialValues:p?.values??(f===null?{}:iu(f)),storedProblems:p?.problems??[],saving:r,saveError:i,onSave:a,onCancel:s},t?.id??`new:${e}`)}var wu=`fromTemplate`;u();var Tu=[`coreBlocks`,`list`],Eu=5e3;function Du(e){return e instanceof Error?e.message:String(e)}function Ou({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:u}=Q(),d=k(),{state:f,openNew:m,openEdit:h,close:g}=Yt({editKey:`block`,newKey:`new`}),_=j(),[v,y]=c(null),[b,x]=c(!1),[S,C]=c(null),[T,E]=c(null),[D,O]=Un(),A=Rn(),M=ot(),N=D.get(wu),P=f.mode!==`closed`;s(()=>{n&&(x(!0),i?.())},[n,i]),s(()=>{N!==null&&(C(N),O(e=>{let t=new URLSearchParams(e);return t.delete(wu),t},{replace:!0}))},[N,O]);let F=a(()=>{x(!1),m()},[m]),I=l({queryKey:Tu,refetchInterval:Eu,queryFn:async()=>(await d.trpcClient.coreBlocks.list.query({})).blocks}),L=()=>{I.refetch()},R=e=>{g(),C(null),L(),Pn({title:u(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},z=p({mutationFn:e=>d.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>R(e.block)}),B=p({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>R(e.block)}),V=p({mutationFn:e=>d.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:L}),ee=p({mutationFn:e=>d.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:L}),H=p({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:Nr(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{g(),L(),t(e.block.id)}}),U=I.data,te=Rl((U??[]).filter(e=>Ar(e.code))),ne=U!==void 0&&te.length===0,W=f.mode===`edit`?te.find(e=>e.id===f.id)??null:null,re=f.mode===`edit`&&U!==void 0&&W===null;s(()=>{re&&g()},[re,g]);let G=W===null?null:Mr(W.code),ie=G!==null&&G.ok?G.recipe.template:void 0,ae=async e=>{let{template:t,...n}=e.recipe,r={version:1,body:n,inputs:[],bindings:[]};E(null);try{let t=await M.mutateAsync({kind:`automation`,name:e.name,payload:r});t.status===`refused`?E(t.detail):A(Wn(t.template.id))}catch(e){E(Du(e))}},oe=z.error===null?B.error===null?H.error===null?null:Du(H.error):Du(B.error):Du(z.error),se=r(()=>[{key:`name`,header:u(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=Mr(e.code);return o(Vl,{block:e,logsOpen:v===e.id,unreadable:t.ok?null:t.reason,flagged:t.ok&&t.recipe.template?.problems!==void 0})},sortValue:e=>e.name},{key:`trigger`,header:u(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=Mr(e.code);return o(Wl,{recipe:t.ok?t.recipe:null})},notSortableReason:u(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:u(`build.automationsTab.lastRun`,`Last run`),render:e=>o(Gl,{blockId:e.id}),notSortableReason:u(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:u(`build.automationsTab.enabled`,`Enabled`),render:e=>o(Kl,{block:e,disabled:ee.isPending,onToggle:t=>ee.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=Mr(e.code);return o(ql,{unreadable:t.ok?null:t.reason,onEdit:()=>h(e.id),onToggleLogs:()=>y(v===e.id?null:e.id),onDelete:()=>{_({title:u(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:u(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:u(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&V.mutate(e.id)})}})}}],[_,v,h,V,ee,u]),ce=()=>{z.reset(),B.reset(),C(null),g()};return S!==null&&!P?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(w,{className:`h-4 w-4 text-foreground-muted`}),u(`build.automationsTab.newAutomation`,`New automation`)]}),o(Cu,{templateId:S,existing:null,recipe:null,saving:z.isPending,saveError:oe,onSave:e=>z.mutate(e),onCancel:ce})]}):P?f.mode===`edit`&&W===null?o(ct,{className:`h-24 w-full`}):W!==null&&ie!==void 0&&G!==null&&G.ok?e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[o(w,{className:`h-4 w-4 text-foreground-muted`}),u(`build.automationsTab.edit`,`Edit {{name}}`,{name:W.name})]}),o(Cu,{templateId:ie.templateId,existing:W,recipe:G.recipe,saving:B.isPending,saveError:oe,onSave:e=>B.mutate({blockId:W.id,block:e}),onCancel:ce})]}):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(w,{className:`h-4 w-4 text-foreground-muted`}),W===null?u(`build.automationsTab.newAutomation`,`New automation`):u(`build.automationsTab.edit`,`Edit {{name}}`,{name:W.name})]}),o(Ml,{existing:W,initialRecipe:G!==null&&G.ok?G.recipe:Li,saving:z.isPending||B.isPending,saveError:oe,ejecting:H.isPending,onSave:e=>{W===null?z.mutate(e):B.mutate({blockId:W.id,block:e})},onEject:()=>{W!==null&&H.mutate(W)},onSaveAsTemplate:e=>void ae(e),savingAsTemplate:M.isPending,onCancel:()=>{z.reset(),B.reset(),H.reset(),g()}},W?.id??`new`),V.error!=null&&o(q,{message:Du(V.error)}),T!==null&&o(q,{message:T})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:U===void 0?``:zl(te)}),I.error!=null&&o(q,{title:u(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Du(I.error),onRetry:L}),ne?o(Jl,{onCreate:()=>x(!0)}):o(Vt,{columns:se,rows:te,rowKey:e=>e.id,pageSize:25,maxBodyHeight:vt,emptyMessage:U===void 0?u(`build.automationsTab.loadingAutomations`,`Loading automations…`):u(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>h(e.id)}),V.error!=null&&o(q,{message:Du(V.error)}),ee.error!=null&&o(q,{message:Du(ee.error)}),o(Yl,{open:b,onBlank:F,onTemplate:e=>{x(!1),C(e)},onClose:()=>x(!1)})]})}var ku={kind:`all`,children:[]};function Au({value:t,devices:n,label:r,onChange:i}){let{t:a}=Q(),s=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[o(Jt,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?ku: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(hc,{recipe:s,devices:n,onChange:e=>i(e.when)})]})]})}var ju=[`sunrise`,`sunset`,`dawn`,`dusk`],Mu=6e4;function Nu(e){return e.kind===`command`||e.kind===`wait`}function Pu(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 Fu({point:t,devices:n,site:r,localDate:i,issues:a,onChange:s,onRemove:c}){let{t:l}=Q(),u=t.at,d=u.kind===`sun`?_s(u,r,i):null,f=vs(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(z,{"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(Pu(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.when`,`When`)}),o(z,{"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(Y,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:xs(u.hh,u.mm),onChange:e=>{let t=bs(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(z,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:ju.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=ju.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(hr,{"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:Ss(d),zone:r.timeZone})})]}),e(X,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[o(g,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&o(Gc,{actions:t.steps,devices:n,allowedKinds:[`command`,`wait`],onChange:e=>s({...t,steps:e.filter(Nu)})}),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(z,{"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*Mu}:{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(hr,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:p.graceMs/Mu,onValue:e=>{e!==null&&s({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*Mu))}})}})]})]}),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 Iu=5e3,Lu=600,Ru=6e4,zu={timeZone:`UTC`,location:null};function Bu(e){return e instanceof Error?e.message:String(e)}function Vu(e){if(e===null)return us();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function Hu(e,t){let[n,r]=c(e);return s(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Uu(e,t){return t(`schedulers.day.${e}`,e)}function Wu({entry:t,onClose:n,onSaved:i}){let{t:a}=Q(),s=f(),l=j(),u=ur(),d=qt(),p=d.data??zu,[m,h]=c(()=>Vu(t)),[_,v]=c(()=>m.profiles[0]?.id??``),[y,b]=c(null),[x,C]=c(null),w=()=>{s.invalidateQueries({queryKey:[[`schedulers`]]})},T=dn({onSuccess:e=>{w(),i(e.scheduler.id)}}),E=On({onSuccess:w}),D=ln({onSuccess:()=>{w(),n()}}),O=Sn({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:Iu}),k=r(()=>ws(m,p),[m,p]),A=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),M=Hu(k.ok?k.input:null,Lu),N=_n(M===null?{scheduler:m}:t===null?{scheduler:M}:{scheduler:M,schedulerId:t.id},{enabled:M!==null&&A&&d.data!==void 0}),I=m.profiles.find(e=>e.id===_)??m.profiles[0],L=I===void 0?-1:m.profiles.indexOf(I),R=gs(p),z=I?.points.find(e=>e.id===y)??null,B=I===void 0||z===null?-1:I.points.indexOf(z),V=k.ok?[]:k.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)}),U=e=>{I!==void 0&&H({...I,points:I.points.map(t=>t.id===e.id?e:t)})},te=r(()=>I===void 0?[]:I.points.flatMap(e=>{let t=_s(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)} (${Ss(t)})`:xs(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`&&vs(e.at,p,R)!==null}]}),[I,p,R,a]),ne=r(()=>I===void 0?[]:Cs(I.points,p,R),[I,p,R]),W=(e,t)=>{let n=I?.points.find(t=>t.id===e);n!==void 0&&U({...n,at:ys(n.at,t,vs(n.at,p,R))})},re=e=>{if(I===void 0)return;let t=ps(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));H({...I,points:[...I.points,fs(e,t,720)]}),b(t)},G=()=>{let e=ps(`profile`,m.profiles.map(e=>e.id));h({...m,profiles:[...m.profiles,ds(e,a(`schedulers.profile.newName`,`New profile`))]}),v(e),b(null)},ie=T.isPending||E.isPending,ae=T.error??E.error??D.error;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`scheduler-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(F,{className:`h-4 w-4 text-foreground-muted`}),o(Y,{"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(mt,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[o(Tn,{label:a(`schedulers.editor.enabled`,`Enabled`),children:o(Jt,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>h({...m,enabled:e})})}),o(Tn,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:o(hr,{"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(Tn,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:o(hr,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/Ru,onValue:e=>{e!==null&&h({...m,maxLateMs:Math.round(e*Ru)})}})})]}),e(`div`,{className:`p-3`,children:[o(Au,{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(mt,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(X,{variant:`outline`,size:`sm`,onClick:G,children:[o(P,{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(Wt,{value:I.id,onValueChange:e=>{v(e),b(null)},appearance:`pills`,children:[o(Ht,{children:m.profiles.map(e=>o(Gt,{value:e.id,children:e.name},e.id))}),e(Tt,{value:I.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(Y,{"aria-label":a(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:I.name,onChange:e=>H({...I,name:e.target.value})}),o(Jt,{checked:I.enabled,label:a(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>H({...I,enabled:e})}),m.profiles.length>1&&e(X,{variant:`ghost`,size:`sm`,onClick:()=>{h({...m,profiles:m.profiles.filter(e=>e.id!==I.id)}),v(``),b(null)},children:[o(g,{className:`h-4 w-4`}),` `,a(`schedulers.profile.remove`,`Remove profile`)]})]}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":a(`schedulers.profile.days`,`Days`),children:ss.map(e=>{let t=I.days.includes(e);return o(X,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>H({...I,days:t?I.days.filter(t=>t!==e):ss.filter(t=>t===e||I.days.includes(t))}),children:Uu(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(Au,{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(En,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:te,bands:ne,selectedId:y,onSelect:b,onMove:W}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:`outline`,size:`sm`,onClick:()=>re(`edge`),children:[o(P,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(X,{variant:`outline`,size:`sm`,onClick:()=>re(`hold`),children:[o(P,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(X,{variant:`outline`,size:`sm`,onClick:()=>re(`release`),children:[o(P,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),o(J,{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(Fu,{point:z,devices:u,site:p,localDate:R,issues:ee(`profiles.${String(L)}.points.${String(B)}`),onChange:U,onRemove:()=>{H({...I,points:I.points.filter(e=>e.id!==z.id)}),b(null)}},z.id)]})]})]})}),N.data!==void 0&&N.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:N.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:Ss(e.fromMinute),to:Ss(e.toMinute),winner:e.winner===`mine`?a(`schedulers.conflict.mine`,`this one wins`):e.winner===`other`?a(`schedulers.conflict.other`,`the other one wins`):a(`schedulers.conflict.tie`,`the one that started first wins`)})},`${e.other.schedulerId}:${e.other.pointId}:${e.mine.pointId}:${String(e.deviceId)}`))}),!k.ok&&m.name!==``&&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}`))}),ae!==null&&o(q,{message:Bu(ae)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(X,{onClick:()=>{k.ok&&(t===null?T.mutate({scheduler:k.input}):E.mutate({schedulerId:t.id,scheduler:k.input}))},disabled:ie||!k.ok||d.data===void 0,children:[ie&&o(S,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(X,{variant:`ghost`,disabled:D.isPending,onClick:()=>{l({title:a(`schedulers.editor.deleteTitle`,`Delete this scheduler?`),message:a(`schedulers.editor.deleteMessage`,`{{name}} will be deleted and any hold it keeps will stop.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&D.mutate({schedulerId:t.id})})},children:[o(g,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(X,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(ci,{traces:t===null?[]:O.data?.traces,selectedId:x,onSelect:C})})]})}u();var Gu=5e3;function Ku(e){return e instanceof Error?e.message:String(e)}function qu({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),a=f(),{state:c,openNew:l,openEdit:u,close:d}=Yt({editKey:`scheduler`,newKey:`new`}),p=jn({},{refetchInterval:Gu}),m=$t({},{refetchInterval:Gu}),h=nn({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(Jt,{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(J,{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=>qn(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(q,{message:Ku(h.error)}),p.data===void 0?p.error==null?o(ct,{className:`h-24 w-full`}):o(q,{title:i(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:Ku(p.error),onRetry:()=>void p.refetch()}):g.length===0?o(dt,{icon:F,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(X,{onClick:l,children:[o(P,{className:`h-4 w-4`}),` `,i(`schedulers.list.new`,`New scheduler`)]})}):o(Vt,{columns:y,rows:g,rowKey:e=>e.id,pageSize:25,maxBodyHeight:vt,emptyMessage:i(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):o(Wu,{entry:_,onClose:d,onSaved:u},_?.id??`new`)}async function Ju(e,t){let n=`${De}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var Yu=10,Xu=400;async function Zu(e,t,n=Xu){for(let r=0;r<Yu;r+=1){let r=await Ju(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var Qu=`media-player`;function $u(e){return e===G.MediaPlayer?`media-source`:`none`}function ed(e){return e===G.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[G.MediaPlayer],accept:[{cap:Qu,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[Qu],exclude:[]}:null}function td(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:Qu,fields:{},commands:Object.fromEntries(Object.keys(Fe()).map(t=>[t,{kind:`forward`,source:e.source,cap:Qu,method:t}]))}]}function nd(e,t){let n=e===G.MediaPlayer?td(t):[];return{target:{kind:`new`,type:e},features:n}}u();function rd({onTitle:t}){let{t:n}=Q(),r=E(),i=Rn(),a=lr(),l=Kt(),u=Ft({addonId:`composer`}),[d,f]=c(G.Sensor),[p,m]=c(``),[h,g]=c([]),[_,v]=c(null),y=h[0]??null,b=ed(d),x=nd(d,y);s(()=>{t(n(`helper.newDevice`))},[t,n]);let S=async()=>{v(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:x}}),r=await Zu(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(Bn(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(z,{value:d,onChange:e=>{let t=Object.values(G).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(G).map(e=>({value:e,label:fn(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(Y,{"aria-label":n(`compositionEditor.name`),value:p,onChange:e=>m(e.target.value)})]})]}),b!==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.${$u(d)}`)}),o(Qn,{kind:`members`,request:b,enabled:!0,members:h,onMembersChange:g,onRefuse:()=>void 0})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(X,{disabled:a.isPending,onClick:()=>void S(),children:n(`compositionEditor.save`)})]})}u();function id({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=Q(),u=rr(!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=>[U({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[U(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:Jn(u.value,S)}:u,[u,S]),w=ar(t,d),T=u.kind===`known`?or(u.value,w,!1):null,E=t.build(d),D=tr(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(U(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(Y,{"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:[sr(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(X,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(X,{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:sr(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(ir,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(X,{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(X,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o($n,{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 ad=`preset`;function od({mode:e,onTitle:t}){return o(e===`helper`?sd:rd,{onTitle:t})}function sd({onTitle:e}){let{t}=Q(),r=Rn(),i=lr(),a=Kt(),l=Ft({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=Un(),g=Zn(m.get(ad)),_=g===null?cd(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(ad):n.set(ad,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 Zu(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:er(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(Bn(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:er(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(rd,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(nr,{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 cr(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 Zu(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(zn(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:ld(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(id,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function cd(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=Je(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function ld(e,t){return e.length>0?e:er(t(`helper.devicePending`))}function ud(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 dd(e){return{state:`answered`,byRef:new Map(e.map(e=>[U(e),e]))}}function fd(e,t){if(e.state!==`unanswered`)return e.byRef.get(U(t))??null}function pd(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function md(e){return le(e).map(e=>e.source)}function hd(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(...md(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...md(e))}let r=new Set;return n.filter(e=>{let t=U(e);return r.has(t)?!1:(r.add(t),!0)})}function gd(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:Z.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Z.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Z.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Z.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Z.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function _d(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return gd(e);case`degraded`:return{tone:`pending`,label:Z.t(`helpers.compositionRows.degraded`),reason:n??Z.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Z.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Z.t(`helpers.compositionRows.failed`),reason:n??Z.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Z.t(`helpers.compositionRows.notRunning`),reason:n??Z.t(`helpers.compositionRows.notRunningReason`)}}}function vd(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Z.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Z.t(`helpers.compositionRows.unknown`),reason:Z.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return _d(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Z.t(`helpers.compositionRows.notReported`),reason:Z.t(`helpers.compositionRows.noRecord`,{stored:r})}}function yd(e){return U(e)}function bd(e,t){let n=fd(t,e);return{key:U(e),label:n?n.name:yd(e),presence:pd(n),deviceId:n?n.id:null}}function xd(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Sd(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:de(e.block.id),a=U(i),o=hd(e).filter(e=>U(e)!==a).map(e=>bd(e,t)),s=n.features.map(e=>e.enabled===!1?Z.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=fd(t,i),l=xd(e),u=vd(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:ud(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=pd(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:yd(r.device),namePresence:d,type:c?c.type:null,origin:ud(n),features:s,state:u,sources:o,reportedDeviceId:l}}function Cd(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function wd(e,t){return Cd(e)-Cd(t)||e.name.localeCompare(t.name)}function Td(e,t){let n=e.flatMap(e=>{let n=Sd(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(wd),customizations:n.filter(e=>e.kind===`customization`).toSorted(wd)}}u();var Ed=1e4;function Dd(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Od(){let e=Fn();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Z.t(`build.customDeviceTab.deviceListPending`):Z.t(`build.customDeviceTab.deviceListUnreadable`,{error:Dd(e.error)})}:dd(e.data)}function kd(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Ad({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Q(),[i,a]=Un(),s=At({},{refetchInterval:Ed}),l=Od(),u=Yt({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?kd(i.get(`new`),t):null,p=f!==null,[h,g]=c(``),_=j(),v=ut(),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:[Md(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(It,{open:p,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:M,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(od,{mode:f,onTitle:g},f)}),o(gr,{blockId:d,onClose:y}),v.error!=null&&o(q,{message:Dd(v.error)})]})}function jd(t){return o(yt,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Z.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Z.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Md(e,t,n,r,i){if(t!=null&&e===void 0)return o(q,{title:Z.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Dd(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Z.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return jd(e.reason);let a=t==null?null:Dd(t);return o(Nd,{lists:Td(e.views,r),fleet:r,refreshError:a,handlers:i})}function Nd({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Q();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(Pd,{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(Pd,{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 Pd({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=Q();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(Vt,{columns:Fd(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:vt,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Fd(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(Ld,{row:e})},{key:`type`,header:Z.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Z.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:Z.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>Id(e.origin,i),render:e=>o(J,{variant:`default`,"data-testid":`composed-origin-badge`,children:Id(e.origin,i)})}]:[],{key:`state`,header:Z.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(J,{variant:Il(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:Z.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(zd,{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(X,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(X,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:o(g,{className:`h-4 w-4`})})]})}),a}function Id(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 Ld({row:t}){let{t:n}=Q();return e(`div`,{className:`space-y-0.5`,children:[o(Rd,{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 Rd({row:e}){let{t}=Q(),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(Hn,{to:e.kind===`composed`?zn(e.reportedDeviceId):Bn(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function zd({sources:t}){let{t:n}=Q();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(Hn,{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 Bd(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 Vd(e){if(Array.isArray(e))return e}function Hd(e,t,n){return(t=Zd(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ud(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 Wd(){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
|
|
4
|
+
`};case`action`:return{kind:e,actionId:``};case`stop`:return{kind:e,reason:``,outcome:`ok`};case`set`:return{kind:e,vars:{}};case`wait-until`:return ki();case`parallel`:return{kind:e,steps:[]};case`repeat`:return Ci();case`choose`:return{kind:e,branches:[{if:{kind:`all`,children:[]},steps:[]}]};default:return{kind:`command`,target:{kind:`devices`,ids:[]},actionId:``}}}function Bi(e,t,n){return e.map((e,r)=>r===t?n:e)}function Vi(e,t){return e.filter((e,n)=>n!==t)}function Hi(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=Vi(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function Ui(e,t){return{...e,actions:[...t]}}var Wi={pass:`success`,fail:`danger`,"not-evaluated":`neutral`},Gi={pass:`success`,fail:`danger`,idle:`neutral`};function Ki({value:e}){let{t}=Q();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 qi(){let{t:e}=Q();return t=>t===`pass`?e(`flow.runs.nodePass`,`Passed`):t===`fail`?e(`flow.runs.nodeFail`,`Failed`):e(`flow.runs.nodeNotEvaluated`,`Not evaluated`)}function Ji(e){let t=he.safeParse(e);return t.success?Mi(t.data):e}function Yi({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(Ki,{value:t.value})})]},t.name))})}function Xi({node:t,vars:n=[],expected:r,observed:i}){let{t:a}=Q(),s=qi(),c=t.subject===null?null:`${t.subject}${t.operator===null?``:` ${Ji(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(J,{variant:Wi[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(Ki,{value:r})]}),i!==null&&e(`span`,{"data-testid":`trace-observed`,children:[a(`flow.runs.observed`,`Observed`),` `,o(Ki,{value:i})]})]}),o(Yi,{testId:`trace-vars`,items:n})]})}function Zi({step:t,deviceName:n}){let{t:r}=Q(),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(J,{variant:Gi[t.tone],children:i}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:t.message})]}),t.chose!==null&&o(`div`,{className:`text-foreground-subtle`,"data-testid":`step-chose`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.nested.length>0&&o(`div`,{className:`text-foreground-subtle`,"data-testid":`step-last-round`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})}),t.nested.length>0&&o(`ol`,{className:`space-y-0.5 text-[11px]`,"data-testid":`step-nested`,children:t.nested.map((t,n)=>e(`li`,{className:`space-y-0.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:Gi[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message}),t.chose!==null&&o(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-chose-${String(n)}`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.inner.length>0&&o(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-rounds-${String(n)}`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})})]}),t.inner.length>0&&o(`ol`,{className:`space-y-0.5 border-l border-border-subtle pl-2`,"data-testid":`nested-inner-${String(n)}`,children:t.inner.map((t,n)=>e(`li`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:Gi[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},String(n)))})]},String(n)))}),o(Yi,{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(J,{variant:Gi[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 $({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function Qi(e){let t=mr(e.deviceId);if(t.data!==void 0)return yr(t.data,e.cap).find(t=>t.path===e.fieldPath)}function $i({value:t,devices:n,onChange:r}){let{t:i,i18n:a}=Q(),[s,l]=c(!1),u=n.find(e=>e.id===t.deviceId),d=t.deviceId===0?i(`automation.fieldPicker.pickAValue`,`Pick a device value…`):`${u?.name??`#${String(t.deviceId)}`}${t.cap===``?``:` · ${Xn(t.cap,t.fieldPath,a.language)}`}`;return e(`div`,{className:`min-w-[14rem] max-w-full flex-[2]`,children:[o($,{children:i(`automation.fieldPicker.value`,`Device value`)}),e(X,{variant:`outline`,className:`w-full min-w-0 justify-between`,"data-testid":`field-picker-open`,onClick:()=>l(!0),children:[o(`span`,{className:`w-0 flex-1 truncate text-left`,children:d}),o(et,{className:`size-3.5 shrink-0`})]}),s&&o(ea,{value:t,onCancel:()=>l(!1),onConfirm:e=>{l(!1),r(e)}})]})}function ea({value:t,onCancel:n,onConfirm:r}){let{t:i}=Q(),a=kn({projection:`slim`}),[s,l]=c(null),[u,d]=c(!1),[f,p]=c(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!u&&a.status===`success`&&(d(!0),l(Yn(a.data).find(e=>e.id===t.deviceId)??null));let h=i(`automation.fieldPicker.title`,`Device value`);return o(It,{open:!0,onClose:n,title:h,width:`xl`,fill:!0,testId:`field-picker-dialog`,footer:e(m,{children:[o(X,{variant:`ghost`,onClick:n,children:i(`common.cancel`,`Cancel`)}),o(X,{disabled:s===null||f===null,"data-testid":`field-picker-confirm`,onClick:()=>{s===null||f===null||r({deviceId:s.id,cap:f.cap,fieldPath:f.path})},children:i(`automation.fieldPicker.use`,`Use this value`)})]}),children:o(Qn,{kind:`formula`,intent:`value`,enabled:!0,fillHeight:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:h,pickerTargetKind:null},device:s,field:f,excludeTypes:dr,onDeviceChange:l,onFieldChange:p})})}var ta=1e4;function na(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 ra(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function ia({step:t,onChange:n}){let{t:r}=Q(),i=tn({},{refetchInterval:ta});if(i.data===void 0)return o(ct,{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($,{children:r(`automation.runAction.action`,`Action`)}),o(z,{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(aa,{variable:e,value:t.variables?.[e.name],onChange:r=>n(ra(t,na(t.variables,e.name,r)))},e.name))})]})}function aa({variable:t,value:n,onChange:r}){let{t:i}=Q(),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($,{children:a}),o(_r,{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($,{children:a}),o(hr,{className:`w-40`,placeholder:s,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[o($,{children:a}),o(Y,{className:`w-40`,placeholder:s,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}function oa({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(X,{variant:`ghost`,disabled:e===null,onClick:e??void 0,"aria-label":t,title:a,"data-testid":r,children:i})})}function sa({move:t,texts:n}){let{t:r}=Q(),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(oa,{onMove:t.up,label:i.up,reason:i.atFirst,testId:`move-up`,children:o(N,{className:`h-3.5 w-3.5`})}),o(oa,{onMove:t.down,label:i.down,reason:i.atLast,testId:`move-down`,children:o(b,{className:`h-3.5 w-3.5`})})]})}var ca=[`command`,`action`,`wait`,`set`,`stop`],la=[`command`,`action`,`wait`];function ua(e){return fa(e)&&la.includes(e.kind)}var da={kind:`all`,children:[]};function fa(e){return ca.includes(e.kind)?!(`if`in e)&&!(`else`in e):!1}function pa(){return{if:da,steps:[]}}function ma(e){return e.branches.length<6}function ha(e){return ma(e)?{...e,branches:[...e.branches,pa()]}:e}function ga(e){return e.branches.length>1}function _a(e,t){return ga(e)?{...e,branches:e.branches.filter((e,n)=>n!==t)}:e}function va(e,t,n){return{...e,branches:e.branches.map((e,r)=>r===t?n:e)}}function ya(e,t){let{else:n,...r}=e;return t===void 0?r:{...r,else:[...t]}}var ba=[...ca,`wait-until`,`choose`,`parallel`,`repeat`];function xa(e){return e<2?ba:ca}function Sa(e){if(fa(e))return!0;switch(e.kind){case`wait-until`:case`parallel`:return!0;case`repeat`:return e.steps.every(fa);case`choose`:return e.branches.every(e=>e.steps.every(fa))&&(e.else??[]).every(fa);default:return!1}}var Ca=[`border-chart-series-a`,`border-chart-series-f`,`border-chart-series-b`,`border-chart-series-d`];function wa(e,t){let n=Ca.length;return(e+1+t%(n-1))%n}function Ta(e,t){let n=0;return e.map(e=>me(e)?null:wa(t,n++))}function Ea(e){return Ca[e%Ca.length]??Ca[0]}function Da(e){let t=[],n=0;return be(e,e=>{fe(e)&&(n+=1,e.id!==void 0&&t.push({id:e.id,ordinal:n,leaf:e}))}),t}function Oa(e){return oe(e.when)?!0:e.actions.some(e=>ee(e).some(e=>oe(e.when)))}function ka(e){let t=1;for(;e.has(`t${t}`);)t+=1;return`t${t}`}function Aa(e,t){if(me(e)){if(!fe(e)||e.id!==void 0)return e;let n=ka(t);return t.add(n),{...e,id:n}}if(e.kind===`not`){let n=Aa(e.child,t);return n===e.child?e:{...e,child:n}}let n=e.children.map(e=>Aa(e,t));return n.every((t,n)=>t===e.children[n])?e:{...e,children:n}}function ja(e){if(!Oa(e))return e;let t=new Set(Da(e.when).map(e=>e.id)),n=Aa(e.when,t);return n===e.when?e:{...e,when:n}}function Ma(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 Na(e,t){return e.leafIds.filter(e=>!t.includes(e))}u();var Pa=[],Fa=d(null);function Ia({when:e,children:t}){let n=r(()=>Da(e),[e]);return o(Fa.Provider,{value:n,children:t})}function La(){return h(Fa)??Pa}function Ra(){return h(Fa)!==null}var za=[`triggered-by`];function Ba(e){return{label:Pi(e),description:Fi(e),example:Ii(e)}}function Va({open:e,onOpenChange:t,mode:n,context:r,underNot:i,treeFull:a,current:s,onPick:c}){let{t:l}=Q(),u=Ra();return o(Zt,{open:e,onOpenChange:t,title:n===`add`?l(`automation.leafPicker.title`,`Add a row`):l(`automation.leafPicker.changeTitle`,`Change the row type`),context:r,underNot:i,treeFull:a,...n===`change`&&s!==void 0?{current:s}:{},...u?{}:{hidden:za},recentKey:`automation-${r}`,textsOf:Ba,categoryLabelOf:e=>l(`automation.leafPicker.category.${e}`),reasonOf:e=>l(`automation.leafPicker.reason.${e}`),onPick:e=>{c(e),t(!1)}})}var Ha=`none`;function Ua(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<=0))return Math.round(t*1e3)}function Wa({hold:t,modes:n,onChange:r}){let{t:i}=Q(),a={held:i(`automation.hold.held`,`held`),stable:i(`automation.hold.stable`,`stable`)},s=e=>{if(e===Ha){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($,{children:i(`automation.hold.label`,`For`)}),o(z,{value:t?.mode??Ha,onChange:e=>s(e.target.value),options:[{value:Ha,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($,{children:i(`automation.hold.seconds`,`Seconds`)}),o(Y,{type:`number`,min:1,value:String(t.ms/1e3),onChange:e=>{let n=Ua(e.target.value);r(n===void 0?void 0:{...t,ms:n})}})]}),t?.mode===`stable`&&e(`label`,{className:`w-28`,children:[o($,{children:i(`automation.hold.tolerance`,`± tolerance`)}),o(Y,{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 Ga({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Q(),c=Qa(n,r,i);if(n?.kind===`boolean`)return o(z,{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(z,{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(Y,{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(Y,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Ka({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Q(),s=Qa(t,n,r);return o(Y,{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 qa(e){return typeof e==`object`&&!qe(e)}function Ja(e){return qe(e)?e.value:qa(e)?e[0]??``:e}function Ya(e){return qe(e)?[e.value]:qa(e)?e:typeof e==`boolean`?[]:[e]}function Xa(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!Pe(t)||t===`none`||t===`device`))return Le(t).length>0?t:void 0}function Za(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Qa(e,t,n){let r=kt(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=en({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=Pe(s)?s:void 0,l=Za(e?.quantity,c);if(l===void 0)return;let u=o?.display;return St({quantity:l,display:u,capName:n,unitPreferences:r})}function $a({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Qi(a),c=Ni(s?.kind),l=t.operator===`in`,u=Xa(s),d=u===void 0?void 0:Re(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=eo(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...Ya(t.value)]:Ja(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o($i,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[o($,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(z,{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($,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Ka,{value:Ya(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?o(Rt,{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=Cn(e,d);r({...t,value:n.value,unit:n.unit})}}):o(Ga,{value:Ja(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]}),o(Wa,{hold:t.for,modes:[`held`,`stable`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})]})}function eo(e,t){return t.find(t=>t.value===e)?.value??`eq`}var to=Object.values(ie).sort((e,t)=>e.localeCompare(t));function no({leaf:t,onChange:n}){let{t:r}=Q();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[o($,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(Y,{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(Ln,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]})}function ro(){return o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Ln,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})}function io(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 ao(e){return e.operator===void 0?e.becomes===void 0?`any`:`becomes`:e.operator}var oo=[`any`,`becomes`,`gt`,`gte`,`lt`,`lte`,`between`,`outside`];function so(e){return e===`between`||e===`outside`}function co(e){if(e.trim()===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function lo(e){return typeof e==`number`?e:void 0}function uo({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Qi(a),c=Ee(t),l=ao(t),u=lo(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(io(a,_));return}if(e===`becomes`){r(io(a,{..._,becomes:``}));return}let t=te.safeParse(e);t.success&&r(io(a,{..._,operator:t.data,value:so(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($i,{value:a,devices:n,onChange:e=>r(io(e,f))}),e(`label`,{className:`min-w-[10rem]`,children:[o($,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),o(z,{value:l,onChange:e=>v(e.target.value),options:oo.map(e=>({value:e,label:y[e]}))})]}),l===`becomes`&&t.becomes!==void 0&&e(`div`,{className:`min-w-[9rem] flex-1`,children:[o($,{children:i(`automation.conditionRow.value`,`Value`)}),o(Ga,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(io(a,{...f,becomes:e}))})]}),t.operator!==void 0&&!so(l)&&e(`label`,{className:`w-28`,children:[o($,{children:i(`automation.conditionRow.value`,`Value`)}),o(Y,{type:`number`,step:`any`,value:u===void 0?``:String(u),onChange:e=>{let n=co(e.target.value);n!==void 0&&r(io(a,{...f,operator:t.operator,value:n}))}})]}),t.operator!==void 0&&so(l)&&[0,1].map(n=>e(`label`,{className:`w-24`,children:[o($,{children:n===0?i(`automation.triggerEditor.rangeFrom`,`From`):i(`automation.triggerEditor.rangeTo`,`To`)}),o(Y,{type:`number`,step:`any`,value:d[n]===void 0?``:String(d[n]),onChange:e=>{let i=co(e.target.value);if(i===void 0)return;let o=[d[0]??0,d[1]??0];o[n]=i,r(io(a,{...f,operator:t.operator,value:o}))}})]},n)),o(Wa,{hold:c,modes:[`held`,`stable`],onChange:e=>{let{hold:t,...n}=f;r(io(a,e===void 0?n:{...n,hold:e}))}}),e(`label`,{className:`w-28`,children:[o($,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(Y,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(io(a,{...f,debounceMs:fo(e.target.value)}))})]})]})}function fo(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function po({leaf:t,onChange:n}){let{t:r}=Q();return e(m,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o($,{children:r(`automation.triggerEditor.eventCategory`,`Event category`)}),o(z,{value:t.category,onChange:e=>n({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:r(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...to.map(e=>({value:e,label:e}))]})]}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o($,{children:r(`automation.triggerEditor.fromDevice`,`From device`)}),o(gn,{pick:`device`,excludeTypes:dr,recentKey:`build-targets`,value:t.deviceId===void 0?null:{deviceId:t.deviceId},placeholder:r(`automation.triggerEditor.anyDevice`,`Any device`),testId:`trigger-event-device`,onChange:e=>n({kind:`device-event`,category:t.category,...e===null?{}:{deviceId:e.deviceId}})})]})]})}function mo(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 ho(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 go={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function _o({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),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(un,{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(vo,{alias:e,source:r,devices:n,onRename:n=>s(xo(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(So(t.bindings,e))},e)),e(X,{variant:`ghost`,onClick:()=>s({...t.bindings,[bo(t.bindings)]:go}),children:[o(P,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]}),o(`div`,{className:`flex flex-wrap items-end gap-2`,children:o(Wa,{hold:t.for,modes:[`held`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})})]})}function vo({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Q(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:n.kind===`global`?ho(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($,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(Y,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o($,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(z,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:go),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($,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(Y,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:yo(e.target.value)})})]}):o($i,{value:u,devices:r,onChange:e=>a(mo(r,e))}),o(X,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(g,{className:`h-3.5 w-3.5`})})]})}function yo(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function bo(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 xo(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function So(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var Co=`event-emitter`;function wo(e){if(e.status===`pending`)return{kind:`pending`};if(e.status===`error`)return{kind:`unknown`};let t=Xe.safeParse(e.data);return t.success?{kind:`known`,vocabulary:Ne(t.data)}:{kind:`unknown`}}function To(e){let t=new Map;for(let n of e)n.source!==void 0&&!t.has(n.source.id)&&t.set(n.source.id,n.source);return[...t.values()]}function Eo(e,t){let n=new Map;for(let r of e)t!==void 0&&r.source?.id!==t||n.has(r.id)||n.set(r.id,r);return[...n.values()]}function Do(e,t){return{kind:`device-fired`,...e.id===void 0?{}:{id:e.id},deviceId:t}}function Oo(e,t,n){let{sourceIds:r,eventIds:i,...a}=e,o=new Set(Eo(n,t).map(e=>e.id)),s=(i??[]).filter(e=>o.has(e));return{...a,...t===void 0?{}:{sourceIds:[t]},...s.length===0?{}:{eventIds:s}}}function ko(e,t){let{eventIds:n,...r}=e;return{...r,...t===void 0?{}:{eventIds:[t]}}}function Ao(e,t){let n=new Set(To(t).map(e=>e.id)),r=new Set(t.map(e=>e.id));return{sourceIds:(e.sourceIds??[]).filter(e=>!n.has(e)),eventIds:(e.eventIds??[]).filter(e=>!r.has(e))}}var jo=``,Mo={caps:[Co]};function No({leaf:t,hideDevice:n=!1,onChange:r}){let{t:i}=Q(),a=t.deviceId>0,s=Lt({deviceId:t.deviceId,capName:Co},{enabled:a}),c=wo({status:s.status,data:s.data}),l=c.kind===`known`?c.vocabulary:[],u=To(l),d=t.sourceIds?.[0],f=t.eventIds?.[0],p=Eo(l,d),h=c.kind===`known`?Ao(t,l):null,g=i(`automation.fired.anyEvent`,`Any event`),_=c.kind===`pending`?i(`automation.fired.loading`,`Reading what this device can fire…`):i(`automation.fired.unknown`,`What this device can fire could not be read.`);return e(m,{children:[!n&&e(`div`,{className:`min-w-[13rem] flex-1`,children:[o($,{children:i(`automation.fired.device`,`Device`)}),o(gn,{pick:`device`,requires:Mo,recentKey:`automation-device-fired`,value:a?{deviceId:t.deviceId}:null,onChange:e=>r(Do(t,e?.deviceId??0))})]}),a&&c.kind!==`known`&&o(`p`,{className:`min-w-[13rem] flex-1 text-xs ${c.kind===`unknown`?`text-warning`:`text-foreground-subtle`}`,"data-testid":`fired-vocabulary-${c.kind}`,children:_}),a&&c.kind===`known`&&u.length>0&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[o($,{children:i(`automation.fired.source`,`From`)}),o(z,{"data-testid":`fired-source`,value:d??jo,onChange:e=>r(Oo(t,e.target.value===jo?void 0:e.target.value,l)),options:[{value:jo,label:i(`automation.fired.anySource`,`Any button`)},...u.map(e=>({value:e.id,label:e.label})),...(h?.sourceIds??[]).map(e=>({value:e,label:i(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),a&&c.kind===`known`&&e(`label`,{className:`min-w-[11rem] flex-1`,children:[o($,{children:i(`automation.fired.event`,`Event`)}),o(z,{"data-testid":`fired-event`,value:f??jo,onChange:e=>r(ko(t,e.target.value===jo?void 0:e.target.value)),options:[{value:jo,label:g},...p.map(e=>({value:e.id,label:e.label})),...(h?.eventIds??[]).map(e=>({value:e,label:i(`automation.fired.gone`,`{{id}} (no longer declared)`,{id:e})}))]})]}),h!==null&&h.sourceIds.length+h.eventIds.length>0&&o(`p`,{className:`basis-full text-xs text-warning`,"data-testid":`fired-stale`,children:i(`automation.fired.staleHint`,`This row names something the device no longer declares, so it will not start a run. Pick again.`)}),(t.kinds!==void 0||t.match!==void 0)&&o(`p`,{className:`basis-full text-xs text-foreground-subtle`,"data-testid":`fired-extra`,children:i(`automation.fired.extraHint`,`This row also carries filters set outside the editor ({{what}}); they are kept as they are.`,{what:[...t.kinds??[],...(t.match??[]).map(e=>`${e.path} = ${String(e.equals)}`)].join(`, `)})})]})}var Po=`text-xs text-foreground-subtle`;function Fo({children:e}){return o(`span`,{className:Po,children:e})}function Io(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function Lo({selected:t,onChange:n}){let{t:r}=Q();return e(`div`,{className:`space-y-1`,children:[o(Fo,{children:r(`flow.scene.cameras`,`Cameras`)}),o(gn,{multiple:!0,pick:`device`,noun:`camera`,fixedTypes:fr,recentKey:`build-cameras`,value:Nt(t),testId:`scene-cameras`,onChange:e=>n(jt(e))})]})}function Ro({device:t,deviceId:n,selected:r,onToggle:i}){let a=ht({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:Po,children:t?.name??`#${String(n)}`}),a.data.map(e=>o(X,{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 zo({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=Q();if(n.length===0)return null;let s=e=>{let t=Io(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(Fo,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(Ro,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:Po,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var Bo=[`animal`,`person`,`vehicle`,`package`,`other`];function Vo(e){return Bo.find(t=>t===e)??`other`}function Ho(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 Uo(){let{t:e}=Q();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 Wo(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 Go=[`automation`,`class-taxonomy`];function Ko(){let e=k();return Ae(l({queryKey:Go,retry:!1,staleTime:1/0,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}).data?.taxonomy)}function qo(e,t,n){let r=n?.groups.find(t=>t.key===e),i=r===void 0?ce(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 Jo({subject:e,onChange:t}){let{t:n}=Q(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=Ko(),a=qo(e.macro,r,i);return a.length===0?null:o(z,{"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===``?Ho(e.macro):Wo(e.macro,r))}})}function Yo({onChange:e,subject:t}){let{t:n}=Q(),r=an(),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(z,{"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 Xo=`plate:`,Zo=`class:`,Qo=200;function $o({onChange:e,subject:t}){let{t:n}=Q(),r=Et({includeCrops:!1,limit:Qo}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,s=Ko(),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?``:`${Zo}${c}`:`${Xo}${a}`;return o(z,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:u,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...qo(`vehicle`,c,s).map(e=>({value:`${Zo}${e.value}`,label:e.label})),...l.map(e=>({value:`${Xo}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(Xo)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(Zo)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function es({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:s}=Q(),c=Uo(),l=t.macro===`other`?[]:Oe[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(z,{"aria-label":s(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:Bo.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=Vo(e.target.value);n!==t.macro&&i(Ho(n))}})}),o(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?o(Y,{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(Yo,{subject:t,onChange:i})}):d&&!n?o(`div`,{className:`w-44`,children:o($o,{subject:t,onChange:i})}):!u&&o(`div`,{className:`w-44`,children:o(Jo,{subject:t,onChange:i})}),a!==null&&o(X,{variant:`ghost`,onClick:a,title:s(`automation.whenTree.removeClass`,`Remove this class`),children:o(g,{className:`h-3.5 w-3.5`})})]})}function ts({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:s}=Q(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>o(es,{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(X,{variant:`ghost`,size:`sm`,onClick:()=>a([...t,Ho(`person`)]),children:[o(P,{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 ns=100;function rs({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=Math.round((t.minScore??0)*ns),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/ns})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(ts,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),o(Lo,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(zo,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(Fo,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/ns).toFixed(2)})}),o(T,{min:0,max:ns,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 is({leaf:t,devices:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(ts,{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(Lo,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(zo,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(Ct,{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 as({leaf:t,onChange:n}){let{t:r}=Q();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(Fo,{children:r(`flow.scene.every`,`Every`)}),o(hr,{"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(Fo,{children:r(`flow.scene.minutes`,`minutes`)})]})}function os({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},s=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{zones:n,...i}=t;r({...i,deviceId:e})};return e(`div`,{className:`space-y-3`,"data-testid":`stationary-present-fields`,children:[e(`div`,{className:`space-y-1`,children:[o(Fo,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(gn,{pick:`device`,noun:`camera`,fixedTypes:fr,recentKey:`build-cameras`,clearable:!1,value:t.deviceId>0?{deviceId:t.deviceId}:null,testId:`stationary-present-camera`,onChange:e=>{e!==null&&e.deviceId!==t.deviceId&&c(e.deviceId)}})]}),o(ts,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.isParked`,`is parked`),onChange:a}),e(`div`,{className:`flex items-center gap-2`,children:[o(Fo,{children:i(`flow.scene.minCount`,`At least`)}),o(hr,{"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(Fo,{children:i(`flow.scene.minCountUnit`,`parked objects`)})]}),o(zo,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:s})]})}var ss=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],cs=720,ls=1440;function us(){return{name:``,enabled:!0,priority:0,maxLateMs:Ce,profiles:[ds(`profile-1`,`Every day`)]}}function ds(e,t){return{id:e,name:t,enabled:!0,days:[...ss],points:[]}}function fs(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function ps(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function ms(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function hs(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 gs(e,t=Date.now()){return ue(t,e.timeZone)}function _s(e,t,n){let r=ms(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=Te(e,n,r);return i===null?null:hs(i,t.timeZone)}function vs(e,t,n){return e.kind===`sun`?_s({...e,offsetMin:0},t,n):null}function ys(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(cs,t-n));return{...e,offsetMin:r}}return e}function bs(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 xs(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function Ss(e){return xs(Math.floor(e/60),e%60)}function Cs(e,t,n){let r=e.flatMap(e=>{let r=_s(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?ls:n.minute}]})}function ws(e,t){let n=ne.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=Ze(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}var Ts=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],Es=[`sunrise`,`sunset`,`dawn`,`dusk`],Ds={from:{kind:`clock`,hh:22,mm:0},to:{kind:`clock`,hh:6,mm:0}};function Os(e,t){return{kind:`time-is`,...e===void 0?{}:{between:e},...t===void 0?{}:{days:[...t]}}}function ks(e){return e.days??Ts}function As(e,t){let n=ks(e),r=n.includes(t)?n.filter(e=>e!==t):Ts.filter(e=>e===t||n.includes(e)),i=r.length===Ts.length;return Os(e.between,i&&e.between!==void 0?void 0:r)}function js(e,t){if(t){let t=e.days!==void 0&&e.days.length===Ts.length;return Os(e.between??Ds,t?void 0:e.days)}return Os(void 0,ks(e))}function Ms(e,t,n){return Os({...e.between??Ds,[t]:n},e.days)}function Ns(e){return e===`sun`?{kind:`sun`,event:`sunset`,offsetMin:0}:{kind:`clock`,hh:12,mm:0}}function Ps(e){return e.kind===`date`?Ns(`clock`):e}function Fs(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 Is(e,t){if(t===void 0)return null;let n=we(e,t)[0];return n===void 0?null:`${n.path}: ${n.message}`}function Ls({label:t,testId:n,end:r,onChange:i}){let{t:a}=Q(),s=e=>`${t}: ${e}`;return e(`div`,{role:`group`,"aria-label":t,"data-testid":n,children:[o($,{children:t}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(z,{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(Ns(t))}}),r.kind===`clock`&&o(Y,{type:`time`,className:`w-28`,"aria-label":s(a(`schedulers.point.time`,`Time`)),value:xs(r.hh,r.mm),onChange:e=>{let t=bs(e.target.value);t!==null&&t.kind===`clock`&&i(t)}}),r.kind===`sun`&&e(m,{children:[o(z,{wrapperClassName:`relative w-40`,"aria-label":s(a(`schedulers.point.sunEvent`,`Sun event`)),value:r.event,options:Es.map(e=>({value:e,label:a(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Es.find(t=>t===e.target.value);t!==void 0&&i({...r,event:t})}}),o(hr,{"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 Rs({leaf:t,onChange:n}){let{t:r}=Q(),i=t.between,a=ks(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($,{children:r(`automation.timeIs.window`,`Time of day`)}),o(z,{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(js(t,e.target.value===`between`))})]}),i!==void 0&&e(m,{children:[o(Ls,{label:r(`automation.timeIs.from`,`From`),testId:`time-is-from`,end:Ps(i.from),onChange:e=>n(Ms(t,`from`,e))}),o(Ls,{label:r(`automation.timeIs.to`,`To`),testId:`time-is-to`,end:Ps(i.to),onChange:e=>n(Ms(t,`to`,e))})]})]}),e(`div`,{children:[o($,{children:r(`schedulers.profile.days`,`Days`)}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":r(`schedulers.profile.days`,`Days`),children:Ts.map(e=>{let i=a.includes(e);return o(X,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,onClick:()=>n(As(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.`)}),Fs(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 zs(e,t){let n=e.leaf;if(n.kind!==`device-becomes`&&n.kind!==`device-event`&&n.kind!==`device-fired`)return;let r=t.find(e=>e.id===n.deviceId)?.name;return n.kind===`device-becomes`?r:n.kind===`device-fired`?[r,[...n.sourceIds??[],...n.eventIds??[]].join(` `)].filter(e=>e!==void 0&&e!==``).join(` · `)||void 0:r===void 0?n.category:`${n.category} · ${r}`}function Bs({leaf:t,devices:n,onChange:r}){let{t:i}=Q(),a=La(),s=a.map(e=>e.id),c=Na(t,s),l=i(`automation.triggeredBy.triggers`,`Started by`);return e(`div`,{children:[o($,{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=zs(e,n);return o(X,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,className:`h-auto min-h-8 whitespace-normal py-1 text-left`,onClick:()=>r(Ma(t,e.id,s)),children:`${e.ordinal}. ${Pi(e.leaf.kind)}${a===void 0?``:` · ${a}`}`},e.id)})}),a.length>0&&t.leafIds.length===0&&o(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-none-picked`,children:i(`automation.triggeredBy.nonePicked`,`Pick at least one trigger.`)}),c.length>0&&o(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-missing`,children:i(`automation.triggeredBy.missing`,{count:c.length,defaultValue_one:`{{count}} chosen trigger no longer exists. Press a trigger to drop it.`,defaultValue_other:`{{count}} chosen triggers no longer exist. Press a trigger to drop them.`})})]})}function Vs(e){return e.kind===`all`||e.kind===`any`}function Hs(e){return[`when`,...e].join(`.`)}function Us(e){let t=e.when;return Vs(t)?t:{kind:`all`,children:[t]}}function Ws(e,t){return{...e,when:t}}function Gs(e){return Ws(e,Us(e))}function Ks(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?Ks(e.child,r):null;if(me(e))return null;let i=e.children[n];return i===void 0?null:Ks(i,r)}function qs(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=qs(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(me(e))return e;let a=e.children[r];if(a===void 0)return e;let o=qs(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 Js(e,t,n){let r=Us(e);return Ws(e,qs(r,t,n)??{kind:r.kind,children:[]})}function Ys(e){return{kind:e,children:[Ri(`device-is`)]}}function Xs(e,t,n){return Js(e,t,e=>Vs(e)?{kind:e.kind,children:[...e.children,n]}:e)}function Zs(e,t,n){return Js(e,t,()=>n)}function Qs(e,t){return Js(e,t,()=>null)}function $s(e,t,n){return Js(e,t,e=>Vs(e)?{kind:n,children:e.children}:e)}function ec(e,t){return t.length===0?e:Js(e,t,e=>({kind:`not`,child:e}))}function tc(e,t){return Js(e,t,e=>e.kind===`not`?e.child:e)}function nc(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=Ri(t);return fe(e)&&e.id!==void 0&&fe(n)?{...n,id:e.id}:n}function rc(e){let t=Us(e),n=t.children.length===0;return{depth:n?0:$e(t),leaves:n?0:_e(t),depthLimit:4,leafLimit:32}}function ic(e,t){let n=Us(e),r=1,i=n;for(let e of t){let t=Ks(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function ac(e,t,n){let r=t[t.length-1];if(r===void 0)return e;let i=t.slice(0,-1),a=Ks(Us(e),i);if(a===null||!Vs(a))return e;let o=r+n;return o<0||o>=a.children.length?e:Js(e,i,()=>({kind:a.kind,children:Hi(a.children,r,o)}))}function oc(e,t,n){let r=Hs(t),i=Hs(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 sc(e,t){return me(e)?t(e.kind):e.kind===`not`?`NOT ${sc(e.child,t)}`:e.children.map(e=>cc(e,t)).join(` · `)}function cc(e,t){return Vs(e)?`${e.kind.toUpperCase()} (${sc(e,t)})`:sc(e,t)}u();function lc({leaf:t,devices:n,context:r,underNot:i,toneClass:a,result:s,onNegate:l,move:u,onChange:d,onRemove:f}){let{t:p}=Q(),[m,h]=c(!1),_=fe(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($,{children:p(`automation.whenTree.rowType`,`Row type`)}),e(X,{variant:`outline`,"data-testid":`when-row-type`,className:`w-full justify-between`,onClick:()=>h(!0),title:p(`automation.leafPicker.changeType`,`Change type`),children:[o(`span`,{className:`truncate`,children:Pi(t.kind)}),o(`span`,{className:`text-foreground-subtle`,children:p(`automation.leafPicker.changeType`,`Change type`)})]}),o(Va,{open:m,onOpenChange:h,mode:`change`,context:r,underNot:i,treeFull:!1,current:t.kind,onPick:e=>{e!==t.kind&&d(nc(t,e))}})]}),o(J,{variant:_?`info`:`neutral`,"data-testid":`when-row-nature`,children:_?p(`automation.whenTree.natureEvent`,`Event`):p(`automation.whenTree.natureState`,`State`)}),o(`span`,{className:`flex-1`}),u!==void 0&&o(sa,{move:u}),l!==null&&o(X,{variant:`ghost`,onClick:l,title:p(`automation.whenTree.negateRow`,`Invert this row (NOT)`),children:`NOT`}),o(X,{variant:`ghost`,onClick:f,title:p(`automation.whenTree.removeRow`,`Remove this row`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:o(uc,{leaf:t,devices:n,onChange:d})}),s!==void 0&&o(`div`,{className:`mt-2`,children:s})]})}function uc({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return o(uo,{leaf:e,devices:t,onChange:n});case`device-event`:return o(po,{leaf:e,onChange:n});case`device-fired`:return o(No,{leaf:e,onChange:n});case`schedule`:return o(no,{leaf:e,onChange:n});case`interval`:return o(as,{leaf:e,onChange:n});case`manual`:return o(ro,{});case`detection`:return o(rs,{leaf:e,devices:t,onChange:n});case`stationary`:return o(is,{leaf:e,devices:t,onChange:n});case`device-is`:return o($a,{leaf:e,devices:t,onChange:n});case`stationary-present`:return o(os,{leaf:e,devices:t,onChange:n});case`expression`:return o(_o,{leaf:e,devices:t,onChange:n});case`time-is`:return o(Rs,{leaf:e,onChange:n});case`triggered-by`:return o(Bs,{leaf:e,devices:t,onChange:n})}}u();function dc(e){return e===`any`?`any`:`all`}function fc(e){return e===`pass`?`pass`:e===`fail`?`fail`:`idle`}function pc(e,t,n=!0){return e===void 0?t:n?li(fc(e)):di(fc(e))}function mc(e,t){return e.run?.nodes.get(Hs(t))}function hc({recipe:t,devices:n,onChange:r,run:i=null,hideRule:a=!1,context:s=`trigger`}){let{t:l}=Q(),u=Us(t),d=rc(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=Hs(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=>oc(t,e,a)),r(ac(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(wc,{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 gc({node:e,path:t,ctx:n,underNot:r,move:i,rail:a}){return me(e)?o(_c,{leaf:e,path:t,ctx:n,underNot:r,move:i}):e.kind===`not`?o(Cc,{child:e.child,path:t,ctx:n,move:i,rail:a}):o(wc,{block:e,path:t,ctx:n,underNot:r,move:i,rail:a,budgetText:null,emptyHint:null})}function _c({leaf:e,path:t,ctx:n,underNot:r,move:i}){let a=mc(n,t),s=n.run!==null&&n.run.triggerPath===Hs(t)?n.run.vars:void 0;return o(lc,{leaf:e,devices:n.devices,context:n.leafContext,underNot:r,toneClass:pc(a?.outcome,`border-border`),result:a===void 0?void 0:o(vc,{leaf:e,node:a,vars:s}),onNegate:r?null:()=>n.reshape(ec(n.recipe,t)),...i===null?{}:{move:i},onChange:e=>n.onChange(Zs(n.recipe,t,e)),onRemove:()=>n.reshape(Qs(n.recipe,t))})}function vc({leaf:e,node:t,vars:n}){return e.kind===`device-is`&&e.unit!==void 0?o(yc,{leaf:e,node:t,vars:n}):o(Xi,{node:t,vars:n,expected:t.expected,observed:t.observed})}function yc({leaf:e,node:t,vars:n}){let r=Xa(Qi({deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})),i=r===void 0?void 0:Re(r),a=t=>t===void 0?null:Xr(t,i,e.unit);return o(Xi,{node:t,vars:n,expected:a(t.rawExpected),observed:a(t.rawObserved)})}function bc({node:e}){return e===void 0?null:o(Xi,{node:e,expected:null,observed:null})}function xc({expanded:e,onToggle:t}){let{t:n}=Q(),r=e?n(`automation.whenTree.collapse`,`Collapse this block`):n(`automation.whenTree.expand`,`Expand this block`);return o(X,{variant:`ghost`,"aria-expanded":e,"aria-label":r,title:r,onClick:t,children:o(wt,{expanded:e})})}function Sc({node:e}){let{t}=Q(),n=`${t(`automation.whenTree.rowCount`,{count:_e(e)})} · ${sc(e,Pi)}`;return o(`p`,{"data-testid":`when-block-summary`,title:n,className:`break-words text-xs text-foreground-muted sm:truncate`,children:n})}function Cc({child:t,path:n,ctx:r,move:i,rail:a}){let{t:s}=Q(),c=!r.collapsed.has(Hs(n));return e(`div`,{className:`space-y-1.5 rounded border p-2 ${pc(mc(r,n)?.outcome,`border-warning/40`,!1)}`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(xc,{expanded:c,onToggle:()=>r.toggleCollapsed(n)}),o(J,{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(sa,{move:i}),e(X,{variant:`ghost`,onClick:()=>r.reshape(tc(r.recipe,n)),title:s(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[o(rt,{className:`h-3.5 w-3.5`}),` `,s(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),o(bc,{node:mc(r,n)}),c?o(`div`,{className:`pl-3`,children:o(gc,{node:t,path:[...n,0],ctx:r,underNot:!0,move:null,rail:a})}):o(Sc,{node:t})]})}function wc({block:t,path:n,ctx:r,underNot:i,move:a,rail:s,budgetText:l,emptyHint:u}){let{t:d}=Q(),f=n.length===0,p=f||!r.collapsed.has(Hs(n)),m=ic(r.recipe,n),[h,_]=c(!1),v=Ta(t.children,s),y=[{value:`all`,label:d(`automation.whenTree.allOf`,`All of (AND)`)},{value:`any`,label:d(`automation.whenTree.anyOf`,`Any of (OR)`)}];return e(`div`,{className:`space-y-2 rounded border p-2 ${pc(mc(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(xc,{expanded:p,onToggle:()=>r.toggleCollapsed(n)}),o(`div`,{className:`w-40`,children:o(z,{"aria-label":d(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:y,onChange:e=>r.onChange($s(r.recipe,n,dc(e.target.value)))})}),l!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:l}),o(`span`,{className:`flex-1`}),a!==null&&o(sa,{move:a}),!f&&!i&&o(X,{variant:`ghost`,onClick:()=>r.reshape(ec(r.recipe,n)),title:d(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!f&&o(X,{variant:`ghost`,onClick:()=>r.reshape(Qs(r.recipe,n)),title:d(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(bc,{node:mc(r,n)}),u!==null&&o(`p`,{className:`text-xs text-foreground-subtle`,children:u}),!p&&o(Sc,{node:t}),p&&t.children.length>0&&o(`div`,{className:`space-y-1.5 border-l-2 pl-3 ${Ea(s)}`,"data-testid":`when-block-rail`,"data-rail":s,children:t.children.map((e,i)=>o(gc,{node:e,path:[...n,i],ctx:r,underNot:!1,move:r.moveControls([...n,i],t.children.length),rail:v[i]??s},Hs([...n,i])))}),p&&e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:`outline`,onClick:()=>_(!0),title:d(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[o(P,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addRow`,`Add row`)]}),o(Va,{open:h,onOpenChange:_,mode:`add`,context:r.leafContext,underNot:i,treeFull:_e(Us(r.recipe))>=32,onPick:e=>r.onChange(Xs(r.recipe,n,Ri(e)))}),e(X,{variant:`outline`,disabled:!m,onClick:()=>r.onChange(Xs(r.recipe,n,Ys(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:rc(r.recipe).depthLimit}),children:[o(P,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addBlock`,`Add block`)]})]})]})}var Tc={kind:`all`,children:[]};function Ec(e){return e.kind===`wait`||e.kind===`command`}function Dc(e){return!me(e)&&e.kind!==`not`&&e.children.length===0?null:Se(e)}function Oc(e){let{if:t,else:n,...r}=e;return r}function kc({when:t,devices:n,hint:r,onChange:i,children:a}){let{t:s}=Q(),c=t===void 0?null:{when:t,actions:[]},l=t===void 0?null:Dc(t);return e(`div`,{className:`space-y-2 border-t border-border-subtle pt-2`,children:[o(Jt,{checked:t!==void 0,label:s(`automation.stepGuard.if`,`Only if…`),"aria-label":s(`automation.stepGuard.if`,`Only if…`),onCheckedChange:e=>i(e?Tc:void 0)}),c!==null&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:r}),o(hc,{hideRule:!0,context:`guard`,recipe:c,devices:n,onChange:e=>i(e.when)}),l!==null&&o(q,{variant:`warning`,message:l}),a]})]})}function Ac({step:t,devices:n,devicesState:r,variables:i,onChange:a}){let{t:s}=Q();return e(kc,{when:t.if,devices:n,hint:s(`automation.stepGuard.hint`,`Checked when this step is reached. If a state cannot be read, the step and its else are both skipped.`),onChange:e=>a(e===void 0?Oc(t):{...t,if:e}),children:[o(Jt,{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(Gc,{nested:!0,actions:t.else,devices:n,...r===void 0?{}:{devicesState:r},...i===void 0?{}:{variables:i},allowedKinds:[`command`,`wait`],onChange:e=>a({...t,else:e.filter(Ec)})})})]})}function jc({index:t,step:n,devices:r,devicesState:i,variables:a,depth:s=0,roundDevices:c,onChange:l}){let{t:u}=Q(),d={nested:!0,flowControl:!0,devices:r,depth:s+1,allowedKinds:xa(s+1),...c===void 0?{}:{roundDevices:c},...i===void 0?{}:{devicesState:i},...a===void 0?{}:{variables:a}};return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.choose.hint`,`Read top to bottom: the first branch whose condition is true runs, and only that one. If a condition cannot be read, nothing runs.`)}),n.branches.map((i,a)=>{let s={when:i.if,actions:[]},c=Dc(i.if);return e(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,"data-testid":`choose-branch-${String(t)}-${String(a)}`,children:[e(`div`,{className:`flex items-center gap-2`,children:[o($,{children:a===0?u(`automation.choose.if`,`If`):u(`automation.choose.elseIf`,`Otherwise, if`)}),o(X,{variant:`ghost`,className:`ml-auto`,disabled:!ga(n),"data-testid":`choose-remove-${String(t)}-${String(a)}`,onClick:()=>l(_a(n,a)),title:ga(n)?u(`automation.choose.removeBranch`,`Remove this branch`):u(`automation.choose.lastBranch`,`A choose keeps at least one branch`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(hc,{hideRule:!0,context:`guard`,recipe:s,devices:r,onChange:e=>l(va(n,a,{...i,if:e.when}))}),c!==null&&o(q,{variant:`warning`,message:c}),o($,{children:u(`automation.choose.then`,`Then run`)}),o(Gc,{...d,actions:i.steps,onChange:e=>l(va(n,a,{...i,steps:e.filter(Sa)}))})]},String(a))}),e(X,{variant:`outline`,"data-testid":`choose-add-${String(t)}`,disabled:!ma(n),onClick:()=>l(ha(n)),title:ma(n)?void 0:u(`automation.choose.maxBranches`,`A choose takes at most 6 branches`),children:[o(P,{className:`h-4 w-4`}),` `,u(`automation.choose.addBranch`,`Add a branch`)]}),o(Jt,{"data-testid":`choose-else-${String(t)}`,checked:n.else!==void 0,label:u(`automation.choose.else`,`Otherwise, run…`),"aria-label":u(`automation.choose.else`,`Otherwise, run…`),onCheckedChange:e=>l(ya(n,e?[]:void 0))}),n.else!==void 0&&o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(Gc,{...d,actions:n.else,onChange:e=>l(ya(n,e.filter(Sa)))})})]})}function Mc(e){return Object.entries(e).map(([e,t])=>({name:e,value:t}))}function Nc(e){return Object.fromEntries(e.map(e=>[e.name,e.value]))}function Pc(e,t,n){let r=Mc(e);return r.some((e,r)=>r!==t&&e.name===n)?e:Nc(r.map((e,r)=>r===t?{...e,name:n}:e))}function Fc(e,t,n){return Nc(Mc(e).map((e,r)=>r===t?{...e,value:n}:e))}function Ic(e){return!Object.keys(e).includes(``)}function Lc(e){return Ic(e)?{...e,"":``}:e}function Rc(e,t){return Nc(Mc(e).filter((e,n)=>n!==t))}var zc=`{{vars.name}}`;function Bc({index:t,vars:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`space-y-2`,children:[Mc(n).map((a,s)=>e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-40`,children:[o($,{children:i(`automation.actionList.setName`,`Variable`)}),o(Y,{"data-testid":`set-name-${String(t)}-${String(s)}`,value:a.name,spellCheck:!1,onChange:e=>r(Pc(n,s,e.target.value))})]}),e(`label`,{className:`min-w-40 flex-1`,children:[o($,{children:i(`automation.actionList.setValue`,`Value`)}),o(Y,{"data-testid":`set-value-${String(t)}-${String(s)}`,value:String(a.value),onChange:e=>r(Fc(n,s,e.target.value))})]}),o(X,{variant:`ghost`,onClick:()=>r(Rc(n,s)),title:i(`automation.actionList.setRemove`,`Remove this variable`),children:o(g,{className:`h-3.5 w-3.5`})})]},String(s))),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:`outline`,"data-testid":`set-add-${String(t)}`,disabled:!Ic(n),onClick:()=>r(Lc(n)),children:[o(P,{className:`h-4 w-4`}),` `,i(`automation.actionList.setAdd`,`Add a variable`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.setHint`,`The steps after this one can use it as {{slot}}.`,{slot:zc,interpolation:{escapeValue:!1}})})]})]})}function Vc({index:t,step:n,devices:r,devicesState:i,variables:a,depth:s=0,roundDevices:c,onChange:l}){let{t:u}=Q(),{loop:d}=n,f={count:u(`automation.repeat.byCount`,`A number of times`),while:u(`automation.repeat.byWhile`,`While a condition is true`),until:u(`automation.repeat.byUntil`,`Until a condition is true`),forEach:u(`automation.repeat.byForEach`,`Once for each device`)},p=d.by===`while`||d.by===`until`,h=p?Dc(d.when):null,g={name:W,hint:u(`automation.repeat.itemHint`,`the device of this round`)},_=d.by===`forEach`?[...a??[],g]:a,v=d.by===`forEach`?d.target.ids:c;return e(`div`,{className:`space-y-2`,children:[o(`div`,{className:`w-64`,children:o(z,{"data-testid":`repeat-by-${String(t)}`,"aria-label":u(`automation.repeat.by`,`Repeat`),value:d.by,onChange:e=>{let t=e.target.value;_i(t)&&t!==d.by&&l({...n,loop:xi(t)})},options:pi.map(e=>({value:e,label:f[e]}))})}),d.by===`count`&&e(`label`,{className:`block w-24`,children:[o($,{children:u(`automation.repeat.count`,`Times`)}),o(Y,{type:`number`,min:1,max:20,"data-testid":`repeat-count-${String(t)}`,value:String(d.count),onChange:e=>l({...n,loop:{...d,count:yi(Number(e.target.value))}})})]}),p&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:d.by===`while`?u(`automation.repeat.whileHint`,`Read before each round: if it is not true at the start, nothing runs. A condition that cannot be read ends the loop.`):u(`automation.repeat.untilHint`,`Read after each round, so the steps run at least once. A condition that cannot be read ends the loop.`)}),o(hc,{hideRule:!0,context:`guard`,recipe:{when:d.when,actions:[]},devices:r,onChange:e=>l({...n,loop:{...d,when:e.when}})}),h!==null&&o(q,{variant:`warning`,message:h}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-28`,children:[o($,{children:u(`automation.repeat.max`,`At most (rounds)`)}),o(Y,{type:`number`,min:1,max:50,"data-testid":`repeat-max-${String(t)}`,value:String(d.maxIterations),onChange:e=>l({...n,loop:{...d,maxIterations:bi(Number(e.target.value))}})})]}),e(`label`,{className:`w-40`,children:[o($,{children:u(`automation.repeat.wait`,`Pause between rounds (s)`)}),o(Y,{type:`number`,min:1,max:3600,"data-testid":`repeat-wait-${String(t)}`,value:d.waitS===void 0?``:String(d.waitS),placeholder:u(`automation.repeat.noWait`,`none`),onChange:e=>l({...n,loop:Si(d,e.target.value===``?null:Number(e.target.value))})})]})]}),o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.maxHint`,`A loop that reaches its maximum stops there, is marked in the run, and the run goes on.`)})]}),d.by===`forEach`&&e(`div`,{className:`space-y-1`,children:[o(gn,{multiple:!0,pick:`device`,maxItems:50,value:d.target.ids.map(e=>({deviceId:e})),onChange:e=>l({...n,loop:{...d,target:{kind:`devices`,ids:e.map(e=>e.deviceId)}}})}),o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.forEachHint`,`One round per device, in this order. In a round the steps read the device as the variable "item".`)})]}),o($,{children:u(`automation.repeat.steps`,`Each time, run`)}),o(`div`,{className:`border-l-2 border-border-subtle pl-3`,"data-testid":`repeat-steps-${String(t)}`,children:o(Gc,{nested:!0,flowControl:!0,actions:n.steps,devices:r,depth:s+1,allowedKinds:xa(s+1),maxSteps:10,...i===void 0?{}:{devicesState:i},..._===void 0?{}:{variables:_},...v===void 0?{}:{roundDevices:v},onChange:e=>l({...n,steps:e.filter(Sa)})})})]})}function Hc({index:t,step:n,devices:r,onChange:i}){let{t:a}=Q(),s={when:n.when,actions:[]},c=Dc(n.when),l=Di(n.timeoutS),u={s:a(`automation.waitUntil.unitSeconds`,`seconds`),min:a(`automation.waitUntil.unitMinutes`,`minutes`),h:a(`automation.waitUntil.unitHours`,`hours`)};return e(`div`,{className:`space-y-2`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.waitUntil.hint`,`The run pauses here until this is true. A value that cannot be read is not "true": the run keeps waiting.`)}),o(hc,{hideRule:!0,context:`guard`,recipe:s,devices:r,onChange:e=>i({...n,when:e.when})}),c!==null&&o(q,{variant:`warning`,message:c}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-24`,children:[o($,{children:a(`automation.waitUntil.timeout`,`At most`)}),o(Y,{type:`number`,min:1,"data-testid":`wait-until-timeout-${String(t)}`,value:String(l.value),onChange:e=>i({...n,timeoutS:Oi(Number(e.target.value),l.unit)})})]}),o(`div`,{className:`w-32`,children:o(z,{"data-testid":`wait-until-unit-${String(t)}`,"aria-label":a(`automation.waitUntil.unit`,`Unit`),value:l.unit,onChange:e=>i({...n,timeoutS:Oi(l.value,Ei(e.target.value)?e.target.value:l.unit)}),options:wi.map(e=>({value:e,label:u[e]}))})}),e(`label`,{className:`min-w-56 flex-1`,children:[o($,{children:a(`automation.waitUntil.onTimeout`,`If it does not happen in time`)}),o(z,{"data-testid":`wait-until-on-timeout-${String(t)}`,value:n.onTimeout,onChange:e=>i({...n,onTimeout:e.target.value===`stop`?`stop`:`continue`}),options:[{value:`continue`,label:a(`automation.waitUntil.continue`,`Go on with the next step`)},{value:`stop`,label:a(`automation.waitUntil.stop`,`Stop the run as a failure`)}]})]})]})]})}var Uc=[{value:`command`,labelKey:`automation.actionList.kindCap`},{value:`action`,labelKey:`automation.actionList.kindAction`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`wait-until`,labelKey:`automation.actionList.kindWaitUntil`},{value:`set`,labelKey:`automation.actionList.kindSet`},{value:`stop`,labelKey:`automation.actionList.kindStop`},{value:`choose`,labelKey:`automation.actionList.kindChoose`},{value:`parallel`,labelKey:`automation.actionList.kindParallel`},{value:`repeat`,labelKey:`automation.actionList.kindRepeat`},{value:`code`,labelKey:`automation.actionList.kindCode`}],Wc=[`set`,`stop`,`choose`,`wait-until`,`parallel`,`repeat`];function Gc({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:s,stepResults:c,nested:l=!1,flowControl:u=!1,maxSteps:d,roundDevices:f,depth:p=0,onChange:m}){let{t:h}=Q(),_=Uc.filter(e=>(i===void 0||i.includes(e.value))&&(u||!Wc.includes(e.value))),v=h(`automation.actionList.flowGuardHint`,`Checked when this step is reached. If it is false, or a state cannot be read, the step does nothing.`),y={up:h(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),down:h(`automation.actionList.runThisStepLater`,`Run this step later`),atFirst:h(`automation.actionList.alreadyFirstStep`,`This step already runs first`),atLast:h(`automation.actionList.alreadyLastStep`,`This step already runs last`)};return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:h(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((i,d)=>e(`div`,{className:`space-y-2 rounded border p-3 ${s===void 0?`border-border`:li(s[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(J,{variant:`default`,children:d+1}),e(`label`,{className:`w-40`,children:[o($,{children:h(`automation.actionList.step`,`Step`)}),o(z,{"data-testid":`step-kind-${String(d)}`,value:i.kind,onChange:e=>m(Bi(t,d,zi(Kc(e.target.value)))),options:_.map(e=>({value:e.value,label:h(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(sa,{move:{up:d===0?null:()=>m(Hi(t,d,d-1)),down:d===t.length-1?null:()=>m(Hi(t,d,d+1))},texts:y}),o(X,{variant:`ghost`,onClick:()=>m(Vi(t,d)),title:h(`automation.actionList.removeThisStep`,`Remove this step`),children:o(g,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o($,{children:h(`automation.actionList.seconds`,`Seconds`)}),o(Y,{type:`number`,min:0,max:3600,value:String(i.seconds),onChange:e=>m(Bi(t,d,{...i,seconds:Number(e.target.value)}))})]}),i.kind===`stop`&&e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`min-w-48 flex-1`,children:[o($,{children:h(`automation.actionList.stopReason`,`Reason`)}),o(Y,{"data-testid":`stop-reason-${String(d)}`,value:i.reason,maxLength:200,onChange:e=>m(Bi(t,d,{...i,reason:e.target.value}))})]}),e(`label`,{className:`w-48`,children:[o($,{children:h(`automation.actionList.stopOutcome`,`The run ends as`)}),o(z,{"data-testid":`stop-outcome-${String(d)}`,value:i.outcome,onChange:e=>m(Bi(t,d,{...i,outcome:e.target.value===`failed`?`failed`:`ok`})),options:[{value:`ok`,label:h(`automation.actionList.stopOk`,`A success`)},{value:`failed`,label:h(`automation.actionList.stopFailed`,`A failure`)}]})]})]}),i.kind===`set`&&o(Bc,{index:d,vars:i.vars,onChange:e=>m(Bi(t,d,{...i,vars:e}))}),i.kind===`wait-until`&&o(Hc,{index:d,step:i,devices:n,onChange:e=>m(Bi(t,d,e))}),i.kind===`repeat`&&o(Vc,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Bi(t,d,e))}),i.kind===`parallel`&&e(`div`,{className:`space-y-2`,"data-testid":`parallel-steps-${String(d)}`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:h(`automation.parallel.hint`,`These start together and the run goes on when all are done. If one fails, the run fails once the others finished.`)}),o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(Gc,{nested:!0,flowControl:!0,actions:i.steps,devices:n,devicesState:r,variables:a,allowedKinds:la,depth:p+1,...f===void 0?{}:{roundDevices:f},maxSteps:5,onChange:e=>m(Bi(t,d,{...i,steps:e.filter(ua)}))})})]}),i.kind===`choose`&&o(jc,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Bi(t,d,e))}),!l&&(i.kind===`stop`||i.kind===`set`)&&o(kc,{when:i.if,devices:n,hint:v,onChange:e=>{let{if:n,...r}=i;m(Bi(t,d,e===void 0?r:{...r,if:e}))}}),i.kind===`code`&&e(`label`,{className:`block`,children:[o($,{children:h(`automation.actionList.code`,`Code`)}),o(Xt,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:i.code,spellCheck:!1,onChange:e=>m(Bi(t,d,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(Ln,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),i.kind===`command`&&o(xr,{step:i,devices:n,variables:a,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Bi(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{},...i.if===void 0?{}:{if:i.if},...i.else===void 0?{}:{else:i.else}}))}),i.kind===`action`&&o(ia,{step:i,onChange:e=>m(Bi(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{}}))}),u&&(i.kind===`command`||i.kind===`action`)&&o(Jt,{"data-testid":`continue-on-error-${String(d)}`,checked:i.continueOnError===!0,label:h(`automation.actionList.continueOnError`,`Continue if this step fails`),"aria-label":h(`automation.actionList.continueOnError`,`Continue if this step fails`),onCheckedChange:e=>{let{continueOnError:n,...r}=i;m(Bi(t,d,e?{...r,continueOnError:!0}:r))}}),!l&&(i.kind===`wait`||i.kind===`command`)&&o(Ac,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>m(Bi(t,d,e))}),c?.[d]!==void 0&&o(Zi,{step:c[d],deviceName:e=>n.find(t=>t.id===e)?.name??`#${String(e)}`})]},`${i.kind}-${String(d)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(X,{variant:`outline`,disabled:d!==void 0&&t.length>=d,onClick:()=>m([...t,zi(_[0]?.value??`command`)]),children:[o(P,{className:`h-4 w-4`}),` `,h(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function Kc(e){return Uc.find(t=>t.value===e)?.value??`command`}function qc(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function Jc(e,t){return Me(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.hintKey??e.name}`,e.description)}))}function Yc(e){return e.some(e=>e.required===!0&&e.default===void 0)}function Xc(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function Zc(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function Qc(e,t){return e.filter(e=>e.required===!0&&!Zc(t[e.name])).map(e=>e.name)}function $c(e,t){let n={};for(let r of e){let e=t[r.name];Zc(e)&&(n[r.name]=e)}return n}u();function el({variable:e,value:t,onChange:n}){let{t:r}=Q(),i=e.label??e.name;return e.type===`number`?o(hr,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?o(_r,{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(_r,{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(Y,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function tl({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:s}=Q(),[l,u]=c(()=>Xc(n)),d=Qc(n,l);return o(wn,{open:!0,onOpenChange:e=>!e&&a(),children:e(_t,{"aria-label":s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(hn,{children:[o(lt,{children:s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),o(gt,{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(el,{variable:t,value:l[t.name],onChange:e=>u({...l,[t.name]:e})})]},t.name))}),e(Pt,{className:`flex flex-wrap gap-2`,children:[o(X,{variant:`ghost`,onClick:a,children:s(`common.cancel`,`Cancel`)}),e(X,{disabled:r||d.length>0,onClick:()=>i($c(n,l)),children:[r?o(S,{className:`h-4 w-4 animate-spin`}):o(R,{className:`h-4 w-4`}),` `,s(`actions.editor.runNow`,`Run now`)]})]})]})})}var nl=[`number`,`string`,`boolean`,`select`];function rl(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function il(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 al(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function ol(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function sl({variables:t,onChange:n,onRename:r}){let{t:i}=Q(),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(mt,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:at,actions:e(X,{variant:`outline`,size:`sm`,onClick:()=>n([...t,Sr(t)]),children:[o(P,{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(Y,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!Cr(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(Y,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,ol(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(_r,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:nl.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=nl.find(t=>t===e.target.value);t!==void 0&&s(l,rl(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(cl,{variable:c,onChange:e=>s(l,al(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(Y,{"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,il(c,e.target.value))})]}),o(X,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(g,{className:`h-4 w-4`})})]},`${String(l)}`)),o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function cl({variable:e,onChange:t}){let{t:n}=Q(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(hr,{"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(_r,{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(Y,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var ll=5e3;function ul(e){return e.kind===`command`||e.kind===`wait`}function dl(e){return e instanceof Error?e.message:String(e)}function fl(){let{t:e}=Q();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 pl({entry:t,onClose:i,onSaved:a,preset:l=null}){let{t:u}=Q(),d=f(),p=j(),h=ur(),_=fl(),[v,y]=c(()=>Er(t)),b=n(!1);s(()=>{if(t!==null||l!==`trigger-alarm`||b.current)return;let e=h.find(e=>e.type===G.AlarmPanel);e!==void 0&&(b.current=!0,y(Dr(e.id,u(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[h,t,l,u]);let[C,w]=c(null),[T,E]=c(!1),D=t!==null&&t.readOnly,O=()=>{d.invalidateQueries({queryKey:[[`actions`]]})},k=cn({onSuccess:e=>{O(),a(e.action.id)}}),A=pt({onSuccess:O}),M=Qt({onSuccess:()=>{O(),i()}}),N=Dn({onSuccess:O}),P=An({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:ll}),F=P.data?.traces.find(e=>e.runId===C)??null,I=r(()=>F===null?null:Vr(F),[F]),L=r(()=>F===null?null:qr(F).steps,[F]),z=wr(v),B=r(()=>qc(v.variables,u),[v.variables,u]),V=k.isPending||A.isPending,ee=k.error??A.error??M.error??N.error,H=Yc(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(x,{className:`h-4 w-4 text-foreground-muted`}),o(Y,{"aria-label":u(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:v.name,disabled:D,placeholder:u(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>y({...v,name:e.target.value})}),o(J,{variant:D?`info`:`primary`,children:D?t?.addonId??``:u(`actions.source.internal`,`Internal`)})]}),D?o(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:u(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(m,{children:[o(sl,{variables:v.variables,onChange:e=>y({...v,variables:e}),onRename:(e,t)=>y(Tr(v,e,t))}),o(fi,{step:`steps`,title:u(`actions.editor.steps`,`Steps`),trace:I===null?null:I.thenBlock,children:o(Gc,{actions:v.steps,devices:h,allowedKinds:[`command`,`wait`],stepTones:I===null?void 0:v.steps.map((e,t)=>Hr(I,t)??`idle`),stepResults:L===null?void 0:v.steps.map((e,t)=>L.find(e=>e.index===t)),variables:B,onChange:e=>y({...v,steps:e.filter(ul)})})})]}),!z.ok&&!D&&v.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:_(z.reason)}),ee!==null&&o(q,{message:dl(ee)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!D&&e(X,{onClick:()=>{z.ok&&(t===null?k.mutate({action:z.input}):A.mutate({actionId:t.id,action:z.input}))},disabled:V||!z.ok,children:[V&&o(S,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),t!==null&&e(X,{variant:`outline`,disabled:N.isPending,onClick:()=>H?E(!0):N.mutate({actionId:t.id}),children:[o(R,{className:`h-4 w-4`}),` `,u(`actions.editor.runNow`,`Run now`)]}),t!==null&&!D&&e(X,{variant:`ghost`,disabled:M.isPending,onClick:()=>{p({title:u(`actions.editor.deleteTitle`,`Delete this action?`),message:u(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:u(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&M.mutate({actionId:t.id})})},children:[o(g,{className:`h-4 w-4`}),` `,u(`common.delete`,`Delete`)]}),o(X,{variant:`ghost`,onClick:i,children:u(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(ci,{traces:t===null?[]:P.data?.traces,selectedId:C,onSelect:w})}),T&&t!==null&&o(tl,{actionName:t.name,variables:t.variables??[],running:N.isPending,onCancel:()=>E(!1),onRun:e=>{N.mutate({actionId:t.id,variables:e}),E(!1)}})]})}u();var ml=5e3;function hl(e){return e instanceof Error?e.message:String(e)}function gl(){let{t:e}=Q();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 _l({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),[a]=Un(),c=f(),l=gl(),{state:u,openNew:d,openEdit:p,close:h}=Yt({editKey:`action`,newKey:`new`}),g=tn({},{refetchInterval:ml}),_=Dn({onSuccess:()=>void c.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(d(),n?.())},[t,n,d]);let v=g.data??[],y=u.mode===`edit`?v.find(e=>e.id===u.id)??null:null,b=r(()=>[{key:`name`,header:i(`actions.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:i(`actions.list.source`,`Source`),render:e=>e.readOnly?o(J,{variant:`info`,children:e.addonId}):o(J,{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:`-`}):qn(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(J,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(X,{variant:`outline`,size:`sm`,disabled:_.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),_.mutate({actionId:t.id})},children:[o(R,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[_,l,i]);return u.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),_.error!=null&&o(q,{message:hl(_.error)}),g.data===void 0?g.error==null?o(ct,{className:`h-24 w-full`}):o(q,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:hl(g.error),onRetry:()=>void g.refetch()}):v.length===0?o(dt,{icon:x,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(X,{onClick:d,children:[o(P,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(m,{children:[g.error!=null&&o(q,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:hl(g.error),onRetry:()=>void g.refetch()}),o(Vt,{columns:b,rows:v,rowKey:e=>e.id,pageSize:25,maxBodyHeight:vt,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>p(e.id)})]})]}):o(pl,{entry:y,onClose:h,onSaved:p,preset:u.mode===`new`?a.get(`preset`):null},y?.id??`new`)}u();function vl({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Q(),[l,u]=c(!1),d=j(),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(X,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?et:O,{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(X,{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(tt,{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(Mn,{maxHeight:420,children:t})})]})}var yl=[`single`,`restart`,`queued`,`parallel`,`cooldown`],bl=2,xl=30;function Sl(e){return e.runMode??{mode:`single`}}function Cl(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function wl(e){switch(e){case`queued`:return{mode:`queued`,max:bl};case`parallel`:return{mode:`parallel`,max:bl};case`cooldown`:return{mode:`cooldown`,minutes:xl};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function Tl(e){return yl.find(t=>t===e)??`single`}function El({value:t,onChange:n}){let{t:r}=Q(),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(_r,{widthClass:`w-56`,value:t.mode,options:yl.map(e=>({value:e,label:i[e]})),onChange:e=>n(wl(Tl(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(hr,{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(hr,{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 Dl;function Ol(){return Dl??=Ue(re),Dl}function kl(e,t=Ol()){return Ge(e,t)}u();var Al=`hub`,jl=5e3;function Ml({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d,onSaveAsTemplate:f,savingAsTemplate:p=!1}){let{t:m}=Q(),[h,g]=c(t?.name??``),[_,v]=c(()=>Gs(n)),y=e=>v(ja(e)),[b,x]=c(!1),[C,w]=c(null),T=bt({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:jl}),E=T.data?.traces.find(e=>e.runId===C)??null,D=r(()=>E===null?null:Vr(E),[E]),O=r(()=>Jc(_.when,m),[_.when,m]),k=r(()=>E===null?null:Jr(E),[E]),A=r(()=>E===null?null:qr(E).steps,[E]),j=ur(),M=ze(_),N=r(()=>Nl(_),[_]),P=r(()=>Pl(h.trim()===``?`Untitled automation`:h.trim(),_),[h,_]),F=qt().data,I=r(()=>N===null?Is(_,F):null,[_,F,N]),L=h.trim()===``,R=L||M!==null||N!==null||I!==null||P.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[o(Ia,{when:_.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:m(`automation.automationEditor.name`,`Name`)}),o(Y,{className:`mt-1`,value:h,onChange:e=>g(e.target.value),placeholder:m(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(fi,{step:`when`,title:m(`automation.automationEditor.when`,`When`),trace:D===null?null:D.when,children:o(hc,{recipe:_,devices:j,run:k,onChange:y})}),o(fi,{step:`then`,title:m(`automation.automationEditor.then`,`Then`),trace:D===null?null:D.thenBlock,hint:m(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(Gc,{flowControl:!0,actions:_.actions,devices:j,variables:O,stepTones:D===null?void 0:_.actions.map((e,t)=>Hr(D,t)??`idle`),stepResults:A===null?void 0:_.actions.map((e,t)=>A.find(e=>e.index===t)),onChange:e=>y(Ui(_,e))})}),o(fi,{step:`mode`,title:m(`flow.runMode.title`,`Overlap`),trace:null,hint:m(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:o(El,{value:Sl(_),onChange:e=>y(Cl(_,e))})}),o(vl,{code:P.code,error:P.error,canEject:t!==null,ejecting:s,onEject:u}),M!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:M}),M===null&&N!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:N}),M===null&&I!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`automation-site-error`,children:I}),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(X,{onClick:()=>{P.code!==null&&l({name:h.trim(),code:P.code,enabled:t?.enabled??!0,placement:Al})},disabled:i||R,children:[i&&o(S,{className:`h-4 w-4 animate-spin`}),` `,m(`common.save`)]}),e(X,{variant:`ghost`,onClick:()=>x(!b),disabled:t===null,title:t===null?m(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):m(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,"aria-expanded":b,children:[o(V,{className:`h-4 w-4`}),` `,m(`common.logs`),` `,o(wt,{expanded:b})]}),f!==void 0&&o(X,{variant:`outline`,disabled:i||p||R,onClick:()=>f({name:h.trim(),recipe:_}),"data-testid":`automation-save-as-template`,children:m(`build.templates.saveAsTemplate`,`Save as template`)}),o(X,{variant:`ghost`,onClick:d,disabled:i,children:m(`common.close`,`Close`)}),L&&o(J,{variant:`warning`,children:m(`automation.automationEditor.nameRequired`,`Name required`)})]}),b&&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(Ln,{i18nKey:`common.logsOf`,values:{id:se(t.id)},components:{code:o(`code`,{})}})}),o(pn,{addonId:se(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}),o(`div`,{className:`order-first lg:order-last`,children:o(ci,{traces:t===null?[]:T.data?.traces,selectedId:C,onSelect:w})})]})}function Nl(e){let t=ae.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Z.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Pl(e,t){let n=kl(t);if(!n.ok)return{code:null,error:n.error};try{return{code:Qe({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Fl(e){if(!e.enabled)return{tone:`idle`,label:Z.t(`helpers.coreBlockStatus.disabled`),detail:Z.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Z.t(`helpers.coreBlockStatus.running`),detail:Z.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Z.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Z.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Z.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Il(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Ll(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Rl(e){let t=e=>{let t=Fl(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 zl(e){if(e.length===0)return Z.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Fl(e).tone===`error`).length,n=e.filter(e=>Fl(e).tone===`ok`).length,r=[Z.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Z.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Z.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var Bl=3e4;function Vl({block:t,logsOpen:n,unreadable:r,flagged:i=!1}){let a=E(),{t:s}=Q(),c=Fl(t),l=zt(t.updatedAt,a);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(J,{variant:Il(c.tone),children:c.label}),i&&o(J,{variant:`warning`,"data-testid":`automation-flagged-badge`,children:s(`build.templates.flagged`,`Flagged`)}),l!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`common.edited`,{when:l})})]}),(c.tone===`error`||c.tone===`pending`)&&o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:c.detail}),r!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:s(`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(Ln,{i18nKey:`common.logsOf`,values:{id:se(t.id)},components:{code:o(`code`,{})}})}),o(pn,{addonId:se(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var Hl=2;function Ul(e){let t=[];if(be(e.when,e=>{fe(e)&&t.push(Pi(e.kind))}),t.length===0)return _e(e.when)===0?``:Z.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,Hl).join(`, `),i=n.length-Hl;return i>0?`${r} +${i}`:r}function Wl({recipe:e}){let{t}=Q();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=Ul(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function Gl({blockId:t}){let{t:n}=Q(),r=bt({blockId:t},{refetchInterval:Bl});if(r.data===void 0)return r.error===null||r.error===void 0?o(ct,{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:[qn(i.lastAt),a&&o(J,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function Kl({block:e,disabled:t,onToggle:n}){let{t:r}=Q();return o(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(Jt,{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 ql({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=Q();return o(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(rn,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:A,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:R,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:V,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:g,danger:!0,separatorBefore:!0,onClick:r}]})})}function Jl({onCreate:t}){let{t:n}=Q();return o(dt,{icon:w,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(X,{onClick:t,"data-testid":`automation-empty-new`,children:[o(P,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();function Yl({open:t,onBlank:n,onTemplate:r,onClose:i}){let{t:a}=Q(),c=vn({kind:`automation`},{enabled:t}),l=c.data!==void 0&&c.data.length===0;return s(()=>{t&&l&&n()},[t,l,n]),o(wn,{open:t&&!l,onOpenChange:e=>!e&&i(),children:e(_t,{width:`md`,placement:`sheet-on-mobile`,children:[o(hn,{children:o(lt,{children:a(`build.templates.newAutomationTitle`,`New automation`)})}),e(Bt,{className:`space-y-2`,"data-testid":`new-automation-chooser`,children:[o(X,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:n,"data-testid":`new-automation-blank`,children:e(`span`,{className:`block`,children:[o(`span`,{className:`block font-medium`,children:a(`build.templates.blank`,`Blank`)}),o(`span`,{className:`block text-xs text-foreground-muted`,children:a(`build.templates.blankHint`,`Start from an empty trigger and steps.`)})]})}),c.data===void 0?o(ct,{className:`h-10 w-full`}):c.data.map(t=>o(X,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>r(t.id),"data-testid":`new-automation-template-${t.id}`,children:e(`span`,{className:`block`,children:[o(`span`,{className:`block font-medium`,children:t.name}),o(`span`,{className:`block text-xs text-foreground-muted`,children:H.safeParse(t.payload).data?.description??a(`build.templates.fromTemplateHint`,`From a template — only its inputs to fill in.`)})]})},t.id))]})]})})}u();var Xl=`s`,Zl=60;function Ql(e){return e!==void 0&&e>=Zl&&e%Zl===0?`min`:Xl}function $l({value:e,min:t,max:n,disabled:r=!1,"aria-label":i,onChange:a}){let[s,l]=c(()=>Ql(e));return o(Rt,{quantity:`duration`,storedUnit:Xl,unit:s,value:e,disabled:r,...t===void 0?{}:{min:t},...n===void 0?{}:{max:n},...i===void 0?{}:{"aria-label":i},onChange:e=>{l(e.unit);try{a(Math.round(Cn(e,Xl).value))}catch{a(void 0)}}})}var eu=`hub`;function tu(e){switch(e.kind){case`number`:case`duration`:case`text`:case`select`:case`boolean`:return e.default;default:return}}function nu(e){let t={};for(let n of e.inputs){let e=tu(n);e!==void 0&&(t[n.key]=e)}return t}function ru(e){return{min:e.minRows??(e.optional===!0?0:1),max:e.maxRows??20}}function iu(e){let t={};for(let n of e.inputs){if(n.kind===`group`){t[n.key]=Array.from({length:ru(n).min},()=>nu(n));continue}let e=tu(n);e!==void 0&&(t[n.key]=e)}return t}function au(e,t,n){let{[t]:r,...i}=e;return n===void 0?i:{...i,[t]:n}}function ou(e,t){let n=e;for(let[e,r]of Object.entries(t))n=au(n,e,r);return n}function su(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e)):[]}function cu(e,t,n,r,i){let a=su(e,t).map((e,t)=>{if(t!==n)return e;let{[r]:a,...o}=e;return i===void 0?o:{...o,[r]:i}});return{...e,[t]:a}}function lu(e,t,n,r){let i=e;for(let[e,a]of Object.entries(r))i=cu(i,t,n,e,a);return i}function uu(e,t){let n=su(e,t.key);return n.length>=ru(t).max?e:{...e,[t.key]:[...n,nu(t)]}}function du(e,t,n){let r=su(e,t.key);return r.length<=ru(t).min?e:{...e,[t.key]:r.filter((e,t)=>t!==n)}}function fu(e,t){return e.filter(e=>e.input===t)}function pu(e,t){let n=new Set(t.map(e=>e.key));return e.filter(e=>e.input===void 0||!n.has(e.input.split(`.`)[0]??``))}function mu(e,t,n){let r=kl(t);if(!r.ok)return{ok:!1,problems:[{code:`invalid-recipe`,detail:r.error}]};try{return{ok:!0,recipe:r.recipe,input:{name:e,code:Qe({name:e,recipe:r.recipe}),enabled:n,placement:eu}}}catch(e){return{ok:!1,problems:[{code:`invalid-recipe`,detail:e instanceof Error?e.message:String(e)}]}}}function hu(e,t,n,r,i){let a=xe(e,t,n);return a.ok?mu(r,a.recipe,i):a}function gu(e,t,n){return mu(t,ge(e),n)}function _u(e){return typeof e==`number`?[e]:Array.isArray(e)?e.filter(e=>typeof e==`number`):[]}function vu(e){let t=We.safeParse(e);return t.success?t.data:void 0}function yu(e){let t=je.safeParse(e);return t.success?t.data:void 0}function bu(e){return e.filter(e=>e.kind!==`group`)}function xu(e,t){let n=e.find(e=>e.key===t&&e.kind===`device`);return n!==void 0&&n.kind===`device`?n:void 0}function Su(e,t){if(e.deviceInput===void 0)return;let n=e.deviceInput;if(t.filter(e=>(e.kind===`action`||e.kind===`event`)&&e.deviceInput===n).length!==1)return;let r=xu(t,n);if(r!==void 0&&!(r.filter?.capability!==void 0||r.filter?.role!==void 0))return r}function Cu(e){let t=new Set;for(let n of e){if(n.kind!==`action`)continue;let r=Su(n,e);r!==void 0&&t.add(r.key)}return t}function wu(e,t){if(!(t.kind!==`devices`||t.ids.length===0))return e.multiple===!0?[...t.ids]:t.ids[0]}function Tu(e){if(e.actionId!==``)return{actionId:e.actionId,...e.args===void 0?{}:{args:e.args}}}function Eu({payload:e,values:t,problems:n,disabled:r=!1,onChange:i}){let a=bu(e.inputs),s=Cu(a);return o(`div`,{className:`space-y-4`,"data-testid":`template-inputs-form`,children:e.inputs.map(e=>e.kind===`group`?o(Du,{group:e,values:t,problems:n,disabled:r,onChange:i},e.key):o(ku,{input:e,siblings:a,hidden:s,siblingValues:t,addressPrefix:``,problems:n,disabled:r,onScalar:(e,n)=>i(au(t,e,n)),onPair:e=>i(ou(t,e))},e.key))})}function Du({group:t,values:n,problems:r,disabled:i,onChange:a}){let{t:s}=Q(),c=su(n,t.key),l=ru(t),u=fu(r,t.key),d=Cu(t.inputs);return e(`section`,{className:`space-y-2`,"data-testid":`template-group-${t.key}`,children:[o(`h4`,{className:`text-sm font-medium text-foreground`,children:t.label}),u.map(e=>o(`p`,{role:`alert`,className:`text-xs text-danger`,children:e.detail},e.detail)),c.map((e,s)=>o(Ou,{group:t,values:n,row:e,index:s,rowCount:c.length,minRows:l.min,hidden:d,problems:r,disabled:i,onChange:a},s)),e(X,{size:`sm`,variant:`outline`,disabled:i||c.length>=l.max,onClick:()=>a(uu(n,t)),"data-testid":`template-group-${t.key}-add`,children:[o(P,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),s(`build.templates.addRow`,`Add row`)]})]})}function Ou({group:t,values:n,row:r,index:i,rowCount:a,minRows:s,hidden:c,problems:l,disabled:u,onChange:d}){let{t:f}=Q(),p=`${t.key}.${String(i)}`;return e(`div`,{className:`space-y-3 rounded-md border border-border bg-surface p-3`,"data-testid":`template-group-${t.key}-row`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[o(`span`,{className:`text-xs font-medium text-foreground-muted`,children:f(`build.templates.row`,`Row {{n}}`,{n:i+1})}),o(Dt,{icon:g,size:`sm`,variant:`ghost`,"aria-label":f(`build.templates.removeRow`,`Remove row`),disabled:u||a<=s,onClick:()=>d(du(n,t,i))})]}),o(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:t.inputs.map(e=>o(ku,{input:e,siblings:t.inputs,hidden:c,siblingValues:r,addressPrefix:p,problems:l,disabled:u,className:`sm:col-span-2`,onScalar:(e,r)=>d(cu(n,t.key,i,e,r)),onPair:e=>d(lu(n,t.key,i,e))},e.key))})]})}function ku({input:e,siblings:t,hidden:n,siblingValues:r,addressPrefix:i,problems:a,disabled:s,className:c,onScalar:l,onPair:u}){if(n.has(e.key))return null;let d=i===``?e.key:`${i}.${e.key}`;if(e.kind===`action`){let n=Su(e,t);if(n!==void 0)return o(Au,{action:e,device:n,siblingValues:r,address:d,deviceAddress:i===``?n.key:`${i}.${n.key}`,problems:a,...c===void 0?{}:{className:c},onChange:u})}return o(ju,{input:e,siblings:t,siblingValues:r,address:d,problems:a,disabled:s,onChange:t=>l(e.key,t)})}function Au({action:e,device:t,siblingValues:n,address:r,deviceAddress:i,problems:a,className:s,onChange:c}){let{t:l}=Q(),u=ur(),d=[...fu(a,i),...fu(a,r)],f=d.length===0?void 0:d.map(e=>e.detail).join(` `),p=yu(n[e.key]),m=_u(n[t.key]);return o(K,{label:l(`build.templates.command`,`Command`),required:e.optional!==!0||t.optional!==!0,...e.description===void 0?{}:{description:e.description},...f===void 0?{}:{error:f},className:s===void 0?`min-w-0`:`min-w-0 ${s}`,children:o(`div`,{"data-testid":`template-input-${r}`,children:o(xr,{autoOpen:!1,singleTarget:t.multiple!==!0,devices:u,variables:[],step:{kind:`command`,target:{kind:`devices`,ids:[...m]},actionId:p?.actionId??``,...p?.args===void 0?{}:{args:p.args}},onChange:n=>c({[t.key]:wu(t,n.target),[e.key]:Tu(n)})})})})}function ju({input:e,siblingValues:t,address:n,problems:r,disabled:i,onChange:a}){let s=fu(r,n),c=s.length===0?void 0:s.map(e=>e.detail).join(` `),l=t[e.key];return o(K,{label:e.label,required:e.optional!==!0,...e.description===void 0?{}:{description:e.description},...c===void 0?{}:{error:c},className:`min-w-0`,children:o(Mu,{input:e,value:l,siblingValues:t,address:n,disabled:i,onChange:a})})}function Mu({input:e,value:t,siblingValues:n,address:r,disabled:i,onChange:a}){let{t:s}=Q(),c=ur();switch(e.kind){case`device`:{let n=e.filter?.capability===void 0?{}:{requires:{caps:[e.filter.capability]}},s=e.filter?.role===void 0?{}:{fixedTypes:[e.filter.role]};if(e.multiple===!0)return o(gn,{pick:`device`,multiple:!0,...n,...s,recentKey:`template-input-${e.key}`,testId:`template-input-${r}`,disabled:i,value:_u(t).map(e=>({deviceId:e})),onChange:e=>{let t=e.map(e=>e.deviceId);a(t.length===0?void 0:t)}});let c=_u(t)[0];return o(gn,{pick:`device`,...n,...s,recentKey:`template-input-${e.key}`,testId:`template-input-${r}`,disabled:i,value:c===void 0?null:{deviceId:c},onChange:e=>a(e===null?void 0:e.deviceId)})}case`event`:{let i=_u(n[e.deviceInput])[0];if(i===void 0)return o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`template-input-${r}`,children:s(`build.templates.pickDeviceFirst`,`Pick the device first.`)});let c=vu(t),l={kind:`device-fired`,deviceId:i,...c?.eventIds===void 0?{}:{eventIds:c.eventIds},...c?.sourceIds===void 0?{}:{sourceIds:c.sourceIds},...c?.kinds===void 0?{}:{kinds:c.kinds}};return o(`div`,{className:`flex flex-wrap items-end gap-2`,"data-testid":`template-input-${r}`,children:o(No,{leaf:l,hideDevice:!0,onChange:e=>{let t={...e.eventIds===void 0?{}:{eventIds:e.eventIds},...e.sourceIds===void 0?{}:{sourceIds:e.sourceIds},...e.kinds===void 0?{}:{kinds:e.kinds}};a(We.safeParse(t).success?t:void 0)}})})}case`action`:{let i=e.deviceInput===void 0?[]:_u(n[e.deviceInput]);if(e.deviceInput!==void 0&&i.length===0)return o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`template-input-${r}`,children:s(`build.templates.pickDevicesFirst`,`Pick the devices first.`)});let l=yu(t);return o(`div`,{"data-testid":`template-input-${r}`,children:o(xr,{autoOpen:!1,devices:c,variables:[],step:{kind:`command`,target:{kind:`devices`,ids:[...i]},actionId:l?.actionId??``,...l?.args===void 0?{}:{args:l.args}},onChange:e=>a({actionId:e.actionId,...e.args===void 0?{}:{args:e.args}})})})}case`duration`:return o(`span`,{"data-testid":`template-input-${r}`,children:o($l,{value:typeof t==`number`?t:void 0,disabled:i,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},"aria-label":e.label,onChange:a})});case`number`:return o(Y,{type:`number`,"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`number`?String(t):``,...e.min===void 0?{}:{min:e.min},...e.max===void 0?{}:{max:e.max},onChange:e=>{let t=e.target.value===``?void 0:Number(e.target.value);a(t===void 0||Number.isNaN(t)?void 0:t)}});case`text`:return o(Y,{"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`string`?t:``,...e.maxLength===void 0?{}:{maxLength:e.maxLength},onChange:e=>a(e.target.value===``?void 0:e.target.value)});case`select`:return o(z,{"data-testid":`template-input-${r}`,disabled:i,value:typeof t==`string`?t:``,options:[...e.optional===!0||typeof t!=`string`?[{value:``,label:s(`build.templates.choose`,`Choose…`)}]:[],...e.options.map(e=>({value:e.value,label:e.label}))],onChange:e=>a(e.target.value===``?void 0:e.target.value)});case`boolean`:return o(Jt,{"data-testid":`template-input-${r}`,disabled:i,checked:t===!0,onCheckedChange:e=>a(e),label:e.label})}}u();function Nu({templateId:t,templateName:n,payload:i,existing:a,currentRecipe:s,initialName:l,initialValues:u,storedProblems:d,saving:f,saveError:p,onSave:m,onCancel:h}){let{t:g}=Q(),_=j(),[v,y]=c(l),[b,x]=c(u),[C,w]=c(!1),T=a?.enabled??!0,E=d.length>0,D=r(()=>i===null?null:hu(t,i,b,v.trim(),T),[i,t,b,v,T]),O=C&&D!==null&&!D.ok?D.problems:[],k=v.trim()===``,A=()=>{w(!0),!(D===null||!D.ok||k)&&m(D.input)},M=async()=>{if(s===null||!await _({title:g(`build.templates.convertTitle`,`Convert to a free automation?`),message:g(`build.templates.convertMessage`,`{{name}} keeps running as it is, but stops following the template.`,{name:v.trim()===``?l:v.trim()}),confirmLabel:g(`build.templates.convert`,`Convert to a free automation`)}))return;let e=gu(s,v.trim()===``?l:v.trim(),T);e.ok&&m(e.input)};return e(`div`,{className:`space-y-4`,"data-testid":`template-instance-editor`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-foreground-subtle`,children:[o(`span`,{children:n===null?g(`build.templates.templateGone`,`The template of this automation no longer exists.`):g(`build.templates.fromTemplate`,`From the template {{name}}`,{name:n})}),E&&o(J,{variant:`warning`,"data-testid":`template-flagged-badge`,children:g(`build.templates.flagged`,`Flagged`)})]}),E&&e(`div`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`template-flagged-problems`,children:[o(`p`,{className:`font-medium`,children:g(`build.templates.flaggedExplain`,`The template changed and these values no longer fit. The automation keeps running as it last did.`)}),o(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:d.map(e=>o(`li`,{children:e.detail},`${e.input??``}:${e.detail}`))})]}),e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`automation.automationEditor.name`,`Name`)}),o(Y,{className:`mt-1`,value:v,onChange:e=>y(e.target.value),"data-testid":`template-instance-name`})]}),i!==null&&o(Eu,{payload:i,values:b,problems:O,disabled:f,onChange:x}),i!==null&&pu(O,i.inputs).map(e=>o(`p`,{role:`alert`,className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:e.detail},e.detail)),p!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:p}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i!==null&&e(X,{onClick:A,disabled:f||k,"data-testid":`template-instance-save`,children:[f&&o(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`,`Save`)]}),a!==null&&s!==null&&o(X,{variant:`outline`,onClick:()=>void M(),disabled:f,"data-testid":`template-instance-convert`,children:g(`build.templates.convert`,`Convert to a free automation`)}),o(X,{variant:`ghost`,onClick:h,disabled:f,children:g(`common.close`,`Close`)}),k&&o(J,{variant:`warning`,children:g(`automation.automationEditor.nameRequired`,`Name required`)})]})]})}function Pu({templateId:e,existing:t,recipe:n,saving:r,saveError:i,onSave:a,onCancel:s}){let{t:c}=Q(),l=xn({id:e});if(l.status===`error`)return o(q,{title:c(`build.templates.loadFailed`,`Could not read the template`),message:l.error.message,onRetry:()=>void l.refetch()});if(l.data===void 0)return o(ct,{className:`h-24 w-full`});let u=l.data,d=u===null?null:H.safeParse(u.payload);if(d!==null&&!d.success)return o(q,{title:c(`build.templates.unreadable`,`This template cannot be read`),message:d.error.issues[0]?.message??``});let f=d===null?null:d.data,p=n?.template;return o(Nu,{templateId:e,templateName:u===null?null:u.name,payload:f,existing:t,currentRecipe:n,initialName:t?.name??u?.name??``,initialValues:p?.values??(f===null?{}:iu(f)),storedProblems:p?.problems??[],saving:r,saveError:i,onSave:a,onCancel:s},t?.id??`new:${e}`)}var Fu=`fromTemplate`;u();var Iu=[`coreBlocks`,`list`],Lu=5e3;function Ru(e){return e instanceof Error?e.message:String(e)}function zu({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:u}=Q(),d=k(),{state:f,openNew:m,openEdit:h,close:g}=Yt({editKey:`block`,newKey:`new`}),_=j(),[v,y]=c(null),[b,x]=c(!1),[S,C]=c(null),[T,E]=c(null),[D,O]=Un(),A=Rn(),M=ot(),N=D.get(Fu),P=f.mode!==`closed`;s(()=>{n&&(x(!0),i?.())},[n,i]),s(()=>{N!==null&&(C(N),O(e=>{let t=new URLSearchParams(e);return t.delete(Fu),t},{replace:!0}))},[N,O]);let F=a(()=>{x(!1),m()},[m]),I=l({queryKey:Iu,refetchInterval:Lu,queryFn:async()=>(await d.trpcClient.coreBlocks.list.query({})).blocks}),L=()=>{I.refetch()},R=e=>{g(),C(null),L(),Pn({title:u(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},z=p({mutationFn:e=>d.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>R(e.block)}),B=p({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>R(e.block)}),V=p({mutationFn:e=>d.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:L}),ee=p({mutationFn:e=>d.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:L}),H=p({mutationFn:e=>d.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:Nr(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{g(),L(),t(e.block.id)}}),U=I.data,te=Rl((U??[]).filter(e=>Ar(e.code))),ne=U!==void 0&&te.length===0,W=f.mode===`edit`?te.find(e=>e.id===f.id)??null:null,re=f.mode===`edit`&&U!==void 0&&W===null;s(()=>{re&&g()},[re,g]);let G=W===null?null:Mr(W.code),ie=G!==null&&G.ok?G.recipe.template:void 0,ae=async e=>{let{template:t,...n}=e.recipe,r={version:1,body:n,inputs:[],bindings:[]};E(null);try{let t=await M.mutateAsync({kind:`automation`,name:e.name,payload:r});t.status===`refused`?E(t.detail):A(Wn(t.template.id))}catch(e){E(Ru(e))}},oe=z.error===null?B.error===null?H.error===null?null:Ru(H.error):Ru(B.error):Ru(z.error),se=r(()=>[{key:`name`,header:u(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=Mr(e.code);return o(Vl,{block:e,logsOpen:v===e.id,unreadable:t.ok?null:t.reason,flagged:t.ok&&t.recipe.template?.problems!==void 0})},sortValue:e=>e.name},{key:`trigger`,header:u(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=Mr(e.code);return o(Wl,{recipe:t.ok?t.recipe:null})},notSortableReason:u(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:u(`build.automationsTab.lastRun`,`Last run`),render:e=>o(Gl,{blockId:e.id}),notSortableReason:u(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:u(`build.automationsTab.enabled`,`Enabled`),render:e=>o(Kl,{block:e,disabled:ee.isPending,onToggle:t=>ee.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=Mr(e.code);return o(ql,{unreadable:t.ok?null:t.reason,onEdit:()=>h(e.id),onToggleLogs:()=>y(v===e.id?null:e.id),onDelete:()=>{_({title:u(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:u(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:u(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&V.mutate(e.id)})}})}}],[_,v,h,V,ee,u]),ce=()=>{z.reset(),B.reset(),C(null),g()};return S!==null&&!P?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(w,{className:`h-4 w-4 text-foreground-muted`}),u(`build.automationsTab.newAutomation`,`New automation`)]}),o(Pu,{templateId:S,existing:null,recipe:null,saving:z.isPending,saveError:oe,onSave:e=>z.mutate(e),onCancel:ce})]}):P?f.mode===`edit`&&W===null?o(ct,{className:`h-24 w-full`}):W!==null&&ie!==void 0&&G!==null&&G.ok?e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[o(w,{className:`h-4 w-4 text-foreground-muted`}),u(`build.automationsTab.edit`,`Edit {{name}}`,{name:W.name})]}),o(Pu,{templateId:ie.templateId,existing:W,recipe:G.recipe,saving:B.isPending,saveError:oe,onSave:e=>B.mutate({blockId:W.id,block:e}),onCancel:ce})]}):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(w,{className:`h-4 w-4 text-foreground-muted`}),W===null?u(`build.automationsTab.newAutomation`,`New automation`):u(`build.automationsTab.edit`,`Edit {{name}}`,{name:W.name})]}),o(Ml,{existing:W,initialRecipe:G!==null&&G.ok?G.recipe:Li,saving:z.isPending||B.isPending,saveError:oe,ejecting:H.isPending,onSave:e=>{W===null?z.mutate(e):B.mutate({blockId:W.id,block:e})},onEject:()=>{W!==null&&H.mutate(W)},onSaveAsTemplate:e=>void ae(e),savingAsTemplate:M.isPending,onCancel:()=>{z.reset(),B.reset(),H.reset(),g()}},W?.id??`new`),V.error!=null&&o(q,{message:Ru(V.error)}),T!==null&&o(q,{message:T})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:U===void 0?``:zl(te)}),I.error!=null&&o(q,{title:u(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Ru(I.error),onRetry:L}),ne?o(Jl,{onCreate:()=>x(!0)}):o(Vt,{columns:se,rows:te,rowKey:e=>e.id,pageSize:25,maxBodyHeight:vt,emptyMessage:U===void 0?u(`build.automationsTab.loadingAutomations`,`Loading automations…`):u(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>h(e.id)}),V.error!=null&&o(q,{message:Ru(V.error)}),ee.error!=null&&o(q,{message:Ru(ee.error)}),o(Yl,{open:b,onBlank:F,onTemplate:e=>{x(!1),C(e)},onClose:()=>x(!1)})]})}var Bu={kind:`all`,children:[]};function Vu({value:t,devices:n,label:r,onChange:i}){let{t:a}=Q(),s=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[o(Jt,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?Bu: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(hc,{recipe:s,devices:n,onChange:e=>i(e.when)})]})]})}var Hu=[`sunrise`,`sunset`,`dawn`,`dusk`],Uu=6e4;function Wu(e){return e.kind===`command`||e.kind===`wait`}function Gu(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 Ku({point:t,devices:n,site:r,localDate:i,issues:a,onChange:s,onRemove:c}){let{t:l}=Q(),u=t.at,d=u.kind===`sun`?_s(u,r,i):null,f=vs(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(z,{"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(Gu(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.when`,`When`)}),o(z,{"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(Y,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:xs(u.hh,u.mm),onChange:e=>{let t=bs(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(z,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:Hu.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Hu.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(hr,{"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:Ss(d),zone:r.timeZone})})]}),e(X,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[o(g,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&o(Gc,{actions:t.steps,devices:n,allowedKinds:[`command`,`wait`],onChange:e=>s({...t,steps:e.filter(Wu)})}),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(z,{"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*Uu}:{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(hr,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:p.graceMs/Uu,onValue:e=>{e!==null&&s({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*Uu))}})}})]})]}),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 qu=5e3,Ju=600,Yu=6e4,Xu={timeZone:`UTC`,location:null};function Zu(e){return e instanceof Error?e.message:String(e)}function Qu(e){if(e===null)return us();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function $u(e,t){let[n,r]=c(e);return s(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function ed(e,t){return t(`schedulers.day.${e}`,e)}function td({entry:t,onClose:n,onSaved:i}){let{t:a}=Q(),s=f(),l=j(),u=ur(),d=qt(),p=d.data??Xu,[m,h]=c(()=>Qu(t)),[_,v]=c(()=>m.profiles[0]?.id??``),[y,b]=c(null),[x,C]=c(null),w=()=>{s.invalidateQueries({queryKey:[[`schedulers`]]})},T=dn({onSuccess:e=>{w(),i(e.scheduler.id)}}),E=On({onSuccess:w}),D=ln({onSuccess:()=>{w(),n()}}),O=Sn({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:qu}),k=r(()=>ws(m,p),[m,p]),A=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),M=$u(k.ok?k.input:null,Ju),N=_n(M===null?{scheduler:m}:t===null?{scheduler:M}:{scheduler:M,schedulerId:t.id},{enabled:M!==null&&A&&d.data!==void 0}),I=m.profiles.find(e=>e.id===_)??m.profiles[0],L=I===void 0?-1:m.profiles.indexOf(I),R=gs(p),z=I?.points.find(e=>e.id===y)??null,B=I===void 0||z===null?-1:I.points.indexOf(z),V=k.ok?[]:k.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)}),U=e=>{I!==void 0&&H({...I,points:I.points.map(t=>t.id===e.id?e:t)})},te=r(()=>I===void 0?[]:I.points.flatMap(e=>{let t=_s(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)} (${Ss(t)})`:xs(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`&&vs(e.at,p,R)!==null}]}),[I,p,R,a]),ne=r(()=>I===void 0?[]:Cs(I.points,p,R),[I,p,R]),W=(e,t)=>{let n=I?.points.find(t=>t.id===e);n!==void 0&&U({...n,at:ys(n.at,t,vs(n.at,p,R))})},re=e=>{if(I===void 0)return;let t=ps(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));H({...I,points:[...I.points,fs(e,t,720)]}),b(t)},G=()=>{let e=ps(`profile`,m.profiles.map(e=>e.id));h({...m,profiles:[...m.profiles,ds(e,a(`schedulers.profile.newName`,`New profile`))]}),v(e),b(null)},ie=T.isPending||E.isPending,ae=T.error??E.error??D.error;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`scheduler-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(F,{className:`h-4 w-4 text-foreground-muted`}),o(Y,{"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(mt,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[o(Tn,{label:a(`schedulers.editor.enabled`,`Enabled`),children:o(Jt,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>h({...m,enabled:e})})}),o(Tn,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:o(hr,{"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(Tn,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:o(hr,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/Yu,onValue:e=>{e!==null&&h({...m,maxLateMs:Math.round(e*Yu)})}})})]}),e(`div`,{className:`p-3`,children:[o(Vu,{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(mt,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(X,{variant:`outline`,size:`sm`,onClick:G,children:[o(P,{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(Wt,{value:I.id,onValueChange:e=>{v(e),b(null)},appearance:`pills`,children:[o(Ht,{children:m.profiles.map(e=>o(Gt,{value:e.id,children:e.name},e.id))}),e(Tt,{value:I.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(Y,{"aria-label":a(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:I.name,onChange:e=>H({...I,name:e.target.value})}),o(Jt,{checked:I.enabled,label:a(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>H({...I,enabled:e})}),m.profiles.length>1&&e(X,{variant:`ghost`,size:`sm`,onClick:()=>{h({...m,profiles:m.profiles.filter(e=>e.id!==I.id)}),v(``),b(null)},children:[o(g,{className:`h-4 w-4`}),` `,a(`schedulers.profile.remove`,`Remove profile`)]})]}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":a(`schedulers.profile.days`,`Days`),children:ss.map(e=>{let t=I.days.includes(e);return o(X,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>H({...I,days:t?I.days.filter(t=>t!==e):ss.filter(t=>t===e||I.days.includes(t))}),children:ed(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(Vu,{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(En,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:te,bands:ne,selectedId:y,onSelect:b,onMove:W}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:`outline`,size:`sm`,onClick:()=>re(`edge`),children:[o(P,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(X,{variant:`outline`,size:`sm`,onClick:()=>re(`hold`),children:[o(P,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(X,{variant:`outline`,size:`sm`,onClick:()=>re(`release`),children:[o(P,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),o(J,{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(Ku,{point:z,devices:u,site:p,localDate:R,issues:ee(`profiles.${String(L)}.points.${String(B)}`),onChange:U,onRemove:()=>{H({...I,points:I.points.filter(e=>e.id!==z.id)}),b(null)}},z.id)]})]})]})}),N.data!==void 0&&N.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:N.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:Ss(e.fromMinute),to:Ss(e.toMinute),winner:e.winner===`mine`?a(`schedulers.conflict.mine`,`this one wins`):e.winner===`other`?a(`schedulers.conflict.other`,`the other one wins`):a(`schedulers.conflict.tie`,`the one that started first wins`)})},`${e.other.schedulerId}:${e.other.pointId}:${e.mine.pointId}:${String(e.deviceId)}`))}),!k.ok&&m.name!==``&&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}`))}),ae!==null&&o(q,{message:Zu(ae)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(X,{onClick:()=>{k.ok&&(t===null?T.mutate({scheduler:k.input}):E.mutate({schedulerId:t.id,scheduler:k.input}))},disabled:ie||!k.ok||d.data===void 0,children:[ie&&o(S,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(X,{variant:`ghost`,disabled:D.isPending,onClick:()=>{l({title:a(`schedulers.editor.deleteTitle`,`Delete this scheduler?`),message:a(`schedulers.editor.deleteMessage`,`{{name}} will be deleted and any hold it keeps will stop.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&D.mutate({schedulerId:t.id})})},children:[o(g,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(X,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(ci,{traces:t===null?[]:O.data?.traces,selectedId:x,onSelect:C})})]})}u();var nd=5e3;function rd(e){return e instanceof Error?e.message:String(e)}function id({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),a=f(),{state:c,openNew:l,openEdit:u,close:d}=Yt({editKey:`scheduler`,newKey:`new`}),p=jn({},{refetchInterval:nd}),m=$t({},{refetchInterval:nd}),h=nn({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(Jt,{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(J,{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=>qn(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(q,{message:rd(h.error)}),p.data===void 0?p.error==null?o(ct,{className:`h-24 w-full`}):o(q,{title:i(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:rd(p.error),onRetry:()=>void p.refetch()}):g.length===0?o(dt,{icon:F,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(X,{onClick:l,children:[o(P,{className:`h-4 w-4`}),` `,i(`schedulers.list.new`,`New scheduler`)]})}):o(Vt,{columns:y,rows:g,rowKey:e=>e.id,pageSize:25,maxBodyHeight:vt,emptyMessage:i(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):o(td,{entry:_,onClose:d,onSaved:u},_?.id??`new`)}async function ad(e,t){let n=`${De}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var od=10,sd=400;async function cd(e,t,n=sd){for(let r=0;r<od;r+=1){let r=await ad(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var ld=`media-player`;function ud(e){return e===G.MediaPlayer?`media-source`:`none`}function dd(e){return e===G.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[G.MediaPlayer],accept:[{cap:ld,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[ld],exclude:[]}:null}function fd(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:ld,fields:{},commands:Object.fromEntries(Object.keys(Fe()).map(t=>[t,{kind:`forward`,source:e.source,cap:ld,method:t}]))}]}function pd(e,t){let n=e===G.MediaPlayer?fd(t):[];return{target:{kind:`new`,type:e},features:n}}u();function md({onTitle:t}){let{t:n}=Q(),r=E(),i=Rn(),a=lr(),l=Kt(),u=Ft({addonId:`composer`}),[d,f]=c(G.Sensor),[p,m]=c(``),[h,g]=c([]),[_,v]=c(null),y=h[0]??null,b=dd(d),x=pd(d,y);s(()=>{t(n(`helper.newDevice`))},[t,n]);let S=async()=>{v(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:x}}),r=await cd(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(Bn(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(z,{value:d,onChange:e=>{let t=Object.values(G).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(G).map(e=>({value:e,label:fn(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(Y,{"aria-label":n(`compositionEditor.name`),value:p,onChange:e=>m(e.target.value)})]})]}),b!==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.${ud(d)}`)}),o(Qn,{kind:`members`,request:b,enabled:!0,members:h,onMembersChange:g,onRefuse:()=>void 0})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(X,{disabled:a.isPending,onClick:()=>void S(),children:n(`compositionEditor.save`)})]})}u();function hd({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=Q(),u=rr(!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=>[U({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[U(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:Jn(u.value,S)}:u,[u,S]),w=ar(t,d),T=u.kind===`known`?or(u.value,w,!1):null,E=t.build(d),D=tr(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(U(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(Y,{"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:[sr(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(X,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(X,{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:sr(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(ir,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(X,{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(X,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o($n,{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 gd=`preset`;function _d({mode:e,onTitle:t}){return o(e===`helper`?vd:md,{onTitle:t})}function vd({onTitle:e}){let{t}=Q(),r=Rn(),i=lr(),a=Kt(),l=Ft({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=Un(),g=Zn(m.get(gd)),_=g===null?yd(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(gd):n.set(gd,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 cd(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:er(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(Bn(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:er(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(md,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(nr,{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 cr(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 cd(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(zn(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:bd(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(hd,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function yd(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=Je(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function bd(e,t){return e.length>0?e:er(t(`helper.devicePending`))}function xd(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 Sd(e){return{state:`answered`,byRef:new Map(e.map(e=>[U(e),e]))}}function Cd(e,t){if(e.state!==`unanswered`)return e.byRef.get(U(t))??null}function wd(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Td(e){return le(e).map(e=>e.source)}function Ed(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(...Td(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Td(e))}let r=new Set;return n.filter(e=>{let t=U(e);return r.has(t)?!1:(r.add(t),!0)})}function Dd(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:Z.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Z.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Z.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Z.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Z.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function Od(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Dd(e);case`degraded`:return{tone:`pending`,label:Z.t(`helpers.compositionRows.degraded`),reason:n??Z.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Z.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Z.t(`helpers.compositionRows.failed`),reason:n??Z.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Z.t(`helpers.compositionRows.notRunning`),reason:n??Z.t(`helpers.compositionRows.notRunningReason`)}}}function kd(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Z.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Z.t(`helpers.compositionRows.unknown`),reason:Z.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return Od(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Z.t(`helpers.compositionRows.notReported`),reason:Z.t(`helpers.compositionRows.noRecord`,{stored:r})}}function Ad(e){return U(e)}function jd(e,t){let n=Cd(t,e);return{key:U(e),label:n?n.name:Ad(e),presence:wd(n),deviceId:n?n.id:null}}function Md(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Nd(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:de(e.block.id),a=U(i),o=Ed(e).filter(e=>U(e)!==a).map(e=>jd(e,t)),s=n.features.map(e=>e.enabled===!1?Z.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Cd(t,i),l=Md(e),u=kd(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:xd(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=wd(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Ad(r.device),namePresence:d,type:c?c.type:null,origin:xd(n),features:s,state:u,sources:o,reportedDeviceId:l}}function Pd(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Fd(e,t){return Pd(e)-Pd(t)||e.name.localeCompare(t.name)}function Id(e,t){let n=e.flatMap(e=>{let n=Nd(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Fd),customizations:n.filter(e=>e.kind===`customization`).toSorted(Fd)}}u();var Ld=1e4;function Rd(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function zd(){let e=Fn();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Z.t(`build.customDeviceTab.deviceListPending`):Z.t(`build.customDeviceTab.deviceListUnreadable`,{error:Rd(e.error)})}:Sd(e.data)}function Bd(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Vd({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Q(),[i,a]=Un(),s=At({},{refetchInterval:Ld}),l=zd(),u=Yt({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?Bd(i.get(`new`),t):null,p=f!==null,[h,g]=c(``),_=j(),v=ut(),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:[Ud(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(It,{open:p,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:M,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(_d,{mode:f,onTitle:g},f)}),o(gr,{blockId:d,onClose:y}),v.error!=null&&o(q,{message:Rd(v.error)})]})}function Hd(t){return o(yt,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Z.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Z.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Ud(e,t,n,r,i){if(t!=null&&e===void 0)return o(q,{title:Z.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Rd(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Z.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return Hd(e.reason);let a=t==null?null:Rd(t);return o(Wd,{lists:Id(e.views,r),fleet:r,refreshError:a,handlers:i})}function Wd({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Q();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(Gd,{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(Gd,{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 Gd({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=Q();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(Vt,{columns:Kd(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:vt,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Kd(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(Jd,{row:e})},{key:`type`,header:Z.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Z.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:Z.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>qd(e.origin,i),render:e=>o(J,{variant:`default`,"data-testid":`composed-origin-badge`,children:qd(e.origin,i)})}]:[],{key:`state`,header:Z.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(J,{variant:Il(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:Z.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(Xd,{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(X,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(X,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:o(g,{className:`h-4 w-4`})})]})}),a}function qd(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 Jd({row:t}){let{t:n}=Q();return e(`div`,{className:`space-y-0.5`,children:[o(Yd,{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 Yd({row:e}){let{t}=Q(),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(Hn,{to:e.kind===`composed`?zn(e.reportedDeviceId):Bn(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Xd({sources:t}){let{t:n}=Q();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(Hn,{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 Zd(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 Qd(e){if(Array.isArray(e))return e}function $d(e,t,n){return(t=lf(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ef(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 tf(){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 nf(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 rf(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?nf(Object(n),!0).forEach(function(t){$d(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):nf(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function af(e,t){if(e==null)return{};var n,r,i=of(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 of(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 sf(e,t){return Qd(e)||ef(e,t)||uf(e,t)||tf()}function cf(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 lf(e){var t=cf(e,`string`);return typeof t==`symbol`?t:t+``}function uf(e,t){if(e){if(typeof e==`string`)return Zd(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)?Zd(e,t):void 0}}function df(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ff(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 pf(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ff(Object(n),!0).forEach(function(t){df(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ff(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function mf(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function hf(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 gf(e){return{}.toString.call(e).includes(`Object`)}function _f(e){return!Object.keys(e).length}function vf(e){return typeof e==`function`}function yf(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function bf(e,t){return gf(t)||Tf(`changeType`),Object.keys(t).some(function(t){return!yf(e,t)})&&Tf(`changeField`),t}function xf(e){vf(e)||Tf(`selectorType`)}function Sf(e){vf(e)||gf(e)||Tf(`handlerType`),gf(e)&&Object.values(e).some(function(e){return!vf(e)})&&Tf(`handlersType`)}function Cf(e){e||Tf(`initialIsRequired`),gf(e)||Tf(`initialType`),_f(e)&&Tf(`initialContent`)}function wf(e,t){throw Error(e[t]||e.default)}var Tf=hf(wf)({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"}),Ef={changes:bf,selector:xf,handler:Sf,initial:Cf};function Df(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ef.initial(e),Ef.handler(t);var n={current:e},r=hf(Af)(n,t),i=hf(kf)(n),a=hf(Ef.changes)(e),o=hf(Of)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Ef.selector(e),e(n.current)}function c(e){mf(r,i,a,o)(e)}return[s,c]}function Of(e,t){return vf(t)?t(e.current):t}function kf(e,t){return e.current=pf(pf({},e.current),t),t}function Af(e,t,n){return vf(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var jf={create:Df},Mf={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Nf(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 Pf(e){return{}.toString.call(e).includes(`Object`)}function Ff(e){return e||zf(`configIsRequired`),Pf(e)||zf(`configType`),e.urls?(If(),{paths:{vs:e.urls.monacoBase}}):e}function If(){console.warn(Rf.deprecation)}function Lf(e,t){throw Error(e[t]||e.default)}var Rf={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
6
|
You are using deprecated way of configuration.
|
|
7
7
|
|
|
8
8
|
Instead of using
|
|
@@ -11,7 +11,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
11
11
|
monaco.config({ paths: { vs: '...' } })
|
|
12
12
|
|
|
13
13
|
For more please check the link https://github.com/suren-atoyan/monaco-loader#config
|
|
14
|
-
`},
|
|
14
|
+
`},zf=Nf(Lf)(Rf),Bf={config:Ff},Vf=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Hf(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Hf(e[n],t[n]))}),rf(rf({},e),t)}var Uf={type:`cancelation`,msg:`operation is manually canceled`};function Wf(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Uf):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var Gf=[`monaco`],Kf=sf(jf.create({config:Mf,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),qf=Kf[0],Jf=Kf[1];function Yf(e){var t=Bf.config(e),n=t.monaco,r=af(t,Gf);Jf(function(e){return{config:Hf(e.config,r),monaco:n}})}function Xf(){var e=qf(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(Jf({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Wf(rp);if(window.monaco&&window.monaco.editor)return tp(window.monaco),e.resolve(window.monaco),Wf(rp);Vf(Zf,$f)(ep)}return Wf(rp)}function Zf(e){return document.body.appendChild(e)}function Qf(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function $f(e){var t=qf(function(e){return{config:e.config,reject:e.reject}}),n=Qf(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function ep(){var e=qf(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;tp(n),e.resolve(n)},function(t){e.reject(t)})}function tp(e){qf().monaco||Jf({monaco:e})}function np(){return qf(function(e){return e.monaco})}var rp=new Promise(function(e,t){return Jf({resolve:e,reject:t})}),ip={config:Yf,init:Xf,__getMonacoInstance:np};u();var ap={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},op={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function sp({children:e}){return t.createElement(`div`,{style:op.container},e)}var cp=sp;function lp({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...ap.wrapper,width:e,height:n},...s},!r&&t.createElement(cp,null,i),t.createElement(`div`,{ref:a,style:{...ap.fullWidth,...!r&&ap.hide},className:o}))}var up=i(lp);function dp(e){s(e,[])}var fp=dp;function pp(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var mp=pp;function hp(){}function gp(e,t,n,r){return _p(e,r)||vp(e,t,n,r)}function _p(e,t){return e.editor.getModel(yp(e,t))}function vp(e,t,n,r){return e.editor.createModel(t,n,r?yp(e,r):void 0)}function yp(e,t){return e.Uri.parse(t)}function bp({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=hp,onMount:S=hp}){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);fp(()=>{let e=ip.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()}),mp(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=gp(O.current,e||``,o||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),mp(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=gp(O.current,r||``,l||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),mp(()=>{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),mp(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),mp(()=>{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),mp(()=>{O.current?.editor.setTheme(m)},[m],C),mp(()=>{D.current?.updateOptions(g)},[g],C);let N=a(()=>{if(!O.current)return;j.current(O.current);let t=gp(O.current,e||``,o||i||`text`,u||``),n=gp(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(up,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(bp);function xp(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var Sp=xp,Cp=new Map;function wp({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=hp,onMount:C=hp,onChange:w,onValidate:T=hp}){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=Sp(u),R=n(!1),z=n(!1);fp(()=>{let e=ip.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()}),mp(()=>{let t=gp(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&Cp.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(Cp.get(u)))},[u],E),mp(()=>{j.current?.updateOptions(m)},[m],E),mp(()=>{!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),mp(()=>{let e=j.current?.getModel();e&&l&&A.current?.editor.setModelLanguage(e,l)},[l],E),mp(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),mp(()=>{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=gp(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(Cp.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&&Cp.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(up,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var Tp=i(wp);u();function Ep(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 Dp={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Op(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Dp}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function kp({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,Op(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&&Op(e,r)},[r]),o(Tp,{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 Ap(e){return e.some(e=>e.severity>=8)}var jp=[{id:`blank`,name:`Blank script`,get description(){return Z.t(`helpers.buildExamples.blankDescription`)},entry:`main.ts`,files:{"main.ts":`import type { AddonContext } from '@camstack/types'
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* A core block. Runs in its own process, with the same \`ctx\` an addon gets.
|
|
@@ -31,12 +31,12 @@ export default function block(ctx: AddonContext) {
|
|
|
31
31
|
clearInterval(timer)
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
|
-
`}}];function
|
|
34
|
+
`}}];function Mp(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 Np=jp.find(e=>e.id===`blank`)?.files[`main.ts`]??`import type { AddonContext } from '@camstack/types'
|
|
35
35
|
|
|
36
36
|
export default function block(ctx: AddonContext) {
|
|
37
37
|
ctx.logger.info('hello from a core block')
|
|
38
38
|
return () => undefined
|
|
39
39
|
}
|
|
40
|
-
`;function Cp({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Z.t(`helpers.restartGate.saveFirstNoProcess`):n?Z.t(`helpers.restartGate.saving`):r?Z.t(`helpers.restartGate.restarting`):t?Z.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Z.t(`helpers.restartGate.disabled`)}u();var wp=5e3;function Tp(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 Ep({blockId:t}){let{t:n}=Q(),i=se(t),a=kn({addonId:i,projection:`slim`},{refetchInterval:wp}),s=r(()=>Tp(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(S,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Ln,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(J,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Ln,{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(Hn,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(xt,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(J,{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 Dp(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 Op(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 kp(e){switch(e){case`refresh-channel-catalog`:return Z.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Z.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Z.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Z.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Z.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Z.t(`build.scriptSettingsPanel.enableUnifi`)}}function Ap(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function jp(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Mp(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Ap(e);n!==null&&(t[n]=jp(e))}return t}function Np(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Pp({blockId:t}){let{t:n}=Q(),i=k(),s=mn({blockId:t},{retry:!1}),l=Mt({blockId:t},{refetchInterval:1e4,retry:!1}),u=Ut({onSuccess:()=>{l.refetch()}}),d=Nn(),f=ft(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=Np(l.data)?l.data:null,C=r(()=>x===null?{}:Mp(x),[x]),w=p??C,T=a(e=>{m(e)},[]),E=p!==null,D=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),O=a(async(e,n)=>{if(Dp(e)){b(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:Op(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(kp(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{b(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(S,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):x===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Ln,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(X,{size:`sm`,variant:`primary`,onClick:D,disabled:!E||u.isPending||y,children:[u.isPending&&o(S,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(Vn,{schema:x,values:w,onChange:T,onAction:O}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var Fp=`hub`;function Ip({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:f,onCancel:h}){let{t:g}=Q(),_=k(),b=j(),{resolvedMode:x}=yn(),C=pe({code:t?.code??Sp,files:t?.files,entry:t?.entry}),[w,T]=c(t?.name??``),[E,O]=c(C.files),[A,M]=c(C.entry),[N,P]=c(C.entry),[F,I]=c(t?.placement??Fp),[L,R]=c(t?.integrationId??``),[B,ee]=c([]),[H,U]=c(!1),[te,ne]=c(`blank`),[W,re]=c(null),[G,ie]=c(``),ae=E[N]??``,oe=e=>{O(t=>({...t,[N]:e}))},ce=Object.keys(E).toSorted(),le=bp.length>1,ue=r(()=>[...n?.libs??[],...hp(E,N)],[n?.libs,E,N]),de=p({mutationFn:()=>_.trpcClient.coreBlocks.compile.mutate({files:E,entry:A})}),fe=r(()=>B.filter(e=>e.severity>=8),[B]),me=yp(B),he=w.trim()===``,ge=t===null?null:pe(t),_e=t===null||ge===null||JSON.stringify(E)!==JSON.stringify(ge.files)||A!==ge.entry||w.trim()!==t.name||F!==t.placement||(L.trim()===``?void 0:L.trim())!==t.integrationId,ve=()=>{de.reset(),f({name:w.trim(),files:E,entry:A,enabled:t?.enabled??!0,placement:F,...L.trim()===``?{}:{integrationId:L.trim()}})},ye=()=>{let e=xp(Object.keys(E));O(t=>({...t,[e]:``})),P(e),re(e),ie(e)},be=e=>{re(e),ie(e)},xe=()=>{if(W===null)return;let e=W,t=G.trim();if(re(null),!(t===``||t===e)){if(E[t]!==void 0){P(t);return}O(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),A===e&&M(t),P(t)}},Se=async e=>{let t=bp.find(t=>t.id===e);if(t===void 0)return;let n=bp.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(E)===JSON.stringify(n.files)&&A===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`})||(ne(e),O({...t.files}),M(t.entry),P(t.entry),(w.trim()===``||te===`blank`)&&T(t.id===`blank`?``:t.name))},Ce=t===null?null:Fl(t),we=Cp({existing:t,dirty:_e,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[Ce!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(J,{variant:Il(Ce.tone),children:Ce.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(Y,{className:`mt-1`,value:w,onChange:e=>T(e.target.value),placeholder:g(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(Y,{className:`mt-1`,value:L,onChange:e=>R(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&le&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),o(z,{className:`mt-1 w-full`,value:te,onChange:e=>void Se(e.target.value),"data-testid":`script-example-select`,children:bp.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(bn,{selectedNodeId:F,onSelect:I,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),F!==Fp&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(D,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(Ln,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[ce.map(t=>W===t?o(Y,{value:G,onChange:e=>ie(e.target.value),onBlur:()=>xe(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),xe()),e.key===`Escape`&&(e.preventDefault(),re(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(X,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs ${t===N?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>P(t),onDoubleClick:()=>be(t),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===A?` · ${g(`build.blockEditor.entry`)}`:``]},t)),o(X,{variant:`unstyled`,type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:ye,"data-testid":`script-file-add`,children:g(`build.blockEditor.file`,`+ file`)}),N!==A&&o(X,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>M(N),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(vp,{value:ae,onChange:oe,path:`file:///${N}`,extraLibs:ue,onDiagnostics:ee,dark:x===`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.`)}),fe.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:fe.length})}),fe.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}`)),fe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:fe.length-5})})]}),de.data!==void 0&&(de.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(y,{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:[de.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(de.data.line)})}),de.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),de.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:`),` `,Lp(de.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(Pp,{blockId:t.id}),o(Ep,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:`outline`,onClick:()=>de.mutate(),disabled:de.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[de.isPending&&o(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(X,{onClick:ve,disabled:a||me||he,children:[a&&o(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(X,{variant:`outline`,onClick:()=>d?.(),disabled:we!==null||d===void 0,title:we??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(v,{className:`h-4 w-4 animate-spin`}):o(v,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),e(X,{variant:`ghost`,onClick:()=>U(!H),title:g(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,"aria-expanded":H,children:[o(V,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,o(wt,{expanded:H})]}),o(X,{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:fe.length}),_e&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),he&&o(J,{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(Ln,{i18nKey:`build.blockEditor.logsOf`,values:{id:se(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(pn,{addonId:se(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Lp(e){return e instanceof Error?e.message:String(e)}u();var Rp=[`coreBlocks`,`list`],zp=[`coreBlocks`,`getTypeDefs`],Bp=5e3;function Vp(e){return e instanceof Error?e.message:String(e)}function Hp({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=E(),{t:f}=Q(),m=k(),{state:h,openNew:_,openEdit:y,close:b}=Yt({editKey:`block`,newKey:`new`}),[x,S]=c(null),C=j(),[w,T]=c(null),D=l({queryKey:Rp,refetchInterval:Bp,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),O=h.mode!==`closed`,A=l({queryKey:zp,enabled:O,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),M=()=>{D.refetch()},N=n(null),P=D.data;s(()=>{t===void 0||N.current===t||P?.find(e=>e.id===t&&Ke(e)===`code`)!==void 0&&(N.current=t,y(t),i?.(t))},[t,P,y,i]),s(()=>{a&&(S(null),_(),i?.(null),u?.())},[a,u,i,_]);let F=p({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{S(e.block),y(e.block.id),i?.(e.block.id),M()}}),I=p({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{S(e.block),y(e.block.id),i?.(e.block.id),M()}}),L=p({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:M}),R=p({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:M}),z=p({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:M}),B=Rl((D.data??[]).filter(e=>Ke(e)===`code`)),ee=D.data!==void 0&&B.length===0,H=F.isPending||I.isPending,U=F.error===null?I.error===null?null:Vp(I.error):Vp(F.error),te=h.mode===`edit`?B.find(e=>e.id===h.id)??(x!==null&&x.id===h.id?x:null):null,ne=h.mode===`new`||te===null?null:Ll(B,te),W=r(()=>[{key:`name`,header:f(`build.scriptsTab.name`,`Name`),render:t=>{let n=Fl(t),r=zt(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(J,{variant:Il(n.tone),children:n.label}),o(J,{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(Ln,{i18nKey:`common.logsOf`,values:{id:se(t.id)},components:{code:o(`code`,{})}})}),o(pn,{addonId:se(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=R.isPending||L.isPending,r=z.isPending&&z.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[o(X,{variant:`ghost`,onClick:e=>{e.stopPropagation(),S(t),y(t.id),i?.(t.id)},title:f(`common.edit`,`Edit`),children:f(`common.edit`,`Edit`)}),o(X,{variant:`ghost`,onClick:e=>{e.stopPropagation(),z.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(v,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(X,{variant:`ghost`,onClick:e=>{e.stopPropagation(),T(w===t.id?null:t.id)},title:f(`build.scriptsTab.logs`,`Logs`),children:o(V,{className:`h-4 w-4`})}),o(X,{variant:`ghost`,onClick:e=>{e.stopPropagation(),R.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(X,{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&&L.mutate(t.id)})},title:f(`common.delete`,`Delete`),children:o(g,{className:`h-4 w-4`})})]})}}],[C,w,i,y,L,z.isPending,z.variables,R,f]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:D.data===void 0?``:zl(B)}),D.error!=null&&o(q,{title:f(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Vp(D.error),onRetry:M}),o(Vt,{columns:W,rows:B,rowKey:e=>e.id,pageSize:25,maxBodyHeight:vt,emptyMessage:ee?f(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):D.data===void 0?f(`build.scriptsTab.loadingScripts`,`Loading scripts…`):f(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{S(e),y(e.id),i?.(e.id)}}),o(It,{open:O,onClose:()=>{F.reset(),I.reset(),z.reset(),S(null),b(),i?.(null)},title:ne===null?f(`build.scriptsTab.newScript`,`New script`):f(`build.scriptsTab.edit`,`Edit {{name}}`,{name:ne.name}),icon:nt,width:`xl`,testId:`script-editor-panel`,children:o(Ip,{existing:ne,typeDefs:A.data,typeDefsLoading:A.isLoading,saving:H,saveError:U,restarting:z.isPending,restartError:z.error===null?null:Vp(z.error),onRestart:ne===null?void 0:()=>z.mutate(ne.id),onSave:e=>{let t=ne;t===null?F.mutate(e):I.mutate({blockId:t.id,block:e})},onCancel:()=>{F.reset(),I.reset(),z.reset(),S(null),b(),i?.(null)}})}),L.error!=null&&o(q,{message:Vp(L.error)}),R.error!=null&&o(q,{message:Vp(R.error)}),z.error!=null&&o(q,{message:Vp(z.error)})]})}function Up(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wp(e){return Up(e)&&typeof e.kind==`string`}function Gp(e){let t=e.actions;return Wp(e.when)&&Array.isArray(t)&&t.every(Wp)}function Kp(e){return Gp(e)?e:null}function qp(e){return{...e}}var Jp=[`device-becomes`,`device-event`,`device-fired`,`device-is`,`stationary-present`],Yp=[`version`,`deviceId`];function Xp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zp(e){let t=e.kind;return typeof t==`string`?t:void 0}function Qp(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function $p(e){return e.map(String).join(`.`)}function em(e){let t=e.replace(/[^A-Za-z0-9]+/g,` `).trim().split(` `).filter(e=>e!==``).map((e,t)=>(t===0?e.charAt(0).toLowerCase():e.charAt(0).toUpperCase())+e.slice(1)).join(``);return(/^[A-Za-z]/.test(t)?t:`input${t}`).slice(0,40)}function tm(e){return Be.test(e)}function nm(e,t){let n=tm(t)?t:em(t),r=new Set(e.map(e=>e.key));if(!r.has(n))return n;for(let e=2;e<100;e+=1){let t=`${n.slice(0,37)}${String(e)}`;if(!r.has(t))return t}return n}function rm(e,t,n){if(Array.isArray(e)){e.forEach((e,r)=>rm(e,[...t,r],n));return}if(!Xp(e))return;let r=Zp(e);r!==void 0&&Jp.includes(r)&&n.push({path:[...t,`deviceId`],kind:`device`,where:r,keyHint:`device`,labelHint:`Device`}),r===`device-fired`&&n.push({path:t,kind:`event`,where:r,keyHint:`event`,labelHint:`Event`}),r===`command`&&(n.push({path:[...t,`target`],kind:`device`,as:`target`,multiple:!0,where:r,keyHint:`targets`,labelHint:`Devices`}),n.push({path:t,kind:`action`,where:r,keyHint:`action`,labelHint:`Action`}));for(let[i,a]of Object.entries(e)){if(typeof a==`number`&&Number.isFinite(a)&&!Yp.includes(i)){n.push({path:[...t,i],kind:i===`seconds`?`duration`:`number`,where:r??i,current:a,keyHint:i,labelHint:i===`seconds`?`Seconds`:i});continue}rm(a,[...t,i],n)}}function im(e,t){let n=[];rm(e,[],n);let r=t.flatMap(e=>e.kind===`value`?[e.path]:[]);return n.filter(e=>!r.some(t=>Qp(t,e.path))).map(e=>({id:`${$p(e.path)}:${e.kind}`,path:e.path,kind:e.kind,where:e.where,suggestedKey:e.keyHint,suggestedLabel:e.labelHint,...e.as===void 0?{}:{as:e.as},...e.multiple===void 0?{}:{multiple:e.multiple},...e.current===void 0?{}:{current:e.current}}))}function am(e,t){let n={key:t.key,label:t.label,...t.optional?{optional:!0}:{}};switch(e.kind){case`device`:return{kind:`device`,...n,...e.multiple===!0?{multiple:!0}:{}};case`event`:return{kind:`event`,...n,deviceInput:t.deviceInput??``};case`action`:return{kind:`action`,...n,...t.deviceInput===void 0||t.deviceInput===``?{}:{deviceInput:t.deviceInput}};case`duration`:return{kind:`duration`,...n,...e.current===void 0?{}:{default:Math.max(0,e.current)}};case`number`:return{kind:`number`,...n,...e.current===void 0?{}:{default:e.current}}}}function om(e,t,n){if(!tm(n.key))return`key`;if(e.inputs.some(e=>e.key===n.key))return`key-taken`;if(n.label.trim()===``)return`label`;if(t.kind===`event`){let t=e.inputs.find(e=>e.key===n.deviceInput);if(t===void 0||t.kind!==`device`)return`device-input`}return null}function sm(e,t,n){let r={kind:`value`,input:n.key,path:[...t.path],...t.as===void 0?{}:{as:t.as}};return{...e,inputs:[...e.inputs,am(t,{...n,label:n.label.trim()})],bindings:[...e.bindings,r]}}function cm(e,t){return{...e,inputs:e.inputs.filter(e=>e.key!==t),bindings:e.bindings.filter(e=>e.input!==t)}}function lm(e,t,n){return{...e,inputs:e.inputs.map(e=>e.key===t?n:e)}}var um=(e,t)=>t in e;function dm(e,t){return um(t,`optional`)?t.optional===!0?{optional:!0}:{}:e.optional===!0?{optional:!0}:{}}function fm(e,t,n,r){return um(e,t)?r(e[t]):n}var pm=e=>typeof e==`number`?e:void 0,mm=e=>typeof e==`string`&&e!==``?e:void 0,hm=e=>typeof e==`boolean`?e:void 0;function gm(e,t){let n=t.label??e.label,r={key:e.key,label:n,...dm(e,t)},i=e.description===void 0?{}:{description:e.description};switch(e.kind){case`number`:case`duration`:{let n=fm(t,`min`,e.min,pm),a=fm(t,`max`,e.max,pm),o=fm(t,`default`,e.default,pm);return{kind:e.kind,...r,...i,...n===void 0?{}:{min:n},...a===void 0?{}:{max:a},...o===void 0?{}:{default:o}}}case`text`:{let n=fm(t,`default`,e.default,mm);return{kind:`text`,...r,...i,...e.maxLength===void 0?{}:{maxLength:e.maxLength},...n===void 0?{}:{default:n}}}case`boolean`:{let n=fm(t,`default`,e.default,hm);return{kind:`boolean`,...r,...i,...n===void 0?{}:{default:n}}}case`select`:{let n=t.options===void 0||t.options.length===0?e.options:[...t.options],a=fm(t,`default`,e.default,mm);return{kind:`select`,...r,...i,options:n,...a===void 0?{}:{default:a}}}case`device`:{let n=um(t,`capability`)?mm(t.capability):e.filter?.capability,a=um(t,`role`)?mm(t.role):e.filter?.role,o={...n===void 0?{}:{capability:n},...a===void 0?{}:{role:a}};return{kind:`device`,...r,...i,...e.multiple===!0?{multiple:!0}:{},...Object.keys(o).length===0?{}:{filter:o}}}case`event`:return{kind:`event`,...r,...i,deviceInput:t.deviceInput??e.deviceInput};case`action`:{let n=um(t,`deviceInput`)?mm(t.deviceInput):e.deviceInput;return{kind:`action`,...r,...i,...n===void 0?{}:{deviceInput:n}}}}}function _m(e){return e.map(e=>`${e.value} = ${e.label}`).join(`
|
|
41
|
-
`)}function
|
|
42
|
-
`).map(e=>e.trim()).filter(e=>e!==``).map(e=>{let t=e.indexOf(`=`),n=(t<0?e:e.slice(0,t)).trim(),r=(t<0?e:e.slice(t+1)).trim();return{value:n,label:r===``?n:r}}).filter(e=>e.value!==``)}u();function ym({payload:t,readOnly:n,onChange:r}){let{t:i}=Q(),[a,s]=c(null);return e(`div`,{className:`space-y-3`,"data-testid":`template-inputs-panel`,children:[t.inputs.length===0?o(`p`,{className:`text-sm text-foreground-muted`,children:i(`build.templates.noInputs`,`No inputs yet. Mark a field of the automation as an input to ask for it each time.`)}):o(`ul`,{className:`space-y-2`,children:t.inputs.map(c=>e(`li`,{className:`rounded-md border border-border bg-surface p-3`,"data-testid":`template-input-row-${c.key}`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium text-foreground`,children:c.label}),o(J,{variant:`neutral`,children:c.kind}),c.optional===!0&&o(J,{variant:`neutral`,children:i(`build.templates.optional`,`Optional`)}),o(`code`,{className:`text-xs text-foreground-subtle`,children:c.key}),c.kind===`group`?o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`build.templates.groupReadOnly`,`Repeatable group — shipped templates only`)}):!n&&e(m,{children:[o(Dt,{icon:A,size:`sm`,variant:`ghost`,"aria-label":i(`common.edit`,`Edit`),onClick:()=>s(a===c.key?null:c.key),"data-testid":`template-input-edit-${c.key}`}),o(Dt,{icon:g,size:`sm`,variant:`ghost`,"aria-label":i(`common.delete`,`Delete`),onClick:()=>{s(null),r(cm(t,c.key))},"data-testid":`template-input-remove-${c.key}`})]})]}),c.kind===`group`&&o(`ul`,{className:`mt-2 space-y-0.5 pl-3 text-xs text-foreground-muted`,children:c.inputs.map(t=>e(`li`,{children:[t.label,` `,e(`span`,{className:`text-foreground-subtle`,children:[`(`,t.kind,`)`]})]},t.key))}),a===c.key&&c.kind!==`group`&&o(xm,{input:c,deviceInputs:t.inputs.filter(e=>e.kind===`device`),onChange:e=>r(lm(t,c.key,e))})]},c.key))}),!n&&o(wm,{payload:t,onChange:r})]})}function bm(e){if(e===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function xm({input:t,deviceInputs:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-2`,"data-testid":`template-input-editor-${t.key}`,children:[o(K,{label:i(`build.templates.label`,`Label`),children:o(Y,{value:t.label,maxLength:80,onChange:e=>r(gm(t,{label:e.target.value})),"data-testid":`template-input-label`})}),o(K,{label:i(`build.templates.requiredField`,`Required`),children:o(Jt,{checked:t.optional!==!0,onCheckedChange:e=>r(gm(t,{optional:!e})),label:i(`build.templates.requiredField`,`Required`),"data-testid":`template-input-required`})}),(t.kind===`number`||t.kind===`duration`)&&e(m,{children:[o(K,{label:i(`build.templates.min`,`Minimum`),children:t.kind===`duration`?o(`span`,{"data-testid":`template-input-min`,children:o($l,{value:t.min,"aria-label":i(`build.templates.min`,`Minimum`),onChange:e=>r(gm(t,{min:e}))})}):o(Y,{type:`number`,value:t.min===void 0?``:String(t.min),onChange:e=>r(gm(t,{min:bm(e.target.value)})),"data-testid":`template-input-min`})}),o(K,{label:i(`build.templates.max`,`Maximum`),children:t.kind===`duration`?o(`span`,{"data-testid":`template-input-max`,children:o($l,{value:t.max,"aria-label":i(`build.templates.max`,`Maximum`),onChange:e=>r(gm(t,{max:e}))})}):o(Y,{type:`number`,value:t.max===void 0?``:String(t.max),onChange:e=>r(gm(t,{max:bm(e.target.value)})),"data-testid":`template-input-max`})}),o(K,{label:i(`build.templates.default`,`Default`),children:t.kind===`duration`?o(`span`,{"data-testid":`template-input-default`,children:o($l,{value:t.default,"aria-label":i(`build.templates.default`,`Default`),onChange:e=>r(gm(t,{default:e}))})}):o(Y,{type:`number`,value:t.default===void 0?``:String(t.default),onChange:e=>r(gm(t,{default:bm(e.target.value)})),"data-testid":`template-input-default`})})]}),t.kind===`text`&&o(K,{label:i(`build.templates.default`,`Default`),children:o(Y,{value:t.default??``,onChange:e=>r(gm(t,{default:e.target.value===``?void 0:e.target.value}))})}),t.kind===`boolean`&&o(K,{label:i(`build.templates.default`,`Default`),children:o(Jt,{checked:t.default===!0,onCheckedChange:e=>r(gm(t,{default:e})),label:i(`build.templates.default`,`Default`)})}),t.kind===`select`&&o(K,{label:i(`build.templates.options`,`Options`),description:i(`build.templates.optionsHint`,`One per line: value = label`),className:`sm:col-span-2`,children:o(Sm,{options:t.options,onChange:e=>r(gm(t,{options:e}))})}),t.kind===`device`&&e(m,{children:[o(K,{label:i(`build.templates.filterCapability`,`Only devices with capability`),children:o(Y,{value:t.filter?.capability??``,onChange:e=>r(gm(t,{capability:e.target.value})),"data-testid":`template-input-filter-capability`})}),o(K,{label:i(`build.templates.filterRole`,`Only devices of type`),children:o(Y,{value:t.filter?.role??``,onChange:e=>r(gm(t,{role:e.target.value}))})})]}),(t.kind===`event`||t.kind===`action`)&&o(K,{label:i(`build.templates.readsDevice`,`Reads the device input`),children:o(z,{value:t.deviceInput??``,options:[...t.kind===`action`?[{value:``,label:i(`build.templates.anyAction`,`Any action`)}]:[],...n.map(e=>({value:e.key,label:e.label}))],onChange:e=>r(gm(t,{deviceInput:e.target.value}))})})]})}function Sm({options:e,onChange:t}){let[n,r]=c(()=>_m(e));return o(Xt,{rows:4,value:n,onChange:e=>{r(e.target.value),t(vm(e.target.value))},"data-testid":`template-input-options`})}function Cm(e,t){return`${{device:t(`build.templates.kindDevice`,`Device`),event:t(`build.templates.kindEvent`,`Event`),action:t(`build.templates.kindAction`,`Action`),duration:t(`build.templates.kindDuration`,`Duration`),number:t(`build.templates.kindNumber`,`Number`)}[e.kind]} — ${e.where} · ${e.path.map(String).join(`.`)}`}function wm({payload:t,onChange:n}){let{t:i}=Q(),a=r(()=>im(t.body,t.bindings),[t.body,t.bindings]),[s,l]=c(``),[u,d]=c(``),[f,p]=c(!1),[h,g]=c(``),_=a.find(e=>e.id===s),v=t.inputs.filter(e=>e.kind===`device`),y=_?.kind===`event`;if(a.length===0)return o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`template-nothing-to-mark`,children:i(`build.templates.nothingToMark`,`Every field that can be an input already is.`)});let b=_===void 0?null:{key:nm(t.inputs,em(u===``?_.suggestedKey:u)),label:u.trim()===``?_.suggestedLabel:u.trim(),optional:f,..._.kind===`event`||_.kind===`action`?{deviceInput:h===``?v[0]?.key:h}:{}},x=_===void 0||b===null?`field`:om(t,_,b);return e(`div`,{className:`space-y-3 rounded-md border border-dashed border-border p-3`,"data-testid":`template-mark-as-input`,children:[o(`p`,{className:`text-sm font-medium text-foreground`,children:i(`build.templates.markAsInput`,`Mark as input`)}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[o(K,{label:i(`build.templates.markField`,`Field`),className:`sm:col-span-2`,children:o(z,{value:s,options:[{value:``,label:i(`build.templates.pickField`,`Choose a field of the automation…`)},...a.map(e=>({value:e.id,label:Cm(e,i)}))],onChange:e=>{l(e.target.value),d(``)},"data-testid":`template-mark-field`})}),_!==void 0&&e(m,{children:[o(K,{label:i(`build.templates.label`,`Label`),children:o(Y,{value:u,placeholder:_.suggestedLabel,maxLength:80,onChange:e=>d(e.target.value),"data-testid":`template-mark-label`})}),o(K,{label:i(`build.templates.requiredField`,`Required`),children:o(Jt,{checked:!f,onCheckedChange:e=>p(!e),label:i(`build.templates.requiredField`,`Required`)})}),(_.kind===`event`||_.kind===`action`)&&o(K,{label:i(`build.templates.readsDevice`,`Reads the device input`),...y&&v.length===0?{error:i(`build.templates.markDeviceFirst`,`Mark the device as an input first.`)}:{},children:o(z,{value:h===``?v[0]?.key??``:h,options:[..._.kind===`action`?[{value:``,label:i(`build.templates.anyAction`,`Any action`)}]:[],...v.map(e=>({value:e.key,label:e.label}))],onChange:e=>g(e.target.value)})})]})]}),e(X,{size:`sm`,disabled:x!==null||_===void 0||b===null,onClick:()=>{_===void 0||b===null||x!==null||(n(sm(t,_,b)),l(``),d(``),p(!1))},"data-testid":`template-mark-add`,children:[o(P,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),i(`build.templates.addInput`,`Add input`)]})]})}u();function Tm(e,t){let n=URL.createObjectURL(new Blob([t],{type:`application/json`})),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),URL.revokeObjectURL(n)}function Em(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return`${t===``?`automation-template`:t}.json`}function Dm({template:t,saving:n,error:i,onSave:a,onDuplicate:s,onClose:l}){let{t:u}=Q(),d=t.builtIn,[f,p]=c(t.name),[m,h]=c(t.payload),g=ur(),v=r(()=>Kp(m.body),[m.body]),y=r(()=>H.safeParse(m),[m]),b=!d&&f.trim()!==``&&y.success&&!n,x=e=>h({...m,body:qp(ja(e))}),C=()=>({id:t.id,kind:`automation`,name:f.trim(),payload:m});return e(`div`,{className:`space-y-4`,"data-testid":`automation-template-editor`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`h3`,{className:`min-w-0 flex-1 truncate text-sm font-semibold`,children:t.id===null?u(`build.templates.newAutomationTemplate`,`New automation template`):f}),d&&o(J,{variant:`neutral`,"data-testid":`template-builtin-badge`,children:u(`build.templates.builtIn`,`Built-in`)})]}),d&&o(`p`,{className:`text-xs text-foreground-muted`,children:u(`build.templates.builtInHint`,`Shipped with CamStack and read-only. Duplicate it to make a copy you can change.`)}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[o(K,{label:u(`remote.templates.name`,`Name`),children:o(Y,{value:f,maxLength:120,disabled:d,onChange:e=>p(e.target.value),"data-testid":`template-name`})}),o(K,{label:u(`build.templates.description`,`Description`),children:o(Xt,{rows:2,value:m.description??``,disabled:d,maxLength:500,onChange:e=>{let{description:t,...n}=m;h(e.target.value===``?n:{...n,description:e.target.value})},"data-testid":`template-description`})})]}),e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_24rem]`,children:[o(mt,{headingId:`template-body`,title:u(`build.templates.body`,`Automation`),children:o(`div`,{className:`space-y-4 p-3`,"data-testid":`template-body-editor`,children:v===null?o(`pre`,{className:`max-h-96 overflow-auto rounded bg-surface-hover p-3 text-xs`,children:JSON.stringify(m.body,null,2)}):o(`div`,{className:`space-y-4`,inert:d,children:e(Ia,{when:v.when,children:[e(`div`,{children:[o(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:u(`automation.automationEditor.when`,`When`)}),o(hc,{recipe:v,devices:g,onChange:x})]}),e(`div`,{children:[o(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:u(`automation.automationEditor.then`,`Then`)}),o(Gc,{flowControl:!0,actions:v.actions,devices:g,onChange:e=>x(Ui(v,e))})]}),e(`div`,{children:[o(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:u(`flow.runMode.title`,`Overlap`)}),o(El,{value:Sl(v),onChange:e=>x(Cl(v,e))})]})]})})})}),o(mt,{headingId:`template-inputs`,title:u(`build.templates.inputs`,`Inputs`),children:o(`div`,{className:`p-3`,children:o(ym,{payload:m,readOnly:d,onChange:h})})})]}),!d&&!y.success&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:y.error.issues[0]?.message??``}),i!==null&&o(`p`,{role:`alert`,className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:i}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[!d&&e(X,{disabled:!b,onClick:()=>a(C()),"data-testid":`template-save`,children:[n&&o(S,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),d&&e(X,{onClick:()=>s(C()),"data-testid":`template-duplicate`,children:[o(_,{className:`h-4 w-4`,"aria-hidden":!0}),u(`remote.templates.duplicate`,`Duplicate`)]}),e(X,{variant:`outline`,disabled:!y.success,onClick:()=>{y.success&&Tm(Em(f),JSON.stringify(ve(f.trim(),y.data),null,2))},"data-testid":`template-export`,children:[o(B,{className:`h-4 w-4`,"aria-hidden":!0}),u(`build.templates.exportJson`,`Export JSON`)]}),o(X,{variant:`ghost`,onClick:l,disabled:n,children:u(`common.close`,`Close`)})]})]})}u();function Om(e){let t=H.safeParse(e.payload);return t.success?{id:e.id,name:e.name,payload:t.data,builtIn:e.builtIn===!0}:null}function km(e,t){return[...e.devices.length===0?[]:[t(`remote.templates.inUseMessage`,{devices:e.devices.map(e=>e.name).join(`, `)})],...e.automations.length===0?[]:[t(`build.templates.inUseAutomations`,{automations:e.automations.map(e=>e.name).join(`, `)})]]}function Am({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),a=f(),l=Rn(),u=vn({}),d=ot(),p=br(),m=on(),h=j(),v=I(),[y,b]=c(null),[x,S]=c(null),[C,T]=c(!1),[E,D]=Un(),O=E.get(Gn),k=e=>{if(p.clearError(),e.kind===`automation`){b(null),S(Om(e));return}S(null),b({id:e.id,kind:e.kind,name:e.name,payload:e.payload})};s(()=>{t&&(T(!0),n?.())},[t,n]),s(()=>{if(O===null||u.data===void 0)return;let e=u.data.find(e=>e.id===O);e!==void 0&&k(e),D(e=>{let t=new URLSearchParams(e);return t.delete(Gn),t},{replace:!0})},[O,u.data,D]);let M=()=>void a.invalidateQueries({queryKey:[[`template`]]}),N=async e=>{await p.save(e)&&(b(null),S(null))},F=async e=>{try{let t=await d.mutateAsync({kind:e.kind,name:i(`remote.templates.copyName`,{name:e.name}),payload:e.payload});return M(),t.status===`saved`?t.template.id:null}catch(e){return await v({title:i(`remote.templates.duplicateFailed`),message:e instanceof Error?e.message:String(e),variant:`danger`}),null}},L=async e=>{let t=u.data?.find(t=>t.id===e.id);t!==void 0&&await F(t)!==null&&S(null)},R=async e=>{if(await h({title:i(`remote.templates.deleteTitle`,{name:e.name}),message:i(`remote.templates.deleteMessage`),confirmLabel:i(`common.delete`),variant:`danger`}))try{let t=await m.mutateAsync({id:e.id});if(t.status===`in-use`){await v({title:i(`remote.templates.inUseTitle`,{name:e.name}),message:km(t,i).join(` `),variant:`warning`});return}if(t.status===`read-only`){await v({title:i(`build.templates.readOnlyTitle`,{name:e.name}),message:i(`build.templates.readOnlyMessage`),variant:`warning`});return}M()}catch(e){await v({title:i(`remote.templates.deleteFailed`),message:e instanceof Error?e.message:String(e),variant:`danger`})}},z=r(()=>[{key:`name`,header:i(`remote.templates.name`),sortValue:e=>e.name.toLowerCase(),render:t=>e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`font-medium text-foreground`,children:t.name}),t.builtIn===!0&&o(J,{variant:`neutral`,children:i(`build.templates.builtIn`,`Built-in`)})]})},{key:`kind`,header:i(`remote.templates.kind.label`),sortValue:e=>e.kind,render:e=>o(J,{variant:`neutral`,children:pr(e.kind).label(i)})},{key:`summary`,header:i(`remote.templates.summary`),notSortableReason:`A sentence built from the payload.`,render:e=>o(`span`,{className:`text-foreground-muted`,children:pr(e.kind).summary(e.payload,i)})},{key:`updated`,header:i(`remote.templates.updated`),sortValue:e=>e.updatedAt,render:e=>o(`span`,{className:`text-foreground-muted`,children:e.builtIn===!0?``:new Date(e.updatedAt).toLocaleDateString()})},{key:`actions`,align:`right`,notSortableReason:`Row actions.`,render:e=>o(rn,{title:i(`remote.templates.actionsFor`,{name:e.name}),items:[...e.kind===`automation`?[{id:`create-automation`,label:i(`build.templates.createAutomation`,`Create automation`),icon:w,onClick:()=>void l(`/build?tab=automations&${wu}=${encodeURIComponent(e.id)}`)}]:[],{id:`edit`,label:e.builtIn===!0?i(`build.templates.view`,`View`):i(`common.edit`),icon:A,onClick:()=>k(e)},{id:`duplicate`,label:i(`remote.templates.duplicate`),icon:_,onClick:()=>void F(e)},...e.builtIn===!0?[]:[{id:`delete`,label:i(`common.delete`),icon:g,danger:!0,onClick:()=>void R(e)}]]})}],[i]),B=u.data??[];return x===null?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`remote.templates.subtitle`)}),u.status===`error`?o(q,{title:i(`remote.templates.loadFailed`),message:u.error.message,onRetry:()=>void u.refetch()}):u.data===void 0?o(ct,{className:`h-32 w-full`}):B.length===0?o(dt,{icon:it,title:i(`remote.templates.emptyTitle`),description:i(`remote.templates.emptyDescription`),action:o(X,{size:`sm`,onClick:()=>T(!0),children:i(`remote.templates.new`)})}):o(Vt,{columns:z,rows:B,rowKey:e=>e.id,maxBodyHeight:vt,defaultSort:{columnKey:`name`,dir:`asc`},onRowClick:k}),o(vr,{draft:y,saving:p.saving,error:p.error,onSave:e=>void N(e),onClose:()=>b(null)}),o(wn,{open:C,onOpenChange:e=>!e&&T(!1),children:e(_t,{width:`md`,placement:`sheet-on-mobile`,children:[o(hn,{children:o(lt,{children:i(`remote.templates.new`)})}),e(Bt,{className:`space-y-2`,"data-testid":`new-template-chooser`,children:[e(X,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>{p.clearError(),T(!1),b({id:null,kind:`remote`,name:``,payload:pr(`remote`).emptyPayload()})},"data-testid":`new-template-remote`,children:[o(P,{className:`h-4 w-4 shrink-0`,"aria-hidden":!0}),e(`span`,{className:`block`,children:[o(`span`,{className:`block font-medium`,children:pr(`remote`).label(i)}),o(`span`,{className:`block text-xs text-foreground-muted`,children:i(`build.templates.newRemoteHint`,`The button layout of a remote.`)})]})]}),e(X,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>{p.clearError(),T(!1),S({id:null,name:``,payload:H.parse(pr(`automation`).emptyPayload()),builtIn:!1})},"data-testid":`new-template-automation`,children:[o(P,{className:`h-4 w-4 shrink-0`,"aria-hidden":!0}),e(`span`,{className:`block`,children:[o(`span`,{className:`block font-medium`,children:pr(`automation`).label(i)}),o(`span`,{className:`block text-xs text-foreground-muted`,children:i(`build.templates.newAutomationHint`,`An automation with inputs, so each copy only asks for its devices.`)})]})]})]})]})})]}):o(Dm,{template:x,saving:p.saving,error:p.error,onSave:e=>void N(e),onDuplicate:e=>void L(e),onClose:()=>S(null)},x.id??`new`)}var jm=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`,`templates`];function Mm(e){return e!==null&&jm.some(t=>t===e)}var Nm=[`coreBlocks`,`list`,`build-counts`],Pm=[`schedulers`,`list`,`build-counts`],Fm=[`actions`,`list`,`build-counts`],Im=[`block`,`action`,`scheduler`,`create`,`new`,`edit`,wu];function Lm(e){return e.filter(e=>Ke(e)===`code`).length}function Rm(e){return e.filter(e=>Ar(e.code)).length}function zm(e,t){return t===null?e:`${e} (${String(t)})`}function Bm(){let{t}=Q(),n=k(),[r,i]=Un(),a=r.get(`tab`),s=Mm(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:Nm,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:Lm(u),f=u===void 0?null:Rm(u),p=l({queryKey:Fm,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=l({queryKey:Pm,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})},w=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},T=s===`automations`?t(`build.newAutomation`,`New automation`):s===`actions`?t(`build.newAction`,`New action`):s===`schedulers`?t(`build.newScheduler`,`New scheduler`):s===`templates`?t(`build.newTemplate`,`New template`):t(`build.newScript`,`New script`),E=In(`/build`,{t,isAdmin:!0})??{icon:C,title:t(`nav.build`,`Build-your-self`)};return o(Kn,{icon:E.icon,title:E.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${E.title} sections`,fill:!0,actions:s===`custom-device`?e(X,{type:`button`,onClick:()=>S(`helper`),"data-testid":`build-new-composed`,children:[o(P,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(X,{type:`button`,onClick:x,"data-testid":`build-new`,children:[o(P,{className:`h-4 w-4`}),` `,T]}),sections:[{id:`automations`,label:zm(t(`build.tabAutomations`,`Automations`),f),ownedParams:Im,content:o(Ou,{onOpenScripts:y,createRequested:s===`automations`&&c,onCreateConsumed:w})},{id:`actions`,label:zm(t(`build.tabActions`,`Actions`),m),ownedParams:Im,content:o(_l,{createRequested:s===`actions`&&c,onCreateConsumed:w})},{id:`schedulers`,label:zm(t(`build.tabSchedulers`,`Schedulers`),g),ownedParams:Im,content:o(qu,{createRequested:s===`schedulers`&&c,onCreateConsumed:w})},{id:`scripts`,label:zm(t(`build.tabCode`,`Code`),d),ownedParams:Im,content:o(Hp,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:b,createRequested:s===`scripts`&&c,onCreateConsumed:w})},{id:`custom-device`,label:zm(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:Im,content:o(Ad,{createRequested:s===`custom-device`&&c,onCreateConsumed:w})},{id:`templates`,label:t(`build.tabTemplates`,`Templates`),ownedParams:Im,content:o(Am,{createRequested:s===`templates`&&c,onCreateConsumed:w})}]})}export{Bm as BuildPage};
|
|
40
|
+
`;function Pp({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Z.t(`helpers.restartGate.saveFirstNoProcess`):n?Z.t(`helpers.restartGate.saving`):r?Z.t(`helpers.restartGate.restarting`):t?Z.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Z.t(`helpers.restartGate.disabled`)}u();var Fp=5e3;function Ip(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 Lp({blockId:t}){let{t:n}=Q(),i=se(t),a=kn({addonId:i,projection:`slim`},{refetchInterval:Fp}),s=r(()=>Ip(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(S,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Ln,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(J,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Ln,{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(Hn,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(xt,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(J,{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 Rp(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 zp(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 Bp(e){switch(e){case`refresh-channel-catalog`:return Z.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Z.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Z.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Z.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Z.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Z.t(`build.scriptSettingsPanel.enableUnifi`)}}function Vp(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Hp(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Up(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Vp(e);n!==null&&(t[n]=Hp(e))}return t}function Wp(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Gp({blockId:t}){let{t:n}=Q(),i=k(),s=mn({blockId:t},{retry:!1}),l=Mt({blockId:t},{refetchInterval:1e4,retry:!1}),u=Ut({onSuccess:()=>{l.refetch()}}),d=Nn(),f=ft(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=Wp(l.data)?l.data:null,C=r(()=>x===null?{}:Up(x),[x]),w=p??C,T=a(e=>{m(e)},[]),E=p!==null,D=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),O=a(async(e,n)=>{if(Rp(e)){b(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:zp(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(Bp(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{b(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(S,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):x===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Ln,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(X,{size:`sm`,variant:`primary`,onClick:D,disabled:!E||u.isPending||y,children:[u.isPending&&o(S,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(Vn,{schema:x,values:w,onChange:T,onAction:O}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var Kp=`hub`;function qp({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:f,onCancel:h}){let{t:g}=Q(),_=k(),b=j(),{resolvedMode:x}=yn(),C=pe({code:t?.code??Np,files:t?.files,entry:t?.entry}),[w,T]=c(t?.name??``),[E,O]=c(C.files),[A,M]=c(C.entry),[N,P]=c(C.entry),[F,I]=c(t?.placement??Kp),[L,R]=c(t?.integrationId??``),[B,ee]=c([]),[H,U]=c(!1),[te,ne]=c(`blank`),[W,re]=c(null),[G,ie]=c(``),ae=E[N]??``,oe=e=>{O(t=>({...t,[N]:e}))},ce=Object.keys(E).toSorted(),le=jp.length>1,ue=r(()=>[...n?.libs??[],...Ep(E,N)],[n?.libs,E,N]),de=p({mutationFn:()=>_.trpcClient.coreBlocks.compile.mutate({files:E,entry:A})}),fe=r(()=>B.filter(e=>e.severity>=8),[B]),me=Ap(B),he=w.trim()===``,ge=t===null?null:pe(t),_e=t===null||ge===null||JSON.stringify(E)!==JSON.stringify(ge.files)||A!==ge.entry||w.trim()!==t.name||F!==t.placement||(L.trim()===``?void 0:L.trim())!==t.integrationId,ve=()=>{de.reset(),f({name:w.trim(),files:E,entry:A,enabled:t?.enabled??!0,placement:F,...L.trim()===``?{}:{integrationId:L.trim()}})},ye=()=>{let e=Mp(Object.keys(E));O(t=>({...t,[e]:``})),P(e),re(e),ie(e)},be=e=>{re(e),ie(e)},xe=()=>{if(W===null)return;let e=W,t=G.trim();if(re(null),!(t===``||t===e)){if(E[t]!==void 0){P(t);return}O(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),A===e&&M(t),P(t)}},Se=async e=>{let t=jp.find(t=>t.id===e);if(t===void 0)return;let n=jp.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(E)===JSON.stringify(n.files)&&A===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`})||(ne(e),O({...t.files}),M(t.entry),P(t.entry),(w.trim()===``||te===`blank`)&&T(t.id===`blank`?``:t.name))},Ce=t===null?null:Fl(t),we=Pp({existing:t,dirty:_e,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[Ce!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(J,{variant:Il(Ce.tone),children:Ce.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(Y,{className:`mt-1`,value:w,onChange:e=>T(e.target.value),placeholder:g(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(Y,{className:`mt-1`,value:L,onChange:e=>R(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&le&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),o(z,{className:`mt-1 w-full`,value:te,onChange:e=>void Se(e.target.value),"data-testid":`script-example-select`,children:jp.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(bn,{selectedNodeId:F,onSelect:I,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),F!==Kp&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(D,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(Ln,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[ce.map(t=>W===t?o(Y,{value:G,onChange:e=>ie(e.target.value),onBlur:()=>xe(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),xe()),e.key===`Escape`&&(e.preventDefault(),re(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(X,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs ${t===N?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>P(t),onDoubleClick:()=>be(t),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===A?` · ${g(`build.blockEditor.entry`)}`:``]},t)),o(X,{variant:`unstyled`,type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:ye,"data-testid":`script-file-add`,children:g(`build.blockEditor.file`,`+ file`)}),N!==A&&o(X,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>M(N),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(kp,{value:ae,onChange:oe,path:`file:///${N}`,extraLibs:ue,onDiagnostics:ee,dark:x===`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.`)}),fe.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:fe.length})}),fe.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}`)),fe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:fe.length-5})})]}),de.data!==void 0&&(de.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(y,{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:[de.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(de.data.line)})}),de.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),de.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:`),` `,Jp(de.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(Gp,{blockId:t.id}),o(Lp,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{variant:`outline`,onClick:()=>de.mutate(),disabled:de.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[de.isPending&&o(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(X,{onClick:ve,disabled:a||me||he,children:[a&&o(S,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(X,{variant:`outline`,onClick:()=>d?.(),disabled:we!==null||d===void 0,title:we??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(v,{className:`h-4 w-4 animate-spin`}):o(v,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),e(X,{variant:`ghost`,onClick:()=>U(!H),title:g(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,"aria-expanded":H,children:[o(V,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,o(wt,{expanded:H})]}),o(X,{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:fe.length}),_e&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),he&&o(J,{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(Ln,{i18nKey:`build.blockEditor.logsOf`,values:{id:se(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(pn,{addonId:se(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Jp(e){return e instanceof Error?e.message:String(e)}u();var Yp=[`coreBlocks`,`list`],Xp=[`coreBlocks`,`getTypeDefs`],Zp=5e3;function Qp(e){return e instanceof Error?e.message:String(e)}function $p({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=E(),{t:f}=Q(),m=k(),{state:h,openNew:_,openEdit:y,close:b}=Yt({editKey:`block`,newKey:`new`}),[x,S]=c(null),C=j(),[w,T]=c(null),D=l({queryKey:Yp,refetchInterval:Zp,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),O=h.mode!==`closed`,A=l({queryKey:Xp,enabled:O,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),M=()=>{D.refetch()},N=n(null),P=D.data;s(()=>{t===void 0||N.current===t||P?.find(e=>e.id===t&&Ke(e)===`code`)!==void 0&&(N.current=t,y(t),i?.(t))},[t,P,y,i]),s(()=>{a&&(S(null),_(),i?.(null),u?.())},[a,u,i,_]);let F=p({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{S(e.block),y(e.block.id),i?.(e.block.id),M()}}),I=p({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{S(e.block),y(e.block.id),i?.(e.block.id),M()}}),L=p({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:M}),R=p({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:M}),z=p({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:M}),B=Rl((D.data??[]).filter(e=>Ke(e)===`code`)),ee=D.data!==void 0&&B.length===0,H=F.isPending||I.isPending,U=F.error===null?I.error===null?null:Qp(I.error):Qp(F.error),te=h.mode===`edit`?B.find(e=>e.id===h.id)??(x!==null&&x.id===h.id?x:null):null,ne=h.mode===`new`||te===null?null:Ll(B,te),W=r(()=>[{key:`name`,header:f(`build.scriptsTab.name`,`Name`),render:t=>{let n=Fl(t),r=zt(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(J,{variant:Il(n.tone),children:n.label}),o(J,{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(Ln,{i18nKey:`common.logsOf`,values:{id:se(t.id)},components:{code:o(`code`,{})}})}),o(pn,{addonId:se(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=R.isPending||L.isPending,r=z.isPending&&z.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[o(X,{variant:`ghost`,onClick:e=>{e.stopPropagation(),S(t),y(t.id),i?.(t.id)},title:f(`common.edit`,`Edit`),children:f(`common.edit`,`Edit`)}),o(X,{variant:`ghost`,onClick:e=>{e.stopPropagation(),z.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(v,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(X,{variant:`ghost`,onClick:e=>{e.stopPropagation(),T(w===t.id?null:t.id)},title:f(`build.scriptsTab.logs`,`Logs`),children:o(V,{className:`h-4 w-4`})}),o(X,{variant:`ghost`,onClick:e=>{e.stopPropagation(),R.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(X,{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&&L.mutate(t.id)})},title:f(`common.delete`,`Delete`),children:o(g,{className:`h-4 w-4`})})]})}}],[C,w,i,y,L,z.isPending,z.variables,R,f]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:D.data===void 0?``:zl(B)}),D.error!=null&&o(q,{title:f(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Qp(D.error),onRetry:M}),o(Vt,{columns:W,rows:B,rowKey:e=>e.id,pageSize:25,maxBodyHeight:vt,emptyMessage:ee?f(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):D.data===void 0?f(`build.scriptsTab.loadingScripts`,`Loading scripts…`):f(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{S(e),y(e.id),i?.(e.id)}}),o(It,{open:O,onClose:()=>{F.reset(),I.reset(),z.reset(),S(null),b(),i?.(null)},title:ne===null?f(`build.scriptsTab.newScript`,`New script`):f(`build.scriptsTab.edit`,`Edit {{name}}`,{name:ne.name}),icon:nt,width:`xl`,testId:`script-editor-panel`,children:o(qp,{existing:ne,typeDefs:A.data,typeDefsLoading:A.isLoading,saving:H,saveError:U,restarting:z.isPending,restartError:z.error===null?null:Qp(z.error),onRestart:ne===null?void 0:()=>z.mutate(ne.id),onSave:e=>{let t=ne;t===null?F.mutate(e):I.mutate({blockId:t.id,block:e})},onCancel:()=>{F.reset(),I.reset(),z.reset(),S(null),b(),i?.(null)}})}),L.error!=null&&o(q,{message:Qp(L.error)}),R.error!=null&&o(q,{message:Qp(R.error)}),z.error!=null&&o(q,{message:Qp(z.error)})]})}function em(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tm(e){return em(e)&&typeof e.kind==`string`}function nm(e){let t=e.actions;return tm(e.when)&&Array.isArray(t)&&t.every(tm)}function rm(e){return nm(e)?e:null}function im(e){return{...e}}var am=[`device-becomes`,`device-event`,`device-fired`,`device-is`,`stationary-present`],om=[`version`,`deviceId`];function sm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cm(e){let t=e.kind;return typeof t==`string`?t:void 0}function lm(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function um(e){return e.map(String).join(`.`)}function dm(e){let t=e.replace(/[^A-Za-z0-9]+/g,` `).trim().split(` `).filter(e=>e!==``).map((e,t)=>(t===0?e.charAt(0).toLowerCase():e.charAt(0).toUpperCase())+e.slice(1)).join(``);return(/^[A-Za-z]/.test(t)?t:`input${t}`).slice(0,40)}function fm(e){return Be.test(e)}function pm(e,t){let n=fm(t)?t:dm(t),r=new Set(e.map(e=>e.key));if(!r.has(n))return n;for(let e=2;e<100;e+=1){let t=`${n.slice(0,37)}${String(e)}`;if(!r.has(t))return t}return n}function mm(e,t,n){if(Array.isArray(e)){e.forEach((e,r)=>mm(e,[...t,r],n));return}if(!sm(e))return;let r=cm(e);r!==void 0&&am.includes(r)&&n.push({path:[...t,`deviceId`],kind:`device`,where:r,keyHint:`device`,labelHint:`Device`}),r===`device-fired`&&n.push({path:t,kind:`event`,where:r,keyHint:`event`,labelHint:`Event`}),r===`command`&&(n.push({path:[...t,`target`],kind:`device`,as:`target`,multiple:!0,where:r,keyHint:`targets`,labelHint:`Devices`}),n.push({path:t,kind:`action`,where:r,keyHint:`action`,labelHint:`Action`}));for(let[i,a]of Object.entries(e)){if(typeof a==`number`&&Number.isFinite(a)&&!om.includes(i)){n.push({path:[...t,i],kind:i===`seconds`?`duration`:`number`,where:r??i,current:a,keyHint:i,labelHint:i===`seconds`?`Seconds`:i});continue}mm(a,[...t,i],n)}}function hm(e,t){let n=[];mm(e,[],n);let r=t.flatMap(e=>e.kind===`value`?[e.path]:[]);return n.filter(e=>!r.some(t=>lm(t,e.path))).map(e=>({id:`${um(e.path)}:${e.kind}`,path:e.path,kind:e.kind,where:e.where,suggestedKey:e.keyHint,suggestedLabel:e.labelHint,...e.as===void 0?{}:{as:e.as},...e.multiple===void 0?{}:{multiple:e.multiple},...e.current===void 0?{}:{current:e.current}}))}function gm(e,t){let n={key:t.key,label:t.label,...t.optional?{optional:!0}:{}};switch(e.kind){case`device`:return{kind:`device`,...n,...e.multiple===!0?{multiple:!0}:{}};case`event`:return{kind:`event`,...n,deviceInput:t.deviceInput??``};case`action`:return{kind:`action`,...n,...t.deviceInput===void 0||t.deviceInput===``?{}:{deviceInput:t.deviceInput}};case`duration`:return{kind:`duration`,...n,...e.current===void 0?{}:{default:Math.max(0,e.current)}};case`number`:return{kind:`number`,...n,...e.current===void 0?{}:{default:e.current}}}}function _m(e,t,n){if(!fm(n.key))return`key`;if(e.inputs.some(e=>e.key===n.key))return`key-taken`;if(n.label.trim()===``)return`label`;if(t.kind===`event`){let t=e.inputs.find(e=>e.key===n.deviceInput);if(t===void 0||t.kind!==`device`)return`device-input`}return null}function vm(e,t,n){let r={kind:`value`,input:n.key,path:[...t.path],...t.as===void 0?{}:{as:t.as}};return{...e,inputs:[...e.inputs,gm(t,{...n,label:n.label.trim()})],bindings:[...e.bindings,r]}}function ym(e,t){return{...e,inputs:e.inputs.filter(e=>e.key!==t),bindings:e.bindings.filter(e=>e.input!==t)}}function bm(e,t,n){return{...e,inputs:e.inputs.map(e=>e.key===t?n:e)}}var xm=(e,t)=>t in e;function Sm(e,t){return xm(t,`optional`)?t.optional===!0?{optional:!0}:{}:e.optional===!0?{optional:!0}:{}}function Cm(e,t,n,r){return xm(e,t)?r(e[t]):n}var wm=e=>typeof e==`number`?e:void 0,Tm=e=>typeof e==`string`&&e!==``?e:void 0,Em=e=>typeof e==`boolean`?e:void 0;function Dm(e,t){let n=t.label??e.label,r={key:e.key,label:n,...Sm(e,t)},i=e.description===void 0?{}:{description:e.description};switch(e.kind){case`number`:case`duration`:{let n=Cm(t,`min`,e.min,wm),a=Cm(t,`max`,e.max,wm),o=Cm(t,`default`,e.default,wm);return{kind:e.kind,...r,...i,...n===void 0?{}:{min:n},...a===void 0?{}:{max:a},...o===void 0?{}:{default:o}}}case`text`:{let n=Cm(t,`default`,e.default,Tm);return{kind:`text`,...r,...i,...e.maxLength===void 0?{}:{maxLength:e.maxLength},...n===void 0?{}:{default:n}}}case`boolean`:{let n=Cm(t,`default`,e.default,Em);return{kind:`boolean`,...r,...i,...n===void 0?{}:{default:n}}}case`select`:{let n=t.options===void 0||t.options.length===0?e.options:[...t.options],a=Cm(t,`default`,e.default,Tm);return{kind:`select`,...r,...i,options:n,...a===void 0?{}:{default:a}}}case`device`:{let n=xm(t,`capability`)?Tm(t.capability):e.filter?.capability,a=xm(t,`role`)?Tm(t.role):e.filter?.role,o={...n===void 0?{}:{capability:n},...a===void 0?{}:{role:a}};return{kind:`device`,...r,...i,...e.multiple===!0?{multiple:!0}:{},...Object.keys(o).length===0?{}:{filter:o}}}case`event`:return{kind:`event`,...r,...i,deviceInput:t.deviceInput??e.deviceInput};case`action`:{let n=xm(t,`deviceInput`)?Tm(t.deviceInput):e.deviceInput;return{kind:`action`,...r,...i,...n===void 0?{}:{deviceInput:n}}}}}function Om(e){return e.map(e=>`${e.value} = ${e.label}`).join(`
|
|
41
|
+
`)}function km(e){return e.split(`
|
|
42
|
+
`).map(e=>e.trim()).filter(e=>e!==``).map(e=>{let t=e.indexOf(`=`),n=(t<0?e:e.slice(0,t)).trim(),r=(t<0?e:e.slice(t+1)).trim();return{value:n,label:r===``?n:r}}).filter(e=>e.value!==``)}u();function Am({payload:t,readOnly:n,onChange:r}){let{t:i}=Q(),[a,s]=c(null);return e(`div`,{className:`space-y-3`,"data-testid":`template-inputs-panel`,children:[t.inputs.length===0?o(`p`,{className:`text-sm text-foreground-muted`,children:i(`build.templates.noInputs`,`No inputs yet. Mark a field of the automation as an input to ask for it each time.`)}):o(`ul`,{className:`space-y-2`,children:t.inputs.map(c=>e(`li`,{className:`rounded-md border border-border bg-surface p-3`,"data-testid":`template-input-row-${c.key}`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium text-foreground`,children:c.label}),o(J,{variant:`neutral`,children:c.kind}),c.optional===!0&&o(J,{variant:`neutral`,children:i(`build.templates.optional`,`Optional`)}),o(`code`,{className:`text-xs text-foreground-subtle`,children:c.key}),c.kind===`group`?o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`build.templates.groupReadOnly`,`Repeatable group — shipped templates only`)}):!n&&e(m,{children:[o(Dt,{icon:A,size:`sm`,variant:`ghost`,"aria-label":i(`common.edit`,`Edit`),onClick:()=>s(a===c.key?null:c.key),"data-testid":`template-input-edit-${c.key}`}),o(Dt,{icon:g,size:`sm`,variant:`ghost`,"aria-label":i(`common.delete`,`Delete`),onClick:()=>{s(null),r(ym(t,c.key))},"data-testid":`template-input-remove-${c.key}`})]})]}),c.kind===`group`&&o(`ul`,{className:`mt-2 space-y-0.5 pl-3 text-xs text-foreground-muted`,children:c.inputs.map(t=>e(`li`,{children:[t.label,` `,e(`span`,{className:`text-foreground-subtle`,children:[`(`,t.kind,`)`]})]},t.key))}),a===c.key&&c.kind!==`group`&&o(Mm,{input:c,deviceInputs:t.inputs.filter(e=>e.kind===`device`),onChange:e=>r(bm(t,c.key,e))})]},c.key))}),!n&&o(Fm,{payload:t,onChange:r})]})}function jm(e){if(e===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function Mm({input:t,deviceInputs:n,onChange:r}){let{t:i}=Q();return e(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-2`,"data-testid":`template-input-editor-${t.key}`,children:[o(K,{label:i(`build.templates.label`,`Label`),children:o(Y,{value:t.label,maxLength:80,onChange:e=>r(Dm(t,{label:e.target.value})),"data-testid":`template-input-label`})}),o(K,{label:i(`build.templates.requiredField`,`Required`),children:o(Jt,{checked:t.optional!==!0,onCheckedChange:e=>r(Dm(t,{optional:!e})),label:i(`build.templates.requiredField`,`Required`),"data-testid":`template-input-required`})}),(t.kind===`number`||t.kind===`duration`)&&e(m,{children:[o(K,{label:i(`build.templates.min`,`Minimum`),children:t.kind===`duration`?o(`span`,{"data-testid":`template-input-min`,children:o($l,{value:t.min,"aria-label":i(`build.templates.min`,`Minimum`),onChange:e=>r(Dm(t,{min:e}))})}):o(Y,{type:`number`,value:t.min===void 0?``:String(t.min),onChange:e=>r(Dm(t,{min:jm(e.target.value)})),"data-testid":`template-input-min`})}),o(K,{label:i(`build.templates.max`,`Maximum`),children:t.kind===`duration`?o(`span`,{"data-testid":`template-input-max`,children:o($l,{value:t.max,"aria-label":i(`build.templates.max`,`Maximum`),onChange:e=>r(Dm(t,{max:e}))})}):o(Y,{type:`number`,value:t.max===void 0?``:String(t.max),onChange:e=>r(Dm(t,{max:jm(e.target.value)})),"data-testid":`template-input-max`})}),o(K,{label:i(`build.templates.default`,`Default`),children:t.kind===`duration`?o(`span`,{"data-testid":`template-input-default`,children:o($l,{value:t.default,"aria-label":i(`build.templates.default`,`Default`),onChange:e=>r(Dm(t,{default:e}))})}):o(Y,{type:`number`,value:t.default===void 0?``:String(t.default),onChange:e=>r(Dm(t,{default:jm(e.target.value)})),"data-testid":`template-input-default`})})]}),t.kind===`text`&&o(K,{label:i(`build.templates.default`,`Default`),children:o(Y,{value:t.default??``,onChange:e=>r(Dm(t,{default:e.target.value===``?void 0:e.target.value}))})}),t.kind===`boolean`&&o(K,{label:i(`build.templates.default`,`Default`),children:o(Jt,{checked:t.default===!0,onCheckedChange:e=>r(Dm(t,{default:e})),label:i(`build.templates.default`,`Default`)})}),t.kind===`select`&&o(K,{label:i(`build.templates.options`,`Options`),description:i(`build.templates.optionsHint`,`One per line: value = label`),className:`sm:col-span-2`,children:o(Nm,{options:t.options,onChange:e=>r(Dm(t,{options:e}))})}),t.kind===`device`&&e(m,{children:[o(K,{label:i(`build.templates.filterCapability`,`Only devices with capability`),children:o(Y,{value:t.filter?.capability??``,onChange:e=>r(Dm(t,{capability:e.target.value})),"data-testid":`template-input-filter-capability`})}),o(K,{label:i(`build.templates.filterRole`,`Only devices of type`),children:o(Y,{value:t.filter?.role??``,onChange:e=>r(Dm(t,{role:e.target.value}))})})]}),(t.kind===`event`||t.kind===`action`)&&o(K,{label:i(`build.templates.readsDevice`,`Reads the device input`),children:o(z,{value:t.deviceInput??``,options:[...t.kind===`action`?[{value:``,label:i(`build.templates.anyAction`,`Any action`)}]:[],...n.map(e=>({value:e.key,label:e.label}))],onChange:e=>r(Dm(t,{deviceInput:e.target.value}))})})]})}function Nm({options:e,onChange:t}){let[n,r]=c(()=>Om(e));return o(Xt,{rows:4,value:n,onChange:e=>{r(e.target.value),t(km(e.target.value))},"data-testid":`template-input-options`})}function Pm(e,t){return`${{device:t(`build.templates.kindDevice`,`Device`),event:t(`build.templates.kindEvent`,`Event`),action:t(`build.templates.kindAction`,`Action`),duration:t(`build.templates.kindDuration`,`Duration`),number:t(`build.templates.kindNumber`,`Number`)}[e.kind]} — ${e.where} · ${e.path.map(String).join(`.`)}`}function Fm({payload:t,onChange:n}){let{t:i}=Q(),a=r(()=>hm(t.body,t.bindings),[t.body,t.bindings]),[s,l]=c(``),[u,d]=c(``),[f,p]=c(!1),[h,g]=c(``),_=a.find(e=>e.id===s),v=t.inputs.filter(e=>e.kind===`device`),y=_?.kind===`event`;if(a.length===0)return o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`template-nothing-to-mark`,children:i(`build.templates.nothingToMark`,`Every field that can be an input already is.`)});let b=_===void 0?null:{key:pm(t.inputs,dm(u===``?_.suggestedKey:u)),label:u.trim()===``?_.suggestedLabel:u.trim(),optional:f,..._.kind===`event`||_.kind===`action`?{deviceInput:h===``?v[0]?.key:h}:{}},x=_===void 0||b===null?`field`:_m(t,_,b);return e(`div`,{className:`space-y-3 rounded-md border border-dashed border-border p-3`,"data-testid":`template-mark-as-input`,children:[o(`p`,{className:`text-sm font-medium text-foreground`,children:i(`build.templates.markAsInput`,`Mark as input`)}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[o(K,{label:i(`build.templates.markField`,`Field`),className:`sm:col-span-2`,children:o(z,{value:s,options:[{value:``,label:i(`build.templates.pickField`,`Choose a field of the automation…`)},...a.map(e=>({value:e.id,label:Pm(e,i)}))],onChange:e=>{l(e.target.value),d(``)},"data-testid":`template-mark-field`})}),_!==void 0&&e(m,{children:[o(K,{label:i(`build.templates.label`,`Label`),children:o(Y,{value:u,placeholder:_.suggestedLabel,maxLength:80,onChange:e=>d(e.target.value),"data-testid":`template-mark-label`})}),o(K,{label:i(`build.templates.requiredField`,`Required`),children:o(Jt,{checked:!f,onCheckedChange:e=>p(!e),label:i(`build.templates.requiredField`,`Required`)})}),(_.kind===`event`||_.kind===`action`)&&o(K,{label:i(`build.templates.readsDevice`,`Reads the device input`),...y&&v.length===0?{error:i(`build.templates.markDeviceFirst`,`Mark the device as an input first.`)}:{},children:o(z,{value:h===``?v[0]?.key??``:h,options:[..._.kind===`action`?[{value:``,label:i(`build.templates.anyAction`,`Any action`)}]:[],...v.map(e=>({value:e.key,label:e.label}))],onChange:e=>g(e.target.value)})})]})]}),e(X,{size:`sm`,disabled:x!==null||_===void 0||b===null,onClick:()=>{_===void 0||b===null||x!==null||(n(vm(t,_,b)),l(``),d(``),p(!1))},"data-testid":`template-mark-add`,children:[o(P,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),i(`build.templates.addInput`,`Add input`)]})]})}u();function Im(e,t){let n=URL.createObjectURL(new Blob([t],{type:`application/json`})),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),URL.revokeObjectURL(n)}function Lm(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return`${t===``?`automation-template`:t}.json`}function Rm({template:t,saving:n,error:i,onSave:a,onDuplicate:s,onClose:l}){let{t:u}=Q(),d=t.builtIn,[f,p]=c(t.name),[m,h]=c(t.payload),g=ur(),v=r(()=>rm(m.body),[m.body]),y=r(()=>H.safeParse(m),[m]),b=!d&&f.trim()!==``&&y.success&&!n,x=e=>h({...m,body:im(ja(e))}),C=()=>({id:t.id,kind:`automation`,name:f.trim(),payload:m});return e(`div`,{className:`space-y-4`,"data-testid":`automation-template-editor`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`h3`,{className:`min-w-0 flex-1 truncate text-sm font-semibold`,children:t.id===null?u(`build.templates.newAutomationTemplate`,`New automation template`):f}),d&&o(J,{variant:`neutral`,"data-testid":`template-builtin-badge`,children:u(`build.templates.builtIn`,`Built-in`)})]}),d&&o(`p`,{className:`text-xs text-foreground-muted`,children:u(`build.templates.builtInHint`,`Shipped with CamStack and read-only. Duplicate it to make a copy you can change.`)}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[o(K,{label:u(`remote.templates.name`,`Name`),children:o(Y,{value:f,maxLength:120,disabled:d,onChange:e=>p(e.target.value),"data-testid":`template-name`})}),o(K,{label:u(`build.templates.description`,`Description`),children:o(Xt,{rows:2,value:m.description??``,disabled:d,maxLength:500,onChange:e=>{let{description:t,...n}=m;h(e.target.value===``?n:{...n,description:e.target.value})},"data-testid":`template-description`})})]}),e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_24rem]`,children:[o(mt,{headingId:`template-body`,title:u(`build.templates.body`,`Automation`),children:o(`div`,{className:`space-y-4 p-3`,"data-testid":`template-body-editor`,children:v===null?o(`pre`,{className:`max-h-96 overflow-auto rounded bg-surface-hover p-3 text-xs`,children:JSON.stringify(m.body,null,2)}):o(`div`,{className:`space-y-4`,inert:d,children:e(Ia,{when:v.when,children:[e(`div`,{children:[o(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:u(`automation.automationEditor.when`,`When`)}),o(hc,{recipe:v,devices:g,onChange:x})]}),e(`div`,{children:[o(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:u(`automation.automationEditor.then`,`Then`)}),o(Gc,{flowControl:!0,actions:v.actions,devices:g,onChange:e=>x(Ui(v,e))})]}),e(`div`,{children:[o(`p`,{className:`mb-1 text-xs font-medium uppercase text-foreground-subtle`,children:u(`flow.runMode.title`,`Overlap`)}),o(El,{value:Sl(v),onChange:e=>x(Cl(v,e))})]})]})})})}),o(mt,{headingId:`template-inputs`,title:u(`build.templates.inputs`,`Inputs`),children:o(`div`,{className:`p-3`,children:o(Am,{payload:m,readOnly:d,onChange:h})})})]}),!d&&!y.success&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:y.error.issues[0]?.message??``}),i!==null&&o(`p`,{role:`alert`,className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:i}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[!d&&e(X,{disabled:!b,onClick:()=>a(C()),"data-testid":`template-save`,children:[n&&o(S,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),d&&e(X,{onClick:()=>s(C()),"data-testid":`template-duplicate`,children:[o(_,{className:`h-4 w-4`,"aria-hidden":!0}),u(`remote.templates.duplicate`,`Duplicate`)]}),e(X,{variant:`outline`,disabled:!y.success,onClick:()=>{y.success&&Im(Lm(f),JSON.stringify(ve(f.trim(),y.data),null,2))},"data-testid":`template-export`,children:[o(B,{className:`h-4 w-4`,"aria-hidden":!0}),u(`build.templates.exportJson`,`Export JSON`)]}),o(X,{variant:`ghost`,onClick:l,disabled:n,children:u(`common.close`,`Close`)})]})]})}u();function zm(e){let t=H.safeParse(e.payload);return t.success?{id:e.id,name:e.name,payload:t.data,builtIn:e.builtIn===!0}:null}function Bm(e,t){return[...e.devices.length===0?[]:[t(`remote.templates.inUseMessage`,{devices:e.devices.map(e=>e.name).join(`, `)})],...e.automations.length===0?[]:[t(`build.templates.inUseAutomations`,{automations:e.automations.map(e=>e.name).join(`, `)})]]}function Vm({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),a=f(),l=Rn(),u=vn({}),d=ot(),p=br(),m=on(),h=j(),v=I(),[y,b]=c(null),[x,S]=c(null),[C,T]=c(!1),[E,D]=Un(),O=E.get(Gn),k=e=>{if(p.clearError(),e.kind===`automation`){b(null),S(zm(e));return}S(null),b({id:e.id,kind:e.kind,name:e.name,payload:e.payload})};s(()=>{t&&(T(!0),n?.())},[t,n]),s(()=>{if(O===null||u.data===void 0)return;let e=u.data.find(e=>e.id===O);e!==void 0&&k(e),D(e=>{let t=new URLSearchParams(e);return t.delete(Gn),t},{replace:!0})},[O,u.data,D]);let M=()=>void a.invalidateQueries({queryKey:[[`template`]]}),N=async e=>{await p.save(e)&&(b(null),S(null))},F=async e=>{try{let t=await d.mutateAsync({kind:e.kind,name:i(`remote.templates.copyName`,{name:e.name}),payload:e.payload});return M(),t.status===`saved`?t.template.id:null}catch(e){return await v({title:i(`remote.templates.duplicateFailed`),message:e instanceof Error?e.message:String(e),variant:`danger`}),null}},L=async e=>{let t=u.data?.find(t=>t.id===e.id);t!==void 0&&await F(t)!==null&&S(null)},R=async e=>{if(await h({title:i(`remote.templates.deleteTitle`,{name:e.name}),message:i(`remote.templates.deleteMessage`),confirmLabel:i(`common.delete`),variant:`danger`}))try{let t=await m.mutateAsync({id:e.id});if(t.status===`in-use`){await v({title:i(`remote.templates.inUseTitle`,{name:e.name}),message:Bm(t,i).join(` `),variant:`warning`});return}if(t.status===`read-only`){await v({title:i(`build.templates.readOnlyTitle`,{name:e.name}),message:i(`build.templates.readOnlyMessage`),variant:`warning`});return}M()}catch(e){await v({title:i(`remote.templates.deleteFailed`),message:e instanceof Error?e.message:String(e),variant:`danger`})}},z=r(()=>[{key:`name`,header:i(`remote.templates.name`),sortValue:e=>e.name.toLowerCase(),render:t=>e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`font-medium text-foreground`,children:t.name}),t.builtIn===!0&&o(J,{variant:`neutral`,children:i(`build.templates.builtIn`,`Built-in`)})]})},{key:`kind`,header:i(`remote.templates.kind.label`),sortValue:e=>e.kind,render:e=>o(J,{variant:`neutral`,children:pr(e.kind).label(i)})},{key:`summary`,header:i(`remote.templates.summary`),notSortableReason:`A sentence built from the payload.`,render:e=>o(`span`,{className:`text-foreground-muted`,children:pr(e.kind).summary(e.payload,i)})},{key:`updated`,header:i(`remote.templates.updated`),sortValue:e=>e.updatedAt,render:e=>o(`span`,{className:`text-foreground-muted`,children:e.builtIn===!0?``:new Date(e.updatedAt).toLocaleDateString()})},{key:`actions`,align:`right`,notSortableReason:`Row actions.`,render:e=>o(rn,{title:i(`remote.templates.actionsFor`,{name:e.name}),items:[...e.kind===`automation`?[{id:`create-automation`,label:i(`build.templates.createAutomation`,`Create automation`),icon:w,onClick:()=>void l(`/build?tab=automations&${Fu}=${encodeURIComponent(e.id)}`)}]:[],{id:`edit`,label:e.builtIn===!0?i(`build.templates.view`,`View`):i(`common.edit`),icon:A,onClick:()=>k(e)},{id:`duplicate`,label:i(`remote.templates.duplicate`),icon:_,onClick:()=>void F(e)},...e.builtIn===!0?[]:[{id:`delete`,label:i(`common.delete`),icon:g,danger:!0,onClick:()=>void R(e)}]]})}],[i]),B=u.data??[];return x===null?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`remote.templates.subtitle`)}),u.status===`error`?o(q,{title:i(`remote.templates.loadFailed`),message:u.error.message,onRetry:()=>void u.refetch()}):u.data===void 0?o(ct,{className:`h-32 w-full`}):B.length===0?o(dt,{icon:it,title:i(`remote.templates.emptyTitle`),description:i(`remote.templates.emptyDescription`),action:o(X,{size:`sm`,onClick:()=>T(!0),children:i(`remote.templates.new`)})}):o(Vt,{columns:z,rows:B,rowKey:e=>e.id,maxBodyHeight:vt,defaultSort:{columnKey:`name`,dir:`asc`},onRowClick:k}),o(vr,{draft:y,saving:p.saving,error:p.error,onSave:e=>void N(e),onClose:()=>b(null)}),o(wn,{open:C,onOpenChange:e=>!e&&T(!1),children:e(_t,{width:`md`,placement:`sheet-on-mobile`,children:[o(hn,{children:o(lt,{children:i(`remote.templates.new`)})}),e(Bt,{className:`space-y-2`,"data-testid":`new-template-chooser`,children:[e(X,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>{p.clearError(),T(!1),b({id:null,kind:`remote`,name:``,payload:pr(`remote`).emptyPayload()})},"data-testid":`new-template-remote`,children:[o(P,{className:`h-4 w-4 shrink-0`,"aria-hidden":!0}),e(`span`,{className:`block`,children:[o(`span`,{className:`block font-medium`,children:pr(`remote`).label(i)}),o(`span`,{className:`block text-xs text-foreground-muted`,children:i(`build.templates.newRemoteHint`,`The button layout of a remote.`)})]})]}),e(X,{variant:`outline`,className:`h-auto w-full justify-start whitespace-normal py-2 text-left`,onClick:()=>{p.clearError(),T(!1),S({id:null,name:``,payload:H.parse(pr(`automation`).emptyPayload()),builtIn:!1})},"data-testid":`new-template-automation`,children:[o(P,{className:`h-4 w-4 shrink-0`,"aria-hidden":!0}),e(`span`,{className:`block`,children:[o(`span`,{className:`block font-medium`,children:pr(`automation`).label(i)}),o(`span`,{className:`block text-xs text-foreground-muted`,children:i(`build.templates.newAutomationHint`,`An automation with inputs, so each copy only asks for its devices.`)})]})]})]})]})})]}):o(Rm,{template:x,saving:p.saving,error:p.error,onSave:e=>void N(e),onDuplicate:e=>void L(e),onClose:()=>S(null)},x.id??`new`)}var Hm=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`,`templates`];function Um(e){return e!==null&&Hm.some(t=>t===e)}var Wm=[`coreBlocks`,`list`,`build-counts`],Gm=[`schedulers`,`list`,`build-counts`],Km=[`actions`,`list`,`build-counts`],qm=[`block`,`action`,`scheduler`,`create`,`new`,`edit`,Fu];function Jm(e){return e.filter(e=>Ke(e)===`code`).length}function Ym(e){return e.filter(e=>Ar(e.code)).length}function Xm(e,t){return t===null?e:`${e} (${String(t)})`}function Zm(){let{t}=Q(),n=k(),[r,i]=Un(),a=r.get(`tab`),s=Um(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:Wm,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:Jm(u),f=u===void 0?null:Ym(u),p=l({queryKey:Km,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=l({queryKey:Gm,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})},w=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},T=s===`automations`?t(`build.newAutomation`,`New automation`):s===`actions`?t(`build.newAction`,`New action`):s===`schedulers`?t(`build.newScheduler`,`New scheduler`):s===`templates`?t(`build.newTemplate`,`New template`):t(`build.newScript`,`New script`),E=In(`/build`,{t,isAdmin:!0})??{icon:C,title:t(`nav.build`,`Build-your-self`)};return o(Kn,{icon:E.icon,title:E.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${E.title} sections`,fill:!0,actions:s===`custom-device`?e(X,{type:`button`,onClick:()=>S(`helper`),"data-testid":`build-new-composed`,children:[o(P,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(X,{type:`button`,onClick:x,"data-testid":`build-new`,children:[o(P,{className:`h-4 w-4`}),` `,T]}),sections:[{id:`automations`,label:Xm(t(`build.tabAutomations`,`Automations`),f),ownedParams:qm,content:o(zu,{onOpenScripts:y,createRequested:s===`automations`&&c,onCreateConsumed:w})},{id:`actions`,label:Xm(t(`build.tabActions`,`Actions`),m),ownedParams:qm,content:o(_l,{createRequested:s===`actions`&&c,onCreateConsumed:w})},{id:`schedulers`,label:Xm(t(`build.tabSchedulers`,`Schedulers`),g),ownedParams:qm,content:o(id,{createRequested:s===`schedulers`&&c,onCreateConsumed:w})},{id:`scripts`,label:Xm(t(`build.tabCode`,`Code`),d),ownedParams:qm,content:o($p,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:b,createRequested:s===`scripts`&&c,onCreateConsumed:w})},{id:`custom-device`,label:Xm(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:qm,content:o(Vd,{createRequested:s===`custom-device`&&c,onCreateConsumed:w})},{id:`templates`,label:t(`build.tabTemplates`,`Templates`),ownedParams:qm,content:o(Vm,{createRequested:s===`templates`&&c,onCreateConsumed:w})}]})}export{Zm as BuildPage};
|