@camstack/addon-admin-ui 1.2.447 → 1.2.449

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/assets/{AddonAssetIcon-4Dl3K5Yu.js → AddonAssetIcon-Rj3wnYY_.js} +1 -1
  2. package/dist/assets/Addons-WsKSFif5.js +4 -0
  3. package/dist/assets/{AdminPage-CTKQzYSK.js → AdminPage-C-diJ3HN.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-DB1wuvwM.js → AdminSectionedPage-B7UrSrns.js} +1 -1
  5. package/dist/assets/AiProfiles-BxHwvLTC.js +3 -0
  6. package/dist/assets/{BrokerForm-DgJKJJ9V.js → BrokerForm-DGyoc2rs.js} +1 -1
  7. package/dist/assets/Build-CWbm1ri9.js +40 -0
  8. package/dist/assets/Calendars-DuG_m8wt.js +1 -0
  9. package/dist/assets/{Cluster-CUFJA8Yh.js → Cluster-Cxo9fb5E.js} +1 -1
  10. package/dist/assets/{ClusterStepModel-G54nm4iG.js → ClusterStepModel-D7FHDo3b.js} +1 -1
  11. package/dist/assets/CompositionEditor-CW5KG78s.js +1 -0
  12. package/dist/assets/{CompositionEditorPage-DqCZgEdJ.js → CompositionEditorPage-C4wgJDTS.js} +1 -1
  13. package/dist/assets/Data-DrUKAnew.js +2 -0
  14. package/dist/assets/DeviceDetail-CgxNDsue.js +2 -0
  15. package/dist/assets/{DeviceDoActionFields-CU_AKA1W.js → DeviceDoActionFields-J1qr8JLD.js} +1 -1
  16. package/dist/assets/{Devices-CdmAtZP1.js → Devices-dusaAUzl.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-OyxmU511.js → EmbedPlayerPage-BuFLE2BZ.js} +1 -1
  18. package/dist/assets/History-D-IwtcW5.js +1 -0
  19. package/dist/assets/Identity-D-M8PFe5.js +1 -0
  20. package/dist/assets/IntegrationDetail-Cm6nS6Dd.js +1 -0
  21. package/dist/assets/IntegrationHub-jG5pe50x.js +1 -0
  22. package/dist/assets/Integrations-CIjceDno.js +1 -0
  23. package/dist/assets/Integrations-CuQ5m9xg.js +1 -0
  24. package/dist/assets/Library-B6dY6kqg.js +1 -0
  25. package/dist/assets/Locations-DcVyPbjW.js +3 -0
  26. package/dist/assets/{Logs-CaO5TsuY.js → Logs-CrcdhSoT.js} +1 -1
  27. package/dist/assets/{MaskShapeCanvas-CnazBudR.js → MaskShapeCanvas-D7B1a_d6.js} +1 -1
  28. package/dist/assets/{MotionZonesSettings-BcEiYvgb.js → MotionZonesSettings-Dv0SmFTj.js} +1 -1
  29. package/dist/assets/MyAccess-B1M-TD_l.js +2 -0
  30. package/dist/assets/{Network-BNthoi6m.js → Network-CNloyJcw.js} +1 -1
  31. package/dist/assets/{NodeAddonsSettingsPanel-CpONFsu0.js → NodeAddonsSettingsPanel-CGnlyS6W.js} +1 -1
  32. package/dist/assets/Notifications-DSQJwH9f.js +1 -0
  33. package/dist/assets/{PrivacyMaskSettings-B89MVHxL.js → PrivacyMaskSettings-ChKQKD1z.js} +1 -1
  34. package/dist/assets/Recordings-Bz4wjb-a.js +1 -0
  35. package/dist/assets/{ScanNetworkModal-B9n2JdTA.js → ScanNetworkModal-CLxLy0Jx.js} +1 -1
  36. package/dist/assets/{SceneMonitorEditor-Bmn_UcYs.js → SceneMonitorEditor-Dc0QrZZd.js} +1 -1
  37. package/dist/assets/SessionsList-D9f2zkon.js +2 -0
  38. package/dist/assets/{Showroom-BaHMWO3G.js → Showroom-lbpS7Xdx.js} +1 -1
  39. package/dist/assets/System-DLjh08cE.js +1 -0
  40. package/dist/assets/{Terminal-TaTeiXX0.js → Terminal-BKjM6jgI.js} +3 -3
  41. package/dist/assets/{Viewer-DXjhAdbS.js → Viewer-CykE8wsK.js} +1 -1
  42. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BYUIhxrf.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DJhucDeE.js} +1 -1
  43. package/dist/assets/{addon-icons-context-0MDrwtIo.js → addon-icons-context-BCJdR2as.js} +1 -1
  44. package/dist/assets/{archive-C3J7kPmp.js → archive-CnyG155u.js} +1 -1
  45. package/dist/assets/{authed-media-dGvmAGIm.js → authed-media-C0Di1-mt.js} +1 -1
  46. package/dist/assets/{bell-off-Df5MKmnk.js → bell-off-BCgckLrg.js} +1 -1
  47. package/dist/assets/{board-model-BVOHJW-k.js → board-model-BEF98n5Q.js} +1 -1
  48. package/dist/assets/{boxes-B4UVG1kT.js → boxes-uA3JVB9e.js} +1 -1
  49. package/dist/assets/circle-slash-CXSKoFJ3.js +1 -0
  50. package/dist/assets/client-CBY2Ai10.js +358 -0
  51. package/dist/assets/{cloud-upload-I7yc63rr.js → cloud-upload-C1akQpc4.js} +1 -1
  52. package/dist/assets/crop-CZVwalbq.js +1 -0
  53. package/dist/assets/{device-integration-icon-C_jsalSP.js → device-integration-icon-BwPIgj71.js} +1 -1
  54. package/dist/assets/device-picker-model-DspKRUOC.js +1 -0
  55. package/dist/assets/{dist-BOKrykX2.js → dist-DICOq93r.js} +1 -1
  56. package/dist/assets/dist-ucVPOol3.js +358 -0
  57. package/dist/assets/{eraser-WGJr5dAG.js → eraser-C_0A9Hjb.js} +1 -1
  58. package/dist/assets/{hard-drive-download-BqS2ahXp.js → hard-drive-download-B-DH1PV-.js} +1 -1
  59. package/dist/assets/{hostInit-Cn05saXf.js → hostInit-BEZmxPgL.js} +1 -1
  60. package/dist/assets/i18n-DBncQ6jl.js +1 -0
  61. package/dist/assets/{icons-BgfaaZCZ.js → icons-DprpVmeV.js} +1 -1
  62. package/dist/assets/{index-2_qB4G1l.js → index-DM2PlJTq.js} +3 -3
  63. package/dist/assets/{key-D741QkPA.js → key-CL8Jmw2S.js} +1 -1
  64. package/dist/assets/{key-round-_blTK3l4.js → key-round-C-Aw6TmA.js} +1 -1
  65. package/dist/assets/{layers-CBNWlTsd.js → layers-DSNZIEzf.js} +1 -1
  66. package/dist/assets/{linked-devices-model-Csh4WaVK.js → linked-devices-model-DzL0krEK.js} +1 -1
  67. package/dist/assets/{list-ordered-BTh8rts2.js → list-ordered-C1bZw0BL.js} +1 -1
  68. package/dist/assets/{location-owned-usage-Dqp8xgaw.js → location-owned-usage-dAl9CTze.js} +1 -1
  69. package/dist/assets/{log-in-Fh5saGuL.js → log-in-Ce7WBmUI.js} +1 -1
  70. package/dist/assets/{memory-stick-2qy4HWOo.js → memory-stick-DRGsvLsv.js} +1 -1
  71. package/dist/assets/{message-square-plus-D70FuCBB.js → message-square-plus-Cjk8neRy.js} +1 -1
  72. package/dist/assets/{mf-entry-bootstrap-0-1defdd87.js → mf-entry-bootstrap-0-2f4164ab.js} +2 -2
  73. package/dist/assets/{mic-off-MTwAUBdb.js → mic-off-CraNg8N9.js} +1 -1
  74. package/dist/assets/{monitor-off-Dn82QkPx.js → monitor-off-CgatD4nF.js} +1 -1
  75. package/dist/assets/{monitor-smartphone-K0Y4ODGq.js → monitor-smartphone-Ct9M1imf.js} +1 -1
  76. package/dist/assets/mount-DspKRUOC.js +1 -0
  77. package/dist/assets/notification-schedule-field-BJxF3SRn.js +1 -0
  78. package/dist/assets/{player-overlays-DyNPyo_W.js → player-overlays-B32sNiuW.js} +1 -1
  79. package/dist/assets/{recycle-DO1B1SCp.js → recycle-YQKD8v3i.js} +1 -1
  80. package/dist/assets/remoteEntry-Ba2ucEqQ.js +1 -0
  81. package/dist/assets/{scan-eye-DSsbXKWH.js → scan-eye-DkWYA8Qn.js} +1 -1
  82. package/dist/assets/{scissors-CGMgxeDq.js → scissors-d-Q62-mJ.js} +1 -1
  83. package/dist/assets/{search-x-CUa_1rys.js → search-x-Dh-cGhc7.js} +1 -1
  84. package/dist/assets/{send-CKZO6JbT.js → send-CUvOOMzH.js} +1 -1
  85. package/dist/assets/{settings-2-Dee5_Dd_.js → settings-2-DOLBKbT-.js} +1 -1
  86. package/dist/assets/{speaker-CGMtKx0N.js → speaker-GR-Ncblv.js} +1 -1
  87. package/dist/assets/src-wMLlETeo.js +67 -0
  88. package/dist/assets/{timer-reset-Dg8WnmrV.js → timer-reset-BSlB8Uty.js} +1 -1
  89. package/dist/assets/{ungroup-DqYydoru.js → ungroup-DlVR3lck.js} +1 -1
  90. package/dist/assets/{unlink-XIrgZrQf.js → unlink-CNQUhGTn.js} +1 -1
  91. package/dist/assets/{usb-33G087e5.js → usb-Bek6n_7R.js} +1 -1
  92. package/dist/assets/{use-scenes-feed-DsXuB27l.js → use-scenes-feed-v_NBqxW2.js} +1 -1
  93. package/dist/assets/{use-stationary-objects-D_FqXLHG.js → use-stationary-objects-CuK9Ramz.js} +1 -1
  94. package/dist/assets/useEventInvalidation-DspKRUOC.js +1 -0
  95. package/dist/assets/{useNodeUrlSelection-DWli8jTd.js → useNodeUrlSelection-WhpPPOny.js} +1 -1
  96. package/dist/assets/user-round-CtzL736C.js +1 -0
  97. package/dist/assets/{user-x-ODLis0Xn.js → user-x-B4ynO2HW.js} +1 -1
  98. package/dist/assets/{video-BtFmM3eg.js → video-JAYMKNkG.js} +1 -1
  99. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CHMiEHNO.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DHtR5Duv.js} +2 -2
  100. package/dist/index.html +10 -10
  101. package/dist/server/addon.js +27 -33
  102. package/package.json +1 -1
  103. package/dist/assets/Addons-D6G-9sO_.js +0 -4
  104. package/dist/assets/AiProfiles-DGYy6F5H.js +0 -3
  105. package/dist/assets/Build-ChuBRxJe.js +0 -40
  106. package/dist/assets/Calendars-DTLTaLNh.js +0 -1
  107. package/dist/assets/CompositionEditor-ZIvK82Sw.js +0 -1
  108. package/dist/assets/Data-Dt-vrsjS.js +0 -2
  109. package/dist/assets/DeviceDetail-B-JixtlL.js +0 -2
  110. package/dist/assets/History-CYEo0VmZ.js +0 -1
  111. package/dist/assets/Identity-CFqxjMZh.js +0 -1
  112. package/dist/assets/IntegrationDetail-Cv36j4Pb.js +0 -1
  113. package/dist/assets/IntegrationHub-Debcc46Y.js +0 -1
  114. package/dist/assets/Integrations-CTza89BR.js +0 -1
  115. package/dist/assets/Integrations-lU3DuymB.js +0 -1
  116. package/dist/assets/Library-D6P3tPHr.js +0 -1
  117. package/dist/assets/Locations-C0hvZIQb.js +0 -3
  118. package/dist/assets/MyAccess-CaTk0IGs.js +0 -2
  119. package/dist/assets/Notifications-WmYoCGsa.js +0 -1
  120. package/dist/assets/Recordings-BBu3Qb1s.js +0 -1
  121. package/dist/assets/SessionsList-D93VogSm.js +0 -2
  122. package/dist/assets/System-D-2Ma-Kz.js +0 -1
  123. package/dist/assets/circle-slash-BTU53Q69.js +0 -1
  124. package/dist/assets/client-CRCWO8cg.js +0 -358
  125. package/dist/assets/crop-B9ZtPXzr.js +0 -1
  126. package/dist/assets/device-picker-model-B0uThmDr.js +0 -1
  127. package/dist/assets/dist-C6cNUgRP.js +0 -358
  128. package/dist/assets/i18n-DzruZdmx.js +0 -1
  129. package/dist/assets/mount-B0uThmDr.js +0 -1
  130. package/dist/assets/notification-schedule-field-CeZmOaz1.js +0 -1
  131. package/dist/assets/remoteEntry-BiLc8a2-.js +0 -1
  132. package/dist/assets/src-_mtQMfPm.js +0 -67
  133. package/dist/assets/useEventInvalidation-B0uThmDr.js +0 -1
  134. package/dist/assets/user-round-CKL9ygyb.js +0 -1
@@ -1,40 +0,0 @@
1
- import{$ as e,B as t,G as n,J as r,L as i,N as a,S as o,T as s,a as c,b as l,q as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{An as p,Fn as m,It as h,Ji as g,Nt as _,Qi as v,Si as y,bi as b,ca as x,kn as S,mi as C,or as w,ot as T,pn as E,pt as D,vn as O,wr as k}from"./player-overlays-DyNPyo_W.js";import{Ar as A,Br as j,Cr as M,Fr as N,Hr as P,Ir as F,Li as I,Rr as L,Sr as R,Vr as z,Xr as B,Yt as V,br as H,xr as ee,zr as te}from"./client-CRCWO8cg.js";import{t as ne}from"./boxes-B4UVG1kT.js";import{n as re,r as ie,t as ae}from"./ungroup-DqYydoru.js";import{s as oe}from"./video-BtFmM3eg.js";import{Cu as U,Du as se,Er as ce,Eu as le,Ga as ue,Mn as de,Ou as W,Pr as G,Tu as fe,Wt as K,Zt as pe,_n as me,aa as he,ca as ge,da as _e,dt as ve,en as ye,fa as be,fr as xe,gn as Se,hr as q,ht as Ce,ia as we,la as Te,lt as Ee,ra as De,sr as Oe,ta as ke,ua as Ae,un as je}from"./src-_mtQMfPm.js";import{t as J}from"./i18n-DzruZdmx.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import{G as Me,Q as Ne,T as Pe,Z as X,nt as Fe,v as Ie,z as Le}from"./index-2_qB4G1l.js";import{t as Re}from"./AdminSectionedPage-DB1wuvwM.js";import{t as ze}from"./DeviceDoActionFields-CU_AKA1W.js";import{E as Be,O as Ve,t as He}from"./CompositionEditor-ZIvK82Sw.js";var Ue=`const AUTOMATION_RECIPE =`,We=`// EJECTED from the visual automation editor — this file is now hand-owned.
2
- // The recipe that produced it was removed with it, on purpose: while it was
3
- // here the editor could re-open this block and overwrite everything below.`;function Ge(e){return e.includes(Ue)}function Ke(e){let t=e.indexOf(Ue);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 qe(e){let t=Ke(e);if(t===null)return{ok:!1,reason:J.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:J.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=te.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?J.t(`helpers.recipeFromCode.schemaMismatch`):J.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function Je(e){let t=Ke(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)}${We}${e.slice(i)}`}e();var Ye=6e4;function Xe(){let e=ue({projection:`slim`});return n(()=>(e.data??[]).filter(e=>V(String(e.type))).map(e=>({id:e.id,name:e.name,stableId:e.stableId,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[e.data])}function Ze(e){let t=T();return c({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:Ye,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function Qe(e,t){return e.find(e=>e.cap===t)?.fields??[]}function Z({children:e}){return f(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function $e(e){let t=Ze(e.deviceId);if(t.data!==void 0)return Qe(t.data,e.cap).find(t=>t.path===e.fieldPath)}function et({value:e,devices:t,onChange:n}){let{t:r}=Y(),i=Ze(e.deviceId),a=i.data??[],s=Qe(a,e.cap);return o(l,{children:[o(`label`,{className:`min-w-[10rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.device`,`Device`)}),f(U,{value:String(e.deviceId),onChange:e=>n({deviceId:Number(e.target.value),cap:``,fieldPath:``}),options:[{value:`0`,label:r(`automation.fieldPicker.selectADevice`,`Select a device…`)},...t.map(e=>({value:String(e.id),label:e.name}))]})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.capability`,`Capability`)}),f(U,{value:e.cap,disabled:e.deviceId===0,onChange:t=>n({...e,cap:t.target.value,fieldPath:``}),options:[{value:``,label:tt(e.deviceId,a.length,i.isLoading)},...a.map(e=>({value:e.cap,label:e.cap}))]})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.field`,`Field`)}),f(U,{value:e.fieldPath,disabled:e.cap===``,onChange:t=>n({...e,fieldPath:t.target.value}),options:[{value:``,label:s.length===0?r(`automation.fieldPicker.noReadableFields`,`No readable fields`):r(`automation.fieldPicker.selectAField`,`Select a field…`)},...s.map(e=>({value:e.path,label:`${e.path} (${e.kind})`}))]})]})]})}function tt(e,t,n){return e===0?J.t(`automation.fieldPicker.pickDeviceFirst`):n?J.t(`automation.fieldPicker.readingDevice`):t===0?J.t(`automation.fieldPicker.noReadableCaps`):J.t(`automation.fieldPicker.selectCap`)}var nt=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function rt(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 nt}}function it(e){switch(e){case`eq`:return J.t(`helpers.recipeParts.op_eq`);case`ne`:return J.t(`helpers.recipeParts.op_ne`);case`gt`:return J.t(`helpers.recipeParts.op_gt`);case`gte`:return J.t(`helpers.recipeParts.op_gte`);case`lt`:return J.t(`helpers.recipeParts.op_lt`);case`lte`:return J.t(`helpers.recipeParts.op_lte`);case`contains`:return J.t(`helpers.recipeParts.op_contains`);default:return J.t(`helpers.recipeParts.op_in`)}}function at(e){return rt(e).map(e=>({value:e,label:it(e)}))}function ot(e){switch(e){case`device-state`:return J.t(`helpers.recipeParts.trigger_device_state`);case`device-event`:return J.t(`helpers.recipeParts.trigger_device_event`);case`schedule`:return J.t(`helpers.recipeParts.trigger_schedule`);default:return J.t(`helpers.recipeParts.trigger_manual`)}}var st={triggers:[],actions:[]};function ct(e){switch(e){case`device-state`:return{kind:e,deviceId:0,cap:``,fieldPath:``};case`device-event`:return{kind:e,category:``};case`schedule`:return{kind:e,cron:`0 30 23 * * *`};default:return{kind:`manual`}}}function lt(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
- `};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function ut(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function dt(){return{kind:`expression`,expr:``,bindings:{}}}function ft(e,t,n){return e.map((e,r)=>r===t?n:e)}function pt(e,t){return e.filter((e,n)=>n!==t)}function mt(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=pt(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function ht(e,t){return{...e,triggers:[...t]}}function gt(e,t){return{...e,actions:[...t]}}var _t=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function vt({actions:e,devices:t,devicesState:n=`answered`,onChange:r}){let{t:i}=Y();return o(`div`,{className:`space-y-2`,children:[e.length===0&&f(`p`,{className:`text-xs text-warning`,children:i(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),e.map((a,s)=>o(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(G,{variant:`default`,children:s+1}),o(`label`,{className:`w-40`,children:[f(Z,{children:i(`automation.actionList.step`,`Step`)}),f(U,{value:a.kind,onChange:t=>r(ft(e,s,lt(yt(t.target.value)))),options:_t.map(e=>({value:e.value,label:i(e.labelKey)}))})]}),o(`div`,{className:`ml-auto flex items-center gap-1`,children:[f(q,{variant:`ghost`,disabled:s===0,onClick:()=>r(mt(e,s,s-1)),title:i(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:f(g,{className:`h-3.5 w-3.5`})}),f(q,{variant:`ghost`,disabled:s===e.length-1,onClick:()=>r(mt(e,s,s+1)),title:i(`automation.actionList.runThisStepLater`,`Run this step later`),children:f(v,{className:`h-3.5 w-3.5`})}),f(q,{variant:`ghost`,onClick:()=>r(pt(e,s)),title:i(`automation.actionList.removeThisStep`,`Remove this step`),children:f(h,{className:`h-3.5 w-3.5`})})]})]}),a.kind===`wait`&&o(`label`,{className:`block w-32`,children:[f(Z,{children:i(`automation.actionList.seconds`,`Seconds`)}),f(W,{type:`number`,min:0,max:300,value:String(a.seconds),onChange:t=>r(ft(e,s,{kind:`wait`,seconds:Number(t.target.value)}))})]}),a.kind===`code`&&o(`label`,{className:`block`,children:[f(Z,{children:i(`automation.actionList.code`,`Code`)}),f(`textarea`,{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:a.code,spellCheck:!1,onChange:t=>r(ft(e,s,{kind:`code`,code:t.target.value}))}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.actionList.codeHint`,components:{code:f(`code`,{})}})})]}),a.kind===`cap`&&f(xt,{action:a,devices:t,devicesState:n,onChange:t=>r(ft(e,s,t))})]},`${a.kind}-${String(s)}`)),o(`div`,{className:`flex items-center gap-2`,children:[o(q,{variant:`outline`,onClick:()=>r([...e,lt(`cap`)]),children:[f(S,{className:`h-4 w-4`}),` `,i(`automation.actionList.addStep`)]}),e.length>1&&f(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function yt(e){return _t.find(t=>t.value===e)?.value??`cap`}function bt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function xt({action:e,devices:t,devicesState:n,onChange:r}){return f(ze,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:bt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function St({value:e,field:t,onChange:n}){let{t:r}=Y();return t?.kind===`boolean`?f(U,{value:e===!0?`true`:`false`,onChange:e=>n(e.target.value===`true`),options:[{value:`true`,label:r(`common.true`)},{value:`false`,label:r(`common.false`)}]}):t?.kind===`enum`&&t.enumValues!==void 0&&t.enumValues.length>0?f(U,{value:String(e),onChange:e=>n(e.target.value),options:t.enumValues.map(e=>({value:e,label:e}))}):t?.kind===`number`?f(W,{type:`number`,value:typeof e==`number`?String(e):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&n(t)}}):f(W,{value:String(e),placeholder:r(`common.valueWord`),onChange:e=>n(e.target.value)})}function Ct({value:e,field:t,onChange:n}){let{t:r}=Y();return f(W,{value:e.join(`, `),placeholder:r(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let r=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);n(t?.kind===`number`?r.map(e=>Number(e)).filter(e=>!Number.isNaN(e)):r)}})}function wt(e){return typeof e==`object`}function Tt(e){return wt(e)?e[0]??``:e}function Et(e){return wt(e)?e:typeof e==`boolean`?[]:[e]}function Dt({leaf:e,devices:t,onChange:n}){let{t:r}=Y(),i={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=$e(i),s=at(a?.kind),c=e.operator===`in`,l=t=>{n({...e,deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath})},u=t=>{let r=Ot(t,s);n({...e,operator:r,value:r===`in`?Et(e.value):Tt(e.value)})};return o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(et,{value:i,devices:t,onChange:l}),o(`label`,{className:`min-w-[8rem]`,children:[f(Z,{children:r(`automation.conditionRow.comparison`,`Comparison`)}),f(U,{value:e.operator,onChange:e=>u(e.target.value),options:s.map(e=>({value:e.value,label:e.label}))})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.conditionRow.value`,`Value`)}),c?f(Ct,{value:Et(e.value),field:a,onChange:t=>n({...e,value:t})}):f(St,{value:Tt(e.value),field:a,onChange:t=>n({...e,value:t})})]})]})}function Ot(e,t){return t.find(t=>t.value===e)?.value??`eq`}var kt={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function At({leaf:e,devices:t,onChange:n}){let{t:r}=Y(),i=Object.entries(e.bindings),a=t=>{n({kind:`expression`,expr:e.expr,bindings:t})};return o(`div`,{className:`space-y-2`,children:[o(`label`,{className:`block`,children:[f(Z,{children:r(`automation.expressionLeafRow.expression`,`Expression`)}),f(W,{value:e.expr,placeholder:r(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:t=>n({kind:`expression`,expr:t.target.value,bindings:e.bindings})}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:r(`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.`)})]}),o(`div`,{className:`space-y-1.5`,children:[i.length===0&&f(`p`,{className:`text-xs text-foreground-subtle`,children:r(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),i.map(([n,r])=>f(jt,{alias:n,source:r,devices:t,onRename:t=>a(Lt(e.bindings,n,t)),onChange:t=>a({...e.bindings,[n]:t}),onRemove:()=>a(Rt(e.bindings,n))},n)),o(q,{variant:`ghost`,onClick:()=>a({...e.bindings,[It(e.bindings)]:kt}),children:[f(S,{className:`h-3.5 w-3.5`}),` `,r(`common.name`)]})]})]})}function jt({alias:e,source:t,devices:n,onRename:r,onChange:i,onRemove:a}){let{t:s}=Y(),c=t.kind===`literal`,l=c?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Pt(n,Nt(t)),cap:t.cap,fieldPath:t.fieldPath};return o(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[o(`label`,{className:`w-32`,children:[f(Z,{children:s(`automation.expressionLeafRow.name`,`Name`)}),f(W,{value:e,placeholder:s(`automation.expressionLeafRow.aliasExample`),onChange:e=>r(e.target.value)})]}),o(`label`,{className:`w-36`,children:[f(Z,{children:s(`automation.expressionLeafRow.reads`,`Reads`)}),f(U,{value:c?`literal`:`global`,onChange:e=>i(e.target.value===`literal`?{kind:`literal`,value:``}:kt),options:[{value:`global`,label:s(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:s(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),c?o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:s(`automation.expressionLeafRow.constant`,`Constant`)}),f(W,{value:t.value===null?``:String(t.value),placeholder:`5`,onChange:e=>i({kind:`literal`,value:Mt(e.target.value)})})]}):f(et,{value:l,devices:n,onChange:e=>i({kind:`global`,sourceStableId:Ft(n,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),f(q,{variant:`ghost`,onClick:a,title:s(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:f(h,{className:`h-3.5 w-3.5`})})]})}function Mt(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Nt(e){return e.kind===`global`?e.sourceStableId:``}function Pt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Ft(e,t){return e.find(e=>e.id===t)?.stableId??``}function It(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 Lt(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Rt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function zt(e){return e.kind===`all`||e.kind===`any`}function Q(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:zt(t)?t:{kind:`all`,children:[t]}}function Bt(e,t){return t===null||zt(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Vt(e){return Bt(e,Q(e))}function Ht(e,t){if(t.length===0)return e;let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?Ht(e.child,r):null;if(!zt(e))return null;let i=e.children[n];return i===void 0?null:Ht(i,r)}function Ut(e,t,n){if(t.length===0)return n(e);let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=Ut(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!zt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Ut(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 Wt(e){return e===null?null:P({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function Gt(e){let t=Q(e);return{depth:t.children.length===0?0:j(t),leaves:t.children.length===0?0:z(t),depthLimit:3,leafLimit:32}}function Kt(e,t){let n=Wt(t);return n===null?{ok:!0,recipe:Bt(e,t)}:{ok:!1,reason:n}}function qt(e,t){let n=Q(e);return Kt(e,{kind:n.kind,children:[...n.children,t]})}function Jt(e,t,n){return Bt(e,Ut(Q(e),t,()=>n))}function Yt(e,t){return Bt(e,Ut(Q(e),t,()=>null))}function Xt(e,t,n){return Bt(e,Ut(Q(e),t,e=>zt(e)?{kind:n,children:e.children}:e))}function Zt(e,t){return Ht(Q(e),t)===null?{ok:!1,reason:J.t(`helpers.recipeOps.rowGone`)}:Kt(e,Ut(Q(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function Qt(e){if(e.length===0)return null;let t=e[e.length-1];return t===void 0?null:{path:e.slice(0,-1),index:t}}function $t(e,t,n){if(t.length<2)return{ok:!1,reason:J.t(`helpers.recipeOps.selectTwo`)};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:J.t(`helpers.recipeOps.differentGroups`)};let r=Qt(t[0]??[]);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.rootGroup`)};let i=Q(e),a=Ht(i,r.path);if(a===null||!zt(a))return{ok:!1,reason:J.t(`helpers.recipeOps.insideNot`)};let o=[...t.map(e=>e[e.length-1]??-1)].sort((e,t)=>e-t),s=o.map(e=>a.children[e]).filter(e=>e!==void 0);if(s.length!==o.length)return{ok:!1,reason:J.t(`helpers.recipeOps.selectedGone`)};let c=a.children.filter((e,t)=>!o.includes(t)),l=o[0]??0,u={kind:n,children:s},d={kind:a.kind,children:[...c.slice(0,l),u,...c.slice(l)]};return Kt(e,Ut(i,r.path,()=>d))}function en(e,t){if(t.length===0)return{ok:!1,reason:J.t(`helpers.recipeOps.outerNotGroup`)};let n=Q(e),r=Ht(n,t);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return Kt(e,Ut(n,t,()=>r.child));if(!zt(r))return{ok:!1,reason:J.t(`helpers.recipeOps.rowIsCondition`)};let i=Qt(t);if(i===null)return{ok:!1,reason:J.t(`helpers.recipeOps.noParent`)};let a=Ht(n,i.path);if(a===null||!zt(a))return{ok:!1,reason:J.t(`helpers.recipeOps.groupInNot`)};let o={kind:a.kind,children:[...a.children.slice(0,i.index),...r.children,...a.children.slice(i.index+1)]};return Kt(e,Ut(n,i.path,()=>o))}e();var tn=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function nn(e){return e.join(`/`)}function rn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function an({recipe:e,devices:t,onChange:i}){let{t:a}=Y(),[s,c]=r([]),[l,u]=r(null),d=Q(e),p=Gt(e),m=n(()=>s.map(rn),[s]),h=e=>{if(!e.ok){u(e.reason);return}u(null),c([]),i(e.recipe)},g=$t(e,m,`all`),_=$t(e,m,`any`),v=m.length===1?Zt(e,m[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},y={devices:t,selected:new Set(s),onToggleSelect:e=>c(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(t,n)=>i(Jt(e,t,n)),onRemove:t=>{c([]),i(Yt(e,t))},onSetKind:(t,n)=>i(Xt(e,t,n)),onUngroup:t=>h(en(e,t))};return o(`div`,{className:`space-y-2`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(G,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),f(`div`,{className:`w-32`,children:f(U,{value:d.kind,onChange:t=>i(Xt(e,[],on(t.target.value))),options:tn.map(e=>({value:e.value,label:a(e.labelKey)}))})}),f(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:p.depth,depthLimit:p.depthLimit,leaves:p.leaves,leafLimit:p.leafLimit})})]}),d.children.length===0?f(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.noConditionsTheActionsRun`,`No conditions. The actions run every time a trigger fires.`)}):f(sn,{container:d,path:[],handlers:y}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(q,{variant:`outline`,onClick:()=>h(qt(e,ut())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[f(S,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),o(q,{variant:`outline`,onClick:()=>h(qt(e,dt())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[f(ie,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),f(`span`,{className:`mx-1 h-5 w-px bg-border`}),f(q,{variant:`ghost`,disabled:!g.ok,onClick:()=>h(g),title:g.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):g.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),f(q,{variant:`ghost`,disabled:!_.ok,onClick:()=>h(_),title:_.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):_.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),f(q,{variant:`ghost`,disabled:!v.ok,onClick:()=>h(v),title:v.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):v.reason,children:`NOT`}),s.length>0&&f(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),l!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:l})]})}function on(e){return e===`any`?`any`:`all`}function sn({container:e,path:t,handlers:n}){return f(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>f(cn,{node:e,path:[...t,r],handlers:n},nn([...t,r])))})}function cn({node:e,path:t,handlers:n}){let{t:r}=Y(),i=nn(t),a=f(de,{checked:n.selected.has(i),onChange:()=>n.onToggleSelect(i),"aria-label":r(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return zt(e)?o(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[o(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[a,f(`div`,{className:`w-32`,children:f(U,{value:e.kind,onChange:e=>n.onSetKind(t,on(e.target.value)),options:tn.map(e=>({value:e.value,label:r(e.labelKey)}))})}),o(q,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:r(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[f(ae,{className:`h-3.5 w-3.5`}),` `,r(`automation.conditionTree.ungroup`)]}),f(q,{variant:`ghost`,onClick:()=>n.onRemove(t),title:r(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:f(h,{className:`h-3.5 w-3.5`})})]}),f(`div`,{className:`pl-4`,children:f(sn,{container:e,path:t,handlers:n})})]}):e.kind===`not`?o(`div`,{className:`rounded border border-border p-2`,children:[o(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[a,f(G,{variant:`warning`,children:`NOT`}),o(q,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:r(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[f(ae,{className:`h-3.5 w-3.5`}),` `,r(`automation.conditionTree.removeNot`)]})]}),f(`div`,{className:`pl-4`,children:f(cn,{node:e.child,path:[...t,0],handlers:n})})]}):o(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[f(`div`,{className:`pt-6`,children:a}),f(`div`,{className:`min-w-0 flex-1`,children:e.kind===`condition`?f(Dt,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)}):f(At,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)})}),f(q,{variant:`ghost`,onClick:()=>n.onRemove(t),title:r(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:f(h,{className:`h-3.5 w-3.5`})})]})}e();function ln({code:e,error:t,canEject:n,ejecting:i,onEject:a}){let{t:s}=Y(),[c,l]=r(!1),u=ce(),d=async()=>{await u({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 o(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[o(q,{variant:`ghost`,onClick:()=>l(!c),children:[f(c?y:b,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),f(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),o(q,{className:`ml-auto`,variant:`ghost`,disabled:!n||e===null||i,onClick:()=>void d(),title:n?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:[f(oe,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),c&&f(`div`,{className:`border-t border-border p-3`,children:e===null?f(`p`,{className:`text-xs text-warning`,children:t??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):f(je,{maxHeight:420,children:e})})]})}var un=[`device-state`,`device-event`,`schedule`,`manual`],dn=Object.values(I).sort((e,t)=>e.localeCompare(t));function fn({triggers:e,devices:t,onChange:n}){let{t:r}=Y();return o(`div`,{className:`space-y-2`,children:[e.length===0&&f(`p`,{className:`text-xs text-warning`,children:r(`automation.triggerEditor.noTriggersYetWithoutOne`,`No triggers yet. Without one nothing can ever start this automation — not even "Run actions", which needs a manual trigger to have somewhere to arrive.`)}),e.map((r,i)=>f(pn,{trigger:r,devices:t,position:i,onChange:t=>n(ft(e,i,t)),onRemove:()=>n(pt(e,i))},`${r.kind}-${String(i)}`)),o(q,{variant:`outline`,onClick:()=>n([...e,ct(`device-state`)]),title:r(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[f(S,{className:`h-4 w-4`}),` `,r(`automation.triggerEditor.trigger`)]})]})}function pn({trigger:e,devices:t,position:n,onChange:r,onRemove:i}){let{t:a}=Y();return o(`div`,{className:`rounded border border-border p-3`,children:[o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(G,{variant:`default`,children:n===0?a(`automation.triggerEditor.when`,`When`):a(`automation.triggerEditor.orWhen`,`or when`)}),o(`label`,{className:`min-w-[13rem] flex-1`,children:[f(Z,{children:a(`automation.triggerEditor.trigger`,`Trigger`)}),f(U,{value:e.kind,onChange:e=>r(ct(mn(e.target.value))),options:un.map(e=>({value:e,label:ot(e)}))})]}),f(q,{variant:`ghost`,onClick:i,title:a(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:f(h,{className:`h-4 w-4`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[e.kind===`device-state`&&f(gn,{trigger:e,devices:t,onChange:r}),e.kind===`device-event`&&f(vn,{trigger:e,devices:t,onChange:r}),e.kind===`schedule`&&o(`label`,{className:`min-w-[14rem] flex-1`,children:[f(Z,{children:a(`automation.triggerEditor.cronExpression`,`Cron expression`)}),f(W,{value:e.cron,placeholder:`0 30 23 * * *`,onChange:e=>r({kind:`schedule`,cron:e.target.value})}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:f(`code`,{})}})})]}),e.kind===`manual`&&f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:f(`strong`,{})}})})]})]})}function mn(e){return un.find(t=>t===e)??`manual`}function hn(e,t){return{kind:`device-state`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function gn({trigger:e,devices:t,onChange:n}){let{t:r}=Y(),i={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=$e(i),s={...e.becomes===void 0?{}:{becomes:e.becomes},...e.edge===void 0?{}:{edge:e.edge},...e.forMs===void 0?{}:{forMs:e.forMs},...e.debounceMs===void 0?{}:{debounceMs:e.debounceMs}};return o(l,{children:[f(et,{value:i,devices:t,onChange:e=>n(hn(e,s))}),o(`div`,{className:`min-w-[11rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.becomes`,`Becomes`)}),o(`div`,{className:`flex items-center gap-2`,children:[o(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[f(de,{checked:e.becomes===void 0,onChange:e=>n(hn(i,{...s,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),r(`automation.triggerEditor.anyChange`,`any change`)]}),e.becomes!==void 0&&f(St,{value:e.becomes,field:a,onChange:e=>n(hn(i,{...s,becomes:e}))})]})]}),o(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[f(de,{checked:e.edge===!0,onChange:e=>n(hn(i,{...s,...e.target.checked?{edge:!0}:{edge:void 0}}))}),r(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),o(`label`,{className:`w-28`,children:[f(Z,{children:r(`automation.triggerEditor.heldForS`,`Held for (s)`)}),f(W,{type:`number`,min:0,value:e.forMs===void 0?``:String(e.forMs/1e3),placeholder:`0`,onChange:e=>n(hn(i,{...s,forMs:_n(e.target.value)}))})]}),o(`label`,{className:`w-28`,children:[f(Z,{children:r(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),f(W,{type:`number`,min:0,value:e.debounceMs===void 0?``:String(e.debounceMs/1e3),placeholder:`0`,onChange:e=>n(hn(i,{...s,debounceMs:_n(e.target.value)}))})]})]})}function _n(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function vn({trigger:e,devices:t,onChange:n}){let{t:r}=Y();return o(l,{children:[o(`label`,{className:`min-w-[15rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.eventCategory`,`Event category`)}),f(U,{value:e.category,onChange:t=>n({kind:`device-event`,category:t.target.value,...e.deviceId===void 0?{}:{deviceId:e.deviceId}}),options:[{value:``,label:r(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...dn.map(e=>({value:e,label:e}))]})]}),o(`label`,{className:`min-w-[11rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.fromDevice`,`From device`)}),f(U,{value:e.deviceId===void 0?``:String(e.deviceId),onChange:t=>n({kind:`device-event`,category:e.category,...t.target.value===``?{}:{deviceId:Number(t.target.value)}}),options:[{value:``,label:r(`automation.triggerEditor.anyDevice`,`Any device`)},...t.map(e=>({value:String(e.id),label:e.name}))]})]})]})}e();var yn=`hub`;function bn({existing:e,initialRecipe:t,saving:i,saveError:a,ejecting:s,onSave:c,onEject:l,onCancel:u}){let{t:d}=Y(),[p,m]=r(e?.name??``),[h,g]=r(()=>Vt(t)),[_,v]=r(!1),y=Xe(),b=P(h),x=n(()=>Sn(h),[h]),S=n(()=>Cn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),C=p.trim()===``,T=C||b!==null||x!==null||S.code===null;return o(`div`,{className:`space-y-4`,children:[f(`div`,{className:`flex flex-wrap items-center gap-2`,children:f(G,{variant:`info`,children:d(`automation.automationEditor.runsOnTheHub`,`runs on the hub`)})}),o(`label`,{className:`block max-w-md text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:d(`automation.automationEditor.name`,`Name`)}),f(W,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:d(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),f(xn,{step:`1`,title:d(`automation.automationEditor.when`,`When`),subtitle:d(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:f(fn,{triggers:h.triggers,devices:y,onChange:e=>g(ht(h,e))})}),f(xn,{step:`2`,title:d(`automation.automationEditor.andOnlyIf`,`And only if`),subtitle:d(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:f(an,{recipe:h,devices:y,onChange:g})}),f(xn,{step:`3`,title:d(`automation.automationEditor.then`,`Then`),subtitle:d(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:f(vt,{actions:h.actions,devices:y,onChange:e=>g(gt(h,e))})}),f(ln,{code:S.code,error:S.error,canEject:e!==null,ejecting:s,onEject:l}),b!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:b}),b===null&&x!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x}),a!==null&&f(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(q,{onClick:()=>{S.code!==null&&c({name:p.trim(),code:S.code,enabled:e?.enabled??!0,placement:yn})},disabled:i||T,children:[i&&f(w,{className:`h-4 w-4 animate-spin`}),` `,d(`common.save`)]}),o(q,{variant:`ghost`,onClick:()=>v(!_),disabled:e===null,title:e===null?d(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):d(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,children:[f(E,{className:`h-4 w-4`}),` `,d(`common.logs`),` `,_?`▾`:`▸`]}),f(q,{variant:`ghost`,onClick:u,disabled:i,children:d(`common.close`,`Close`)}),C&&f(G,{variant:`warning`,children:d(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&e!==null&&o(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:H(e.id)},components:{code:f(`code`,{})}})}),f(pe,{addonId:H(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function xn({step:e,title:t,subtitle:n,children:r}){return o(`section`,{className:`border-l-2 border-border pl-4`,children:[o(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[f(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:e}),f(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:t}),f(`span`,{className:`text-xs text-foreground-subtle`,children:n})]}),r]})}function Sn(e){let t=te.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?J.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Cn(e,t){try{return{code:L({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function wn(e){if(!e.enabled)return{tone:`idle`,label:J.t(`helpers.coreBlockStatus.disabled`),detail:J.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:J.t(`helpers.coreBlockStatus.running`),detail:J.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??J.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??J.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??J.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Tn(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function En(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Dn(e){let t=e=>{let t=wn(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 On(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>wn(e).tone===`error`).length,n=e.filter(e=>wn(e).tone===`ok`).length,r=[J.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(J.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(J.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}function kn({block:e,busy:t,confirming:n,logsOpen:r,unreadable:i,onEdit:a,onToggle:s,onToggleLogs:c,onAskDelete:l,onCancelDelete:u,onConfirmDelete:d}){let g=x(),{t:_}=Y(),v=wn(e),y=K(e.updatedAt,g);return o(`li`,{className:`flex flex-col gap-2 p-3`,children:[o(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[o(`div`,{className:`min-w-0 flex-1`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(`span`,{className:`truncate font-medium`,children:e.name}),f(G,{variant:Tn(v.tone),children:v.label}),y!==null&&f(`span`,{className:`text-xs text-foreground-subtle`,children:_(`common.edited`,{when:y})})]}),f(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:v.detail}),i!==null&&f(`p`,{className:`mt-0.5 text-xs text-warning`,children:_(`automation.editor.listUnreadable`,{reason:i})})]}),n?o(`div`,{className:`flex justify-end gap-1`,children:[f(`span`,{className:`text-xs text-foreground-subtle`,children:_(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),f(q,{variant:`danger`,onClick:e=>{e.stopPropagation(),d()},disabled:t,children:_(`common.delete`,`Delete`)}),f(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},children:_(`common.cancel`,`Cancel`)})]}):o(`div`,{className:`flex justify-end gap-1`,children:[f(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),a()},disabled:i!==null,title:i===null?_(`common.edit`,`Edit`):_(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:f(m,{className:`h-4 w-4`})}),o(fe,{children:[f(se,{children:f(q,{variant:`ghost`,disabled:!0,title:_(`automation.automationList.runActions`,`Run actions`),children:f(p,{className:`h-4 w-4`})})}),f(le,{children:_(`automation.automationList.runningAnAutomationByHand`,`Running an automation by hand needs the automation-control authority, which is not wired up yet. There is deliberately no second way to execute one.`)})]}),f(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c()},title:_(`automation.automationList.logs`,`Logs`),children:f(E,{className:`h-4 w-4`})}),f(q,{variant:`ghost`,onClick:t=>{t.stopPropagation(),s(!e.enabled)},disabled:t,title:e.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`),children:e.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`)}),f(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:_(`common.delete`,`Delete`),children:f(h,{className:`h-4 w-4`})})]})]}),r&&o(`div`,{className:`rounded border border-border`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:H(e.id)},components:{code:f(`code`,{})}})}),f(pe,{addonId:H(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function An({onCreate:e}){let{t}=Y();return f(Oe,{children:o(`div`,{className:`space-y-2 p-4`,children:[f(`p`,{className:`text-sm text-foreground`,children:t(`automation.automationList.noAutomationsYet`,`No automations yet.`)}),f(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:t(`automation.automationList.anAutomationIsATrigger`,`An automation is a trigger, a set of conditions and a list of actions. It compiles to an ordinary block and runs in its own supervised process — there is no separate engine, so anything that goes wrong shows up here with a reason.`)}),f(q,{onClick:e,children:t(`automation.automationList.newAutomation`,`New automation`)})]})})}e();var jn=[`coreBlocks`,`list`],Mn=5e3;function Nn(e){return e instanceof Error?e.message:String(e)}function Pn({onOpenScripts:e,initialBlockId:i,onBlockIdChange:a,createRequested:s=!1,onCreateConsumed:l}){let{t:p}=Y(),m=T(),{state:h,openNew:g,openEdit:_,close:v}=Ee({editKey:`block`,newKey:`new`}),[y,b]=r(null),[x,S]=r(null),[C,w]=r(null),E=u(null),O=h.mode!==`closed`;t(()=>{s&&(b(null),g(),a?.(null),l?.())},[s,l,a,g]);let k=c({queryKey:jn,refetchInterval:Mn,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=()=>{k.refetch()},j=k.data;t(()=>{i===void 0||E.current===i||j?.find(e=>e.id===i&&Ge(e.code))!==void 0&&(E.current=i,_(i),a?.(i))},[i,j,_,a]);let M=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),A()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),A()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{S(null),A()}}),F=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:A}),I=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:Je(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:t=>{v(),b(null),A(),e(t.block.id)}}),L=k.data,R=Dn((L??[]).filter(e=>Ge(e.code))),z=L!==void 0&&R.length===0,B=h.mode===`edit`?R.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,V=h.mode===`new`||B===null?null:En(R,B),H=V===null?null:qe(V.code),ee=M.error===null?N.error===null?I.error===null?null:Nn(I.error):Nn(N.error):Nn(M.error),te=n(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=qe(e.code);return f(`ul`,{className:`list-none`,children:f(kn,{block:e,busy:F.isPending||P.isPending,confirming:x===e.id,logsOpen:C===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{b(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>w(C===e.id?null:e.id),onAskDelete:()=>S(e.id),onCancelDelete:()=>S(null),onConfirmDelete:()=>P.mutate(e.id)})})},sortValue:e=>e.name}],[x,C,a,_,P,F,p]);return o(`div`,{className:`space-y-3`,children:[f(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:On(R)}),k.error!=null&&f(xe,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Nn(k.error),onRetry:A}),z?f(An,{onCreate:()=>{b(null),g(),a?.(null)}}):f(Se,{columns:te,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:me,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{b(e),_(e.id),a?.(e.id)}}),f(ve,{open:O,onClose:()=>{M.reset(),N.reset(),I.reset(),b(null),v(),a?.(null)},title:V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:D,width:`xl`,testId:`automation-editor-panel`,children:f(bn,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:st,saving:M.isPending||N.isPending,saveError:ee,ejecting:I.isPending,onSave:e=>{V===null?M.mutate(e):N.mutate({blockId:V.id,block:e})},onEject:()=>{V!==null&&I.mutate(V)},onCancel:()=>{M.reset(),N.reset(),I.reset(),b(null),v(),a?.(null)}},V?.id??`new`)}),P.error!=null&&f(xe,{message:Nn(P.error)}),F.error!=null&&f(xe,{message:Nn(F.error)})]})}function Fn(e){return{state:`answered`,byRef:new Map(e.map(e=>[N(e),e]))}}function In(e,t){if(e.state!==`unanswered`)return e.byRef.get(N(t))??null}function Ln(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Rn(e){return F(e).map(e=>e.source)}function zn(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(...Rn(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Rn(e))}let r=new Set;return n.filter(e=>{let t=N(e);return r.has(t)?!1:(r.add(t),!0)})}function Bn(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:J.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[J.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[J.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??J.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function Vn(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Bn(e);case`degraded`:return{tone:`pending`,label:J.t(`helpers.compositionRows.degraded`),reason:n??J.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:J.t(`helpers.compositionRows.failed`),reason:n??J.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:J.t(`helpers.compositionRows.notRunning`),reason:n??J.t(`helpers.compositionRows.notRunningReason`)}}}function Hn(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:J.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:J.t(`helpers.compositionRows.unknown`),reason:J.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return Vn(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.notReported`),reason:J.t(`helpers.compositionRows.noRecord`,{stored:r})}}function Un(e){return N(e)}function Wn(e,t){let n=In(t,e);return{key:N(e),label:n?n.name:Un(e),presence:Ln(n),deviceId:n?n.id:null}}function Gn(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Kn(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:A(e.block.id),a=N(i),o=zn(e).filter(e=>N(e)!==a).map(e=>Wn(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=In(t,i),l=Gn(e),u=Hn(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}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=Ln(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Un(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function qn(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Jn(e,t){return qn(e)-qn(t)||e.name.localeCompare(t.name)}function Yn(e,t){let n=e.flatMap(e=>{let n=Kn(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Jn),customizations:n.filter(e=>e.kind===`customization`).toSorted(Jn)}}e();var Xn=1e4;function Zn(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Qn(e){let t=e.trim();return t===``?{}:{name:t}}function $n(){let e=Me();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:Zn(e.error)})}:Fn(e.data)}function er({createRequested:e=!1,onCreateConsumed:n}={}){let{t:r}=Y(),i=ge({},{refetchInterval:Xn}),a=$n(),s=Ee({editKey:`block`,newKey:`new`});t(()=>{e&&(s.openNew(),n?.())},[e]);let c=i.data;if(i.error!=null&&c===void 0)return f(xe,{title:r(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Zn(i.error),onRetry:()=>void i.refetch()});if(c===void 0)return f(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:r(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(c.state===`not-loaded`)return f(Oe,{children:o(`div`,{className:`space-y-1 p-4`,children:[f(`p`,{className:`text-sm text-warning`,children:r(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:[r(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),c.reason,`).`]})]})});let u=i.error==null?null:Zn(i.error),d=Yn(c.views,a),p=s.state.mode===`edit`?s.state.id:null,m=s.state.mode===`new`;return o(l,{children:[f(rr,{lists:d,fleet:a,refreshError:u,onEditComposed:e=>s.openEdit(e)}),f(ve,{open:m||p!==null,onClose:()=>s.close(),title:m?r(`build.customDeviceTab.newComposedDevice`,`New composed device`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:ne,width:`xl`,testId:`composed-device-editor`,children:m?f(tr,{onClose:()=>s.close(),onCreated:e=>{i.refetch(),s.openEdit(e)}}):p===null?null:f(nr,{blockId:p,onClose:()=>s.close(),onSaved:()=>void i.refetch()})})]})}function tr({onClose:e,onCreated:t}){let n=ke();return f(He,{initial:Ve(B.Sensor),blockId:null,deviceType:B.Sensor,nativeCaps:null,targetFields:null,showTemplates:!0,onCancel:e,save:async(e,r)=>{try{let{block:i}=await n.mutateAsync({block:{...Qn(r),enabled:!0,composition:e}});return t(i.id),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Zn(e)}}}})}function nr({blockId:e,onClose:t,onSaved:n}){let{t:r}=Y(),i=be(),a=he({blockId:e});if(a.status===`pending`)return f(`p`,{role:`status`,children:r(`compositionEditor.loading`)});if(a.status===`error`)return f(xe,{title:r(`compositionEditor.loadFailed`),message:a.error.message});if(a.data.state===`not-loaded`)return f(`p`,{role:`status`,children:r(`customize.status.notLoaded`,{reason:a.data.reason})});let o=a.data.view;if(o===null)return f(`p`,{children:r(`compositionEditor.notFound`,{blockId:e})});let s=ee(o.block);if(s===null)return f(`p`,{children:r(`compositionEditor.notComposition`)});if(s.target.kind===`existing`){let e=o.state.kind===`answered`?o.state.state?.deviceId??null:null;return e===null?f(`p`,{children:r(`compositionEditor.customizationUnknownDevice`)}):f(Ne,{className:`text-primary`,to:Ie(e),children:r(`compositionEditor.openOnDevice`)})}return f(He,{initial:Be(s,o.block.name),blockId:o.block.id,deviceType:s.target.type,nativeCaps:null,targetFields:null,onCancel:t,save:async(e,t)=>{try{return await i.mutateAsync({blockId:o.block.id,expectedUpdatedAt:o.block.updatedAt,block:{...Qn(t),composition:e}}),await a.refetch(),n(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Zn(e)}}}},`${o.block.id}@${o.block.updatedAt}`)}function rr({lists:e,fleet:t,refreshError:n,onEditComposed:r}){let{t:i}=Y();return o(`div`,{className:`space-y-4`,children:[n!==null&&o(`p`,{className:`text-xs text-warning`,children:[i(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,n]}),t.state===`unanswered`&&o(`p`,{className:`text-xs text-warning`,children:[i(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,t.reason,`. No source is marked missing until it has.`]}),f(ir,{title:i(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:i(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:e.composed,nameHeader:`Name`,emptyMessage:i(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,onEditComposed:r}),f(ir,{title:i(`build.customDeviceTab.customizations`,`Customizations`),hint:i(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:e.customizations,nameHeader:`Device`,emptyMessage:i(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,onEditComposed:r})]})}function ir({title:e,hint:t,rows:n,nameHeader:r,emptyMessage:i,kind:a,onEditComposed:s}){return o(`section`,{className:`space-y-2`,"aria-label":e,children:[o(`div`,{children:[f(`h3`,{className:`font-medium`,children:e}),f(`p`,{className:`text-xs text-foreground-subtle`,children:t})]}),f(Oe,{variant:`flat`,className:`p-0`,children:f(Se,{columns:ar(r,a,s),rows:n,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,maxBodyHeight:me,emptyMessage:i,onRowClick:a===`composed`?e=>s(e.blockId):void 0})})]})}function ar(e,t,n){let r=[{key:`name`,header:e,sortValue:e=>e.name.toLowerCase(),render:e=>f(or,{row:e})},{key:`type`,header:J.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>f(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??J.t(`common.unknownWord`)})},{key:`state`,header:J.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:e=>o(`div`,{className:`space-y-0.5`,children:[f(G,{variant:Tn(e.state.tone),children:e.state.label}),e.state.reason!==null&&f(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:e.state.reason})]})},{key:`sources`,header:J.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>f(cr,{sources:e.sources})}];return t===`composed`&&r.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>f(`div`,{className:`flex justify-end gap-1`,children:f(q,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),n(e.blockId)},children:J.t(`common.edit`,`Edit`)})})}),r}function or({row:e}){let{t}=Y();return o(`div`,{className:`space-y-0.5`,children:[f(sr,{row:e}),e.namePresence===`missing`&&f(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:t(`build.customDeviceTab.deviceMissing`,`device missing`)}),f(`p`,{className:`text-[11px] text-foreground-subtle`,children:e.features.join(`, `)})]})}function sr({row:e}){let{t}=Y();return e.kind===`composed`?f(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):e.reportedDeviceId===null?f(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:e.name})}):f(Ne,{to:Ie(e.reportedDeviceId),className:`text-xs text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:e.name})}function cr({sources:e}){let{t}=Y();return e.length===0?f(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):f(`ul`,{className:`space-y-0.5`,children:e.map(e=>o(`li`,{className:`text-xs`,children:[e.deviceId===null?f(`span`,{className:e.presence===`missing`?`text-danger`:`text-foreground`,children:e.label}):f(Ne,{to:`/devices/${String(e.deviceId)}`,className:`hover:underline`,children:e.label}),e.presence===`missing`&&f(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:t(`common.missing`)})]},e.key))})}function lr(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 ur(e){if(Array.isArray(e))return e}function dr(e,t,n){return(t=br(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fr(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 pr(){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 mr(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 hr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?mr(Object(n),!0).forEach(function(t){dr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function gr(e,t){if(e==null)return{};var n,r,i=_r(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 _r(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 vr(e,t){return ur(e)||fr(e,t)||xr(e,t)||pr()}function yr(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 br(e){var t=yr(e,`string`);return typeof t==`symbol`?t:t+``}function xr(e,t){if(e){if(typeof e==`string`)return lr(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)?lr(e,t):void 0}}function Sr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Cr(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 wr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cr(Object(n),!0).forEach(function(t){Sr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Tr(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Er(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 Dr(e){return{}.toString.call(e).includes(`Object`)}function Or(e){return!Object.keys(e).length}function kr(e){return typeof e==`function`}function Ar(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function jr(e,t){return Dr(t)||Ir(`changeType`),Object.keys(t).some(function(t){return!Ar(e,t)})&&Ir(`changeField`),t}function Mr(e){kr(e)||Ir(`selectorType`)}function Nr(e){kr(e)||Dr(e)||Ir(`handlerType`),Dr(e)&&Object.values(e).some(function(e){return!kr(e)})&&Ir(`handlersType`)}function Pr(e){e||Ir(`initialIsRequired`),Dr(e)||Ir(`initialType`),Or(e)&&Ir(`initialContent`)}function Fr(e,t){throw Error(e[t]||e.default)}var Ir=Er(Fr)({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"}),Lr={changes:jr,selector:Mr,handler:Nr,initial:Pr};function Rr(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Lr.initial(e),Lr.handler(t);var n={current:e},r=Er(Vr)(n,t),i=Er(Br)(n),a=Er(Lr.changes)(e),o=Er(zr)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Lr.selector(e),e(n.current)}function c(e){Tr(r,i,a,o)(e)}return[s,c]}function zr(e,t){return kr(t)?t(e.current):t}function Br(e,t){return e.current=wr(wr({},e.current),t),t}function Vr(e,t,n){return kr(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var Hr={create:Rr},Ur={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Wr(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 Gr(e){return{}.toString.call(e).includes(`Object`)}function Kr(e){return e||Xr(`configIsRequired`),Gr(e)||Xr(`configType`),e.urls?(qr(),{paths:{vs:e.urls.monacoBase}}):e}function qr(){console.warn(Yr.deprecation)}function Jr(e,t){throw Error(e[t]||e.default)}var Yr={configIsRequired:`the configuration object is required`,configType:`the configuration object should be an object`,default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
6
- You are using deprecated way of configuration.
7
-
8
- Instead of using
9
- monaco.config({ urls: { monacoBase: '...' } })
10
- use
11
- monaco.config({ paths: { vs: '...' } })
12
-
13
- For more please check the link https://github.com/suren-atoyan/monaco-loader#config
14
- `},Xr=Wr(Jr)(Yr),Zr={config:Kr},Qr=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function $r(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],$r(e[n],t[n]))}),hr(hr({},e),t)}var ei={type:`cancelation`,msg:`operation is manually canceled`};function ti(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(ei):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var ni=[`monaco`],ri=vr(Hr.create({config:Ur,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),ii=ri[0],ai=ri[1];function oi(e){var t=Zr.config(e),n=t.monaco,r=gr(t,ni);ai(function(e){return{config:$r(e.config,r),monaco:n}})}function si(){var e=ii(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(ai({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),ti(mi);if(window.monaco&&window.monaco.editor)return fi(window.monaco),e.resolve(window.monaco),ti(mi);Qr(ci,ui)(di)}return ti(mi)}function ci(e){return document.body.appendChild(e)}function li(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function ui(e){var t=ii(function(e){return{config:e.config,reject:e.reject}}),n=li(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function di(){var e=ii(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;fi(n),e.resolve(n)},function(t){e.reject(t)})}function fi(e){ii().monaco||ai({monaco:e})}function pi(){return ii(function(e){return e.monaco})}var mi=new Promise(function(e,t){return ai({resolve:e,reject:t})}),hi={config:oi,init:si,__getMonacoInstance:pi};e();var gi={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},_i={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function vi({children:e}){return s.createElement(`div`,{style:_i.container},e)}var yi=vi;function bi({width:e,height:t,isEditorReady:n,loading:r,_ref:i,className:a,wrapperProps:o}){return s.createElement(`section`,{style:{...gi.wrapper,width:e,height:t},...o},!n&&s.createElement(yi,null,r),s.createElement(`div`,{ref:i,style:{...gi.fullWidth,...!n&&gi.hide},className:a}))}var xi=a(bi);function Si(e){t(e,[])}var Ci=Si;function wi(e,n,r=!0){let i=u(!0);t(i.current||!r?()=>{i.current=!1}:e,n)}var $=wi;function Ti(){}function Ei(e,t,n,r){return Di(e,r)||Oi(e,t,n,r)}function Di(e,t){return e.editor.getModel(ki(e,t))}function Oi(e,t,n,r){return e.editor.createModel(t,n,r?ki(e,r):void 0)}function ki(e,t){return e.Uri.parse(t)}function Ai({original:e,modified:n,language:a,originalLanguage:o,modifiedLanguage:c,originalModelPath:l,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=Ti,onMount:S=Ti}){let[C,w]=r(!1),[T,E]=r(!0),D=u(null),O=u(null),k=u(null),A=u(S),j=u(x),M=u(!1);Ci(()=>{let e=hi.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?F():e.cancel()}),$(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=Ei(O.current,e||``,o||a||`text`,l||``);n!==t.getModel()&&t.setModel(n)}},[l],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=Ei(O.current,n||``,c||a||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(n||``):n!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:n||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[n],C),$(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||a||`text`),O.current.editor.setModelLanguage(t,c||a||`text`)},[a,o,c],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=i(()=>{if(!O.current)return;j.current(O.current);let t=Ei(O.current,e||``,o||a||`text`,l||``),r=Ei(O.current,n||``,c||a||`text`,d||``);D.current?.setModel({original:t,modified:r})},[a,n,c,e,o,l,d]),P=i(()=>{!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]);t(()=>{C&&A.current(D.current,O.current)},[C]),t(()=>{!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 s.createElement(xi,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}a(Ai);function ji(e){let n=u();return t(()=>{n.current=e},[e]),n.current}var Mi=ji,Ni=new Map;function Pi({defaultValue:e,defaultLanguage:n,defaultPath:a,value:o,language:c,path:l,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=Ti,onMount:C=Ti,onChange:w,onValidate:T=Ti}){let[E,D]=r(!1),[O,k]=r(!0),A=u(null),j=u(null),M=u(null),N=u(C),P=u(S),F=u(),I=u(o),L=Mi(l),R=u(!1),z=u(!1);Ci(()=>{let e=hi.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?V():e.cancel()}),$(()=>{let t=Ei(A.current,e||o||``,n||c||``,l||a||``);t!==j.current?.getModel()&&(g&&Ni.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(Ni.get(l)))},[l],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&c&&A.current?.editor.setModelLanguage(e,c)},[c],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let B=i(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=l||a,r=Ei(A.current,o||e||``,n||c||``,t||``);j.current=A.current?.editor.create(M.current,{model:r,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(Ni.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,n,a,o,c,l,m,h,g,d,f]);t(()=>{E&&N.current(j.current,A.current)},[E]),t(()=>{!O&&!E&&B()},[O,E,B]),I.current=o,t(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),t(()=>{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&&Ni.set(l,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return s.createElement(xi,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var Fi=a(Pi);e();function Ii(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 Li={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Ri(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Li}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function zi({value:e,onChange:n,extraLibs:r=[],path:a=`file:///block.ts`,onDiagnostics:o,readOnly:s=!1,heightPx:c=420,dark:l=!0}){let d=u(null),p=i((e,t)=>{if(d.current=t,Ri(t,r),o===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{o(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,o]);return t(()=>{let e=d.current;e!==null&&Ri(e,r)},[r]),f(Fi,{height:c,defaultLanguage:`typescript`,path:a,theme:l?`vs-dark`:`vs`,value:e,onChange:e=>n(e??``),onMount:p,options:{readOnly:s,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function Bi(e){return e.some(e=>e.severity>=8)}var Vi=[{id:`blank`,name:`Blank script`,get description(){return J.t(`helpers.buildExamples.blankDescription`)},entry:`main.ts`,files:{"main.ts":`import type { AddonContext } from '@camstack/types'
15
-
16
- /**
17
- * A core block. Runs in its own process, with the same \`ctx\` an addon gets.
18
- * Return a function to release whatever you took (timers, sockets, listeners).
19
- *
20
- * Declaring devices: import { reconcileBlockDevices, exposeBlockDevices } from
21
- * '@camstack/types' and hang them off the shared Blocks integration.
22
- */
23
- export default function block(ctx: AddonContext) {
24
- ctx.logger.info('hello from a core block')
25
-
26
- const timer = setInterval(() => {
27
- ctx.logger.info('tick')
28
- }, 60_000)
29
-
30
- return () => {
31
- clearInterval(timer)
32
- }
33
- }
34
- `}}];function Hi(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 Ui=Vi.find(e=>e.id===`blank`)?.files[`main.ts`]??`import type { AddonContext } from '@camstack/types'
35
-
36
- export default function block(ctx: AddonContext) {
37
- ctx.logger.info('hello from a core block')
38
- return () => undefined
39
- }
40
- `;function Wi({existing:e,dirty:t,saving:n,restarting:r}){return e===null?J.t(`helpers.restartGate.saveFirstNoProcess`):n?J.t(`helpers.restartGate.saving`):r?J.t(`helpers.restartGate.restarting`):t?J.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:J.t(`helpers.restartGate.disabled`)}e();var Gi=5e3;function Ki(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 qi({blockId:e}){let{t}=Y(),r=H(e),i=ue({addonId:r,projection:`slim`},{refetchInterval:Gi}),a=n(()=>Ki(i.data),[i.data]);return i.isLoading?o(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[f(w,{className:`h-3.5 w-3.5 animate-spin`}),` `,t(`build.scriptDevicesPanel.loading`)]}):i.isError?o(`p`,{className:`text-xs text-danger`,children:[t(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,i.error instanceof Error?i.error.message:String(i.error)]}):o(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[o(`div`,{className:`flex items-center justify-between gap-2`,children:[o(`div`,{children:[f(`h4`,{className:`text-sm font-medium`,children:t(`build.scriptDevicesPanel.devices`,`Devices`)}),f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:r},components:{code:f(`code`,{className:`text-[11px]`})}})})]}),f(G,{variant:`default`,children:a.length})]}),a.length===0?f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:f(`code`,{})}})}):f(`ul`,{className:`space-y-3`,children:a.map(e=>f(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${e.id}`,children:o(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[f(Ne,{to:`/devices/${String(e.id)}`,className:`text-sm font-medium hover:underline`,title:t(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:e.name}),f(G,{variant:`info`,style:`outline`,children:e.type}),e.stableId!==void 0&&o(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,f(`code`,{children:e.stableId})]}),o(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,e.id]})]})},e.id))})]})}e();function Ji(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 Yi(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 Xi(e){switch(e){case`refresh-channel-catalog`:return J.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return J.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return J.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return J.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return J.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return J.t(`build.scriptSettingsPanel.enableUnifi`)}}function Zi(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Qi(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function $i(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Zi(e);n!==null&&(t[n]=Qi(e))}return t}function ea(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function ta({blockId:e}){let{t}=Y(),a=T(),s=De({blockId:e},{retry:!1}),c=we({blockId:e},{refetchInterval:1e4,retry:!1}),l=_e({onSuccess:()=>{c.refetch()}}),u=Te(),d=Ae(),[p,m]=r(null),[h,g]=r(null),[_,v]=r(null),[y,b]=r(!1),x=ea(c.data)?c.data:null,S=n(()=>x===null?{}:$i(x),[x]),C=p??S,E=i(e=>{m(e)},[]),D=p!==null,O=i(()=>{p!==null&&(g(null),l.mutate({blockId:e,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[e,p,l]),k=i(async(t,n)=>{if(Ji(t)){b(!0),g(null),v(null);try{p!==null&&(await a.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:e,patch:p}),m(null)),await a.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:e,patch:Yi(t)}),s.data?.block?.enabled!==!0&&(await d.mutateAsync({blockId:e,enabled:!0}),v(Xi(t))),await u.mutateAsync({blockId:e}),await c.refetch(),t===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):t===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):t===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):t===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):t===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{b(!1)}}},[e,s.data?.block?.enabled,p,u,d,c,a.trpcClient.coreBlocks]);return c.isLoading?o(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[f(w,{className:`h-3.5 w-3.5 animate-spin`}),` `,t(`build.scriptSettingsPanel.loading`)]}):c.isError?o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[t(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,c.error instanceof Error?c.error.message:String(c.error)]}):x===null?null:o(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[o(`div`,{className:`flex items-center justify-between gap-2`,children:[o(`div`,{children:[f(`h4`,{className:`text-sm font-medium`,children:t(`build.scriptSettingsPanel.settings`,`Settings`)}),f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:f(`code`,{})}})})]}),o(q,{size:`sm`,variant:`primary`,onClick:O,disabled:!D||l.isPending||y,children:[l.isPending&&f(w,{className:`h-3.5 w-3.5 animate-spin`}),t(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),f(Le,{schema:x,values:C,onChange:E,onAction:k}),h===null?null:f(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:f(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}e();var na=`hub`;function ra({existing:e,typeDefs:t,typeDefsLoading:i,saving:a,saveError:s,restarting:c,restartError:u,onRestart:p,onSave:m,onCancel:h}){let{t:g}=Y(),v=T(),y=ce(),{resolvedMode:b}=ye(),x=M({code:e?.code??Ui,files:e?.files,entry:e?.entry}),[S,D]=r(e?.name??``),[k,A]=r(x.files),[j,N]=r(x.entry),[P,F]=r(x.entry),[I,L]=r(e?.placement??na),[R,z]=r(e?.integrationId??``),[B,V]=r([]),[ee,te]=r(!1),[ne,re]=r(`blank`),[ie,ae]=r(null),[oe,U]=r(``),se=k[P]??``,le=e=>{A(t=>({...t,[P]:e}))},ue=Object.keys(k).toSorted(),de=Vi.length>1,fe=n(()=>[...t?.libs??[],...Ii(k,P)],[t?.libs,k,P]),K=d({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:k,entry:j})}),me=n(()=>B.filter(e=>e.severity>=8),[B]),he=Bi(B),ge=S.trim()===``,_e=e===null?null:M(e),ve=e===null||_e===null||JSON.stringify(k)!==JSON.stringify(_e.files)||j!==_e.entry||S.trim()!==e.name||I!==e.placement||(R.trim()===``?void 0:R.trim())!==e.integrationId,be=()=>{K.reset(),m({name:S.trim(),files:k,entry:j,enabled:e?.enabled??!0,placement:I,...R.trim()===``?{}:{integrationId:R.trim()}})},xe=()=>{let e=Hi(Object.keys(k));A(t=>({...t,[e]:``})),F(e),ae(e),U(e)},Se=e=>{ae(e),U(e)},we=()=>{if(ie===null)return;let e=ie,t=oe.trim();if(ae(null),!(t===``||t===e)){if(k[t]!==void 0){F(t);return}A(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),j===e&&N(t),F(t)}},Te=async e=>{let t=Vi.find(t=>t.id===e);if(t===void 0)return;let n=Vi.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(k)===JSON.stringify(n.files)&&j===n.entry)&&!await y({title:g(`build.blockEditor.loadExample`,`Load example`),message:g(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:g(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(re(e),A({...t.files}),N(t.entry),F(t.entry),(S.trim()===``||ne===`blank`)&&D(t.id===`blank`?``:t.name))},Ee=e===null?null:wn(e),De=Wi({existing:e,dirty:ve,saving:a,restarting:c});return o(`div`,{className:`space-y-4`,children:[Ee!==null&&f(`div`,{className:`flex flex-wrap items-center gap-2`,children:f(G,{variant:Tn(Ee.tone),children:Ee.label})}),o(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.name`,`Name`)}),f(W,{className:`mt-1`,value:S,onChange:e=>D(e.target.value),placeholder:g(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),f(W,{className:`mt-1`,value:R,onChange:e=>z(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),e===null&&de&&o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),f(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:ne,onChange:e=>void Te(e.target.value),"data-testid":`script-example-select`,children:Vi.map(e=>o(`option`,{value:e.id,children:[e.name,` — `,e.description]},e.id))})]}),o(`div`,{children:[f(Ce,{selectedNodeId:I,onSelect:L,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),I!==na&&o(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[f(_,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),f(`span`,{children:f(X,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:f(`strong`,{})}})})]})]}),o(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[o(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[ue.map(e=>ie===e?f(W,{value:oe,onChange:e=>U(e.target.value),onBlur:()=>we(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),we()),e.key===`Escape`&&(e.preventDefault(),ae(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`)},e):o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs ${e===P?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>F(e),onDoubleClick:()=>Se(e),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${e}`,children:[e,e===j?` · ${g(`build.blockEditor.entry`)}`:``]},e)),f(`button`,{type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:xe,"data-testid":`script-file-add`,children:g(`build.blockEditor.file`,`+ file`)}),P!==j&&f(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>N(P),title:g(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:g(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?f(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:g(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):f(zi,{value:se,onChange:le,path:`file:///${P}`,extraLibs:fe,onDiagnostics:V,dark:b===`dark`,heightPx:560})]}),t!==void 0&&t.libs.length===0&&f(`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.`)}),me.length>0&&o(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[f(`p`,{className:`font-medium text-danger`,children:g(`build.blockEditor.errorsCannotSave`,{count:me.length})}),me.slice(0,5).map(e=>f(`p`,{className:`text-danger`,children:g(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),me.length>5&&f(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:me.length-5})})]}),K.data!==void 0&&(K.data.ok?o(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[f(C,{className:`h-3.5 w-3.5`}),` `,g(`build.blockEditor.compiledOk`)]}):o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[K.data.line!==void 0&&f(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(K.data.line)})}),K.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),K.error!==null&&o(`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:`),` `,ia(K.error)]}),s!==null&&f(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&f(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),e!==null&&o(`div`,{className:`space-y-3`,children:[f(ta,{blockId:e.id}),f(qi,{blockId:e.id})]}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(q,{variant:`outline`,onClick:()=>K.mutate(),disabled:K.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[K.isPending&&f(w,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),o(q,{onClick:be,disabled:a||he||ge,children:[a&&f(w,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),o(q,{variant:`outline`,onClick:()=>p?.(),disabled:De!==null||p===void 0,title:De??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[c?f(O,{className:`h-4 w-4 animate-spin`}):f(O,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),o(q,{variant:`ghost`,onClick:()=>te(!ee),title:g(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,children:[f(E,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,ee?`▾`:`▸`]}),f(q,{variant:`ghost`,onClick:h,disabled:a,children:g(`common.close`,`Close`)}),o(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[g(`build.blockEditor.errorsCount`,{count:me.length}),ve&&e!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),ge&&f(G,{variant:`warning`,children:g(`build.blockEditor.nameRequired`,`Name required`)})]}),ee&&o(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:e===null?g(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):f(l,{children:f(X,{i18nKey:`build.blockEditor.logsOf`,values:{id:H(e.id)},components:{code:f(`code`,{})}})})}),e!==null&&f(pe,{addonId:H(e.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function ia(e){return e instanceof Error?e.message:String(e)}e();var aa=[`coreBlocks`,`list`],oa=[`coreBlocks`,`getTypeDefs`],sa=5e3;function ca(e){return e instanceof Error?e.message:String(e)}function la({initialBlockId:e,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:s}={}){let l=x(),{t:p}=Y(),m=T(),{state:g,openNew:_,openEdit:v,close:y}=Ee({editKey:`block`,newKey:`new`}),[b,S]=r(null),[C,w]=r(null),[D,k]=r(null),A=c({queryKey:aa,refetchInterval:sa,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),j=g.mode!==`closed`,M=c({queryKey:oa,enabled:j,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),N=()=>{A.refetch()},P=u(null),F=A.data;t(()=>{e===void 0||P.current===e||F?.find(t=>t.id===e&&R(t)===`code`)!==void 0&&(P.current=e,v(e),i?.(e))},[e,F,v,i]),t(()=>{a&&(S(null),_(),i?.(null),s?.())},[a,s,i,_]);let I=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{S(e.block),v(e.block.id),i?.(e.block.id),N()}}),L=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{S(e.block),v(e.block.id),i?.(e.block.id),N()}}),z=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{w(null),N()}}),B=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:N}),V=d({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:N}),ee=Dn((A.data??[]).filter(e=>R(e)===`code`)),te=A.data!==void 0&&ee.length===0,ne=I.isPending||L.isPending,ie=I.error===null?L.error===null?null:ca(L.error):ca(I.error),ae=g.mode===`edit`?ee.find(e=>e.id===g.id)??(b!==null&&b.id===g.id?b:null):null,oe=g.mode===`new`||ae===null?null:En(ee,ae),U=n(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:e=>{let t=wn(e),n=K(e.updatedAt,l);return o(`div`,{className:`min-w-0`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(`span`,{className:`truncate font-medium`,children:e.name}),f(G,{variant:Tn(t.tone),children:t.label}),f(G,{variant:`info`,children:e.placement}),n!==null&&f(`span`,{className:`text-xs text-foreground-subtle`,children:p(`common.edited`,{when:n})})]}),f(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.detail}),D===e.id&&o(`div`,{className:`mt-2 rounded border border-border`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:H(e.id)},components:{code:f(`code`,{})}})}),f(pe,{addonId:H(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=B.isPending||z.isPending,n=V.isPending&&V.variables===e.id;return C===e.id?o(`div`,{className:`flex justify-end gap-1`,children:[f(`span`,{className:`text-xs text-foreground-subtle`,children:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`)}),f(q,{variant:`danger`,onClick:()=>z.mutate(e.id),disabled:t,children:p(`common.delete`,`Delete`)}),f(q,{variant:`ghost`,onClick:()=>w(null),children:p(`common.cancel`,`Cancel`)})]}):o(`div`,{className:`flex justify-end gap-1`,children:[f(q,{variant:`ghost`,onClick:t=>{t.stopPropagation(),S(e),v(e.id),i?.(e.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),f(q,{variant:`ghost`,onClick:t=>{t.stopPropagation(),V.mutate(e.id)},disabled:t||n||!e.enabled,title:e.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:f(O,{className:`h-4 w-4${n?` animate-spin`:``}`})}),f(q,{variant:`ghost`,onClick:t=>{t.stopPropagation(),k(D===e.id?null:e.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:f(E,{className:`h-4 w-4`})}),f(q,{variant:`ghost`,onClick:t=>{t.stopPropagation(),B.mutate({blockId:e.id,enabled:!e.enabled})},disabled:t,title:e.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`),children:e.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`)}),f(q,{variant:`ghost`,onClick:t=>{t.stopPropagation(),w(e.id)},title:p(`common.delete`,`Delete`),children:f(h,{className:`h-4 w-4`})})]})}}],[C,D,i,v,z,V.isPending,V.variables,B,p]);return o(`div`,{className:`space-y-3`,children:[f(`p`,{className:`text-xs text-foreground-subtle`,children:A.data===void 0?``:On(ee)}),A.error!=null&&f(xe,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:ca(A.error),onRetry:N}),f(Se,{columns:U,rows:ee,rowKey:e=>e.id,pageSize:25,maxBodyHeight:me,emptyMessage:te?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):A.data===void 0?p(`build.scriptsTab.loadingScripts`,`Loading scripts…`):p(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{S(e),v(e.id),i?.(e.id)}}),f(ve,{open:j,onClose:()=>{I.reset(),L.reset(),V.reset(),S(null),y(),i?.(null)},title:oe===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:oe.name}),icon:re,width:`xl`,testId:`script-editor-panel`,children:f(ra,{existing:oe,typeDefs:M.data,typeDefsLoading:M.isLoading,saving:ne,saveError:ie,restarting:V.isPending,restartError:V.error===null?null:ca(V.error),onRestart:oe===null?void 0:()=>V.mutate(oe.id),onSave:e=>{let t=oe;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),V.reset(),S(null),y(),i?.(null)}})}),z.error!=null&&f(xe,{message:ca(z.error)}),B.error!=null&&f(xe,{message:ca(B.error)}),V.error!=null&&f(xe,{message:ca(V.error)})]})}var ua=[`automations`,`scripts`,`custom-device`];function da(e){return e!==null&&ua.some(t=>t===e)}var fa=[`coreBlocks`,`list`,`build-counts`],pa=[`block`,`create`];function ma(e){return e.filter(e=>R(e)===`code`).length}function ha(e){return e.filter(e=>Ge(e.code)).length}function ga(e,t){return t===null?e:`${e} (${String(t)})`}function _a(){let{t:e}=Y(),t=T(),[n,r]=Fe(),i=n.get(`tab`),a=da(i)?i:`automations`,s=n.get(`create`)===`1`,l=c({queryKey:fa,refetchInterval:5e3,queryFn:async()=>(await t.trpcClient.coreBlocks.list.query({})).blocks}).data,u=l===void 0?null:ma(l),d=l===void 0?null:ha(l),p=c({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>t.trpcClient.coreBlocks.listCompositions.query({})}),m=p.data?.state===`loaded`?p.data.views.length:null,h=e=>{r(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})},g=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`automations`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},_=e=>{r(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})},v=()=>{r(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},y=()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`create`),t},{replace:!0})},b=a===`automations`?`New automation`:a===`scripts`?`New script`:`New composition`,x=Pe(`/build`,{t:e,isAdmin:!0})??{icon:k,title:e(`nav.build`,`Build-your-self`)};return f(Re,{icon:x.icon,title:x.title,subtitle:e(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${x.title} sections`,fill:!0,actions:o(q,{type:`button`,onClick:v,"data-testid":`build-new`,children:[f(S,{className:`h-4 w-4`}),` `,b]}),sections:[{id:`automations`,label:ga(`Automations`,d),ownedParams:pa,content:f(Pn,{onOpenScripts:h,initialBlockId:a===`automations`?n.get(`block`)??void 0:void 0,onBlockIdChange:g,createRequested:a===`automations`&&s,onCreateConsumed:y})},{id:`scripts`,label:ga(`Scripts`,u),ownedParams:pa,content:f(la,{initialBlockId:a===`scripts`?n.get(`block`)??void 0:void 0,onBlockIdChange:_,createRequested:a===`scripts`&&s,onCreateConsumed:y})},{id:`custom-device`,label:ga(`Custom Device`,m),ownedParams:pa,content:f(er,{createRequested:a===`custom-device`&&s,onCreateConsumed:y})}]})}export{_a as BuildPage};
@@ -1 +0,0 @@
1
- import{$ as e,G as t,J as n,L as r,S as i,b as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{bi as s,xi as c}from"./player-overlays-DyNPyo_W.js";import{Tn as l,wn as u}from"./client-CRCWO8cg.js";import{h as d}from"./video-BtFmM3eg.js";import{$i as f,$n as p,Qi as m,Qn as h,Zi as g,ea as _,er as v,hr as y,ir as b,nr as x,rr as S}from"./src-_mtQMfPm.js";import{t as C}from"./i18n-DzruZdmx.js";import{t as w}from"./useTranslation-D3Is_4B6.js";import{Q as T,Z as E}from"./index-2_qB4G1l.js";import{t as D}from"./AdminPage-CTKQzYSK.js";e();var O=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function k(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function A(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function j(e){let t=e.getDay();return k(A(e,t===0?-6:1-t))}function M(e,t){if(t===`day`){let t=k(e);return{startMs:t.getTime(),endMs:A(t,1).getTime()}}if(t===`week`){let t=j(e);return{startMs:t.getTime(),endMs:A(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=j(n),a=A(j(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function N(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=j(e),n=A(t,6),r={month:`short`,day:`numeric`};return`${t.toLocaleDateString(void 0,r)} – ${n.toLocaleDateString(void 0,{...r,year:`numeric`})}`}return e.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}function P(e,t,n){return t===`day`?A(e,n):t===`week`?A(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function F(e,t){if(t===void 0)return e;let n=t.calendars[e.id];return n===void 0?e:{...e,visible:n.visible??e.visible,color:n.color??e.defaultColor}}function I(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function L(e){if(e.allDay===!0)return C.t(`systemPage.calendars.allDay`);let t=new Date(e.startMs),n=new Date(e.endMs),r={hour:`2-digit`,minute:`2-digit`};return`${t.toLocaleTimeString([],r)} – ${n.toLocaleTimeString([],r)}`}function R(e){let t=u(e),n=new Date(t.startMs),r=new Date(t.endMs),i={weekday:`short`,year:`numeric`,month:`short`,day:`numeric`};if(e.allDay===!0){let e=k(n),t=A(k(r),-1);return H(e,t)?C.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):C.t(`systemPage.calendars.rangeAllDay`,{from:n.toLocaleDateString(void 0,i),to:t.toLocaleDateString(void 0,i)})}let a={hour:`2-digit`,minute:`2-digit`};return H(n,r)?`${n.toLocaleDateString(void 0,i)} · ${n.toLocaleTimeString([],a)} – ${r.toLocaleTimeString([],a)}`:`${n.toLocaleString(void 0,{...i,...a})} – ${r.toLocaleString(void 0,{...i,...a})}`}function z({label:e,children:t}){return i(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[o(`dt`,{className:`text-foreground-subtle`,children:e}),o(`dd`,{className:`min-w-0 break-words text-foreground`,children:t})]})}function B({ev:e,calendarName:t,color:n,onClose:r}){let{t:a}=w();return o(h,{open:!0,onOpenChange:e=>!e&&r(),children:i(v,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[o(S,{children:i(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[o(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:n},"aria-hidden":!0}),o(b,{className:`min-w-0 break-words`,children:e.title})]})}),o(p,{children:i(`dl`,{className:`space-y-3`,children:[o(z,{label:a(`systemPage.calendars.when`,`When`),children:R(e)}),o(z,{label:a(`systemPage.calendars.calendar`,`Calendar`),children:t}),e.location!==void 0&&e.location.length>0?o(z,{label:a(`systemPage.calendars.location`,`Location`),children:e.location}):null,e.description!==void 0&&e.description.length>0?o(z,{label:a(`systemPage.calendars.description`,`Description`),children:o(`span`,{className:`whitespace-pre-wrap`,children:e.description})}):null]})}),o(x,{children:o(y,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:a(`common.close`,`Close`)})})]})})}function V(e,t){return e.filter(e=>l(e,t))}function H(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function U({mode:e,onChange:t}){let{t:n}=w(),r=[{id:`month`,label:n(`systemPage.calendars.month`,`Month`)},{id:`week`,label:n(`systemPage.calendars.week`,`Week`)},{id:`day`,label:n(`systemPage.calendars.day`,`Day`)}];return o(`div`,{className:`inline-flex rounded-lg border border-border bg-surface p-0.5`,role:`group`,"aria-label":n(`systemPage.calendars.calendarView`,`Calendar view`),children:r.map(n=>o(`button`,{type:`button`,className:e===n.id?`rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground`:`rounded-md px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground`,"aria-pressed":e===n.id,onClick:()=>t(n.id),"data-testid":`calendars-view-${n.id}`,children:n.label},n.id))})}function W({calendars:e,onToggleVisible:t,onColorChange:n,busy:r}){let{t:a}=w();return i(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[o(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:a(`systemPage.calendars.calendars`,`Calendars`)}),o(`ul`,{className:`space-y-1`,children:e.map(e=>i(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface`,children:[o(`input`,{type:`checkbox`,className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:e.visible,disabled:r,onChange:n=>t(e.id,n.target.checked),"aria-label":a(`systemPage.calendars.show`,`Show {{name}}`,{name:e.name}),"data-testid":`calendars-visible-${e.id}`}),o(`input`,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:e.color,disabled:r,onChange:t=>n(e.id,t.target.value.toUpperCase()),"aria-label":a(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:e.name}),"data-testid":`calendars-color-${e.id}`}),i(`div`,{className:`min-w-0 flex-1`,children:[o(`div`,{className:`truncate text-sm font-medium ${e.visible?`text-foreground`:`text-foreground-subtle`}`,children:e.name}),i(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[I(e),e.enabled?``:` · ${a(`systemPage.calendars.unavailableAtSource`)}`]})]})]},e.id))})]})}function G({ev:e,color:t,compact:n,onSelect:r}){return o(`button`,{type:`button`,className:n?`block w-full truncate rounded px-1 py-0.5 text-left text-[10px] leading-tight text-white hover:brightness-110`:`block w-full rounded-md px-2 py-1.5 text-left text-xs text-white hover:brightness-110`,style:{backgroundColor:t},title:e.title,onClick:()=>r(e),"data-testid":`calendars-event-${e.id}`,children:n?e.title:i(a,{children:[o(`div`,{className:`font-medium`,children:e.title}),o(`div`,{className:`opacity-90`,children:L(e)})]})})}function K({anchor:e,events:t,colorById:n,today:r,onSelectEvent:a}){let{t:s}=w(),{startMs:c,endMs:l}=M(e,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=A(e,1))u.push(e);let d=e.getMonth();return i(`div`,{"data-testid":`calendars-month`,children:[o(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:O.map(e=>o(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),o(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(e=>{let c=k(e).getTime(),l=V(t,c),u=e.getMonth()!==d,f=H(e,r);return i(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[o(`div`,{className:f?`mb-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] font-semibold text-primary-foreground`:`mb-1 text-[11px] font-medium text-foreground-subtle`,children:e.getDate()}),i(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>o(G,{ev:e,color:n.get(e.calendarId)??`#64748B`,compact:!0,onSelect:a},e.id)),l.length>3?o(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function q({anchor:e,events:t,colorById:n,today:r,onSelectEvent:a}){let s=j(e);return o(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-7 sm:gap-px sm:overflow-hidden sm:rounded-lg sm:border sm:border-border sm:bg-border`,"data-testid":`calendars-week`,children:Array.from({length:7},(e,t)=>A(s,t)).map(e=>{let s=k(e).getTime(),c=V(t,s);return i(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[o(`div`,{className:H(e,r)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:e.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),o(`div`,{className:`space-y-1`,children:c.length===0?o(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>o(G,{ev:e,color:n.get(e.calendarId)??`#64748B`,onSelect:a},e.id))})]},s)})})}function J({anchor:e,events:t,colorById:n,calName:r,onSelectEvent:a}){let{t:s}=w(),c=V(t,k(e).getTime());return c.length===0?o(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):o(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(e=>o(`li`,{children:i(`button`,{type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>a(e),"data-testid":`calendars-event-${e.id}`,children:[o(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:n.get(e.calendarId)??`#64748B`}}),i(`div`,{className:`min-w-0`,children:[o(`div`,{className:`font-medium text-sm text-foreground`,children:e.title}),i(`div`,{className:`text-xs text-foreground-subtle`,children:[L(e),` · `,r.get(e.calendarId)??e.calendarId]}),e.location!==void 0&&e.location.length>0?o(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:e.location}):null]})]})},e.id))})}function Y(){let{t:e}=w(),a=m(),l=g({}),u=_(),[p,h]=n(`month`),[v,y]=n(()=>k(new Date)),[b,x]=n(null),S=t(()=>k(new Date),[]),C=a.isSuccess,O=l.isSuccess&&l.data!==void 0?l.data:void 0,A=t(()=>!C||a.data===void 0?[]:a.data.map(e=>F(e,O)),[C,a.data,O]),j=t(()=>A.filter(e=>e.visible),[A]),I=t(()=>j.map(e=>e.id),[j]),L=t(()=>M(v,p),[v,p]),R=f({startMs:L.startMs,endMs:L.endMs,calendarIds:[...I]},{enabled:C&&I.length>0}),z=R.data??[],V=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.color);return e},[A]),H=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.name);return e},[A]),G=r((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>l.refetch())},[l,u]),Y=r((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>l.refetch())},[l,u]),X=r(()=>y(k(new Date)),[]),Z=r(()=>y(e=>P(e,p,-1)),[p]),ee=r(()=>y(e=>P(e,p,1)),[p]),Q=`inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border bg-surface text-foreground hover:bg-primary/5 disabled:opacity-50`,$;return $=a.isPending?o(`p`,{className:`text-sm text-foreground-subtle`,children:e(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):a.isError?i(`p`,{className:`text-sm text-destructive`,children:[e(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,a.error.message]}):A.length===0?o(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:o(E,{i18nKey:`systemPage.calendars.emptySources`,components:{link:o(T,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):I.length===0?i(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[o(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),o(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:e(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):i(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[o(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),i(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(U,{mode:p,onChange:h}),i(`div`,{className:`flex items-center gap-1`,children:[o(`button`,{type:`button`,className:Q,onClick:Z,"aria-label":e(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:o(c,{className:`h-4 w-4`})}),o(`button`,{type:`button`,className:`inline-flex items-center rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5`,onClick:X,"data-testid":`calendars-today`,children:e(`systemPage.calendars.today`,`Today`)}),o(`button`,{type:`button`,className:Q,onClick:ee,"aria-label":e(`common.next`,`Next`),"data-testid":`calendars-next`,children:o(s,{className:`h-4 w-4`})})]}),o(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:N(v,p)})]}),R.isPending?o(`p`,{className:`text-sm text-foreground-subtle`,children:e(`systemPage.calendars.loadingEvents`,`Loading events…`)}):R.isError?i(`p`,{className:`text-sm text-destructive`,children:[e(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,R.error.message]}):p===`month`?o(K,{anchor:v,events:z,colorById:V,today:S,onSelectEvent:x}):p===`week`?o(q,{anchor:v,events:z,colorById:V,today:S,onSelectEvent:x}):o(J,{anchor:v,events:z,colorById:V,calName:H,onSelectEvent:x})]})]}),i(D,{icon:d,title:e(`systemPage.calendars.calendars`,`Calendars`),subtitle:e(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[$,b===null?null:o(B,{ev:b,calendarName:H.get(b.calendarId)??b.calendarId,color:V.get(b.calendarId)??`#64748B`,onClose:()=>x(null)})]})}export{Y as CalendarsPage,Y as default};
@@ -1 +0,0 @@
1
- import{$ as e,B as t,J as n,K as r,L as i,S as a,b as o,q as s,x as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{D as l,O as u,V as d,ca as f,ot as p}from"./player-overlays-DyNPyo_W.js";import{Cn as m,Dr as h,Fr as g,Ir as _,Mr as v,Nr as y,Or as b,Pr as x,Ur as S,Wr as C,Xr as w,Yr as T,dn as ee,fn as te,jr as ne,kr as re,mn as ie,pn as ae,un as oe,wr as E}from"./client-CRCWO8cg.js";import{Bu as se,Er as ce,Ga as D,Hu as le,Ou as ue,Pr as de,Wa as fe,bo as pe,fr as O,hr as k,pa as me,s as he,sa as ge}from"./src-_mtQMfPm.js";import{t as A}from"./i18n-DzruZdmx.js";import{t as j}from"./useTranslation-D3Is_4B6.js";e();function _e(e){return{target:{kind:`new`,type:e},name:``,features:[]}}function ve(e){return{target:{kind:`existing`,device:e},name:``,features:[]}}function M(e,t){return{target:e.target,name:t,features:e.features.flatMap(e=>e.kind===`fields`?[e]:[])}}function N(e,t,n){return{...e,features:e.features.map(e=>e.cap===t?n(e):e)}}function P(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ye(e,t){switch(t.type){case`set-new-type`:return e.target.kind===`new`?{...e,target:{...e.target,type:t.deviceType}}:e;case`set-new-role`:{if(e.target.kind!==`new`)return e;let{role:n,...r}=e.target;return{...e,target:t.role===null?r:{...r,role:t.role}}}case`set-name`:return{...e,name:t.name};case`add-feature`:return e.features.some(e=>e.cap===t.cap)?e:{...e,features:[...e.features,{kind:`fields`,cap:t.cap,fields:{}}]};case`remove-feature`:return{...e,features:e.features.filter(e=>e.cap!==t.cap)};case`set-field`:return N(e,t.cap,e=>({...e,fields:{...e.fields,[t.path]:t.source}}));case`clear-field`:return N(e,t.cap,e=>({...e,fields:P(e.fields,t.path)}));case`remove-binding`:return N(e,t.cap,e=>{let n=e.fields[t.path];return n?.kind===`expression`?{...e,fields:{...e.fields,[t.path]:{...n,bindings:P(n.bindings,t.bindingName)}}}:e});case`copy-feature`:return N(e,t.cap,e=>({...e,fields:{...e.fields,...Object.fromEntries(t.paths.map(e=>[e,{kind:`from`,source:t.from,cap:t.sourceCap,fieldPath:e}]))}}))}}function be(e){let t=re.safeParse({target:e.target,features:e.features});return t.success?{ok:!0,composition:t.data}:{ok:!1,problems:t.error.issues.map(e=>`${e.path.join(`.`)||`composition`}: ${e.message}`)}}function xe(e,t){return JSON.stringify(e)!==JSON.stringify(t)}function Se(e){for(let t=1;;t++){let n=`s${t}`;if(!e.includes(n))return n}}var Ce=[`room`,`converted-sensor`,`derived-binary`],F={addonId:`provider-homeassistant`,stableId:`sensor.template_source`};function we(){return M(ae({temperatureSources:ee,motionSources:oe,occupancyWindowMs:te}),`Room`)}function Te(){return M({target:{kind:`new`,type:w.Sensor},features:[{kind:`fields`,cap:`numeric-sensor`,fields:{value:{kind:`expression`,expr:`convert(v, "°C", "°F")`,bindings:{v:{kind:`from`,source:F,cap:`numeric-sensor`,fieldPath:`value`}}},unit:{kind:`expression`,expr:`"°F"`,bindings:{}},lastFetchedAt:{kind:`expression`,expr:`now`,bindings:{}}}}]},`Converted sensor`)}function Ee(){return M({target:{kind:`new`,type:w.Sensor},features:[{kind:`fields`,cap:`binary`,fields:{on:{kind:`expression`,expr:`v > 20`,bindings:{v:{kind:`from`,source:F,cap:`temperature-sensor`,fieldPath:`celsius`}}},lastChangedAt:{kind:`expression`,expr:`now`,bindings:{}}}}]},`Derived binary`)}function De(e){switch(e){case`room`:return we();case`converted-sensor`:return Te();case`derived-binary`:return Ee()}}function Oe(e,t){return typeof t==`number`&&Number.isFinite(t)&&t>0?{kind:`device`,path:`/devices/${t}`}:{kind:`editor`,path:`/build/compositions/${encodeURIComponent(e)}`}}var I=`rounded-lg border border-border bg-surface p-4`,ke=I;function Ae(e){return{addonId:e.addonId,stableId:e.stableId}}function L(e){return new Map(e.map(e=>[g(Ae(e)),e]))}function je(e,t,n){let r=e?.features??[],i=r.findIndex(e=>e.cap===n.cap);return{target:e?.target??{kind:`existing`,device:t},features:i===-1?[...r,n]:r.map((e,t)=>t===i?n:e)}}function Me(e,t){let n=e.features.filter(e=>e.cap!==t);return n.length===0?null:{target:e.target,features:n}}function Ne(e,t){let n=e?.features.find(e=>e.cap===t);return n!==void 0&&n.kind===`fields`?n:null}function R(e){return Array.isArray(e)?e.map(R):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,R(t)]))}function z(e){return JSON.stringify(R(e))}function Pe(e,t){return z(e)===z(t)}function B(e,t){return z(e)===z(t)}function Fe(e,t){switch(e.kind){case`pending`:return{kind:`refused`,reason:A.t(`helpers.customizationSave.notReadYet`)};case`unknown`:return{kind:`refused`,reason:`the customization could not be read: ${e.reason}`};case`not-loaded`:return{kind:`refused`,reason:`the customizations are not loaded yet: ${e.reason}`};case`none`:return t===null?{kind:`noop`}:{kind:`create`,input:{enabled:!0,composition:t}};case`present`:{let n=e.view.block.id;return t===null?{kind:`delete`,blockId:n}:z(t)===z(e.composition)?{kind:`noop`}:{kind:`update`,blockId:n,expectedUpdatedAt:e.view.block.updatedAt,composition:t}}}}function V(e,t){let n=e===`enum`?`string`:e,r=t.kind===`enum`?`string`:t.kind,i={source:t.source,cap:t.cap,fieldPath:t.fieldPath};return r===n?{kind:`from`,...i}:n===`number`&&r===`string`?{kind:`expression`,expr:`number(x)`,bindings:{x:{kind:`from`,...i}}}:null}function H(e){return{kind:`expression`,expr:e,bindings:{}}}function U(e){let t=V(`number`,e.percentage);return t===null?null:{kind:`fields`,cap:`battery`,fields:e.mode===`replace`?{percentage:t}:{percentage:t,charging:H(`"unknown"`),sleeping:H(`false`),lastUpdated:H(`now`)}}}var Ie=[`percent`,...m.options];function W(e,t){return t===`percent`?{level:e}:{"remaining.value":e,"remaining.unit":H(JSON.stringify(t))}}function Le(e,t){let n=V(`number`,t.remaining);if(n===null||!b.test(t.key)||t.label.trim()===``)return null;let r={label:t.label.trim(),fields:W(n,t.unit)};return{kind:`fields`,cap:`consumables`,...e?.enabled===void 0?{}:{enabled:e.enabled},fields:e?.fields??{lastChangedAt:H(`now`),lastFetchedAt:H(`now`)},items:{...e?.items,[t.key]:r}}}function Re(e){if(e.level!==void 0)return`percent`;let t=e[`remaining.unit`];if(t===void 0||t.kind!==`expression`)return null;try{let e=m.safeParse(JSON.parse(t.expr));return e.success?e.data:null}catch{return null}}function ze(e){return Object.entries(e?.items??{}).map(([e,t])=>{let n=Re(t.fields),r=G(t.fields.level??t.fields[`remaining.value`]),i=r===null?null:V(`number`,r);return n!==null&&i!==null&&Pe(W(i,n),t.fields)?{key:e,label:t.label,unit:n,source:r}:{key:e,label:t.label,unit:null,source:null}})}function Be(e,t){let n=Object.fromEntries(Object.entries(e.items??{}).filter(([e])=>e!==t));return Object.keys(n).length===0?null:{...e,items:n}}function Ve(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,48)}function He(e){let t=e.fields.lastPressedAt;if(t===void 0||t.kind!==`expression`)return[];let n=Object.entries(t.bindings).filter(([e])=>e.startsWith(`active`)).flatMap(([,e])=>e.kind===`from`?[e.source]:[]);return[...new Map(n.map(e=>[g(e),e])).values()]}function Ue(e){let t=e.fields.lastPressedAt;if(t===void 0||t.kind!==`expression`)return[];let n=t.bindings;return Object.entries(n).flatMap(([e,t])=>{if(!e.startsWith(`active`)||t.kind!==`from`)return[];let r=n[`changed${e.slice(6)}`];return r===void 0||r.kind!==`from`?[]:[{source:t.source,cap:t.cap,activeField:t.fieldPath,changedAtField:r.fieldPath}]})}function G(e){if(e===void 0)return null;if(e.kind===`from`){let{kind:t,...n}=e;return{...n,kind:`number`}}if(e.kind!==`expression`||e.expr!==`number(x)`)return null;let t=e.bindings.x;if(t===void 0||t.kind!==`from`||Object.keys(e.bindings).length!==1)return null;let{kind:n,...r}=t;return{...r,kind:`string`}}function We(e,t){let n=G(e.fields.percentage);if(n===null)return!1;let r=U({percentage:n,mode:t}),{enabled:i,...a}=e;return r!==null&&B(a,r)}function K(e){return e.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,location:e.location,type:e.type}))}function Ge(e,t,n){let r=t.trim().toLowerCase();return r===``?[]:e.filter(e=>!n.includes(e.id)&&[e.name,e.stableId,e.location??``].some(e=>e.toLowerCase().includes(r))).toSorted((e,t)=>e.name.localeCompare(t.name)).slice(0,20)}function q(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=Object.getOwnPropertyDescriptor(n,e)?.value}return n}function Ke(e,t,n,r){return r===null?{kind:`from`,source:e,cap:t,fieldPath:n.path}:V(r,{source:e,cap:t,fieldPath:n.path,kind:n.kind})}function qe(e,t,n,r){let i={addonId:e.addonId,stableId:e.stableId};return t.caps.flatMap(e=>e.fields.filter(e=>e.item!==!0).map(t=>({cap:e.cap,path:t.path,kind:t.kind,value:n===null?void 0:q(n[e.cap],t.path),source:Ke(i,e.cap,t,r)})))}function J(e,t){return t?e===void 0?`—`:e===null?`null`:typeof e==`string`||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e):`…`}var Je=[];function Y({title:e,targetKind:t,excludeDeviceIds:r=Je,onPick:i,onCancel:o}){let{t:s}=j(),[f,p]=n(null);return a(`aside`,{"aria-label":e,className:`${u} ${l} flex flex-col gap-2`,children:[c(`h3`,{className:d,children:e}),f===null?c(Ye,{excludeDeviceIds:r,onSelect:p}):c(X,{device:f,targetKind:t,onPick:i,onBack:()=>p(null)}),c(`div`,{children:c(k,{variant:`ghost`,size:`sm`,onClick:o,children:s(`customize.picker.cancel`)})})]})}function Ye({excludeDeviceIds:e,onSelect:t}){let{t:r}=j(),[i,s]=n(``),l=D({projection:`slim`});return a(o,{children:[a(`label`,{className:`flex flex-col gap-1 text-[11px] text-foreground-subtle`,children:[r(`customize.picker.search`),c(ue,{type:`search`,"aria-label":r(`customize.picker.search`),value:i,onChange:e=>s(e.target.value)})]}),l.status===`pending`&&c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:r(`customize.picker.loadingDevices`)}),l.status===`error`&&c(O,{title:r(`customize.picker.devicesFailed`),message:l.error?.message??``}),l.status===`success`&&c(`ul`,{className:`flex flex-col gap-1`,children:Ge(K(l.data),i,e).map(e=>c(`li`,{children:a(`button`,{type:`button`,className:`text-left text-[11px] hover:underline`,onClick:()=>t(e),children:[e.name,` `,a(`span`,{className:`text-foreground-subtle`,children:[`· `,e.stableId]})]})},e.id))})]})}function X({device:e,targetKind:t,selected:n,onPick:r,onBack:i}){let{t:o}=j(),s=fe({deviceId:e.id}),l=pe({deviceId:e.id});if(s.status===`pending`)return c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:o(`customize.picker.loadingFields`)});if(s.status===`error`)return c(O,{title:o(`customize.picker.fieldsFailed`),message:s.error?.message??``});let u=qe(e,s.data,l.status===`success`?l.data:null,t),d=u.filter(e=>e.source===null).length,f={addonId:e.addonId,stableId:e.stableId};return a(`div`,{className:`flex flex-col gap-1`,children:[a(`button`,{type:`button`,className:`text-left text-[11px] text-primary`,onClick:i,children:[`← `,e.name]}),l.status===`error`&&c(`p`,{role:`alert`,className:`text-[10px] text-warning`,children:o(`customize.picker.valuesFailed`,{reason:l.error?.message??``})}),c(`ul`,{role:`listbox`,"aria-label":o(`customize.picker.fields`),className:`flex flex-col gap-1`,children:u.map(t=>{let i=t.source;if(i===null)return null;let o=()=>r({device:e,ref:f,cap:t.cap,path:t.path,kind:t.kind,source:i,value:t.value});return a(`li`,{role:`option`,"aria-selected":n?.cap===t.cap&&n.path===t.path,tabIndex:0,className:`flex justify-between gap-2 text-[11px] cursor-pointer hover:bg-surface-hover rounded px-1`,onClick:o,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&o()},children:[a(`span`,{className:`font-mono`,children:[t.cap,`.`,t.path]}),c(`span`,{children:J(t.value,l.status===`success`)})]},`${t.cap}.${t.path}`)})}),d>0&&t!==null&&c(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`customize.picker.hidden`,{count:d,kind:o(`customize.kinds.${t}`)})})]})}var Xe=`integration`;function Z(e,t){switch(e.kind){case`from`:{let n=g(e.source);return`${t.get(n)??n} · ${e.cap}.${e.fieldPath}`}case`expression`:return e.expr;case`code`:return`code`}}function Ze(e,t){if(e.kind===`unreachable`)return{kind:`unknown`,reason:e.error};if(e.state===null)return{kind:`unknown`,reason:A.t(`helpers.fieldsTableRows.composerNotReported`)};let n=e.state.fields.find(t);return n===void 0?{kind:`unknown`,reason:A.t(`helpers.fieldsTableRows.noValue`)}:n.state===`unavailable`?{kind:`unavailable`,reason:n.reason??A.t(`common.unavailable`)}:{kind:`value`,value:n.value,staleReason:n.state===`stale`?n.reason??A.t(`common.stale`):null}}function Q(e,t,n,r){return{key:`${e.feature.cap}.${t}`,cap:e.feature.cap,field:t,origin:`composed`,mode:e.mode,from:Z(n,e.input.sourceNames),value:e.enabled?Ze(e.input.state,r):{kind:`off`}}}function Qe(e){let t=e.feature.cap;return Object.entries(e.feature.fields).map(([n,r])=>Q(e,n,r,e=>e.cap===t&&e.path===n&&e.item===void 0))}function $e(e){let t=e.feature.cap;return Object.entries(e.feature.items??{}).flatMap(([n,r])=>Object.entries(r.fields).map(([r,i])=>Q(e,v(h,n,r),i,e=>e.cap===t&&e.path===r&&e.item?.arrayPath===`items`&&e.item.key===n)))}function et(e,t,n){if(e===null)return{kind:`unknown`,reason:A.t(`helpers.fieldsTableRows.stateUnreadable`)};let r=q(e[t],n),i=r===void 0?void 0:S(r);return i===void 0?{kind:`unknown`,reason:A.t(`helpers.fieldsTableRows.notReported`)}:{kind:`value`,value:i,staleReason:null}}function tt(e){if(e.mode!==`replace`)return[];let t=e.feature.cap,n=new Set(Object.keys(e.feature.fields));return(e.input.nativeFields.get(t)??[]).filter(e=>!n.has(e)).map(n=>({key:`${t}.${n}`,cap:t,field:n,origin:`native`,mode:e.mode,from:Xe,value:et(e.input.snapshot,t,n)}))}function nt(e){return e.composition.features.flatMap(t=>{if(t.kind!==`fields`)return[];let n={feature:t,mode:e.nativeCaps.has(t.cap)?`replace`:`add`,enabled:ne(t),input:e};return[...Qe(n),...$e(n),...tt(n)]})}var rt={min:`min(a, b, …)`,max:`max(a, b, …)`,abs:`abs(x)`,floor:`floor(x)`,ceil:`ceil(x)`,sqrt:`sqrt(x)`,round:`round(x, digits?)`,pow:`pow(x, y)`,clamp:`clamp(x, lo, hi)`,avg:`avg(a, b, …)`,sum:`sum(a, b, …)`,coalesce:`coalesce(a, b, …)`,age:`age(now, ts)`,convert:`convert(x, "from", "to")`,any:`any(a, b, …)`,all:`all(a, b, …)`,within:`within(ts, ms)`,number:`number(x)`,latest:`latest(ts, …)`,rose:`rose(level, changedAt, debounceMs?)`,count:`count(x)`},it=/[A-Za-z_][A-Za-z0-9_]*$/;function at(e,t,n){let r=it.exec(e.slice(0,t))?.[0]??``;if(r===``)return[];let i=n.filter(e=>e.startsWith(r)).toSorted().map(e=>({kind:`binding`,label:e,insert:e,hintKey:null})),a=`now`.startsWith(r)?[{kind:`now`,label:`now`,insert:`now`,hintKey:`compositionEditor.now`}]:[],o=[...C].filter(e=>e.startsWith(r)).toSorted().map(e=>({kind:`builtin`,label:rt[e]??e,insert:`${e}(`,hintKey:`compositionEditor.builtins.${e}`}));return[...i,...a,...o].slice(0,8)}function ot(e,t,n){let r=t-(it.exec(e.slice(0,t))?.[0]??``).length;return{text:`${e.slice(0,r)}${n.insert}${e.slice(t)}`,cursor:r+n.insert.length}}e();function st({label:e,value:t,bindings:r,onChange:i}){let{t:o}=j(),l=s(null),[u,d]=n(t.length),f=at(t,u,r);return a(`div`,{className:`flex flex-col gap-1`,children:[a(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[e,c(`input`,{ref:l,className:`font-mono px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`,value:t,onChange:e=>{i(e.target.value),d(e.target.selectionStart??e.target.value.length)},onSelect:e=>d(e.currentTarget.selectionStart??t.length)})]}),f.length>0&&c(`ul`,{role:`listbox`,"aria-label":o(`compositionEditor.suggestions`),className:`rounded border border-border bg-surface text-[11px]`,children:f.map(e=>a(`li`,{role:`option`,"aria-selected":!1,tabIndex:0,className:`flex justify-between gap-2 px-1 cursor-pointer hover:bg-surface-hover`,onClick:()=>{let n=ot(t,u,e);i(n.text),d(n.cursor),l.current?.focus()},children:[c(`span`,{className:`font-mono`,children:e.label}),e.hintKey!==null&&c(`span`,{className:`text-foreground-subtle`,children:o(e.hintKey)})]},`${e.kind}:${e.label}`))})]})}function ct(e,t,n){if(e.kind===`code`)return{kind:`unavailable`,reason:A.t(`helpers.fieldPreview.codeFields`)};if(e.kind===`expression`&&(E(e.expr,`rose`)||E(e.expr,`count`)))return{kind:`runtime-only`};let r=_(e).filter(e=>t.get(x(e.source,e.cap))?.kind!==`value`).map(y);if(r.length>0)return{kind:`waiting`,missing:r};let i=ie({source:e,now:n,read:e=>{let n=t.get(x(e.source,e.cap)),r=n?.kind===`value`?q(n.slice,e.fieldPath):void 0,i=r===void 0?void 0:S(r);return i===void 0?{state:`unavailable`,reason:A.t(`helpers.fieldPreview.notReported`,{path:`${e.cap}.${e.fieldPath}`}),fatal:!1}:{state:`fresh`,value:i}}});return i.state===`unavailable`?{kind:`unavailable`,reason:i.reason}:{kind:`value`,value:i.value,stale:i.reason}}e();function lt({sliceKey:e,deviceId:n,capName:r,onReading:i}){let a=he(p().trpcClient,n,r);return t(()=>{i(e,a===void 0?{kind:`pending`}:{kind:`value`,slice:a})},[e,a,i]),null}function ut(e,t){return[...new Map(_(e).map(e=>[x(e.source,e.cap),e]))].map(([e,n])=>({key:e,read:n,device:t.get(g(n.source))}))}function dt({source:e}){let{t}=j(),r=D({projection:`slim`}),[o,s]=n(new Map),l=i((e,t)=>{s(n=>new Map([...n,[e,t]]))},[]),u=ut(e,L(r.status===`success`?K(r.data):[])),d=r.status===`success`?u.filter(e=>e.device===void 0).map(e=>g(e.read.source)):[];return a(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px]`,children:[u.map(e=>e.device===void 0?null:c(lt,{sliceKey:e.key,deviceId:e.device.id,capName:e.read.cap,onReading:l},e.key)),c(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.label`)}),r.status===`error`?c(`span`,{className:`text-warning`,children:t(`compositionEditor.preview.devicesFailed`,{reason:r.error?.message??``})}):d.length>0?c(`span`,{className:`text-warning`,children:t(`compositionEditor.preview.unknownDevice`,{sources:d.join(`, `)})}):c(ft,{preview:ct(e,o,Date.now())})]})}function ft({preview:e}){let{t}=j();switch(e.kind){case`value`:return a(`strong`,{children:[`→ `,J(e.value,!0),e.stale===null?``:` (${e.stale})`]});case`unavailable`:return c(`span`,{className:`text-warning`,children:e.reason});case`waiting`:return c(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.waiting`,{sources:e.missing.join(`, `)})});case`runtime-only`:return c(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.runtimeOnly`)})}}e();function pt({path:e,kind:t,required:r,source:i,onSet:s,onClear:l,onRemoveBinding:u,sourceNames:d}){let{t:f}=j(),[p,m]=n(`idle`),h=i?.kind===`expression`?i:null;return a(`div`,{className:`flex flex-col gap-1 rounded border border-border p-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[c(`span`,{className:`font-mono text-[11px]`,children:e}),a(`span`,{className:`text-[10px] text-foreground-subtle`,children:[f(`customize.kinds.${t}`),r?` · ${f(`compositionEditor.required`)}`:``]}),c(k,{size:`sm`,variant:`outline`,onClick:()=>m(`take`),children:f(`compositionEditor.takeFrom`)}),c(k,{size:`sm`,variant:`outline`,"aria-pressed":h!==null,onClick:()=>s(h??{kind:`expression`,expr:`null`,bindings:{}}),children:f(`compositionEditor.formula`)}),i!==void 0&&c(k,{size:`sm`,variant:`ghost`,onClick:l,children:f(`compositionEditor.clear`)})]}),i?.kind===`from`&&c(`span`,{className:`text-[11px]`,children:Z(i,d)}),h!==null&&a(o,{children:[c(st,{label:f(`compositionEditor.formulaFor`,{path:e}),value:h.expr,bindings:Object.keys(h.bindings),onChange:e=>s({...h,expr:e})}),c(`ul`,{className:`text-[11px] flex flex-col gap-0.5`,children:Object.entries(h.bindings).map(([e,t])=>a(`li`,{className:`flex flex-wrap items-center gap-2`,children:[c(`span`,{className:`font-mono`,children:e}),c(`span`,{children:t.kind===`from`?Z(t,d):JSON.stringify(t.value)}),c(k,{size:`sm`,variant:`ghost`,"aria-label":f(`compositionEditor.removeBinding`,{name:e}),onClick:()=>u(e),children:`×`})]},e))}),c(k,{size:`sm`,variant:`ghost`,onClick:()=>m(`add-binding`),children:f(`compositionEditor.addSource`)})]}),p!==`idle`&&c(Y,{title:f(p===`take`?`compositionEditor.takeFrom`:`compositionEditor.addSource`),targetKind:p===`take`?t:null,onCancel:()=>m(`idle`),onPick:e=>{if(p===`take`)s(e.source);else if(h!==null){let t=Se(Object.keys(h.bindings));s({...h,bindings:{...h.bindings,[t]:{kind:`from`,source:e.ref,cap:e.cap,fieldPath:e.path}}})}m(`idle`)}}),i!==void 0&&c(dt,{source:i})]})}e();function mt(e){return e===null||e.kind===`known`?null:e}function ht({draft:e,deviceType:t,nativeCaps:r,targetFields:i,dispatch:s}){let{t:l}=j(),u=ge({deviceType:t}),d=D({projection:`slim`}),f=new Map([...L(d.status===`success`?K(d.data):[])].map(([e,t])=>[e,t.name])),[p,m]=n(null),h=mt(r)??mt(i),g=r?.kind===`known`?r.value:new Set,_=new Set(e.features.map(e=>e.cap)),v=u.status===`success`?u.data.caps.filter(e=>!_.has(e.cap)&&!g.has(e.cap)):[],y=[...g].filter(e=>!_.has(e)),b=e=>g.has(e)?((i?.kind===`known`?i.value.caps.find(t=>t.cap===e):void 0)?.fields??[]).filter(e=>e.item!==!0&&!e.path.includes(`.`)).map(e=>({path:e.path,kind:e.kind,required:!1})):((u.status===`success`?u.data.caps.find(t=>t.cap===e):void 0)?.fields??[]).map(e=>({path:e.path,kind:e.kind,required:e.required}));return h===null?a(o,{children:[a(`section`,{"aria-labelledby":`editor-features`,className:`${I} flex flex-col gap-2`,children:[c(`h2`,{id:`editor-features`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.features`)}),u.status===`pending`&&c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:l(`compositionEditor.checking`)}),u.status===`error`&&c(`p`,{role:`alert`,className:`text-[11px] text-warning`,children:l(`compositionEditor.unknown`,{reason:u.error?.message??``})}),a(`div`,{className:`flex flex-wrap gap-1`,children:[e.features.map(e=>a(`span`,{className:`flex items-center gap-1 rounded border border-border px-1.5 text-[11px]`,children:[e.cap,c(de,{variant:g.has(e.cap)?`default`:`info`,children:g.has(e.cap)?l(`compositionEditor.replaces`):l(`compositionEditor.added`)}),c(`button`,{type:`button`,"aria-label":l(`compositionEditor.removeFeature`,{cap:e.cap}),onClick:()=>s({type:`remove-feature`,cap:e.cap}),children:`×`})]},e.cap)),v.map(e=>a(k,{size:`sm`,variant:`outline`,onClick:()=>s({type:`add-feature`,cap:e.cap}),children:[`+ `,e.cap]},e.cap)),y.map(e=>c(k,{size:`sm`,variant:`ghost`,onClick:()=>s({type:`add-feature`,cap:e}),children:l(`compositionEditor.replaceIn`,{cap:e})},e))]})]}),e.features.map(e=>a(`section`,{"aria-label":l(`compositionEditor.steps.fieldsOf`,{cap:e.cap}),className:`${I} flex flex-col gap-2`,children:[a(`div`,{className:`flex items-center justify-between`,children:[c(`h2`,{className:`text-sm font-semibold`,children:l(`compositionEditor.steps.fieldsOf`,{cap:e.cap})}),c(k,{size:`sm`,variant:`outline`,onClick:()=>m(e.cap),children:l(`compositionEditor.copyFeature`)})]}),p===e.cap&&c(Y,{title:l(`compositionEditor.copyFeature`),targetKind:null,onCancel:()=>m(null),onPick:t=>{s({type:`copy-feature`,cap:e.cap,from:t.ref,sourceCap:t.cap,paths:b(e.cap).map(e=>e.path)}),m(null)}}),b(e.cap).map(t=>c(pt,{path:t.path,kind:t.kind,required:t.required,source:e.fields[t.path],onSet:n=>s({type:`set-field`,cap:e.cap,path:t.path,source:n}),onClear:()=>s({type:`clear-field`,cap:e.cap,path:t.path}),onRemoveBinding:n=>s({type:`remove-binding`,cap:e.cap,path:t.path,bindingName:n}),sourceNames:f},t.path))]},e.cap))]}):a(`section`,{"aria-labelledby":`editor-features`,className:`${I} flex flex-col gap-2`,children:[c(`h2`,{id:`editor-features`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.features`)}),c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:h.kind===`unknown`?h.reason:l(`compositionEditor.reading`)})]})}var $=`px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`;function gt({draft:e,targetName:t,dispatch:n}){let r=f(),{t:i}=j(),o=e.target;return a(`section`,{"aria-labelledby":`editor-target`,className:`${I} flex flex-col gap-2`,children:[c(`h2`,{id:`editor-target`,className:`text-sm font-semibold`,children:i(`compositionEditor.steps.target`)}),o.kind===`existing`?c(`p`,{className:`text-[11px]`,children:i(`compositionEditor.existingTarget`,{name:t??`${o.device.addonId}/${o.device.stableId}`})}):a(`div`,{className:`grid grid-cols-3 gap-2`,children:[a(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[i(`compositionEditor.targetType`),c(`select`,{className:$,value:o.type,onChange:e=>{let t=Object.values(w).find(t=>t===e.target.value);t!==void 0&&n({type:`set-new-type`,deviceType:t})},children:Object.values(w).map(e=>c(`option`,{value:e,children:le(e,r).label},e))})]}),a(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[i(`customize.identity.role`),a(`select`,{className:$,value:o.role??``,onChange:e=>n({type:`set-new-role`,role:Object.values(T).find(t=>t===e.target.value)??null}),children:[c(`option`,{value:``,children:i(`customize.identity.noRole`)}),Object.values(T).map(e=>c(`option`,{value:e,children:se(e,r).label},e))]})]}),a(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[i(`compositionEditor.name`),c(`input`,{className:$,value:e.name,onChange:e=>n({type:`set-name`,name:e.target.value})})]})]})]})}e();function _t({draft:e,blockId:r,saving:i,onSave:o,onCancel:s}){let{t:l}=j(),u=me(),d=be(e),f=d.ok?JSON.stringify(d.composition):``,[p,m]=n({key:``,state:{kind:`checking`}});t(()=>{if(!d.ok)return;let e=d.composition,t=setTimeout(()=>{u.mutateAsync({composition:e,...r===null?{}:{blockId:r}}).then(e=>m({key:f,state:e.ok?{kind:`ok`}:{kind:`refused`,problems:e.problems}})).catch(e=>m({key:f,state:{kind:`unknown`,reason:e instanceof Error?e.message:String(e)}}))},500);return()=>clearTimeout(t)},[f,r]);let h=d.ok?p.key===f?p.state:{kind:`checking`}:{kind:`invalid-draft`,problems:d.problems};return a(`section`,{"aria-labelledby":`editor-verify`,className:`${I} flex flex-col gap-2`,children:[c(`h2`,{id:`editor-verify`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.verify`)}),h.kind===`checking`&&c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:l(`compositionEditor.verify.checking`)}),h.kind===`ok`&&c(`p`,{className:`text-[11px] text-success`,children:l(`compositionEditor.verify.ok`)}),h.kind===`unknown`&&c(`p`,{role:`alert`,className:`text-[11px] text-warning`,children:l(`compositionEditor.verify.unknown`,{reason:h.reason})}),(h.kind===`invalid-draft`||h.kind===`refused`)&&c(`ul`,{role:`alert`,className:`flex flex-col gap-1 text-[11px] text-danger`,children:h.kind===`invalid-draft`?h.problems.map(e=>c(`li`,{children:e},e)):h.problems.map(e=>a(`li`,{children:[c(`span`,{className:`font-mono`,children:e.path}),` — `,e.message]},`${e.path}:${e.code}`))}),a(`div`,{className:`flex gap-2`,children:[c(k,{variant:`ghost`,onClick:s,children:l(`compositionEditor.cancel`)}),c(k,{disabled:h.kind!==`ok`||i||!d.ok,onClick:()=>d.ok&&o(d.composition),children:l(`compositionEditor.save`)})]})]})}e();function vt({initial:e,blockId:t,deviceType:r,targetName:i=null,nativeCaps:a,targetFields:o,save:s,onCancel:l,showTemplates:u=!1}){let[d,f]=n(e),p=`${d.name}:${d.features.map(e=>e.cap).join(`,`)}:${d.target.kind===`new`?d.target.type:`existing`}`;return c(yt,{seed:d,blockId:t,deviceType:r,targetName:i,nativeCaps:a,targetFields:o,showTemplates:u,onApplyTemplate:e=>{f(De(e))},save:s,onCancel:l},p)}function yt({seed:e,blockId:t,deviceType:i,targetName:o,nativeCaps:s,targetFields:l,showTemplates:u,onApplyTemplate:d,save:f,onCancel:p}){let{t:m}=j(),h=ce(),[g,_]=r(ye,e),[v,y]=n(!1),[b,x]=n(null),S=async t=>{xe(e,g)&&!await h({title:m(`compositionEditor.templates.confirmTitle`),message:m(`compositionEditor.templates.confirmMessage`),confirmLabel:m(`compositionEditor.templates.confirmApply`),variant:`danger`})||d(t)},C=g.target.kind===`new`?g.target.type:i,w=async e=>{y(!0);let t=await f(e,g.name);y(!1),x(t.kind===`refused`?t.reason:null)};return a(`div`,{className:`flex flex-col gap-4`,children:[u&&g.target.kind===`new`&&a(`div`,{className:`rounded-lg border border-border bg-surface p-4 flex flex-wrap gap-2`,"data-testid":`composition-templates`,children:[c(`span`,{className:`text-[11px] text-foreground-subtle self-center`,children:m(`compositionEditor.templates.label`)}),Ce.map(e=>c(k,{size:`sm`,variant:`outline`,onClick:()=>void S(e),children:m(`compositionEditor.templates.${e}`)},e))]}),c(gt,{draft:g,targetName:o,dispatch:_}),c(ht,{draft:g,deviceType:C,nativeCaps:s,targetFields:l,dispatch:_}),c(_t,{draft:g,blockId:t,saving:v,onSave:e=>void w(e),onCancel:p}),b!==null&&c(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:b})]})}export{Me as C,ve as D,M as E,_e as O,je as S,Oe as T,G as _,X as a,Fe as b,K as c,Le as d,ze as f,Ve as g,We as h,nt as i,Ie as l,Ue as m,ct as n,J as o,He as p,st as r,q as s,vt as t,U as u,Be as v,ke as w,B as x,Ne as y};
@@ -1,2 +0,0 @@
1
- import{$ as e,B as t,G as n,J as r,L as i,S as a,b as o,o as s,x as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{An as l,D as u,Fn as d,Gr as f,It as p,Ki as m,Nt as h,Q as g,Qr as _,Si as v,Xi as y,Yr as b,Zi as x,bi as S,ci as C,fn as w,ir as T,kn as E,mi as D,oi as O,or as k,rr as A,vn as j}from"./player-overlays-DyNPyo_W.js";import{n as M,t as N}from"./cloud-upload-I7yc63rr.js";import{t as P}from"./circle-slash-BTU53Q69.js";import{t as F}from"./hard-drive-download-BqS2ahXp.js";import{$n as I,Aa as ee,Ai as te,An as L,Bi as R,Cu as ne,Di as re,Dn as ie,Ei as ae,Er as z,Fi as oe,Ii as se,Li as ce,Mi as le,Mn as ue,Ni as de,Nl as fe,Oi as pe,Ou as me,Pi as he,Qn as ge,Ri as _e,Ti as ve,_l as ye,_n as be,at as xe,bl as Se,dt as Ce,er as B,fr as we,gn as Te,hr as V,ir as Ee,ji as De,ki as Oe,kn as ke,ku as H,li as Ae,lt as je,nr as Me,ol as Ne,pr as Pe,rr as Fe,ut as Ie,vl as Le,vt as U,yl as Re,zi as ze}from"./src-_mtQMfPm.js";import{t as W}from"./i18n-DzruZdmx.js";import{t as G}from"./useTranslation-D3Is_4B6.js";import"./mount-B0uThmDr.js";import{$ as Be,T as Ve,Z as He,nt as Ue}from"./index-2_qB4G1l.js";import{t as We}from"./AdminSectionedPage-DB1wuvwM.js";import{t as Ge}from"./AdminPage-CTKQzYSK.js";import{n as Ke}from"./authed-media-dGvmAGIm.js";import{t as K}from"./format-size-DIxKXxtj.js";import{a as qe,c as Je,l as Ye,n as Xe,o as Ze,s as Qe,t as $e,u as et}from"./location-owned-usage-Dqp8xgaw.js";e();function tt(){let{t:e}=G(),r=s(),i=z(),{data:o,isLoading:l,isError:u}=Se({}),d=Re(),f=n(()=>d.data??[],[d.data]),{data:p}=Ne({},{refetchOnWindowFocus:!1}),m=n(()=>$e(o??[],p?.locations),[o,p?.locations]),{data:h}=Le({},{refetchOnWindowFocus:!1}),g=n(()=>qe(h),[h]),{state:_,openNew:v,openEdit:y,close:b}=je(),[x,S]=Ie(`type`),C=()=>{S(null),b()},w=e=>{S(e),v()},T=e=>{S(null),y(e.id)},E=o??[],D=_.mode===`edit`?E.find(e=>e.id===_.id)??null:null;t(()=>{_.mode===`new`&&(x===null||x===``)&&(S(null),b())},[_.mode,x,b,S]),t(()=>{_.mode===`edit`&&!l&&D===null&&(S(null),b())},[_.mode,l,D,b,S]),t(()=>{_.mode===`closed`&&x!==null&&S(null)},[_.mode,x,S]);let O=ye({onSuccess:()=>{r.invalidateQueries({queryKey:[[`storage`,`listLocations`]]})}}),k=fe({onSuccess:()=>{r.invalidateQueries({queryKey:[[`storage`,`listLocations`]]})}}),A=async(t,n)=>{Ye(n)&&!await i({title:e(`system.storage.disable`,`Disable "{{displayName}}"?`,{displayName:t.displayName}),message:e(`system.storage.nothingIsDeletedSetThe`,`{{consequence}} Nothing is deleted — set the location back to Read-only or Active to bring its footage back.`,{consequence:Je(n).consequence}),confirmLabel:e(`common.disable`,`Disable`),variant:`danger`})||k.mutate(Qe(t,{mode:n}))},j=async t=>{if(await i({title:e(`system.storage.deleteLocation`,`Delete location "{{displayName}}"?`,{displayName:t.displayName}),message:e(`system.storage.thisRemovesTheLocationRecord`,`This removes the location record. Files on disk are not deleted; the underlying directory or remote path stays untouched.`),confirmLabel:e(`common.delete`,`Delete`),variant:`danger`}))try{await O.mutateAsync({id:t.id}),_.mode===`edit`&&_.id===t.id&&C()}catch(n){await i({title:e(`system.storage.deleteAnyway`,`Delete anyway?`),message:e(`system.storage.forcingNote`,{error:n instanceof Error?n.message:String(n)}),confirmLabel:e(`system.storage.forceDelete`,`Force delete`),variant:`danger`})&&O.mutate({id:t.id,force:!0},{onSuccess:()=>{_.mode===`edit`&&_.id===t.id&&C()}})}},M=n(()=>{let e=new Map;for(let t of o??[]){let n=e.get(t.type);n?n.push(t):e.set(t.type,[t])}return e},[o]),N=l||d.isLoading,P=u||d.isError,F=_.mode===`new`&&x!==null&&x!==``,I=_.mode===`edit`&&D!==null;return a(Ge,{embedded:!0,children:[N&&c(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:e(`system.storage.loadingLocations`,`Loading locations…`)}),P&&c(`div`,{className:`text-xs text-danger`,children:e(`system.storage.failedToLoadStorageLocations`,`Failed to load storage locations.`)}),!N&&!P&&a(`div`,{className:`space-y-3`,children:[f.length===0&&c(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-4 text-center text-[11px] text-foreground-subtle italic`,children:e(`system.storage.noStorageLocationsDeclaredBy`,`No storage locations declared by any installed addon.`)}),f.map(e=>c(Xe,{type:e.id,displayName:e.displayName,description:e.description,cardinality:e.cardinality,locations:M.get(e.id)??[],onAdd:w,onEdit:T,onDelete:e=>{j(e)},ownedBytesById:m,drainById:g,onSetMode:(e,t)=>{A(e,t)}},e.id))]}),F&&x!==null&&c(et,{initialType:x,onClose:C,onCreated:()=>{r.invalidateQueries({queryKey:[[`storage`,`listLocations`]]}),C()}}),I&&D!==null&&c(Ze,{location:D,onClose:C,onSaved:()=>{r.invalidateQueries({queryKey:[[`storage`,`listLocations`]]}),C()}})]})}var q={settings:{labelKey:`helpers.backupDatabases.settings.label`,descriptionKey:`helpers.backupDatabases.settings.description`,shortKey:`helpers.backupDatabases.settings.short`},events:{labelKey:`helpers.backupDatabases.events.label`,descriptionKey:`helpers.backupDatabases.events.description`,shortKey:`helpers.backupDatabases.events.short`},history:{labelKey:`helpers.backupDatabases.history.label`,descriptionKey:`helpers.backupDatabases.history.description`,shortKey:`helpers.backupDatabases.history.short`}},nt=Object.keys(q),J=[`settings`];function rt(){return W.t(`helpers.backupDatabases.notCreated`)}function it(e){return W.t(q[e].labelKey)}function at(e){return W.t(q[e].shortKey)}function ot(e){return W.t(q[e].descriptionKey)}function Y(e){let t=new Set(e);return nt.filter(e=>t.has(e))}function X(e){return e!==void 0&&e.length>0?Y(e):J}function st(e){return Y(e)}function ct(e,t){return t===void 0||!t.answered?`unknown`:t.databases.includes(e)?`present`:`absent`}function lt(e,t,n){return ct(e,t)===`absent`&&!n.has(e)}function ut(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function dt(e){return!e.includes(`settings`)}function ft(e){return{databases:[...st(e)]}}function pt(e,t){return e!==void 0&&e.length>0?Y(e):t!==void 0&&t.length>0?Y(t.map(e=>e.databaseId??`settings`)):J}function Z({databases:e}){return c(`span`,{className:`text-xs font-medium uppercase tracking-wide text-foreground-muted`,"data-testid":`backup-database-badges`,children:e.map(e=>at(e)).join(` · `)})}e();var mt=[[`backup`,`listDestinations`]],ht=[`backup`,`listArchives`];function gt({destinationId:e,restoreSupported:t,onOpenRestoreWizard:o}){let{t:l}=G(),u=s(),d=z(),{data:m,isLoading:h,isError:g}=De({destinationId:e}),_=m??[],v=ae({onSuccess:()=>{u.invalidateQueries({queryKey:[[...ht]]}),u.invalidateQueries({queryKey:mt})}}),y=i(async t=>{await d({title:l(`backup.archiveList.deleteThisArchive`,`Delete this archive?`),message:l(`backup.archiveList.permanentlyDeletesAndFrees`,`Permanently deletes "{{value1}}" and frees {{value2}}.`,{value1:t.label??t.id,value2:K(t.sizeBytes)}),confirmLabel:l(`common.delete`,`Delete`),variant:`danger`})&&v.mutate({destinationId:e,backupId:t.id})},[d,e,v,l]),[b,x]=r(null),S=i(async t=>{x(t.id);try{let n=await Ke(_t(e,t.id)),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${t.label??t.id}.tar.gz${t.encryption===void 0?``:`.csbk`}`,document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(r)}finally{x(null)}},[e]),C=n(()=>[..._].toSorted((e,t)=>t.createdAt-e.createdAt),[_]);return h?c(`div`,{className:`text-xs text-foreground-subtle animate-pulse py-2`,children:l(`backup.archiveList.loadingArchives`,`Loading archives…`)}):g?c(`div`,{className:`text-xs text-danger py-2`,children:l(`backup.archiveList.failedToReadManifestFor`,`Failed to read manifest for this destination`)}):C.length===0?c(`div`,{className:`text-xs text-foreground-subtle italic py-2`,children:l(`backup.archiveList.noArchivesAtThisDestination`,`No archives at this destination yet.`)}):c(Te,{columns:[{key:`when`,header:l(`backup.archiveList.when`,`When`),sortValue:e=>e.createdAt,render:e=>c(`span`,{className:`tabular-nums`,children:vt(e.createdAt)})},{key:`label`,header:l(`backup.archiveList.label`,`Label`),sortValue:e=>e.label??null,render:e=>a(`span`,{className:`inline-flex items-center gap-1`,children:[e.encryption!==void 0&&c(A,{className:`h-3 w-3 text-success`,"aria-label":l(`backup.archiveList.encryptedRestoreNeedsBackupKey`,`encrypted — restore needs backup key {{keyId}}`,{keyId:e.encryption.keyId})}),e.label??c(`span`,{className:`text-foreground-subtle italic`,children:`—`})]})},{key:`databases`,header:l(`backup.archiveList.databases`,`Databases`),nowrap:!1,notSortableReason:`Database badges`,render:e=>c(Z,{databases:X(e.databases)})},{key:`includes`,header:l(`backup.archiveList.files`,`Files`),nowrap:!1,notSortableReason:`Location list`,render:e=>e.locations.length>0?c(`span`,{className:`text-foreground-subtle`,children:e.locations.join(`, `)}):c(`span`,{className:`text-foreground-subtle italic`,children:l(`common.none`)})},{key:`size`,header:l(`backup.archiveList.size`,`Size`),align:`right`,sortValue:e=>e.sizeBytes,render:e=>c(`span`,{className:`tabular-nums`,children:K(e.sizeBytes)})},{key:`actions`,header:``,align:`right`,notSortableReason:`Actions`,render:n=>a(`span`,{className:`flex items-center justify-end gap-1`,children:[a(V,{variant:`ghost`,size:`sm`,onClick:()=>{S(n)},disabled:b===n.id,title:l(`backup.archiveList.downloadArchive`,`Download archive`),children:[b===n.id?c(k,{className:`h-3 w-3 animate-spin`}):c(f,{className:`h-3 w-3`}),l(`backup.archiveList.download`,`Download`)]}),t&&o&&a(V,{variant:`ghost`,size:`sm`,onClick:()=>o({destinationId:e,archiveId:n.id}),title:l(`backup.archiveList.restoreFromThisArchive`,`Restore from this archive`),children:[c(j,{className:`h-3 w-3`}),l(`backup.archiveList.restore`,`Restore`)]}),c(H,{variant:`ghost`,size:`sm`,icon:p,"aria-label":l(`backup.archiveList.delete`,`Delete {{value1}}`,{value1:n.label??n.id}),disabled:v.isPending,onClick:()=>{y(n)}})]})}],rows:C,rowKey:e=>e.id,minWidthPx:760,emptyMessage:l(`backup.archiveList.noArchivesAtThisDestination`,`No archives at this destination yet.`)})}function _t(e,t){return g(`/api/backup/download/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}function vt(e){return new Date(e).toLocaleString(void 0,{day:`2-digit`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`})}e();var yt=[[`backup`,`listSchedules`]];function bt({onEdit:e,onOpenRestoreWizard:t}){let{t:o}=G(),{data:s,isLoading:l,isError:u,error:d,refetch:f}=oe(),p=s??[],m=de().data??[],h=n(()=>{let e=new Map;for(let t of m)e.set(t.id,t);return e},[m]),[g,_]=r(null),v=i(e=>{_(t=>t===e?null:e)},[]),y=n(()=>xt({destById:h,expandedId:g,onToggleExpand:v,onEdit:e}),[h,g,v,e]);return l?a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle animate-pulse`,children:[c(k,{className:`h-3.5 w-3.5 animate-spin`}),o(`backup.backupEntriesTable.loadingBackupEntries`,`Loading backup entries…`)]}):u?c(we,{title:o(`backup.backupEntriesTable.failedToLoadBackupEntries`,`Failed to load backup entries`),message:d instanceof Error?d.message:o(`backup.backupEntriesTable.unknownError`,`Unknown error`),onRetry:()=>void f()}):p.length===0?c(Pe,{icon:M,title:o(`backup.backupEntriesTable.noBackupEntriesYet`,`No backup entries yet`),description:o(`backup.backupEntriesTable.createOneToScheduleBackups`,`Create one to schedule backups across one or more storage locations.`)}):c(Te,{columns:y,rows:p,rowKey:e=>e.id,minWidthPx:980,maxBodyHeight:be,emptyMessage:o(`backup.backupEntriesTable.noBackupEntriesYet`,`No backup entries yet`),onRowClick:t=>e(t),isExpanded:e=>e.id===g,renderExpanded:e=>c(Ot,{row:e,destById:h,...t?{onOpenRestoreWizard:t}:{}})})}function xt(e){return[{key:`expand`,header:``,width:`w-8`,nowrap:!0,notSortableReason:`Expand control`,render:t=>{let n=e.expandedId===t.id;return c(H,{variant:`ghost`,size:`sm`,icon:n?v:S,"aria-label":n?W.t(`backup.backupEntriesTable.hideArchives`,`Hide archives`):W.t(`backup.backupEntriesTable.showArchives`,`Show archives`),"aria-expanded":n,onClick:n=>{n.stopPropagation(),e.onToggleExpand(t.id)}})}},{key:`entry`,header:W.t(`backup.backupEntriesTable.entry`,`Entry`),sortValue:e=>e.label,render:e=>a(`span`,{className:`flex min-w-0 flex-col`,children:[c(`span`,{className:`truncate font-medium text-foreground`,children:e.label||W.t(`backup.backupEntriesTable.unnamed`,`(unnamed)`)}),e.lastRunAt!==void 0&&c(`span`,{className:`text-[10px] text-foreground-subtle`,children:W.t(`backup.backupEntriesTable.lastRun`,{when:new Date(e.lastRunAt).toLocaleString()})})]})},{key:`enabled`,header:W.t(`backup.backupEntriesTable.enabled`,`Enabled`),width:`w-20`,nowrap:!0,sortValue:e=>+!!e.enabled,render:e=>c(`span`,{onClick:e=>e.stopPropagation(),children:c(Tt,{row:e})})},{key:`databases`,header:W.t(`backup.backupEntriesTable.backsUp`,`Backs up`),nowrap:!1,notSortableReason:`Database badges`,render:e=>c(Z,{databases:X(e.databases)})},{key:`locations`,header:W.t(`backup.backupEntriesTable.locations`,`Locations`),nowrap:!1,notSortableReason:`Location chips`,render:t=>c(St,{row:t,destById:e.destById})},{key:`retention`,header:W.t(`backup.backupEntriesTable.retention`,`Retention`),width:`w-24`,nowrap:!0,sortValue:e=>e.retentionCount,render:e=>c(`span`,{onClick:e=>e.stopPropagation(),children:c(Et,{row:e})})},{key:`schedule`,header:W.t(`backup.backupEntriesTable.schedule`,`Schedule`),width:`w-48`,nowrap:!0,sortValue:e=>e.cron,render:e=>c(Ct,{row:e})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Actions`,render:t=>c(`span`,{onClick:e=>e.stopPropagation(),children:c(Dt,{row:t,onEdit:()=>e.onEdit(t)})})}]}function St({row:e,destById:t}){let{t:n}=G();return e.locationIds.length===0?c(`span`,{className:`text-[11px] italic text-danger`,children:n(`backup.backupEntriesTable.noLocations`,`No locations`)}):c(`span`,{className:`flex flex-wrap gap-1`,children:e.locationIds.map(e=>c(`span`,{className:`inline-flex items-center rounded border border-border bg-background px-1.5 py-0.5 text-[10px] text-foreground`,title:e,children:t.get(e)?.displayName??e},e))})}function Ct({row:e}){let{t}=G(),n=e.cron.trim().length>0;return a(`span`,{className:`flex flex-col items-start gap-0.5`,children:[a(`span`,{className:`inline-flex items-center gap-1`,children:[c(M,{className:`h-3 w-3 text-foreground-subtle`}),c(`span`,{className:`font-mono text-[11px] text-foreground`,children:n?e.cron:t(`backup.backupEntriesTable.manual`,`Manual`)})]}),n&&e.nextRunAt!==void 0&&c(`span`,{className:`text-[10px] text-foreground-subtle`,children:W.t(`common.nextRun`,{when:new Date(e.nextRunAt).toLocaleString()})})]})}function wt(e){return n(()=>({id:e.id,label:e.label,cron:e.cron,locationIds:[...e.locationIds],retentionCount:e.retentionCount,...e.dataSources?{dataSources:[...e.dataSources]}:{},...e.databases?{databases:[...e.databases]}:{}}),[e])}function Tt({row:e}){let{t}=G(),n=s(),r=R({onSuccess:()=>{n.invalidateQueries({queryKey:yt})}}),i=wt(e);return c(`label`,{className:`inline-flex cursor-pointer items-center`,children:c(`input`,{type:`checkbox`,className:`accent-primary`,checked:e.enabled,disabled:r.isPending,onChange:e=>r.mutate({...i,enabled:e.target.checked}),"aria-label":t(`backup.backupEntriesTable.enable`,`Enable {{value1}}`,{value1:e.label||e.id})})})}function Et({row:e}){let{t:n}=G(),i=s(),a=R({onSuccess:()=>{i.invalidateQueries({queryKey:yt})}}),o=wt(e),[l,u]=r(String(e.retentionCount));return t(()=>{u(String(e.retentionCount))},[e.retentionCount]),c(me,{type:`number`,min:1,max:1e3,value:l,disabled:a.isPending,onChange:e=>u(e.target.value),onBlur:()=>{let t=Number.parseInt(l,10);if(Number.isNaN(t)||t<1){u(String(e.retentionCount));return}t!==e.retentionCount&&a.mutate({...o,enabled:e.enabled,retentionCount:t})},onKeyDown:t=>{t.key===`Enter`&&t.target.blur(),t.key===`Escape`&&u(String(e.retentionCount))},className:`w-16`,"aria-label":n(`backup.backupEntriesTable.retentionFor`,`Retention for {{value1}}`,{value1:e.label||e.id})})}function Dt({row:e,onEdit:t}){let{t:n}=G(),r=s(),i=z(),o=re({onSuccess:()=>{r.invalidateQueries({queryKey:yt})}}),u=ze({onMutate:()=>{r.invalidateQueries({queryKey:[[`backup`,`listRuns`]]})},onSuccess:()=>{r.invalidateQueries({queryKey:[[`backup`,`listArchives`]]}),r.invalidateQueries({queryKey:[[`backup`,`listDestinations`]]}),r.invalidateQueries({queryKey:[[`backup`,`listRuns`]]})}}),f=()=>{e.locationIds.length!==0&&u.mutate({destinations:[...e.locationIds],...e.dataSources&&e.dataSources.length>0?{locations:[...e.dataSources]}:{},label:e.label,retentionCount:e.retentionCount,databases:[...X(e.databases)]})},m=async()=>{await i({title:n(`backup.backupEntriesTable.deleteBackupEntry`,`Delete backup entry?`),message:n(`backup.backupEntriesTable.willStopRunningExistingArchives`,`"{{value1}}" will stop running. Existing archives are kept.`,{value1:e.label||e.id}),confirmLabel:n(`common.delete`,`Delete`),variant:`warning`})&&o.mutate({id:e.id})};return a(`span`,{className:`flex items-center justify-end gap-1.5`,children:[a(V,{size:`sm`,type:`button`,onClick:f,disabled:u.isPending||e.locationIds.length===0,title:n(`backup.backupEntriesTable.runThisEntryNow`,`Run this entry now`),children:[u.isPending?c(k,{className:`h-3 w-3 animate-spin`}):c(l,{className:`h-3 w-3`}),n(`backup.backupEntriesTable.runNow`,`Run now`)]}),c(H,{variant:`ghost`,size:`sm`,icon:d,"aria-label":n(`backup.backupEntriesTable.edit`,`Edit {{value1}}`,{value1:e.label||e.id}),onClick:t}),c(H,{variant:`ghost`,size:`sm`,icon:p,"aria-label":n(`backup.backupEntriesTable.delete`,`Delete {{value1}}`,{value1:e.label||e.id}),disabled:o.isPending,onClick:()=>{m()}})]})}function Ot({row:e,destById:t,onOpenRestoreWizard:n}){let{t:r}=G();return a(`div`,{className:`space-y-4 rounded-lg border border-border bg-background/30 px-4 py-3`,children:[c(`p`,{className:`text-[11px] font-medium text-foreground-subtle`,children:r(`backup.backupEntriesTable.archivesFor`,{name:e.label||e.id})}),e.locationIds.length===0&&c(`p`,{className:`text-xs italic text-foreground-subtle`,children:r(`backup.backupEntriesTable.thisEntryHasNoLocations`,`This entry has no locations selected.`)}),e.locationIds.map(e=>a(`div`,{className:`space-y-1.5`,children:[c(`div`,{className:`text-[11px] font-medium text-foreground-subtle`,children:t.get(e)?.displayName??e}),c(gt,{destinationId:e,restoreSupported:t.get(e)?.restoreSupported??!0,...n?{onOpenRestoreWizard:n}:{}})]},e))]})}function kt({selected:e,onChange:t,disabled:n=!1,testId:r=`backup-databases`}){let{t:i}=G(),o=le().data,s=e.size>0&&dt(Y(e)),l=e.size===0?`Pick at least one.`:s?`Snapshots only: configuration and files are not part of this backup.`:null;return c(U,{label:i(`backup.backupDatabasePicker.whatToBackUp`,`What to back up`),required:!0,...l===null?{}:{description:l},children:c(`div`,{className:`divide-y divide-border rounded border border-border bg-background`,"data-testid":r,children:nt.map(i=>{let s=ct(i,o),l=n||lt(i,o,e);return a(`label`,{className:`flex items-start gap-2 px-3 py-2 text-xs ${l?`opacity-60`:`cursor-pointer hover:bg-primary/5`}`,children:[c(ue,{checked:e.has(i),disabled:l,onChange:()=>t(ut(e,i)),"data-testid":`${r}-${i}`}),a(`span`,{className:`min-w-0 flex-1`,children:[c(`span`,{className:`flex flex-wrap items-center gap-1.5 text-foreground`,children:it(i)}),c(`span`,{className:`block text-[11px] text-foreground-subtle`,children:s===`absent`?rt():ot(i)})]})]},i)})})})}e();function At({onClose:e}){let{t}=G(),n=s(),[i,o]=r(new Set(J)),u=ze({onMutate:()=>{n.invalidateQueries({queryKey:[[`backup`,`listRuns`]]})},onSuccess:()=>{n.invalidateQueries({queryKey:[[`backup`,`listArchives`]]}),n.invalidateQueries({queryKey:[[`backup`,`listDestinations`]]}),n.invalidateQueries({queryKey:[[`backup`,`listRuns`]]}),e()}});return c(ge,{open:!0,onOpenChange:t=>!t&&e(),children:a(B,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[a(Fe,{children:[c(Ee,{children:t(`backup.backupNowDialog.backUpNow`,`Back up now`)}),c(`p`,{className:`text-xs text-foreground-subtle`,children:t(`backup.backupNowDialog.runsOnceAndWritesThe`,`Runs once and writes the archive to every enabled backup location.`)})]}),c(I,{children:a(`div`,{className:`p-4`,children:[c(kt,{selected:i,onChange:o,disabled:u.isPending,testId:`backup-now-databases`}),u.error&&c(`p`,{role:`alert`,className:`pt-2 text-xs text-danger`,children:u.error.message})]})}),a(Me,{children:[c(V,{variant:`outline`,size:`sm`,onClick:e,children:t(`common.cancel`,`Cancel`)}),a(V,{size:`sm`,onClick:()=>{i.size!==0&&u.mutate(ft(i))},disabled:i.size===0||u.isPending,"data-testid":`backup-now-run`,children:[u.isPending?c(k,{className:`h-3.5 w-3.5 animate-spin`}):c(l,{className:`h-3.5 w-3.5`}),t(`backup.backupNowDialog.backUpNow`,`Back up now`)]})]})]})})}e();function jt(e){return e===null?`—`:new Date(e).toLocaleString()}function Mt(e){let t=new Blob([`${e.secretKey}\n`],{type:`text/plain`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=`camstack-backup-key-${e.keyId}.txt`,r.click(),URL.revokeObjectURL(n)}function Nt({revealed:e,onDone:t}){let{t:n}=G(),[i,o]=r(!1),[s,l]=r(!1);return c(ge,{open:!0,onOpenChange:e=>!e&&i&&t(),children:a(B,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`border-danger/40`,"aria-labelledby":`backup-key-title`,children:[c(Fe,{children:c(Ee,{id:`backup-key-title`,children:n(`backup.encryptionCard.yourKey`,{keyId:e.keyId})})}),a(I,{className:`space-y-3`,children:[a(`p`,{className:`flex items-start gap-2 rounded-md border border-danger/40 bg-danger/10 p-2 text-xs text-foreground`,children:[c(h,{className:`mt-0.5 h-4 w-4 shrink-0 text-danger`}),c(`span`,{children:n(`backup.backupEncryptionCard.thisKeyIsShownOnly`,`This key is shown only once. CamStack does not keep it — not the hub, not its database, not its backups. Without it, an encrypted backup cannot be restored by anyone, including you. Store it in a password manager or print it, away from this server.`)})]}),c(`div`,{className:`break-all rounded-md border border-border bg-background p-2 font-mono text-xs text-foreground select-all`,children:e.secretKey}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(V,{size:`sm`,variant:`outline`,onClick:()=>{navigator.clipboard?.writeText(e.secretKey).then(()=>l(!0))},children:[c(_,{className:`mr-1 h-3.5 w-3.5`}),s?n(`backup.backupEncryptionCard.copied`,`Copied`):n(`common.copy`,`Copy`)]}),a(V,{size:`sm`,variant:`outline`,onClick:()=>Mt(e),children:[c(f,{className:`mr-1 h-3.5 w-3.5`}),n(`backup.backupEncryptionCard.downloadAsFile`,`Download as file`)]})]}),a(`label`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[c(`input`,{type:`checkbox`,checked:i,onChange:e=>o(e.target.checked),className:`accent-primary`}),n(`backup.backupEncryptionCard.iHaveStoredThisKey`,`I have stored this key somewhere safe, off this server.`)]})]}),c(Me,{children:c(V,{size:`sm`,disabled:!i,onClick:t,children:n(`backup.backupEncryptionCard.iHaveStoredIt`,`I have stored it`)})})]})})}function Pt(){let{t:e}=G(),t=Oe(),n=_e(),i=pe(),s=z(),[l,u]=r(null),[d,f]=r(null),p=t.data?.enabled??!1,m=t.data?.active??null,h=(t.data?.keys??[]).filter(e=>e.retiredAt!==null),g=async()=>{if(await s({title:p?e(`backup.backupEncryptionCard.replaceTheBackupKey`,`Replace the backup key`):e(`backup.backupEncryptionCard.encryptBackups`,`Encrypt backups`),message:p?e(`backup.backupEncryptionCard.aNewKeyIsGenerated`,`A new key is generated and shown once; new backups are encrypted to it. Older backups keep needing the key they were made with — keep that one too.`):e(`backup.backupEncryptionCard.aBackupKeyIsGenerated`,`A backup key is generated and shown once. Every new backup is encrypted to it, and restoring one will ask for it. Existing backups stay as they are.`),confirmLabel:p?e(`backup.backupEncryptionCard.generateANewKey`,`Generate a new key`):e(`backup.backupEncryptionCard.generateTheKey`,`Generate the key`),variant:`warning`})){f(null);try{let e=await n.mutateAsync({});u({keyId:e.keyId,secretKey:e.secretKey})}catch(e){f(e instanceof Error?e.message:String(e))}}},_=async()=>{if(await s({title:e(`backup.backupEncryptionCard.turnBackupEncryptionOff`,`Turn backup encryption off`),message:e(`backup.backupEncryptionCard.newBackupsWillBeWritten`,`New backups will be written unencrypted. Existing encrypted backups still need their key to be restored.`),confirmLabel:e(`backup.backupEncryptionCard.turnOff`,`Turn off`),variant:`danger`})){f(null);try{await i.mutateAsync({}),t.refetch()}catch(e){f(e instanceof Error?e.message:String(e))}}};return a(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-4`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`flex items-center gap-2`,children:[p?c(A,{className:`h-4 w-4 text-success`}):c(T,{className:`h-4 w-4 text-foreground-subtle`}),c(`h2`,{className:`text-sm font-semibold text-foreground`,children:e(`backup.backupEncryptionCard.encryption`,`Encryption`)}),c(`span`,{className:`text-xs text-foreground-subtle`,children:p&&m!==null?e(`backup.backupEncryptionCard.onKeySince`,`On — key {{keyId}}, since {{value2}}`,{keyId:m.keyId,value2:jt(m.createdAt)}):e(`backup.backupEncryptionCard.offBackupsAreNotEncrypted`,`Off — backups are not encrypted`)})]}),c(`div`,{className:`flex gap-2`,children:p?a(o,{children:[c(V,{size:`sm`,variant:`outline`,disabled:n.isPending,onClick:()=>void g(),children:e(`backup.backupEncryptionCard.replaceKey`,`Replace key`)}),c(V,{size:`sm`,variant:`outline`,disabled:i.isPending,onClick:()=>void _(),children:e(`backup.backupEncryptionCard.turnOff`,`Turn off`)})]}):c(V,{size:`sm`,disabled:n.isPending,onClick:()=>void g(),children:e(`backup.backupEncryptionCard.enableEncryption`,`Enable encryption`)})})]}),c(`p`,{className:`text-xs text-foreground-subtle`,children:e(`backup.backupEncryptionCard.archivesAreEncryptedOnThis`,`Archives are encrypted on this server before they reach any destination. The server keeps only a public key, so it can encrypt scheduled backups but cannot decrypt them — only your backup key can. Covers the database snapshot, config.yaml, addon data (HomeKit pairing, Matter fabric, Tailscale state) and TLS.`)}),h.length>0&&a(`div`,{className:`text-xs`,children:[c(`p`,{className:`text-foreground-subtle`,children:e(`backup.backupEncryptionCard.olderKeysBackupsMadeWith`,`Older keys (backups made with them still need them):`)}),c(`ul`,{className:`font-mono text-foreground`,children:h.map(e=>a(`li`,{children:[e.keyId,` · `,jt(e.createdAt),` → `,jt(e.retiredAt)]},e.keyId))})]}),d!==null&&c(`p`,{className:`text-xs text-danger`,children:d}),l!==null&&c(Nt,{revealed:l,onDone:()=>{u(null),t.refetch()}})]})}e();var Ft=[{id:`manual`,labelKey:`backup.cronEditor.presetManual`,cron:``},{id:`hourly`,labelKey:`backup.cronEditor.presetHourly`,cron:`0 * * * *`,descriptionKey:`backup.cronEditor.presetHourlyDesc`},{id:`every-3h`,labelKey:`backup.cronEditor.preset3h`,cron:`0 */3 * * *`,description:`00:00, 03:00, 06:00, 09:00 …`},{id:`every-6h`,labelKey:`backup.cronEditor.preset6h`,cron:`0 */6 * * *`,description:`00:00, 06:00, 12:00, 18:00`},{id:`daily-3am`,labelKey:`backup.cronEditor.presetDaily`,cron:`0 3 * * *`,descriptionKey:`backup.cronEditor.presetDailyDesc`},{id:`weekly-sun`,labelKey:`backup.cronEditor.presetWeekly`,cron:`0 3 * * 0`,descriptionKey:`backup.cronEditor.presetWeeklyDesc`}];function It(e){let t=e.trim();for(let e of Ft)if(e.cron===t)return e.id;return`custom`}function Lt({value:e,onChange:n,previewCount:i=5,disabled:o=!1}){let{t:s}=G(),l=It(e),[u,d]=r(l===`custom`);t(()=>{l!==`custom`&&d(!1)},[l]);let f=Bt(e,250),p=se({cron:f,count:i},{enabled:f.trim().length>0}),m=p.data??null,h=e=>{d(!1),n(e.cron)},g=u||l===`custom`;return a(`div`,{className:`space-y-3`,children:[a(`div`,{className:`space-y-1`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:s(`backup.cronEditor.schedulePreset`,`Schedule preset`)}),a(`div`,{className:`flex flex-wrap gap-1.5`,children:[Ft.map(e=>c(`button`,{type:`button`,onClick:()=>h(e),disabled:o,className:`rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 `+(!u&&l===e.id?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground`),title:e.descriptionKey===void 0?e.description??s(e.labelKey):s(e.descriptionKey),children:s(e.labelKey)},e.id)),c(`button`,{type:`button`,onClick:()=>{d(!0),e.trim().length===0&&n(`0 3 * * *`)},disabled:o,className:`rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 `+(g?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground`),children:s(`backup.cronEditor.custom`,`Custom…`)})]})]}),g&&a(`div`,{className:`space-y-1`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:s(`backup.cronEditor.cronExpression5FieldPosix`,`Cron expression (5-field POSIX)`)}),c(`input`,{type:`text`,value:e,onChange:e=>n(e.target.value),disabled:o,placeholder:`0 3 * * *`,spellCheck:!1,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`}),a(`p`,{className:`text-[10px] text-foreground-subtle`,children:[s(`backup.cronEditor.format`,`Format:`),` `,c(He,{i18nKey:`backup.cronEditor.formatLine`,components:{code:c(`span`,{className:`font-mono`})}})]})]}),c(Rt,{cron:f,preview:m,loading:p.isFetching})]})}function Rt({cron:e,preview:t,loading:n}){let{t:r}=G();return n&&t===null?a(`div`,{className:`flex items-center gap-2 rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle`,children:[c(k,{className:`h-3 w-3 animate-spin`}),r(`backup.cronEditor.validating`,`Validating…`)]}):t===null?null:t.ok?t.nextRuns.length===0?c(`div`,{className:`rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle`,children:r(`backup.cronEditor.noFutureRunsMatchThis`,`No future runs match this expression.`)}):a(`div`,{className:`space-y-1`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:r(`backup.cronEditor.nextRuns`,`Next runs`)}),c(`ul`,{className:`rounded border border-border bg-background/40 divide-y divide-border`,children:t.nextRuns.map((e,t)=>a(`li`,{className:`flex items-center justify-between px-3 py-1.5 text-[11px]`,children:[c(`span`,{className:`text-foreground tabular-nums`,children:new Date(e).toLocaleString()}),c(`span`,{className:`text-foreground-subtle text-[10px] tabular-nums`,children:zt(e)})]},`${e}-${t}`))})]}):c(`div`,{className:`rounded border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:t.error??r(`backup.cronEditor.invalidCronExpression`,`Invalid cron expression`)})}function zt(e){let t=e-Date.now();if(t<=0)return W.t(`helpers.relativeTime.now`);let n=Math.floor(t/1e3);if(n<60)return W.t(`helpers.relativeTime.inSeconds`,{count:n});let r=Math.floor(n/60);if(r<60)return W.t(`helpers.relativeTime.inMinutes`,{count:r});let i=Math.floor(r/60);if(i<24)return W.t(`helpers.relativeTime.inHours`,{count:i});let a=Math.floor(i/24);return W.t(`helpers.relativeTime.inDays`,{count:a})}function Bt(e,i){let[a,o]=r(e),s=n(()=>e,[e]);return t(()=>{let e=setTimeout(()=>o(s),i);return()=>clearTimeout(e)},[s,i]),a}e();var Vt=[[`backup`,`listSchedules`]];function Ht({entry:e,onClose:t,onSaved:i}){let{t:o}=G(),l=s(),u=de(),d=u.data??[],[f,p]=r(e?.label??``),[m,h]=r(e?.cron??`0 3 * * *`),[g,_]=r(e?.enabled??!0),[v,y]=r(String(e?.retentionCount??7)),[b,x]=r(new Set(e?.locationIds??[])),[S,C]=r(new Set(e===null?J:X(e.databases))),w=R({onSuccess:()=>{l.invalidateQueries({queryKey:Vt}),i()}}),T=e=>{x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},E=Number.parseInt(v,10),D=n(()=>f.trim().length>0&&b.size>0&&S.size>0&&!Number.isNaN(E)&&E>=1&&E<=1e3,[f,b,S,E]),O=()=>{D&&w.mutate({...e?{id:e.id}:{},label:f.trim(),cron:m.trim(),enabled:g,locationIds:Array.from(b),retentionCount:E,databases:[...st(S)]})},A=w.error instanceof Error?w.error.message:null;return c(Ce,{open:!0,onClose:t,title:e?o(`backup.backupEntryModal.editBackupEntry`,`Edit backup entry`):o(`backup.backupEntryModal.newBackupEntry`,`New backup entry`),icon:M,error:A,width:`lg`,testId:`backup-entry-form`,footer:a(V,{size:`sm`,type:`button`,onClick:O,disabled:!D||w.isPending,children:[w.isPending?c(k,{className:`h-3.5 w-3.5 animate-spin`}):null,e?o(`common.save`,`Save`):o(`backup.backupEntryModal.createEntry`,`Create entry`)]}),children:a(`div`,{className:`space-y-4`,children:[c(U,{label:o(`backup.backupEntryModal.name`,`Name`),required:!0,children:c(me,{value:f,onChange:e=>p(e.target.value),placeholder:o(`backup.backupEntryModal.nightlyOffsite`,`Nightly offsite`),autoFocus:!0,"data-testid":`backup-entry-name`})}),a(U,{label:o(`backup.backupEntryModal.locationsSelected`,`Locations ({{value1}} selected)`,{value1:String(b.size)}),required:!0,children:[u.isLoading&&a(`div`,{className:`flex items-center gap-2 px-1 py-2 text-xs text-foreground-subtle`,children:[c(k,{className:`h-3.5 w-3.5 animate-spin`}),o(`backup.backupEntryModal.loadingLocations`,`Loading locations…`)]}),!u.isLoading&&d.length===0&&c(`div`,{className:`rounded border border-border bg-background px-3 py-2 text-xs text-foreground-subtle italic`,children:o(`backup.backupEntryModal.noBackupsStorageLocationsConfigured`,"No `backups` storage locations configured. Add one in Settings → Storage first.")}),d.length>0&&c(`div`,{className:`max-h-52 divide-y divide-border overflow-y-auto rounded border border-border bg-background`,children:d.map(e=>a(`label`,{className:`flex cursor-pointer items-center justify-between px-3 py-2 text-xs hover:bg-primary/5`,children:[a(`div`,{className:`flex items-center gap-2`,children:[c(`input`,{type:`checkbox`,checked:b.has(e.id),onChange:()=>T(e.id),className:`accent-primary`}),c(`span`,{className:`text-foreground`,children:e.displayName})]}),a(`div`,{className:`flex items-center gap-1.5`,children:[c(`span`,{className:`rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-foreground-subtle`,children:e.kind}),c(`span`,{className:`font-mono text-[10px] text-foreground-subtle`,children:e.id})]})]},e.id))})]}),c(kt,{selected:S,onChange:C,disabled:w.isPending,testId:`backup-entry-databases`}),a(`div`,{className:`grid grid-cols-2 gap-3`,children:[c(U,{label:o(`backup.backupEntryModal.retentionArchivesKept`,`Retention (archives kept)`),required:!0,children:c(me,{type:`number`,min:1,max:1e3,value:v,onChange:e=>y(e.target.value),"data-testid":`backup-entry-retention`})}),c(U,{label:o(`backup.backupEntryModal.enabled`,`Enabled`),description:o(`backup.backupEntryModal.runOnScheduleWhenChecked`,`Run on schedule when checked.`),children:a(`label`,{className:`inline-flex cursor-pointer items-center gap-2 py-1.5 text-xs text-foreground`,children:[c(`input`,{type:`checkbox`,checked:g,onChange:e=>_(e.target.checked),className:`accent-primary`,"data-testid":`backup-entry-enabled`}),c(`span`,{children:o(`backup.backupEntryModal.runOnSchedule`,`Run on schedule`)})]})})]}),c(U,{label:o(`backup.backupEntryModal.schedule`,`Schedule`),children:c(Lt,{value:m,onChange:h,disabled:w.isPending})})]})})}e();var Ut=2e3,Wt=5e3;function Q(e){return e.state===`queued`||e.state===`running`}function Gt(e){if(e.state===`queued`)return{title:W.t(`backup.backupRunsPanel.cancelQueuedBackupRun`,`Cancel queued backup run?`),message:W.t(`backup.backupRunsPanel.thisRunHasNotStarted`,`This run has not started. Cancelling removes it from the queue — nothing has been written, nothing is deleted.`),confirmLabel:W.t(`backup.backupRunsPanel.cancelRun`,`Cancel run`),variant:`warning`};let t=e.completedDestinationIds.length,n=t>0?`${t===1?`The 1 destination`:`The ${t} destinations`} that already completed KEEP${t===1?`S`:``} the archive.`:`No destination has completed yet, so nothing will be kept.`;return{title:W.t(`backup.backupRunsPanel.stopThisBackupRun`,`Stop this backup run?`),message:W.t(`backup.backupRunsPanel.theHalfWrittenStagingArchive`,`The half-written staging archive is deleted and the destination currently uploading discards its partial copy. {{keptSentence}}`,{keptSentence:n}),confirmLabel:W.t(`backup.backupRunsPanel.stopRun`,`Stop run`),variant:`danger`}}function Kt(){let e=z(),[t,n]=r(null),a=he(void 0,{refetchInterval:e=>(e.state.data??[]).some(Q)?Ut:Wt}),o=ve({onSettled:()=>{n(null),a.refetch()}}),s=i(async t=>{await e(Gt(t))&&(n(t.id),o.mutate({runId:t.id}))},[e,o]);return c(qt,{queryState:a.isError?`error`:a.data===void 0?`pending`:`ready`,runs:a.data??[],cancelingId:t,onCancelRequest:e=>{s(e)},now:Date.now()})}function qt({queryState:e,runs:t,cancelingId:n,onCancelRequest:r,now:i}){let{t:o}=G(),s=e===`ready`&&t.some(Q),l=t.filter(e=>e.state===`running`),u=t.filter(e=>e.state===`queued`),d=t.filter(e=>!Q(e)),f=[...l,...u,...d];return a(`section`,{className:`rounded-lg border border-border bg-surface`,children:[a(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border`,children:[c(`h2`,{className:`text-xs font-semibold text-foreground`,children:o(`backup.backupRunsPanel.runs`,`Runs`)}),s&&a(`span`,{className:`inline-flex items-center gap-1 text-[10px] font-medium text-primary`,title:o(`backup.backupRunsPanel.aBackupRunIsIn`,`A backup run is in progress`),children:[c(`span`,{className:`h-1.5 w-1.5 rounded-full bg-primary animate-pulse`}),o(`backup.runsPanel.live`)]}),c(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:o(`backup.backupRunsPanel.oneRunExecutesAtA`,`One run executes at a time — queued runs wait in line.`)})]}),e===`pending`&&c(`div`,{className:`px-3 py-2.5 text-xs text-foreground-subtle animate-pulse`,children:o(`backup.backupRunsPanel.checkingForBackupRuns`,`Checking for backup runs…`)}),e===`error`&&c(`div`,{className:`px-3 py-2.5 text-xs text-danger`,children:o(`backup.backupRunsPanel.couldNotReadBackupRuns`,`Could not read backup runs — the orchestrator did not answer.`)}),e===`ready`&&t.length===0&&c(`div`,{className:`px-3 py-2.5 text-xs text-foreground-subtle italic`,children:o(`backup.backupRunsPanel.noBackupRunsYetRuns`,`No backup runs yet. Runs appear here the moment one starts — manual or scheduled.`)}),e===`ready`&&t.length>0&&c(`div`,{className:`overflow-x-auto`,children:a(`table`,{className:`w-full text-xs min-w-[720px]`,children:[c(`thead`,{children:a(`tr`,{className:`text-foreground-subtle bg-background/30`,children:[c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.run`,`Run`)}),c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.state`,`State`)}),c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.progress`,`Progress`)}),c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.destinations`,`Destinations`)}),c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.timing`,`Timing`)}),c(`th`,{className:`text-right px-3 py-1.5 font-medium w-28`,children:o(`backup.backupRunsPanel.actions`,`Actions`)})]})}),c(`tbody`,{children:f.map(e=>c(Jt,{run:e,canceling:n===e.id,onCancelRequest:r,now:i},e.id))})]})})]})}function Jt({run:e,canceling:t,onCancelRequest:n,now:r}){let{t:i}=G(),o=Q(e);return a(`tr`,{className:`border-t border-border hover:bg-primary/5 align-top`,children:[c(`td`,{className:`px-3 py-2`,children:c(`div`,{className:`text-foreground`,title:e.id,children:e.label??c(`span`,{className:`text-foreground-subtle italic`,children:i(`backup.runsPanel.manual`)})})}),a(`td`,{className:`px-3 py-2`,children:[c(Yt,{run:e}),e.state===`failed`&&e.error!==void 0&&c(`div`,{className:`mt-1 text-[10px] text-danger max-w-56 truncate`,title:e.error,children:e.error})]}),c(`td`,{className:`px-3 py-2`,children:c(Xt,{run:e})}),c(`td`,{className:`px-3 py-2`,children:c(Zt,{run:e})}),c(`td`,{className:`px-3 py-2 text-foreground-subtle tabular-nums`,children:c(Qt,{run:e,now:r})}),c(`td`,{className:`px-3 py-2`,children:c(`div`,{className:`flex justify-end`,children:o&&a(`button`,{onClick:()=>n(e),disabled:t,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,title:e.state===`queued`?i(`backup.backupRunsPanel.removeThisRunFromThe`,`Remove this run from the queue before it starts`):i(`backup.backupRunsPanel.stopThisRunTheHalf`,`Stop this run — the half-written archive is discarded`),children:[t?c(k,{className:`h-3 w-3 animate-spin`}):c(m,{className:`h-3 w-3`}),e.state===`queued`?i(`common.cancel`,`Cancel`):i(`backup.backupRunsPanel.stop`,`Stop`)]})})})]})}function Yt({run:e}){let{t}=G();switch(e.state){case`queued`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:[c(O,{className:`h-3 w-3`}),t(`backup.backupRunsPanel.queued`,`Queued`)]});case`running`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,children:[c(k,{className:`h-3 w-3 animate-spin`}),e.phase===`uploading`?t(`backup.backupRunsPanel.uploading`,`Uploading`):t(`backup.backupRunsPanel.buildingArchive`,`Building archive`)]});case`succeeded`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-success/10 px-1.5 py-0.5 text-[10px] font-medium text-success`,children:[c(D,{className:`h-3 w-3`}),t(`backup.backupRunsPanel.succeeded`,`Succeeded`)]});case`failed`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-danger/10 px-1.5 py-0.5 text-[10px] font-medium text-danger`,children:[c(C,{className:`h-3 w-3`}),t(`backup.backupRunsPanel.failed`,`Failed`)]});case`cancelled`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300`,title:t(`backup.backupRunsPanel.stoppedBeforeCompletingEveryDestination`,`Stopped before completing every destination — not a success`),children:[c(P,{className:`h-3 w-3`}),t(`backup.backupRunsPanel.stopped`,`Stopped`)]})}}function Xt({run:e}){let{t}=G();if(e.state===`queued`)return c(`span`,{className:`text-foreground-subtle`,children:e.queuePosition===void 0?c(`span`,{className:`italic`,children:t(`backup.backupRunsPanel.waitingItsTurn`,`waiting its turn`)}):a(`span`,{className:`inline-flex items-center gap-1`,children:[c(`span`,{className:e.queuePosition===1?`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`:`rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium`,children:$t(e.queuePosition)}),t(`backup.backupRunsPanel.inLine`,`in line`)]})});if(e.state===`running`&&e.phase===`building`)return a(`span`,{className:`inline-flex items-center gap-1.5 text-foreground`,children:[c(F,{className:`h-3 w-3 text-primary`}),c(`span`,{className:`tabular-nums font-medium animate-pulse`,children:K(e.stagedBytes)}),c(`span`,{className:`text-foreground-subtle`,children:t(`backup.backupRunsPanel.stagedSoFar`,`staged so far`)})]});if(e.state===`running`){let n=e.archiveSizeBytes;return a(`span`,{className:`inline-flex items-center gap-1.5 text-foreground`,children:[c(N,{className:`h-3 w-3 text-primary`}),a(`span`,{className:`tabular-nums font-medium`,children:[K(e.uploadedBytes),n===void 0?``:` / ${K(n)}`]}),c(`span`,{className:`text-foreground-subtle`,children:t(`backup.backupRunsPanel.toCurrentDestination`,`to current destination`)})]})}let n=e.archiveSizeBytes??(e.stagedBytes>0?e.stagedBytes:void 0);return n===void 0?c(`span`,{className:`text-foreground-subtle italic`,children:`—`}):c(`span`,{className:`tabular-nums text-foreground`,children:t(`backup.runsPanel.archiveSize`,{size:K(n)})})}function Zt({run:e}){let{t}=G(),n=e.destinationIds.length,r=e.completedDestinationIds.length,i=e.failedDestinationIds.length;return n===0?c(`span`,{className:`text-foreground-subtle italic`,children:t(`backup.backupRunsPanel.notResolvedYet`,`not resolved yet`)}):a(`div`,{className:`flex flex-col gap-0.5`,children:[c(`span`,{className:`text-foreground-subtle`,title:e.destinationIds.join(`, `),children:t(`backup.runsPanel.targets`,{count:n})}),a(`span`,{className:`inline-flex items-center gap-2 text-[10px]`,children:[r>0&&c(`span`,{className:`text-success`,title:t(`backup.backupRunsPanel.keptTheirArchive`,`Kept their archive: {{value1}}`,{value1:e.completedDestinationIds.join(`, `)}),children:t(`backup.runsPanel.completed`,{count:r})}),i>0&&c(`span`,{className:`text-danger`,title:t(`backup.backupRunsPanel.failed2`,`Failed: {{value1}}`,{value1:e.failedDestinationIds.join(`, `)}),children:t(`backup.runsPanel.failedCount`,{count:i})})]})]})}function Qt({run:e,now:t}){let{t:n}=G();return e.state===`queued`?c(`span`,{children:n(`backup.runsPanel.queuedAgo`,{elapsed:en(t-e.requestedAt)})}):e.startedAt===void 0?c(`span`,{children:`—`}):e.finishedAt===void 0?c(`span`,{children:n(`backup.runsPanel.runningFor`,{elapsed:en(t-e.startedAt)})}):a(`div`,{className:`flex flex-col gap-0.5`,children:[c(`span`,{children:tn(e.finishedAt)}),c(`span`,{className:`text-[10px]`,children:n(`backup.runsPanel.took`,{elapsed:en(e.finishedAt-e.startedAt)})})]})}function $t(e){if(e<=1)return`next`;let t=e%100;if(t>=11&&t<=13)return`${e}th`;switch(e%10){case 1:return`${e}st`;case 2:return`${e}nd`;case 3:return`${e}rd`;default:return`${e}th`}}function en(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${String(t%60).padStart(2,`0`)}s`:`${Math.floor(n/60)}h ${String(n%60).padStart(2,`0`)}m`}function tn(e){return new Date(e).toLocaleString(void 0,{day:`2-digit`,month:`short`,hour:`2-digit`,minute:`2-digit`})}e();var nn=[[`backup`,`list`]];function rn({initialDestinationId:e,initialArchiveId:i,onClose:o,onScheduled:l}){let{t:u}=G(),d=s(),[f,p]=r(e&&i?2:1),[m,h]=r(e),[g,_]=r(i),[v,b]=r(new Set),[S,C]=r(``),{data:w}=de(),T=w??[],{data:E,isLoading:D}=De({destinationId:m??``},{enabled:!!m}),O=E??[];t(()=>{if(m!==void 0)return;let e=T.filter(e=>e.restoreSupported);e.length===1&&h(e[0].id)},[m,T]);let{data:A}=te({destinationId:m??``,backupId:g??``},{enabled:!!m&&!!g}),M=n(()=>A?.locations??[],[A]);t(()=>{M.length!==0&&b(e=>e.size===0?new Set(M):e)},[M]);let N=ce({onSuccess:()=>{d.invalidateQueries({queryKey:nn}),l(),o()}}),P=e=>{b(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},F=O.find(e=>e.id===g),ee=F?.encryption!==void 0,L=pt(F?.databases,A?.sqliteSnapshots),R=dt(L),ne=!!m&&!!g,re=R||v.size>0,ie=ne&&re&&!N.isPending&&(!ee||S.trim().length>0),ae=()=>{!m||!g||N.mutate({destinationId:m,backupId:g,...R?{}:{locations:[...v]},...ee?{backupSecretKey:S.trim()}:{}})};return c(ge,{open:!0,onOpenChange:e=>!e&&o(),children:a(B,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[a(Fe,{children:[c(Ee,{children:u(`backup.restoreWizard.restoreBackup`,`Restore Backup`)}),c(`p`,{className:`text-xs text-foreground-subtle`,children:u(`backup.restoreWizard.stepOf`,{step:f,name:f===1?u(`backup.restoreWizard.pickSource`,`pick source`):f===2?u(`backup.restoreWizard.pickLocations`,`pick locations`):u(`backup.restoreWizard.confirmStep`)})})]}),a(I,{children:[f===1&&c(an,{destinations:T,destinationId:m,onPickDestination:e=>{h(e),_(void 0),b(new Set)},archives:O,archivesLoading:D,archiveId:g,onPickArchive:_}),f===2&&c(on,{locations:M,picked:v,onToggle:P,databases:L,snapshotsOnly:R}),f===3&&c(sn,{destinationName:T.find(e=>e.id===m)?.displayName??m??``,archive:F,picked:[...v],databases:L,snapshotsOnly:R}),f===3&&F?.encryption!==void 0&&c(cn,{keyId:F.encryption.keyId,value:S,onChange:C}),f===3&&N.error&&c(`p`,{role:`alert`,className:`px-4 pb-2 text-xs text-danger`,children:N.error.message})]}),a(Me,{className:`justify-between`,children:[c(`div`,{children:f>1&&a(V,{variant:`outline`,size:`sm`,onClick:()=>p(e=>e===3?2:1),children:[c(x,{className:`h-3 w-3`}),u(`common.back`,`Back`)]})}),a(`div`,{className:`flex items-center gap-2`,children:[c(V,{variant:`outline`,size:`sm`,onClick:o,children:u(`common.cancel`,`Cancel`)}),f<3?a(V,{size:`sm`,disabled:f===1&&!ne||f===2&&!re,onClick:()=>p(e=>e===1?2:3),children:[u(`common.next`,`Next`),c(y,{className:`h-3 w-3`})]}):a(V,{size:`sm`,onClick:ae,disabled:!ie,children:[N.isPending?c(k,{className:`h-3.5 w-3.5 animate-spin`}):c(j,{className:`h-3.5 w-3.5`}),u(`backup.restoreWizard.scheduleRestore`,`Schedule Restore`)]})]})]})]})})}function an({destinations:e,destinationId:t,onPickDestination:n,archives:r,archivesLoading:i,archiveId:o,onPickArchive:s}){let{t:l}=G(),u=e.filter(e=>e.restoreSupported);return a(`div`,{className:`p-4 space-y-3`,children:[a(`div`,{className:`space-y-1.5`,children:[c(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:l(`backup.restoreWizard.destination`,`Destination`)}),c(ne,{value:t??``,onChange:e=>n(e.target.value),options:[{value:``,label:l(`backup.restoreWizard.selectDestination`,`Select destination…`)},...u.map(e=>({value:e.id,label:`${e.displayName} (${e.kind})`}))]})]}),a(`div`,{className:`space-y-1.5`,children:[c(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:l(`backup.restoreWizard.archive`,`Archive`)}),!t&&c(`div`,{className:`text-xs text-foreground-subtle italic`,children:l(`backup.restoreWizard.pickADestinationFirst`,`Pick a destination first.`)}),t&&i&&c(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:l(`backup.restoreWizard.readingArchives`,`Reading archives…`)}),t&&!i&&r.length===0&&c(`div`,{className:`text-xs text-foreground-subtle italic`,children:l(`backup.restoreWizard.noArchivesAvailableAtThis`,`No archives available at this destination.`)}),t&&r.length>0&&c(`div`,{className:`rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto`,children:r.map(e=>{let t=o===e.id;return a(`label`,{className:`flex items-center justify-between px-3 py-2 text-xs cursor-pointer ${t?`bg-primary/10`:`hover:bg-primary/5`}`,children:[a(`div`,{className:`flex items-center gap-2`,children:[c(`input`,{type:`radio`,name:`archive`,checked:t,onChange:()=>s(e.id),className:`accent-primary`}),a(`div`,{children:[a(`div`,{className:`flex items-center gap-1 font-medium text-foreground`,children:[e.encryption!==void 0&&c(A,{className:`h-3 w-3 text-success`,"aria-label":l(`backup.restoreWizard.encryptedKey`,`encrypted (key {{keyId}})`,{keyId:e.encryption.keyId})}),e.label??e.id]}),c(`div`,{className:`text-[10px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()}),c(`div`,{className:`pt-1`,children:c(Z,{databases:pt(e.databases,void 0)})})]})]}),c(`span`,{className:`text-[10px] text-foreground-subtle tabular-nums`,children:K(e.sizeBytes)})]},e.id)})})]})]})}function on({locations:e,picked:t,onToggle:n,databases:r,snapshotsOnly:i}){let{t:o}=G();return i?a(`div`,{className:`space-y-3 p-4`,children:[a(`div`,{className:`space-y-1.5`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:o(`backup.restoreWizard.databasesInThisArchive`,`Databases in this archive`)}),c(Z,{databases:r})]}),c(`div`,{className:`rounded border border-info/30 bg-info/10 px-3 py-2 text-[11px] text-info`,children:o(`backup.restoreWizard.snapshotsOnlyRestoringThisArchive`,`Snapshots only: restoring this archive replaces just these databases. It does NOT touch configuration, addons, addon data or certificates.`)})]}):e.length===0?c(`div`,{className:`p-4`,children:c(`div`,{className:`text-xs text-foreground-subtle`,children:o(`backup.restoreWizard.loadingArchiveManifestIfThis`,`Loading archive manifest… If this persists, the archive may predate manifests — restoring will apply everything in the tarball.`)})}):a(`div`,{className:`p-4 space-y-3`,children:[a(`div`,{className:`space-y-1.5`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:o(`backup.restoreWizard.databasesInThisArchive`,`Databases in this archive`)}),c(Z,{databases:r})]}),c(`div`,{className:`rounded border border-warning/30 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:o(`backup.restoreWizard.selectedEntriesWillOverwriteLive`,`Selected entries will overwrite live data on the next server restart. Unchecked entries stay current.`)}),a(`div`,{className:`space-y-1.5`,children:[c(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:o(`common.apply`,`Apply`)}),c(`div`,{className:`rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto`,children:e.map(e=>a(`label`,{className:`flex items-center gap-2 px-3 py-2 text-xs hover:bg-primary/5 cursor-pointer`,children:[c(`input`,{type:`checkbox`,checked:t.has(e),onChange:()=>n(e),className:`accent-primary`}),c(`span`,{className:`font-mono text-foreground`,children:e}),c(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:un(e)})]},e))})]})]})}function sn({destinationName:e,archive:t,picked:n,databases:r,snapshotsOnly:i}){let{t:o}=G();return a(`div`,{className:`p-4 space-y-3 text-xs`,children:[c(`div`,{className:`rounded border border-warning/30 bg-warning/10 px-3 py-2 text-warning`,children:o(`backup.restoreWizard.restoreIsAppliedAtNext`,`Restore is applied at next server boot. Active connections will drop when you restart.`)}),a(`dl`,{className:`space-y-1.5`,children:[c($,{term:`Destination`,value:e}),c($,{term:`Archive`,value:t?.label??t?.id??`—`}),t&&c($,{term:`Created`,value:`${new Date(t.createdAt).toLocaleString()} · ${K(t.sizeBytes)}`}),a(`div`,{className:`flex justify-between gap-3`,children:[c(`dt`,{className:`text-foreground-subtle`,children:`Databases`}),c(`dd`,{className:`text-right`,children:c(Z,{databases:r})})]}),c($,{term:`Locations`,value:i?`none (configuration is not touched)`:n.length>0?n.join(`, `):`— (full archive)`})]})]})}function cn({keyId:e,value:t,onChange:n}){let{t:r}=G();return a(`div`,{className:`space-y-1.5 px-4 pb-3`,children:[c(`label`,{htmlFor:`restore-backup-key`,className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:r(`backup.restoreWizard.backupKey`,`Backup key`)}),c(`input`,{id:`restore-backup-key`,type:`password`,autoComplete:`off`,spellCheck:!1,value:t,onChange:e=>n(e.target.value),placeholder:r(`backup.restoreWizard.camstackBackupSecretV1`,`camstack-backup-secret-v1:…`),className:`w-full rounded border border-border bg-background px-2 py-1.5 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`}),c(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(He,{i18nKey:`backup.restoreWizard.encryptedTo`,values:{keyId:e},components:{mono:c(`span`,{className:`font-mono`})}})})]})}function $({term:e,value:t}){return a(`div`,{className:`flex justify-between gap-3`,children:[c(`dt`,{className:`text-foreground-subtle`,children:e}),c(`dd`,{className:`text-foreground font-mono text-right truncate`,children:t})]})}var ln={db:`Database`,addons:`Addon configs`,"addons-data":`Addon data`,tls:`TLS certificates`,cache:`Cache`,data:`Top-level data`};function un(e){return ln[e]??``}e();function dn(){let{t:e}=G(),n=z(),i=Ae(),{state:o,openNew:s,openEdit:u,close:d}=je({editKey:`edit`,newKey:`new`}),f=oe(),p=f.data??[],[m,h]=r(null),[g,_]=r(!1),[v,y]=r(!1),[b,x]=r(!1),S=o.mode===`edit`?p.find(e=>e.id===o.id)??null:null;t(()=>{o.mode===`edit`&&!f.isLoading&&S===null&&d()},[o.mode,f.isLoading,S,d]);let C=o.mode===`new`||o.mode===`edit`&&S!==null,w=async()=>{await n({title:e(`system.backup.restartServerNow`,`Restart server now?`),message:e(`system.backup.activeConnectionsWillDropAnd`,`Active connections will drop and the apply-backup hook will run before boot.`),confirmLabel:e(`system.backup.restart`,`Restart`),variant:`warning`})&&i.mutate({confirm:!0})};return a(Ge,{embedded:!0,children:[a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,"data-testid":`backup-actions`,children:[a(V,{variant:`outline`,size:`sm`,type:`button`,onClick:()=>x(!0),"data-testid":`backup-now`,children:[c(l,{className:`h-3.5 w-3.5`}),e(`system.backup.backUpNow`,`Back up now`)]}),a(V,{variant:`outline`,size:`sm`,type:`button`,onClick:()=>_(!0),children:[c(j,{className:`h-3.5 w-3.5`}),e(`system.backup.restore`,`Restore…`)]}),a(V,{size:`sm`,type:`button`,onClick:s,"data-testid":`backup-new-entry`,children:[c(E,{className:`h-3.5 w-3.5`}),e(`system.backup.newEntry`,`New entry`)]})]}),v&&c(`div`,{className:`rounded-lg border border-warning/30 bg-warning/10 px-3 py-2.5 text-xs text-warning`,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{className:`flex items-center gap-2`,children:[c(j,{className:`h-3.5 w-3.5`}),c(`span`,{children:e(`system.backup.restoreScheduledRestartTheServer`,`Restore scheduled. Restart the server to apply.`)})]}),a(V,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{w()},disabled:i.isPending,children:[i.isPending?c(k,{className:`h-3.5 w-3.5 animate-spin`}):c(j,{className:`h-3.5 w-3.5`}),e(`system.backup.restartNow`,`Restart Now`)]})]})}),c(Pt,{}),c(Kt,{}),c(bt,{onEdit:e=>u(e.id),onOpenRestoreWizard:e=>h(e)}),C&&c(Ht,{entry:S,onClose:d,onSaved:d}),b&&c(At,{onClose:()=>x(!1)}),(m||g)&&c(rn,{...m?{initialDestinationId:m.destinationId,initialArchiveId:m.archiveId}:{},onClose:()=>{h(null),_(!1)},onScheduled:()=>y(!0)})]})}e();function fn(e){return Object.entries(e).map(([e,t])=>`${e} ${t}`).join(` · `)}function pn(e){return e.reduce((e,t)=>e+Object.values(t.stores).reduce((e,t)=>e+t,0),0)}function mn(){let{t:e}=G(),t=z(),n=ee(),[i,s]=r(null),[l,u]=r(null),d=async e=>{u(null);try{s(await n.mutateAsync({confirm:e}))}catch(e){u(e instanceof Error?e.message:String(e))}},f=async()=>{i===null||i.status!==`dry-run`||await t({title:e(`systemPage.deletedDevices.confirmTitle`,`Delete the data of deleted devices?`),message:i.devices.map(e=>`#${e.deviceId}: ${fn(e.stores)}`).join(`
2
- `),confirmLabel:e(`systemPage.deletedDevices.confirmLabel`,`Delete`),variant:`danger`})&&await d(!0)},m=[{key:`device`,header:e(`systemPage.deletedDevices.device`,`Device`),render:e=>`#${e.deviceId}`},{key:`stores`,header:e(`systemPage.deletedDevices.stores`,`Data held`),nowrap:!1,render:e=>fn(e.stores)}];return a(`div`,{className:`space-y-4`,"data-testid":`deleted-devices-data`,children:[c(`p`,{className:`text-sm text-foreground-muted`,children:e(`systemPage.deletedDevices.intro`,`Data that still belongs to devices that were deleted before deletions were recorded: footage, events, history and per-addon settings. Scanning deletes nothing; deleting asks first and shows what goes.`)}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(V,{variant:`outline`,onClick:()=>void d(!1),disabled:n.isPending,"data-testid":`deleted-devices-scan`,children:[n.isPending?c(k,{className:`mr-2 h-4 w-4 animate-spin`}):c(w,{className:`mr-2 h-4 w-4`}),e(`systemPage.deletedDevices.scan`,`Scan`)]}),i?.status===`dry-run`&&i.devices.length>0?a(V,{variant:`danger`,onClick:()=>void f(),disabled:n.isPending,"data-testid":`deleted-devices-delete`,children:[c(p,{className:`mr-2 h-4 w-4`}),e(`systemPage.deletedDevices.delete`,`Delete the data of {{count}} devices…`,{count:i.devices.length})]}):null]}),l===null?null:c(`p`,{className:`text-sm text-danger`,children:l}),i?.status===`skipped`?c(`p`,{className:`text-sm text-warning`,"data-testid":`deleted-devices-skipped`,children:e(`systemPage.deletedDevices.skipped`,`Nothing was listed or deleted: the device list could not be trusted ({{reason}}). Try again.`,{reason:i.reason??``})}):null,i!==null&&i.status!==`skipped`?a(o,{children:[c(`p`,{className:`text-sm`,"data-testid":`deleted-devices-summary`,children:i.status===`cleaned`?e(`systemPage.deletedDevices.cleaned`,`Deleted {{rows}} items of {{count}} devices.`,{rows:pn(i.devices),count:i.devices.length}):e(`systemPage.deletedDevices.found`,`{{count}} deleted devices still hold {{rows}} items.`,{rows:pn(i.devices),count:i.devices.length})}),c(Te,{columns:m,rows:i.devices,rowKey:e=>e.deviceId,emptyMessage:e(`systemPage.deletedDevices.none`,`No data belongs to a deleted device.`)}),i.unreachable.length>0?c(`p`,{className:`text-xs text-foreground-muted`,children:e(`systemPage.deletedDevices.unreachable`,`Not asked (unreachable): {{names}}`,{names:i.unreachable.join(`, `)})}):null]}):null]})}var hn=`view`,gn=`kinds`,_n=`deleted-devices`;function vn(){let{t:e}=G(),[t,n]=Ue(),r=t.get(`view`)===`deleted-devices`?_n:gn;return a(`div`,{className:u,children:[a(`div`,{className:`mb-3 space-y-2`,children:[c(ie,{appearance:`pills`,value:r,onValueChange:e=>{n(t=>{let n=new URLSearchParams(t);return e===`kinds`?n.delete(hn):n.set(hn,e),n},{replace:!0})},children:a(ke,{className:`flex flex-wrap gap-1`,children:[c(L,{value:gn,children:e(`systemPage.data.viewKinds`,`Record kinds`)}),c(L,{value:_n,children:e(`systemPage.data.viewDeletedDevices`,`Deleted devices`)})]})}),r===`kinds`?c(`p`,{className:`text-xs text-foreground-muted`,children:e(`systemPage.data.recordsUnifiedIntro`,`Every declared record kind on this hub. Entry kinds can be added, edited and deleted; the rest are read-only. Secret fields are redacted.`)}):null]}),c(r===`kinds`?xe:mn,{})]})}var yn={entries:null,"deleted-devices":`deleted-devices`};function bn(){let{t:e}=G(),t=Ve(`/system/data`,{t:e,isAdmin:!0})??{icon:b,title:e(`system.data`,`Data`)},[n]=Ue(),r=yn[n.get(`tab`)??``];if(r!==void 0){let e=new URLSearchParams(n);return e.set(`tab`,`records`),r!==null&&e.set(`view`,r),c(Be,{replace:!0,to:{search:e.toString()}})}return c(We,{icon:t.icon,title:t.title,defaultSection:`storage`,sectionsLabel:`${t.title} sections`,sections:[{id:`storage`,label:e(`systemPage.data.storage`,`Storage`),content:c(tt,{})},{id:`records`,label:e(`systemPage.data.records`,`Records`),content:c(vn,{}),ownedParams:[`view`,`recordsOwner`,`recordsKind`,`entryNew`,`entryEdit`]},{id:`backup`,label:e(`systemPage.data.backup`,`Backup`),content:c(dn,{})}]})}export{bn as DataPage};