@camstack/addon-admin-ui 1.2.643 → 1.2.644

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 (109) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/dist/assets/Addons-ShOLWXd0.js +5 -0
  3. package/dist/assets/{AdminPage-BZvFoK-C.js → AdminPage-DBIlGQcg.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-C6F2XhY_.js → AdminSectionedPage-BZZVpePX.js} +1 -1
  5. package/dist/assets/AiProfiles-0WnsACbl.js +3 -0
  6. package/dist/assets/{BootstrapSettingsForm-ChlI6gkO.js → BootstrapSettingsForm-B4JdtXuz.js} +1 -1
  7. package/dist/assets/Build-9NCzkPDG.js +39 -0
  8. package/dist/assets/{Calendars-DJZwEA_T.js → Calendars-C7qfbr7A.js} +1 -1
  9. package/dist/assets/{CameraGrids-Mx13QcCo.js → CameraGrids-mWpZKvQ5.js} +1 -1
  10. package/dist/assets/{Cluster-BoaxEKbX.js → Cluster-DZcoj2rP.js} +1 -1
  11. package/dist/assets/CompositionBlockEditor-C76eQ7Js.js +2 -0
  12. package/dist/assets/{CompositionEditorPage-BzcNLyXz.js → CompositionEditorPage-D2-woXyS.js} +1 -1
  13. package/dist/assets/Data-DKNCfvhH.js +2 -0
  14. package/dist/assets/DeviceDetail-DHep5JCp.js +2 -0
  15. package/dist/assets/{Devices-CFiT4SEp.js → Devices-CWvTKpnT.js} +1 -1
  16. package/dist/assets/EmbedDevicePage-CvbzEbvN.js +1 -0
  17. package/dist/assets/{EmbedPlayerPage-Dw6ZuDJq.js → EmbedPlayerPage-MuC48n-_.js} +1 -1
  18. package/dist/assets/{History-q6klNCf4.js → History-EJImyfJF.js} +1 -1
  19. package/dist/assets/Identity-Bp-Zr3O5.js +1 -0
  20. package/dist/assets/InstancesTable-CvfpkEKd.js +1 -0
  21. package/dist/assets/{IntegrationDetail-CdDEVjrn.js → IntegrationDetail-D8rUMymg.js} +1 -1
  22. package/dist/assets/{IntegrationWizard-CJzJK4X4.js → IntegrationWizard-CUcCjYQD.js} +1 -1
  23. package/dist/assets/{Integrations-CRISOUeT.js → Integrations-2NtF5fL7.js} +2 -2
  24. package/dist/assets/Integrations-DsjUFK8h.js +1 -0
  25. package/dist/assets/Library-Dxr2Pajp.js +1 -0
  26. package/dist/assets/Locations-rnb6AjY3.js +3 -0
  27. package/dist/assets/{Logs-C_hIQLbk.js → Logs-CoJh-c0a.js} +1 -1
  28. package/dist/assets/{MaskShapeCanvas-dpTYLn-I.js → MaskShapeCanvas-j1uA0PkL.js} +1 -1
  29. package/dist/assets/{MotionZonesSettings-BeZ8c48s.js → MotionZonesSettings-0iA5mYRg.js} +1 -1
  30. package/dist/assets/{MyAccess-CkleYUFw.js → MyAccess-DHgBU4Se.js} +1 -1
  31. package/dist/assets/Network-DzqpooQx.js +1 -0
  32. package/dist/assets/{NodeAddonsSettingsPanel-CzinR980.js → NodeAddonsSettingsPanel-CieUBerm.js} +1 -1
  33. package/dist/assets/Notifications-DIrApxQt.js +1 -0
  34. package/dist/assets/Pipeline-CXIrhlea.js +1 -0
  35. package/dist/assets/{PrivacyMaskSettings-ufaM81lx.js → PrivacyMaskSettings-BLOdiPL9.js} +1 -1
  36. package/dist/assets/{Recordings-qUFS33dH.js → Recordings-D_GHaGDS.js} +1 -1
  37. package/dist/assets/{RemoteGrid-mhCQPrw4.js → RemoteGrid-DdvsdB_y.js} +1 -1
  38. package/dist/assets/{ScanSubnetEditor-ByUeuUPH.js → ScanSubnetEditor-BCfqLZIA.js} +1 -1
  39. package/dist/assets/{SceneMonitorEditor-_WrCw9Qm.js → SceneMonitorEditor-Cy11U5pJ.js} +1 -1
  40. package/dist/assets/{SessionsList-WLJF11Gk.js → SessionsList-CFVXs0eU.js} +2 -2
  41. package/dist/assets/{Showroom-NE9QetSE.js → Showroom-CDNZCmQ9.js} +1 -1
  42. package/dist/assets/{StorageLocationsTable-DY-jybRD.js → StorageLocationsTable-C2jWCBaP.js} +1 -1
  43. package/dist/assets/{System-Dhsni5ue.js → System-CKbbRmxa.js} +1 -1
  44. package/dist/assets/{Templates-BSzdR4Qf.js → Templates-BQW0A24V.js} +1 -1
  45. package/dist/assets/{Terminal-7LrKBjd7.js → Terminal-CflJDBLw.js} +3 -3
  46. package/dist/assets/{TrainingProviders-CSWf7FWS.js → TrainingProviders--io-U4Mx.js} +1 -1
  47. package/dist/assets/{Viewer-g8Ina8Au.js → Viewer-z_gjByXA.js} +1 -1
  48. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DP55Xu7L.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CMJDSqwo.js} +1 -1
  49. package/dist/assets/{action-draft-B8uc37EO.js → action-draft-Dg61GkLS.js} +1 -1
  50. package/dist/assets/{ai-page.helpers-Dib89wmm.js → ai-page.helpers-QIeUykiQ.js} +1 -1
  51. package/dist/assets/{assignment-candidates-B6Lh-6_J.js → assignment-candidates-CwKJ2Z54.js} +1 -1
  52. package/dist/assets/{authed-media-C3W-vMO8.js → authed-media-BkzUgfxS.js} +1 -1
  53. package/dist/assets/{board-model-D3Kg5nIR.js → board-model-K39WWIgs.js} +1 -1
  54. package/dist/assets/client-B60QT14E.js +951 -0
  55. package/dist/assets/create-composition-B7qf5-qP.js +2 -0
  56. package/dist/assets/{device-detail-C-OoPQkZ.js → device-detail-CJ8-lleI.js} +1 -1
  57. package/dist/assets/{device-integration-icon-BdKyz1yq.js → device-integration-icon-TWc3Gi9v.js} +1 -1
  58. package/dist/assets/device-picker-model-CsHVNi49.js +1 -0
  59. package/dist/assets/{dist-DZjvZVe0.js → dist-B8qwp9-f.js} +1 -1
  60. package/dist/assets/dist-DXms20e9.js +951 -0
  61. package/dist/assets/{format-7WsDyBWf.js → format-hVW7RBVv.js} +1 -1
  62. package/dist/assets/{hostInit-CgEEuJPE.js → hostInit-CWx4j9gp.js} +1 -1
  63. package/dist/assets/i18n-CvWKDmFM.js +1 -0
  64. package/dist/assets/icons-Di72eW9A.js +1 -0
  65. package/dist/assets/index-CxPpnulu.js +4 -0
  66. package/dist/assets/{linked-devices-model-CyoKmlf1.js → linked-devices-model-h00bTRRT.js} +1 -1
  67. package/dist/assets/{mf-entry-bootstrap-0-571f562d.js → mf-entry-bootstrap-0-58e92d28.js} +2 -2
  68. package/dist/assets/mount-CsHVNi49.js +1 -0
  69. package/dist/assets/{notification-rule-status-CnuKK1z9.js → notification-rule-status-B-P-wl_0.js} +1 -1
  70. package/dist/assets/{player-overlays-BHFWIcWp.js → player-overlays-D-63t-DL.js} +1 -1
  71. package/dist/assets/remoteEntry-Bz4Zdkwj.js +1 -0
  72. package/dist/assets/src-g2TJby3U.js +230 -0
  73. package/dist/assets/{step-inspector-model-BN-6Ysky.js → step-inspector-model-De5uJK-p.js} +1 -1
  74. package/dist/assets/{use-scenes-feed-Cr8kNEzV.js → use-scenes-feed-CpY0pBjC.js} +1 -1
  75. package/dist/assets/{use-stationary-objects-Befc4ui9.js → use-stationary-objects-BACQuMo9.js} +1 -1
  76. package/dist/assets/{useAdminDeviceRemoval-CSXgA4m4.js → useAdminDeviceRemoval-8_UQkuQg.js} +1 -1
  77. package/dist/assets/useEventInvalidation-CsHVNi49.js +1 -0
  78. package/dist/assets/{useNodeUrlSelection-DlX-xEsy.js → useNodeUrlSelection-gHQAfZml.js} +1 -1
  79. package/dist/assets/{useTemplateSave-B5WJqsrS.js → useTemplateSave-DxkUWI5Q.js} +1 -1
  80. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CqjtgsPE.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-hv9stH43.js} +2 -2
  81. package/dist/index.html +7 -7
  82. package/dist/server/addon.js +113 -4
  83. package/package.json +2 -2
  84. package/dist/assets/Addons-CmKKSYT6.js +0 -5
  85. package/dist/assets/AiProfiles-BRZy6Fa4.js +0 -3
  86. package/dist/assets/Build-BW2OslEd.js +0 -39
  87. package/dist/assets/CompositionBlockEditor-BYf4xPq-.js +0 -2
  88. package/dist/assets/Data-C2hKzrIe.js +0 -2
  89. package/dist/assets/DeviceDetail-DHrVifn8.js +0 -2
  90. package/dist/assets/EmbedDevicePage-r-cr6Bk-.js +0 -1
  91. package/dist/assets/Identity-B2BZy6Xv.js +0 -1
  92. package/dist/assets/InstancesTable-6rM7NsAl.js +0 -1
  93. package/dist/assets/Integrations-D9ZIdQ-k.js +0 -1
  94. package/dist/assets/Library-BOLcGUpc.js +0 -1
  95. package/dist/assets/Locations-BamYML3K.js +0 -3
  96. package/dist/assets/Network-8M-uJ8XE.js +0 -1
  97. package/dist/assets/Notifications-DvuuxOT6.js +0 -1
  98. package/dist/assets/Pipeline-Dpe6Ot41.js +0 -1
  99. package/dist/assets/client-BsGn43se.js +0 -921
  100. package/dist/assets/create-composition-BmMT1YBQ.js +0 -2
  101. package/dist/assets/device-picker-model-ChgpoWnb.js +0 -1
  102. package/dist/assets/dist-Zu7rz3zb.js +0 -921
  103. package/dist/assets/i18n-CEvnkGPR.js +0 -1
  104. package/dist/assets/icons-pVM3dlwn.js +0 -1
  105. package/dist/assets/index-BLPWUlRi.js +0 -4
  106. package/dist/assets/mount-ChgpoWnb.js +0 -1
  107. package/dist/assets/remoteEntry-x4q7yukG.js +0 -1
  108. package/dist/assets/src-5RckhTPX.js +0 -230
  109. package/dist/assets/useEventInvalidation-ChgpoWnb.js +0 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.644] - 2026-11-11
11
+
12
+ ### Added
13
+
14
+ - Automation editor: a 'Time is' condition with its window (clock time or sun event with an offset) and weekdays; a sun-based window is refused at save when the site has no location.
15
+ - Automation editor: the "Started by" condition picks among the automation's own trigger rows, in the rules and in a step's condition
16
+ - Automation editor: a step argument can insert the device, the old value and the new value of a "device becomes" trigger
17
+
18
+ ### Changed
19
+
20
+ - The shared device card follows the signed-in user's real device permission instead of assuming admin; inside the viewer it drops its duplicate name and is centred at a readable width on desktop
21
+ - The shared device card asks the hub whether the signed-in user may command THIS device (instead of assuming admin) and disables its controls with the reason when not; inside the viewer it drops its duplicate name and is centred at a readable width on desktop
22
+ - The "Started by" condition is offered only inside an automation, not in a standalone action list or a scheduler
23
+
10
24
  ## [1.2.643] - 2026-11-11
11
25
 
12
26
  ### Changed
@@ -92,7 +106,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
92
106
  - The mosaic caption and the timelapse preview caption stay plain text with their variable chips: no device-value picker where the hub fills variables only
93
107
  - Automation editor: rows and blocks in WHEN and IF move up and down, nested blocks collapse to a one-line summary, the Ungroup button is labelled, and the per-block warnings inside the tree are gone: a WHEN that cannot run is still explained beside the disabled Save, and a step's IF that can never be true now shows one non-blocking note under its tree.
94
108
 
95
-
96
109
  ## [1.2.632] - 2026-11-10
97
110
 
98
111
  ### Changed
@@ -0,0 +1,5 @@
1
+ import{B as e,C as t,J as n,K as r,R as i,S as a,V as o,Y as s,et as c,o as l,x 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{An as d,Bi as f,Bt as p,Dr as m,Jn as h,Kt as g,Li as _,Mi as v,Mn as y,Nn as b,Q as x,St as S,Un as C,Yt as ee,ci as w,ct as te,ot as T,sr as ne,ut as re,vn as E,wi as D}from"./player-overlays-D-63t-DL.js";import{nc as O}from"./client-B60QT14E.js";import{t as ie}from"./chevron-down-CBb-F8DT.js";import{a as k,p as A}from"./video-BV-3O_ZC.js";import{Br as ae,Ca as oe,Cn as se,Gr as ce,Hr as le,Kc as j,Kr as ue,Oi as de,Pf as M,Pi as N,Ta as fe,Vr as pe,Wr as me,aa as he,af as ge,ba as P,ca as _e,cr as F,ec as ve,fa as I,fr as ye,ga as L,ha as R,ht as be,ia as z,jf as B,la as xe,lr as Se,ma as Ce,oa as we,pa as V,ra as H,sa as U,sr as W,st as G,ta as Te,ua as Ee,ur as De,va as K,wa as Oe,wn as ke,xa as Ae,ya as je}from"./src-g2TJby3U.js";import{t as q}from"./useTranslation-BJr-n0es.js";import"./mount-CsHVNi49.js";import{Kr as Me,Qr as Ne,Xr as Pe}from"./index-CxPpnulu.js";import{t as Fe}from"./AdminPage-DBIlGQcg.js";import{i as Ie,r as Le,t as Re}from"./addon-kind-filter-CEGKkC1O.js";import{n as J,t as ze}from"./framework-packages-B0ugw-Ay.js";import{t as Y}from"./NodeAddonsSettingsPanel-CieUBerm.js";import{n as X,r as Be,t as Ve}from"./useNodeUrlSelection-gHQAfZml.js";function He(e){if(e===void 0)return null;switch(e.state){case`failed`:case`refused`:case`missing`:case`crashed`:return{kind:e.state,...e.reason===void 0?{}:{reason:e.reason}};default:return null}}c();var Ue={queued:{icon:D,bg:`bg-muted text-foreground-subtle`,labelKey:`addons.addonRowBadge.queued`},updating:{icon:m,bg:`bg-primary/10 text-primary`,labelKey:`addons.addonRowBadge.updating`,spin:!0},"done-pending-restart":{icon:C,bg:`bg-amber-500/10 text-amber-700`,labelKey:`addons.addonRowBadge.pendingRestart`},done:{icon:f,bg:`bg-success/10 text-success`,labelKey:`addons.addonRowBadge.done`},failed:{icon:k,bg:`bg-danger/10 text-danger`,labelKey:`addons.addonRowBadge.failed`}};function Z({item:e}){let{t:n}=q(),r=Ue[e.status],i=r.icon;return t(`span`,{className:`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded ${r.bg}`,title:e.error,children:[a(i,{className:`w-2.5 h-2.5 ${r.spin?`animate-spin`:``}`}),n(r.labelKey)]})}var Q=new Set([`completed`,`failed`,`partially-failed`,`cancelled`]),We=new Set([`done`,`failed`,`skipped`]);function Ge(e){return!We.has(e.phase)&&!Q.has(e.jobState)}function Ke(e,t){let n=new Map,r=[...e].sort((e,t)=>e.createdAtMs-t.createdAtMs);for(let e of r){let r=Q.has(e.state);for(let i of e.tasks)r&&i.finishedAtMs!==null&&t-i.finishedAtMs>6e4||n.set(i.packageName,{jobId:e.jobId,packageName:i.packageName,phase:i.phase,fromVersion:i.fromVersion,toVersion:i.toVersion,error:i.error,jobState:e.state,finishedAtMs:i.finishedAtMs})}return n}function qe(){let{data:e}=V({activeOnly:!0},{refetchOnWindowFocus:!1,refetchInterval:e=>(e.state.data?.length??0)>0?3e3:!1}),{map:t}=M(O.AddonsJobProgress,e=>e.job.jobId);return r(()=>{let n=new Map;for(let t of e??[])n.set(t.jobId,t);for(let[e,r]of t)n.set(e,r.job);return Ke([...n.values()],Date.now())},[e,t])}var Je={queued:{icon:D,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.queued`},fetching:{icon:m,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.fetching`,spin:!0},staged:{icon:m,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.staged`,spin:!0},validating:{icon:m,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.validating`,spin:!0},applying:{icon:m,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.applying`,spin:!0},restarting:{icon:m,cls:`bg-amber-500/10 text-amber-600 dark:text-amber-400`,labelKey:`addons.jobProgress.restarting`,spin:!0},applied:{icon:m,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.finalizing`,spin:!0},done:{icon:f,cls:`bg-success/10 text-success`,labelKey:`addons.jobProgress.updated`},failed:{icon:k,cls:`bg-danger/10 text-danger`,labelKey:`addons.jobProgress.failed`},skipped:{icon:E,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.skipped`}};function Ye({progress:e}){let{t:n}=q(),r=Je[e.phase],i=r.icon,o=e.error??`${e.packageName}: ${e.fromVersion??`?`} → ${e.toVersion}`;return t(`span`,{"data-testid":`addon-job-progress`,className:`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded shrink-0 ${r.cls}`,title:o,children:[a(i,{className:`w-2.5 h-2.5 ${r.spin?`animate-spin`:``}`}),n(r.labelKey),t(`span`,{className:`font-mono`,children:[`→ `,e.toVersion]})]})}function Xe(e,t){return e.filter(e=>e.packageName===t).slice().sort((e,t)=>e.isHub===t.isHub?e.nodeName.localeCompare(t.nodeName):e.isHub?-1:1)}function Ze(e){let t=e.version===null?``:` ${e.version}`,n=e.isOnline?``:` (offline: removed when it reconnects)`;return`- ${e.nodeName}${t}${n}`}function Qe(e,t,n){let r=[`${e} will be uninstalled from ${t.length} node(s). Its runners stop, its capabilities are deregistered and its code is deleted:`,...t.map(Ze)];return n.length>0&&r.push(`Could not ask: ${n.join(`, `)} — not included.`),r.push(`This cannot be undone.`),r.join(`
2
+ `)}function $e(e,t,n){let r=[`${e} will be uninstalled from ${t}: its runners stop and its code is deleted.`];return n.length>0&&r.push(`It stays installed on: ${n.map(e=>e.nodeName).join(`, `)}. Use "Everywhere" to remove it from every node.`),r.push(`This cannot be undone.`),r.join(`
3
+ `)}var et={uninstalled:`uninstalled`,"not-installed":`was not installed`,refused:`REFUSED`,failed:`FAILED`,"pending-reconnect":`offline — removed when it reconnects`};function tt(e,t){let n=[];for(let r of e.results){let e=r.runnersStopped.length>0?` (stopped ${r.runnersStopped.join(`, `)})`:``;n.push(`${t(r.nodeId)}: ${et[r.outcome]}${e}`),r.error!==void 0&&n.push(` ${r.error}`);for(let e of r.warnings)n.push(` ${e}`)}return n.join(`
4
+ `)}var nt={},rt=3e4,it=`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border border-border text-foreground-subtle hover:text-red-400 hover:border-red-500/30 hover:bg-red-500/10 disabled:opacity-50 transition-colors`;function at({packageName:e,displayName:n,selectedNode:r,hideNodeAction:i,disabled:o}){let{t:s}=q(),c=l(),u=te(),d=T(),f=I(nt,{staleTime:rt}),p=f.data?.installations??[],m=(f.data?.unreachable??[]).map(e=>e.nodeId),h=Xe(p,e),g=e=>h.find(t=>t.nodeId===e)?.nodeName??(e===r.id?r.name:e),_=Oe({onSettled:()=>{c.invalidateQueries({queryKey:[[`addons`]]}),c.invalidateQueries({queryKey:[[`addonPages`]]}),c.invalidateQueries({queryKey:[[`capabilities`]]}),c.invalidateQueries({queryKey:[[`nodes`]]})}}),v=async e=>{await d({title:e.success?s(`addons.addonUninstallControls.uninstalled`,`{{displayName}} uninstalled`,{displayName:n}):s(`addons.addonUninstallControls.notEveryNodeWasCleaned`,`{{displayName}}: not every node was cleaned`,{displayName:n}),message:tt(e,g),variant:e.success?`default`:`danger`})},y=async t=>{try{await v(await _.mutateAsync({packageName:e,...t}))}catch(e){await d({title:s(`addons.addonUninstallControls.uninstallFailed`,`Uninstall {{displayName}} failed`,{displayName:n}),message:e instanceof Error?e.message:String(e),variant:`danger`})}},b=async()=>{let e=h.filter(e=>e.nodeId!==r.id);await u({title:s(`addons.addonUninstallControls.uninstallFrom`,`Uninstall {{displayName}} from {{name}}?`,{displayName:n,name:r.name}),message:$e(n,r.name,e),confirmLabel:s(`addons.addonUninstallControls.uninstall`,`Uninstall`),variant:`danger`})&&await y(r.isHub?{}:{nodeId:r.id})},x=async()=>{let t=(await f.refetch()).data;if(t===void 0){await d({title:s(`addons.addonUninstallControls.cannotListTheNodes`,`Cannot list the nodes`),message:s(`addons.addonUninstallControls.theHubDidNotAnswer`,`The hub did not answer which nodes have this package — nothing was removed.`),variant:`danger`});return}let r=Xe(t.installations,e);await u({title:s(`addons.addonUninstallControls.uninstallEverywhere`,`Uninstall {{displayName}} everywhere?`,{displayName:n}),message:Qe(n,r,t.unreachable.map(e=>e.nodeId)),confirmLabel:s(`addons.addonUninstallControls.uninstallFromNodeS`,`Uninstall from {{length}} node(s)`,{length:r.length}),variant:`danger`})&&await y({everywhere:!0})},S=_.isPending||o===!0;return t(`div`,{className:`flex items-center gap-1.5`,children:[i!==!0&&t(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),b()},disabled:S,className:it,title:s(`addons.addonUninstallControls.uninstallFrom2`,`Uninstall from {{name}}`,{name:r.name}),children:[a(ee,{className:`h-3 w-3`}),_.isPending?s(`addons.addonUninstallControls.removing`,`Removing...`):s(`addons.addonUninstallControls.uninstall`,`Uninstall`)]}),(h.length>1||i===!0||m.length>0)&&t(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),x()},disabled:S,className:it,title:s(`addons.addonUninstallControls.uninstallFromEveryNodeThat`,`Uninstall from every node that has it`),children:[a(A,{className:`h-3 w-3`}),h.length>0?s(`addons.uninstallControls.everywhereCount`,{count:h.length}):s(`addons.uninstallControls.everywhere`)]})]})}function ot(e){return typeof e.deprecated==`string`&&e.deprecated.length>0}function st(e,t){return t?e:e.filter(e=>e.distTags.includes(`latest`)||!ot(e))}function ct(e){return e.length-st(e,!1).length}c();function lt({packageName:e,currentVersion:n,installSource:r,onInstall:i,onClose:o,onSelect:c,selectedVersion:l}){let{t:d}=q(),h=r===`upload`||r===`local`,[g,_]=s(!1),{data:v,isLoading:y,isError:b}=_e({name:e}),x=v?st(v,g):[],C=v?ct(v):0;return t(`div`,{className:`fixed z-50 w-72 rounded-lg border border-border bg-surface shadow-xl overflow-hidden`,style:{top:`auto`,bottom:`auto`},ref:e=>{if(!e)return;let t=e.parentElement?.getBoundingClientRect();if(!t)return;let n=window.innerHeight-t.bottom,r=t.top;n<280&&r>n?(e.style.bottom=`${window.innerHeight-t.top+4}px`,e.style.top=`auto`):(e.style.top=`${t.bottom+4}px`,e.style.bottom=`auto`),e.style.right=`${window.innerWidth-t.right}px`},onClick:e=>e.stopPropagation(),children:[t(`div`,{className:`flex items-center justify-between px-3 py-2 border-b border-border`,children:[a(`span`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle font-medium`,children:d(`addons.versionPicker.versions`,`Versions`)}),a(N,{variant:`unstyled`,type:`button`,onClick:o,className:`text-foreground-subtle hover:text-foreground`,children:a(S,{className:`h-3 w-3`})})]}),h&&t(`div`,{className:`flex items-start gap-2 px-3 py-2 border-b border-border bg-cyan-500/10 text-[10px]`,children:[a(p,{className:`h-3 w-3 mt-0.5 text-cyan-500 shrink-0`}),t(`div`,{className:`text-cyan-700 dark:text-cyan-200`,children:[a(`span`,{className:`font-semibold`,children:d(`addons.versionPicker.inPlace`,{kind:r===`upload`?d(`addons.versionPicker.uploadedCopy`,`Uploaded copy`):d(`addons.versionPicker.localCopy`,`Local copy`)})}),` `,a(Me,{i18nKey:`addons.versionPicker.reinstall`,values:{version:n},components:{mono:a(`span`,{className:`font-mono`})}})]})]}),y&&t(`div`,{className:`flex items-center justify-center gap-2 py-6 text-[10px] text-foreground-subtle`,children:[a(m,{className:`h-3.5 w-3.5 animate-spin`}),d(`addons.versionPicker.loadingVersions`,`Loading versions...`)]}),b&&a(`div`,{className:`px-3 py-4 text-center text-[10px] text-danger`,children:d(`addons.versionPicker.registryError`,`Could not load versions from the registry.`)}),x.length>0&&a(`div`,{className:`max-h-64 overflow-auto divide-y divide-border`,children:x.map(e=>{let r=e.version===n,o=c!==void 0&&e.version===l,s=/-(alpha|beta|rc|dev|canary|next)/i.test(e.version),p=t(u,{children:[a(`span`,{className:`font-mono flex-1 text-left ${r?`text-primary font-semibold`:s?`text-amber-400`:`text-foreground`}`,children:e.version}),r&&a(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium bg-primary/10 text-primary`,children:d(`common.current`)}),e.distTags.map(e=>a(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e===`latest`?`bg-emerald-500/15 text-emerald-400`:e===`beta`?`bg-amber-500/15 text-amber-400`:`bg-gray-500/15 text-gray-400`}`,children:e},e)),ot(e)&&a(`span`,{className:`text-[9px] text-red-400 line-through`,children:d(`common.deprecated`)}),a(`span`,{className:`text-[9px] text-foreground-subtle shrink-0`,children:new Date(e.publishedAt).toLocaleDateString()})]});return c?t(N,{variant:`unstyled`,type:`button`,"aria-label":d(`addons.versionPicker.select`,`Select {{version}}`,{version:e.version}),onClick:()=>c(e.version),className:`w-full flex items-center gap-2 px-3 py-2 text-[11px] ${o?`bg-primary/5`:`hover:bg-surface-hover`} transition-colors`,children:[p,o?a(f,{className:`h-3 w-3 text-primary shrink-0`}):a(`span`,{className:`w-3 shrink-0`})]},e.version):t(`div`,{className:`flex items-center gap-2 px-3 py-2 text-[11px] ${r?`bg-primary/5`:`hover:bg-surface-hover`} transition-colors`,children:[p,a(N,{variant:`unstyled`,type:`button`,onClick:()=>i(e.version),className:`shrink-0 rounded p-0.5 hover:bg-primary/20 text-foreground-subtle hover:text-primary transition-colors`,title:r?d(`addons.versionPicker.reInstallFromNpm`,`Re-install {{version}} from npm`,{version:e.version}):d(`addons.versionPicker.install`,`Install {{version}}`,{version:e.version}),children:a(w,{className:`h-3 w-3`})})]},e.version)})}),!y&&!b&&v&&v.length===0&&a(`div`,{className:`py-4 text-center text-[10px] text-foreground-subtle`,children:d(`addons.versionPicker.noVersionsFound`,`No versions found`)}),C>0&&a(N,{type:`button`,variant:`ghost`,size:`sm`,className:`h-auto w-full justify-start rounded-none border-t border-border px-3 py-2 text-left text-[10px] font-normal text-foreground-subtle`,onClick:()=>_(e=>!e),children:g?d(`addons.versionPicker.hideOlder`,`Hide older versions`):d(`addons.versionPicker.showOlder`,`Show older versions ({{count}})`,{count:C})})]})}c();var ut=`device-export`;function dt(e){return e.capabilities.some(e=>(typeof e==`string`?e:e.name)===ut)}function ft(e){return e!==`local`&&e!==`upload`}function pt({isBundle:e,installSource:n,addonId:r,iconPath:i,color:o}){let[c,l]=s(!1),u=o?{backgroundColor:`${o.startsWith(`#`)?o:`#${o}`}26`}:void 0,d=e?`bg-indigo-500/20 text-indigo-700 dark:text-indigo-300`:`bg-purple-500/20 text-purple-700 dark:text-purple-300`,f=r&&i?x(`/api/addon-assets/${r}/${i}`):null,m=!!f&&!c;return t(`div`,{className:`relative flex-shrink-0`,children:[a(`div`,{className:`h-8 w-8 rounded-md flex items-center justify-center ${u?``:d}`,style:u,children:m?a(`img`,{src:f,alt:r,className:`h-4 w-4`,onError:()=>l(!0)}):a(e?ne:h,{className:`h-3.5 w-3.5`})}),n===`local`&&a(`span`,{className:`absolute -top-1.5 -left-1.5 text-[7px] font-bold leading-none bg-orange-500 text-white px-1 py-0.5 rounded -rotate-12 shadow-sm`,children:`DEV`}),ft(n)&&a(`span`,{className:`absolute -top-1 -left-1 w-4 h-4 rounded bg-[#cb3837] flex items-center justify-center -rotate-12 shadow-sm`,children:a(`svg`,{viewBox:`0 0 780 250`,className:`w-[11px] h-[11px]`,children:a(`path`,{fill:`#fff`,d:`M240 250h100V50h100v200h340V0H0v250z`})})}),n===`upload`&&a(`span`,{className:`absolute -top-1.5 -left-1.5 flex items-center justify-center h-4 w-4 rounded bg-cyan-500 -rotate-12 shadow-sm`,children:a(p,{className:`h-2.5 w-2.5 text-white`})})]})}function mt({version:e,availableUpdate:n,selectedVersion:r,isUpdating:i,installSource:o,disabled:s,onUpdate:c,onOpenPicker:l,children:u}){let{t:d}=q();if(i)return t(`span`,{className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border border-blue-500/30 bg-blue-500/10 text-blue-400 shrink-0`,children:[a(m,{className:`h-3 w-3 animate-spin`}),d(`addons.addonCard.updating`,`Updating…`)]});if(n){let i=r??n;return t(`div`,{className:`relative inline-flex items-center gap-1 shrink-0`,children:[c&&t(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),c()},disabled:s,className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-semibold border border-blue-500/30 bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,title:d(`addons.addonCard.updateTo`,`Update to {{target}}`,{target:i}),children:[a(w,{className:`h-3 w-3`}),d(`addons.addonCard.update`,`Update`)]}),t(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),l()},disabled:s,"aria-label":d(`addons.addonCard.selectVersionToInstall`,`Select version to install`),title:d(`addons.addonCard.installedUpdateAvailableSelectedTap`,`Installed {{version}} — update available. Selected {{target}}; tap to choose another version.`,{version:e,target:i}),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-bold font-mono border border-amber-500/40 bg-amber-500/15 text-amber-500 hover:bg-amber-500/25 animate-pulse disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,children:[a(`span`,{className:`font-normal opacity-70`,children:e}),a(`span`,{className:`font-normal opacity-70`,children:`→`}),i,a(ie,{className:`h-3 w-3`})]}),u]})}return t(`div`,{className:`relative inline-flex items-center gap-1 shrink-0`,children:[t(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),l()},disabled:s,className:[`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-bold font-mono border transition-colors disabled:opacity-50 disabled:cursor-not-allowed`,o===`local`?`border-orange-500/30 bg-orange-500/10 text-orange-400 hover:bg-orange-500/20`:`border-emerald-500/30 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20`].join(` `),title:d(`addons.addonCard.versionTapToViewAll`,`Version {{version}} — tap to view all versions`,{version:e}),children:[e,a(ie,{className:`h-3 w-3 opacity-50`})]}),u]})}function ht({addonId:e}){let t=l(),{data:n=`inherit`}=z({addonId:e}),r=P({onSuccess:()=>{t.invalidateQueries({queryKey:[[`addons`,`getAddonAutoUpdate`]]})}});return a(`div`,{className:`flex rounded-lg border border-border overflow-hidden text-[10px] font-medium`,children:[`inherit`,`off`,`latest`,`beta`].map(t=>a(N,{variant:`unstyled`,type:`button`,onClick:n=>{n.stopPropagation(),r.mutate({addonId:e,channel:t})},disabled:r.isPending,className:`px-2.5 py-1 transition-colors capitalize ${n===t?t===`inherit`?`bg-gray-700/50 text-gray-700 dark:text-gray-300`:t===`off`?`bg-gray-700 text-gray-700 dark:text-gray-300`:t===`latest`?`bg-blue-500/20 text-blue-400`:`bg-amber-500/20 text-amber-400`:`bg-transparent text-foreground-subtle hover:bg-surface-hover`} ${t===`inherit`?``:`border-l border-border`}`,children:t},t))})}var gt={id:`hub`,name:`Hub`,isHub:!0};function _t({addon:e,clusterStatus:n,hideVersion:r,availableUpdate:i,blockedUpdate:c,onUpdateServer:f,onUpdate:p,isUpdating:m,jobProgress:h,bundle:g,bulkItem:v,disabledByBulk:y,isSystem:x,selectedNode:ee}){let{t:w}=q(),[te,T]=s(!1),[re,E]=s(!1),[D,O]=s(null);o(()=>{O(null)},[i]);let A=D??i,[oe,j]=s(!1),[M,fe]=s(!1),[he,ge]=s(`logs`),P=l(),_e=Pe(),{manifest:F}=e,ve=!g&&!F.protected&&F.removable!==!1,I=!!g,ye=g?.displayName??F.name,R=g?.packageName??F.packageName,z=g?.version??F.packageVersion??F.version,B=g?.installSource??e.installSource,Se=g?g.bundle?.description??g.addons[0]?.manifest.description:F.description,Ce=L({onSuccess:()=>{P.invalidateQueries({queryKey:[[`addons`]]})}}),we=xe({onSuccess:()=>{P.invalidateQueries({queryKey:[[`addons`]]}),P.invalidateQueries({queryKey:[[`addonPages`]]}),P.invalidateQueries({queryKey:[[`capabilities`]]}),P.invalidateQueries({queryKey:[[`integrations`]]})}}),V=K({onSuccess:()=>{P.invalidateQueries({queryKey:[[`addons`]]}),P.invalidateQueries({queryKey:[[`alerts`]]})}}),H=e.health,U=H?.phase===`failed`&&!H.inGracePeriod,W=U&&H?.nextRetryAt&&!H.retrying,G=He(e.process);return t(`div`,{className:`rounded-md border bg-surface overflow-hidden ${U?`border-red-500/50`:`border-border`}`,children:[U&&H&&t(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[a(k,{className:`h-4 w-4 text-danger shrink-0 mt-0.5`}),t(`div`,{className:`flex-1 min-w-0`,children:[a(`div`,{className:`text-xs font-semibold text-danger`,children:w(`addons.addonCard.failedToLoad`,{attempt:H.retryCount})}),a(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:H.lastError?.message??w(`addons.addonCard.unknownError`,`Unknown error`)}),W&&H.nextRetryAt&&a(`div`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`addons.addonCard.autoRetryAt`,{time:new Date(H.nextRetryAt).toLocaleTimeString()})})]}),t(N,{variant:`unstyled`,type:`button`,disabled:V.isPending||H.retrying,onClick:e=>{e.stopPropagation(),V.mutate({packageName:R})},className:`inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-semibold border border-red-400/40 bg-red-400/10 text-red-700 dark:text-red-300 hover:bg-red-400/20 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shrink-0`,title:w(`addons.addonCard.resetRetryCounterAndForce`,`Reset retry counter and force immediate reload`),children:[a(C,{className:`h-3 w-3 ${V.isPending||H.retrying?`animate-spin`:``}`}),w(`addons.addonCard.retryNow`,`Retry now`)]})]}),G!==null&&t(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[a(k,{className:`h-4 w-4 text-danger shrink-0 mt-0.5`}),t(`div`,{className:`flex-1 min-w-0`,children:[a(`div`,{className:`text-xs font-semibold text-danger`,children:w(`addons.addonCard.processProblem.${G.kind}`)}),G.reason!==void 0&&a(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:G.reason})]})]}),t(`div`,{className:`flex items-start gap-2.5 px-3 py-2`,children:[a(pt,{isBundle:I||!!F.components&&F.components.length>1,installSource:B,addonId:I?g.addons[0]?.manifest.id:F.id,iconPath:I?g.bundle?.icon??g.addons[0]?.manifest.icon:F.icon,color:I?g.addons[0]?.manifest.color:F.color}),t(`div`,{className:`flex-1 min-w-0`,children:[t(`div`,{className:`flex items-start justify-between gap-2`,children:[a(`span`,{className:`text-xs font-semibold text-foreground truncate min-w-0`,children:ye}),!r&&a(mt,{version:z,availableUpdate:i,...A===void 0?{}:{selectedVersion:A},isUpdating:m,installSource:B,disabled:y,...p&&A!==void 0?{onUpdate:()=>p(A)}:{},onOpenPicker:()=>E(e=>!e),children:re&&a(lt,{packageName:R,currentVersion:z,...B?{installSource:B}:{},...i!==void 0&&A!==void 0?{selectedVersion:A,onSelect:e=>{O(e),E(!1)}}:{},onInstall:e=>{E(!1),we.mutate({packageName:R,version:e})},onClose:()=>E(!1)})})]}),t(`div`,{className:`flex flex-wrap items-center gap-x-1.5 gap-y-1 mt-0.5`,children:[R!==ye&&a(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate max-w-full`,children:R}),I&&t(`span`,{className:`text-[10px] rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium shrink-0 inline-flex items-center gap-1`,children:[a(ne,{className:`h-3 w-3`}),g.addons.length]}),x&&t(`span`,{className:`text-[10px] rounded-full bg-amber-500/15 text-amber-700 dark:text-amber-300 px-2 py-0.5 font-medium shrink-0 inline-flex items-center gap-1`,title:w(`addons.addonCard.systemPackageUpdatingRestartsThe`,`System package — updating restarts the hub`),children:[a(C,{className:`h-3 w-3`}),w(`addons.addonCard.system`,`System`)]}),v!=null&&a(Z,{item:v}),c!==void 0&&a(de,{variant:`warning`,title:w(`addons.addonCard.updateHeldTitle`,{defaultValue:`{{latest}} is held until the server is {{required}} or newer`,latest:c.latestVersion,required:c.requiredServer}),children:w(`addons.addonCard.requiresServer`,{defaultValue:`requires server ≥ {{version}}`,version:c.requiredServer})}),c!==void 0&&f!==void 0&&a(N,{type:`button`,size:`sm`,variant:`secondary`,onClick:f,children:w(`clusterUpdate.updateServer`,`Update server`)}),h!=null&&a(Ye,{progress:h})]}),Se&&a(`p`,{className:`text-[10px] text-foreground-subtle mt-1 line-clamp-1`,children:Se}),!I&&e.process&&t(`div`,{className:`flex flex-wrap items-center gap-1.5 mt-1`,children:[a(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e.process.mode===`forked`?`bg-blue-500/15 text-blue-400`:`bg-gray-500/15 text-gray-400`}`,children:e.process.mode===`forked`?w(`addons.addonCard.forked`):w(`addons.addonCard.inProcess`)}),e.process.pid!=null&&t(`span`,{className:`text-[9px] font-mono text-foreground-subtle`,children:[`PID `,e.process.pid]}),a(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e.process.state===`running`?`bg-emerald-500/15 text-emerald-400`:G===null?`bg-gray-500/15 text-gray-400`:`bg-red-500/15 text-red-400`}`,children:e.process.state})]})]})]}),!I&&t(`div`,{className:`flex items-center gap-1 px-3 py-1 border-t border-border/50 bg-surface-hover/20`,children:[t(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),Ce.mutate({addonId:F.id})},disabled:Ce.isPending||y,className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border border-border text-foreground-subtle hover:text-blue-400 hover:border-blue-500/30 hover:bg-blue-500/10 disabled:opacity-50 transition-colors`,children:[a(C,{className:`h-3 w-3 ${Ce.isPending?`animate-spin`:``}`}),w(`addons.addonCard.restart`,`Restart`)]}),t(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),j(e=>!e)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${oe?`border-primary/30 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:border-primary/30 hover:bg-primary/10`}`,children:[a(b,{className:`h-3 w-3`}),w(`addons.addonCard.logs`,`Logs`)]}),!I&&t(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),fe(!0)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${M?`border-primary/30 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:border-primary/30 hover:bg-primary/10`}`,children:[a(d,{className:`h-3 w-3`}),w(`addons.addonCard.settings`,`Settings`)]}),a(`div`,{className:`flex-1`}),ve&&a(at,{packageName:F.packageName,displayName:F.name,selectedNode:ee??gt,disabled:y})]}),n&&n.nodes.length>1&&!I&&t(`div`,{className:`border-t border-border px-3 py-1.5 bg-muted/10`,children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle mb-1.5`,children:w(`addons.addonCard.clusterDeployment`,`Cluster Deployment`)}),a(`div`,{className:`space-y-1`,children:n.nodes.map(e=>t(`div`,{className:`flex items-center gap-2 text-[10px]`,children:[a(`div`,{className:`h-1.5 w-1.5 rounded-full shrink-0 ${e.status===`offline`?`bg-muted-foreground/30`:e.synced?`bg-success`:`bg-amber-500`}`}),a(`span`,{className:`font-medium text-foreground min-w-[60px]`,children:e.name}),a(`span`,{className:`font-mono text-foreground-subtle`,children:e.version}),!e.synced&&e.status!==`offline`&&a(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20`,children:w(`addons.addonCard.outdated`)}),e.status===`offline`&&a(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground`,children:w(`common.offline`)}),e.synced&&e.status!==`offline`&&a(`span`,{className:`text-[9px] text-success`,children:w(`common.synced`)})]},e.nodeId))})]}),oe&&!I&&t(`div`,{className:`border-t border-border`,children:[t(`div`,{className:`flex items-center px-3 py-0.5 bg-surface-hover/20 border-b border-border/50`,children:[t(`div`,{className:`flex rounded border border-border overflow-hidden text-[9px]`,children:[a(N,{variant:`unstyled`,type:`button`,onClick:()=>ge(`logs`),className:`px-2 py-0.5 transition-colors ${he===`logs`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:w(`addons.addonCard.logs`,`Logs`)}),a(N,{variant:`unstyled`,type:`button`,onClick:()=>ge(`events`),className:`px-2 py-0.5 border-l border-border transition-colors ${he===`events`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:w(`addons.addonCard.events`,`Events`)})]}),a(`div`,{className:`flex-1`}),a(N,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),j(!1)},className:`text-foreground-subtle hover:text-foreground`,children:a(S,{className:`h-3.5 w-3.5`})})]}),he===`logs`&&a(ke,{addonId:F.id,maxHeight:`max-h-64`,showFilters:!1}),he===`events`&&a(se,{addonId:F.id,category:`addon.*`,maxHeight:`max-h-64`})]}),I&&t(u,{children:[a(N,{variant:`unstyled`,type:`button`,onClick:()=>T(e=>!e),className:`w-full flex items-center justify-center border-t border-border py-1 hover:bg-surface-hover/50 transition-colors`,children:a(te?_:ie,{className:`h-3.5 w-3.5 text-foreground-subtle`})}),te&&a(`div`,{className:`border-t border-border px-2.5 py-1.5 space-y-1.5`,children:g.addons.map(e=>a(_t,{addon:e,hideVersion:!0},e.manifest.id))})]}),M&&!I&&a(ae,{open:!0,onOpenChange:e=>!e&&fe(!1),children:t(le,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[a(ce,{children:t(ue,{className:`flex items-center gap-2`,children:[a(d,{className:`h-4 w-4 text-primary`}),w(`addons.addonCard.settingsTitle`,{name:ye})]})}),t(pe,{className:`space-y-4`,children:[a(`div`,{className:`text-[10px] text-foreground-subtle mb-2`,children:w(`addons.addonCard.clusterWideSettingsOneValue`,`Cluster-wide settings — one value for every node. Per-node settings live under Cluster → the node → Settings.`)}),a(Y,{nodeId:null,addonIds:[F.id],level:`global`,fieldScope:`cluster`,emptyMessage:w(`addons.addonCard.thisAddonExposesNoCluster`,`This addon exposes no cluster-wide settings. Anything it can configure is per-node — open it from Cluster → the node → Settings.`)}),dt(F)&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:w(`addons.addonCard.deviceExport`,`Device export`)}),a(be,{addonId:F.id,onOpenDevice:e=>_e(`/devices/${e}`)})]}),ft(B)&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:w(`addons.addonCard.autoUpdate`,`Auto-Update`)}),a(ht,{addonId:F.id})]}),F.components&&F.components.length>0&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:w(`addons.addonCard.components`,{count:F.components.length})}),a(`div`,{className:`flex flex-wrap gap-1`,children:F.components.map(e=>a(`span`,{className:`text-[10px] rounded bg-background border border-border px-1.5 py-0.5 text-foreground-subtle font-mono`,children:e},e))})]})]}),a(me,{children:a(N,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>fe(!1),children:w(`common.close`,`Close`)})})]})})]})}c();var vt=`.tgz,.tar.gz,.zip`;function yt({onUploadSuccess:e}){let{t:r}=q(),[o,c]=s(!1),l=n(null),d=i(async t=>{c(!0);let n=new FormData;n.append(`file`,t);let r=localStorage.getItem(`camstack_admin_token`)??``;try{(await(await fetch(x(`/api/addons/upload`),{method:`POST`,headers:{Authorization:`Bearer ${r}`},body:n})).json()).success&&e()}finally{c(!1)}},[e]);return t(u,{children:[a(ye,{ref:l,accept:vt,onChange:i(e=>{let t=e.target.files?.[0];t&&d(t),e.target.value=``},[d]),className:`hidden`}),t(N,{variant:`unstyled`,type:`button`,onClick:()=>l.current?.click(),disabled:o,className:`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors`,children:[o?a(m,{className:`w-3.5 h-3.5 animate-spin`}):a(p,{className:`w-3.5 h-3.5`}),o?r(`addons.addonUploadZone.uploading`,`Uploading...`):r(`addons.addonUploadZone.upload`,`Upload`)]})]})}var bt=/```[^\n]*\n([\s\S]*?)```/g;function xt(e){let t=[],n=0;for(let r of e.matchAll(bt)){let i=r.index??0;i>n&&t.push({kind:`text`,body:e.slice(n,i)}),t.push({kind:`code`,body:r[1]??``}),n=i+r[0].length}return n<e.length&&t.push({kind:`text`,body:e.slice(n)}),t}function St(e){let t=e.trim();return t.startsWith(`https://`)||t.startsWith(`http://`)?t:null}function Ct(e,t){let n=[],r=/(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g,i=0,o=0;for(let s of e.matchAll(r)){let r=s.index??0;r>i&&n.push(e.slice(i,r));let c=s[0],l=`${t}-${o}`;if(o+=1,c.startsWith(`**`))n.push(a(`strong`,{children:c.slice(2,-2)},l));else if(c.startsWith("`"))n.push(a(`code`,{className:`font-mono text-[0.9em]`,children:c.slice(1,-1)},l));else{let e=/^\[([^\]]+)\]\(([^)]+)\)$/.exec(c),t=e?.[1]??c,r=e?St(e[2]??``):null;n.push(r?a(`a`,{href:r,target:`_blank`,rel:`noreferrer noopener`,className:`text-primary underline`,children:t},l):a(`span`,{children:t},l))}i=r+c.length}return i<e.length&&n.push(e.slice(i)),n}function wt(e,t){let n=e.split(`
5
+ `),r=[],i=[],o=[],s=0,c=()=>{if(i.length===0)return;let e=i.join(` `).trim();i=[],e.length!==0&&(r.push(a(`p`,{className:`mb-2 last:mb-0`,children:Ct(e,`${t}-p-${s}`)},`${t}-p-${s}`)),s+=1)},l=()=>{if(o.length===0)return;let e=o;o=[],r.push(a(`ul`,{className:`mb-2 list-disc pl-4 last:mb-0`,children:e.map((e,n)=>a(`li`,{children:Ct(e,`${t}-li-${s}-${n}`)},`${t}-li-${s}-${n}`))},`${t}-ul-${s}`)),s+=1};for(let e of n){let n=/^(#{1,3})\s+(.*)$/.exec(e),u=/^\s*[-*]\s+(.*)$/.exec(e);if(n){c(),l();let e=n[1]?.length??1,i=Ct(n[2]??``,`${t}-h-${s}`),o=e===1?`text-sm font-semibold mb-2`:`text-xs font-semibold mb-1.5 mt-2`;r.push(a(e===1?`h3`:`h4`,{className:o,children:i},`${t}-h-${s}`)),s+=1;continue}if(u){c(),o=[...o,u[1]??``];continue}if(e.trim().length===0){c(),l();continue}l(),i=[...i,e.trim()]}return c(),l(),r}function Tt({markdown:e}){return a(`div`,{className:`text-xs text-foreground leading-relaxed`,children:xt(e).map((e,t)=>e.kind===`code`?a(`pre`,{className:`mb-2 overflow-auto rounded-md bg-surface-hover p-2 font-mono text-[10px] last:mb-0`,children:e.body.replace(/\n$/,``)},`code-${t}`):a(`div`,{children:wt(e.body,`b${t}`)},`text-${t}`))})}c();function Et(e){return e.replace(/^@camstack\/(addon-)?/,``)}function Dt(e,t,n){let r=st(e,n);return r.some(e=>e.version===t)?r:[{version:t,distTags:[],deprecated:void 0},...r]}function Ot({pending:e,failed:n,body:r,missing:i}){let{t:o}=q();return e?t(`div`,{className:`flex items-center gap-2 py-6 text-xs text-foreground-subtle`,children:[a(m,{className:`h-3.5 w-3.5 animate-spin`}),o(`addons.installDialog.loadingDocument`,`Loading…`)]}):n||r===void 0?a(`p`,{className:`py-4 text-xs text-danger`,children:o(`addons.installDialog.couldNotLoadDocument`,`Could not load this file from the registry.`)}):r.status===`ok`&&r.markdown!==void 0?a(Tt,{markdown:r.markdown}):r.status===`error`?a(`p`,{className:`py-4 text-xs text-danger`,children:o(`addons.installDialog.documentError`,`Could not load this file. {{message}}`,{message:r.message??``})}):a(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:i})}function kt({target:e,installing:n,installError:r,onClose:i,onInstall:o}){let{t:c}=q(),[l,u]=s(e.version),[d,f]=s(!1),p=_e({name:e.name}),h=U({name:e.name,version:l}),g=p.data??[],_=ct(g),v=Dt(g,l,d),y=h.data;return a(ae,{open:!0,onOpenChange:e=>!e&&i(),children:t(le,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[a(ce,{children:a(ue,{children:c(`addons.installDialog.title`,`Install {{name}}`,{name:Et(e.name)})})}),t(pe,{className:`space-y-3`,children:[a(`p`,{className:`font-mono text-[10px] text-foreground-subtle`,children:e.name}),e.description.length>0&&a(`p`,{className:`text-xs text-foreground`,children:e.description}),t(`div`,{className:`space-y-1.5`,children:[a(`span`,{className:`text-[10px] text-foreground-subtle`,children:c(`addons.installDialog.version`,`Version`)}),a(re,{"aria-label":c(`addons.installDialog.version`,`Version`),value:l,options:v.map(e=>({value:e.version,label:ot(e)?c(`addons.installDialog.deprecatedVersion`,`{{version}} (deprecated)`,{version:e.version}):e.version})),onChange:e=>u(e.target.value)}),p.isError&&a(`p`,{className:`text-[10px] text-danger`,children:c(`addons.versionPicker.registryError`,`Could not load versions from the registry.`)}),_>0&&a(N,{type:`button`,variant:`ghost`,size:`sm`,className:`h-auto justify-start px-0 text-[10px] font-normal text-foreground-subtle underline`,onClick:()=>f(e=>!e),children:d?c(`addons.versionPicker.hideOlder`,`Hide older versions`):c(`addons.versionPicker.showOlder`,`Show older versions ({{count}})`,{count:_})})]}),t(W,{defaultValue:`readme`,children:[t(Se,{children:[a(De,{value:`readme`,children:c(`addons.installDialog.readme`,`README`)}),a(De,{value:`changelog`,children:c(`addons.installDialog.changelog`,`CHANGELOG`)})]}),a(F,{value:`readme`,children:a(`div`,{className:`max-h-80 overflow-auto rounded-md border border-border bg-background p-3`,children:a(Ot,{pending:h.isPending,failed:h.isError,body:y?.readme,missing:c(`addons.installDialog.missingReadme`,`This package has no README.`)})})}),a(F,{value:`changelog`,children:a(`div`,{className:`max-h-80 overflow-auto rounded-md border border-border bg-background p-3`,children:a(Ot,{pending:h.isPending,failed:h.isError,body:y?.changelog,missing:c(`addons.installDialog.missingChangelog`,`This package has no CHANGELOG.`)})})})]}),r!=null&&r.length>0&&a(`p`,{className:`text-xs text-danger`,children:r})]}),t(me,{children:[a(N,{type:`button`,variant:`outline`,size:`sm`,onClick:i,children:c(`common.cancel`,`Cancel`)}),a(N,{type:`button`,size:`sm`,disabled:n||l.length===0,onClick:()=>o(e.name,l),children:n?a(m,{className:`h-3.5 w-3.5 animate-spin`}):c(`addons.installDialog.install`,`Install`)})]})]})})}function At(e,t){let n=new Map;for(let r of e){if(r.isHub||r.onHub||J(r.packageName)||!t.isHub&&r.nodeId!==t.id)continue;let e=n.get(r.packageName)??[];e.push(r),n.set(r.packageName,e)}return[...n].map(([e,t])=>({packageName:e,rows:t})).sort((e,t)=>e.packageName.localeCompare(t.packageName))}function jt({selectedNode:e}){let{t:n}=q(),{data:r}=I(nt,{staleTime:rt});if(r===void 0)return null;let i=At(r.installations,e),o=r.unreachable.filter(t=>e.isHub||t.nodeId===e.id);return i.length===0&&o.length===0?null:t(`div`,{className:`rounded-lg border border-warning/30 bg-warning/5 px-3 py-2.5 space-y-2`,children:[t(`div`,{className:`flex items-center gap-2 text-[11px] font-semibold text-foreground`,children:[a(g,{className:`h-3.5 w-3.5 text-warning`}),e.isHub?n(`addons.nodeOnlyPackagesPanel.installedOnAgentsButNot`,`Installed on agents but not on the hub`):n(`addons.nodeOnlyPackagesPanel.installedOnButNotOn`,`Installed on {{name}} but not on the hub`,{name:e.name})]}),o.length>0&&a(`div`,{className:`text-[10px] text-foreground-subtle`,children:n(`addons.nodeOnlyPackagesPanel.unreachable`,{nodes:o.map(e=>e.nodeId).join(`, `)})}),i.map(n=>t(`div`,{className:`flex items-center justify-between gap-3 flex-wrap rounded-md border border-border bg-surface px-3 py-2`,children:[t(`div`,{className:`min-w-0`,children:[a(`div`,{className:`text-xs font-mono text-foreground break-all`,children:n.packageName}),a(`div`,{className:`text-[10px] text-foreground-subtle`,children:n.rows.map(e=>`${e.nodeName}${e.version===null?``:` ${e.version}`}${e.isOnline?``:` (offline)`}`).join(` · `)})]}),a(at,{packageName:n.packageName,displayName:n.packageName,selectedNode:e,hideNodeAction:e.isHub})]},n.packageName))]})}function Mt({addon:e,installing:n,onInstall:r}){let{t:i}=q();return t(`div`,{className:`flex items-center gap-3 px-3 py-2 hover:bg-surface-hover transition-colors`,children:[a(`div`,{className:`w-6 h-6 rounded-md bg-primary/10 flex items-center justify-center text-primary text-[9px] font-bold shrink-0`,children:e.name.replace(`@camstack/addon-`,``).charAt(0).toUpperCase()}),t(`div`,{className:`flex-1 min-w-0`,children:[t(`div`,{className:`flex items-baseline gap-2 min-w-0`,children:[a(`span`,{className:`text-[11px] font-semibold break-words`,children:e.name.replace(/^@camstack\/(addon-)?/,``)}),t(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:[`v`,e.version]})]}),a(`div`,{className:`font-mono text-[9px] text-foreground-subtle/80 truncate`,children:e.name}),e.description&&a(`div`,{className:`text-[10px] text-foreground-subtle truncate`,children:e.description})]}),e.installed?a(de,{variant:`success`,icon:a(f,{className:`h-3 w-3`}),children:e.installedVersion??i(`system.capabilityCatalog.installed`,`Installed`)}):t(N,{size:`sm`,onClick:()=>r(e),disabled:n,className:`shrink-0`,children:[n?a(m,{className:`h-3 w-3 animate-spin`}):a(w,{className:`h-3 w-3`}),i(`system.capabilityCatalog.install`,`Install`)]})]})}function Nt({capability:e,installing:n,onInstall:r}){let{t:i}=q(),{data:o,isPending:s,isError:c}=je({capability:e}),l;if(c)l=a(`div`,{className:`px-3 py-2 text-xs text-danger`,children:i(`system.capabilityCatalog.couldNotSearchTheNpm`,`Could not search the npm catalog right now. Try again in a moment.`)});else if(s||o===void 0)l=t(`div`,{className:`flex items-center gap-2 px-3 py-2 text-xs text-foreground-subtle`,children:[a(m,{className:`h-3 w-3 animate-spin`}),i(`system.capabilityCatalog.searchingTheNpmCatalog`,`Searching the npm catalog…`)]});else{let t=o.filter(e=>!e.installed);l=t.length===0?a(`div`,{className:`px-3 py-2 text-xs text-foreground-subtle`,children:o.length===0?i(`system.capabilityCatalog.noPublishedAddonDeclaresThe`,`No published addon declares the "{{capability}}" capability.`,{capability:e}):i(`system.capabilityCatalog.everyPublishedAddonThatDeclares`,`Every published addon that declares "{{capability}}" is already installed.`,{capability:e})}):a(`div`,{className:`divide-y divide-border`,children:t.map(e=>a(Mt,{addon:e,installing:n,onInstall:r},e.name))})}return t(`section`,{className:`rounded-md border border-border bg-surface overflow-hidden`,"aria-label":i(`system.capabilityCatalog.availableToInstall`,`Available to install`),children:[a(`h2`,{className:`px-3 py-1.5 text-[10px] uppercase tracking-wide text-foreground-subtle border-b border-border`,children:i(`system.capabilityCatalog.availableToInstall`,`Available to install`)}),l]})}c();function Pt(e){return e===`npm`||e===`dev`?e:null}var Ft=`rounded-full border border-primary bg-primary/10 px-2 py-0.5 text-[10px] text-foreground`,It=`rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-muted hover:bg-surface-hover`,Lt=[{seconds:900,label:`15m`},{seconds:3600,label:`1h`},{seconds:21600,label:`6h`},{seconds:43200,label:`12h`},{seconds:86400,label:`24h`}],Rt={id:`hub`,name:`Hub`,isHub:!0,isOnline:!0};function zt(e,t){let n=e??`hub-only`;return n===`any-node`?!0:n===`hub-only`?t:!t}function Bt(e){return e===`local`?`dev`:`npm`}function Vt(e){let t=e;if(!t?.manifest)return null;let n={...t.manifest,name:t.manifest.name??t.manifest.id,version:t.manifest.version??`0.0.0`,capabilities:t.manifest.capabilities??[]},r=t.process,i=r?{pid:r.pid,mode:r.mode===`forked`?`forked`:`in-process`,state:r.state??`unknown`,...r.reason===void 0?{}:{reason:r.reason}}:void 0,a=t.health,o=t.declaration?.execution,s=t.manifest.execution,c=o?.placement??s?.placement;return{manifest:n,enabled:!0,source:t.source,installSource:t.installSource,installedOn:[],...i?{process:i}:{},hasBackup:t.hasBackup,...a?{health:a}:{},...c?{placement:c}:{}}}function Ht(e){let t=new Map,n=[];for(let r of e){let e=r.manifest.packageName;if(!e){n.push(r);continue}let i=t.get(e);if(i)i.addons.push(r);else{let n=r.manifest.bundle,i={packageName:e,displayName:n?.displayName??r.manifest.packageDisplayName??r.manifest.name,version:r.manifest.packageVersion,addons:[r],...r.installSource===void 0?{}:{installSource:r.installSource},...n===void 0?{}:{bundle:n}};t.set(e,i)}}let r=[];for(let e of t.values())e.bundle!==void 0||e.addons.length>=2?r.push({bundle:e,representative:e.addons[0]}):r.push(e.addons[0]);return r.push(...n),r}function $(e){return`bundle`in e}function Ut({addons:c,clusterStatus:u,selectedNode:d,onRefresh:f,listPhase:p}){let{t:h}=q(),g=l(),[_,b]=s(``),[x,S]=s(!1),ee=e(_),[T,ne]=s(!1),E=n(null);o(()=>{if(!T)return;let e=e=>{E.current&&!E.current.contains(e.target)&&ne(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[T]);let{data:D}=Ce({nodeId:d.id}),O=r(()=>{let e=new Map;for(let t of D??[])t.blockedBy===void 0&&e.set(t.name,t.latestVersion);return e},[D]),ie=r(()=>{let e=new Map;for(let t of D??[]){let n=t.blockedBy?.find(e=>e.kind===`server-too-old`);n!==void 0&&e.set(t.name,{latestVersion:t.latestVersion,requiredServer:n.required})}return e},[D]),k=r(()=>(D??[]).filter(e=>!e.isSystem&&e.blockedBy===void 0).length,[D]),[A,ae]=s(()=>new Set),[se,ce]=s(()=>new Map),le=i(e=>{ae(t=>new Set(t).add(e))},[]),j=i(e=>{ae(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),ue=i((e,t)=>{ce(n=>new Map(n).set(e,t))},[]),de=i(e=>{ce(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})},[]),M=fe({onMutate:e=>{le(e.name),de(e.name)},onSuccess:(e,t)=>{j(t.name);let n=e;if(n&&n.success===!1){ue(t.name,n.error??`Update failed (no error message returned by server)`);return}g.invalidateQueries({queryKey:[[`addons`]]}),g.invalidateQueries({queryKey:[[`addons`,`listUpdates`]]})},onError:(e,t)=>{j(t.name),ue(t.name,e instanceof Error?e.message:String(e))}}),pe=qe(),me=n(new Set);o(()=>{let e=new Set;for(let[t,n]of pe)Ge(n)&&e.add(t);let t=[...me.current].some(t=>!e.has(t));me.current=e,t&&(g.invalidateQueries({queryKey:[[`addons`]]}),g.invalidateQueries({queryKey:[[`addons`,`listUpdates`]]}))},[pe,g]);let{data:P}=he(void 0),_e=Te({onSuccess:()=>{g.invalidateQueries({queryKey:[[`addons`,`getAutoUpdateSettings`]]})}}),F=Ae({onSuccess:()=>{g.invalidateQueries({queryKey:[[`addons`,`getAutoUpdateSettings`]]})}}),{data:I,isFetching:ye}=je({query:ee||void 0},{enabled:T}),L=oe(),{data:R}=we(void 0),be=R?.requestedAt,[z,B]=s(null),[Se,V]=s(!1);o(()=>{if(R?.kind===`framework-bulk-update`&&R.requestedAt!==z){B(R.requestedAt),V(!0);let e=window.setTimeout(()=>V(!1),6e3);return()=>window.clearTimeout(e)}},[be,z,R]),te();let H=i(async()=>{let e=(D??[]).filter(e=>!e.isSystem&&e.blockedBy===void 0);if(e.length!==0){if(!d.isHub){for(let t of e)await M.mutateAsync({name:t.name,version:t.latestVersion,nodeId:d.id});return}await L.mutateAsync({kind:`update`,targets:e.map(e=>({name:e.name,version:e.latestVersion})),nodeIds:[d.id]})}},[D,d.id,d.isHub,L,M]),[U,W]=s(null),[G,Ee]=s(null),De=e=>{Ee(null),W(e)},K=xe({onSuccess:()=>{W(null),Ee(null),g.invalidateQueries({queryKey:[[`addons`]]}),g.invalidateQueries({queryKey:[[`addonPages`]]}),g.invalidateQueries({queryKey:[[`capabilities`]]}),g.invalidateQueries({queryKey:[[`integrations`]]})},onError:e=>{Ee(e instanceof Error?e.message:`Install failed`)}}),[Oe,ke]=s(`type`),[Me,Pe]=s(()=>typeof window>`u`?`grouped`:window.localStorage.getItem(`camstack.addons.viewMode`)===`flat`?`flat`:`grouped`),Fe=e=>{Pe(e),typeof window<`u`&&window.localStorage.setItem(`camstack.addons.viewMode`,e)},[J,Y]=Ne(),X=J.get(`capability`),Ve=J.get(`updatable`)===`1`,Ue=J.get(`error`)===`1`,Z=Pt(J.get(`source`)),Q=Ie(J.get(Re))===`integration`,{data:We}=ve(void 0,{enabled:Q}),Ke=r(()=>We===void 0?null:new Set(We.map(e=>e.addonId)),[We]),Je=i(e=>{let t=new URLSearchParams(J);e?t.set(Re,`integration`):t.delete(Re),Y(t,{replace:!0})},[J,Y]),Ye=i(e=>{let t=new URLSearchParams(J);e?t.set(`updatable`,`1`):t.delete(`updatable`),Y(t,{replace:!0})},[J,Y]),Xe=i(e=>{let t=new URLSearchParams(J);e?t.set(`error`,`1`):t.delete(`error`),Y(t,{replace:!0})},[J,Y]),Ze=i(e=>{let t=new URLSearchParams(J);e===null?t.delete(`source`):t.set(`source`,e),Y(t,{replace:!0})},[J,Y]),Qe=r(()=>c.filter(e=>He(e.process)!==null).length,[c]),$e=r(()=>{let e=c.filter(e=>!ze(e.manifest.packageName));return d.isHub||(e=e.filter(e=>zt(e.placement,d.isHub))),X&&(e=e.filter(e=>(e.manifest.capabilities??[]).some(e=>(typeof e==`string`?e:e.name)===X))),Q&&(e=[...Le(e,Ke)]),Ve&&(e=e.filter(e=>{let t=e.manifest.packageName;return t!==void 0&&O.has(t)})),Z!==null&&(e=e.filter(e=>Bt(e.installSource)===Z)),Ue&&(e=e.filter(e=>He(e.process)!==null)),e},[c,d.isHub,X,Ve,Z,Ue,Q,Ke,O]),et=()=>{let e=new URLSearchParams(J);e.delete(`capability`),Y(e,{replace:!0})},tt=Me===`flat`?$e:Ht($e),nt=r(()=>{let e=[...tt];switch(Oe){case`type`:e.sort((e,t)=>{let n=+!$(e),r=+!$(t);if(n!==r)return n-r;let i=$(e)?e.bundle.displayName:e.manifest.name,a=$(t)?t.bundle.displayName:t.manifest.name;return i.localeCompare(a)});break;case`name`:e.sort((e,t)=>{let n=$(e)?e.bundle.displayName:e.manifest.name,r=$(t)?t.bundle.displayName:t.manifest.name;return n.localeCompare(r)});break;case`source`:e.sort((e,t)=>{let n=$(e)?e.bundle.installSource??``:e.installSource??``,r=$(t)?t.bundle.installSource??``:t.installSource??``;return n.localeCompare(r)});break}return e},[tt,Oe]);return t(`div`,{className:`space-y-3`,children:[a(Be,{open:x,onOpenChange:S}),[...se.entries()].map(([e,n])=>a(`div`,{className:`rounded-md border border-danger/30 bg-danger/5 px-2.5 py-1.5 text-[11px]`,children:t(`div`,{className:`flex items-start justify-between gap-3`,children:[t(`div`,{className:`space-y-0.5`,children:[a(`div`,{className:`font-medium text-danger`,children:h(`systemPage.addons.updateFailed`,{name:e})}),a(`div`,{className:`text-foreground-subtle font-mono`,children:n})]}),a(N,{variant:`unstyled`,type:`button`,onClick:()=>de(e),className:`text-foreground-subtle hover:text-foreground text-[10px]`,children:h(`common.dismiss`)})]})},e)),t(`div`,{className:`flex items-center gap-x-2 gap-y-1.5 flex-wrap`,children:[t(`div`,{className:`flex items-center gap-1.5`,children:[a(`span`,{className:`text-[10px] text-foreground-subtle`,children:h(`admin.system.addons.sort`,`Sort:`)}),t(re,{wrapperClassName:`inline-block w-auto`,value:Oe,onChange:e=>ke(e.target.value),children:[a(`option`,{value:`type`,children:h(`admin.system.addons.bundlesFirst`,`Bundles first`)}),a(`option`,{value:`name`,children:h(`admin.system.addons.name`,`Name`)}),a(`option`,{value:`source`,children:h(`admin.system.addons.installSource`,`Install source`)})]})]}),t(`div`,{className:`flex items-center gap-1.5`,children:[a(`span`,{className:`text-[10px] text-foreground-subtle`,children:h(`admin.system.addons.view`,`View:`)}),a(`div`,{className:`flex rounded-md border border-border overflow-hidden text-[10px] font-medium`,children:[`grouped`,`flat`].map(e=>a(N,{variant:`unstyled`,type:`button`,onClick:()=>Fe(e),className:`px-2 py-1 transition-colors capitalize ${Me===e?`bg-primary/10 text-primary`:`bg-transparent text-foreground-subtle hover:bg-surface-hover`}`,title:e===`grouped`?h(`admin.system.addons.groupMultiAddonPackagesInto`,`Group multi-addon packages into a bundle card`):h(`admin.system.addons.showEveryAddonAsIts`,`Show every addon as its own card`),children:e},e))})]}),d.isHub&&t(`div`,{className:`flex items-center gap-1.5`,children:[a(C,{className:`h-3 w-3 text-foreground-subtle`}),a(`span`,{className:`text-[10px] text-foreground-subtle`,children:h(`admin.system.addons.autoUpdate`,`Auto-Update:`)}),a(`div`,{className:`flex rounded-md border border-border overflow-hidden text-[10px] font-medium`,children:[`off`,`latest`,`beta`].map(e=>a(N,{variant:`unstyled`,type:`button`,onClick:()=>_e.mutate({channel:e}),disabled:_e.isPending,className:`px-2 py-1 transition-colors capitalize ${P?.channel===e?e===`off`?`bg-gray-700 text-gray-200`:e===`latest`?`bg-blue-500/20 text-blue-400`:`bg-amber-500/20 text-amber-400`:`bg-transparent text-foreground-subtle hover:bg-surface-hover`} ${e===`off`?``:`border-l border-border`}`,children:e},e))})]}),d.isHub&&t(`div`,{className:`flex items-center gap-1.5`,children:[a(`span`,{className:`text-[10px] text-foreground-subtle`,children:h(`admin.system.addons.checkEvery`,`Check every:`)}),a(re,{wrapperClassName:`inline-block w-auto`,className:`font-medium text-foreground-subtle`,value:P?.updateCheckIntervalSeconds??21600,disabled:F.isPending||P===void 0,onChange:e=>{P!==void 0&&F.mutate({channel:P.channel,updateCheckIntervalSeconds:Number(e.target.value)})},children:Lt.map(e=>a(`option`,{value:e.seconds,children:e.label},e.seconds))})]}),k>0&&t(N,{variant:`unstyled`,type:`button`,onClick:()=>void H(),disabled:L.isPending,className:`flex items-center gap-1 px-2 py-1 text-[11px] rounded-md bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 border border-blue-500/30 disabled:opacity-50 transition-colors font-medium`,children:[L.isPending?a(m,{className:`w-3 h-3 animate-spin`}):a(w,{className:`w-3 h-3`}),L.isPending?h(`admin.system.addons.updating`,`Updating…`):h(`admin.system.addons.updateAll`,`Update All ({{nonSystemUpdateCount}})`,{nonSystemUpdateCount:k})]})]}),t(`div`,{className:`flex flex-wrap items-center gap-1.5`,role:`group`,"aria-label":h(`admin.system.addons.filterInstalledAddons`,`Filter installed addons`),children:[a(`span`,{className:`text-[10px] text-foreground-subtle`,children:h(`admin.system.addons.filter`,`Filter:`)}),[{id:`integrations`,label:h(`admin.system.addons.integrations`,`Integrations`),pressed:Q,toggle:()=>Je(!Q)},{id:`updatable`,label:h(`admin.system.addons.updatable`,`Updatable`),pressed:Ve,toggle:()=>Ye(!Ve)},{id:`error`,label:h(`admin.system.addons.inError`,`In error ({{count}})`,{count:Qe}),pressed:Ue,toggle:()=>Xe(!Ue)},{id:`npm`,label:`npm`,pressed:Z===`npm`,toggle:()=>Ze(Z===`npm`?null:`npm`)},{id:`dev`,label:h(`admin.system.addons.dev`,`Dev`),pressed:Z===`dev`,toggle:()=>Ze(Z===`dev`?null:`dev`)}].map(e=>a(N,{variant:`unstyled`,type:`button`,"aria-pressed":e.pressed,onClick:e.toggle,className:e.pressed?Ft:It,children:e.label},e.id))]}),t(`div`,{className:`flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-2`,children:[t(`div`,{className:`relative flex-1 min-w-0 sm:min-w-[200px]`,ref:E,children:[a(ge,{type:`text`,searchHotkey:!0,value:_,onChange:e=>{b(e.target.value),ne(!0)},onFocus:()=>ne(!0),placeholder:h(`admin.system.addons.searchAddonsOnNpm`,`Search addons on npm...`),"aria-label":h(`admin.system.addons.searchAddonsOnNpm2`,`Search addons on npm`),disabled:L.isPending,leftSlot:a(y,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),rightSlot:ye?a(m,{className:`h-3 w-3 animate-spin`}):void 0}),T&&I&&I.length>0&&t(`div`,{className:`absolute left-0 right-0 top-full mt-1 z-40 rounded-md border border-border bg-surface shadow-xl overflow-hidden`,children:[I.length>0&&a(`div`,{className:`px-3 py-1.5 text-[10px] uppercase tracking-wide text-foreground-subtle border-b border-border`,children:h(`systemPage.addons.npmResults`,{count:I.length})}),I&&I.length>0&&a(`div`,{className:`max-h-72 overflow-auto divide-y divide-border`,children:I.map(e=>a(Mt,{addon:e,installing:K.isPending,onInstall:e=>De({name:e.name,version:e.version,description:e.description})},e.name))})]})]}),a(yt,{onUploadSuccess:()=>{g.invalidateQueries({queryKey:[[`addons`]]}),f()}})]}),X&&t(`div`,{className:`flex items-center gap-2 px-2.5 py-1.5 rounded-md bg-primary/10 border border-primary/30 text-xs`,children:[a(`span`,{className:`text-foreground-subtle`,children:h(`admin.system.addons.filteringByCapability`,`Filtering by capability:`)}),a(`span`,{className:`font-mono text-primary font-semibold`,children:X}),a(N,{variant:`unstyled`,type:`button`,onClick:et,className:`ml-auto text-xs text-foreground-subtle hover:text-foreground underline`,children:h(`admin.system.addons.clear`,`Clear`)})]}),X&&a(Nt,{capability:X,installing:K.isPending,onInstall:e=>De({name:e.name,version:e.version,description:e.description})}),X&&$e.length>0&&a(`h2`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:h(`admin.system.addons.installed`,`Installed`)}),Se&&t(`div`,{className:`fixed top-[calc(env(safe-area-inset-top)+1rem)] right-[calc(env(safe-area-inset-right)+1rem)] z-50 flex items-start gap-2 px-3 py-2.5 rounded-md border border-green-500/30 bg-green-500/10 shadow-lg max-w-sm pointer-events-auto`,children:[a(v,{className:`w-4 h-4 shrink-0 mt-0.5 text-green-400`}),t(`div`,{children:[a(`div`,{className:`text-[11px] font-semibold text-foreground`,children:h(`admin.system.addons.bulkUpdateCompleted`,`Bulk update completed`)}),a(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:h(`admin.system.addons.systemPackagesUpdatedHubRestarted`,`System packages updated — hub restarted successfully.`)})]})]}),p===`pending`&&t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[a(m,{className:`h-3 w-3 animate-spin`}),h(`admin.system.addons.loadingInstalled`,`Loading installed addons…`)]}),p===`error`&&a(`div`,{className:`text-xs text-danger`,children:h(`admin.system.addons.failedToLoadAddons`,`Failed to load addons`)}),p===`ready`&&$e.length===0&&a(`div`,{className:`text-xs text-foreground-subtle`,children:c.length===0?h(`admin.system.addons.noAddonsInstalled`,`No addons installed`):X?h(`admin.system.addons.noInstalledAddonDeclaresThe`,`No installed addon declares the "{{capabilityFilter}}" capability. Any addon you can install appears under "Available to install" above.`,{capabilityFilter:X}):h(`admin.system.addons.noAddonsCompatibleWithPlacement`,`No addons compatible with {{name}} (placement filter active)`,{name:d.name})}),a(`div`,{className:`space-y-1.5`,children:p===`ready`&&nt.map(e=>{let t=$(e)?e.bundle.packageName:e.manifest.packageName,n=O.get(t),r=ie.get(t),i=$(e)?e.representative:e,o=n?e=>M.mutate({name:t,version:e,nodeId:d.id}):void 0,s=pe.get(t)??null,c=s!==null&&Ge(s);return a(_t,{addon:i,clusterStatus:u?.[i.manifest.id],bundle:$(e)?e.bundle:void 0,availableUpdate:n,...r===void 0?{}:{blockedUpdate:r},...r===void 0?{}:{onUpdateServer:()=>S(!0)},isUpdating:A.has(t)||c,jobProgress:s,onUpdate:o,disabledByBulk:L.isPending,selectedNode:d},$(e)?t:e.manifest.id)})}),U!==null&&a(kt,{target:U,installing:K.isPending,installError:G,onClose:()=>W(null),onInstall:(e,t)=>K.mutate({packageName:e,version:t})})]})}function Wt(){let{t:e}=q(),r=l(),{data:i}=j(void 0),{nodes:s}=B(),{selection:c,selectNode:u,requestedNodeId:d}=Ve(s.length>0?s:[Rt]),f=c.node??Rt,p=f.id,m=s.length>0?c.staleNodeId:null,{data:h,isLoading:g,isError:_}=Ee({nodeId:p}),v=H(),y=R(),b=v.isPending||y.isPending,x=async()=>{await v.mutateAsync({nodeId:p}),await y.mutateAsync(),r.invalidateQueries({queryKey:[[`addons`]]})},S=n(v);S.current=v;let ee=n(d??`hub`);o(()=>{S.current.mutate({nodeId:ee.current})},[]);let w=(h??[]).map(Vt).filter(e=>e!==null);return t(Fe,{children:[t(`div`,{className:`flex items-center justify-between gap-2 flex-wrap`,children:[a(G,{selectedNodeId:p,onSelect:u}),t(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[!g&&!_&&a(`span`,{className:`text-[10px] rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium`,children:e(`systemPage.addons.installedCount`,{count:w.length})}),t(N,{variant:`unstyled`,type:`button`,onClick:()=>void x(),disabled:b,className:`inline-flex items-center gap-1 px-2 py-1 text-[11px] rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors`,title:e(`admin.system.addons.reFetchAddonsCheckNpm`,`Re-fetch addons + check npm for new versions`),children:[a(C,{className:`w-3 h-3 ${b?`animate-spin`:``}`}),e(`admin.system.addons.checkForUpdates`,`Check for updates`)]})]})]}),a(X,{staleNodeId:m,shownNodeName:f.name}),a(jt,{selectedNode:f}),a(Ut,{addons:w,clusterStatus:i,selectedNode:f,onRefresh:()=>void x(),listPhase:g?`pending`:_?`error`:`ready`})]})}export{Wt as AddonsPage};
@@ -1 +1 @@
1
- import{S as e,x as t}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{ot as n}from"./src-5RckhTPX.js";function r({icon:r,title:i,subtitle:a,actions:o,nav:s,embedded:c=!1,children:l}){return c?e(t,{children:l}):e(n,{icon:r,title:i,subtitle:a,actions:o,nav:s,children:l})}export{r as t};
1
+ import{S as e,x as t}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{ot as n}from"./src-g2TJby3U.js";function r({icon:r,title:i,subtitle:a,actions:o,nav:s,embedded:c=!1,children:l}){return c?e(t,{children:l}):e(n,{icon:r,title:i,subtitle:a,actions:o,nav:s,children:l})}export{r as t};
@@ -1 +1 @@
1
- import{R as e,S as t,et as n}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{rt as r}from"./src-5RckhTPX.js";import{Qr as i}from"./index-BLPWUlRi.js";n();function a({paramName:n=`tab`,defaultSection:a,sections:o,...s}){let[c,l]=i(),u=a??o[0]?.id??``,d=c.get(n),f=o.some(e=>e.id===d)?d??u:u,p=e((e,t)=>{l(r=>{let i=new URLSearchParams(r);for(let e of t)i.delete(e);return i.set(n,e),i},{replace:!0})},[n,l]);return t(r,{...s,paramName:n,defaultSection:a,sections:o,activeSection:f,onSectionChange:p})}export{a as t};
1
+ import{R as e,S as t,et as n}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{rt as r}from"./src-g2TJby3U.js";import{Qr as i}from"./index-CxPpnulu.js";n();function a({paramName:n=`tab`,defaultSection:a,sections:o,...s}){let[c,l]=i(),u=a??o[0]?.id??``,d=c.get(n),f=o.some(e=>e.id===d)?d??u:u,p=e((e,t)=>{l(r=>{let i=new URLSearchParams(r);for(let e of t)i.delete(e);return i.set(n,e),i},{replace:!0})},[n,l]);return t(r,{...s,paramName:n,defaultSection:a,sections:o,activeSection:f,onSectionChange:p})}export{a as t};
@@ -0,0 +1,3 @@
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,Dr as f,G as p,Gi as m,L as h,Mn as g,Q as _,St as v,Yt as y,Zi as b,ci as x,cn as S,gt as C,jn as w,pn as T,qr as E,ut as D}from"./player-overlays-D-63t-DL.js";import{vi as O}from"./client-B60QT14E.js";import{n as k,t as A}from"./send-D_NAoo3n.js";import{t as j}from"./message-square-plus-_aGccjyj.js";import{Af as M,Ei as N,Gn as P,K as ee,Kn as F,Oi as I,Pi as L,Ti as R,Un as z,af as te,ei as B,ki as V,lt as H,mr as ne,of as re,qo as U,si as W,wi as G}from"./src-g2TJby3U.js";import{t as K}from"./i18n-CvWKDmFM.js";import{t as q}from"./useTranslation-BJr-n0es.js";import"./mount-CsHVNi49.js";import{Qr as J,X as Y,x as X}from"./index-CxPpnulu.js";import{t as Z}from"./AdminSectionedPage-BZZVpePX.js";import{t as ie}from"./AdminPage-DBIlGQcg.js";import{t as ae}from"./InstancesTable-CvfpkEKd.js";import{a as oe,c as se,d as ce,f as le,i as ue,l as de,n as fe,o as pe,p as me,r as he,s as ge,t as _e,u as ve}from"./ai-page.helpers-QIeUykiQ.js";c();function ye(){let{t}=q(),n=C(),r=R({functionCap:`llm`}).data??[],a=s({queryKey:fe,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(z,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${d} grid gap-4 sm:grid-cols-2`,children:he.map(({purpose:n,visionOnly:a})=>{let s=a?r.filter(de):r,u=c(n),d=r.find(e=>e.id===u);return e(`div`,{children:[i(ne,{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:ge(e)===``?e.name:`${e.name} · ${ge(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 K.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}=q(),l=C(),[d,p]=o(``),[m,h]=o(null),[_,v]=o(!1),y=s({queryKey:_e,queryFn:()=>l.trpcClient.llm.listModelCatalog.query({})}),b=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>l.trpcClient.llm.listNodeModels.query({nodeId:t})}),S=u({mutationFn:e=>l.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{h(e),v(!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:()=>{v(!0),b.refetch()}}),T=s({queryKey:ue,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=(y.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=m?.ok===!0?[{value:`custom`,label:`${m.label} · ${Q(m.totalBytes)}`}]:[];return[{value:``,label:c(`ai.selectModel`,`Select a model…`)},...e,...n,...r]},[y.data,b.data,m,t,c]),O=e=>{if(e===``){a(null);return}if(e===`custom`){if(m?.ok!==!0)return;a({model:m.model,modelId:m.label,supportsVision:m.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=y.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()!==``&&S.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(H,{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(H,{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(te,{"aria-label":c(`ai.hfTitle`,`Add a model from Hugging Face`),value:d,onChange:e=>p(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()===``||S.isPending,onClick:()=>k(),children:[S.isPending?i(f,{className:`h-3.5 w-3.5 animate-spin`}):i(g,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),S.isError&&i(N,{message:S.error instanceof Error?S.error.message:c(`common.error`,`Error`)}),m?.ok===!1&&i(N,{message:m.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(m.candidates??[]).map(e=>i(L,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;p(t),S.mutate({ref:t})},children:e},e)),m.requiredBytes!==void 0&&i(L,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>k(m.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:Q(m.requiredBytes)})})]})}),m?.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:m.label}),i(I,{variant:m.purpose===`vision`?`info`:`default`,children:m.purpose}),i(I,{variant:`default`,children:Q(m.totalBytes)})]}),m.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:m.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(L,{size:`sm`,type:`button`,disabled:w.isPending||_,onClick:()=>w.mutate(m.model),children:[w.isPending?i(f,{className:`h-3.5 w-3.5 animate-spin`}):i(x,{className:`h-3.5 w-3.5`}),_?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(N,{message:w.error instanceof Error?w.error.message:c(`common.error`,`Error`)})]})]})}function Ce({value:t,onChange:n}){let{t:r}=q(),a=C(),o=s({queryKey:ue,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(f,{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=pe(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(I,{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}=q(),d=C(),p=l(),m=s({queryKey:n(()=>[Y,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}}}),[h,g]=o({}),_=t({}),v=t(!1),y=u({mutationFn:e=>d.trpcClient.integrationInstances.updateInstance.mutate({addonId:a.addonId,id:a.id,values:e}),onSuccess:async()=>{await p.invalidateQueries({queryKey:[Y]}),await p.invalidateQueries({queryKey:[G]}),g({})}}),b=r(e=>{_.current={..._.current,...e},g(t=>({...t,...e})),!v.current&&(v.current=!0,queueMicrotask(()=>{let e=_.current;_.current={},v.current=!1,y.mutate(e)}))},[y]),x=m.data?.description.kinds?.find(e=>e.id===a.kindId),S=m.data?.instance?.formValues,w=n(()=>({...S,...h}),[S,h]),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(m.isPending)return null;if(m.isError)return i(N,{variant:`warning`,message:m.error.message});let j=A.data?.ok===!0?A.data.models:[],M=A.data?.ok===!1?A.data:null,P=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(N,{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(H,{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(f,{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=>P(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})]}),y.isError&&i(N,{variant:`warning`,message:y.error.message})]})}c();var Ae=5e3;function je(e){return K.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function Me(){let{t}=q(),r=C(),a=s({queryKey:ue,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(I,{variant:me(n),children:t(le(n))}),n.status?.downloadProgress!==void 0&&i(I,{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=ce(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(I,{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(z,{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(V,{className:`h-8 w-full`}),i(V,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:d,children:i(N,{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:w,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:F})})}var Ne=_(`/addon/ai/test-chat`),Pe=_(`/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:K.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 K.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return K.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?K.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):K.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return K.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}=q();C();let[c,l]=o(``),[u,f]=o(``),[p,g]=o(``),[_,x]=o([]),[w,T]=o(null),[E,O]=o(`none`),[k,M]=o(`throwaway`),[P,F]=o(null),[I,B]=o([]),[V,H]=o(null),[U,W]=o(null),G=t(null);a(()=>()=>G.current?.abort(),[]);let K=r(async()=>{let e=await fetch(Pe,{credentials:`same-origin`});e.ok&&B((await e.json()).chats??[])},[]);a(()=>{k===`persistent`&&K()},[k,K]);let J=R({functionCap:`llm`}),Y=n(()=>(J.data??[]).filter(e=>e.enabled),[J.data]),X=Y.find(e=>e.id===c)??null,Z=U!==null,ie=r(async(e,t)=>{let n=new AbortController;G.current=n,H(null);let r=Ie(X===null?{}:ve(X));W({...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,...P===null?{}:{conversationId:P}}:{}})});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`:W(t=>({...t??Ze,phase:e.phase}));break;case`meta`:a=e.mediaSent,o=e.model,W(t=>({...t??Ze,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:i+=e.text,W(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||H(e instanceof Error?e.message:s(`common.error`,`Error`))}finally{G.current=null,W(null)}f!==void 0&&(F(f),K());let p=n.signal.aborted&&i.length>0;l===null&&i.length===0&&!p||x(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,P,X,c,K,u,s]),ae=r(()=>{let e=p.trim();if(e===``||c===``||Z)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...w===null?{}:{attachmentLabel:w.label,attachmentKind:w.ref.kind}},n=[..._,t];x(n),g(``);let r=w?.ref;T(null),O(`none`),ie(k===`persistent`&&P!==null?[{role:`user`,content:e}]:He(n),r)},[k,P,p,w,c,ie,Z,_]),oe=()=>G.current?.abort(),se=()=>{G.current?.abort(),x([]),T(null),g(``),H(null),W(null),F(null)},ce=async e=>{G.current?.abort();let t=await fetch(`${Pe}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();F(e),x(We(n)),W(null),H(null)};return e(`div`,{className:h,children:[i(z,{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(ne,{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…`)},...Y.map(e=>({value:e.id,label:`${e.name} · ${ge(e)}${de(e)?` · vision`:``}`}))]}),Y.length===0&&!J.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(ne,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:s(`ai.systemPrompt`,`System prompt (optional)`)}),i(te,{id:`ai-test-system`,value:u,onChange:e=>f(e.target.value),placeholder:s(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),i(ee,{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`&&F(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:se,children:[i(j,{className:`h-3.5 w-3.5`}),s(`ai.newChat`,`New chat`)]}),I.length>0&&i(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:I.map(e=>i(`button`,{type:`button`,onClick:()=>void ce(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-xs hover:bg-surface-hover ${e.id===P?`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.`)}),X!==null&&!de(X)&&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.`)})]})}),V!==null&&i(N,{title:s(`ai.chatFailed`,`The test call failed`),message:V}),e(z,{headingId:`ai-test-conversation`,title:s(`ai.testConversation`,`Conversation`),actions:e(L,{size:`sm`,variant:`ghost`,type:`button`,disabled:_.length===0&&w===null,onClick:se,children:[i(y,{className:`h-3.5 w-3.5`}),s(`ai.clearChat`,`Clear`)]}),children:[i($e,{turns:_,live:U}),e(`div`,{className:`${d} space-y-2 border-t border-border`,children:[w!==null&&e(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-background px-2.5 py-1.5`,children:[w.ref.kind===`snapshot`?i(m,{className:`h-3.5 w-3.5 text-foreground-subtle`}):i(b,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:w.label}),i(re,{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(m,{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(b,{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(te,{value:p,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ae())},placeholder:s(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":s(`ai.message`,`Message`)}),Z?e(L,{size:`sm`,variant:`secondary`,type:`button`,onClick:oe,children:[i(S,{className:`h-3.5 w-3.5`}),s(`ai.stop`,`Stop`)]}):e(L,{size:`sm`,type:`button`,disabled:p.trim()===``||c===``,onClick:ae,children:[i(A,{className:`h-3.5 w-3.5`}),s(`ai.send`,`Send`)]})]})]})]})]})}function $e({turns:t,live:n}){let{t:r}=q();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(f,{className:`h-3.5 w-3.5 animate-spin`}),Ke(n.phase,n.firstTokenTimeoutMs)]})]})]})}function et({turn:t,streaming:n=!1}){let{t:r}=q(),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(b,{className:`h-3 w-3`}):i(m,{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(m,{className:`h-3 w-3`}):i(b,{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}=q(),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}=q(),n=U({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?i(f,{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}=q(),a=W(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(I,{variant:`warning`,children:r(`common.off`)}),i(`span`,{className:`truncate text-[10px] text-foreground`,children:a})]})]})}function it({onPick:t}){let{t:r}=q(),a=C(),o=U({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(f,{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(b,{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}=q(),r=C(),[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:[...oe,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(z,{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(V,{className:`h-8 w-full`}),i(V,{className:`h-8 w-full`}),i(V,{className:`h-8 w-full`})]}):f.isError?i(`div`,{className:d,children:i(N,{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:E,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:F})})}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}=q(),t=M(ct),[n]=J(),r=X(`/system/ai`,{t:e,isAdmin:!0})??{icon:T,title:e(`system.ai`,`AI`)};if(t!==`present`)return i(ie,{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(Z,{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,ge)??``,r=t=>pt(t,e,de)??!1,a=t=>pt(t,e,se)??``;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(I,{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}=q(),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:h,children:[i(ye,{}),i(ae,{functionCap:ct,icon:T,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}=q();return t===`pending`?e(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[i(V,{className:`h-8 w-64`}),i(V,{className:`h-40 w-full`})]}):t===`unknown`?i(N,{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:T,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 +1 @@
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{t as o}from"./useTranslation-BJr-n0es.js";import{F as s,P as c,_ as l,dt as u,g as d}from"./index-BLPWUlRi.js";import{n as f}from"./NodeAddonsSettingsPanel-CzinR980.js";a();function p(e,t){if(e.type===`group`){for(let n of e.fields)p(n,t);return}if(e.type===`sub-tabs`){for(let n of e.tabs)for(let e of n.fields)p(e,t);return}`value`in e&&(t[e.key]=e.value)}function m(e){let t={};for(let n of e.sections)for(let e of n.fields)p(e,t);return t}var h=`system-config-auth`;function g({sectionIds:e,omitSectionIds:n,hideSectionChrome:i,emptyMessage:a}){let o=d(),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)===!0||e===void 0&&t.id===`system-config-auth`));return{...o.data,sections:f(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(_,{schema:s})}function _({schema:a}){let{t:d}=o(),f=l(),[p,h]=i(null),g=t(()=>m(a),[a]),_=n(async e=>{h(null);try{await f.mutateAsync({patch:e})}catch(e){throw h(e instanceof Error&&e.message.length>0?e.message:d(`system.bootstrapForm.saveFailed`,`Could not save`)),e}},[f,d]),v=s({schema:a,serverValues:g,onImmediateSave:e=>void _(e).catch(()=>void 0),onDeferredSave:_});return e(`div`,{className:`flex flex-col gap-3`,children:[p!==null&&r(`div`,{role:`alert`,className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:p}),r(u,{schema:a,values:v.values,onChange:v.handleChange,disabled:f.isPending}),r(c,{pendingCount:v.pendingKeys.length,onSave:()=>v.handleSave(v.pendingKeys),onDiscard:()=>v.handleDiscard(v.pendingKeys),saving:f.isPending})]})}export{h as n,g as t};
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{t as o}from"./useTranslation-BJr-n0es.js";import{F as s,P as c,_ as l,dt as u,g as d}from"./index-CxPpnulu.js";import{n as f}from"./NodeAddonsSettingsPanel-CieUBerm.js";a();function p(e,t){if(e.type===`group`){for(let n of e.fields)p(n,t);return}if(e.type===`sub-tabs`){for(let n of e.tabs)for(let e of n.fields)p(e,t);return}`value`in e&&(t[e.key]=e.value)}function m(e){let t={};for(let n of e.sections)for(let e of n.fields)p(e,t);return t}var h=`system-config-auth`;function g({sectionIds:e,omitSectionIds:n,hideSectionChrome:i,emptyMessage:a}){let o=d(),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)===!0||e===void 0&&t.id===`system-config-auth`));return{...o.data,sections:f(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(_,{schema:s})}function _({schema:a}){let{t:d}=o(),f=l(),[p,h]=i(null),g=t(()=>m(a),[a]),_=n(async e=>{h(null);try{await f.mutateAsync({patch:e})}catch(e){throw h(e instanceof Error&&e.message.length>0?e.message:d(`system.bootstrapForm.saveFailed`,`Could not save`)),e}},[f,d]),v=s({schema:a,serverValues:g,onImmediateSave:e=>void _(e).catch(()=>void 0),onDeferredSave:_});return e(`div`,{className:`flex flex-col gap-3`,children:[p!==null&&r(`div`,{role:`alert`,className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:p}),r(u,{schema:a,values:v.values,onChange:v.handleChange,disabled:f.isPending}),r(c,{pendingCount:v.pendingKeys.length,onSave:()=>v.handleSave(v.pendingKeys),onDiscard:()=>v.handleDiscard(v.pendingKeys),saving:f.isPending})]})}export{h as n,g as t};
@@ -0,0 +1,39 @@
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{$n as m,Dr as h,Ki as g,Kt as _,Ma as v,Mi as y,Nn as b,Qn as x,Ri as S,Ur as C,Yt as w,ct as T,gt as E,ir as D,kr as O,ut as k,wt as A,zn as j}from"./player-overlays-D-63t-DL.js";import{Ji as M,Ki as N,La as P,Na as F,Nr as I,So as L,Va as R,Yi as z,_o as B,ao as V,as as H,go as U,ho as ee,ia as te,la as ne,mr as re,oo as W,wo as ie,xo as ae,yo as oe,za as se}from"./client-B60QT14E.js";import{t as ce}from"./chevron-down-CBb-F8DT.js";import{t as le}from"./boxes-k5PsZ3NR.js";import{c as ue}from"./video-BV-3O_ZC.js";import{n as de,t as fe}from"./variable-IcIR23WN.js";import{Br as G,Bu as pe,Ei as K,En as me,Gi as he,Gn as q,Gr as ge,Gu as _e,Hi as ve,Hr as ye,Hu as be,It as xe,Ki as Se,Kn as Ce,Kr as we,Ku as Te,Of as Ee,Oi as J,Pi as Y,Ui as De,Un as Oe,Ur as ke,Uu as Ae,Vu as je,Wn as Me,Wr as Ne,Wu as Pe,Yi as Fe,Yr as Ie,af as X,ai as Le,b as Re,bd as ze,ci as Be,cr as Ve,do as He,dr as Ue,ef as We,ei as Ge,es as Ke,fo as qe,gs as Je,io as Ye,ki as Xe,lo as Ze,lr as Qe,no as $e,nt as et,po as tt,qi as nt,qo as rt,ro as it,so as at,sr as ot,st,tt as ct,ur as lt,wn as ut,yn as dt,zn as ft,zu as pt}from"./src-g2TJby3U.js";import{t as Z}from"./i18n-CvWKDmFM.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import{H as mt,Kr as ht,Qr as gt,Xr as _t,ct as vt,dt as yt,m as bt,p as xt,qr as St,x as Ct}from"./index-CxPpnulu.js";import{t as wt}from"./AdminSectionedPage-BZZVpePX.js";import{n as Tt}from"./format-hVW7RBVv.js";import{C as Et,a as Dt,at as Ot,b as kt,g as At,i as jt,lt as Mt,n as Nt,nt as Pt,o as Ft,r as It,w as Lt,y as Rt}from"./CompositionBlockEditor-C76eQ7Js.js";import{A as zt,C as Bt,D as Vt,E as Ht,F as Ut,M as Wt,O as Gt,P as Kt,S as qt,T as Jt,_ as Yt,a as Xt,b as Zt,c as Qt,d as $t,f as en,g as tn,h as nn,i as rn,j as an,k as on,l as sn,m as cn,n as ln,o as un,p as dn,r as fn,s as pn,t as mn,u as hn,v as gn,w as _n,x as vn,y as yn}from"./create-composition-B7qf5-qP.js";import{a as bn,i as xn,n as Sn,o as Cn,r as wn,s as Tn}from"./action-draft-Dg61GkLS.js";var En=`const AUTOMATION_RECIPE =`,Dn=`// 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 On(e){return e.includes(En)}function kn(e){let t=e.indexOf(En);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 An(e){let t=kn(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=B.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 jn(e){let t=kn(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)}${Dn}${e.slice(i)}`}u();function Mn(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function Nn(e,t){return U(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.hintKey??e.name}`,e.description)}))}function Pn(e){return e.some(e=>e.required===!0&&e.default===void 0)}function Fn(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function In(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function Ln(e,t){return e.filter(e=>e.required===!0&&!In(t[e.name])).map(e=>e.name)}function Rn(e,t){let n={};for(let r of e){let e=t[r.name];In(e)&&(n[r.name]=e)}return n}function zn({variable:e,value:t,onChange:n}){let{t:r}=Q(),i=e.label??e.name;return e.type===`number`?o(Ut,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?o(Kt,{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(Kt,{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 Bn({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:s}=Q(),[l,u]=c(()=>Fn(n)),d=Ln(n,l);return o(G,{open:!0,onOpenChange:e=>!e&&a(),children:e(ye,{"aria-label":s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(ge,{children:[o(we,{children:s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),o(ke,{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(zn,{variable:t,value:l[t.name],onChange:e=>u({...l,[t.name]:e})})]},t.name))}),e(Ne,{className:`flex flex-wrap gap-2`,children:[o(Y,{variant:`ghost`,onClick:a,children:s(`common.cancel`,`Cancel`)}),e(Y,{disabled:r||d.length>0,onClick:()=>i(Rn(n,l)),children:[r?o(h,{className:`h-4 w-4 animate-spin`}):o(m,{className:`h-4 w-4`}),` `,s(`actions.editor.runNow`,`Run now`)]})]})]})})}var Vn=[`number`,`string`,`boolean`,`select`];function Hn(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function Un(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 Wn(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function Gn(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function Kn({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(Oe,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:fe,actions:e(Y,{variant:`outline`,size:`sm`,onClick:()=>n([...t,bn(t)]),children:[o(x,{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":!xn(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,Gn(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(Kt,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:Vn.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=Vn.find(t=>t===e.target.value);t!==void 0&&s(l,Hn(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(qn,{variable:c,onChange:e=>s(l,Wn(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,Un(c,e.target.value))})]}),o(Y,{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 qn({variable:e,onChange:t}){let{t:n}=Q(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(Ut,{"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(Kt,{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 Jn=5e3;function Yn(e){return e.kind===`cap`||e.kind===`wait`}function Xn(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 Qn({entry:t,onClose:i,onSaved:a,preset:l=null}){let{t:u}=Q(),f=d(),g=T(),_=Bt(),v=Zn(),[y,b]=c(()=>wn(t)),x=n(!1);s(()=>{if(t!==null||l!==`trigger-alarm`||x.current)return;let e=_.find(e=>e.type===H.AlarmPanel);e!==void 0&&(x.current=!0,b(Tn(e.id,u(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[_,t,l,u]);let[S,C]=c(null),[E,D]=c(!1),k=t!==null&&t.readOnly,A=()=>{f.invalidateQueries({queryKey:[[`actions`]]})},j=ve({onSuccess:e=>{A(),a(e.action.id)}}),M=Fe({onSuccess:A}),N=De({onSuccess:()=>{A(),i()}}),P=nt({onSuccess:A}),F=he({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Jn}),I=F.data?.traces.find(e=>e.runId===S)??null,L=r(()=>I===null?null:an(I),[I]),R=r(()=>I===null?null:zt(I).steps,[I]),z=Sn(y),B=r(()=>Mn(y.variables,u),[y.variables,u]),V=j.isPending||M.isPending,U=j.error??M.error??N.error??P.error,ee=Pn(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(O,{className:`h-4 w-4 text-foreground-muted`}),o(X,{"aria-label":u(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:y.name,disabled:k,placeholder:u(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>b({...y,name:e.target.value})}),o(J,{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(Kn,{variables:y.variables,onChange:e=>b({...y,variables:e}),onRename:(e,t)=>b(Cn(y,e,t))}),o(Gt,{step:`steps`,title:u(`actions.editor.steps`,`Steps`),trace:L===null?null:L.thenBlock,children:o(fn,{actions:y.steps,devices:_,allowedKinds:[`cap`,`wait`],stepTones:L===null?void 0:y.steps.map((e,t)=>on(L,t)??`idle`),stepResults:R===null?void 0:y.steps.map((e,t)=>R.find(e=>e.index===t)),variables:B,onChange:e=>b({...y,steps:e.filter(Yn)})})})]}),!z.ok&&!k&&y.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:v(z.reason)}),U!==null&&o(K,{message:Xn(U)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!k&&e(Y,{onClick:()=>{z.ok&&(t===null?j.mutate({action:z.input}):M.mutate({actionId:t.id,action:z.input}))},disabled:V||!z.ok,children:[V&&o(h,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),t!==null&&e(Y,{variant:`outline`,disabled:P.isPending,onClick:()=>ee?D(!0):P.mutate({actionId:t.id}),children:[o(m,{className:`h-4 w-4`}),` `,u(`actions.editor.runNow`,`Run now`)]}),t!==null&&!k&&e(Y,{variant:`ghost`,disabled:N.isPending,onClick:()=>{g({title:u(`actions.editor.deleteTitle`,`Delete this action?`),message:u(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:u(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&N.mutate({actionId:t.id})})},children:[o(w,{className:`h-4 w-4`}),` `,u(`common.delete`,`Delete`)]}),o(Y,{variant:`ghost`,onClick:i,children:u(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Vt,{traces:t===null?[]:F.data?.traces,selectedId:S,onSelect:C})}),E&&t!==null&&o(Bn,{actionName:t.name,variables:t.variables??[],running:P.isPending,onCancel:()=>D(!1),onRun:e=>{P.mutate({actionId:t.id,variables:e}),D(!1)}})]})}u();var $n=5e3;function er(e){return e instanceof Error?e.message:String(e)}function tr(){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 nr({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),[a]=gt(),c=d(),l=tr(),{state:u,openNew:f,openEdit:h,close:g}=ct({editKey:`action`,newKey:`new`}),_=Se({},{refetchInterval:$n}),v=nt({onSuccess:()=>void c.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(f(),n?.())},[t,n,f]);let y=_.data??[],b=u.mode===`edit`?y.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(J,{variant:`info`,children:e.addonId}):o(J,{variant:`primary`,children:i(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:i(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?o(`span`,{className:`text-foreground-subtle`,children:`-`}):Tt(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:i(`actions.list.status`,`Status`),render:e=>{let t=l(e);return o(`span`,{title:e.status.lastError??void 0,children:o(J,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(Y,{variant:`outline`,size:`sm`,disabled:v.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),v.mutate({actionId:t.id})},children:[o(m,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[v,l,i]);return u.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),v.error!=null&&o(K,{message:er(v.error)}),_.data===void 0?_.error==null?o(Xe,{className:`h-24 w-full`}):o(K,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:er(_.error),onRetry:()=>void _.refetch()}):y.length===0?o(Ge,{icon:O,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(Y,{onClick:f,children:[o(x,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(p,{children:[_.error!=null&&o(K,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:er(_.error),onRetry:()=>void _.refetch()}),o(q,{columns:S,rows:y,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ce,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>h(e.id)})]})]}):o(Qn,{entry:b,onClose:g,onSaved:h,preset:u.mode===`new`?a.get(`preset`):null},b?.id??`new`)}u();function rr({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(Y,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?ce:S,{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(Y,{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(ue,{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(ft,{maxHeight:420,children:t})})]})}var ir=[`single`,`restart`,`queued`,`parallel`,`cooldown`],ar=2,or=30;function sr(e){return e.runMode??{mode:`single`}}function cr(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function lr(e){switch(e){case`queued`:return{mode:`queued`,max:ar};case`parallel`:return{mode:`parallel`,max:ar};case`cooldown`:return{mode:`cooldown`,minutes:or};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function ur(e){return ir.find(t=>t===e)??`single`}function dr({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(Kt,{widthClass:`w-56`,value:t.mode,options:ir.map(e=>({value:e,label:i[e]})),onChange:e=>n(lr(ur(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(Ut,{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(Ut,{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 fr;function pr(){return fr??=W(I),fr}function mr(e,t=pr()){return V(e,t)}u();var hr=`hub`,gr=5e3;function _r({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??``),[g,_]=c(()=>Xt(n)),v=e=>_(qt(e)),[y,x]=c(!1),[S,C]=c(null),w=at({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:gr}),T=w.data?.traces.find(e=>e.runId===S)??null,E=r(()=>T===null?null:an(T),[T]),D=r(()=>Nn(g.when,f),[g.when,f]),O=r(()=>T===null?null:Wt(T),[T]),k=r(()=>T===null?null:zt(T).steps,[T]),A=Bt(),j=oe(g),M=r(()=>vr(g),[g]),P=r(()=>yr(p.trim()===``?`Untitled automation`:p.trim(),g),[p,g]),F=ze().data,I=r(()=>M===null?un(g,F):null,[g,F,M]),L=p.trim()===``,R=L||j!==null||M!==null||I!==null||P.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[o(vn,{when:g.when,children:e(`div`,{className:`space-y-4`,children:[e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(X,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Gt,{step:`when`,title:f(`automation.automationEditor.when`,`When`),trace:E===null?null:E.when,children:o(rn,{recipe:g,devices:A,run:O,onChange:v})}),o(Gt,{step:`then`,title:f(`automation.automationEditor.then`,`Then`),trace:E===null?null:E.thenBlock,hint:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(fn,{actions:g.actions,devices:A,variables:D,stepTones:E===null?void 0:g.actions.map((e,t)=>on(E,t)??`idle`),stepResults:k===null?void 0:g.actions.map((e,t)=>k.find(e=>e.index===t)),onChange:e=>v(Ht(g,e))})}),o(Gt,{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(dr,{value:sr(g),onChange:e=>v(cr(g,e))})}),o(rr,{code:P.code,error:P.error,canEject:t!==null,ejecting:s,onEject:u}),j!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:j}),j===null&&M!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:M}),j===null&&I!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`automation-site-error`,children:I}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(Y,{onClick:()=>{P.code!==null&&l({name:p.trim(),code:P.code,enabled:t?.enabled??!0,placement:hr})},disabled:i||R,children:[i&&o(h,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(Y,{variant:`ghost`,onClick:()=>x(!y),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,"aria-expanded":y,children:[o(b,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,o(We,{expanded:y})]}),o(Y,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),L&&o(J,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),y&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(ht,{i18nKey:`common.logsOf`,values:{id:N(t.id)},components:{code:o(`code`,{})}})}),o(ut,{addonId:N(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}),o(`div`,{className:`order-first lg:order-last`,children:o(Vt,{traces:t===null?[]:w.data?.traces,selectedId:S,onSelect:C})})]})}function vr(e){let t=B.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 yr(e,t){let n=mr(t);if(!n.ok)return{code:null,error:n.error};try{return{code:ee({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function br(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 xr(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Sr(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Cr(e){let t=e=>{let t=br(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 wr(e){if(e.length===0)return Z.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>br(e).tone===`error`).length,n=e.filter(e=>br(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 Tr=3e4;function Er({block:t,logsOpen:n,unreadable:r}){let i=v(),{t:a}=Q(),s=br(t),c=xe(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(J,{variant:xr(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(ht,{i18nKey:`common.logsOf`,values:{id:N(t.id)},components:{code:o(`code`,{})}})}),o(ut,{addonId:N(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var Dr=2;function Or(e){let t=[];if(L(e.when,e=>{ie(e)&&t.push(Jt(e.kind))}),t.length===0)return ae(e.when)===0?``:Z.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,Dr).join(`, `),i=n.length-Dr;return i>0?`${r} +${i}`:r}function kr({recipe:e}){let{t}=Q();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=Or(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function Ar({blockId:t}){let{t:n}=Q(),r=at({blockId:t},{refetchInterval:Tr});if(r.data===void 0)return r.error===null||r.error===void 0?o(Xe,{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:[Tt(i.lastAt),a&&o(J,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function jr({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(Ue,{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 Mr({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(dt,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:D,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:m,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:b,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:w,danger:!0,separatorBefore:!0,onClick:r}]})})}function Nr({onCreate:t}){let{t:n}=Q();return o(Ge,{icon:A,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(Y,{onClick:t,"data-testid":`automation-empty-new`,children:[o(x,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();var Pr=[`coreBlocks`,`list`],Fr=5e3;function Ir(e){return e instanceof Error?e.message:String(e)}function Lr({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:a}=Q(),u=E(),{state:d,openNew:p,openEdit:m,close:h}=ct({editKey:`block`,newKey:`new`}),g=T(),[_,v]=c(null),y=d.mode!==`closed`;s(()=>{n&&(p(),i?.())},[n,i,p]);let b=l({queryKey:Pr,refetchInterval:Fr,queryFn:async()=>(await u.trpcClient.coreBlocks.list.query({})).blocks}),x=()=>{b.refetch()},S=e=>{h(),x(),vt({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)}),D=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:jn(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=Cr((j??[]).filter(e=>On(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:An(P.code),L=C.error===null?w.error===null?k.error===null?null:Ir(k.error):Ir(w.error):Ir(C.error),R=r(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=An(e.code);return o(Er,{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=An(e.code);return o(kr,{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(Ar,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>o(jr,{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=An(e.code);return o(Mr,{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&&D.mutate(e.id)})}})}}],[g,_,m,D,O,a]);return y?d.mode===`edit`&&P===null?o(Xe,{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(_r,{existing:P,initialRecipe:I!==null&&I.ok?I.recipe:_n,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`),D.error!=null&&o(K,{message:Ir(D.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:j===void 0?``:wr(M)}),b.error!=null&&o(K,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Ir(b.error),onRetry:x}),N?o(Nr,{onCreate:p}):o(q,{columns:R,rows:M,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ce,emptyMessage:j===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>m(e.id)}),D.error!=null&&o(K,{message:Ir(D.error)}),O.error!=null&&o(K,{message:Ir(O.error)})]})}var Rr={kind:`all`,children:[]};function zr({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(Ue,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?Rr: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(rn,{recipe:s,devices:n,onChange:e=>i(e.when)})]})]})}var Br=[`sunrise`,`sunset`,`dawn`,`dusk`],Vr=6e4;function Hr(e){return e.kind===`cap`||e.kind===`wait`}function Ur(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 Wr({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`?Yt(u,r,i):null,f=gn(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(Ur(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:sn(u.hh,u.mm),onChange:e=>{let t=tn(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:Br.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Br.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(Ut,{"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:dn(d),zone:r.timeZone})})]}),e(Y,{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(fn,{actions:t.steps,devices:n,allowedKinds:[`cap`,`wait`],onChange:e=>s({...t,steps:e.filter(Hr)})}),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*Vr}:{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(Ut,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:m.graceMs/Vr,onValue:e=>{e!==null&&s({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*Vr))}})}})]})]}),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 Gr=5e3,Kr=600,qr=6e4,Jr={timeZone:`UTC`,location:null};function Yr(e){return e instanceof Error?e.message:String(e)}function Xr(e){if(e===null)return $t();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function Zr(e,t){let[n,r]=c(e);return s(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Qr(e,t){return t(`schedulers.day.${e}`,e)}function $r({entry:t,onClose:n,onSaved:i}){let{t:a}=Q(),s=d(),l=T(),u=Bt(),f=ze(),p=f.data??Jr,[m,_]=c(()=>Xr(t)),[v,y]=c(()=>m.profiles[0]?.id??``),[b,S]=c(null),[C,E]=c(null),D=()=>{s.invalidateQueries({queryKey:[[`schedulers`]]})},O=pe({onSuccess:e=>{D(),i(e.scheduler.id)}}),k=Te({onSuccess:D}),A=je({onSuccess:()=>{D(),n()}}),j=Ae({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:Gr}),M=r(()=>Qt(m,p),[m,p]),N=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),P=Zr(M.ok?M.input:null,Kr),F=pt(P===null?{scheduler:m}:t===null?{scheduler:P}:{scheduler:P,schedulerId:t.id},{enabled:P!==null&&N&&f.data!==void 0}),I=m.profiles.find(e=>e.id===v)??m.profiles[0],L=I===void 0?-1:m.profiles.indexOf(I),R=Zt(p),z=I?.points.find(e=>e.id===b)??null,B=I===void 0||z===null?-1:I.points.indexOf(z),V=M.ok?[]:M.issues,H=e=>V.filter(t=>t.path===e||t.path.startsWith(`${e}.`)),U=e=>_({...m,profiles:m.profiles.map((t,n)=>n===L?e:t)}),ee=e=>{I!==void 0&&U({...I,points:I.points.map(t=>t.id===e.id?e:t)})},te=r(()=>I===void 0?[]:I.points.flatMap(e=>{let t=Yt(e.at,p,R);if(t===null)return[];let n=e.at.kind===`sun`?`${a(`schedulers.sun.${e.at.event}`,e.at.event)} ${e.at.offsetMin>=0?`+`:``}${String(e.at.offsetMin)} (${dn(t)})`:sn(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`&&gn(e.at,p,R)!==null}]}),[I,p,R,a]),ne=r(()=>I===void 0?[]:en(I.points,p,R),[I,p,R]),re=(e,t)=>{let n=I?.points.find(t=>t.id===e);n!==void 0&&ee({...n,at:yn(n.at,t,gn(n.at,p,R))})},W=e=>{if(I===void 0)return;let t=nn(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));U({...I,points:[...I.points,cn(e,t,720)]}),S(t)},ie=()=>{let e=nn(`profile`,m.profiles.map(e=>e.id));_({...m,profiles:[...m.profiles,hn(e,a(`schedulers.profile.newName`,`New profile`))]}),y(e),S(null)},ae=O.isPending||k.isPending,oe=O.error??k.error??A.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(g,{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=>_({...m,name:e.target.value})})]}),e(Oe,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[o(Me,{label:a(`schedulers.editor.enabled`,`Enabled`),children:o(Ue,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>_({...m,enabled:e})})}),o(Me,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:o(Ut,{"aria-label":a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),className:`w-24`,value:m.priority,onValue:e=>{e!==null&&_({...m,priority:Math.round(e)})}})}),o(Me,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:o(Ut,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/qr,onValue:e=>{e!==null&&_({...m,maxLateMs:Math.round(e*qr)})}})})]}),e(`div`,{className:`p-3`,children:[o(zr,{value:m.activeWhen,devices:u,label:a(`schedulers.editor.activeWhen`,`Only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=m;_(e===void 0?n:{...n,activeWhen:e})}}),H(`activeWhen`).map(e=>o(`p`,{className:`mt-1 text-xs text-warning`,children:e.message},e.message))]})]}),o(Oe,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(Y,{variant:`outline`,size:`sm`,onClick:ie,children:[o(x,{className:`h-4 w-4`}),` `,a(`schedulers.profile.add`,`Add profile`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.profile.hint`,`Each day, the first profile in this order whose days and condition hold is the one that runs.`)}),I!==void 0&&e(ot,{value:I.id,onValueChange:e=>{y(e),S(null)},appearance:`pills`,children:[o(Qe,{children:m.profiles.map(e=>o(lt,{value:e.id,children:e.name},e.id))}),e(Ve,{value:I.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:I.name,onChange:e=>U({...I,name:e.target.value})}),o(Ue,{checked:I.enabled,label:a(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>U({...I,enabled:e})}),m.profiles.length>1&&e(Y,{variant:`ghost`,size:`sm`,onClick:()=>{_({...m,profiles:m.profiles.filter(e=>e.id!==I.id)}),y(``),S(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:pn.map(e=>{let t=I.days.includes(e);return o(Y,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>U({...I,days:t?I.days.filter(t=>t!==e):pn.filter(t=>t===e||I.days.includes(t))}),children:Qr(e,a)},e)})}),H(`profiles.${String(L)}.days`).map(e=>o(`p`,{className:`text-xs text-warning`,children:a(`schedulers.profile.daysNeeded`,`Pick at least one day.`)},e.message)),o(zr,{value:I.activeWhen,devices:u,label:a(`schedulers.profile.activeWhen`,`This profile only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=I;U(e===void 0?n:{...n,activeWhen:e})}}),o(Re,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:te,bands:ne,selectedId:b,onSelect:S,onMove:re}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(Y,{variant:`outline`,size:`sm`,onClick:()=>W(`edge`),children:[o(x,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(Y,{variant:`outline`,size:`sm`,onClick:()=>W(`hold`),children:[o(x,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(Y,{variant:`outline`,size:`sm`,onClick:()=>W(`release`),children:[o(x,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),o(J,{variant:`neutral`,children:p.timeZone})]}),I.points.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.timeline.empty`,`Add a point to place something on the day.`)}),z!==null&&o(Wr,{point:z,devices:u,site:p,localDate:R,issues:H(`profiles.${String(L)}.points.${String(B)}`),onChange:ee,onRemove:()=>{U({...I,points:I.points.filter(e=>e.id!==z.id)}),S(null)}},z.id)]})]})]})}),F.data!==void 0&&F.data.conflicts.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:F.data.conflicts.map(e=>o(`li`,{children:a(`schedulers.conflict.message`,`{{other}} wants device {{device}} in another state from {{from}} to {{to}} ({{winner}}).`,{other:e.other.schedulerName,device:e.deviceId,from:dn(e.fromMinute),to:dn(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)}`))}),!M.ok&&m.name!==``&&V.length>0&&z===null&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:V.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))}),oe!==null&&o(K,{message:Yr(oe)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(Y,{onClick:()=>{M.ok&&(t===null?O.mutate({scheduler:M.input}):k.mutate({schedulerId:t.id,scheduler:M.input}))},disabled:ae||!M.ok||f.data===void 0,children:[ae&&o(h,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(Y,{variant:`ghost`,disabled:A.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&&A.mutate({schedulerId:t.id})})},children:[o(w,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(Y,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Vt,{traces:t===null?[]:j.data?.traces,selectedId:C,onSelect:E})})]})}u();var ei=5e3;function ti(e){return e instanceof Error?e.message:String(e)}function ni({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Q(),a=d(),{state:c,openNew:l,openEdit:u,close:f}=ct({editKey:`scheduler`,newKey:`new`}),p=Pe({},{refetchInterval:ei}),m=be({},{refetchInterval:ei}),h=_e({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(Ue,{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(J,{variant:t.variant,children:t.label})},notSortableReason:i(`schedulers.list.statusNotSortable`,`Derived from the live hold`)},{key:`updated`,header:i(`schedulers.list.updated`,`Updated`),render:e=>Tt(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(K,{message:ti(h.error)}),p.data===void 0?p.error==null?o(Xe,{className:`h-24 w-full`}):o(K,{title:i(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:ti(p.error),onRetry:()=>void p.refetch()}):_.length===0?o(Ge,{icon:g,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(Y,{onClick:l,children:[o(x,{className:`h-4 w-4`}),` `,i(`schedulers.list.new`,`New scheduler`)]})}):o(q,{columns:b,rows:_,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ce,emptyMessage:i(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):o($r,{entry:v,onClose:f,onSaved:u},v?.id??`new`)}async function ri(e,t){let n=`${R}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var ii=10,ai=400;async function oi(e,t,n=ai){for(let r=0;r<ii;r+=1){let r=await ri(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var si=`media-player`;function ci(e){return e===H.MediaPlayer?`media-source`:e===H.Heater?`control-source`:`none`}function li(e){return e===H.Heater?re():e===H.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[H.MediaPlayer],accept:[{cap:si,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[si],exclude:[]}:null}function ui(e,t){return e!==H.Heater||t!==null&&t.cap===`switch`}var di={kind:`expression`,expr:`now`,bindings:{}};function fi(e){return{kind:`fields`,cap:`switch`,fields:{on:{kind:`from`,source:e.source,cap:e.cap,fieldPath:e.fieldPath},lastChangedAt:di},commands:{setState:{kind:`forward`,source:e.source,cap:`switch`,method:`setState`}}}}function pi(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:si,fields:{},commands:Object.fromEntries(Object.keys(ne()).map(t=>[t,{kind:`forward`,source:e.source,cap:si,method:t}]))}]}function mi(e,t){if(!ui(e,t))return null;let n=e===H.Heater&&t!==null?[fi(t)]:e===H.MediaPlayer?pi(t):[];return{target:{kind:`new`,type:e},features:n}}u();function hi({onTitle:t}){let{t:n}=Q(),r=v(),i=_t(),a=mn(),l=Je(),u=Ke({addonId:`composer`}),[d,f]=c(H.Sensor),[p,m]=c(``),[h,g]=c([]),[_,y]=c(null),b=h[0]??null,x=li(d),S=mi(d,b);s(()=>{t(n(`helper.newDevice`))},[t,n]);let C=async()=>{if(S!==null){y(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:S}}),r=await oi(t.id,async()=>(await u.refetch()).data??u.data);if(r===null){y(n(`helper.devicePending`));return}e!==``&&await l.mutateAsync({deviceId:r,name:e}),i(xt(r),{replace:!0})}catch(e){y(e instanceof Error?e.message:String(e))}}};return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`device-create-form`,children:[e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.targetType`),o(k,{value:d,onChange:e=>{let t=Object.values(H).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(H).map(e=>({value:e,label:Ee(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.${ci(d)}`)}),o(Ot,{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(Y,{disabled:!ui(d,b)||a.isPending,onClick:()=>void C(),children:n(`compositionEditor.save`)})]})}u();function gi({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=Q(),u=Pt(!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=>[P({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[P(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:Et(u.value,S)}:u,[u,S]),w=It(t,d),T=u.kind===`known`?Lt(u.value,w,!1):null,E=t.build(d),D=jt(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(P(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:[Mt(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(Y,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(Y,{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:Mt(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(Ft,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(Y,{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(Y,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o(kt,{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 _i=`preset`;function vi({mode:e,onTitle:t}){return o(e===`helper`?yi:hi,{onTitle:t})}function yi({onTitle:e}){let{t}=Q(),r=_t(),i=mn(),a=Je(),l=Ke({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=gt(),g=Dt(m.get(_i)),_=g===null?bi(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(_i):n.set(_i,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 oi(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:At(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(xt(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:At(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(hi,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Nt,{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 Rt(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 oi(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(bt(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:xi(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(gi,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function bi(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=te(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function xi(e,t){return e.length>0?e:At(t(`helper.devicePending`))}function Si(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 Ci(e){return{state:`answered`,byRef:new Map(e.map(e=>[P(e),e]))}}function wi(e,t){if(e.state!==`unanswered`)return e.byRef.get(P(t))??null}function Ti(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Ei(e){return se(e).map(e=>e.source)}function Di(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(...Ei(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Ei(e))}let r=new Set;return n.filter(e=>{let t=P(e);return r.has(t)?!1:(r.add(t),!0)})}function Oi(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 ki(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Oi(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 Ai(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 ki(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 ji(e){return P(e)}function Mi(e,t){let n=wi(t,e);return{key:P(e),label:n?n.name:ji(e),presence:Ti(n),deviceId:n?n.id:null}}function Ni(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Pi(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:F(e.block.id),a=P(i),o=Di(e).filter(e=>P(e)!==a).map(e=>Mi(e,t)),s=n.features.map(e=>e.enabled===!1?Z.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=wi(t,i),l=Ni(e),u=Ai(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:Si(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=Ti(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:ji(r.device),namePresence:d,type:c?c.type:null,origin:Si(n),features:s,state:u,sources:o,reportedDeviceId:l}}function Fi(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Ii(e,t){return Fi(e)-Fi(t)||e.name.localeCompare(t.name)}function Li(e,t){let n=e.flatMap(e=>{let n=Pi(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Ii),customizations:n.filter(e=>e.kind===`customization`).toSorted(Ii)}}u();var Ri=1e4;function zi(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Bi(){let e=mt();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Z.t(`build.customDeviceTab.deviceListPending`):Z.t(`build.customDeviceTab.deviceListUnreadable`,{error:zi(e.error)})}:Ci(e.data)}function Vi(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Hi({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Q(),[i,a]=gt(),s=Ze({},{refetchInterval:Ri}),l=Bi(),u=ct({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?Vi(i.get(`new`),t):null,m=f!==null,[h,g]=c(``),_=T(),v=$e(),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:[Wi(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(et,{open:m,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:le,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(vi,{mode:f,onTitle:g},f)}),o(ln,{blockId:d,onClose:y}),v.error!=null&&o(K,{message:zi(v.error)})]})}function Ui(t){return o(Ie,{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 Wi(e,t,n,r,i){if(t!=null&&e===void 0)return o(K,{title:Z.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:zi(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 Ui(e.reason);let a=t==null?null:zi(t);return o(Gi,{lists:Li(e.views,r),fleet:r,refreshError:a,handlers:i})}function Gi({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(Ki,{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(Ki,{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 Ki({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(q,{columns:qi(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:Ce,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function qi(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(Yi,{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=>Ji(e.origin,i),render:e=>o(J,{variant:`default`,"data-testid":`composed-origin-badge`,children:Ji(e.origin,i)})}]:[],{key:`state`,header:Z.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(J,{variant:xr(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(Zi,{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(Y,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(Y,{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 Ji(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 Yi({row:t}){let{t:n}=Q();return e(`div`,{className:`space-y-0.5`,children:[o(Xi,{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 Xi({row:e}){let{t}=Q(),n=Be(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(St,{to:e.kind===`composed`?bt(e.reportedDeviceId):xt(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Zi({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(St,{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 Qi(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 $i(e){if(Array.isArray(e))return e}function ea(e,t,n){return(t=la(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ta(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 na(){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 ra(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 ia(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ra(Object(n),!0).forEach(function(t){ea(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ra(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function aa(e,t){if(e==null)return{};var n,r,i=oa(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 oa(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 sa(e,t){return $i(e)||ta(e,t)||ua(e,t)||na()}function ca(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 la(e){var t=ca(e,`string`);return typeof t==`symbol`?t:t+``}function ua(e,t){if(e){if(typeof e==`string`)return Qi(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)?Qi(e,t):void 0}}function da(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fa(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 pa(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?fa(Object(n),!0).forEach(function(t){da(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):fa(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ma(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function ha(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 ga(e){return{}.toString.call(e).includes(`Object`)}function _a(e){return!Object.keys(e).length}function va(e){return typeof e==`function`}function ya(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ba(e,t){return ga(t)||Ta(`changeType`),Object.keys(t).some(function(t){return!ya(e,t)})&&Ta(`changeField`),t}function xa(e){va(e)||Ta(`selectorType`)}function Sa(e){va(e)||ga(e)||Ta(`handlerType`),ga(e)&&Object.values(e).some(function(e){return!va(e)})&&Ta(`handlersType`)}function Ca(e){e||Ta(`initialIsRequired`),ga(e)||Ta(`initialType`),_a(e)&&Ta(`initialContent`)}function wa(e,t){throw Error(e[t]||e.default)}var Ta=ha(wa)({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"}),Ea={changes:ba,selector:xa,handler:Sa,initial:Ca};function Da(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ea.initial(e),Ea.handler(t);var n={current:e},r=ha(Aa)(n,t),i=ha(ka)(n),a=ha(Ea.changes)(e),o=ha(Oa)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Ea.selector(e),e(n.current)}function c(e){ma(r,i,a,o)(e)}return[s,c]}function Oa(e,t){return va(t)?t(e.current):t}function ka(e,t){return e.current=pa(pa({},e.current),t),t}function Aa(e,t,n){return va(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var ja={create:Da},Ma={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Na(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 Pa(e){return{}.toString.call(e).includes(`Object`)}function Fa(e){return e||za(`configIsRequired`),Pa(e)||za(`configType`),e.urls?(Ia(),{paths:{vs:e.urls.monacoBase}}):e}function Ia(){console.warn(Ra.deprecation)}function La(e,t){throw Error(e[t]||e.default)}var Ra={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
+ `},za=Na(La)(Ra),Ba={config:Fa},Va=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Ha(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Ha(e[n],t[n]))}),ia(ia({},e),t)}var Ua={type:`cancelation`,msg:`operation is manually canceled`};function Wa(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Ua):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var Ga=[`monaco`],Ka=sa(ja.create({config:Ma,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),qa=Ka[0],Ja=Ka[1];function Ya(e){var t=Ba.config(e),n=t.monaco,r=aa(t,Ga);Ja(function(e){return{config:Ha(e.config,r),monaco:n}})}function Xa(){var e=qa(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(Ja({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Wa(ro);if(window.monaco&&window.monaco.editor)return to(window.monaco),e.resolve(window.monaco),Wa(ro);Va(Za,$a)(eo)}return Wa(ro)}function Za(e){return document.body.appendChild(e)}function Qa(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function $a(e){var t=qa(function(e){return{config:e.config,reject:e.reject}}),n=Qa(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function eo(){var e=qa(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;to(n),e.resolve(n)},function(t){e.reject(t)})}function to(e){qa().monaco||Ja({monaco:e})}function no(){return qa(function(e){return e.monaco})}var ro=new Promise(function(e,t){return Ja({resolve:e,reject:t})}),io={config:Ya,init:Xa,__getMonacoInstance:no};u();var ao={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},oo={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function so({children:e}){return t.createElement(`div`,{style:oo.container},e)}var co=so;function lo({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...ao.wrapper,width:e,height:n},...s},!r&&t.createElement(co,null,i),t.createElement(`div`,{ref:a,style:{...ao.fullWidth,...!r&&ao.hide},className:o}))}var uo=i(lo);function fo(e){s(e,[])}var po=fo;function mo(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=mo;function ho(){}function go(e,t,n,r){return _o(e,r)||vo(e,t,n,r)}function _o(e,t){return e.editor.getModel(yo(e,t))}function vo(e,t,n,r){return e.editor.createModel(t,n,r?yo(e,r):void 0)}function yo(e,t){return e.Uri.parse(t)}function bo({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=ho,onMount:S=ho}){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);po(()=>{let e=io.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=go(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=go(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=go(O.current,e||``,o||i||`text`,u||``),n=go(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(uo,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(bo);function xo(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var So=xo,Co=new Map;function wo({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=ho,onMount:C=ho,onChange:w,onValidate:T=ho}){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=So(u),R=n(!1),z=n(!1);po(()=>{let e=io.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=go(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&Co.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(Co.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=go(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(Co.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&&Co.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(uo,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var To=i(wo);u();function Eo(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 Do={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Oo(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Do}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function ko({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,Oo(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&&Oo(e,r)},[r]),o(To,{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 Ao(e){return e.some(e=>e.severity>=8)}var jo=[{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 Mo(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 No=jo.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 Po({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 Fo=5e3;function Io(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 Lo({blockId:t}){let{t:n}=Q(),i=N(t),a=rt({addonId:i,projection:`slim`},{refetchInterval:Fo}),s=r(()=>Io(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(h,{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(ht,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(J,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(ht,{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(St,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(Le,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(J,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,o(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}u();function Ro(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 zo(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 Bo(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 Vo(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Ho(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Uo(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Vo(e);n!==null&&(t[n]=Ho(e))}return t}function Wo(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Go({blockId:t}){let{t:n}=Q(),i=E(),s=it({blockId:t},{retry:!1}),l=Ye({blockId:t},{refetchInterval:1e4,retry:!1}),u=tt({onSuccess:()=>{l.refetch()}}),d=He(),f=qe(),[p,m]=c(null),[g,_]=c(null),[v,y]=c(null),[b,x]=c(!1),S=Wo(l.data)?l.data:null,C=r(()=>S===null?{}:Uo(S),[S]),w=p??C,T=a(e=>{m(e)},[]),D=p!==null,O=a(()=>{p!==null&&(_(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>_(e instanceof Error?e.message:String(e))}))},[t,p,u]),k=a(async(e,n)=>{if(Ro(e)){x(!0),_(null),y(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:zo(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),y(Bo(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?y(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?y(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?y(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?y(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&y(`Refreshing UniFi ID catalogs…`)}catch(e){_(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(h,{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(ht,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(Y,{size:`sm`,variant:`primary`,onClick:O,disabled:!D||u.isPending||b,children:[u.isPending&&o(h,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(yt,{schema:S,values:w,onChange:T,onAction:k}),g===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:g}),v===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:v})]})}u();var Ko=`hub`;function qo({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:m,onCancel:g}){let{t:v}=Q(),x=E(),S=T(),{resolvedMode:C}=me(),w=z({code:t?.code??No,files:t?.files,entry:t?.entry}),[D,O]=c(t?.name??``),[A,M]=c(w.files),[P,F]=c(w.entry),[I,L]=c(w.entry),[R,B]=c(t?.placement??Ko),[V,H]=c(t?.integrationId??``),[U,ee]=c([]),[te,ne]=c(!1),[re,W]=c(`blank`),[ie,ae]=c(null),[oe,se]=c(``),ce=A[I]??``,le=e=>{M(t=>({...t,[I]:e}))},ue=Object.keys(A).toSorted(),de=jo.length>1,fe=r(()=>[...n?.libs??[],...Eo(A,I)],[n?.libs,A,I]),G=f({mutationFn:()=>x.trpcClient.coreBlocks.compile.mutate({files:A,entry:P})}),pe=r(()=>U.filter(e=>e.severity>=8),[U]),K=Ao(U),he=D.trim()===``,q=t===null?null:z(t),ge=t===null||q===null||JSON.stringify(A)!==JSON.stringify(q.files)||P!==q.entry||D.trim()!==t.name||R!==t.placement||(V.trim()===``?void 0:V.trim())!==t.integrationId,_e=()=>{G.reset(),m({name:D.trim(),files:A,entry:P,enabled:t?.enabled??!0,placement:R,...V.trim()===``?{}:{integrationId:V.trim()}})},ve=()=>{let e=Mo(Object.keys(A));M(t=>({...t,[e]:``})),L(e),ae(e),se(e)},ye=e=>{ae(e),se(e)},be=()=>{if(ie===null)return;let e=ie,t=oe.trim();if(ae(null),!(t===``||t===e)){if(A[t]!==void 0){L(t);return}M(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),P===e&&F(t),L(t)}},xe=async e=>{let t=jo.find(t=>t.id===e);if(t===void 0)return;let n=jo.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(A)===JSON.stringify(n.files)&&P===n.entry)&&!await S({title:v(`build.blockEditor.loadExample`,`Load example`),message:v(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:v(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(W(e),M({...t.files}),F(t.entry),L(t.entry),(D.trim()===``||re===`blank`)&&O(t.id===`blank`?``:t.name))},Se=t===null?null:br(t),Ce=Po({existing:t,dirty:ge,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[Se!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(J,{variant:xr(Se.tone),children:Se.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:v(`build.blockEditor.name`,`Name`)}),o(X,{className:`mt-1`,value:D,onChange:e=>O(e.target.value),placeholder:v(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:v(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(X,{className:`mt-1`,value:V,onChange:e=>H(e.target.value),placeholder:v(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&de&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:v(`build.blockEditor.startFrom`,`Start from`)}),o(k,{className:`mt-1 w-full`,value:re,onChange:e=>void xe(e.target.value),"data-testid":`script-example-select`,children:jo.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(st,{selectedNodeId:R,onSelect:B,label:v(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),R!==Ko&&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(ht,{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:[ue.map(t=>ie===t?o(X,{value:oe,onChange:e=>se(e.target.value),onBlur:()=>be(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),be()),e.key===`Escape`&&(e.preventDefault(),ae(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":v(`build.blockEditor.renameFile`,`Rename file`)},t):e(Y,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs ${t===I?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>L(t),onDoubleClick:()=>ye(t),title:v(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===P?` · ${v(`build.blockEditor.entry`)}`:``]},t)),o(Y,{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:v(`build.blockEditor.file`,`+ file`)}),I!==P&&o(Y,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>F(I),title:v(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:v(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:v(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(ko,{value:ce,onChange:le,path:`file:///${I}`,extraLibs:fe,onDiagnostics:ee,dark:C===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:v(`build.blockEditor.theNodeReturnedNoType`,`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`)}),pe.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:v(`build.blockEditor.errorsCannotSave`,{count:pe.length})}),pe.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:v(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),pe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:v(`build.blockEditor.moreErrors`,{count:pe.length-5})})]}),G.data!==void 0&&(G.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(y,{className:`h-3.5 w-3.5`}),` `,v(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[G.data.line!==void 0&&o(`span`,{className:`mr-1`,children:v(`build.blockEditor.errorLine`,{line:String(G.data.line)})}),G.data.error??v(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),G.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[v(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,Jo(G.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(Go,{blockId:t.id}),o(Lo,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(Y,{variant:`outline`,onClick:()=>G.mutate(),disabled:G.isPending||a,title:v(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[G.isPending&&o(h,{className:`h-4 w-4 animate-spin`}),` `,v(`common.compile`)]}),e(Y,{onClick:_e,disabled:a||K||he,children:[a&&o(h,{className:`h-4 w-4 animate-spin`}),` `,v(`common.save`)]}),e(Y,{variant:`outline`,onClick:()=>d?.(),disabled:Ce!==null||d===void 0,title:Ce??v(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(j,{className:`h-4 w-4 animate-spin`}):o(j,{className:`h-4 w-4`}),` `,v(`build.blockEditor.restart`,`Restart`)]}),e(Y,{variant:`ghost`,onClick:()=>ne(!te),title:v(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,"aria-expanded":te,children:[o(b,{className:`h-4 w-4`}),` `,v(`common.logs`),` `,o(We,{expanded:te})]}),o(Y,{variant:`ghost`,onClick:g,disabled:a,children:v(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[v(`build.blockEditor.errorsCount`,{count:pe.length}),ge&&t!==null?` · ${v(`build.blockEditor.unsavedChanges`)}`:``]}),he&&o(J,{variant:`warning`,children:v(`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?v(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(p,{children:o(ht,{i18nKey:`build.blockEditor.logsOf`,values:{id:N(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(ut,{addonId:N(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Jo(e){return e instanceof Error?e.message:String(e)}u();var Yo=[`coreBlocks`,`list`],Xo=[`coreBlocks`,`getTypeDefs`],Zo=5e3;function Qo(e){return e instanceof Error?e.message:String(e)}function $o({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=v(),{t:p}=Q(),m=E(),{state:h,openNew:g,openEdit:_,close:y}=ct({editKey:`block`,newKey:`new`}),[x,S]=c(null),C=T(),[D,O]=c(null),k=l({queryKey:Yo,refetchInterval:Zo,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=h.mode!==`closed`,P=l({queryKey:Xo,enabled:A,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),F=()=>{k.refetch()},I=n(null),L=k.data;s(()=>{t===void 0||I.current===t||L?.find(e=>e.id===t&&M(e)===`code`)!==void 0&&(I.current=t,_(t),i?.(t))},[t,L,_,i]),s(()=>{a&&(S(null),g(),i?.(null),u?.())},[a,u,i,g]);let R=f({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{S(e.block),_(e.block.id),i?.(e.block.id),F()}}),z=f({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{S(e.block),_(e.block.id),i?.(e.block.id),F()}}),B=f({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:F}),V=f({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:F}),H=f({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:F}),U=Cr((k.data??[]).filter(e=>M(e)===`code`)),ee=k.data!==void 0&&U.length===0,te=R.isPending||z.isPending,ne=R.error===null?z.error===null?null:Qo(z.error):Qo(R.error),re=h.mode===`edit`?U.find(e=>e.id===h.id)??(x!==null&&x.id===h.id?x:null):null,W=h.mode===`new`||re===null?null:Sr(U,re),ie=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=br(t),r=xe(t.updatedAt,d);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(J,{variant:xr(n.tone),children:n.label}),o(J,{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}),D===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(ht,{i18nKey:`common.logsOf`,values:{id:N(t.id)},components:{code:o(`code`,{})}})}),o(ut,{addonId:N(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(Y,{variant:`ghost`,onClick:e=>{e.stopPropagation(),S(t),_(t.id),i?.(t.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),o(Y,{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(j,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(Y,{variant:`ghost`,onClick:e=>{e.stopPropagation(),O(D===t.id?null:t.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:o(b,{className:`h-4 w-4`})}),o(Y,{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(Y,{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,D,i,_,B,H.isPending,H.variables,V,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:k.data===void 0?``:wr(U)}),k.error!=null&&o(K,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Qo(k.error),onRetry:F}),o(q,{columns:ie,rows:U,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ce,emptyMessage:ee?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):k.data===void 0?p(`build.scriptsTab.loadingScripts`,`Loading scripts…`):p(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{S(e),_(e.id),i?.(e.id)}}),o(et,{open:A,onClose:()=>{R.reset(),z.reset(),H.reset(),S(null),y(),i?.(null)},title:W===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:W.name}),icon:de,width:`xl`,testId:`script-editor-panel`,children:o(qo,{existing:W,typeDefs:P.data,typeDefsLoading:P.isLoading,saving:te,saveError:ne,restarting:H.isPending,restartError:H.error===null?null:Qo(H.error),onRestart:W===null?void 0:()=>H.mutate(W.id),onSave:e=>{let t=W;t===null?R.mutate(e):z.mutate({blockId:t.id,block:e})},onCancel:()=>{R.reset(),z.reset(),H.reset(),S(null),y(),i?.(null)}})}),B.error!=null&&o(K,{message:Qo(B.error)}),V.error!=null&&o(K,{message:Qo(V.error)}),H.error!=null&&o(K,{message:Qo(H.error)})]})}var es=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`];function ts(e){return e!==null&&es.some(t=>t===e)}var ns=[`coreBlocks`,`list`,`build-counts`],rs=[`schedulers`,`list`,`build-counts`],is=[`actions`,`list`,`build-counts`],as=[`block`,`action`,`scheduler`,`create`,`new`];function os(e){return e.filter(e=>M(e)===`code`).length}function ss(e){return e.filter(e=>On(e.code)).length}function cs(e,t){return t===null?e:`${e} (${String(t)})`}function ls(){let{t}=Q(),n=E(),[r,i]=gt(),a=r.get(`tab`),s=ts(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:ns,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:os(u),f=u===void 0?null:ss(u),p=l({queryKey:is,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=l({queryKey:rs,refetchInterval:1e4,queryFn:async()=>n.trpcClient.schedulers.list.query({})}),g=h.data===void 0?null:h.data.length,_=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),v=_.data?.state===`loaded`?_.data.views.length:null,y=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},b=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},S=()=>{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})},D=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=Ct(`/build`,{t,isAdmin:!0})??{icon:C,title:t(`nav.build`,`Build-your-self`)};return o(wt,{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(Y,{type:`button`,onClick:()=>w(`helper`),"data-testid":`build-new-composed`,children:[o(x,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(Y,{type:`button`,onClick:S,"data-testid":`build-new`,children:[o(x,{className:`h-4 w-4`}),` `,D]}),sections:[{id:`automations`,label:cs(t(`build.tabAutomations`,`Automations`),f),ownedParams:as,content:o(Lr,{onOpenScripts:y,createRequested:s===`automations`&&c,onCreateConsumed:T})},{id:`actions`,label:cs(t(`build.tabActions`,`Actions`),m),ownedParams:as,content:o(nr,{createRequested:s===`actions`&&c,onCreateConsumed:T})},{id:`schedulers`,label:cs(t(`build.tabSchedulers`,`Schedulers`),g),ownedParams:as,content:o(ni,{createRequested:s===`schedulers`&&c,onCreateConsumed:T})},{id:`scripts`,label:cs(t(`build.tabCode`,`Code`),d),ownedParams:as,content:o($o,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:b,createRequested:s===`scripts`&&c,onCreateConsumed:T})},{id:`custom-device`,label:cs(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:as,content:o(Hi,{createRequested:s===`custom-device`&&c,onCreateConsumed:T})}]})}export{ls as BuildPage};