@camstack/addon-admin-ui 1.2.634 → 1.2.635

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 (161) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/assets/Addons-it-7xyWO.js +5 -0
  3. package/dist/assets/{AdminPage-CPPoleZA.js → AdminPage-C28MWSEJ.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-C_DLslGH.js → AdminSectionedPage-N7ZzoaCA.js} +1 -1
  5. package/dist/assets/AiProfiles-DvvGmPqc.js +3 -0
  6. package/dist/assets/Authentication-CdkAuFpQ.js +1 -0
  7. package/dist/assets/Build-Dj-J_LDL.js +39 -0
  8. package/dist/assets/Calendars-Bl2YxKcY.js +1 -0
  9. package/dist/assets/{CameraGrids-CIJubNTN.js → CameraGrids-BmuQfQwD.js} +1 -1
  10. package/dist/assets/Cluster-BHVazygn.js +1 -0
  11. package/dist/assets/CompositionBlockEditor-BJo6-Hg-.js +2 -0
  12. package/dist/assets/{CompositionEditorPage-jP0e8vX8.js → CompositionEditorPage-CSgC3j3b.js} +1 -1
  13. package/dist/assets/Data-DMpGwsud.js +2 -0
  14. package/dist/assets/DeviceDetail-C5qPLFqX.js +2 -0
  15. package/dist/assets/{Devices-Ddhmovvw.js → Devices-DfUS0XHQ.js} +1 -1
  16. package/dist/assets/{EmbedPlayerPage-B9wkgcPc.js → EmbedPlayerPage-CXqkku3M.js} +1 -1
  17. package/dist/assets/History-Bu9dClRP.js +1 -0
  18. package/dist/assets/Identity-P-9FfQY9.js +1 -0
  19. package/dist/assets/InstancesTable-D2wYEpEv.js +1 -0
  20. package/dist/assets/IntegrationDetail-Ckv-pM-X.js +1 -0
  21. package/dist/assets/Integrations-BAN_fC9m.js +1 -0
  22. package/dist/assets/Integrations-DM8ICLWP.js +2 -0
  23. package/dist/assets/{Library-COZVDG1J.js → Library-Boz_glAa.js} +1 -1
  24. package/dist/assets/Locations-G2ggYLH1.js +3 -0
  25. package/dist/assets/{Logs-_Lymv-hK.js → Logs-BUWUMnM2.js} +1 -1
  26. package/dist/assets/{MaskShapeCanvas-Dkn9mTx5.js → MaskShapeCanvas-GSzxL0sb.js} +1 -1
  27. package/dist/assets/{MotionZonesSettings-DbJd1q0y.js → MotionZonesSettings-zuXI8WDy.js} +1 -1
  28. package/dist/assets/MyAccess-BEvsl84G.js +2 -0
  29. package/dist/assets/Network-Q3AVjSDy.js +1 -0
  30. package/dist/assets/NodeAddonsSettingsPanel-DY9KrknX.js +1 -0
  31. package/dist/assets/Notifications-B09FRQLf.js +1 -0
  32. package/dist/assets/{Pipeline-CBIucM6P.js → Pipeline-DzMkRdB8.js} +1 -1
  33. package/dist/assets/{PrivacyMaskSettings-B7mOaiDG.js → PrivacyMaskSettings-B4NUHvPx.js} +1 -1
  34. package/dist/assets/Recordings-d918Fao6.js +1 -0
  35. package/dist/assets/{ScanSubnetEditor-g4rMYaaa.js → ScanSubnetEditor-C7Np_Myd.js} +1 -1
  36. package/dist/assets/{SceneMonitorEditor-B99BtkWG.js → SceneMonitorEditor-D5EfTLG4.js} +1 -1
  37. package/dist/assets/SessionsList--ByXUdry.js +2 -0
  38. package/dist/assets/{Showroom-BlMJHK6P.js → Showroom-CpQU2YYQ.js} +1 -1
  39. package/dist/assets/{StorageLocationsTable-BCc20Y-P.js → StorageLocationsTable-Cb-zvsAa.js} +1 -1
  40. package/dist/assets/{System-_om1Qy_Z.js → System-c-od2eUi.js} +1 -1
  41. package/dist/assets/{Templates-ClUtf6zo.js → Templates-DbOHcEoP.js} +1 -1
  42. package/dist/assets/{Terminal-CK-OPJi8.js → Terminal-vgjKTZ6i.js} +3 -3
  43. package/dist/assets/{TrainingProviders-CMfEG1p0.js → TrainingProviders-DwApoYD1.js} +1 -1
  44. package/dist/assets/{Viewer-D8ErfEDa.js → Viewer-wmQSDFx4.js} +1 -1
  45. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-D5EjGbog.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BJYMJYN7.js} +1 -1
  46. package/dist/assets/{action-draft-BF1Yv5wJ.js → action-draft-SrqFGFVW.js} +1 -1
  47. package/dist/assets/{ai-page.helpers-7-YKMWA7.js → ai-page.helpers-C_Yr1xBa.js} +1 -1
  48. package/dist/assets/{archive-WByIhorf.js → archive-CnD3EIbI.js} +1 -1
  49. package/dist/assets/{assignment-candidates-CerZJluZ.js → assignment-candidates-JnnkKMNk.js} +1 -1
  50. package/dist/assets/{authed-media-vTZUQ8BO.js → authed-media-b_KsU6o6.js} +1 -1
  51. package/dist/assets/{bell-off-HUbueWAa.js → bell-off-DXoIeft3.js} +1 -1
  52. package/dist/assets/{board-model-BeY6U40R.js → board-model-Dhq6ifuR.js} +1 -1
  53. package/dist/assets/{boxes-Sn1wqpgK.js → boxes-2HiFvbRi.js} +1 -1
  54. package/dist/assets/{calendar-clock-TWIEL7Fd.js → calendar-clock-BdVpCjGZ.js} +1 -1
  55. package/dist/assets/{circle-arrow-up-BZb1tft0.js → circle-arrow-up-DtE1a3jK.js} +1 -1
  56. package/dist/assets/circle-slash-DD5DGeBE.js +1 -0
  57. package/dist/assets/client-DtixJSIH.js +839 -0
  58. package/dist/assets/create-composition-CdHcgM5T.js +2 -0
  59. package/dist/assets/crop-DtJsKDRR.js +1 -0
  60. package/dist/assets/{database-zap-DDQJWo1I.js → database-zap-hwvWqFAr.js} +1 -1
  61. package/dist/assets/{device-integration-icon-BEojiV6j.js → device-integration-icon-JcbJW-sx.js} +1 -1
  62. package/dist/assets/device-picker-model-BhZ3nUKX.js +1 -0
  63. package/dist/assets/dist-DN98Ncd8.js +839 -0
  64. package/dist/assets/{dist-BAkSt7-o.js → dist-DtXy-_hV.js} +1 -1
  65. package/dist/assets/{eraser-BXfY9g0S.js → eraser-0igUeEn4.js} +1 -1
  66. package/dist/assets/{file-up-CGHZOKg0.js → file-up-Bim5lEKk.js} +1 -1
  67. package/dist/assets/{format-C6WZEo_1.js → format-ClefNnBA.js} +1 -1
  68. package/dist/assets/{framework-packages-DoBKjjer.js → framework-packages-B0ugw-Ay.js} +1 -1
  69. package/dist/assets/{hard-drive-download-B12jnOmz.js → hard-drive-download-BqaDoqeT.js} +1 -1
  70. package/dist/assets/{hostInit-DvgZnKz2.js → hostInit-Zt1c3yOY.js} +1 -1
  71. package/dist/assets/i18n-xBJb_nV7.js +1 -0
  72. package/dist/assets/icons-DWvhrrHw.js +1 -0
  73. package/dist/assets/index-BZIzoUuI.css +2 -0
  74. package/dist/assets/index-IUYaCNr3.js +4 -0
  75. package/dist/assets/{key-C7vcpiqV.js → key-OpPYfUdn.js} +1 -1
  76. package/dist/assets/{languages-NIG6fIsC.js → languages-NKFv36FH.js} +1 -1
  77. package/dist/assets/{layers-igKznkhu.js → layers-BYYEeSk8.js} +1 -1
  78. package/dist/assets/{link-2-off-ViXG09ia.js → link-2-off-BQUSK1Q1.js} +1 -1
  79. package/dist/assets/{linked-devices-model-Coihabk7.js → linked-devices-model-CNibZiAj.js} +1 -1
  80. package/dist/assets/{memory-stick-Cb3rfsma.js → memory-stick-FrjSgbSx.js} +1 -1
  81. package/dist/assets/{message-square-plus-MY_vmmYC.js → message-square-plus-R1KzFT_3.js} +1 -1
  82. package/dist/assets/{mf-entry-bootstrap-0-bf765b1e.js → mf-entry-bootstrap-0-b11ec2f0.js} +2 -2
  83. package/dist/assets/{mic-off-DQbHj0Dp.js → mic-off-D-uv270W.js} +1 -1
  84. package/dist/assets/{monitor-off-KvLmRgXm.js → monitor-off-23GJfNCk.js} +1 -1
  85. package/dist/assets/{monitor-smartphone-wbkRUoUy.js → monitor-smartphone-Bv9btLO7.js} +1 -1
  86. package/dist/assets/mount-BhZ3nUKX.js +1 -0
  87. package/dist/assets/{notification-rule-status-DSPA2LGi.js → notification-rule-status-CSdUF_tS.js} +1 -1
  88. package/dist/assets/{player-overlays-D2iM_dnq.js → player-overlays-DS6dT7SD.js} +1 -1
  89. package/dist/assets/remoteEntry-C8Nu6Wkp.js +1 -0
  90. package/dist/assets/{ruler-Cnh0qH1K.js → ruler-B5-PAq3K.js} +1 -1
  91. package/dist/assets/{scan-eye-B57MjUsN.js → scan-eye-B6Jzl98g.js} +1 -1
  92. package/dist/assets/{scissors-jk6_pSRI.js → scissors-DSuf9Nu7.js} +1 -1
  93. package/dist/assets/{search-x-KiZ1cgFX.js → search-x-DikQGG4z.js} +1 -1
  94. package/dist/assets/{send-DAC8bZ9x.js → send-DjOMX7BE.js} +1 -1
  95. package/dist/assets/{settings-2-B5Wblm0D.js → settings-2-RGt6KSqH.js} +1 -1
  96. package/dist/assets/{shapes-C877FMvu.js → shapes-C2fW7MJb.js} +1 -1
  97. package/dist/assets/{sigma-48mqbKtS.js → sigma-BhKqPZ7F.js} +1 -1
  98. package/dist/assets/src-D1sUPCi1.js +169 -0
  99. package/dist/assets/{sso-popup-zJECU9yL.js → sso-popup-C1hR2YBu.js} +1 -1
  100. package/dist/assets/{step-inspector-model-flcREGWU.js → step-inspector-model-BuQhYJra.js} +1 -1
  101. package/dist/assets/{table-2-Dcc8x9NW.js → table-2-CMyjawoR.js} +1 -1
  102. package/dist/assets/{timer-reset-DPB7Vi_P.js → timer-reset-B7vcTXYk.js} +1 -1
  103. package/dist/assets/{ungroup-CaRYV5oo.js → ungroup-cZrrI4SI.js} +1 -1
  104. package/dist/assets/{unlink-B1jawH2n.js → unlink-CU8i3fPe.js} +1 -1
  105. package/dist/assets/{usb-B566yDR8.js → usb-CZTccxRm.js} +1 -1
  106. package/dist/assets/{use-scenes-feed-Cv3Lv9tp.js → use-scenes-feed-DzJr-F4l.js} +1 -1
  107. package/dist/assets/{use-stationary-objects-DPdFLI4G.js → use-stationary-objects-DWdYOvvX.js} +1 -1
  108. package/dist/assets/{useAdminDeviceRemoval-CK79vXvY.js → useAdminDeviceRemoval-BRmWRglP.js} +1 -1
  109. package/dist/assets/useEventInvalidation-BhZ3nUKX.js +1 -0
  110. package/dist/assets/useNodeUrlSelection-BHycntFj.js +1 -0
  111. package/dist/assets/useTemplateSave-BIt_84s3.js +1 -0
  112. package/dist/assets/user-round-Cdt6x46z.js +1 -0
  113. package/dist/assets/{user-x-Dalx5dz-.js → user-x-C8J-JEQi.js} +1 -1
  114. package/dist/assets/{variable-CxFXQLx9.js → variable-B1tjLNN5.js} +1 -1
  115. package/dist/assets/{video-DFWp1_fo.js → video-lKXIQOeO.js} +1 -1
  116. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Dbfg8wPM.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-aKVCr1TV.js} +2 -2
  117. package/dist/index.html +10 -10
  118. package/dist/server/addon.js +302 -14
  119. package/package.json +2 -2
  120. package/dist/assets/Addons-Cng9jF6c.js +0 -5
  121. package/dist/assets/AiProfiles-B6Xt0CM1.js +0 -3
  122. package/dist/assets/Authentication-CkLg9Az9.js +0 -1
  123. package/dist/assets/Build-DMEXJqf9.js +0 -39
  124. package/dist/assets/Calendars-BHc1dbvk.js +0 -1
  125. package/dist/assets/Cluster-CSTB-np5.js +0 -1
  126. package/dist/assets/CompositionBlockEditor-B4WN_aXq.js +0 -2
  127. package/dist/assets/Data-DJFzG2dC.js +0 -2
  128. package/dist/assets/DeviceDetail-3P3i5bd9.js +0 -2
  129. package/dist/assets/History-Cv6TryZt.js +0 -1
  130. package/dist/assets/Identity-Dmwp8J7o.js +0 -1
  131. package/dist/assets/InstanceSwitchCell-xSu6VGOy.js +0 -1
  132. package/dist/assets/InstancesTable-dSeWjA48.js +0 -1
  133. package/dist/assets/IntegrationDetail-oEpvT757.js +0 -1
  134. package/dist/assets/IntegrationHub-CIVmSeKd.js +0 -1
  135. package/dist/assets/Integrations-C5BzsIy2.js +0 -2
  136. package/dist/assets/Integrations-zlHqQ0X9.js +0 -1
  137. package/dist/assets/Locations-CpG6tIMC.js +0 -3
  138. package/dist/assets/MyAccess-3IH5sTuq.js +0 -2
  139. package/dist/assets/Network-DNJ2W_md.js +0 -1
  140. package/dist/assets/NodeAddonsSettingsPanel-BleYmajR.js +0 -1
  141. package/dist/assets/Notifications-C5S8_cBI.js +0 -1
  142. package/dist/assets/Recordings-Dzfu0JHh.js +0 -1
  143. package/dist/assets/SessionsList-DB9t5c5h.js +0 -2
  144. package/dist/assets/circle-slash-Yb1HMMEU.js +0 -1
  145. package/dist/assets/client-BT1qTuWk.js +0 -839
  146. package/dist/assets/create-composition-BCz5rteK.js +0 -2
  147. package/dist/assets/crop-Rp-pMXj8.js +0 -1
  148. package/dist/assets/device-picker-model-DxRFIJt2.js +0 -1
  149. package/dist/assets/dist-MZVzWw2Y.js +0 -839
  150. package/dist/assets/i18n-DO003gOw.js +0 -1
  151. package/dist/assets/icons-CSB91nWL.js +0 -1
  152. package/dist/assets/index-BtIAcMod.js +0 -4
  153. package/dist/assets/index-W6guS92q.css +0 -2
  154. package/dist/assets/key-square-wAKOa45w.js +0 -1
  155. package/dist/assets/mount-DxRFIJt2.js +0 -1
  156. package/dist/assets/remoteEntry-CjzR4ng6.js +0 -1
  157. package/dist/assets/src-Djs5D3BM.js +0 -169
  158. package/dist/assets/useEventInvalidation-DxRFIJt2.js +0 -1
  159. package/dist/assets/useNodeUrlSelection-B4V72DKj.js +0 -1
  160. package/dist/assets/useTemplateSave-sDhvqUj4.js +0 -1
  161. package/dist/assets/user-round-gyXn4SEe.js +0 -1
@@ -1,3 +0,0 @@
1
- import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,o as l,t as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{D as d,Dn as f,G as p,L as m,On as h,Q as g,Qi as _,St as v,Tr as y,Yt as b,cn as x,gt as S,li as C,qi as w,qr as T,un as E,ut as D}from"./player-overlays-D2iM_dnq.js";import{mi as O}from"./client-BT1qTuWk.js";import{n as k,t as A}from"./send-DAC8bZ9x.js";import{t as j}from"./message-square-plus-MY_vmmYC.js";import{$o as M,Ii as N,Jn as P,Kn as F,Li as ee,Lt as I,Oi as L,Ri as R,Yn as z,ai as B,br as te,hf as ne,ii as V,mf as re,mi as ie,oi as H,si as U,vt as ae}from"./src-Djs5D3BM.js";import{t as W}from"./i18n-DO003gOw.js";import{t as G}from"./useTranslation-BJr-n0es.js";import"./mount-DxRFIJt2.js";import{S as K,Wr as q,Z as J}from"./index-BtIAcMod.js";import{t as Y}from"./AdminSectionedPage-C_DLslGH.js";import{t as oe}from"./AdminPage-CPPoleZA.js";import{t as se}from"./InstancesTable-dSeWjA48.js";import{a as ce,c as le,d as ue,f as de,i as fe,l as X,n as pe,o as me,p as he,r as ge,s as Z,t as _e,u as ve}from"./ai-page.helpers-7-YKMWA7.js";c();function ye(){let{t}=G(),n=S(),r=R({functionCap:`llm`}).data??[],a=s({queryKey:pe,queryFn:()=>n.trpcClient.llm.getDefaults.query({})}),o=u({mutationFn:e=>n.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{a.refetch()}}),c=e=>(a.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,l=e=>e===`vision`?t(`ai.defaultVision`,`Default vision profile`):t(`ai.defaultText`,`Default text profile`);return i(F,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${d} grid gap-4 sm:grid-cols-2`,children:ge.map(({purpose:n,visionOnly:a})=>{let s=a?r.filter(X):r,u=c(n),d=r.find(e=>e.id===u);return e(`div`,{children:[i(te,{className:`mb-1 block`,htmlFor:`llm-default-${n}`,children:l(n)}),i(D,{id:`llm-default-${n}`,"aria-label":l(n),value:u,onChange:e=>o.mutate({purpose:n,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:t(`ai.none`,`None`)},...u!==``&&!s.some(e=>e.id===u)?[{value:u,label:d?.name??u}]:[],...s.map(e=>({value:e.id,label:Z(e)===``?e.name:`${e.name} · ${Z(e)}`}))]}),u!==``&&d===void 0&&i(`p`,{className:`mt-1 text-xs text-danger`,children:t(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&i(`p`,{className:`mt-1 text-xs text-warning`,children:t(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:String(o.error)})]},n)})})})}var be=2e3;function Q(e){return W.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function xe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function Se({nodeId:t,value:r,onChange:a}){let{t:c}=G(),l=S(),[d,f]=o(``),[p,m]=o(null),[g,_]=o(!1),v=s({queryKey:_e,queryFn:()=>l.trpcClient.llm.listModelCatalog.query({})}),b=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>l.trpcClient.llm.listNodeModels.query({nodeId:t})}),x=u({mutationFn:e=>l.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(e),_(!1),e.ok&&a({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),w=u({mutationFn:e=>l.trpcClient.llm.installModel.mutate({nodeId:t,model:e}),onSuccess:()=>{_(!0),b.refetch()}}),T=s({queryKey:fe,enabled:w.isPending,refetchInterval:w.isPending?be:!1,queryFn:()=>l.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(e=>e.nodeId===t)?.status?.download,E=n(()=>{let e=(v.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${Q(e.sizeBytes)}`})),n=(b.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(e=>({value:`node:${e.file}`,label:c(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:e.file,size:Q(e.sizeBytes),node:t})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${Q(p.totalBytes)}`}]:[];return[{value:``,label:c(`ai.selectModel`,`Select a model…`)},...e,...n,...r]},[v.data,b.data,p,t,c]),O=e=>{if(e===``){a(null);return}if(e===`custom`){if(p?.ok!==!0)return;a({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=v.data?.find(e=>e.id===t);a({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=b.data?.find(e=>e.file===t);n?.path!==void 0&&a({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},k=e=>{d.trim()!==``&&x.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(I,{label:c(`ai.model`,`Model`),required:!0,children:i(D,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:xe(r),options:E,onChange:e=>O(e.target.value)})}),i(I,{label:c(`ai.hfTitle`,`Add a model from Hugging Face`),description:c(`ai.hfHint`,`Paste a GGUF file URL, or type org/repo — add :QUANT (e.g. unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M) when the repo publishes more than one quantization.`),children:e(`div`,{className:`flex gap-2`,children:[i(re,{"aria-label":c(`ai.hfTitle`,`Add a model from Hugging Face`),value:d,onChange:e=>f(e.target.value),placeholder:c(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),k())}}),e(L,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||x.isPending,onClick:()=>k(),children:[x.isPending?i(y,{className:`h-3.5 w-3.5 animate-spin`}):i(h,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),x.isError&&i(V,{message:x.error instanceof Error?x.error.message:c(`common.error`,`Error`)}),p?.ok===!1&&i(V,{message:p.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>i(L,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),x.mutate({ref:t})},children:e},e)),p.requiredBytes!==void 0&&i(L,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>k(p.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:Q(p.requiredBytes)})})]})}),p?.ok===!0&&e(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),i(N,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),i(N,{variant:`default`,children:Q(p.totalBytes)})]}),p.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(L,{size:`sm`,type:`button`,disabled:w.isPending||g,onClick:()=>w.mutate(p.model),children:[w.isPending?i(y,{className:`h-3.5 w-3.5 animate-spin`}):i(C,{className:`h-3.5 w-3.5`}),g?c(`ai.hfInstalled`,`Downloaded`):c(`ai.hfInstall`,`Download to {{node}}`,{node:t})]}),T!==void 0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:T.phase===`verifying`?c(`ai.hfVerifying`,`verifying {{file}}…`,{file:T.file}):c(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:T.file,index:T.fileIndex,count:T.fileCount,done:Q(T.downloadedBytes),total:T.totalBytes===void 0?``:` / ${Q(T.totalBytes)}`})})]}),w.isError&&i(V,{message:w.error instanceof Error?w.error.message:c(`common.error`,`Error`)})]})]})}function Ce({value:t,onChange:n}){let{t:r}=G(),a=S(),o=s({queryKey:fe,queryFn:()=>a.trpcClient.llm.listRuntimeNodes.query({})});return e(`div`,{children:[i(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:r(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(y,{className:`h-3.5 w-3.5 animate-spin`}),r(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&i(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:r(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&i(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(a=>{let o=me(a),s=o.nodeId===t;return e(L,{variant:`unstyled`,type:`button`,role:`radio`,"aria-checked":s,disabled:!o.selectable&&!s,onClick:()=>n(o.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${s?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block font-medium text-foreground`,children:o.nodeId}),o.detail!==null&&i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:o.detail})]}),i(N,{variant:o.tone,children:r(o.labelKey,o.labelDefault)})]},o.nodeId)})}),i(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:r(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function we(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Te({providerConfig:e,onProviderConfigChange:t}){return i(Ce,{value:we(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function Ee({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=O.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(Se,{nodeId:we(e,`nodeId`)??`hub`,value:o,onChange:n=>{if(n===null){let{model:n,...i}=e;t(i),r({id:``,supportsVision:!1});return}t({...e,model:n.model}),r({id:n.modelId,supportsVision:n.supportsVision})}})}var De=new Map([[`ai/apple-node`,Te],[`ai/managed-model`,Ee]]);function Oe(e){return De.get(e)??null}c();function $(e,t){let n=e[t];return typeof n==`string`?n:``}function ke({row:a}){let{t:c}=G(),d=S(),f=l(),p=s({queryKey:n(()=>[J,a.addonId,`ai-lead`,a.id],[a]),queryFn:async()=>{let e=d.trpcClient.integrationInstances,[t,n]=await Promise.all([e.describe.query({addonId:a.addonId}),e.getInstance.query({addonId:a.addonId,id:a.id})]);return{description:t,instance:n}}}),[m,h]=o({}),g=t({}),_=t(!1),v=u({mutationFn:e=>d.trpcClient.integrationInstances.updateInstance.mutate({addonId:a.addonId,id:a.id,values:e}),onSuccess:async()=>{await f.invalidateQueries({queryKey:[J]}),await f.invalidateQueries({queryKey:[ee]}),h({})}}),b=r(e=>{g.current={...g.current,...e},h(t=>({...t,...e})),!_.current&&(_.current=!0,queueMicrotask(()=>{let e=g.current;g.current={},_.current=!1,v.mutate(e)}))},[v]),x=p.data?.description.kinds?.find(e=>e.id===a.kindId),C=p.data?.instance?.formValues,w=n(()=>({...C,...m}),[C,m]),T=x?.widgets??[],E=T.some(e=>e.placement===`model`),O=n(()=>({...$(w,`nodeId`)===``?{}:{nodeId:$(w,`nodeId`)},...typeof w.modelRef==`object`&&w.modelRef!==null?{model:w.modelRef}:{}}),[w]),k={id:$(w,`model`),supportsVision:w.supportsVision===!0},A=u({mutationFn:()=>d.trpcClient.llm.listModels.mutate({addonId:a.addonId,kind:a.kindId??``,profileId:a.id})});if(p.isPending)return null;if(p.isError)return i(V,{variant:`warning`,message:p.error.message});let j=A.data?.ok===!0?A.data.models:[],M=A.data?.ok===!1?A.data:null,N=e=>{let t=j.find(t=>t.id===e);b({model:e,...t?.features?.vision===void 0?{}:{supportsVision:t.features.vision}})};return e(`div`,{className:`space-y-3`,"data-testid":`ai-profile-lead`,children:[T.map(({id:e})=>{let t=Oe(e);return t===null?i(V,{variant:`warning`,message:c(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:e})},e):i(t,{providerConfig:O,onProviderConfigChange:e=>b({...$(e,`nodeId`)===$(O,`nodeId`)?{}:{nodeId:$(e,`nodeId`)},...e.model!==void 0&&e.model!==O.model?{modelRef:e.model}:{}}),model:k,onModelChange:e=>b({model:e.id,supportsVision:e.supportsVision})},e)}),!E&&e(I,{label:c(`ai.model`,`Model`),children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(L,{size:`sm`,variant:`secondary`,type:`button`,disabled:A.isPending,onClick:()=>A.mutate(),children:[A.isPending?i(y,{className:`h-3.5 w-3.5 animate-spin`}):null,c(`ai.loadModels`,`Load models`)]}),j.length>0&&i(D,{"aria-label":c(`ai.model`,`Model`),value:k.id,onChange:e=>N(e.target.value),options:[...j.some(e=>e.id===k.id)||k.id===``?[]:[{value:k.id,label:k.id}],...j.map(e=>({value:e.id,label:e.label??e.id}))]})]}),M!==null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:M.message}),A.isError&&i(`p`,{className:`mt-1 text-xs text-danger`,children:A.error.message})]}),v.isError&&i(V,{variant:`warning`,message:v.error.message})]})}c();var Ae=5e3;function je(e){return W.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function Me(){let{t}=G(),r=S(),a=s({queryKey:fe,refetchInterval:Ae,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})}),o=n(()=>[{key:`node`,header:t(`ai.colNode`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:t(`ai.colState`,`State`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(N,{variant:he(n),children:t(de(n))}),n.status?.downloadProgress!==void 0&&i(N,{variant:`info`,children:`${String(Math.round(n.status.downloadProgress*100))}%`})]})},{key:`model`,header:t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:t(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:je(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeature`,`Feature`),render:n=>{let r=ue(n);if(r.length===0)return i(`span`,{className:`text-foreground-subtle`,children:`—`});let a=r.flatMap(e=>e.detail===null?[]:[e.detail]);return e(`span`,{className:`flex flex-col items-start gap-0.5`,children:[i(`span`,{className:`flex flex-wrap gap-1`,children:r.map(e=>i(N,{variant:e.tone,children:t(e.labelKey)},e.id))}),a.length>0&&i(`span`,{className:`text-foreground-subtle`,children:a.join(` · `)})]})}},{key:`error`,header:t(`ai.colError`,`Error`),render:e=>e.error===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):i(`span`,{className:`text-danger`,children:e.error})}],[t]),c=a.data??[];return i(F,{headingId:`ai-runtimes-list`,title:t(`ai.runtimesList`,`Nodes`),children:a.isPending?e(`div`,{className:`${d} space-y-2`,"data-testid":`ai-runtimes-loading`,children:[i(U,{className:`h-8 w-full`}),i(U,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:d,children:i(V,{title:t(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:a.error instanceof Error?a.error.message:t(`common.error`,`Error`),onRetry:()=>void a.refetch()})}):c.length===0?i(B,{icon:f,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(P,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:z})})}var Ne=g(`/addon/ai/test-chat`),Pe=g(`/addon/ai/test-chat/chats`),Fe=6e5;function Ie(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),Fe)}function Le(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Re(e){if(!Le(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var ze=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function Be(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Le(t))return null;switch(t.kind){case`status`:{let e=ze.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:Re(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:W.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*Ve(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
- `);for(;a>=0;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length>0){let t=Be(e);t!==null&&(yield t)}a=r.indexOf(`
3
- `)}}let e=r.trim();if(e.length>0){let t=Be(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function He(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Ue(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function We(e){return e.messages.map((t,n)=>{let r=t.mediaSent??void 0;return{id:`${e.id}-${String(n)}`,role:t.role,content:t.content,...t.attachment===void 0?{}:{attachmentRef:t.attachment,attachmentKind:t.attachment.kind},...r===void 0?{}:{attachment:r}}})}function Ge(e){let t=e.sizeBytes<1024*1024?`${(e.sizeBytes/1024).toFixed(0)} KB`:`${(e.sizeBytes/(1024*1024)).toFixed(1)} MB`,n=[e.kind===`snapshot`?`camera snapshot`:`track best-shot`,t];return e.mediaKind!==void 0&&n.push(e.mediaKind),e.capturedAt!==void 0&&n.push(new Date(e.capturedAt).toLocaleTimeString()),n.join(` · `)}function Ke(e,t){switch(e){case`resolving-image`:return W.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return W.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?W.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):W.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return W.t(`helpers.aiTestChat.phaseAnswering`)}}c();var qe=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],Je=360*60*1e3,Ye=40,Xe=160,Ze={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function Qe(){let{t:s}=G();S();let[c,l]=o(``),[u,f]=o(``),[p,h]=o(``),[g,y]=o([]),[C,T]=o(null),[E,O]=o(`none`),[k,M]=o(`throwaway`),[N,P]=o(null),[ee,I]=o([]),[z,B]=o(null),[ie,H]=o(null),U=t(null);a(()=>()=>U.current?.abort(),[]);let W=r(async()=>{let e=await fetch(Pe,{credentials:`same-origin`});e.ok&&I((await e.json()).chats??[])},[]);a(()=>{k===`persistent`&&W()},[k,W]);let K=R({functionCap:`llm`}),q=n(()=>(K.data??[]).filter(e=>e.enabled),[K.data]),J=q.find(e=>e.id===c)??null,Y=ie!==null,oe=r(async(e,t)=>{let n=new AbortController;U.current=n,B(null);let r=Ie(J===null?{}:ve(J));H({...Ze,firstTokenTimeoutMs:r??0});let i=``,a=null,o,l=null,d=null,f;try{let s=await fetch(Ne,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:n.signal,body:JSON.stringify({profileId:c,messages:e,...u.trim()===``?{}:{system:u.trim()},...t===void 0?{}:{attachment:t},...r===void 0?{}:{firstTokenTimeoutMs:r},...k===`persistent`?{persist:!0,...N===null?{}:{conversationId:N}}:{}})});if(!s.ok||s.body===null){let e=await s.text().catch(()=>``);throw Error(e.length>0?e:`HTTP ${String(s.status)}`)}for await(let e of Ve(s.body))switch(e.kind){case`status`:H(t=>({...t??Ze,phase:e.phase}));break;case`meta`:a=e.mediaSent,o=e.model,H(t=>({...t??Ze,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:i+=e.text,H(e=>({...e??Ze,text:i}));break;case`done`:d={outputTokens:e.outputTokens,latencyMs:e.latencyMs},f=e.conversationId;break;case`error`:l=`${e.code}: ${e.message}`;break}}catch(e){n.signal.aborted||B(e instanceof Error?e.message:s(`common.error`,`Error`))}finally{U.current=null,H(null)}f!==void 0&&(P(f),W());let p=n.signal.aborted&&i.length>0;l===null&&i.length===0&&!p||y(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:l??i,...l===null?{}:{failed:!0},...a===null?{}:{attachment:a},...o!==void 0&&l===null?{model:o}:{},...d===null?{}:d}])},[k,N,J,c,W,u,s]),se=r(()=>{let e=p.trim();if(e===``||c===``||Y)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...C===null?{}:{attachmentLabel:C.label,attachmentKind:C.ref.kind}},n=[...g,t];y(n),h(``);let r=C?.ref;T(null),O(`none`),oe(k===`persistent`&&N!==null?[{role:`user`,content:e}]:He(n),r)},[k,N,p,C,c,oe,Y,g]),ce=()=>U.current?.abort(),le=()=>{U.current?.abort(),y([]),T(null),h(``),B(null),H(null),P(null)},ue=async e=>{U.current?.abort();let t=await fetch(`${Pe}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();P(e),y(We(n)),H(null),B(null)};return e(`div`,{className:m,children:[i(F,{headingId:`ai-test-setup`,title:s(`ai.testSetup`,`Setup`),children:e(`div`,{className:`${d} space-y-3`,children:[e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(te,{className:`mb-1 block`,htmlFor:`ai-test-profile`,children:s(`ai.profile`,`Profile`)}),i(D,{id:`ai-test-profile`,value:c,onChange:e=>l(e.target.value),options:[{value:``,label:s(`ai.selectProfile`,`Select a profile…`)},...q.map(e=>({value:e.id,label:`${e.name} · ${Z(e)}${X(e)?` · vision`:``}`}))]}),q.length===0&&!K.isLoading&&i(`p`,{className:`mt-1 text-xs text-foreground-subtle`,children:s(`ai.noEnabledProfiles`,`No enabled profile. Add one on the Profiles tab.`)})]}),e(`div`,{children:[i(te,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:s(`ai.systemPrompt`,`System prompt (optional)`)}),i(re,{id:`ai-test-system`,value:u,onChange:e=>f(e.target.value),placeholder:s(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),i(ae,{label:s(`ai.chatMode`,`Conversation mode`),value:k,options:[{value:`throwaway`,label:s(`ai.throwawayMode`,`Throwaway`)},{value:`persistent`,label:s(`ai.saveConversation`,`Save conversation`)}],onChange:e=>{M(e),e===`throwaway`&&P(null)}}),k===`persistent`&&e(`div`,{className:`space-y-2`,children:[i(`p`,{className:`text-xs text-foreground-subtle`,children:s(`ai.testSubtitlePersistent`,`Conversations are saved for you and can be reopened. Throwaway mode is still available.`)}),e(L,{size:`sm`,variant:`secondary`,type:`button`,onClick:le,children:[i(j,{className:`h-3.5 w-3.5`}),s(`ai.newChat`,`New chat`)]}),ee.length>0&&i(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:ee.map(e=>i(`button`,{type:`button`,onClick:()=>void ue(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-xs hover:bg-surface-hover ${e.id===N?`bg-primary/10`:``}`,children:i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.title})},e.id))})]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:s(`ai.streamNote`,`The answer streams as the model produces it. A cold model can take a while to load — the status line says which phase it is in.`)}),J!==null&&!X(J)&&i(`p`,{className:`text-xs text-warning`,children:s(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]})}),z!==null&&i(V,{title:s(`ai.chatFailed`,`The test call failed`),message:z}),e(F,{headingId:`ai-test-conversation`,title:s(`ai.testConversation`,`Conversation`),actions:e(L,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.length===0&&C===null,onClick:le,children:[i(b,{className:`h-3.5 w-3.5`}),s(`ai.clearChat`,`Clear`)]}),children:[i($e,{turns:g,live:ie}),e(`div`,{className:`${d} space-y-2 border-t border-border`,children:[C!==null&&e(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-background px-2.5 py-1.5`,children:[C.ref.kind===`snapshot`?i(w,{className:`h-3.5 w-3.5 text-foreground-subtle`}):i(_,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:C.label}),i(ne,{size:`sm`,variant:`ghost`,type:`button`,icon:v,"aria-label":s(`ai.removeAttachment`,`Remove attachment`),onClick:()=>T(null)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(L,{size:`sm`,variant:E===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>O(E===`snapshot`?`none`:`snapshot`),children:[i(w,{className:`h-3.5 w-3.5`}),s(`ai.attachSnapshot`,`Camera snapshot`)]}),e(L,{size:`sm`,variant:E===`track`?`primary`:`outline`,type:`button`,onClick:()=>O(E===`track`?`none`:`track`),children:[i(_,{className:`h-3.5 w-3.5`}),s(`ai.attachTrack`,`Recent track`)]})]}),E===`snapshot`&&i(nt,{onPick:(e,t)=>{T({ref:{kind:`snapshot`,deviceId:e.id},label:s(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t})}),O(`none`)}}),E===`track`&&i(it,{onPick:(e,t)=>{T({ref:{kind:`track`,trackId:e.trackId,deviceId:e.deviceId},label:s(`ai.trackOf`,`{{class}} on {{name}}`,{class:e.label??e.className,name:t})}),O(`none`)}}),e(`div`,{className:`flex items-center gap-2`,children:[i(re,{value:p,onChange:e=>h(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),se())},placeholder:s(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":s(`ai.message`,`Message`)}),Y?e(L,{size:`sm`,variant:`secondary`,type:`button`,onClick:ce,children:[i(x,{className:`h-3.5 w-3.5`}),s(`ai.stop`,`Stop`)]}):e(L,{size:`sm`,type:`button`,disabled:p.trim()===``||c===``,onClick:se,children:[i(A,{className:`h-3.5 w-3.5`}),s(`ai.send`,`Send`)]})]})]})]})]})}function $e({turns:t,live:n}){let{t:r}=G();return t.length===0&&n===null?i(B,{icon:k,title:r(`ai.chatEmptyTitle`,`No messages yet`),description:r(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):e(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto ${d}`,children:[t.map(e=>i(et,{turn:e},e.id)),n!==null&&e(`div`,{className:`space-y-1`,children:[n.mediaSent!==null&&i(tt,{attachment:n.mediaSent}),n.text.length>0&&i(et,{turn:{id:`live`,role:`assistant`,content:n.text},streaming:!0}),e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(y,{className:`h-3.5 w-3.5 animate-spin`}),Ke(n.phase,n.firstTokenTimeoutMs)]})]})]})}function et({turn:t,streaming:n=!1}){let{t:r}=G(),a=t.role===`user`,o=t.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return i(`div`,{className:`flex ${a?`justify-end`:`justify-start`}`,children:e(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${a?`border-primary/40 bg-primary/10`:o}`,children:[e(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[t.content,n&&i(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),t.attachment!==void 0&&i(tt,{attachment:t.attachment}),t.attachmentLabel!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachmentKind===`track`?i(_,{className:`h-3 w-3`}):i(w,{className:`h-3 w-3`}),t.attachmentLabel]}),t.attachment!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachment.kind===`snapshot`?i(w,{className:`h-3 w-3`}):i(_,{className:`h-3 w-3`}),Ge(t.attachment)]}),t.model!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:r(`system.aiTestChat.tokMs`,`{{model}} · {{value2}} tok · {{value3}} ms`,{model:t.model,value2:String(t.outputTokens??0),value3:String(t.latencyMs??0)})})]})})}function tt({attachment:e}){let{t}=G(),n=Ue(e);return n===null?null:i(`img`,{src:n,alt:t(`system.aiTestChat.sentToTheModel`,`sent to the model`),className:`mt-1 max-h-32 rounded-md border border-border object-contain`})}function nt({onPick:e}){let{t}=G(),n=M({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?i(y,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):i(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>i(rt,{device:t,onPick:e},t.id))})}function rt({device:t,onPick:n}){let{t:r}=G(),a=ie(t,`compact`),{src:o}=p(t.id,{width:Xe});return e(`button`,{type:`button`,onClick:()=>n(t,a),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[i(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:o!==null&&i(`img`,{src:o,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),e(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!t.online&&i(N,{variant:`warning`,children:r(`common.off`)}),i(`span`,{className:`truncate text-[10px] text-foreground`,children:a})]})]})}function it({onPick:t}){let{t:r}=G(),a=S(),o=M({isCamera:!0,projection:`slim`}),c=n(()=>(o.data??[]).map(e=>e.id),[o.data]),l=n(()=>{let e=new Map;for(let t of o.data??[])e.set(t.id,t.name);return e},[o.data]),u=s({queryKey:[...qe,c.length],enabled:c.length>0,queryFn:()=>a.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...c],since:Date.now()-Je,limit:Ye,projection:`slim`})});if(o.isLoading||u.isLoading)return i(y,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=u.data?.tracks??[];return d.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noTracks`,`No track in the last 6 hours.`)}):i(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(n=>e(`button`,{type:`button`,onClick:()=>t(n,l.get(n.deviceId)??String(n.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[i(_,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:n.label??n.className}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:l.get(n.deviceId)??n.deviceId}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(n.lastSeen).toLocaleTimeString()})]},n.trackId))})}c();var at=1440*60*1e3,ot=[1,7,30,90];function st(){let{t}=G(),r=S(),[a,c]=o(7),l=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(a-1)*at},[a]),u=R({functionCap:`llm`}),f=s({queryKey:[...ce,a],queryFn:()=>r.trpcClient.llm.getUsage.query({since:l})}),p=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),m=n(()=>[{key:`day`,header:t(`ai.colDay`,`Day`),nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:e.day})},{key:`consumer`,header:t(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground`,children:e.consumer})},{key:`profile`,header:t(`ai.colProfile`,`Profile`),render:e=>i(`span`,{className:`text-foreground`,children:p.get(e.profileId)??e.profileId})},{key:`calls`,header:t(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(e.calls)})},{key:`okErr`,header:t(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums ${e.errorCalls>0?`text-danger`:``}`,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:t(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:`${String(e.inputTokens)} / ${String(e.outputTokens)}`})},{key:`latency`,header:t(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(Math.round(e.avgLatencyMs))})}],[p,t]),h=f.data??[],g=i(`div`,{className:`w-36`,children:i(D,{"aria-label":t(`ai.window`,`Window`),value:String(a),options:ot.map(e=>({value:String(e),label:t(`ai.lastDays`,`Last {{days}} days`,{days:e})})),onChange:e=>c(Number(e.target.value))})});return i(F,{headingId:`ai-usage-list`,title:t(`ai.usageList`,`Rollup`),actions:g,children:f.isPending?e(`div`,{className:`${d} space-y-2`,"data-testid":`ai-usage-loading`,children:[i(U,{className:`h-8 w-full`}),i(U,{className:`h-8 w-full`}),i(U,{className:`h-8 w-full`})]}):f.isError?i(`div`,{className:d,children:i(V,{title:t(`ai.usageFailed`,`Failed to read usage`),message:f.error instanceof Error?f.error.message:t(`common.error`,`Error`),onRetry:()=>void f.refetch()})}):h.length===0?i(B,{icon:T,title:t(`ai.noUsage`,`No AI calls in this window.`)}):i(P,{columns:m,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:z})})}c();var ct=`llm`,lt=[`profiles`,`runtimes`,`usage`,`test`],ut=[`instance`,`instance-new`];function dt(e){return lt.some(t=>t===e)}function ft(){let{t:e}=G(),t=H(ct),[n]=q(),r=K(`/system/ai`,{t:e,isAdmin:!0})??{icon:E,title:e(`system.ai`,`AI`)};if(t!==`present`)return i(oe,{icon:r.icon,title:r.title,children:i(gt,{presence:t})});let a=n.get(`tab`),o=dt(a)?a:`profiles`,s={profiles:e(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),runtimes:e(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),usage:e(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),test:e(`ai.testSubtitle`,`A throwaway conversation with one profile. Attach a live camera snapshot or a recent track to check the model can actually read a picture. Nothing is saved — only the usage row.`)};return i(Y,{icon:r.icon,title:r.title,subtitle:s[o],defaultSection:`profiles`,sectionsLabel:`${r.title} sections`,sections:[{id:`profiles`,label:e(`ai.tabProfiles`,`Profiles`),content:i(ht,{}),ownedParams:ut},{id:`runtimes`,label:e(`ai.tabRuntimes`,`Runtimes`),content:i(Me,{})},{id:`usage`,label:e(`ai.tabUsage`,`Usage`),content:i(st,{})},{id:`test`,label:e(`ai.tabTest`,`Test`),content:i(Qe,{})}]})}function pt(e,t,n){let r=e.kind===`instance`?t.get(e.id):void 0;return r===void 0?void 0:n(r)}function mt(e,t){let n=t=>pt(t,e,Z)??``,r=t=>pt(t,e,X)??!1,a=t=>pt(t,e,le)??``;return[{key:`model`,header:t(`ai.colModel`,`Model`),sortValue:n,render:e=>i(`span`,{className:`font-mono text-xs text-foreground-muted`,children:n(e)||`—`})},{key:`vision`,header:t(`ai.colVision`,`Vision`),sortValue:e=>+!!r(e),render:e=>r(e)?i(N,{variant:`info`,children:t(`ai.vision`,`vision`)}):null},{key:`node`,header:t(`ai.colNode`,`Node`),sortValue:a,render:e=>i(`span`,{className:`text-xs text-foreground-muted`,children:a(e)||`—`})}]}function ht(){let{t}=G(),r=R({functionCap:ct}),a=n(()=>new Map((r.data??[]).map(e=>[e.id,e])),[r.data]),o=n(()=>mt(a,t),[a,t]);return e(`div`,{className:m,children:[i(ye,{}),i(se,{functionCap:ct,icon:E,title:t(`ai.profilesList`,`Profiles`),subtitle:t(`ai.profilesTableSubtitle`,`Each profile is one model endpoint; switch one off to keep it without using it.`),emptyTitle:t(`ai.noProfilesTitle`,`No AI profiles yet`),emptyDescription:t(`ai.noProfilesDescription`,`Add a profile to give features a model to talk to.`),addLabel:t(`ai.addProfile`,`Add profile`),extraColumns:o,lead:e=>i(ke,{row:e})})]})}function gt({presence:t}){let{t:n}=G();return t===`pending`?e(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[i(U,{className:`h-8 w-64`}),i(U,{className:`h-40 w-full`})]}):t===`unknown`?i(V,{title:n(`ai.presenceUnknownTitle`,`Could not check whether AI is installed`),message:n(`ai.presenceUnknown`,`The hub did not answer the capability check. Reload the page to try again.`)}):i(B,{icon:E,title:n(`ai.absentTitle`,`AI is not installed`),description:n(`ai.absentDescription`,`Install the AI addon from System → Addons to add model profiles.`)})}export{ft as AiProfilesPage,ft as default};
@@ -1 +0,0 @@
1
- import{C as e,K as t,R as n,S as r,Y as i,et as a}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Cn as o,D as s,Nr as c,gt as l,pn as u}from"./player-overlays-D2iM_dnq.js";import{n as d,t as f}from"./key-square-wAKOa45w.js";import{p}from"./video-DFWp1_fo.js";import{Fr as m,Ii as h,Kn as g,ha as _,ma as v}from"./src-Djs5D3BM.js";import{t as y}from"./useTranslation-BJr-n0es.js";import{$ as b,F as x,I as S,Rr as C,_ as w,ct as T,ft as E,v as D,zr as O}from"./index-BtIAcMod.js";import{n as k}from"./NodeAddonsSettingsPanel-BleYmajR.js";import{f as A,t as j}from"./InstancesTable-dSeWjA48.js";import{n as M,t as N}from"./IntegrationHub-CIVmSeKd.js";import{t as P}from"./useInvalidateAddonSettings-CyofQfBo.js";a();function F(e,t){if(e.type===`group`){for(let n of e.fields)F(n,t);return}if(e.type===`sub-tabs`){for(let n of e.tabs)for(let e of n.fields)F(e,t);return}`value`in e&&(t[e.key]=e.value)}function I(e){let t={};for(let n of e.sections)for(let e of n.fields)F(e,t);return t}function L({sectionIds:e,omitSectionIds:n,hideSectionChrome:i,emptyMessage:a}){let o=w(),s=t(()=>{if(o.data===void 0)return null;let t=o.data.sections.filter(t=>(e===void 0||e.includes(t.id))&&!(n?.includes(t.id)??!1));return{...o.data,sections:k(t,{...i===!0?{hideSectionChrome:i}:{}})}},[o.data,e,n,i]);return o.isPending?null:s===null||o.isError?r(`p`,{className:`text-sm text-foreground-muted`,children:a}):s.sections.length===0?null:r(R,{schema:s})}function R({schema:a}){let{t:o}=y(),s=D(),[c,l]=i(null),u=t(()=>I(a),[a]),d=n(async e=>{l(null);try{await s.mutateAsync({patch:e})}catch(e){throw l(e instanceof Error&&e.message.length>0?e.message:o(`system.bootstrapForm.saveFailed`,`Could not save`)),e}},[s,o]),f=S({schema:a,serverValues:u,onImmediateSave:e=>void d(e).catch(()=>void 0),onDeferredSave:d});return e(`div`,{className:`flex flex-col gap-3`,children:[c!==null&&r(`div`,{role:`alert`,className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:c}),r(E,{schema:a,values:f.values,onChange:f.handleChange,disabled:s.isPending}),r(x,{pendingCount:f.pendingKeys.length,onSave:()=>f.handleSave(f.pendingKeys),onDiscard:()=>f.handleDiscard(f.pendingKeys),saving:s.isPending})]})}function z(e){return e?{state:`ok`,stateLabel:`enabled`}:{state:`off`,stateLabel:`disabled`}}a();var B=3e4,V=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],H={titleKey:`system.authentication.sectionTitle`,subtitleKey:`system.authentication.sectionSubtitle`,emptyTitleKey:`system.authentication.sectionEmptyTitle`,emptyDescriptionKey:`system.authentication.sectionEmptyDescription`,installLabelKey:`system.authentication.sectionInstall`};function U(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:f,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`Scoped tokens, admin tokens and sessions are managed from Identity → Tokens & sessions.`],setupSteps:[`A fresh hub has one account, admin / changeme — the first sign-in asks for a new password. Add users from Users → New user.`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:p,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`Explicit linking only: an IdP account signs in only the CamStack user who linked it from their profile (My access → Linked sign-in accounts). No auto-created users, no email matching.`,`The linked user’s role, scopes and two-factor authentication apply.`],setupSteps:[`Register a web app at your IdP and copy the client_id + client_secret.`,"Choose a stable instance id (slug). Set the IdP redirect URI to `https://<this-hub>/addon/auth-oidc/<id>/callback`.",`In Sign-in connections below, Add connection — enter the id, issuer, and credentials; Save.`,`Each user then links their IdP account from My access → Linked sign-in accounts.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:p,bullets:[`Heavier handshake than OIDC — exchange metadata XML with your IdP.`,`Group → role mapping via SAML assertions.`]}:e.startsWith(`auth-webauthn`)||e.startsWith(`auth-passkey`)?{headline:`Passkeys / WebAuthn — passwordless second factor.`,icon:u,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)?{headline:`TOTP — second factor.`,icon:u,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:o,bullets:[`Generic authentication provider. No additional hints registered.`]}}function W(){let{t:n}=y(),i=_({capName:V[0].capName},{refetchInterval:B}),a=_({capName:V[1].capName},{refetchInterval:B}),s=v(void 0,{refetchInterval:B}),c=t(()=>T(s.data??[]),[s.data]),l=t(()=>{let e=[],t=[i.data??[],a.data??[]];for(let[n,r]of V.entries())for(let i of t[n]??[])e.push({addonId:i.addonId,displayName:c.get(i.addonId)??i.addonId,isActive:i.isActive,capName:r.capName,stageBadge:r.stageBadge});return e},[i.data,a.data,c]),u=[{id:`authentication`,label:n(`system.authentication.authenticationProviders`,`Authentication providers`),install:{capability:V[0].capName,label:n(H.installLabelKey)},entries:l.map(e=>({id:e.addonId,name:e.displayName,fallbackIcon:o,...z(e.isActive),render:()=>r(M,{addonId:e.addonId,displayName:e.displayName,capName:e.capName,isActive:e.isActive,badges:e.stageBadge===null?null:r(h,{variant:`info`,className:A,children:e.stageBadge}),panels:[{id:`about`,title:n(`system.authentication.about`,`About`),icon:U(e.addonId).icon,content:r(Y,{addonId:e.addonId})}]})}))}];return e(`div`,{className:`space-y-3 sm:space-y-4`,children:[r(N,{embedded:!0,icon:o,title:n(H.titleKey),subtitle:n(H.subtitleKey),groups:u,isLoading:i.isLoading||a.isLoading,emptyTitle:n(H.emptyTitleKey),emptyDescription:n(H.emptyDescriptionKey)}),r(j,{functionCap:`login-method`,icon:p,title:n(`system.authentication.connectionsTitle`,`Sign-in connections`),subtitle:n(`system.authentication.connectionsSubtitle`,`Identity providers that sign users in. Each connection has its own id, which cannot be changed later.`),emptyTitle:n(`system.authentication.connectionsEmptyTitle`,`No sign-in connections`),emptyDescription:n(`system.authentication.connectionsEmptyDescription`,`Add a connection to let users sign in through an identity provider.`),addLabel:n(`system.authentication.addConnection`,`Add connection`),typedId:()=>({pattern:b})}),r(K,{}),r(J,{})]})}var G=`system-config-auth`;function K(){let{t:e}=y();return r(g,{headingId:`authentication-policy`,title:e(`system.authentication.policyTitle`,`Sign-in policy`),icon:o,children:r(`div`,{className:s,children:r(L,{sectionIds:[G],hideSectionChrome:!0,emptyMessage:e(`system.authentication.policyUnavailable`,`Not available — the addon that owns these settings did not answer.`)})})})}var q=`webauthn`;function J(){let{t:e}=y(),t=l(),n=P();return r(g,{headingId:`authentication-passkey-rp`,title:e(`system.authentication.passkeyRpTitle`,`Passkey relying party`),icon:u,children:r(`div`,{className:s,children:r(m,{trpc:t.trpcClient,addonId:`auth-webauthn`,cap:`login-method`,scope:`cluster`,sectionIds:[q],unavailableText:e(`system.authentication.passkeyRpUnavailable`,`Not available — the addon that owns these settings did not answer.`),onAfterChange:n,bare:!0})})})}function Y({addonId:t}){let{t:n}=y(),i=U(t),a=i.icon;return e(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[e(`div`,{className:`flex items-start gap-2.5`,children:[r(a,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),r(`div`,{className:`text-xs text-foreground font-medium`,children:i.headline})]}),r(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:i.bullets.map((e,t)=>r(`li`,{children:e},t))}),i.setupSteps&&i.setupSteps.length>0&&e(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[e(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[r(d,{className:`h-3 w-3`}),n(`system.authentication.setupSteps`,`Setup steps`)]}),r(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:i.setupSteps.map((e,t)=>r(`li`,{children:e},t))})]}),t===`local-auth`&&e(`div`,{className:`rounded-md border border-info/30 bg-info/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[r(c,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),r(`span`,{children:r(C,{i18nKey:`system.authentication.totpNote`,components:{access:r(O,{to:`/system/my-access?tab=sign-in`,className:`underline text-primary`}),users:r(O,{to:`/system/identity?tab=users`,className:`underline text-primary`})}})})]})]})}export{L as i,W as n,q as r,G as t};
@@ -1,39 +0,0 @@
1
- import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,o as d,t as f,x as p}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Dr as m,Fn as h,Jn as g,Kt as _,Ni as v,Oa as y,Tr as b,Ur as x,Vi as S,Yn as C,Yt as w,ct as T,er as E,gt as D,kn as O,ut as k,wt as A,zi as j}from"./player-overlays-D2iM_dnq.js";import{$i as M,Go as N,Ia as P,Ma as F,Oa as I,Pa as L,Ui as R,Vi as z,Wi as B,Xa as V,Ya as H,_o as U,ao as ee,co as te,do as ne,fo as W,fr as G,go as re,ia as ie,io as ae,jr as oe,no as se,oo as ce,ro as le,to as ue,uo as de}from"./client-BT1qTuWk.js";import{t as K}from"./boxes-Sn1wqpgK.js";import{t as fe}from"./calendar-clock-TWIEL7Fd.js";import{c as pe}from"./video-DFWp1_fo.js";import{n as me,t as he}from"./variable-CxFXQLx9.js";import{$i as ge,$o as _e,$r as ve,$u as ye,Dd as be,Dn as xe,Dt as Se,Ft as Ce,Hn as we,If as Te,Ii as q,Jn as Ee,Jr as De,Ju as Oe,Ki as ke,Kn as Ae,Kr as je,Ku as Me,Oi as J,Pt as Ne,Qu as Pe,Ss as Fe,Wr as Ie,Xi as Le,Xr as Re,Xu as ze,Yi as Be,Yn as Ve,Yr as He,Yu as Ue,Zi as We,Zu as Ge,_o as Ke,ai as qe,b as Je,co as Ye,do as Xe,dr as Ze,fi as Qe,fr as $e,gn as et,go as tt,hi as nt,ho as rt,ii as Y,kn as it,kt as at,lf as ot,mf as X,mr as st,oo as ct,os as lt,po as ut,pr as dt,qi as ft,qn as pt,qr as mt,qu as ht,si as gt,so as _t,ur as vt}from"./src-Djs5D3BM.js";import{t as Z}from"./i18n-DO003gOw.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import{Hr as yt,Rr as bt,S as xt,U as St,Wr as Ct,ft as wt,h as Tt,lt as Et,m as Dt,zr as Ot}from"./index-BtIAcMod.js";import{t as kt}from"./AdminSectionedPage-C_DLslGH.js";import{n as At}from"./format-C6WZEo_1.js";import{C as jt,a as Mt,at as Nt,b as Pt,g as Ft,i as It,lt as Lt,n as Rt,nt as zt,o as Bt,r as Vt,w as Ht,y as Ut}from"./CompositionBlockEditor-B4WN_aXq.js";import{_ as Wt,a as Gt,c as Kt,d as qt,f as Jt,h as Yt,i as Xt,l as Zt,m as Qt,n as $t,o as en,p as tn,r as nn,s as rn,t as an,u as on,v as sn}from"./create-composition-BCz5rteK.js";import{a as cn,i as ln,n as un,o as dn,r as fn,s as pn}from"./action-draft-BF1Yv5wJ.js";var mn=`const AUTOMATION_RECIPE =`,hn=`// 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 gn(e){return e.includes(mn)}function _n(e){let t=e.indexOf(mn);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 vn(e){let t=_n(e);if(t===null)return{ok:!1,reason:Z.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:Z.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=ce.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Z.t(`helpers.recipeFromCode.schemaMismatch`):Z.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function yn(e){let t=_n(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)}${hn}${e.slice(i)}`}u();function bn(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function xn(e,t){return ee(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.name}`,e.description)}))}function Sn(e){return e.some(e=>e.required===!0&&e.default===void 0)}function Cn(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function wn(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function Tn(e,t){return e.filter(e=>e.required===!0&&!wn(t[e.name])).map(e=>e.name)}function En(e,t){let n={};for(let r of e){let e=t[r.name];wn(e)&&(n[r.name]=e)}return n}function Dn({variable:e,value:t,onChange:n}){let{t:r}=Q(),i=e.label??e.name;return e.type===`number`?o(sn,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?o(Wt,{widthClass:`w-28`,"aria-label":i,value:t===!0?`yes`:`no`,onChange:e=>n(e.target.value===`yes`),options:[{value:`yes`,label:r(`common.yes`,`Yes`)},{value:`no`,label:r(`common.no`,`No`)}]}):e.type===`select`?o(Wt,{widthClass:`w-48`,"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`actions.editor.runDialog.choose`,`Choose…`)},...(e.options??[]).map(e=>({value:e,label:e}))]}):o(X,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function On({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:s}=Q(),[l,u]=c(()=>Cn(n)),d=Tn(n,l);return o(Ie,{open:!0,onOpenChange:e=>!e&&a(),children:e(je,{"aria-label":s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(He,{children:[o(Re,{children:s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),o(mt,{children:s(`actions.editor.runDialog.description`,`Give the variables this run should use.`)})]}),o(`div`,{className:`space-y-3`,"data-testid":`run-variables-form`,children:n.map(t=>e(`label`,{className:`block space-y-1`,children:[e(`span`,{className:`text-xs text-foreground-subtle`,children:[t.label??t.name,t.required===!0?` *`:``]}),o(Dn,{variable:t,value:l[t.name],onChange:e=>u({...l,[t.name]:e})})]},t.name))}),e(De,{className:`flex flex-wrap gap-2`,children:[o(J,{variant:`ghost`,onClick:a,children:s(`common.cancel`,`Cancel`)}),e(J,{disabled:r||d.length>0,onClick:()=>i(En(n,l)),children:[r?o(b,{className:`h-4 w-4 animate-spin`}):o(C,{className:`h-4 w-4`}),` `,s(`actions.editor.runNow`,`Run now`)]})]})]})})}var kn=[`number`,`string`,`boolean`,`select`];function An(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function jn(e,t){let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``),r=e.default!==void 0&&typeof e.default==`string`&&n.includes(e.default),{default:i,...a}=e;return{...r?e:a,options:n.length===0?[`option`]:n}}function Mn(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function Nn(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function Pn({variables:t,onChange:n,onRename:r}){let{t:i}=Q(),a=e=>{switch(e){case`number`:return i(`actions.variables.typeNumber`,`number`);case`string`:return i(`actions.variables.typeText`,`text`);case`boolean`:return i(`actions.variables.typeBoolean`,`yes / no`);default:return i(`actions.variables.typeSelect`,`select`)}},s=(e,r)=>n(t.map((t,n)=>n===e?r:t));return o(Ae,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:he,actions:e(J,{variant:`outline`,size:`sm`,onClick:()=>n([...t,cn(t)]),children:[o(g,{className:`h-4 w-4`}),` `,i(`actions.variables.add`,`Variable`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[t.map((c,l)=>e(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_8rem_1fr_1.2fr_auto] sm:items-end`,"data-testid":`variable-row`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.name`,`Name`)}),o(X,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!ln(c.name),onChange:e=>r(l,e.target.value)})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.label`,`Label`)}),o(X,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,Nn(c,e.target.value))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.type`,`Type`)}),o(Wt,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:kn.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=kn.find(t=>t===e.target.value);t!==void 0&&s(l,An(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(Fn,{variable:c,onChange:e=>s(l,Mn(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(X,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>s(l,jn(c,e.target.value))})]}),o(J,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(w,{className:`h-4 w-4`})})]},`${String(l)}`)),o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function Fn({variable:e,onChange:t}){let{t:n}=Q(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(sn,{"aria-label":r,value:typeof e.default==`number`?e.default:void 0,onValue:t});if(e.type===`boolean`||e.type===`select`){let i=e.type===`boolean`?[{value:`true`,label:n(`common.yes`,`Yes`)},{value:`false`,label:n(`common.no`,`No`)}]:(e.options??[]).map(e=>({value:e,label:e}));return o(Wt,{widthClass:`w-full`,"aria-label":r,value:e.default===void 0?``:String(e.default),options:[{value:``,label:n(`actions.variables.noDefault`,`None`)},...i],onChange:n=>{n.target.value===``?t(null):t(e.type===`boolean`?n.target.value===`true`:n.target.value)}})}return o(X,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var In=5e3;function Ln(e){return e.kind===`cap`||e.kind===`wait`}function Rn(e){return e instanceof Error?e.message:String(e)}function zn(){let{t:e}=Q();return t=>{switch(t.kind){case`name`:return e(`actions.editor.problemName`,`Give the action a name.`);case`no-steps`:return e(`actions.editor.problemNoSteps`,`Add at least one step.`);case`undeclared`:return e(`actions.editor.problemUndeclared`,`A step uses {{name}}, which is not declared under Variables.`,{name:t.name});case`duplicate`:return e(`actions.editor.problemDuplicate`,`The variable {{name}} is declared twice.`,{name:t.name});case`bad-name`:return e(`actions.editor.problemBadName`,`The variable name "{{name}}" must start with a letter and use letters, digits or _.`,{name:t.name});default:return t.message}}}function Bn({entry:t,onClose:i,onSaved:a,preset:l=null}){let{t:u}=Q(),f=d(),h=T(),g=en(),_=zn(),[v,y]=c(()=>fn(t)),x=n(!1);s(()=>{if(t!==null||l!==`trigger-alarm`||x.current)return;let e=g.find(e=>e.type===N.AlarmPanel);e!==void 0&&(x.current=!0,y(pn(e.id,u(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[g,t,l,u]);let[S,E]=c(null),[D,O]=c(!1),k=t!==null&&t.readOnly,A=()=>{f.invalidateQueries({queryKey:[[`actions`]]})},j=ke({onSuccess:e=>{A(),a(e.action.id)}}),M=ge({onSuccess:A}),P=ft({onSuccess:()=>{A(),i()}}),F=We({onSuccess:A}),I=Be({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:In}),L=I.data?.traces.find(e=>e.runId===S)??null,R=r(()=>L===null?null:Qt(L),[L]),z=r(()=>L===null?null:tn(L).steps,[L]),B=un(v),V=r(()=>bn(v.variables,u),[v.variables,u]),H=j.isPending||M.isPending,U=j.error??M.error??P.error??F.error,ee=Sn(t?.variables??[]);return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`action-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(m,{className:`h-4 w-4 text-foreground-muted`}),o(X,{"aria-label":u(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:v.name,disabled:k,placeholder:u(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>y({...v,name:e.target.value})}),o(q,{variant:k?`info`:`primary`,children:k?t?.addonId??``:u(`actions.source.internal`,`Internal`)})]}),k?o(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:u(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(p,{children:[o(Pn,{variables:v.variables,onChange:e=>y({...v,variables:e}),onRename:(e,t)=>y(dn(v,e,t))}),o(qt,{step:`steps`,title:u(`actions.editor.steps`,`Steps`),trace:R===null?null:R.thenBlock,children:o(nn,{actions:v.steps,devices:g,allowedKinds:[`cap`,`wait`],stepTones:R===null?void 0:v.steps.map((e,t)=>Jt(R,t)??`idle`),stepResults:z===null?void 0:v.steps.map((e,t)=>z.find(e=>e.index===t)),variables:V,onChange:e=>y({...v,steps:e.filter(Ln)})})})]}),!B.ok&&!k&&v.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:_(B.reason)}),U!==null&&o(Y,{message:Rn(U)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!k&&e(J,{onClick:()=>{B.ok&&(t===null?j.mutate({action:B.input}):M.mutate({actionId:t.id,action:B.input}))},disabled:H||!B.ok,children:[H&&o(b,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),t!==null&&e(J,{variant:`outline`,disabled:F.isPending,onClick:()=>ee?O(!0):F.mutate({actionId:t.id}),children:[o(C,{className:`h-4 w-4`}),` `,u(`actions.editor.runNow`,`Run now`)]}),t!==null&&!k&&e(J,{variant:`ghost`,disabled:P.isPending,onClick:()=>{h({title:u(`actions.editor.deleteTitle`,`Delete this action?`),message:u(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:u(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&P.mutate({actionId:t.id})})},children:[o(w,{className:`h-4 w-4`}),` `,u(`common.delete`,`Delete`)]}),o(J,{variant:`ghost`,onClick:i,children:u(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(on,{traces:t===null?[]:I.data?.traces,selectedId:S,onSelect:E})}),D&&t!==null&&o(On,{actionName:t.name,variables:t.variables??[],running:F.isPending,onCancel:()=>O(!1),onRun:e=>{F.mutate({actionId:t.id,variables:e}),O(!1)}})]})}u();var Vn=5e3;function Hn(e){return e instanceof Error?e.message:String(e)}function Un(){let{t:e}=Q();return t=>t.status.isRunning?{variant:`info`,label:e(`actions.status.running`,`Running`)}:t.status.lastError===null?t.status.lastRunAt===null?{variant:`neutral`,label:e(`actions.status.neverRan`,`Never ran`)}:{variant:`success`,label:e(`actions.status.ok`,`OK`)}:{variant:`danger`,label:e(`actions.status.failed`,`Failed`)}}function Wn({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),[a]=Ct(),c=d(),l=Un(),{state:u,openNew:f,openEdit:h,close:_}=Se({editKey:`action`,newKey:`new`}),v=Le({},{refetchInterval:Vn}),y=We({onSuccess:()=>void c.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(f(),n?.())},[t,n,f]);let b=v.data??[],x=u.mode===`edit`?b.find(e=>e.id===u.id)??null:null,S=r(()=>[{key:`name`,header:i(`actions.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:i(`actions.list.source`,`Source`),render:e=>e.readOnly?o(q,{variant:`info`,children:e.addonId}):o(q,{variant:`primary`,children:i(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:i(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?o(`span`,{className:`text-foreground-subtle`,children:`-`}):At(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:i(`actions.list.status`,`Status`),render:e=>{let t=l(e);return o(`span`,{title:e.status.lastError??void 0,children:o(q,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(J,{variant:`outline`,size:`sm`,disabled:y.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),y.mutate({actionId:t.id})},children:[o(C,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[y,l,i]);return u.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),y.error!=null&&o(Y,{message:Hn(y.error)}),v.data===void 0?v.error==null?o(gt,{className:`h-24 w-full`}):o(Y,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:Hn(v.error),onRetry:()=>void v.refetch()}):b.length===0?o(qe,{icon:m,title:i(`actions.list.emptyTitle`,`No actions yet`),description:i(`actions.list.emptyDescription`,`An action is a short list of commands, such as feeding the dog, that you can reuse.`),action:e(J,{onClick:f,children:[o(g,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(p,{children:[v.error!=null&&o(Y,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:Hn(v.error),onRetry:()=>void v.refetch()}),o(Ee,{columns:S,rows:b,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ve,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>h(e.id)})]})]}):o(Bn,{entry:x,onClose:_,onSaved:h,preset:u.mode===`new`?a.get(`preset`):null},x?.id??`new`)}u();function Gn({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Q(),[l,u]=c(!1),d=T(),f=async()=>{await d({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(J,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?S:j,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(J,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[o(pe,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),l&&o(`div`,{className:`border-t border-border p-3`,children:t===null?o(`p`,{className:`text-xs text-warning`,children:n??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):o(we,{maxHeight:420,children:t})})]})}var Kn=[`single`,`restart`,`queued`,`parallel`,`cooldown`],qn=2,Jn=30;function Yn(e){return e.runMode??{mode:`single`}}function Xn(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function Zn(e){switch(e){case`queued`:return{mode:`queued`,max:qn};case`parallel`:return{mode:`parallel`,max:qn};case`cooldown`:return{mode:`cooldown`,minutes:Jn};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function Qn(e){return Kn.find(t=>t===e)??`single`}function $n({value:t,onChange:n}){let{t:r}=Q(),i={single:r(`flow.runMode.single`,`Skip it`),restart:r(`flow.runMode.restart`,`Restart the run`),queued:r(`flow.runMode.queued`,`Queue it`),parallel:r(`flow.runMode.parallel`,`Run at the same time`),cooldown:r(`flow.runMode.cooldown`,`Wait after a run`)},a={single:r(`flow.runMode.singleHint`,`A trigger that arrives during a run is dropped.`),restart:r(`flow.runMode.restartHint`,`The run in progress stops and a new one starts.`),queued:r(`flow.runMode.queuedHint`,`Triggers wait their turn, up to the limit.`),parallel:r(`flow.runMode.parallelHint`,`Runs overlap, up to the limit.`),cooldown:r(`flow.runMode.cooldownHint`,`No new run until this long after the last one began.`)};return e(`div`,{className:`flex flex-wrap items-end gap-3`,"data-testid":`run-mode`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.label`,`When it is already running`)}),o(Wt,{widthClass:`w-56`,value:t.mode,options:Kn.map(e=>({value:e,label:i[e]})),onChange:e=>n(Zn(Qn(e.target.value)))})]}),(t.mode===`queued`||t.mode===`parallel`)&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.max`,`Up to`)}),o(sn,{className:`w-20`,"aria-label":r(`flow.runMode.max`,`Up to`),value:t.max,onValue:e=>{e!==null&&n({mode:t.mode,max:Math.round(e)})}})]}),t.mode===`cooldown`&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.minutes`,`Minutes`)}),o(sn,{className:`w-20`,"aria-label":r(`flow.runMode.minutes`,`Minutes`),value:t.minutes,onValue:e=>{e!==null&&n({mode:`cooldown`,minutes:Math.round(e)})}})]}),o(`p`,{className:`basis-full text-xs text-foreground-subtle`,children:a[t.mode]})]})}var er;function tr(){return er??=V(oe),er}function nr(e,t=tr()){return H(e,t)}u();var rr=`hub`,ir=5e3;function ar({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=Q(),[p,m]=c(t?.name??``),[h,g]=c(()=>Gt(n)),[_,v]=c(!1),[y,x]=c(null),S=Xe({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:ir}),C=S.data?.traces.find(e=>e.runId===y)??null,w=r(()=>C===null?null:Qt(C),[C]),T=r(()=>xn(h.when,f),[h.when,f]),E=r(()=>C===null?null:Yt(C),[C]),D=r(()=>C===null?null:tn(C).steps,[C]),k=en(),A=te(h),j=r(()=>or(h),[h]),M=r(()=>sr(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),N=p.trim()===``,P=N||A!==null||j!==null||M.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[e(`div`,{className:`space-y-4`,children:[e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(X,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(qt,{step:`when`,title:f(`automation.automationEditor.when`,`When`),trace:w===null?null:w.when,children:o(Xt,{recipe:h,devices:k,run:E,onChange:g})}),o(qt,{step:`then`,title:f(`automation.automationEditor.then`,`Then`),trace:w===null?null:w.thenBlock,hint:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(nn,{actions:h.actions,devices:k,variables:T,stepTones:w===null?void 0:h.actions.map((e,t)=>Jt(w,t)??`idle`),stepResults:D===null?void 0:h.actions.map((e,t)=>D.find(e=>e.index===t)),onChange:e=>g(Zt(h,e))})}),o(qt,{step:`mode`,title:f(`flow.runMode.title`,`Overlap`),trace:null,hint:f(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:o($n,{value:Yn(h),onChange:e=>g(Xn(h,e))})}),o(Gn,{code:M.code,error:M.error,canEject:t!==null,ejecting:s,onEject:u}),A!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:A}),A===null&&j!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:j}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{onClick:()=>{M.code!==null&&l({name:p.trim(),code:M.code,enabled:t?.enabled??!0,placement:rr})},disabled:i||P,children:[i&&o(b,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(J,{variant:`ghost`,onClick:()=>v(!_),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,"aria-expanded":_,children:[o(O,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,o(ot,{expanded:_})]}),o(J,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),N&&o(q,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(bt,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(xe,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(on,{traces:t===null?[]:S.data?.traces,selectedId:y,onSelect:x})})]})}function or(e){let t=ce.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Z.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function sr(e,t){let n=nr(t);if(!n.ok)return{code:null,error:n.error};try{return{code:ae({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function cr(e){if(!e.enabled)return{tone:`idle`,label:Z.t(`helpers.coreBlockStatus.disabled`),detail:Z.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Z.t(`helpers.coreBlockStatus.running`),detail:Z.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Z.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Z.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Z.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Z.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function lr(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function ur(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function dr(e){let t=e=>{let t=cr(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 fr(e){if(e.length===0)return Z.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>cr(e).tone===`error`).length,n=e.filter(e=>cr(e).tone===`ok`).length,r=[Z.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Z.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Z.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var pr=3e4;function mr({block:t,logsOpen:n,unreadable:r}){let i=y(),{t:a}=Q(),s=cr(t),c=et(t.updatedAt,i);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(q,{variant:lr(s.tone),children:s.label}),c!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.edited`,{when:c})})]}),(s.tone===`error`||s.tone===`pending`)&&o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:s.detail}),r!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:a(`automation.editor.listUnreadable`,{reason:r})}),n&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(bt,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(xe,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var hr=2;function gr(e){let t=[];if(ne(e.when,e=>{W(e)&&t.push(Kt(e.kind))}),t.length===0)return de(e.when)===0?``:Z.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,hr).join(`, `),i=n.length-hr;return i>0?`${r} +${i}`:r}function _r({recipe:e}){let{t}=Q();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=gr(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function vr({blockId:t}){let{t:n}=Q(),r=Xe({blockId:t},{refetchInterval:pr});if(r.data===void 0)return r.error===null||r.error===void 0?o(gt,{className:`h-4 w-16`}):o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.lastRunUnknown`,`Unknown`)});let i=r.data.traces.findLast(e=>!e.outcome.startsWith(`skipped-`));if(i===void 0)return o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.neverRan`,`Never ran`)});let a=i.outcome===`failed`||i.outcome===`aborted`;return e(`span`,{className:`inline-flex items-center gap-2`,children:[At(i.lastAt),a&&o(q,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function yr({block:e,disabled:t,onToggle:n}){let{t:r}=Q();return o(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(st,{checked:e.enabled,disabled:t,onCheckedChange:n,"aria-label":e.enabled?r(`automation.automationList.disableNamed`,`Disable {{name}}`,{name:e.name}):r(`automation.automationList.enableNamed`,`Enable {{name}}`,{name:e.name})})})}function br({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=Q();return o(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(Ce,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:E,disabled:e!==null,description:e===null?void 0:i(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),onClick:t},{id:`run`,label:i(`automation.automationList.runActions`,`Run actions`),icon:C,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:O,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:w,danger:!0,separatorBefore:!0,onClick:r}]})})}function xr({onCreate:t}){let{t:n}=Q();return o(qe,{icon:A,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(J,{onClick:t,"data-testid":`automation-empty-new`,children:[o(g,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();var Sr=[`coreBlocks`,`list`],Cr=5e3;function wr(e){return e instanceof Error?e.message:String(e)}function Tr({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:a}=Q(),u=D(),{state:d,openNew:p,openEdit:m,close:h}=Se({editKey:`block`,newKey:`new`}),g=T(),[_,v]=c(null),y=d.mode!==`closed`;s(()=>{n&&(p(),i?.())},[n,i,p]);let b=l({queryKey:Sr,refetchInterval:Cr,queryFn:async()=>(await u.trpcClient.coreBlocks.list.query({})).blocks}),x=()=>{b.refetch()},S=e=>{h(),x(),Et({title:a(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},C=f({mutationFn:e=>u.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>S(e.block)}),w=f({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>S(e.block)}),E=f({mutationFn:e=>u.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:x}),O=f({mutationFn:e=>u.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:x}),k=f({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:yn(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{h(),x(),t(e.block.id)}}),j=b.data,M=dr((j??[]).filter(e=>gn(e.code))),N=j!==void 0&&M.length===0,P=d.mode===`edit`?M.find(e=>e.id===d.id)??null:null,F=d.mode===`edit`&&j!==void 0&&P===null;s(()=>{F&&h()},[F,h]);let I=P===null?null:vn(P.code),L=C.error===null?w.error===null?k.error===null?null:wr(k.error):wr(w.error):wr(C.error),R=r(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=vn(e.code);return o(mr,{block:e,logsOpen:_===e.id,unreadable:t.ok?null:t.reason})},sortValue:e=>e.name},{key:`trigger`,header:a(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=vn(e.code);return o(_r,{recipe:t.ok?t.recipe:null})},notSortableReason:a(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:a(`build.automationsTab.lastRun`,`Last run`),render:e=>o(vr,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>o(yr,{block:e,disabled:O.isPending,onToggle:t=>O.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=vn(e.code);return o(br,{unreadable:t.ok?null:t.reason,onEdit:()=>m(e.id),onToggleLogs:()=>v(_===e.id?null:e.id),onDelete:()=>{g({title:a(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:a(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&E.mutate(e.id)})}})}}],[g,_,m,E,O,a]);return y?d.mode===`edit`&&P===null?o(gt,{className:`h-24 w-full`}):e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[o(A,{className:`h-4 w-4 text-foreground-muted`}),P===null?a(`build.automationsTab.newAutomation`,`New automation`):a(`build.automationsTab.edit`,`Edit {{name}}`,{name:P.name})]}),o(ar,{existing:P,initialRecipe:I!==null&&I.ok?I.recipe:rn,saving:C.isPending||w.isPending,saveError:L,ejecting:k.isPending,onSave:e=>{P===null?C.mutate(e):w.mutate({blockId:P.id,block:e})},onEject:()=>{P!==null&&k.mutate(P)},onCancel:()=>{C.reset(),w.reset(),k.reset(),h()}},P?.id??`new`),E.error!=null&&o(Y,{message:wr(E.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:j===void 0?``:fr(M)}),b.error!=null&&o(Y,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:wr(b.error),onRetry:x}),N?o(xr,{onCreate:p}):o(Ee,{columns:R,rows:M,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ve,emptyMessage:j===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>m(e.id)}),E.error!=null&&o(Y,{message:wr(E.error)}),O.error!=null&&o(Y,{message:wr(O.error)})]})}var Er={kind:`all`,children:[]};function Dr({value:t,devices:n,label:r,onChange:i}){let{t:a}=Q(),s=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[o(st,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?Er:void 0)}),s!==null&&e(p,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.activeWhen.hint`,`Only states count here, such as "someone is home". While they are false, nothing runs and holds pause.`)}),o(Xt,{recipe:s,devices:n,onChange:e=>i(e.when)})]})]})}var Or=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],kr=720,Ar=1440;function jr(){return{name:``,enabled:!0,priority:0,maxLateMs:ue,profiles:[Mr(`profile-1`,`Every day`)]}}function Mr(e,t){return{id:e,name:t,enabled:!0,days:[...Or],points:[]}}function Nr(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function Pr(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function Fr(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function Ir(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,hourCycle:`h23`,hour:`2-digit`,minute:`2-digit`}).formatToParts(new Date(e)),r=e=>Number(n.find(t=>t.type===e)?.value??0);return r(`hour`)*60+r(`minute`)}function Lr(e,t=Date.now()){return re(t,e.timeZone)}function Rr(e,t,n){let r=Fr(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=U(e,n,r);return i===null?null:Ir(i,t.timeZone)}function zr(e,t,n){return e.kind===`sun`?Rr({...e,offsetMin:0},t,n):null}function Br(e,t,n){if(e.kind===`clock`)return{kind:`clock`,hh:Math.floor(t/60),mm:t%60};if(e.kind===`sun`&&n!==null){let r=Math.max(-720,Math.min(kr,t-n));return{...e,offsetMin:r}}return e}function Vr(e){let t=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(e);return t===null?null:{kind:`clock`,hh:Number(t[1]),mm:Number(t[2])}}function Hr(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function Ur(e){return Hr(Math.floor(e/60),e%60)}function Wr(e,t,n){let r=e.flatMap(e=>{let r=Rr(e.at,t,n);return r===null?[]:[{point:e,minute:r}]}).toSorted((e,t)=>e.minute-t.minute);return r.flatMap((e,t)=>{if(e.point.mode!==`hold`)return[];let n=r[t+1];return[{id:e.point.id,fromMinute:e.minute,toMinute:n===void 0?Ar:n.minute}]})}function Gr(e,t){let n=se.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=le(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}var Kr=[`sunrise`,`sunset`,`dawn`,`dusk`],qr=6e4;function Jr(e){return e.kind===`cap`||e.kind===`wait`}function Yr(e,t){let n={id:e.id,at:e.at,mode:t,steps:t===`release`?[]:e.steps,...e.conditions===void 0?{}:{conditions:e.conditions}};return t===`hold`?{...n,...e.override===void 0?{}:{override:e.override},...e.maxHoldAttempts===void 0?{}:{maxHoldAttempts:e.maxHoldAttempts}}:n}function Xr({point:t,devices:n,site:r,localDate:i,issues:a,onChange:s,onRemove:c}){let{t:l}=Q(),u=t.at,d=u.kind===`sun`?Rr(u,r,i):null,f=zr(u,r,i),m=t.override??{mode:`respect`},h=e=>s({...t,at:e});return e(`div`,{className:`space-y-3`,"data-testid":`point-editor`,children:[e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.kind`,`Point type`)}),o(k,{"aria-label":l(`schedulers.point.kind`,`Point type`),value:t.mode,options:[{value:`edge`,label:l(`schedulers.point.edge`,`Edge: run once`)},{value:`hold`,label:l(`schedulers.point.hold`,`Hold: keep true`)},{value:`release`,label:l(`schedulers.point.release`,`Release: end the hold`)}],onChange:e=>{let n=e.target.value;(n===`edge`||n===`hold`||n===`release`)&&s(Yr(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.when`,`When`)}),o(k,{"aria-label":l(`schedulers.point.when`,`When`),value:u.kind===`sun`?`sun`:`clock`,options:[{value:`clock`,label:l(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:l(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{e.target.value===`sun`?h({kind:`sun`,event:`sunset`,offsetMin:0}):h({kind:`clock`,hh:12,mm:0})}})]}),u.kind===`clock`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.time`,`Time`)}),o(X,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:Hr(u.hh,u.mm),onChange:e=>{let t=Vr(e.target.value);t!==null&&h(t)}})]}),u.kind===`sun`&&e(p,{children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.sunEvent`,`Sun event`)}),o(k,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:Kr.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Kr.find(t=>t===e.target.value);t!==void 0&&h({...u,event:t})}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.offset`,`Offset (minutes, negative = before)`)}),o(sn,{"aria-label":l(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-28`,value:u.offsetMin,onValue:e=>{e!==null&&h({...u,offsetMin:Math.round(e)})}})]}),o(`p`,{className:`pb-2 text-xs text-foreground-muted`,"data-testid":`sun-computed`,children:d===null||f===null?l(`schedulers.point.sunUnknown`,`No time today: the site location is not set.`):l(`schedulers.point.sunComputed`,`Today at {{time}} ({{zone}})`,{time:Ur(d),zone:r.timeZone})})]}),e(J,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[o(w,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&o(nn,{actions:t.steps,devices:n,allowedKinds:[`cap`,`wait`],onChange:e=>s({...t,steps:e.filter(Jr)})}),t.mode===`release`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:l(`schedulers.point.releaseHint`,`A release ends the running hold without doing anything to the devices.`)}),t.mode===`hold`&&e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.override`,`If someone changes it by hand`)}),o(k,{"aria-label":l(`schedulers.point.override`,`If someone changes it by hand`),value:m.mode,options:[{value:`respect`,label:l(`schedulers.point.respect`,`Leave it alone`)},{value:`reassert`,label:l(`schedulers.point.reassert`,`Put the hold back after a while`)}],onChange:e=>s({...t,override:e.target.value===`reassert`?{mode:`reassert`,graceMs:10*qr}:{mode:`respect`}})})]}),m.mode===`reassert`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.grace`,`Wait (minutes)`)}),o(sn,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:m.graceMs/qr,onValue:e=>{e!==null&&s({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*qr))}})}})]})]}),a.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:a.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))})]})}u();var Zr=5e3,Qr=600,$r=6e4,ei={timeZone:`UTC`,location:null};function ti(e){return e instanceof Error?e.message:String(e)}function ni(e){if(e===null)return jr();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function ri(e,t){let[n,r]=c(e);return s(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function ii(e,t){return t(`schedulers.day.${e}`,e)}function ai({entry:t,onClose:n,onSaved:i}){let{t:a}=Q(),s=d(),l=T(),u=en(),f=be(),p=f.data??ei,[m,h]=c(()=>ni(t)),[_,v]=c(()=>m.profiles[0]?.id??``),[y,x]=c(null),[S,C]=c(null),E=()=>{s.invalidateQueries({queryKey:[[`schedulers`]]})},D=ht({onSuccess:e=>{E(),i(e.scheduler.id)}}),O=ye({onSuccess:E}),k=Oe({onSuccess:()=>{E(),n()}}),A=ze({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:Zr}),j=r(()=>Gr(m,p),[m,p]),M=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),N=ri(j.ok?j.input:null,Qr),P=Me(N===null?{scheduler:m}:t===null?{scheduler:N}:{scheduler:N,schedulerId:t.id},{enabled:N!==null&&M&&f.data!==void 0}),F=m.profiles.find(e=>e.id===_)??m.profiles[0],I=F===void 0?-1:m.profiles.indexOf(F),L=Lr(p),R=F?.points.find(e=>e.id===y)??null,z=F===void 0||R===null?-1:F.points.indexOf(R),B=j.ok?[]:j.issues,V=e=>B.filter(t=>t.path===e||t.path.startsWith(`${e}.`)),H=e=>h({...m,profiles:m.profiles.map((t,n)=>n===I?e:t)}),U=e=>{F!==void 0&&H({...F,points:F.points.map(t=>t.id===e.id?e:t)})},ee=r(()=>F===void 0?[]:F.points.flatMap(e=>{let t=Rr(e.at,p,L);if(t===null)return[];let n=e.at.kind===`sun`?`${a(`schedulers.sun.${e.at.event}`,e.at.event)} ${e.at.offsetMin>=0?`+`:``}${String(e.at.offsetMin)} (${Ur(t)})`:Hr(e.at.hh,e.at.mm);return[{id:e.id,minute:t,label:n,tone:e.mode===`hold`?`success`:e.mode===`release`?`neutral`:`primary`,draggable:e.at.kind===`clock`||e.at.kind===`sun`&&zr(e.at,p,L)!==null}]}),[F,p,L,a]),te=r(()=>F===void 0?[]:Wr(F.points,p,L),[F,p,L]),ne=(e,t)=>{let n=F?.points.find(t=>t.id===e);n!==void 0&&U({...n,at:Br(n.at,t,zr(n.at,p,L))})},W=e=>{if(F===void 0)return;let t=Pr(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));H({...F,points:[...F.points,Nr(e,t,720)]}),x(t)},G=()=>{let e=Pr(`profile`,m.profiles.map(e=>e.id));h({...m,profiles:[...m.profiles,Mr(e,a(`schedulers.profile.newName`,`New profile`))]}),v(e),x(null)},re=D.isPending||O.isPending,ie=D.error??O.error??k.error;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`scheduler-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(fe,{className:`h-4 w-4 text-foreground-muted`}),o(X,{"aria-label":a(`schedulers.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,placeholder:a(`schedulers.editor.namePlaceholder`,`What this scheduler does`),onChange:e=>h({...m,name:e.target.value})})]}),e(Ae,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[o(pt,{label:a(`schedulers.editor.enabled`,`Enabled`),children:o(st,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>h({...m,enabled:e})})}),o(pt,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:o(sn,{"aria-label":a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),className:`w-24`,value:m.priority,onValue:e=>{e!==null&&h({...m,priority:Math.round(e)})}})}),o(pt,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:o(sn,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/$r,onValue:e=>{e!==null&&h({...m,maxLateMs:Math.round(e*$r)})}})})]}),e(`div`,{className:`p-3`,children:[o(Dr,{value:m.activeWhen,devices:u,label:a(`schedulers.editor.activeWhen`,`Only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=m;h(e===void 0?n:{...n,activeWhen:e})}}),V(`activeWhen`).map(e=>o(`p`,{className:`mt-1 text-xs text-warning`,children:e.message},e.message))]})]}),o(Ae,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(J,{variant:`outline`,size:`sm`,onClick:G,children:[o(g,{className:`h-4 w-4`}),` `,a(`schedulers.profile.add`,`Add profile`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.profile.hint`,`Each day, the first profile in this order whose days and condition hold is the one that runs.`)}),F!==void 0&&e(vt,{value:F.id,onValueChange:e=>{v(e),x(null)},appearance:`pills`,children:[o($e,{children:m.profiles.map(e=>o(dt,{value:e.id,children:e.name},e.id))}),e(Ze,{value:F.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(X,{"aria-label":a(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:F.name,onChange:e=>H({...F,name:e.target.value})}),o(st,{checked:F.enabled,label:a(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>H({...F,enabled:e})}),m.profiles.length>1&&e(J,{variant:`ghost`,size:`sm`,onClick:()=>{h({...m,profiles:m.profiles.filter(e=>e.id!==F.id)}),v(``),x(null)},children:[o(w,{className:`h-4 w-4`}),` `,a(`schedulers.profile.remove`,`Remove profile`)]})]}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":a(`schedulers.profile.days`,`Days`),children:Or.map(e=>{let t=F.days.includes(e);return o(J,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>H({...F,days:t?F.days.filter(t=>t!==e):Or.filter(t=>t===e||F.days.includes(t))}),children:ii(e,a)},e)})}),V(`profiles.${String(I)}.days`).map(e=>o(`p`,{className:`text-xs text-warning`,children:a(`schedulers.profile.daysNeeded`,`Pick at least one day.`)},e.message)),o(Dr,{value:F.activeWhen,devices:u,label:a(`schedulers.profile.activeWhen`,`This profile only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=F;H(e===void 0?n:{...n,activeWhen:e})}}),o(Je,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:ee,bands:te,selectedId:y,onSelect:x,onMove:ne}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:`outline`,size:`sm`,onClick:()=>W(`edge`),children:[o(g,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(J,{variant:`outline`,size:`sm`,onClick:()=>W(`hold`),children:[o(g,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(J,{variant:`outline`,size:`sm`,onClick:()=>W(`release`),children:[o(g,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),o(q,{variant:`neutral`,children:p.timeZone})]}),F.points.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.timeline.empty`,`Add a point to place something on the day.`)}),R!==null&&o(Xr,{point:R,devices:u,site:p,localDate:L,issues:V(`profiles.${String(I)}.points.${String(z)}`),onChange:U,onRemove:()=>{H({...F,points:F.points.filter(e=>e.id!==R.id)}),x(null)}},R.id)]})]})]})}),P.data!==void 0&&P.data.conflicts.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:P.data.conflicts.map(e=>o(`li`,{children:a(`schedulers.conflict.message`,`{{other}} wants device {{device}} in another state from {{from}} to {{to}} ({{winner}}).`,{other:e.other.schedulerName,device:e.deviceId,from:Ur(e.fromMinute),to:Ur(e.toMinute),winner:e.winner===`mine`?a(`schedulers.conflict.mine`,`this one wins`):e.winner===`other`?a(`schedulers.conflict.other`,`the other one wins`):a(`schedulers.conflict.tie`,`the one that started first wins`)})},`${e.other.schedulerId}:${e.other.pointId}:${e.mine.pointId}:${String(e.deviceId)}`))}),!j.ok&&m.name!==``&&B.length>0&&R===null&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:B.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))}),ie!==null&&o(Y,{message:ti(ie)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(J,{onClick:()=>{j.ok&&(t===null?D.mutate({scheduler:j.input}):O.mutate({schedulerId:t.id,scheduler:j.input}))},disabled:re||!j.ok||f.data===void 0,children:[re&&o(b,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(J,{variant:`ghost`,disabled:k.isPending,onClick:()=>{l({title:a(`schedulers.editor.deleteTitle`,`Delete this scheduler?`),message:a(`schedulers.editor.deleteMessage`,`{{name}} will be deleted and any hold it keeps will stop.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&k.mutate({schedulerId:t.id})})},children:[o(w,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(J,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(on,{traces:t===null?[]:A.data?.traces,selectedId:S,onSelect:C})})]})}u();var oi=5e3;function si(e){return e instanceof Error?e.message:String(e)}function ci({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),a=d(),{state:c,openNew:l,openEdit:u,close:f}=Se({editKey:`scheduler`,newKey:`new`}),p=Ge({},{refetchInterval:oi}),m=Ue({},{refetchInterval:oi}),h=Pe({onSuccess:()=>void a.invalidateQueries({queryKey:[[`schedulers`]]})});s(()=>{t&&(l(),n?.())},[t,n,l]);let _=p.data??[],v=c.mode===`edit`?_.find(e=>e.id===c.id)??null:null,y=e=>{if(!e.enabled)return{variant:`neutral`,label:i(`schedulers.status.off`,`Off`)};let t=m.data?.find(t=>t.schedulerId===e.id);return t===void 0?{variant:`neutral`,label:`-`}:t.hold===null?{variant:`neutral`,label:i(`schedulers.status.idle`,`Idle`)}:t.hold.suspendedInactive?{variant:`warning`,label:i(`schedulers.status.paused`,`Paused`)}:t.hold.targets.some(e=>e.status===`gave-up`)?{variant:`danger`,label:i(`schedulers.status.gaveUp`,`Gave up`)}:{variant:`success`,label:i(`schedulers.status.holding`,`Holding`)}},b=r(()=>[{key:`name`,header:i(`schedulers.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`enabled`,header:i(`schedulers.list.enabled`,`Enabled`),render:e=>o(`span`,{onClick:e=>e.stopPropagation(),children:o(st,{checked:e.enabled,disabled:h.isPending,"aria-label":i(`schedulers.list.enabledAria`,`Enable {{name}}`,{name:e.name}),onCheckedChange:t=>h.mutate({schedulerId:e.id,enabled:t})})}),sortValue:e=>Number(e.enabled)},{key:`profiles`,header:i(`schedulers.list.profiles`,`Profiles`),render:e=>String(e.profiles.length),sortValue:e=>e.profiles.length},{key:`priority`,header:i(`schedulers.list.priority`,`Priority`),render:e=>String(e.priority),sortValue:e=>e.priority},{key:`status`,header:i(`schedulers.list.status`,`Now`),render:e=>{let t=y(e);return o(q,{variant:t.variant,children:t.label})},notSortableReason:i(`schedulers.list.statusNotSortable`,`Derived from the live hold`)},{key:`updated`,header:i(`schedulers.list.updated`,`Updated`),render:e=>At(e.updatedAt),sortValue:e=>e.updatedAt}],[h,m.data,i]);return c.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`schedulers.list.hint`,`A scheduler does things over the day: run something at a time or at sunset, or keep a device in a state for a stretch of time.`)}),h.error!=null&&o(Y,{message:si(h.error)}),p.data===void 0?p.error==null?o(gt,{className:`h-24 w-full`}):o(Y,{title:i(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:si(p.error),onRetry:()=>void p.refetch()}):_.length===0?o(qe,{icon:fe,title:i(`schedulers.list.emptyTitle`,`No schedulers yet`),description:i(`schedulers.list.emptyDescription`,`A scheduler turns the garden lights on at sunset and off at 23:00, every day or only on some days.`),action:e(J,{onClick:l,children:[o(g,{className:`h-4 w-4`}),` `,i(`schedulers.list.new`,`New scheduler`)]})}):o(Ee,{columns:b,rows:_,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ve,emptyMessage:i(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):o(ai,{entry:v,onClose:f,onSaved:u},v?.id??`new`)}async function li(e,t){let n=`${P}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var ui=10,di=400;async function fi(e,t,n=di){for(let r=0;r<ui;r+=1){let r=await li(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var pi=`media-player`;function mi(e){return e===N.MediaPlayer?`media-source`:e===N.Heater?`control-source`:`none`}function hi(e){return e===N.Heater?G():e===N.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[N.MediaPlayer],accept:[{cap:pi,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[pi],exclude:[]}:null}function gi(e,t){return e!==N.Heater||t!==null&&t.cap===`switch`}var _i={kind:`expression`,expr:`now`,bindings:{}};function vi(e){return{kind:`fields`,cap:`switch`,fields:{on:{kind:`from`,source:e.source,cap:e.cap,fieldPath:e.fieldPath},lastChangedAt:_i},commands:{setState:{kind:`forward`,source:e.source,cap:`switch`,method:`setState`}}}}function yi(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:pi,fields:{},commands:Object.fromEntries(Object.keys(ie()).map(t=>[t,{kind:`forward`,source:e.source,cap:pi,method:t}]))}]}function bi(e,t){if(!gi(e,t))return null;let n=e===N.Heater&&t!==null?[vi(t)]:e===N.MediaPlayer?yi(t):[];return{target:{kind:`new`,type:e},features:n}}u();function xi({onTitle:t}){let{t:n}=Q(),r=y(),i=yt(),a=an(),l=Fe(),u=lt({addonId:`composer`}),[d,f]=c(N.Sensor),[p,m]=c(``),[h,g]=c([]),[_,v]=c(null),b=h[0]??null,x=hi(d),S=bi(d,b);s(()=>{t(n(`helper.newDevice`))},[t,n]);let C=async()=>{if(S!==null){v(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:S}}),r=await fi(t.id,async()=>(await u.refetch()).data??u.data);if(r===null){v(n(`helper.devicePending`));return}e!==``&&await l.mutateAsync({deviceId:r,name:e}),i(Dt(r),{replace:!0})}catch(e){v(e instanceof Error?e.message:String(e))}}};return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`device-create-form`,children:[e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.targetType`),o(k,{value:d,onChange:e=>{let t=Object.values(N).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(N).map(e=>({value:e,label:Te(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(X,{"aria-label":n(`compositionEditor.name`),value:p,onChange:e=>m(e.target.value)})]})]}),x!==null&&e(`div`,{className:`flex flex-col gap-1`,"data-testid":`device-create-source`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:n(`helper.deviceSource.${mi(d)}`)}),o(Nt,{kind:`members`,request:x,enabled:!0,members:h,onMembersChange:g,onRefuse:()=>void 0})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(J,{disabled:!gi(d,b)||a.isPending,onClick:()=>void C(),children:n(`compositionEditor.save`)})]})}u();function Si({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=Q(),u=zt(!0),[d,f]=c({}),[p,m]=c(s(t.nameKey)),[h,g]=c(null),[_,v]=c([]),[y,b]=c(!1),x=r(()=>u.kind===`known`?new Map(u.value.map(e=>[F({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[F(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:jt(u.value,S)}:u,[u,S]),w=Vt(t,d),T=u.kind===`known`?Ht(u.value,w,!1):null,E=t.build(d),D=It(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(F(e))??e.stableId;return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`preset-wizard`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:s(t.descriptionKey)}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[s(`preset.name`),o(X,{"aria-label":s(`preset.name`),value:p,onChange:e=>m(e.target.value)})]}),o(`ul`,{className:`flex flex-col gap-2`,"aria-label":s(`preset.slots`),children:t.slots.map(t=>{let n=d[t.key];return e(`li`,{className:`grid grid-cols-1 gap-1 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center`,"data-testid":`preset-slot-${t.key}`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`text-xs text-foreground`,children:[s(t.labelKey),t.optionalGroup===void 0?` *`:``]}),e(`div`,{className:`text-[11px] text-foreground-muted break-words`,children:[Lt(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(J,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(J,{variant:`ghost`,size:`sm`,onClick:()=>O(t.key,void 0),children:s(`preset.clear`)})]})]},t.key)})}),E===null&&D.length>0&&o(`p`,{className:`text-[11px] text-foreground-muted`,"data-testid":`preset-missing`,children:s(`preset.missing`,{slots:D.map(e=>s(e.labelKey)).join(`, `)})}),E!==null&&e(`section`,{className:`flex flex-col gap-1`,"data-testid":`preset-preview`,children:[o(`h3`,{className:`text-xs font-medium text-foreground`,children:s(`preset.preview`)}),o(`ul`,{className:`flex flex-col gap-1 text-[11px] text-foreground-muted`,children:E.features.map(e=>e.kind===`fields`?o(`li`,{children:s(`preset.previewFeature`,{cap:Lt(e.cap,l.language),fields:Object.keys(e.fields).length,commands:Object.keys(e.commands??{}).length+Object.values(e.items??{}).filter(e=>e.reset!==void 0).length})},e.cap):null)})]}),o(Bt,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(J,{disabled:E===null||n||y,onClick:()=>{E===null||y||(b(!0),i(E,p.trim()).then(e=>{e.kind===`refused`&&v(e.lines)}).finally(()=>b(!1)))},"data-testid":`preset-create`,children:s(`preset.create`)}),o(J,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o(Pt,{open:h!==null,title:h===null?``:s(`preset.pickTitle`,{slot:s(h.labelKey)}),selection:`single`,candidates:C,room:T,confirmLabel:()=>s(`preset.pickConfirm`),onConfirm:e=>{let t=e[0],n=h;g(null),t!==void 0&&n!==null&&O(n.key,t.ref)},onClose:()=>g(null)})]})}u();var Ci=`preset`;function wi({mode:e,onTitle:t}){return o(e===`helper`?Ti:xi,{onTitle:t})}function Ti({onTitle:e}){let{t}=Q(),r=yt(),i=an(),a=Fe(),l=lt({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=Ct(),g=Mt(m.get(Ci)),_=g===null?Ei(u,t):t(g.labelKey);s(()=>{f||e(_)},[e,_,f]);let v=e=>h(t=>{let n=new URLSearchParams(t);return e===null?n.delete(Ci):n.set(Ci,e),n},{replace:!0}),y=async(e,n)=>{try{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:e}}),s=await fi(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:Ft(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(Dt(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:Ft(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(xi,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Rt,{fillHeight:!0,onDevice:()=>p(!0),onPreset:v,purpose:`create`,initial:null,start:`template`,saving:i.isPending,onDraftChange:d,onSave:async(e,n)=>{let o=null,s=await Ut(e,async(s,c)=>{let u=b.current,d;if(u!==null&&u.draft===e)d=u.blockId;else{let{block:t}=await i.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:s}});d=t.id,b.current={draft:e,blockId:d}}let f=await fi(d,async()=>(await l.refetch()).data??l.data);if(f===null)throw Error(t(`helper.devicePending`));o=f,b.current=null,c!==``&&await a.mutateAsync({deviceId:f,name:c}),n===`open`&&r(Tt(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:Di(s,t)}:{kind:`saved`,deviceId:c}}})}):o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Si,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function Ei(e,t){if(e===null)return t(`helper.newComposed`);if(e.kind===`statistic`)return t(`helper.newTitle.statistic`);if(e.kind===`integral`)return t(`helper.newTitle.integral`);if(e.kind===`arithmetic`)return t(`helper.newTitle.${e.op}`);if(e.kind===`threshold`||e.kind===`expression`||e.kind===`derivative`)return t(`helper.newTitle.${e.kind}`);let n=M(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function Di(e,t){return e.length>0?e:Ft(t(`helper.devicePending`))}function Oi(e){let t=e.helper;if(t===void 0)return{section:`advanced`,kind:null};switch(t.kind){case`group`:return{section:`group`,kind:t.templateId};case`arithmetic`:return{section:`calculation`,kind:t.op};case`expression`:return{section:`advanced`,kind:`expression`};default:return{section:`calculation`,kind:t.kind}}}function ki(e){return{state:`answered`,byRef:new Map(e.map(e=>[F(e),e]))}}function Ai(e,t){if(e.state!==`unanswered`)return e.byRef.get(F(t))??null}function ji(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Mi(e){return L(e).map(e=>e.source)}function Ni(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(...Mi(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Mi(e))}let r=new Set;return n.filter(e=>{let t=F(e);return r.has(t)?!1:(r.add(t),!0)})}function Pi(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:Z.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Z.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Z.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Z.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Z.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function Fi(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Pi(e);case`degraded`:return{tone:`pending`,label:Z.t(`helpers.compositionRows.degraded`),reason:n??Z.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Z.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Z.t(`helpers.compositionRows.failed`),reason:n??Z.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Z.t(`helpers.compositionRows.notRunning`),reason:n??Z.t(`helpers.compositionRows.notRunningReason`)}}}function Ii(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Z.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Z.t(`helpers.compositionRows.unknown`),reason:Z.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return Fi(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Z.t(`helpers.compositionRows.notReported`),reason:Z.t(`helpers.compositionRows.noRecord`,{stored:r})}}function Li(e){return F(e)}function Ri(e,t){let n=Ai(t,e);return{key:F(e),label:n?n.name:Li(e),presence:ji(n),deviceId:n?n.id:null}}function zi(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Bi(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:I(e.block.id),a=F(i),o=Ni(e).filter(e=>F(e)!==a).map(e=>Ri(e,t)),s=n.features.map(e=>e.enabled===!1?Z.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Ai(t,i),l=zi(e),u=Ii(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,origin:Oi(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=ji(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Li(r.device),namePresence:d,type:c?c.type:null,origin:Oi(n),features:s,state:u,sources:o,reportedDeviceId:l}}function Vi(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Hi(e,t){return Vi(e)-Vi(t)||e.name.localeCompare(t.name)}function Ui(e,t){let n=e.flatMap(e=>{let n=Bi(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Hi),customizations:n.filter(e=>e.kind===`customization`).toSorted(Hi)}}u();var Wi=1e4;function Gi(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Ki(){let e=St();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Z.t(`build.customDeviceTab.deviceListPending`):Z.t(`build.customDeviceTab.deviceListUnreadable`,{error:Gi(e.error)})}:ki(e.data)}function qi(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Ji({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Q(),[i,a]=Ct(),s=ut({},{refetchInterval:Wi}),l=Ki(),u=Se({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?qi(i.get(`new`),t):null,m=f!==null,[h,g]=c(``),_=T(),v=ct(),y=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},b=s.data;return e(p,{children:[Xi(b,s.error,()=>void s.refetch(),l,{onEditComposed:e=>u.openEdit(e),deleting:v.isPending,onDelete:e=>{_({title:r(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`),message:r(`build.customDeviceTab.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:r(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&v.mutate({blockId:e.blockId},{onSuccess:()=>void s.refetch()})})}}),o(at,{open:m,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:K,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(wi,{mode:f,onTitle:g},f)}),o($t,{blockId:d,onClose:y}),v.error!=null&&o(Y,{message:Gi(v.error)})]})}function Yi(t){return o(ve,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Z.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Z.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Xi(e,t,n,r,i){if(t!=null&&e===void 0)return o(Y,{title:Z.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Gi(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Z.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return Yi(e.reason);let a=t==null?null:Gi(t);return o(Zi,{lists:Ui(e.views,r),fleet:r,refreshError:a,handlers:i})}function Zi({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Q();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(Qi,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,handlers:i}),o(Qi,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,handlers:i})]})}function Qi({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=Q();return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(Ee,{columns:$i(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:Ve,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function $i(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(ta,{row:e})},{key:`type`,header:Z.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Z.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:Z.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>ea(e.origin,i),render:e=>o(q,{variant:`default`,"data-testid":`composed-origin-badge`,children:ea(e.origin,i)})}]:[],{key:`state`,header:Z.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(q,{variant:lr(t.state.tone),children:t.state.label}),t.state.reason!==null&&o(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:Z.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(ra,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[o(J,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(J,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:o(w,{className:`h-4 w-4`})})]})}),a}function ea(e,t){let n=e.kind===null?null:t(`helper.template.${e.kind}`);return e.section===`group`?t(`helper.badge.group`,{kind:n}):e.section===`calculation`?t(`helper.badge.calculation`,{kind:n}):n===null?t(`helper.badge.advanced`):t(`helper.badge.advancedKind`,{kind:n})}function ta({row:t}){let{t:n}=Q();return e(`div`,{className:`space-y-0.5`,children:[o(na,{row:t}),t.namePresence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),o(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function na({row:e}){let{t}=Q(),n=nt(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):o(Ot,{to:e.kind===`composed`?Tt(e.reportedDeviceId):Dt(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function ra({sources:t}){let{t:n}=Q();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(Ot,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function ia(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 aa(e){if(Array.isArray(e))return e}function oa(e,t,n){return(t=ha(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function sa(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 ca(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
4
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function la(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 ua(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?la(Object(n),!0).forEach(function(t){oa(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):la(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function da(e,t){if(e==null)return{};var n,r,i=fa(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 fa(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 pa(e,t){return aa(e)||sa(e,t)||ga(e,t)||ca()}function ma(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 ha(e){var t=ma(e,`string`);return typeof t==`symbol`?t:t+``}function ga(e,t){if(e){if(typeof e==`string`)return ia(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)?ia(e,t):void 0}}function _a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function va(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 ya(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?va(Object(n),!0).forEach(function(t){_a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):va(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ba(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function xa(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 Sa(e){return{}.toString.call(e).includes(`Object`)}function Ca(e){return!Object.keys(e).length}function wa(e){return typeof e==`function`}function Ta(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ea(e,t){return Sa(t)||ja(`changeType`),Object.keys(t).some(function(t){return!Ta(e,t)})&&ja(`changeField`),t}function Da(e){wa(e)||ja(`selectorType`)}function Oa(e){wa(e)||Sa(e)||ja(`handlerType`),Sa(e)&&Object.values(e).some(function(e){return!wa(e)})&&ja(`handlersType`)}function ka(e){e||ja(`initialIsRequired`),Sa(e)||ja(`initialType`),Ca(e)&&ja(`initialContent`)}function Aa(e,t){throw Error(e[t]||e.default)}var ja=xa(Aa)({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"}),Ma={changes:Ea,selector:Da,handler:Oa,initial:ka};function Na(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ma.initial(e),Ma.handler(t);var n={current:e},r=xa(Ia)(n,t),i=xa(Fa)(n),a=xa(Ma.changes)(e),o=xa(Pa)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Ma.selector(e),e(n.current)}function c(e){ba(r,i,a,o)(e)}return[s,c]}function Pa(e,t){return wa(t)?t(e.current):t}function Fa(e,t){return e.current=ya(ya({},e.current),t),t}function Ia(e,t,n){return wa(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var La={create:Na},Ra={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function za(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 Ba(e){return{}.toString.call(e).includes(`Object`)}function Va(e){return e||Ga(`configIsRequired`),Ba(e)||Ga(`configType`),e.urls?(Ha(),{paths:{vs:e.urls.monacoBase}}):e}function Ha(){console.warn(Wa.deprecation)}function Ua(e,t){throw Error(e[t]||e.default)}var Wa={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!
5
- You are using deprecated way of configuration.
6
-
7
- Instead of using
8
- monaco.config({ urls: { monacoBase: '...' } })
9
- use
10
- monaco.config({ paths: { vs: '...' } })
11
-
12
- For more please check the link https://github.com/suren-atoyan/monaco-loader#config
13
- `},Ga=za(Ua)(Wa),Ka={config:Va},qa=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Ja(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Ja(e[n],t[n]))}),ua(ua({},e),t)}var Ya={type:`cancelation`,msg:`operation is manually canceled`};function Xa(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Ya):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var Za=[`monaco`],Qa=pa(La.create({config:Ra,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),$a=Qa[0],eo=Qa[1];function to(e){var t=Ka.config(e),n=t.monaco,r=da(t,Za);eo(function(e){return{config:Ja(e.config,r),monaco:n}})}function no(){var e=$a(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(eo({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Xa(lo);if(window.monaco&&window.monaco.editor)return so(window.monaco),e.resolve(window.monaco),Xa(lo);qa(ro,ao)(oo)}return Xa(lo)}function ro(e){return document.body.appendChild(e)}function io(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function ao(e){var t=$a(function(e){return{config:e.config,reject:e.reject}}),n=io(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function oo(){var e=$a(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;so(n),e.resolve(n)},function(t){e.reject(t)})}function so(e){$a().monaco||eo({monaco:e})}function co(){return $a(function(e){return e.monaco})}var lo=new Promise(function(e,t){return eo({resolve:e,reject:t})}),uo={config:to,init:no,__getMonacoInstance:co};u();var fo={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},po={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function mo({children:e}){return t.createElement(`div`,{style:po.container},e)}var ho=mo;function go({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...fo.wrapper,width:e,height:n},...s},!r&&t.createElement(ho,null,i),t.createElement(`div`,{ref:a,style:{...fo.fullWidth,...!r&&fo.hide},className:o}))}var _o=i(go);function vo(e){s(e,[])}var yo=vo;function bo(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=bo;function xo(){}function So(e,t,n,r){return Co(e,r)||wo(e,t,n,r)}function Co(e,t){return e.editor.getModel(To(e,t))}function wo(e,t,n,r){return e.editor.createModel(t,n,r?To(e,r):void 0)}function To(e,t){return e.Uri.parse(t)}function Eo({original:e,modified:r,language:i,originalLanguage:o,modifiedLanguage:l,originalModelPath:u,modifiedModelPath:d,keepCurrentOriginalModel:f=!1,keepCurrentModifiedModel:p=!1,theme:m=`light`,loading:h=`Loading...`,options:g={},height:_=`100%`,width:v=`100%`,className:y,wrapperProps:b={},beforeMount:x=xo,onMount:S=xo}){let[C,w]=c(!1),[T,E]=c(!0),D=n(null),O=n(null),k=n(null),A=n(S),j=n(x),M=n(!1);yo(()=>{let e=uo.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=So(O.current,e||``,o||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=So(O.current,r||``,l||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(r||``):r!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:r||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[r],C),$(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||i||`text`),O.current.editor.setModelLanguage(t,l||i||`text`)},[i,o,l],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=a(()=>{if(!O.current)return;j.current(O.current);let t=So(O.current,e||``,o||i||`text`,u||``),n=So(O.current,r||``,l||i||`text`,d||``);D.current?.setModel({original:t,modified:n})},[i,r,l,e,o,u,d]),P=a(()=>{!M.current&&k.current&&(D.current=O.current.editor.createDiffEditor(k.current,{automaticLayout:!0,...g}),N(),O.current?.editor.setTheme(m),w(!0),M.current=!0)},[g,m,N]);s(()=>{C&&A.current(D.current,O.current)},[C]),s(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return t.createElement(_o,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(Eo);function Do(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var Oo=Do,ko=new Map;function Ao({defaultValue:e,defaultLanguage:r,defaultPath:i,value:o,language:l,path:u,theme:d=`light`,line:f,loading:p=`Loading...`,options:m={},overrideServices:h={},saveViewState:g=!0,keepCurrentModel:_=!1,width:v=`100%`,height:y=`100%`,className:b,wrapperProps:x={},beforeMount:S=xo,onMount:C=xo,onChange:w,onValidate:T=xo}){let[E,D]=c(!1),[O,k]=c(!0),A=n(null),j=n(null),M=n(null),N=n(C),P=n(S),F=n(),I=n(o),L=Oo(u),R=n(!1),z=n(!1);yo(()=>{let e=uo.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=So(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&ko.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(ko.get(u)))},[u],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&l&&A.current?.editor.setModelLanguage(e,l)},[l],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let B=a(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=u||i,n=So(A.current,o||e||``,r||l||``,t||``);j.current=A.current?.editor.create(M.current,{model:n,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(ko.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,r,i,o,l,u,m,h,g,d,f]);s(()=>{E&&N.current(j.current,A.current)},[E]),s(()=>{!O&&!E&&B()},[O,E,B]),I.current=o,s(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),s(()=>{if(E){let e=A.current.editor.onDidChangeMarkers(e=>{let t=j.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=A.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function V(){F.current?.dispose(),_?g&&ko.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(_o,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var jo=i(Ao);u();function Mo(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 No={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Po(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...No}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function Fo({value:e,onChange:t,extraLibs:r=[],path:i=`file:///block.ts`,onDiagnostics:c,readOnly:l=!1,heightPx:u=420,dark:d=!0}){let f=n(null),p=a((e,t)=>{if(f.current=t,Po(t,r),c===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{c(t.editor.getModelMarkers({resource:n.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(i),i()},[r,c]);return s(()=>{let e=f.current;e!==null&&Po(e,r)},[r]),o(jo,{height:u,defaultLanguage:`typescript`,path:i,theme:d?`vs-dark`:`vs`,value:e,onChange:e=>t(e??``),onMount:p,options:{readOnly:l,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function Io(e){return e.some(e=>e.severity>=8)}var Lo=[{id:`blank`,name:`Blank script`,get description(){return Z.t(`helpers.buildExamples.blankDescription`)},entry:`main.ts`,files:{"main.ts":`import type { AddonContext } from '@camstack/types'
14
-
15
- /**
16
- * A core block. Runs in its own process, with the same \`ctx\` an addon gets.
17
- * Return a function to release whatever you took (timers, sockets, listeners).
18
- *
19
- * Declaring devices: import { reconcileBlockDevices, exposeBlockDevices } from
20
- * '@camstack/types' and hang them off the shared Blocks integration.
21
- */
22
- export default function block(ctx: AddonContext) {
23
- ctx.logger.info('hello from a core block')
24
-
25
- const timer = setInterval(() => {
26
- ctx.logger.info('tick')
27
- }, 60_000)
28
-
29
- return () => {
30
- clearInterval(timer)
31
- }
32
- }
33
- `}}];function Ro(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 zo=Lo.find(e=>e.id===`blank`)?.files[`main.ts`]??`import type { AddonContext } from '@camstack/types'
34
-
35
- export default function block(ctx: AddonContext) {
36
- ctx.logger.info('hello from a core block')
37
- return () => undefined
38
- }
39
- `;function Bo({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Z.t(`helpers.restartGate.saveFirstNoProcess`):n?Z.t(`helpers.restartGate.saving`):r?Z.t(`helpers.restartGate.restarting`):t?Z.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Z.t(`helpers.restartGate.disabled`)}u();var Vo=5e3;function Ho(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 Uo({blockId:t}){let{t:n}=Q(),i=z(t),a=_e({addonId:i,projection:`slim`},{refetchInterval:Vo}),s=r(()=>Ho(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(b,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(bt,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(q,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(bt,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:o(`code`,{})}})}):o(`ul`,{className:`space-y-3`,children:s.map(t=>o(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${t.id}`,children:e(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[o(Ot,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(Qe,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(q,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,o(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}u();function Wo(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 Go(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 Ko(e){switch(e){case`refresh-channel-catalog`:return Z.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Z.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Z.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Z.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Z.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Z.t(`build.scriptSettingsPanel.enableUnifi`)}}function qo(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Jo(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Yo(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=qo(e);n!==null&&(t[n]=Jo(e))}return t}function Xo(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Zo({blockId:t}){let{t:n}=Q(),i=D(),s=_t({blockId:t},{retry:!1}),l=Ye({blockId:t},{refetchInterval:1e4,retry:!1}),u=Ke({onSuccess:()=>{l.refetch()}}),d=rt(),f=tt(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,x]=c(!1),S=Xo(l.data)?l.data:null,C=r(()=>S===null?{}:Yo(S),[S]),w=p??C,T=a(e=>{m(e)},[]),E=p!==null,O=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),k=a(async(e,n)=>{if(Wo(e)){x(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:Go(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(Ko(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{x(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(b,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):S===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(bt,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(J,{size:`sm`,variant:`primary`,onClick:O,disabled:!E||u.isPending||y,children:[u.isPending&&o(b,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(wt,{schema:S,values:w,onChange:T,onAction:k}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var Qo=`hub`;function $o({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:m,onCancel:g}){let{t:y}=Q(),x=D(),S=T(),{resolvedMode:C}=it(),w=B({code:t?.code??zo,files:t?.files,entry:t?.entry}),[E,A]=c(t?.name??``),[j,M]=c(w.files),[N,P]=c(w.entry),[F,I]=c(w.entry),[L,R]=c(t?.placement??Qo),[V,H]=c(t?.integrationId??``),[U,ee]=c([]),[te,ne]=c(!1),[W,G]=c(`blank`),[re,ie]=c(null),[ae,oe]=c(``),se=j[F]??``,ce=e=>{M(t=>({...t,[F]:e}))},le=Object.keys(j).toSorted(),ue=Lo.length>1,de=r(()=>[...n?.libs??[],...Mo(j,F)],[n?.libs,j,F]),K=f({mutationFn:()=>x.trpcClient.coreBlocks.compile.mutate({files:j,entry:N})}),fe=r(()=>U.filter(e=>e.severity>=8),[U]),pe=Io(U),me=E.trim()===``,he=t===null?null:B(t),ge=t===null||he===null||JSON.stringify(j)!==JSON.stringify(he.files)||N!==he.entry||E.trim()!==t.name||L!==t.placement||(V.trim()===``?void 0:V.trim())!==t.integrationId,_e=()=>{K.reset(),m({name:E.trim(),files:j,entry:N,enabled:t?.enabled??!0,placement:L,...V.trim()===``?{}:{integrationId:V.trim()}})},ve=()=>{let e=Ro(Object.keys(j));M(t=>({...t,[e]:``})),I(e),ie(e),oe(e)},ye=e=>{ie(e),oe(e)},be=()=>{if(re===null)return;let e=re,t=ae.trim();if(ie(null),!(t===``||t===e)){if(j[t]!==void 0){I(t);return}M(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),N===e&&P(t),I(t)}},Se=async e=>{let t=Lo.find(t=>t.id===e);if(t===void 0)return;let n=Lo.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(j)===JSON.stringify(n.files)&&N===n.entry)&&!await S({title:y(`build.blockEditor.loadExample`,`Load example`),message:y(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:y(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(G(e),M({...t.files}),P(t.entry),I(t.entry),(E.trim()===``||W===`blank`)&&A(t.id===`blank`?``:t.name))},Ce=t===null?null:cr(t),we=Bo({existing:t,dirty:ge,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[Ce!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(q,{variant:lr(Ce.tone),children:Ce.label})}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:y(`build.blockEditor.name`,`Name`)}),o(X,{className:`mt-1`,value:E,onChange:e=>A(e.target.value),placeholder:y(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:y(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(X,{className:`mt-1`,value:V,onChange:e=>H(e.target.value),placeholder:y(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&ue&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:y(`build.blockEditor.startFrom`,`Start from`)}),o(k,{className:`mt-1 w-full`,value:W,onChange:e=>void Se(e.target.value),"data-testid":`script-example-select`,children:Lo.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(Ne,{selectedNodeId:L,onSelect:R,label:y(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),L!==Qo&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(_,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(bt,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[le.map(t=>re===t?o(X,{value:ae,onChange:e=>oe(e.target.value),onBlur:()=>be(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),be()),e.key===`Escape`&&(e.preventDefault(),ie(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":y(`build.blockEditor.renameFile`,`Rename file`)},t):e(J,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs ${t===F?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>I(t),onDoubleClick:()=>ye(t),title:y(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===N?` · ${y(`build.blockEditor.entry`)}`:``]},t)),o(J,{variant:`unstyled`,type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:ve,"data-testid":`script-file-add`,children:y(`build.blockEditor.file`,`+ file`)}),F!==N&&o(J,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>P(F),title:y(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:y(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:y(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(Fo,{value:se,onChange:ce,path:`file:///${F}`,extraLibs:de,onDiagnostics:ee,dark:C===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:y(`build.blockEditor.theNodeReturnedNoType`,`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`)}),fe.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:y(`build.blockEditor.errorsCannotSave`,{count:fe.length})}),fe.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:y(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),fe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:y(`build.blockEditor.moreErrors`,{count:fe.length-5})})]}),K.data!==void 0&&(K.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(v,{className:`h-3.5 w-3.5`}),` `,y(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[K.data.line!==void 0&&o(`span`,{className:`mr-1`,children:y(`build.blockEditor.errorLine`,{line:String(K.data.line)})}),K.data.error??y(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),K.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[y(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,es(K.error)]}),s!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),t!==null&&e(`div`,{className:`space-y-3`,children:[o(Zo,{blockId:t.id}),o(Uo,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:`outline`,onClick:()=>K.mutate(),disabled:K.isPending||a,title:y(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[K.isPending&&o(b,{className:`h-4 w-4 animate-spin`}),` `,y(`common.compile`)]}),e(J,{onClick:_e,disabled:a||pe||me,children:[a&&o(b,{className:`h-4 w-4 animate-spin`}),` `,y(`common.save`)]}),e(J,{variant:`outline`,onClick:()=>d?.(),disabled:we!==null||d===void 0,title:we??y(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(h,{className:`h-4 w-4 animate-spin`}):o(h,{className:`h-4 w-4`}),` `,y(`build.blockEditor.restart`,`Restart`)]}),e(J,{variant:`ghost`,onClick:()=>ne(!te),title:y(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,"aria-expanded":te,children:[o(O,{className:`h-4 w-4`}),` `,y(`common.logs`),` `,o(ot,{expanded:te})]}),o(J,{variant:`ghost`,onClick:g,disabled:a,children:y(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[y(`build.blockEditor.errorsCount`,{count:fe.length}),ge&&t!==null?` · ${y(`build.blockEditor.unsavedChanges`)}`:``]}),me&&o(q,{variant:`warning`,children:y(`build.blockEditor.nameRequired`,`Name required`)})]}),te&&e(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:t===null?y(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(p,{children:o(bt,{i18nKey:`build.blockEditor.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(xe,{addonId:z(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function es(e){return e instanceof Error?e.message:String(e)}u();var ts=[`coreBlocks`,`list`],ns=[`coreBlocks`,`getTypeDefs`],rs=5e3;function is(e){return e instanceof Error?e.message:String(e)}function as({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=y(),{t:p}=Q(),m=D(),{state:g,openNew:_,openEdit:v,close:b}=Se({editKey:`block`,newKey:`new`}),[x,S]=c(null),C=T(),[E,k]=c(null),A=l({queryKey:ts,refetchInterval:rs,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),j=g.mode!==`closed`,M=l({queryKey:ns,enabled:j,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),N=()=>{A.refetch()},P=n(null),F=A.data;s(()=>{t===void 0||P.current===t||F?.find(e=>e.id===t&&R(e)===`code`)!==void 0&&(P.current=t,v(t),i?.(t))},[t,F,v,i]),s(()=>{a&&(S(null),_(),i?.(null),u?.())},[a,u,i,_]);let I=f({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{S(e.block),v(e.block.id),i?.(e.block.id),N()}}),L=f({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{S(e.block),v(e.block.id),i?.(e.block.id),N()}}),B=f({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:N}),V=f({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:N}),H=f({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:N}),U=dr((A.data??[]).filter(e=>R(e)===`code`)),ee=A.data!==void 0&&U.length===0,te=I.isPending||L.isPending,ne=I.error===null?L.error===null?null:is(L.error):is(I.error),W=g.mode===`edit`?U.find(e=>e.id===g.id)??(x!==null&&x.id===g.id?x:null):null,G=g.mode===`new`||W===null?null:ur(U,W),re=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=cr(t),r=et(t.updatedAt,d);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(q,{variant:lr(n.tone),children:n.label}),o(q,{variant:`info`,children:t.placement}),r!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`common.edited`,{when:r})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:n.detail}),E===t.id&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(bt,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(xe,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:t=>{let n=V.isPending||B.isPending,r=H.isPending&&H.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),S(t),v(t.id),i?.(t.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),H.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(h,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),k(E===t.id?null:t.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:o(O,{className:`h-4 w-4`})}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),V.mutate({blockId:t.id,enabled:!t.enabled})},disabled:n,title:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`),children:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`)}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),C({title:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`),message:p(`build.scriptsTab.deleteMessage`,`{{name}} and its source will be deleted. This cannot be undone.`,{name:t.name}),confirmLabel:p(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&B.mutate(t.id)})},title:p(`common.delete`,`Delete`),children:o(w,{className:`h-4 w-4`})})]})}}],[C,E,i,v,B,H.isPending,H.variables,V,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:A.data===void 0?``:fr(U)}),A.error!=null&&o(Y,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:is(A.error),onRetry:N}),o(Ee,{columns:re,rows:U,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ve,emptyMessage:ee?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)}}),o(at,{open:j,onClose:()=>{I.reset(),L.reset(),H.reset(),S(null),b(),i?.(null)},title:G===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:G.name}),icon:me,width:`xl`,testId:`script-editor-panel`,children:o($o,{existing:G,typeDefs:M.data,typeDefsLoading:M.isLoading,saving:te,saveError:ne,restarting:H.isPending,restartError:H.error===null?null:is(H.error),onRestart:G===null?void 0:()=>H.mutate(G.id),onSave:e=>{let t=G;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),H.reset(),S(null),b(),i?.(null)}})}),B.error!=null&&o(Y,{message:is(B.error)}),V.error!=null&&o(Y,{message:is(V.error)}),H.error!=null&&o(Y,{message:is(H.error)})]})}var os=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`];function ss(e){return e!==null&&os.some(t=>t===e)}var cs=[`coreBlocks`,`list`,`build-counts`],ls=[`schedulers`,`list`,`build-counts`],us=[`actions`,`list`,`build-counts`],ds=[`block`,`action`,`scheduler`,`create`,`new`];function fs(e){return e.filter(e=>R(e)===`code`).length}function ps(e){return e.filter(e=>gn(e.code)).length}function ms(e,t){return t===null?e:`${e} (${String(t)})`}function hs(){let{t}=Q(),n=D(),[r,i]=Ct(),a=r.get(`tab`),s=ss(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:cs,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:fs(u),f=u===void 0?null:ps(u),p=l({queryKey:us,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=l({queryKey:ls,refetchInterval:1e4,queryFn:async()=>n.trpcClient.schedulers.list.query({})}),_=h.data===void 0?null:h.data.length,v=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),y=v.data?.state===`loaded`?v.data.views.length:null,b=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},S=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},C=()=>{i(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},w=e=>{i(()=>{let t=new URLSearchParams(window.location.search);return t.set(`tab`,`custom-device`),t.delete(`block`),t.delete(`create`),t.set(`new`,e),t},{replace:!0})},T=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},E=s===`automations`?t(`build.newAutomation`,`New automation`):s===`actions`?t(`build.newAction`,`New action`):s===`schedulers`?t(`build.newScheduler`,`New scheduler`):t(`build.newScript`,`New script`),O=xt(`/build`,{t,isAdmin:!0})??{icon:x,title:t(`nav.build`,`Build-your-self`)};return o(kt,{icon:O.icon,title:O.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${O.title} sections`,fill:!0,actions:s===`custom-device`?e(J,{type:`button`,onClick:()=>w(`helper`),"data-testid":`build-new-composed`,children:[o(g,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(J,{type:`button`,onClick:C,"data-testid":`build-new`,children:[o(g,{className:`h-4 w-4`}),` `,E]}),sections:[{id:`automations`,label:ms(t(`build.tabAutomations`,`Automations`),f),ownedParams:ds,content:o(Tr,{onOpenScripts:b,createRequested:s===`automations`&&c,onCreateConsumed:T})},{id:`actions`,label:ms(t(`build.tabActions`,`Actions`),m),ownedParams:ds,content:o(Wn,{createRequested:s===`actions`&&c,onCreateConsumed:T})},{id:`schedulers`,label:ms(t(`build.tabSchedulers`,`Schedulers`),_),ownedParams:ds,content:o(ci,{createRequested:s===`schedulers`&&c,onCreateConsumed:T})},{id:`scripts`,label:ms(t(`build.tabCode`,`Code`),d),ownedParams:ds,content:o(as,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:S,createRequested:s===`scripts`&&c,onCreateConsumed:T})},{id:`custom-device`,label:ms(t(`build.tabCustomDevice`,`Custom Device`),y),ownedParams:ds,content:o(Ji,{createRequested:s===`custom-device`&&c,onCreateConsumed:T})}]})}export{hs as BuildPage};
@@ -1 +0,0 @@
1
- import{C as e,K as t,R as n,S as r,Y as i,et as a,o,x as s}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Bi as c,zi as l}from"./player-overlays-D2iM_dnq.js";import{Ka as u,qa as d}from"./client-BT1qTuWk.js";import{y as f}from"./video-DFWp1_fo.js";import{Gr as p,Jr as m,Kr as h,Oi as g,Wr as _,Xr as v,Yr as y,io as b,mf as x,no as S,ro as C,to as w,yr as T}from"./src-Djs5D3BM.js";import{t as E}from"./i18n-DO003gOw.js";import{t as D}from"./useTranslation-BJr-n0es.js";import{Q as ee,Rr as te,zr as O}from"./index-BtIAcMod.js";import{t as ne}from"./AdminPage-CPPoleZA.js";import{t as k}from"./InstanceSwitchCell-xSu6VGOy.js";a();function A(e,t){return e.flatMap(e=>e.instances.map(n=>({addonId:e.addonId,id:n.id,name:n.name,enabled:n.enabled!==!1,providerName:t.get(e.addonId)??e.addonId})))}function re(e,t,n){let r=new Set,i=(e,t)=>`${e}\u0000${t}`,a=e.map(e=>{let a=e.instanceId===void 0?null:t.find(t=>t.addonId===e.providerAddonId&&t.id===e.instanceId)??null;return a!==null&&r.add(i(a.addonId,a.id)),{key:a===null?e.id:`instance:${a.addonId}:${a.id}`,name:e.name,providerName:a?.providerName??n(e),calendar:e,instance:a}});for(let e of t)r.has(i(e.addonId,e.id))||a.push({key:`instance:${e.addonId}:${e.id}`,name:e.name,providerName:e.providerName,calendar:null,instance:e});return a}var j=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function M(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function N(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function P(e){let t=e.getDay();return M(N(e,t===0?-6:1-t))}function F(e,t){if(t===`day`){let t=M(e);return{startMs:t.getTime(),endMs:N(t,1).getTime()}}if(t===`week`){let t=P(e);return{startMs:t.getTime(),endMs:N(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=P(n),a=N(P(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function I(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=P(e),n=N(t,6),r={month:`short`,day:`numeric`};return`${t.toLocaleDateString(void 0,r)} – ${n.toLocaleDateString(void 0,{...r,year:`numeric`})}`}return e.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}function L(e,t,n){return t===`day`?N(e,n):t===`week`?N(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function R(e,t){if(t===void 0)return e;let n=t.calendars[e.id];return n===void 0?e:{...e,visible:n.visible??e.visible,color:n.color??e.defaultColor}}function z(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function B(e){if(e.allDay===!0)return E.t(`systemPage.calendars.allDay`);let t=new Date(e.startMs),n=new Date(e.endMs),r={hour:`2-digit`,minute:`2-digit`};return`${t.toLocaleTimeString([],r)} – ${n.toLocaleTimeString([],r)}`}function V(e){let t=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=M(n),t=N(M(r),-1);return G(e,t)?E.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):E.t(`systemPage.calendars.rangeAllDay`,{from:n.toLocaleDateString(void 0,i),to:t.toLocaleDateString(void 0,i)})}let a={hour:`2-digit`,minute:`2-digit`};return G(n,r)?`${n.toLocaleDateString(void 0,i)} · ${n.toLocaleTimeString([],a)} – ${r.toLocaleTimeString([],a)}`:`${n.toLocaleString(void 0,{...i,...a})} – ${r.toLocaleString(void 0,{...i,...a})}`}function H({label:t,children:n}){return e(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[r(`dt`,{className:`text-foreground-subtle`,children:t}),r(`dd`,{className:`min-w-0 break-words text-foreground`,children:n})]})}function U({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=D();return r(_,{open:!0,onOpenChange:e=>!e&&a(),children:e(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(y,{children:e(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[r(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:i},"aria-hidden":!0}),r(v,{className:`min-w-0 break-words`,children:t.title})]})}),r(p,{children:e(`dl`,{className:`space-y-3`,children:[r(H,{label:o(`systemPage.calendars.when`,`When`),children:V(t)}),r(H,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(H,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(H,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(m,{children:r(g,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`common.close`,`Close`)})})]})})}function W(e,t){return e.filter(e=>d(e,t))}function G(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function ie({mode:e,onChange:t}){let{t:n}=D(),i=[{id:`month`,label:n(`systemPage.calendars.month`,`Month`)},{id:`week`,label:n(`systemPage.calendars.week`,`Week`)},{id:`day`,label:n(`systemPage.calendars.day`,`Day`)}];return r(`div`,{className:`inline-flex rounded-lg border border-border bg-surface p-0.5`,role:`group`,"aria-label":n(`systemPage.calendars.calendarView`,`Calendar view`),children:i.map(n=>r(g,{variant:`unstyled`,type:`button`,className:e===n.id?`rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground`:`rounded-md px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground`,"aria-pressed":e===n.id,onClick:()=>t(n.id),"data-testid":`calendars-view-${n.id}`,children:n.label},n.id))})}function K({rows:t,onToggleVisible:n,onColorChange:i,onSwitched:a,busy:o}){let{t:c}=D();return e(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[r(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:c(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>{let l=t.calendar,u=t.instance!==null&&!t.instance.enabled;return e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface ${u?`opacity-60`:``}`,"data-testid":`calendars-row-${t.key}`,children:[l!==null&&!u?e(s,{children:[r(T,{className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:l.visible,disabled:o,onChange:e=>n(l.id,e.target.checked),"aria-label":c(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${l.id}`}),r(x,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:l.color,disabled:o,onChange:e=>i(l.id,e.target.value.toUpperCase()),"aria-label":c(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${l.id}`})]}):null,e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${l?.visible===!0&&!u?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[t.providerName,u?` · ${c(`systemPage.calendars.switchedOff`)}`:``,l!==null&&!l.enabled?` · ${c(`systemPage.calendars.unavailableAtSource`)}`:``]})]}),t.instance===null?null:r(k,{row:t.instance,pinning:0,onChanged:a})]},t.key)})})]})}function q({ev:t,color:n,compact:i,onSelect:a}){return r(g,{variant:`unstyled`,type:`button`,className:i?`block w-full truncate rounded px-1 py-0.5 text-left text-[10px] leading-tight text-white hover:brightness-110`:`block w-full rounded-md px-2 py-1.5 text-left text-xs text-white hover:brightness-110`,style:{backgroundColor:n},title:t.title,onClick:()=>a(t),"data-testid":`calendars-event-${t.id}`,children:i?t.title:e(s,{children:[r(`div`,{className:`font-medium`,children:t.title}),r(`div`,{className:`opacity-90`,children:B(t)})]})})}function ae({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=D(),{startMs:c,endMs:l}=F(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=N(e,1))u.push(e);let d=t.getMonth();return e(`div`,{"data-testid":`calendars-month`,children:[r(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:j.map(e=>r(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),r(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(t=>{let c=M(t).getTime(),l=W(n,c),u=t.getMonth()!==d,f=G(t,a);return e(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[r(`div`,{className:f?`mb-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] font-semibold text-primary-foreground`:`mb-1 text-[11px] font-medium text-foreground-subtle`,children:t.getDate()}),e(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>r(q,{ev:e,color:i.get(e.calendarId)??`#64748B`,compact:!0,onSelect:o},e.id)),l.length>3?r(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function oe({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=P(t);return r(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-7 sm:gap-px sm:overflow-hidden sm:rounded-lg sm:border sm:border-border sm:bg-border`,"data-testid":`calendars-week`,children:Array.from({length:7},(e,t)=>N(s,t)).map(t=>{let s=M(t).getTime(),c=W(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:G(t,a)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:t.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),r(`div`,{className:`space-y-1`,children:c.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>r(q,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function se({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=D(),c=W(n,M(t).getTime());return c.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):r(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(t=>r(`li`,{children:e(g,{variant:`unstyled`,type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>o(t),"data-testid":`calendars-event-${t.id}`,children:[r(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:i.get(t.calendarId)??`#64748B`}}),e(`div`,{className:`min-w-0`,children:[r(`div`,{className:`font-medium text-sm text-foreground`,children:t.title}),e(`div`,{className:`text-xs text-foreground-subtle`,children:[B(t),` · `,a.get(t.calendarId)??t.calendarId]}),t.location!==void 0&&t.location.length>0?r(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.location}):null]})]})},t.id))})}function J(){let{t:a}=D(),s=S(),u=w({}),d=b(),p=o(),m=ee(`calendar-source`),[h,_]=i(`month`),[v,y]=i(()=>M(new Date)),[x,T]=i(null),E=t(()=>M(new Date),[]),k=s.isSuccess,j=u.isSuccess&&u.data!==void 0?u.data:void 0,N=t(()=>!k||s.data===void 0?[]:s.data.map(e=>R(e,j)),[k,s.data,j]),P=t(()=>N.filter(e=>e.visible),[N]),B=t(()=>P.map(e=>e.id),[P]),V=t(()=>F(v,h),[v,h]),H=C({startMs:V.startMs,endMs:V.endMs,calendarIds:[...B]},{enabled:k&&B.length>0}),W=H.data??[],G=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.color);return e},[N]),q=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.name);return e},[N]),J=t(()=>re(N,A(m.holders,m.displayNames),z),[N,m.holders,m.displayNames]),Y=n(()=>void p.invalidateQueries({queryKey:[[`calendars`]]}),[p]),X=n((e,t)=>{d.mutateAsync({calendarId:e,visible:t}).then(()=>u.refetch())},[u,d]),Z=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&d.mutateAsync({calendarId:e,color:t}).then(()=>u.refetch())},[u,d]),ce=n(()=>y(M(new Date)),[]),le=n(()=>y(e=>L(e,h,-1)),[h]),ue=n(()=>y(e=>L(e,h,1)),[h]),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 $=s.isPending||m.state===`pending`?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):s.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,s.error.message]}):m.state===`error`&&J.length===0?e(`p`,{className:`text-sm text-danger`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,m.error]}):J.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(te,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(O,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):B.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(K,{rows:J,onToggleVisible:X,onColorChange:Z,onSwitched:Y,busy:d.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:N.length===0?a(`systemPage.calendars.allSwitchedOff`):a(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(K,{rows:J,onToggleVisible:X,onColorChange:Z,onSwitched:Y,busy:d.isPending}),e(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(ie,{mode:h,onChange:_}),e(`div`,{className:`flex items-center gap-1`,children:[r(g,{variant:`unstyled`,type:`button`,className:Q,onClick:le,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(c,{className:`h-4 w-4`})}),r(g,{variant:`unstyled`,type:`button`,className:`inline-flex items-center rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5`,onClick:ce,"data-testid":`calendars-today`,children:a(`systemPage.calendars.today`,`Today`)}),r(g,{variant:`unstyled`,type:`button`,className:Q,onClick:ue,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(l,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:I(v,h)})]}),H.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):H.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,H.error.message]}):h===`month`?r(ae,{anchor:v,events:W,colorById:G,today:E,onSelectEvent:T}):h===`week`?r(oe,{anchor:v,events:W,colorById:G,today:E,onSelectEvent:T}):r(se,{anchor:v,events:W,colorById:G,calName:q,onSelectEvent:T})]})]}),e(ne,{icon:f,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[m.state===`error`&&J.length>0?e(`p`,{className:`mb-3 text-sm text-warning`,role:`status`,"data-testid":`calendars-switches-unavailable`,children:[a(`systemPage.calendars.switchesUnavailable`,`The calendar switches could not be loaded, so they are hidden. Calendars switched off are not listed until they load.`),` `,m.error]}):null,$,x===null?null:r(U,{ev:x,calendarName:q.get(x.calendarId)??x.calendarId,color:G.get(x.calendarId)??`#64748B`,onClose:()=>T(null)})]})}export{J as CalendarsPage,J as default};