@camstack/addon-admin-ui 1.2.373 → 1.2.374
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AddonAssetIcon-DzDR4RgH.js → AddonAssetIcon-B3Nf3xlx.js} +1 -1
- package/dist/assets/{AddonIntegrationBody-WZ-GmbiU.js → AddonIntegrationBody-BhLL7FoP.js} +1 -1
- package/dist/assets/{Addons-DYnLpXZv.js → Addons-BX4RGdki.js} +1 -1
- package/dist/assets/{AdminTabs-C1o_WGDw.js → AdminTabs-BcE-Q0tO.js} +1 -1
- package/dist/assets/{AiProfiles-BaPBs0qt.js → AiProfiles-Bu0zedHk.js} +1 -1
- package/dist/assets/{BrokerForm-CUEA6_x3.js → BrokerForm-nF-ssRGh.js} +1 -1
- package/dist/assets/{Build-IvUCLdig.js → Build-CuTxMnpV.js} +1 -1
- package/dist/assets/{Calendars-I6TCXQIG.js → Calendars-B3HYs0JU.js} +1 -1
- package/dist/assets/Cluster-CjOkqkYw.js +1 -0
- package/dist/assets/{ClusterStepModel-BKEy6uc_.js → ClusterStepModel-B9pwzZ_M.js} +1 -1
- package/dist/assets/{CompositionEditor-CUJz5zIO.js → CompositionEditor-BS_jFILf.js} +1 -1
- package/dist/assets/{CompositionEditorPage-ggzQcHQq.js → CompositionEditorPage-d2NmF7hL.js} +1 -1
- package/dist/assets/{Data-X0oYW_Rh.js → Data-BjabNrW5.js} +1 -1
- package/dist/assets/{DetectionIntelligence-CzuLuRps.js → DetectionIntelligence-Drsxk61A.js} +1 -1
- package/dist/assets/{DeviceDetail-ByFN1i10.js → DeviceDetail-UKHvJh8G.js} +1 -1
- package/dist/assets/{DeviceDoActionFields-DirqSmTT.js → DeviceDoActionFields-C3lawEZ6.js} +1 -1
- package/dist/assets/{Devices-D_N3dsDP.js → Devices-Bi_w3OGa.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-BwnkfDUy.js → EmbedPlayerPage-CDnqLk2A.js} +1 -1
- package/dist/assets/{Events-CR7guuuS.js → Events-BoFeLCPi.js} +1 -1
- package/dist/assets/{Identity-DIGRfdjI.js → Identity-riQA9K3r.js} +1 -1
- package/dist/assets/{IntegrationDetail-6BYWzrle.js → IntegrationDetail-DYz00LhA.js} +1 -1
- package/dist/assets/{Integrations-Dtep2eUt.js → Integrations-Dj59hlDo.js} +1 -1
- package/dist/assets/{Integrations-DxgCSKYL.js → Integrations-x5pgUuxU.js} +1 -1
- package/dist/assets/{Locations-PBa5sZr9.js → Locations-BveQrqYZ.js} +1 -1
- package/dist/assets/{Logs-CqrKzl8c.js → Logs-B_2PKsST.js} +1 -1
- package/dist/assets/{MyAccess-2HFGVdy3.js → MyAccess-C_eIFq1z.js} +1 -1
- package/dist/assets/{Network-lmWW7YF8.js → Network-CpuyFLhq.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-VjOJE4Mg.js → NodeAddonsSettingsPanel-xFAQ20so.js} +1 -1
- package/dist/assets/{Notifications-C95KlkmG.js → Notifications-DbeLe6-5.js} +1 -1
- package/dist/assets/{Plates-CYU7XcQC.js → Plates-DcCJBtJq.js} +1 -1
- package/dist/assets/{Recordings-CZnERdvC.js → Recordings-1_ShsTqb.js} +1 -1
- package/dist/assets/{ScanNetworkModal-BcwSCus9.js → ScanNetworkModal-DuIQym22.js} +1 -1
- package/dist/assets/{Scenes-Cf37C7N3.js → Scenes-CgiGYYQy.js} +1 -1
- package/dist/assets/{SessionsList-DW5tspI_.js → SessionsList-B-6hhNIP.js} +1 -1
- package/dist/assets/{Showroom-BCHYtMRz.js → Showroom-CF1Qu7mr.js} +1 -1
- package/dist/assets/{System-DoO-0QYY.js → System-DvOg-3a-.js} +1 -1
- package/dist/assets/{Terminal-Cl6odY2y.js → Terminal-742YDR-F.js} +1 -1
- package/dist/assets/{Viewer-BeiK1WJq.js → Viewer-0fo1xtXq.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-itrNHhFH.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-u191sqrt.js} +1 -1
- package/dist/assets/{authed-media-hm_YC5GG.js → authed-media-BaRjbtMq.js} +1 -1
- package/dist/assets/{debounced-invalidate-Dy7qLdW1.js → debounced-invalidate-BOR3Wuyx.js} +1 -1
- package/dist/assets/{device-integration-icon-C6TnIOOf.js → device-integration-icon-5T12cCTw.js} +1 -1
- package/dist/assets/device-picker-model-D8gNhpYS.js +1 -0
- package/dist/assets/{face-bbox-CNmj5VUt.js → face-bbox-BEIyL1yX.js} +1 -1
- package/dist/assets/{hostInit-44uecb4-.js → hostInit-C3KwadjS.js} +1 -1
- package/dist/assets/{index-Wd9AuQ7z.js → index-BWu66tVw.js} +3 -3
- package/dist/assets/{location-owned-usage-ByCAX4XJ.js → location-owned-usage-B6a7vInb.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-894be14f.js → mf-entry-bootstrap-0-801b692c.js} +2 -2
- package/dist/assets/mount-D8gNhpYS.js +1 -0
- package/dist/assets/{notification-schedule-field-DtmwnNDm.js → notification-schedule-field-CyG86j1n.js} +1 -1
- package/dist/assets/remoteEntry-CUnRKStz.js +1 -0
- package/dist/assets/{src-QOexoM_4.js → src-BTX2jfA7.js} +1 -1
- package/dist/assets/{use-scenes-feed-BkLm9Irc.js → use-scenes-feed-DqzF-2_b.js} +1 -1
- package/dist/assets/{use-stationary-objects-C_J8GfJs.js → use-stationary-objects-BPLoE6ig.js} +1 -1
- package/dist/assets/useEventInvalidation-D8gNhpYS.js +1 -0
- package/dist/assets/{useNodeUrlSelection-BUjxvnuG.js → useNodeUrlSelection-s67zn-kU.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CYQBrudz.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Ds3l678P.js} +2 -2
- package/dist/index.html +5 -5
- package/dist/server/addon.js +1 -1
- package/package.json +1 -1
- package/dist/assets/Cluster-Ct_1WPkP.js +0 -1
- package/dist/assets/device-picker-model-PKbAt0O0.js +0 -1
- package/dist/assets/mount-PKbAt0O0.js +0 -1
- package/dist/assets/remoteEntry-CGNtQhcK.js +0 -1
- package/dist/assets/useEventInvalidation-PKbAt0O0.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{I as e,K as t,Q as n,S as r,W as i,a,b as o,o as s,q as c,x as l,z as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{R as d,X as f,Z as p,at as m,ct as h,ft as g,gt as _,ht as v,st as y,vt as b}from"./player-overlays-B7T46vDu.js";import{$n as x,An as S,Cn as C,Cr as w,Du as T,Fl as E,Fn as D,Hl as O,Hu as k,Il as A,In as j,Jn as M,Kd as N,Kn as ee,Md as P,Nn as F,Od as I,Tf as L,Ud as te,Vo as ne,Yu as R,_u as re,af as ie,as as ae,cn as oe,ds as z,er as B,fs as V,gd as H,hd as se,iu as ce,kt as le,la as ue,ls as de,nf as fe,os as pe,ot as me,qn as he,rs as ge,ss as _e,tr as U,tu as ve,wu as ye,xn as be,zd as xe}from"./src-QOexoM_4.js";import{a as Se,c as Ce,d as we,f as Te,i as Ee,m as De,n as Oe,o as ke,p as Ae,r as je,s as Me,t as Ne}from"./debounced-invalidate-Dy7qLdW1.js";import{Un as Pe,vi as Fe}from"./client-BBcQuaON.js";import{t as Ie}from"./useTranslation-Bc5yH9V9.js";import"./mount-PKbAt0O0.js";import{$ as Le,X as Re,Z as ze}from"./index-Wd9AuQ7z.js";import{t as Be}from"./AdminPage-BSFohA3i.js";import{a as Ve,i as He,r as Ue,t as We}from"./authed-media-hm_YC5GG.js";import{t as Ge}from"./use-stationary-objects-C_J8GfJs.js";import{t as Ke}from"./AdminTabs-C1o_WGDw.js";var qe=b(`arrow-down-wide-narrow`,[[`path`,{d:`m3 16 4 4 4-4`,key:`1co6wj`}],[`path`,{d:`M7 20V4`,key:`1yoxec`}],[`path`,{d:`M11 4h10`,key:`1w87gc`}],[`path`,{d:`M11 8h7`,key:`djye34`}],[`path`,{d:`M11 12h4`,key:`q8tih4`}]]),Je=b(`square-parking`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 17V7h4a3 3 0 0 1 0 6H9`,key:`1dfk2c`}]]);n();function Ye(e){let t=e.subLabel??e.label;if(t!==void 0)return t;let n=e.audioLabels?.[0]?.label;return n!==void 0&&n.length>0?n:void 0}var Xe=720*60*60*1e3;function Ze(e){let t=[];for(let n of e)t.push(...n);return t}function Qe(e,t){let n=[...e];return n.sort((e,n)=>t===`importance`?n.importance-e.importance:n.timestamp-e.timestamp),n}function $e(e,t){return e.filter(e=>!(e.importance<t.minImportance||t.cameras.size>0&&!t.cameras.has(e.deviceId)||t.classes.size>0&&!t.classes.has(e.className)))}function et(e,t){return`${String(e)}:${t}`}function tt(e,t){let n=new Map,r=new Set;for(let i of e){let e=et(i.deviceId,i.trackId);if(!t.has(e)||r.has(e))continue;r.add(e);let a=n.get(i.deviceId);a?a.push(i.trackId):n.set(i.deviceId,[i.trackId])}return n}function nt(e,t){return{since:e.fromMs??t-Xe,until:e.toMs??t}}var rt=[`native`,`raster`,`standin`];function it(e){return rt.some(t=>t===e)}var at={standin:{label:`stand-in`,title:`Stand-in: this tile is a face or plate detail crop copied in because no frame of the subject was captured. It is not a best shot.`,tone:`warning`},raster:{label:`low-res`,title:`Raster crop: a sub-native cut of the subject, not a native capture. Honest, but lower resolution than a best shot.`,tone:`info`}};function ot(e){return e===`standin`?at.standin:e===`raster`?at.raster:null}var st={"no-key-frame":`No key frame existed at close, so no native tile could be cut.`,"no-best-seen-bbox":`No subject box was ever recorded, so there was nothing to cut around.`,"derive-returned-null":`The close-time crop was attempted and produced nothing.`,"derive-threw":`The close-time crop failed with an error.`,"derive-not-wired":`No close-time crop was wired on this node.`,"no-media-store":`The node was shutting down mid-close.`,"no-thumbnail":`The track closed with no tile of any kind.`,"standin-tile":`The track closed with a detail crop standing in for the subject.`,"raster-tile":`The track closed with a sub-native raster crop of the subject.`,"native-tile":`The track closed with a native tile.`};function ct(e){if(e===void 0)return null;let t=e.trim();if(t.length===0)return null;let n=t.split(/\s+/),r=n[0]??t,i=[];for(let e of n.slice(1)){let t=e.indexOf(`=`);t===-1?i.push({key:e,value:null}):i.push({key:e.slice(0,t),value:e.slice(t+1)})}return{sentence:st[r]??r,detail:i,raw:t}}function lt(e){if(e===void 0||!Number.isFinite(e)||e<=0)return``;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${String(n)}m ${String(r).padStart(2,`0`)}s`}function ut({row:e,cameraName:t,nowMs:n,onOpenDetail:i,selected:a=!1,onToggleSelect:o,score:s,provenance:c,footer:u}){let d=Ve(e.mediaId===void 0?He(`track`,e.trackId):Ue(e.mediaId)),f=Math.round(e.importance*100),p=s===void 0?void 0:Math.round(s*100),m=lt(e.windowMs),_=()=>i(e),v=ot(c);return r(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${a?`border-primary ring-1 ring-primary`:`border-border`}`,children:[r(`div`,{className:`aspect-video relative overflow-hidden bg-surface-hover`,children:[d.src?l(`img`,{src:d.src,alt:`Event from ${t}`,onClick:_,className:`h-full w-full cursor-zoom-in object-cover`}):l(`button`,{type:`button`,onClick:_,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-surface-hover text-foreground-subtle`,title:d.failed?`Key-event media unavailable`:`No key-event media`,children:l(g,{className:`h-6 w-6 opacity-60`})}),o&&l(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),o(et(e.deviceId,e.trackId))},className:`absolute left-0 top-0 z-10 rounded-br-md bg-black/50 p-1.5 text-white hover:bg-black/70`,"aria-label":a?`Deselect`:`Select`,children:a?l(De,{className:`h-4 w-4 text-primary`}):l(h,{className:`h-4 w-4`})}),p!==void 0&&r(`span`,{className:`absolute left-1 top-1 z-10 rounded bg-primary/85 px-1.5 py-0.5 text-[10px] font-semibold text-white tabular-nums`,title:`CLIP semantic-match score`,children:[String(p),`%`]}),f>0&&l(`span`,{className:`absolute right-1 top-1 z-10 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-semibold text-white`,children:String(f)}),v!==null&&l(`span`,{className:`absolute bottom-1 right-1 z-10 rounded px-1.5 py-0.5 text-[10px] font-semibold text-white ${v.tone===`warning`?`bg-warning/90`:`bg-black/70`}`,title:v.title,children:v.label}),(e.markForTrain===!0||e.retrainStatus===`trained`||e.debug===!0||e.favourited===!0)&&r(`span`,{className:`absolute bottom-1 left-1 z-10 flex gap-1`,children:[e.markForTrain===!0&&l(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:`Marked for training`,"aria-label":`Marked for training`,children:l(I,{className:`h-3 w-3`})}),e.retrainStatus===`trained`&&e.markForTrain!==!0&&l(`span`,{className:`rounded bg-success/85 p-0.5 text-white`,title:`Training complete`,"aria-label":`Training complete`,"data-testid":`retrain-status-trained`,children:l(fe,{className:`h-3 w-3`})}),e.debug===!0&&l(`span`,{className:`rounded bg-black/70 p-0.5 text-white`,title:`Flagged for debug`,"aria-label":`Flagged for debug`,children:l(ie,{className:`h-3 w-3`})}),e.favourited===!0&&l(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:`Favourited`,"aria-label":`Favourited`,children:l(T,{className:`h-3 w-3`})})]})]}),r(`button`,{type:`button`,onClick:_,className:`min-w-0 px-2 py-1.5 text-left space-y-0.5`,children:[r(`p`,{className:`text-[11px] font-medium text-foreground truncate`,title:e.className,children:[e.className,Ye(e)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,Ye(e)]}):null]}),l(`p`,{className:`text-[10px] text-foreground-subtle truncate`,title:t,children:t}),r(`div`,{className:`flex items-center justify-between gap-2`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle truncate`,children:Te(e.timestamp,n)}),m&&l(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:m})]})]}),u!==void 0&&l(`div`,{className:`px-2 pb-1.5`,children:u})]})}var dt=1400,ft=`Admin-gated URL — opens only inside an authenticated session`;function pt({label:t,value:n,title:i}){let[a,o]=c(!1),s=M();return u(()=>{if(!a)return;let e=setTimeout(()=>o(!1),dt);return()=>clearTimeout(e)},[a]),r(`button`,{type:`button`,onClick:e(()=>{(async()=>{try{await navigator.clipboard.writeText(n),o(!0)}catch{await s({title:`Copy the media URL`,message:`Clipboard access was refused. Select the URL below and copy it manually.`,label:`${t} URL`,defaultValue:n,readOnly:!0,cancelLabel:`Close`})}})()},[n,t,s]),title:i,"aria-label":`Copy ${t} URL`,className:`flex min-w-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${a?`border-success/40 bg-success/10 text-success`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[l(a?fe:te,{className:`h-2.5 w-2.5 shrink-0`}),l(`span`,{className:`truncate`,children:a?`Copied`:t})]})}function mt({localUrl:e,publicUrl:t}){return r(`div`,{className:`flex flex-wrap gap-1`,children:[l(pt,{label:`Local`,value:e,title:`Copy LAN URL — ${ft}`}),t&&l(pt,{label:`Public`,value:t,title:`Copy public URL — ${ft}`})]})}var ht={firstFrame:`First frame (track start)`,lastFrame:`Last frame (track end)`,thumbnail:`Best detection`,thumbnailSmall:`Best detection (480)`,snapshot:`Snapshot`,keyFrame:`Key frame (native-res)`,keyFrameSmall:`Key frame (960)`,crop:`Object crop`,fullFrame:`Full frame`,fullFrameBoxed:`Full frame (boxed)`,faceCrop:`Face crop`,plateCrop:`Plate crop`,confirmationCrop:`Confirmation crop (what the gate saw)`,debugCrop:`Debug crop (why this decision)`,sceneFrame:`Scene frame (clean)`,lastSceneFrame:`Last frame (clean)`};function gt(e){return e in ht}function _t(e){return gt(e)?ht[e]:e}function vt(e,t){return`${e}${t}`}n();var yt=3e4;function bt(t){let[n,r]=c(null),i=e(e=>{r(t=>t??e)},[]);return u(()=>{t||r(null)},[t]),{publicOrigin:n,probes:t?l(xt,{onOrigin:i}):null}}function xt({onOrigin:e}){let{data:t}=w({capName:`network-access`});return l(o,{children:(t??[]).map(t=>l(St,{addonId:t.addonId,onOrigin:e},t.addonId))})}function St({addonId:e,onOrigin:t}){let{data:n}=ne({addonId:e},{refetchInterval:yt,retry:!1});return u(()=>{let e=n?Pe.safeParse(n):null,r=e?.success?e.data.endpoint?.url:void 0;if(r)try{t(new URL(r).origin)}catch{}},[n,t]),null}var W=typeof V==`function`,Ct=`Track flags arrive with the next server update`;function wt(){return{mutateAsync:async()=>{throw Error(`setTrackFlags unavailable`)},isPending:!1}}var Tt=W?V:wt;function Et(e){if(typeof e!=`object`||!e||!(`trackId`in e)||!(`markForTrain`in e)||!(`debug`in e)||!(`favourited`in e))return null;let{trackId:t,markForTrain:n,debug:r,favourited:i}=e;return typeof t!=`string`||typeof n!=`boolean`||typeof r!=`boolean`||typeof i!=`boolean`?null:{trackId:t,markForTrain:n,debug:r,favourited:i}}n();function Dt({label:e,hint:t,checked:n,disabled:i,title:a,icon:o,onToggle:s}){return r(`button`,{type:`button`,role:`switch`,"aria-checked":n,"aria-label":e,disabled:i,title:a,onClick:s,className:`flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left transition-colors disabled:opacity-50 ${n?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[l(`span`,{className:n?`text-primary`:`text-foreground-subtle`,children:o}),r(`span`,{className:`min-w-0 flex-1`,children:[l(`span`,{className:`block text-[11px] font-medium text-foreground`,children:e}),l(`span`,{className:`block text-[10px] text-foreground-subtle`,children:t})]}),l(`span`,{"aria-hidden":`true`,className:`h-4 w-7 shrink-0 rounded-full p-0.5 transition-colors ${n?`bg-primary`:`bg-border`}`,children:l(`span`,{className:`block h-3 w-3 rounded-full bg-white transition-transform ${n?`translate-x-3`:``}`})})]})}function Ot({deviceId:e,trackId:t,markForTrain:n,debug:i,favourited:a,onChange:o}){let s=Tt(),u=ee(),[d,f]=c(null),p=d?.markForTrain??n===!0,m=d?.debug??i===!0,h=d?.favourited??a===!0,g=!W||s.isPending,_=W?void 0:Ct,v=n=>{g||(async()=>{try{let r=Et(await s.mutateAsync({deviceId:e,trackId:t,flags:n}));if(!r)return;f(r),o?.(r)}catch(e){let t=e instanceof Error?e.message:``;await u({title:`Could not update this track`,message:t===``?`Could not update this track. Check the server logs.`:t,variant:`danger`})}})()};return r(`div`,{className:`grid gap-1.5 sm:grid-cols-2`,children:[l(Dt,{label:`Mark for training`,hint:`Keeps this track and its media past retention`,checked:p,disabled:g,..._===void 0?{}:{title:_},icon:l(I,{className:`h-4 w-4`}),onToggle:()=>v({markForTrain:!p})}),l(Dt,{label:`Debug`,hint:`Flag this track for diagnostic attention`,checked:m,disabled:g,..._===void 0?{}:{title:_},icon:l(ie,{className:`h-4 w-4`}),onToggle:()=>v({debug:!m})}),l(Dt,{label:`Favourited`,hint:`Keeps this track and its media past retention`,checked:h,disabled:g,..._===void 0?{}:{title:_},icon:l(T,{className:`h-4 w-4`}),onToggle:()=>v({favourited:!h})})]})}var G=100,kt=120,At={polyline:``,points:[],snapshots:[],start:null,end:null,peakBox:null},K=e=>e<0?0:e>1?1:e,q=e=>Math.round(e*100)/100;function jt(e,t){if(e.length<=t)return[...e];let n=(e.length-1)/(t-1),r=[];for(let i=0;i<t;i++)r.push(e[Math.round(i*n)]);return r[r.length-1]=e[e.length-1],r}function Mt(e,t,n){if(e.length===0||t===null)return At;let{width:r,height:i}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)return At;let a=jt(e,n?.maxPoints??kt).map(e=>({x:q(K(e.x/r)*G),y:q(K(e.y/i)*G)})),o=a[0]??null,s=a[a.length-1]??null,c=a.length>=2?a.map(e=>`${e.x},${e.y}`).join(` `):``,l=(n?.snapshots??[]).map(e=>({x:q(K(e.x/r)*G),y:q(K(e.y/i)*G),mediaId:e.mediaId})),u=null,d=-1;for(let t of e){let e=K(t.bbox.w/r)*K(t.bbox.h/i);e>d&&(d=e,u=t)}return{polyline:c,points:a,snapshots:l,start:o,end:s,peakBox:u?{x:q(K(u.bbox.x/r)*G),y:q(K(u.bbox.y/i)*G),w:q(K(u.bbox.w/r)*G),h:q(K(u.bbox.h/i)*G)}:null}}var Nt=typeof ge==`function`,Pt=`Track deletion arrives with the next server update`;function Ft(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var It=Nt?ge:Ft;n();var Lt=15e3,Rt=f();function zt({url:e,label:t}){let{src:n,failed:r}=Ve(e);return n===null?l(`div`,{className:`flex h-full w-full items-center justify-center bg-surface-hover`,children:r?l(g,{className:`h-4 w-4 text-foreground-subtle opacity-60`}):l(H,{className:`h-4 w-4 animate-spin text-foreground-subtle opacity-70`})}):l(`img`,{src:n,alt:t,className:`h-full w-full object-cover`})}var Bt=new Set([`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]),Vt=new Set([`keyFrame`,`fullFrame`,`fullFrameBoxed`,`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`,`sceneFrame`,`lastSceneFrame`]);function Ht(e){let[t,n]=c(null);return u(()=>{if(n(null),!e)return;let t=!1,r=new Image;return r.onload=()=>{t||n({width:r.naturalWidth,height:r.naturalHeight})},r.src=e,()=>{t=!0,r.onload=null}},[e]),t}function Ut({overlay:e,onPickSnapshot:t}){return!e.polyline&&!e.peakBox&&e.snapshots.length===0?null:r(`svg`,{viewBox:`0 0 100 100`,preserveAspectRatio:`none`,className:`pointer-events-none absolute inset-0 h-full w-full`,children:[e.peakBox&&l(`rect`,{x:e.peakBox.x,y:e.peakBox.y,width:e.peakBox.w,height:e.peakBox.h,fill:`none`,stroke:`var(--color-warning)`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),e.polyline&&l(`polyline`,{points:e.polyline,fill:`none`,stroke:`var(--color-info)`,strokeWidth:2,strokeLinejoin:`round`,strokeLinecap:`round`,strokeOpacity:.85,vectorEffect:`non-scaling-stroke`}),e.points.map((e,t)=>l(`circle`,{cx:e.x,cy:e.y,r:1,fill:`var(--color-info)`,fillOpacity:.6,vectorEffect:`non-scaling-stroke`},`${String(e.x)}-${String(e.y)}-${String(t)}`)),e.snapshots.map((e,n)=>l(`circle`,{cx:e.x,cy:e.y,r:1.9,fill:`var(--color-info)`,fillOpacity:.95,stroke:`var(--color-background)`,strokeWidth:.7,vectorEffect:`non-scaling-stroke`,className:t?`pointer-events-auto cursor-pointer`:void 0,onClick:t?n=>{n.stopPropagation(),t(e.mediaId)}:void 0,children:l(`title`,{children:`Snapshot checkpoint — click to view this frame`})},`snap-${String(e.mediaId)}-${String(n)}`)),e.start&&l(`circle`,{cx:e.start.x,cy:e.start.y,r:2.4,fill:`var(--color-success)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),e.end&&l(`circle`,{cx:e.end.x,cy:e.end.y,r:2.4,fill:`var(--color-danger)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function J({label:e,value:t,mono:n}){return r(`div`,{className:`flex items-baseline justify-between gap-3 border-b border-border/60 py-1.5 last:border-0`,children:[l(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:e}),l(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground ${n?`font-mono text-[11px]`:``}`,title:t,children:t})]})}function Wt({row:t,cameraName:n,deleteAvailable:a,onClose:s,onDeleted:d,onFlagsChanged:f}){let p=m(),h=ee(),_=he(),v=It(),b=t!==null,x=t?.deviceId??0,S=t?.trackId??``,w=t?.timestamp??0,T=t?.windowMs??0,{data:D}=ae({deviceId:x,trackId:S},{enabled:b}),{data:O}=de({trackId:S,deviceId:x},{enabled:b}),k=D?.bestEventId===void 0?void 0:Number(D.bestEventId),{data:M}=_e({ownerType:`object`,eventId:k??0,deviceId:x},{enabled:b&&k!==void 0&&Number.isFinite(k)}),{data:N}=A({deviceId:x},{enabled:b}),F=(N??[]).find(e=>e.addonId!==void 0)?.addonId,{data:I}=E({deviceId:x,since:w-Lt,until:w+T+Lt,provider:F??``},{enabled:b&&F!==void 0}),[L,te]=c(null),[ne,R]=c(!1),{publicOrigin:re,probes:ie}=bt(b);u(()=>{te(null)},[x,S]);let oe=i(()=>{let e=O??[],t=M??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[O,M]),z=L??oe,B=Ve(z?z.url:void 0),V=i(()=>{let e=new Set,t=[];for(let n of[...M??[],...O??[]])e.has(n.mediaId)||(e.add(n.mediaId),t.push(n));return t},[M,O]),se=i(()=>V.find(e=>Bt.has(e.kind))??null,[V]),ce=Ht(Ve(se?se.url:void 0).src),le=i(()=>Mt(D?.positions??[],ce,{snapshots:(D?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaId:e.mediaId}))}),[D?.positions,D?.snapshots,ce]),ue=e(e=>{let t=V.find(t=>t.mediaId===e);t&&te(t)},[V]);if(t===null)return null;let fe=B.src,pe=z?.kind,me=pe!==void 0&&Vt.has(pe)&&ce!==null&&(D?.positions.length??0)>=2,ge=I&&I.length>0?I[0]:null,U=()=>{ge&&(R(!0),(async()=>{try{let e=await p.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:ge.id});window.open(e.playbackUrl,`_blank`,`noopener`)}catch{h({title:`Clip unavailable`,message:`Could not resolve clip playback. Check the server logs.`,variant:`warning`})}finally{R(!1)}})())},ve=()=>{!a||v.isPending||(async()=>{if(await _({title:`Delete track`,message:`Delete this track and every image and clip captured for it? This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`}))try{await v.mutateAsync({deviceId:t.deviceId,trackIds:[t.trackId]}),d()}catch{await h({title:`Delete failed`,message:`Failed to delete this track. Check the server logs.`,variant:`danger`})}})()},ye=Math.round(t.importance*100),xe=D?.importanceReason?`${String(ye)}% · ${D.importanceReason}`:`${String(ye)}%`,Se=D?.zonesVisited&&D.zonesVisited.length>0?D.zonesVisited.join(`, `):`—`,Ce=D?.audioLabels&&D.audioLabels.length>0?D.audioLabels:t.audioLabels&&t.audioLabels.length>0?t.audioLabels:void 0,Te=Ce===void 0?`—`:Ce.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `),Ee=D?D.totalDistance.toFixed(2):`—`,De=ct(D?.previewMissReason),ke=Ae(D?D.firstSeen:w),je=D?Ae(D.lastSeen):`—`;return l(be,{open:!0,onOpenChange:e=>!e&&s(),children:r(C,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":`Event detail`,className:`flex h-[92dvh] flex-col gap-0 overflow-hidden p-0 bottom-0 left-0 right-0 top-auto w-full max-w-full translate-x-0 translate-y-0 rounded-b-none md:bottom-auto md:left-1/2 md:right-auto md:top-1/2 md:h-auto md:w-[calc(100vw-2rem)] md:max-w-xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:max-h-[calc(100dvh-2rem)]`,children:[l(`header`,{className:`flex shrink-0 items-start gap-2 border-b border-border py-3 pl-4 pr-10`,children:r(`div`,{className:`min-w-0`,children:[r(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:[t.className,Ye(t)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,Ye(t)]}):null]}),l(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:n})]})}),r(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[fe?l(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:l(Oe,{src:fe,alt:`Key frame from ${n}`,fit:`natural`,className:`w-full`,overlay:me?l(Ut,{overlay:le,onPickSnapshot:ue}):void 0})}):l(`div`,{className:`flex aspect-video w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-surface-hover text-foreground-subtle`,children:B.failed?r(o,{children:[l(g,{className:`h-8 w-8 opacity-60`}),l(`span`,{className:`text-[11px]`,children:`Key-frame media unavailable`})]}):l(H,{className:`h-6 w-6 animate-spin opacity-70`})}),V.length>0&&l(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:V.map(e=>{let t=_t(e.kind),n=vt(Rt,e.url),i=re?vt(re,e.url):null;return r(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[l(`button`,{type:`button`,onClick:()=>te(e),className:`relative h-16 w-full overflow-hidden rounded border border-border hover:border-primary`,title:`${t} · ${Ae(e.timestamp)}`,children:l(zt,{url:e.url,label:t})}),r(`figcaption`,{className:`min-w-0 px-0.5`,children:[l(`div`,{className:`truncate text-[10px] font-medium leading-tight text-foreground`,title:t,children:t}),l(`div`,{className:`text-[10px] leading-tight text-foreground-subtle`,title:Ae(e.timestamp),children:we(e.timestamp)})]}),l(mt,{localUrl:n,publicUrl:i})]},e.mediaId)})}),ie,ge&&r(j,{variant:`secondary`,onClick:U,disabled:ne,children:[ne?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(P,{className:`h-3.5 w-3.5`}),` `,`View clip`]}),l(Ot,{deviceId:t.deviceId,trackId:t.trackId,...(D?.markForTrain??t.markForTrain)===void 0?{}:{markForTrain:D?.markForTrain??t.markForTrain},...(D?.debug??t.debug)===void 0?{}:{debug:D?.debug??t.debug},...(D?.favourited??t.favourited)===void 0?{}:{favourited:D?.favourited??t.favourited},onChange:f}),De!==null&&r(`div`,{className:`rounded-lg border border-warning/40 bg-warning/8 px-3 py-2`,children:[l(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`Best shot`}),l(`p`,{className:`mt-0.5 text-xs text-foreground`,children:De.sentence}),l(`code`,{className:`mt-1 block break-all font-mono text-[10px] text-foreground-subtle`,children:De.raw})]}),r(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[l(J,{label:`Camera`,value:n}),l(J,{label:`Class`,value:t.className}),l(J,{label:`Label`,value:t.label??`—`}),l(J,{label:`Sub-label`,value:t.subLabel??`—`}),l(J,{label:`Importance`,value:xe}),l(J,{label:`Zones visited`,value:Se}),l(J,{label:`Audio heard`,value:Te}),l(J,{label:`Total distance`,value:Ee}),l(J,{label:`First seen`,value:ke}),l(J,{label:`Last seen`,value:je}),l(J,{label:`Track`,value:t.trackId,mono:!0})]})]}),l(`footer`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]`,children:l(`span`,{title:a?void 0:Pt,children:r(j,{variant:`secondary`,onClick:ve,disabled:!a||v.isPending,children:[v.isPending?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(y,{className:`h-3.5 w-3.5`}),` `,`Delete track`]})})})]})})}var Gt={status:`debug.tape.status`,promote:`debug.tape.promote`,list:`debug.tape.list`,tracks:`debug.tape.tracks`,review:`debug.tape.review`,release:`debug.tape.release`,remove:`debug.tape.delete`},Kt={setRelation:`debug.gt.setRelation`,setPurity:`debug.gt.setPurity`,list:`debug.gt.list`},qt=p(`/addon/pipeline-analytics/tape-export`),Jt=10*6e4;function Yt(e){return`${qt}?tapeId=${encodeURIComponent(e)}`}var Xt=`The server answered in a shape this build does not understand.`;function Zt(e){return e instanceof Error?e.message:`The action failed.`}function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Qt(e,t){if(!(t in e))return;let n=e[t];return n===null?null:typeof n==`number`&&Number.isFinite(n)?n:void 0}function Z(e,t){let n=e[t];return typeof n==`string`?n:null}function $t(e,t){let n=e[t];return typeof n==`boolean`?n:null}function en(e,t){if(!Array.isArray(e))return null;let n=[];for(let r of e){let e=t(r);if(e===null)return null;n.push(e)}return n}function tn(e){return e===`off`||e===`recording`||e===`refused`||e===`failing`||e===`unknown`}function nn(e){if(!Y(e))return null;let t=X(e,`deviceId`),n=e.state,r=X(e,`gapsSinceArmed`),i=Qt(e,`segmentsHeld`),a=Qt(e,`bytesLastHour`),o=Qt(e,`bytesHeld`);if(t===null||!tn(n)||r===null||i===void 0||a===void 0||o===void 0)return null;let s=Z(e,`reason`),c=X(e,`segmentOriginMs`),l=X(e,`framesPerMin`),u=X(e,`heldFromMs`),d=X(e,`heldToMs`),f=Z(e,`shelfError`);return{deviceId:t,state:n,gapsSinceArmed:r,segmentsHeld:i,bytesLastHour:a,bytesHeld:o,...s===null?{}:{reason:s},...c===null?{}:{segmentOriginMs:c},...l===null?{}:{framesPerMin:l},...u===null?{}:{heldFromMs:u},...d===null?{}:{heldToMs:d},...f===null?{}:{shelfError:f}}}function rn(e){return Y(e)?en(e.cameras,nn):null}function an(e){if(!Y(e))return null;let t=Z(e,`id`),n=X(e,`deviceId`),r=Z(e,`scenario`),i=e.lighting,a=X(e,`fromMs`),o=X(e,`toMs`),s=e.state,c=X(e,`frames`),l=X(e,`gaps`),u=X(e,`bytes`),d=$t(e,`reviewed`),f=$t(e,`released`),p=en(e.tracks,e=>typeof e==`string`?e:null),m=X(e,`tracksStillStored`);return t===null||n===null||r===null||i!==`day`&&i!==`ir`||a===null||o===null||s!==`complete`&&s!==`incomplete`||c===null||l===null||u===null||d===null||f===null||p===null||m===null?null:{id:t,deviceId:n,scenario:r,note:Z(e,`note`),lighting:i,fromMs:a,toMs:o,state:s,frames:c,gaps:l,bytes:u,reviewed:d,released:f,tracks:p,tracksStillStored:m}}function on(e){return Y(e)?en(e.tapes,an):null}function sn(e){if(!Y(e))return null;let t=Z(e,`trackId`),n=X(e,`firstT`),r=X(e,`lastT`),i=X(e,`boundFrames`),a=Z(e,`cls`),o=$t(e,`stillStored`);return t===null||n===null||r===null||i===null||a===null||o===null?null:{trackId:t,firstT:n,lastT:r,boundFrames:i,cls:a,stillStored:o}}function cn(e){if(!Y(e))return null;let t=Z(e,`tapeId`),n=X(e,`deviceId`),r=X(e,`fromMs`),i=X(e,`toMs`),a=$t(e,`reviewed`),o=en(e.lanes,sn);return t===null||n===null||r===null||i===null||a===null||o===null?null:{tapeId:t,deviceId:n,fromMs:r,toMs:i,reviewed:a,lanes:o}}function ln(e){if(!Y(e))return null;if(e.ok===!1){let t=Z(e,`reason`),n=Z(e,`detail`);return t===null||n===null?null:{ok:!1,reason:t,detail:n}}if(e.ok!==!0)return null;let t=Z(e,`tapeId`),n=e.state,r=X(e,`frames`),i=X(e,`gaps`),a=X(e,`pinnedTracks`),o=X(e,`bytes`);return t===null||n!==`complete`&&n!==`incomplete`||r===null||i===null||a===null||o===null?null:{ok:!0,tapeId:t,state:n,frames:r,gaps:i,pinnedTracks:a,bytes:o}}function un(e){if(!Y(e))return null;let t=e.status;if(t===`released`){let n=X(e,`unpinned`),r=$t(e,`pinsSettled`);return n===null||r===null?null:{status:t,unpinned:n,pinsSettled:r}}if(t===`already-released`||t===`not-found`)return{status:t};if(t===`unavailable`){let n=Z(e,`reason`);return n===null?null:{status:t,reason:n}}return null}function dn(e){if(!Y(e))return null;let t=e.status;if(t===`deleted`||t===`pins-owed`||t===`not-found`)return{status:t};if(t===`unavailable`){let n=Z(e,`reason`);return n===null?null:{status:t,reason:n}}return null}function fn(e){switch(e.status){case`released`:case`deleted`:return null;case`already-released`:return`This tape was already released.`;case`not-found`:return`That tape no longer exists — it may have been released or deleted elsewhere.`;case`pins-owed`:return`Refused: this tape still names pins not yet taken back. Try again shortly — the ledger settles them automatically.`;case`unavailable`:return`Unavailable on this node: ${e.reason}`}}function pn(e){if(!Y(e))return null;let t=Z(e,`leftTrackId`),n=Z(e,`rightTrackId`),r=e.relation,i=e.presence;return t===null||n===null||r!==`same-subject`&&r!==`different-subjects`?null:{leftTrackId:t,rightTrackId:n,relation:r,presence:i===`continuous`?`continuous`:null}}function mn(e){if(!Y(e))return null;let t=Z(e,`sourceTrackId`),n=e.purity;return t===null||n!==`mixed`&&n!==`not-a-subject`?null:{sourceTrackId:t,purity:n,switchAtMs:X(e,`switchAtMs`)}}function hn(e){if(!Y(e))return null;let t=en(e.relations,pn),n=en(e.purities,mn),r=$t(e,`truncated`);return t===null||n===null||r===null?null:{relations:t,purities:n,truncated:r}}function gn(e){if(!e.truncated)return null;let t=e.relations.length+e.purities.length;return`Showing the first ${String(t)} marks — more exist for this window.`}function _n(e){return e.filter(e=>e.segmentsHeld===null||e.segmentsHeld>0).map(e=>({deviceId:e.deviceId,segmentsUnknown:e.segmentsHeld===null}))}function vn(e){return e.slice(1).map((t,n)=>({trackId:e[n]??t,otherTrackId:t}))}function yn(e){return e.flatMap((t,n)=>e.slice(n+1).map(e=>({trackId:t,otherTrackId:e})))}function bn(e,t){let n=[];for(let r of t.relations){let t=r.leftTrackId===e?r.rightTrackId:r.rightTrackId===e?r.leftTrackId:null;if(t===null)continue;let i=r.relation===`same-subject`?`same as`:`different from`;n.push(`${i} ${t}${r.presence===`continuous`?` (continuous)`:``}`)}for(let r of t.purities)r.sourceTrackId===e&&n.push(r.purity===`not-a-subject`?`not a subject`:r.switchAtMs===null?`mixed`:`mixed at switch`);return n}function xn(e){switch(e.state){case`off`:return`Off`;case`recording`:return`Recording`;case`refused`:return`Refused: ${e.reason??`unknown reason`}`;case`failing`:return`Failing: ${e.reason??`unknown reason`}`;case`unknown`:return`Unknown: ${e.reason??`unknown reason`}`}}var Sn={"window-too-long":`A promoted window is at most 30 minutes.`,"window-in-future":`The window ends in the future.`,"window-not-recorded":`No segment covers that window — the camera was not recording then, or it is older than 24 h.`,"invalid-scenario":`The scenario must be a slug: lowercase letters, digits and dashes, 3–64 characters.`,"promotion-budget":`A promotion budget is full (60 tapes, 1 GiB, 3 000 pinned tracks). Release or delete a tape already committed as a case first.`,"empty-window":`No frame was recorded in that window.`,"shelf-unreadable":`The camera's recorded segments could not be listed, so the window cannot be proven whole.`,"not-post-processing-node":`This node does not post-process frames, so it records no tracking tapes.`,"artifacts-elsewhere":`The artifacts storage location is on another node; tapes are recorded only where it lives.`,"tapes-not-started":`The tape recorder has not started on this node (or failed to).`};function Cn(e,t){let n=Sn[e]??`Refused (${e}).`;return t.length>0?`${n} ${t}`:n}function wn(e){if(e.length===0)return null;let t=new Date(e).getTime();return Number.isFinite(t)?t:null}function Tn(e){return e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function En(e){return e===null?`unknown`:Tn(e)}function Dn(e){return e===null?`unknown`:String(e)}function On(e,t){let n=t.trim();return e===404?`This tape no longer exists on this node (unknown tape).`:e===503?n.length>0?n:`Tapes are unavailable on this node.`:e===500?n.length>0?n:`The export could not be read (the tape may have just been released or deleted).`:`Download failed (${String(e)}).`}n();function kn({cameras:e,call:t,onPromoted:n}){let[i,a]=c(``),[o,s]=c(``),[u,d]=c(``),[f,p]=c(``),[m,h]=c(``),[g,_]=c(`auto`),[v,y]=c(!1),[b,x]=c(null),S=async()=>{let r=Number.parseInt(i===``?e[0]?.value??``:i,10),a=wn(o),s=wn(u);if(!Number.isFinite(r)||a===null||s===null){x(`Pick a camera and both ends of the window.`);return}y(!0),x(null);try{let e=ln(await t(Gt.promote,{deviceId:r,fromMs:a,toMs:s,scenario:f,...m.trim().length>0?{note:m.trim()}:{},...g===`day`||g===`ir`?{lighting:g}:{}}));e===null?x(Xt):e.ok?(x(`Promoted ${e.tapeId}: ${String(e.frames)} frames, ${Tn(e.bytes)}, ${String(e.pinnedTracks)} tracks pinned`+(e.state===`incomplete`?` — incomplete (it has gaps) and cannot become a case.`:`.`)),n()):x(Cn(e.reason,e.detail))}catch(e){x(Zt(e))}finally{y(!1)}};return r(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border px-3 py-2`,children:[l(`div`,{className:`w-40`,children:l(D,{value:i,options:[...e],onChange:e=>a(e.target.value),"aria-label":`Camera`})}),l(O,{type:`datetime-local`,"aria-label":`From`,value:o,onChange:e=>s(e.target.value),className:`w-48`}),l(O,{type:`datetime-local`,"aria-label":`To`,value:u,onChange:e=>d(e.target.value),className:`w-48`}),l(O,{"aria-label":`Scenario`,placeholder:`615-door-groups`,value:f,onChange:e=>p(e.target.value),className:`w-44`}),l(O,{"aria-label":`Note`,placeholder:`optional note`,value:m,onChange:e=>h(e.target.value),className:`w-52`}),l(`div`,{className:`w-28`,children:l(D,{value:g,"aria-label":`Lighting`,options:[{value:`auto`,label:`Lighting: auto`},{value:`day`,label:`day`},{value:`ir`,label:`ir`}],onChange:e=>_(e.target.value)})}),r(j,{onClick:()=>void S(),disabled:v||e.length===0,children:[v?l(H,{className:`h-3.5 w-3.5 animate-spin`}):null,` Promote window`]}),l(`p`,{className:`w-full text-xs text-foreground-subtle`,children:`A promoted tape may be shared as a test case — keep the scenario slug and note free of names or other personal data.`}),b!==null&&l(`p`,{className:`w-full text-xs text-foreground`,children:b})]})}var An=`pipeline-analytics`,jn=`debug.listTracks`,Mn=`debug.analyze`,Nn=p(`/addon/pipeline-analytics/debug-export`);function Pn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`string`?n:null}function $(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Fn(e,t){let n=e[t];return typeof n==`boolean`?n:null}function In(e){return e===`error`||e===`warn`||e===`info`}function Ln(e){if(!Pn(e))return null;let t=Q(e,`code`),n=Q(e,`detail`),r=e.severity;return t===null||n===null||!In(r)?null:{code:t,severity:r,detail:n}}function Rn(e){if(!Pn(e))return null;let t=Q(e,`trackId`),n=$(e,`deviceId`),r=Q(e,`className`),i=$(e,`firstSeen`),a=$(e,`lastSeen`),o=$(e,`durationMs`),s=Fn(e,`active`);if(t===null||n===null||r===null||i===null||a===null||o===null||s===null)return null;let c=Q(e,`label`),l=Q(e,`subLabel`),u=Q(e,`previewMissReason`),d=Fn(e,`markForTrain`),f=Fn(e,`favourited`);return{trackId:t,deviceId:n,className:r,...c===null?{}:{label:c},...l===null?{}:{subLabel:l},firstSeen:i,lastSeen:a,durationMs:o,active:s,timestamp:i,windowMs:o,importance:$(e,`importance`)??0,bestEventId:Q(e,`bestEventId`)??``,...d===null?{}:{markForTrain:d},...f===null?{}:{favourited:f},debug:!0,...u===null||u.length===0?{}:{previewMissReason:u}}}function zn(e){let t=Rn(e);if(t===null||!Pn(e))return null;let n=$(e,`mediaCount`),r=$(e,`eventCount`),i=$(e,`positionCount`);if(n===null||r===null||i===null)return null;let a=e.mediaKinds,o=e.findings;if(!Array.isArray(a)||!Array.isArray(o))return null;let s=a.filter(e=>typeof e==`string`),c=[];for(let e of o){let t=Ln(e);t!==null&&c.push(t)}let l=e.thumbnailProvenance;return{...t,mediaCount:n,mediaKinds:s,eventCount:r,positionCount:i,findings:c,...it(l)?{thumbnailProvenance:l}:{}}}function Bn(e){if(!Pn(e))return null;let t=Fn(e,`truncated`),n=e.tracks;if(t===null||!Array.isArray(n))return null;let r=[];for(let e of n){let t=Rn(e);if(t===null)return null;r.push(t)}return{tracks:r,truncated:t}}function Vn(e){if(!Pn(e))return null;let t=e.reports,n=e.vanished;if(!Array.isArray(t)||!Array.isArray(n))return null;let r=[];for(let e of t){let t=zn(e);if(t===null)return null;r.push(t)}return{reports:r,vanished:n.filter(e=>typeof e==`string`)}}var Hn={MEDIA_EVICTED_OR_NEVER:`no media`,MISSING_KEYFRAME:`no keyframe`,MISSING_FIRSTFRAME:`no first frame`,MISSING_LASTFRAME:`no last frame`,MISSING_THUMBNAIL:`no thumbnail`,MISSING_BEST_CROP:`no crop`,SHORT_TRACK:`very short`,ZERO_EVENTS:`no events`,ZERO_POSITIONS:`no trajectory`,NO_PERIODIC_SNAPSHOTS:`no snapshots`,LASTFRAME_STALE:`stale last frame`,MEDIA_STOPPED_EARLY:`media stopped early`,NO_BEST_EVENT:`no best event`,LOW_BEST_SCORE:`low score`,UNSCORED_LABEL:`unscored label`,BEST_SHOT_STANDIN:`stand-in best shot`,BEST_SHOT_RASTER:`low-res best shot`};function Un(e){return Hn[e]??e}var Wn={error:0,warn:1,info:2};function Gn(e){return e.toSorted((e,t)=>Wn[e.severity]-Wn[t.severity]||e.code.localeCompare(t.code))}function Kn(e){return e.length===0?Nn:`${Nn}?deviceIds=${e.join(`,`)}`}function qn(e){if(e<1e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.round(e/1e3);if(t<60)return`${String(t)}s`;let n=Math.floor(t/60);return`${String(n)}m ${String(t%60).padStart(2,`0`)}s`}function Jn(e,t){return`${String(e)}:${t}`}function Yn(e,t){let n=[],r=new Set;for(let i of e){let e=Jn(i.deviceId,i.trackId);!t.has(e)||r.has(e)||(r.add(e),n.push({deviceId:i.deviceId,trackId:i.trackId}))}return n}n();function Xn({tapeId:e,call:t,onClose:n,onChanged:i}){let o=a({queryKey:[`events-debug`,`tapes`,`tracks`,e],queryFn:async()=>cn(await t(Gt.tracks,{tapeId:e}))}),s=o.data??null,u=a({queryKey:[`events-debug`,`tapes`,`marks`,e],enabled:s!==null,queryFn:async()=>s===null?null:hn(await t(Kt.list,{deviceId:s.deviceId,since:s.fromMs-Jt,until:s.toMs+Jt,limit:5e3}))}),[d,f]=c([]),[p,m]=c(``),[h,g]=c(null),_=e=>f(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),v=async e=>{g(null);try{for(let[n,r]of e)await t(n,r);f([]),await u.refetch(),i()}catch(e){g(Zt(e))}};if(s===null)return o.isLoading?l(`p`,{className:`text-xs`,children:`Loading the tape…`}):l(F,{message:Xt});let y=s.deviceId,b=(e,t)=>v(e.map(e=>[Kt.setRelation,{deviceId:y,...e,relation:t}])),x=e=>{let t=Number.parseFloat(p),n=e===`mixed`&&Number.isFinite(t)?s.fromMs+t*1e3:void 0;return v(d.map(t=>[Kt.setPurity,{deviceId:y,trackId:t,purity:e,...n===void 0?{}:{switchAtMs:Math.round(n)}}]))},S=u.data==null?null:gn(u.data);return r(`div`,{className:`space-y-2 rounded-md border border-primary/40 px-3 py-2`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[r(`span`,{className:`text-xs font-medium`,children:[s.tapeId,` — `,String(s.lanes.length),` tracks`]}),l(j,{disabled:d.length<2,onClick:()=>void b(vn(d),`same-subject`),children:`Same subject`}),l(j,{variant:`secondary`,disabled:d.length<2,onClick:()=>void b(yn(d),`different-subjects`),children:`Different subjects`}),l(O,{"aria-label":`Changed at (s from tape start)`,placeholder:`changed at s`,value:p,onChange:e=>m(e.target.value),className:`w-28`}),l(j,{variant:`secondary`,disabled:d.length!==1,onClick:()=>void x(`mixed`),children:`Mixed`}),l(j,{variant:`secondary`,disabled:d.length===0,onClick:()=>void x(`not-a-subject`),children:`Not a subject`}),l(j,{variant:s.reviewed?`secondary`:`primary`,onClick:()=>void v([[Gt.review,{tapeId:s.tapeId,reviewed:!s.reviewed}]]).then(()=>o.refetch()),children:s.reviewed?`Mark not reviewed`:`Mark reviewed`}),l(j,{variant:`ghost`,onClick:n,children:`Close`})]}),h!==null&&l(F,{message:h}),S!==null&&l(F,{variant:`warning`,message:S}),l(`ul`,{className:`space-y-1`,children:s.lanes.toSorted((e,t)=>e.firstT-t.firstT).map(e=>l(Zn,{lane:e,marks:u.data===null||u.data===void 0?[]:bn(e.trackId,u.data),selected:d.includes(e.trackId),onToggle:()=>_(e.trackId)},e.trackId))})]})}function Zn({lane:e,marks:t,selected:n,onToggle:i}){let{src:a}=Ve(e.stillStored?He(`track`,e.trackId):void 0);return r(`li`,{className:`flex items-center gap-2 text-xs`,children:[l(`input`,{type:`checkbox`,"aria-label":`select ${e.trackId}`,checked:n,onChange:i}),a===null?l(`div`,{className:`h-10 w-10 rounded bg-surface-hover`}):l(`img`,{src:a,alt:e.trackId,className:`h-10 w-10 rounded object-cover`}),l(`span`,{className:`font-mono`,children:e.trackId}),l(`span`,{children:e.cls}),r(`span`,{className:`text-foreground-subtle`,children:[qn(e.firstT),` → `,qn(e.lastT),` · `,String(e.boundFrames),` `,`frames`]}),!e.stillStored&&l(`span`,{className:`text-foreground-subtle`,children:`not stored — marked through the tape`}),t.map(e=>l(U,{variant:`info`,children:e},e))]})}n();var Qn=`camstack_admin_token`;function $n(){let e=m();return(t,n)=>e.trpcClient.addons.custom.mutate({addonId:An,action:t,input:n})}async function er(e,t){let n=localStorage.getItem(Qn),r={};n!==null&&(r.Authorization=`Bearer ${n}`);let i=await fetch(Yt(e),{headers:r});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(On(i.status,e))}let a=await i.blob(),o=i.headers.get(`content-disposition`),s=(o===null?null:/filename="?([^";]+)"?/i.exec(o))?.[1]?.trim()??t,c=URL.createObjectURL(a),l=document.createElement(`a`);l.href=c,l.download=s,l.click(),setTimeout(()=>URL.revokeObjectURL(c),6e4)}function tr(){let[e,t]=c(!1);return l(oe,{expanded:e,onExpandedChange:t,header:l(`span`,{className:`text-sm font-medium text-foreground`,children:`Tracking tapes`}),children:l(nr,{})})}function nr(){let e=$n(),t=ue({isCamera:!0,projection:`slim`}),n=i(()=>{let e=new Map;for(let n of t.data??[])e.set(n.id,n.name);return t=>e.get(t)??`Camera ${String(t)}`},[t.data]),o=a({queryKey:[`events-debug`,`tapes`,`status`],queryFn:async()=>rn(await e(Gt.status,{}))}),s=a({queryKey:[`events-debug`,`tapes`,`list`],queryFn:async()=>on(await e(Gt.list,{}))}),[u,d]=c(null),[f,p]=c(null),m=async e=>{p(null);try{await er(e.id,`${e.scenario}.tape-bundle.json.gz`)}catch(e){p(Zt(e))}},h=async t=>{let n=un(await e(Gt.release,{tapeId:t.id}));if(n===null)throw Error(Xt);let r=fn(n);if(r!==null)throw Error(r);await s.refetch()},g=async t=>{let n=dn(await e(Gt.remove,{tapeId:t.id}));if(n===null)throw Error(Xt);let r=fn(n);if(r!==null)throw Error(r);await s.refetch()};return r(`div`,{className:`space-y-3`,children:[r(`p`,{className:`text-xs text-foreground-subtle`,children:[`A camera records while its `,l(`strong`,{children:`Record the track history`}),` switch (camera settings → Tracking) is on; segments are kept 24 h. Promote a window worth keeping, label it in the review, mark it reviewed, download it and turn it into a test case with`,` `,l(`code`,{children:`npm run tracking-bench -- case`}),`.`]}),f!==null&&l(F,{message:f}),o.isLoading&&l(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading camera status…`}),o.data===null&&l(F,{message:`The server answered in a shape this build does not understand.`}),r(`table`,{className:`w-full text-xs`,children:[l(`thead`,{children:r(`tr`,{className:`text-left text-foreground-subtle`,children:[l(`th`,{children:`Camera`}),l(`th`,{children:`State`}),l(`th`,{children:`Frames/min`}),l(`th`,{children:`Last hour`}),l(`th`,{children:`Held`}),l(`th`,{children:`Gaps`})]})}),l(`tbody`,{children:(o.data??[]).map(e=>r(`tr`,{children:[l(`td`,{children:n(e.deviceId)}),l(`td`,{children:l(U,{variant:e.state===`recording`?`success`:e.state===`off`?`default`:e.state===`unknown`?`warning`:`danger`,children:xn(e)})}),l(`td`,{children:e.framesPerMin===void 0?`—`:String(Math.round(e.framesPerMin))}),l(`td`,{title:e.shelfError,children:En(e.bytesLastHour)}),r(`td`,{title:e.shelfError,children:[Dn(e.segmentsHeld),` seg · `,En(e.bytesHeld)]}),l(`td`,{children:String(e.gapsSinceArmed)})]},e.deviceId))})]}),l(kn,{cameras:_n(o.data??[]).map(e=>({value:String(e.deviceId),label:e.segmentsUnknown?`${n(e.deviceId)} (segments unknown)`:n(e.deviceId)})),call:e,onPromoted:()=>void s.refetch()}),s.isLoading&&l(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading promoted tapes…`}),s.data===null&&l(F,{message:`The server answered in a shape this build does not understand.`}),r(`table`,{className:`w-full text-xs`,children:[l(`thead`,{children:r(`tr`,{className:`text-left text-foreground-subtle`,children:[l(`th`,{children:`Scenario`}),l(`th`,{children:`Camera`}),l(`th`,{children:`Window`}),l(`th`,{children:`State`}),l(`th`,{children:`Tracks`}),l(`th`,{})]})}),l(`tbody`,{children:(s.data??[]).map(e=>r(`tr`,{children:[l(`td`,{children:e.scenario}),l(`td`,{children:n(e.deviceId)}),r(`td`,{children:[new Date(e.fromMs).toLocaleString(),` · `,qn(e.toMs-e.fromMs),` `,`· `,e.lighting]}),r(`td`,{children:[l(U,{variant:e.state===`complete`?`success`:`warning`,children:e.state}),` `,e.reviewed&&l(U,{variant:`info`,children:`reviewed`}),` `,e.released&&l(U,{children:`released`})]}),r(`td`,{children:[String(e.tracksStillStored),`/`,String(e.tracks.length),` stored`]}),r(`td`,{className:`space-x-1 text-right`,children:[l(j,{variant:`secondary`,"aria-label":`Review ${e.scenario}`,onClick:()=>d(e.id),children:`Review`}),l(j,{variant:`ghost`,"aria-label":`Download ${e.scenario}`,onClick:()=>void m(e),children:l(xe,{className:`h-3.5 w-3.5`})}),l(le,{label:`Release`,icon:se,title:`Release ${e.scenario}?`,description:`Releasing returns this tape's pinned tracks to ordinary retention — they can be pruned from then on. The promoted bundle itself is kept until deleted.`,confirmLabel:`Release`,triggerVariant:`ghost`,confirmVariant:`danger`,disabled:e.released,action:()=>h(e)}),l(le,{label:`Delete`,icon:y,title:`Delete ${e.scenario}?`,description:`Deleting removes the promoted bundle and its index row for good. Its tracks' pins are released first — this cannot be undone.`,confirmLabel:`Delete`,triggerVariant:`ghost`,confirmVariant:`danger`,action:()=>g(e)})]})]},e.id))})]}),u!==null&&l(Xn,{tapeId:u,call:e,onClose:()=>d(null),onChanged:()=>void s.refetch()})]})}n();var rr=`all`,ir=`The server answered in a shape this build does not understand.`,ar={error:`danger`,warn:`warning`,info:`info`};function or({findings:e}){return e.length===0?l(U,{variant:`success`,children:`no anomaly found`}):l(`div`,{className:`flex flex-wrap gap-1`,children:Gn(e).map(e=>l(U,{variant:ar[e.severity],title:e.detail,children:Un(e.code)},e.code))})}function sr({track:e,report:t,analyzing:n}){let i=ct(t?.previewMissReason??e.previewMissReason);return r(`div`,{className:`space-y-1 border-t border-border pt-1.5`,children:[t===void 0?l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n?`analysing…`:`not analysed`}):r(o,{children:[l(or,{findings:t.findings}),r(`p`,{className:`text-[10px] text-foreground-subtle`,title:t.mediaKinds.length>0?t.mediaKinds.join(`, `):`no media of any kind`,children:[String(t.mediaCount),` media · `,String(t.eventCount),` events ·`,` `,String(t.positionCount),` positions`]})]}),i!==null&&l(`p`,{className:`text-[10px] text-foreground-subtle`,title:i.raw,children:i.sentence})]})}function cr(){let e=m(),[t,n]=c(rr),[o,s]=c(!1),[u,d]=c(null),[f,p]=c(new Set),[h,g]=c(null),[_,v]=c(null),[y,b]=c(null),[x,C]=c([]),w=Tt(),E=ue({isCamera:!0,projection:`slim`}),O=i(()=>[{value:rr,label:`All cameras`},...(E.data??[]).map(e=>({value:String(e.id),label:e.name}))],[E.data]),k=i(()=>{let e=new Map;for(let t of E.data??[])e.set(t.id,t.name);return e},[E.data]),A=e=>k.get(e)??`Camera ${String(e)}`,M=i(()=>t===rr?[]:[Number.parseInt(t,10)],[t]),N=a({queryKey:[`events-debug`,`list`,M],queryFn:async()=>Bn(await e.trpcClient.addons.custom.mutate({addonId:An,action:jn,input:M.length===0?{}:{deviceIds:M}}))}),ee=i(()=>(N.data?.tracks??[]).map(e=>e.trackId),[N.data]),P=a({queryKey:[`events-debug`,`analyze`,ee],enabled:ee.length>0,queryFn:async()=>Vn(await e.trpcClient.addons.custom.mutate({addonId:An,action:Mn,input:{trackIds:ee}}))}),I=i(()=>{let e=new Map;for(let t of P.data?.reports??[])e.set(t.trackId,t);return e},[P.data]),L=N.data?.tracks??[],te=N.data===null||P.data===null,ne=()=>{N.refetch(),P.refetch()},ae=e=>{p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},oe=()=>{p(new Set(L.map(e=>Jn(e.deviceId,e.trackId))))},z=()=>p(new Set),B=async(e,t)=>{let n=e===`analyzed`?{debug:!1}:{favourited:!0},r=0,i=[];for(let e of t)try{await w.mutateAsync({deviceId:e.deviceId,trackId:e.trackId,flags:n}),r+=1}catch{i.push(e.trackId)}return{applied:r,refused:i}},V=e=>{if(!W||_!==null)return;let t=Yn(L,f);t.length!==0&&(v(e),b(null),(async()=>{let n=await B(e,t);v(null);let r=new Set(n.refused);p(new Set(t.filter(e=>r.has(e.trackId)).map(e=>Jn(e.deviceId,e.trackId)))),e===`analyzed`&&C(t.filter(e=>!r.has(e.trackId))),n.refused.length>0&&b(`${String(n.refused.length)} of ${String(t.length)} were refused by the server and are still selected. Check the hub log.`),N.refetch()})())},se=()=>{let e=x;e.length===0||_!==null||(v(`analyzed`),b(null),(async()=>{for(let t of e)try{await w.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,flags:{debug:!0}})}catch{b(`Some tracks could not be re-marked. Refresh and try again.`)}v(null),C([]),N.refetch()})())},le=async()=>{s(!0),d(null);try{await We(Kn(M),`camstack-debug.zip`)}catch(e){d(e instanceof Error?e.message:`Export failed.`)}finally{s(!1)}},de=_!==null;return l(Be,{children:r(`section`,{className:`space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[l(`div`,{className:`w-44`,children:l(D,{value:t,options:O,onChange:e=>n(e.target.value)})}),r(j,{variant:`secondary`,onClick:ne,disabled:N.isFetching,children:[N.isFetching?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(R,{className:`h-3.5 w-3.5`}),`Refresh`]}),r(j,{onClick:()=>void le(),disabled:o||L.length===0,children:[o?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(xe,{className:`h-3.5 w-3.5`}),`Export all (`,String(L.length),`)`]}),L.length>0&&f.size<L.length&&l(j,{variant:`ghost`,onClick:oe,children:`Select all`})]}),r(`p`,{className:`text-xs text-foreground-subtle`,children:[`A `,l(`code`,{children:`debug`}),` mark does not pin retention — this lists the marked tracks that still exist. A track whose media was evicted shows as missing media. Use `,l(`strong`,{children:`Keep`}),` `,`to hold a selection against pruning while you investigate, and `,l(`strong`,{children:`Analyzed`}),` `,`to un-mark the ones you are finished with.`]}),l(tr,{}),N.isError&&l(F,{message:`Could not load the marked tracks.`}),te&&!N.isError&&l(F,{message:ir}),u!==null&&l(F,{message:u}),y!==null&&l(F,{message:y}),N.data?.truncated===!0&&l(F,{message:`A camera filled the per-camera cap — some marked tracks are not listed. Un-mark a few, or filter to one camera.`}),(P.data?.vanished.length??0)>0&&r(`p`,{className:`text-xs text-foreground-subtle`,children:[String(P.data?.vanished.length),` marked track(s) were evicted between the list and the analysis.`]}),f.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[String(f.size),` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[l(`span`,{title:W?void 0:`Track flags arrive with the next server update`,children:r(j,{variant:`secondary`,onClick:()=>V(`keep`),disabled:!W||de,children:[_===`keep`?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(T,{className:`h-3.5 w-3.5`}),` `,`Keep`]})}),l(`span`,{title:W?void 0:`Track flags arrive with the next server update`,children:r(j,{onClick:()=>V(`analyzed`),disabled:!W||de,children:[_===`analyzed`?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(fe,{className:`h-3.5 w-3.5`}),` `,`Analyzed`]})}),l(j,{variant:`ghost`,onClick:z,disabled:de,children:l(ce,{className:`h-3.5 w-3.5`})})]})]}),x.length>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-border bg-surface px-3 py-2`,children:[r(`span`,{className:`text-xs text-foreground`,children:[String(x.length),` track(s) marked analyzed and removed from this list.`]}),r(j,{variant:`ghost`,onClick:se,disabled:de,children:[l(re,{className:`h-3.5 w-3.5`}),` Undo`]}),l(j,{variant:`ghost`,onClick:()=>C([]),disabled:de,children:l(ce,{className:`h-3.5 w-3.5`})})]}),N.isLoading?l(S,{children:l(`div`,{className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:`Loading…`})}):L.length===0?l(S,{children:r(`div`,{className:`flex flex-col items-center gap-2 px-3 py-8 text-center`,children:[l(ie,{className:`h-5 w-5 text-foreground-subtle`}),l(`p`,{className:`text-xs text-foreground-subtle`,children:`No track is marked for debug. Mark one from a track's actions to see it here.`})]})}):l(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:L.map(e=>{let t=I.get(e.trackId);return l(ut,{row:e,cameraName:A(e.deviceId),nowMs:e.lastSeen,selected:f.has(Jn(e.deviceId,e.trackId)),onToggleSelect:ae,onOpenDetail:g,...t?.thumbnailProvenance===void 0?{}:{provenance:t.thumbnailProvenance},footer:l(sr,{track:e,report:t,analyzing:P.isFetching})},Jn(e.deviceId,e.trackId))})}),h&&l(Wt,{row:h,cameraName:A(h.deviceId),deleteAvailable:Nt,onClose:()=>g(null),onDeleted:()=>{g(null),N.refetch()},onFlagsChanged:e=>{e.debug||(g(null),N.refetch())}})]})})}var lr=200,ur=3e4,dr=[];function fr(e){let t=m(),n=e.deviceIds.length>0,r=[...e.deviceIds].sort((e,t)=>e-t),{data:i,isLoading:o}=a({queryKey:[`events-feed`,r,e.since,e.until,e.minImportance??null,e.classFilter??null],enabled:n,staleTime:ur,refetchInterval:ur,queryFn:async()=>(await t.trpcClient.pipelineAnalytics.getKeyEventsBatch.query({deviceIds:r,since:e.since,until:e.until,limit:lr,...e.minImportance===void 0?{}:{minImportance:e.minImportance},...e.classFilter===void 0?{}:{classFilter:e.classFilter}})).map(e=>e.events.map(t=>({...t,deviceId:e.deviceId})))});return{rows:Qe(Ze(i??dr),`importance`),isLoading:n&&o}}n();var pr=[`events-feed`],mr=2e3;function hr(n){let r=s(),i=n?.paused===!0,a=t(r);a.current=r;let o=t(i);o.current=i;let[l,d]=c(!1),f=e(()=>{a.current.invalidateQueries({queryKey:pr})},[]),p=t(void 0);p.current||=Ne({delayMs:mr,invalidate:()=>{o.current?d(!0):f()}}),u(()=>()=>p.current?.cancel(),[]),u(()=>{i||!l||(d(!1),f())},[i,l,f]);let m=e(()=>{d(!1),f()},[f]);return ve(Fe.PipelineAnalyticsDetectionEvent,()=>{p.current?.trigger()}),ve(Fe.PipelineAnalyticsTrackEnded,()=>{p.current?.trigger()}),{pending:l,refreshNow:m}}n();function gr({groups:e,selected:t,onChange:n,loading:a=!1}){let{t:o}=Ie(),[s,u]=c(!1),[d,f]=c(``),[p,m]=c(new Set),h=d.trim().toLowerCase(),g=e=>h.length===0||x(e,o).toLowerCase().includes(h),y=i(()=>e.map(e=>({macro:e.macro,subs:e.subs.filter(t=>g(t)||g(e.macro))})).filter(e=>g(e.macro)||e.subs.length>0),[e,h]),b=e=>m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),S=e=>{let r=new Set(t),i=t.has(e.macro.kind)&&e.subs.every(e=>t.has(e.kind)),a=[e.macro.kind,...e.subs.map(e=>e.kind)];if(i)for(let e of a)r.delete(e);else for(let e of a)r.add(e);n(r)},C=e=>{let r=new Set(t);r.has(e)?r.delete(e):r.add(e),n(r)},w=()=>n(new Set),T=t.size;return r(`div`,{className:`relative`,children:[r(`button`,{type:`button`,onClick:()=>u(e=>!e),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${T>0?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[l(ye,{className:`h-3.5 w-3.5`}),T>0?`Kinds (${String(T)})`:`Kinds`,l(_,{className:`h-3 w-3`})]}),s&&r(`div`,{className:`absolute z-20 mt-1 max-h-80 w-64 overflow-auto rounded-md border border-border bg-surface p-2 shadow-lg`,children:[r(`div`,{className:`mb-2 flex items-center gap-1 rounded border border-border px-1.5`,children:[l(k,{className:`h-3.5 w-3.5 text-foreground-subtle`}),l(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),placeholder:`Search kinds…`,className:`w-full bg-transparent py-1 text-xs outline-none`}),T>0&&l(`button`,{type:`button`,onClick:w,className:`text-[10px] text-foreground-subtle hover:text-foreground`,children:`Clear`})]}),y.length===0&&l(`div`,{className:`px-1 py-2 text-[11px] text-foreground-subtle`,children:a?`Loading kinds…`:h.length>0?`No kind matches that search.`:`These cameras advertise no event kinds.`}),y.map(e=>{let n=B(e.macro.iconId),i=p.has(e.macro.kind)||h.length>0,a=t.has(e.macro.kind);return r(`div`,{className:`mb-0.5`,children:[r(`div`,{className:`flex items-center gap-1`,children:[e.subs.length>0?l(`button`,{type:`button`,onClick:()=>b(e.macro.kind),className:`text-foreground-subtle hover:text-foreground`,"aria-label":`Expand`,children:l(i?_:v,{className:`h-3 w-3`})}):l(`span`,{className:`w-3`}),r(`label`,{className:`flex flex-1 cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:a,onChange:()=>S(e),className:`accent-primary`}),l(n,{className:`h-3.5 w-3.5`,style:{color:e.macro.color}}),l(`span`,{className:`font-medium`,children:x(e.macro,o)})]})]}),i&&e.subs.map(e=>{let n=B(e.iconId);return r(`label`,{className:`ml-5 flex cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:t.has(e.kind),onChange:()=>C(e.kind),className:`accent-primary`}),l(n,{className:`h-3.5 w-3.5`,style:{color:e.color}}),l(`span`,{children:x(e,o)})]},e.kind)})]},e.macro.kind)})]})]})}function _r(e,t){let n=new Map;for(let r of e)if(!(t.size>0&&!t.has(r.deviceId)))for(let e of r.kinds)n.has(e.kind)||n.set(e.kind,e);return n}function vr(e,t){return{...t,kind:e,labelKey:`eventKind.${e}`,label:e.charAt(0).toUpperCase()+e.slice(1),iconId:e,parentKind:null,level:`macro`}}var yr=new Set([`detection`,`package`]);function br(e,t){return[..._r(e,t).values()].filter(e=>e.parentKind===null&&yr.has(e.category)).sort((e,t)=>e.label.localeCompare(t.label))}function xr(e,t){let n=_r(e,t),r=new Map,i=new Map;for(let e of n.values()){if(e.parentKind===null){i.set(e.kind,e);continue}let t=r.get(e.parentKind);t===void 0?r.set(e.parentKind,[e]):t.push(e)}for(let[e,t]of r){if(i.has(e))continue;let n=t[0];n!==void 0&&i.set(e,vr(e,n))}return[...i.values()].map(e=>({macro:e,subs:[...r.get(e.kind)??[]].sort((e,t)=>e.label.localeCompare(t.label))})).sort((e,t)=>e.macro.label.localeCompare(t.macro.label))}n();function Sr(){let[n,r]=c(!1),i=t(null),[a,o]=c(0),s=e(e=>{i.current!==e&&(i.current=e,o(e=>e+1))},[]);return u(()=>{let e=i.current;if(!e||typeof IntersectionObserver>`u`){r(!1);return}let t=new IntersectionObserver(e=>{let t=e[e.length-1];t&&r(!t.isIntersecting)},{rootMargin:`64px 0px 0px 0px`,threshold:0});return t.observe(e),()=>t.disconnect()},[a]),{ref:s,scrolledPast:n}}n();var Cr=[`events-feed`],wr=60,Tr=[{value:`importance`,label:`Importance`,icon:qe},{value:`time`,label:`Recent`,icon:N}];function Er(){let e=s(),t=ee(),n=he(),[a,d]=c(Me),[f,p]=c(new Set),[m,h]=c(new Set),[g,_]=c(0),[v,b]=c(`time`),[x,S]=c(new Set),[C,w]=c(null),[T,E]=c(()=>Date.now());u(()=>{let e=setInterval(()=>E(Date.now()),6e4);return()=>clearInterval(e)},[]);let{since:D,until:O}=i(()=>nt({fromMs:a.fromMs,toMs:a.toMs},T),[a.fromMs,a.toMs,T]),k=Sr(),{pending:A,refreshNow:M}=hr({paused:C!==null||x.size>0||k.scrolledPast}),{data:N=[]}=ue({isCamera:!0,projection:`slim`}),P=i(()=>N.map(e=>e.id),[N]),{data:F,isLoading:I}=pe({deviceIds:P},{enabled:P.length>0,staleTime:5*6e4}),L=i(()=>xr(F??[],f),[F,f]),te=It(),ne=te.isPending,{rows:R,isLoading:re}=fr({deviceIds:P,since:D,until:O,minImportance:g>0?g:void 0,classFilter:m.size===1?[...m][0]:void 0}),ie=i(()=>{let e=new Map;for(let t of N??[])e.set(t.id,t.name);return e},[N]),ae=e=>ie.get(e)??`Camera #${String(e)}`,oe=i(()=>Ce(R).map(e=>({id:e,name:ae(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[R,ie]),z=i(()=>Qe($e(R,{cameras:f,classes:m,minImportance:g}),v),[R,f,m,g,v]),B=ke(z,wr,i(()=>JSON.stringify([[...f].sort((e,t)=>e-t),[...m].sort(),g,v,D,O]),[f,m,g,v,D,O])),V=()=>{e.invalidateQueries({queryKey:Cr})},se=()=>S(new Set);function le(e){S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function de(){if(x.size===0||!Nt)return;let e=tt(R,x),t=[...e.values()].reduce((e,t)=>e+t.length,0);t!==0&&(async()=>{await n({title:`Delete ${String(t)} track${t===1?``:`s`}`,message:`Delete ${String(t)} track${t===1?``:`s`} and every image and clip captured for ${t===1?`it`:`them`}? This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&fe(e)})()}function fe(e){let n=[...e];Promise.allSettled(n.map(([e,t])=>te.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{V();let r=[],i=new Set;e.forEach((e,t)=>{let a=n[t];if(!a)return;let[o,s]=a;if(e.status===`fulfilled`)for(let e of s)i.add(et(o,e));else r.push(o)}),S(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t}),r.length>0&&t({title:`Some tracks were not deleted`,message:`Failed to delete tracks on: ${r.map(e=>ae(e)).join(`, `)}. They remain selected — retry, or check the server logs.`,variant:`danger`})})}let me=z.length!==R.length;return r(`div`,{className:`relative space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[l(je,{onChange:d}),l(Ee,{cameras:oe,selected:f,onChange:p}),l(gr,{groups:L,selected:m,onChange:h,loading:I}),r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(`span`,{children:`Min score`}),l(`input`,{type:`range`,min:0,max:1,step:.05,value:g,onChange:e=>_(Number(e.target.value)),className:`h-1 w-24 cursor-pointer accent-primary`,"aria-label":`Minimum importance`}),l(`span`,{className:`w-6 tabular-nums text-foreground`,children:Math.round(g*100)})]}),l(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:Tr.map(e=>{let t=e.icon;return r(`button`,{type:`button`,onClick:()=>b(e.value),className:`flex items-center gap-1 rounded px-2 py-1 text-[11px] transition-colors ${v===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[l(t,{className:`h-3.5 w-3.5`}),` `,e.label]},e.value)})}),!re&&l(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:me?`${String(z.length)} of ${String(R.length)} events`:`${String(z.length)} event${z.length===1?``:`s`}`})]}),x.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[x.size,` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[l(`span`,{title:Nt?void 0:`Track deletion arrives with the next server update`,children:r(j,{variant:`secondary`,onClick:de,disabled:!Nt||ne,children:[ne?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(y,{className:`h-3.5 w-3.5`}),` `,`Delete`]})}),l(j,{variant:`ghost`,onClick:se,disabled:ne,children:l(ce,{className:`h-3.5 w-3.5`})})]})]}),re&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[l(H,{className:`h-4 w-4 animate-spin`}),` Loading events…`]}),!re&&z.length===0&&l(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:`No key events in this window.`}),A&&l(`div`,{className:`sticky top-2 z-20 flex justify-center`,children:l(`button`,{type:`button`,onClick:M,className:`rounded-full border border-primary/40 bg-surface px-3 py-1 text-[11px] font-medium text-primary shadow-sm hover:bg-primary/10`,children:`New events — refresh`})}),!re&&z.length>0&&r(o,{children:[l(`div`,{ref:k.ref,"aria-hidden":!0,className:`h-0`}),l(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:B.pageItems.map(e=>l(ut,{row:e,cameraName:ae(e.deviceId),nowMs:T,selected:x.has(et(e.deviceId,e.trackId)),onToggleSelect:le,onOpenDetail:w},et(e.deviceId,e.trackId)))}),l(Se,{currentPage:B.page,totalItems:B.totalItems,pageSize:B.pageSize,onPageChange:B.setPage,itemNoun:`events`})]}),C&&l(Wt,{row:C,cameraName:ae(C.deviceId),deleteAvailable:Nt,onClose:()=>w(null),onDeleted:()=>{V(),w(null)},onFlagsChanged:e=>{w(t=>t&&t.trackId===e.trackId?{...t,markForTrain:e.markForTrain,debug:e.debug,favourited:e.favourited}:t)}})]})}var Dr=`/addon/training`;function Or(){let e=ze();return r(S,{className:`flex flex-col gap-3 border-border bg-surface p-3 sm:flex-row sm:items-center sm:gap-4`,"data-testid":`events-feed-retrain-cta`,children:[r(`div`,{className:`flex min-w-0 flex-1 items-start gap-2.5`,children:[l(I,{className:`mt-0.5 h-4 w-4 shrink-0 text-primary`,"aria-hidden":!0}),r(`div`,{className:`min-w-0 space-y-0.5`,children:[l(`p`,{className:`text-xs font-medium text-foreground`,children:`Training from this feed`}),l(`p`,{className:`${d} leading-relaxed`,children:`Mark a track with the graduation-cap control on its card. On Training you correct frames, build collections, and start cloud fine-tunes.`})]})]}),l(j,{variant:`outline`,size:`sm`,className:`shrink-0 self-start sm:self-center`,onClick:()=>e(Dr),children:`Open Training`})]})}n();var kr=50,Ar=350,jr=[{value:`loose`,label:`Loose`,title:`The search model's own floor`},{value:`balanced`,label:`Balanced`,title:`1.25× the search model's floor`},{value:`strict`,label:`Strict`,title:`1.5× the search model's floor`}];function Mr(e){let t=String(e.id);return{id:t,trackId:e.trackId??t,deviceId:e.deviceId,timestamp:e.timestamp,className:e.className,label:e.label,subLabel:e.subLabel,importance:e.importance??0,bestEventId:t,mediaId:e.keyFrameMediaId??e.mediaId,windowMs:void 0}}function Nr({onActiveChange:e}){let[t,n]=c(``),[a,o]=c(`loose`),[s,d]=c(null),[f,p]=c(null),[m,h]=c(null),g=me(t,Ar).trim(),_=g.length>0;u(()=>{e(_)},[_,e]);let[v,y]=c(()=>Date.now());u(()=>{let e=setInterval(()=>y(Date.now()),6e4);return()=>clearInterval(e)},[]);let{data:b=[]}=ue({isCamera:!0,projection:`slim`}),S=i(()=>{let e=new Map;for(let t of b)e.set(t.id,t.name);return e},[b]),C=e=>S.get(e)??`Camera #${String(e)}`,w=i(()=>b.map(e=>e.id),[b]),{data:T}=pe({deviceIds:w},{enabled:w.length>0,staleTime:5*6e4}),E=i(()=>br(T??[],new Set(f===null?[]:[f])),[T,f]);u(()=>{s!==null&&(E.some(e=>e.kind===s)||d(null))},[E,s]);let{data:D,isFetching:O,isError:A,error:j}=z({text:g,strictness:a,limit:kr,classFilter:s??void 0,deviceId:f??void 0},{enabled:_}),M=i(()=>[...D??[]].sort((e,t)=>t.score-e.score).map(e=>({...Mr(e),score:e.score})),[D]);function N(e){d(t=>t===e?null:e)}return r(`div`,{className:`space-y-3`,children:[r(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(`div`,{className:`relative min-w-[16rem] flex-1`,children:[l(k,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle`}),l(`input`,{type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:`Semantic search — describe what you're looking for…`,className:`h-9 w-full rounded-md border border-border bg-background pl-8 pr-8 text-sm text-foreground placeholder:text-foreground-subtle focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary`,"aria-label":`Semantic event search`}),t&&l(`button`,{type:`button`,onClick:()=>n(``),className:`absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Clear search`,children:l(ce,{className:`h-3.5 w-3.5`})})]}),O&&_&&l(H,{className:`h-4 w-4 shrink-0 animate-spin text-foreground-subtle`})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[l(`div`,{className:`flex items-center gap-1`,children:E.map(e=>l(`button`,{type:`button`,onClick:()=>N(e.kind),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${s===e.kind?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:x(e)},e.kind))}),r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(`span`,{children:`Camera`}),r(`select`,{value:f===null?``:String(f),onChange:e=>p(e.target.value===``?null:Number(e.target.value)),className:`h-7 rounded-md border border-border bg-background px-1.5 text-xs text-foreground focus:border-primary focus:outline-none`,"aria-label":`Filter by camera`,children:[l(`option`,{value:``,children:`All`}),b.map(e=>l(`option`,{value:String(e.id),children:e.name},e.id))]})]}),r(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(`span`,{children:`Match`}),l(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:jr.map(e=>l(`button`,{type:`button`,onClick:()=>o(e.value),className:`rounded px-2 py-1 text-[11px] transition-colors ${a===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,title:e.title,children:e.label},e.value))})]}),_&&!O&&!A&&r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[M.length,` match`,M.length===1?``:`es`]})]})]}),_&&r(`div`,{className:`space-y-3`,children:[A&&r(`p`,{className:`py-4 text-xs text-danger`,children:[`Search failed: `,j instanceof Error?j.message:`unknown error`,`. Check that the CLIP embedding step is enabled.`]}),!A&&O&&M.length===0&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[l(H,{className:`h-4 w-4 animate-spin`}),` Searching…`]}),!A&&!O&&M.length===0&&r(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:[`No semantic matches for “`,g,`”. Try a looser match threshold or a different phrasing.`]}),!A&&M.length>0&&l(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:M.map(e=>l(ut,{row:e,cameraName:C(e.deviceId),nowMs:v,score:e.score,onOpenDetail:h},e.id))})]}),m&&l(Wt,{row:m,cameraName:C(m.deviceId),deleteAvailable:Nt,onClose:()=>h(null),onDeleted:()=>h(null)})]})}n();function Pr(e,t){let n=Math.max(0,Math.round((e-t)/6e4));if(n<1)return`just now`;if(n<60)return`${String(n)}m`;let r=Math.floor(n/60);return`${String(r)}h ${String(n%60)}m`}function Fr({row:e,cameraName:t,nowMs:n}){let i=Ve(e.keyFrameMediaId===void 0?void 0:Ue(e.keyFrameMediaId));return r(`div`,{className:`flex flex-col overflow-hidden rounded-md border border-border bg-surface`,children:[r(`div`,{className:`relative aspect-video overflow-hidden bg-surface-hover`,children:[i.src?l(`img`,{src:i.src,alt:`Parked ${e.className} on ${t}`,className:`h-full w-full object-cover`}):l(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:l(Je,{className:`h-6 w-6`})}),l(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium capitalize text-white`,children:e.label??e.className})]}),r(`div`,{className:`flex flex-col gap-0.5 p-1.5`,children:[l(`span`,{className:`truncate text-[11px] text-foreground`,children:t}),r(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`parked `,Pr(n,e.becameStationaryAt)]})]})]})}function Ir(){let[e,t]=c(!1),n=Date.now(),{data:a=[]}=ue({isCamera:!0,projection:`slim`}),o=i(()=>a.map(e=>e.id),[a]),s=i(()=>{let e=new Map;for(let t of a)e.set(t.id,t.name);return e},[a]),{rows:u,unreadableCount:d}=Ge(o);return u.length===0&&d===0?null:r(`div`,{className:`rounded-md border border-border bg-surface/40`,children:[r(`button`,{type:`button`,onClick:()=>t(e=>!e),className:`flex w-full items-center gap-2 px-3 py-2 text-left`,children:[l(e?_:v,{className:`h-4 w-4 text-foreground-subtle`}),l(Je,{className:`h-4 w-4 text-foreground-subtle`}),l(`span`,{className:`text-sm font-semibold text-foreground`,children:`Stationary`}),l(`span`,{className:`rounded-full bg-surface-hover px-2 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:u.length}),l(`span`,{className:`ml-2 text-[11px] text-foreground-subtle`,children:`Parked objects — kept out of the event feed`}),d>0?r(`span`,{className:`ml-2 text-[11px] text-warning`,children:[d,` camera`,d===1?``:`s`,` could not be read`]}):null]}),e&&l(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] gap-2 p-3 pt-0`,children:u.map(e=>l(Fr,{row:e,cameraName:s.get(e.deviceId)??`Camera #${String(e.deviceId)}`,nowMs:n},e.id))})]})}n();function Lr(){let[e,t]=c(!1);return l(Be,{children:r(`section`,{className:`space-y-3`,children:[l(Or,{}),l(Nr,{onActiveChange:t}),!e&&l(Ir,{}),!e&&l(Er,{})]})})}function Rr(){let[e]=Le();return e.get(`tab`)===`retrain`?l(Re,{to:`/addon/training`,replace:!0}):l(`div`,{className:`flex flex-col p-4`,children:l(Ke,{tabs:[{id:`feed`,label:`Feed`,icon:L,content:l(Lr,{})},{id:`debug`,label:`Debug`,icon:ie,content:l(cr,{})}]})})}export{Rr as EventsPage};
|
|
1
|
+
import{I as e,K as t,Q as n,S as r,W as i,a,b as o,o as s,q as c,x as l,z as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{R as d,X as f,Z as p,at as m,ct as h,ft as g,gt as _,ht as v,st as y,vt as b}from"./player-overlays-B7T46vDu.js";import{$n as x,An as S,Cn as C,Cr as w,Du as T,Fl as E,Fn as D,Hl as O,Hu as k,Il as A,In as j,Jn as M,Kd as N,Kn as ee,Md as P,Nn as F,Od as I,Tf as L,Ud as te,Vo as ne,Yu as R,_u as re,af as ie,as as ae,cn as oe,ds as z,er as B,fs as V,gd as H,hd as se,iu as ce,kt as le,la as ue,ls as de,nf as fe,os as pe,ot as me,qn as he,rs as ge,ss as _e,tr as U,tu as ve,wu as ye,xn as be,zd as xe}from"./src-BTX2jfA7.js";import{a as Se,c as Ce,d as we,f as Te,i as Ee,m as De,n as Oe,o as ke,p as Ae,r as je,s as Me,t as Ne}from"./debounced-invalidate-BOR3Wuyx.js";import{Un as Pe,vi as Fe}from"./client-BBcQuaON.js";import{t as Ie}from"./useTranslation-Bc5yH9V9.js";import"./mount-D8gNhpYS.js";import{$ as Le,X as Re,Z as ze}from"./index-BWu66tVw.js";import{t as Be}from"./AdminPage-BSFohA3i.js";import{a as Ve,i as He,r as Ue,t as We}from"./authed-media-BaRjbtMq.js";import{t as Ge}from"./use-stationary-objects-BPLoE6ig.js";import{t as Ke}from"./AdminTabs-BcE-Q0tO.js";var qe=b(`arrow-down-wide-narrow`,[[`path`,{d:`m3 16 4 4 4-4`,key:`1co6wj`}],[`path`,{d:`M7 20V4`,key:`1yoxec`}],[`path`,{d:`M11 4h10`,key:`1w87gc`}],[`path`,{d:`M11 8h7`,key:`djye34`}],[`path`,{d:`M11 12h4`,key:`q8tih4`}]]),Je=b(`square-parking`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 17V7h4a3 3 0 0 1 0 6H9`,key:`1dfk2c`}]]);n();function Ye(e){let t=e.subLabel??e.label;if(t!==void 0)return t;let n=e.audioLabels?.[0]?.label;return n!==void 0&&n.length>0?n:void 0}var Xe=720*60*60*1e3;function Ze(e){let t=[];for(let n of e)t.push(...n);return t}function Qe(e,t){let n=[...e];return n.sort((e,n)=>t===`importance`?n.importance-e.importance:n.timestamp-e.timestamp),n}function $e(e,t){return e.filter(e=>!(e.importance<t.minImportance||t.cameras.size>0&&!t.cameras.has(e.deviceId)||t.classes.size>0&&!t.classes.has(e.className)))}function et(e,t){return`${String(e)}:${t}`}function tt(e,t){let n=new Map,r=new Set;for(let i of e){let e=et(i.deviceId,i.trackId);if(!t.has(e)||r.has(e))continue;r.add(e);let a=n.get(i.deviceId);a?a.push(i.trackId):n.set(i.deviceId,[i.trackId])}return n}function nt(e,t){return{since:e.fromMs??t-Xe,until:e.toMs??t}}var rt=[`native`,`raster`,`standin`];function it(e){return rt.some(t=>t===e)}var at={standin:{label:`stand-in`,title:`Stand-in: this tile is a face or plate detail crop copied in because no frame of the subject was captured. It is not a best shot.`,tone:`warning`},raster:{label:`low-res`,title:`Raster crop: a sub-native cut of the subject, not a native capture. Honest, but lower resolution than a best shot.`,tone:`info`}};function ot(e){return e===`standin`?at.standin:e===`raster`?at.raster:null}var st={"no-key-frame":`No key frame existed at close, so no native tile could be cut.`,"no-best-seen-bbox":`No subject box was ever recorded, so there was nothing to cut around.`,"derive-returned-null":`The close-time crop was attempted and produced nothing.`,"derive-threw":`The close-time crop failed with an error.`,"derive-not-wired":`No close-time crop was wired on this node.`,"no-media-store":`The node was shutting down mid-close.`,"no-thumbnail":`The track closed with no tile of any kind.`,"standin-tile":`The track closed with a detail crop standing in for the subject.`,"raster-tile":`The track closed with a sub-native raster crop of the subject.`,"native-tile":`The track closed with a native tile.`};function ct(e){if(e===void 0)return null;let t=e.trim();if(t.length===0)return null;let n=t.split(/\s+/),r=n[0]??t,i=[];for(let e of n.slice(1)){let t=e.indexOf(`=`);t===-1?i.push({key:e,value:null}):i.push({key:e.slice(0,t),value:e.slice(t+1)})}return{sentence:st[r]??r,detail:i,raw:t}}function lt(e){if(e===void 0||!Number.isFinite(e)||e<=0)return``;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${String(n)}m ${String(r).padStart(2,`0`)}s`}function ut({row:e,cameraName:t,nowMs:n,onOpenDetail:i,selected:a=!1,onToggleSelect:o,score:s,provenance:c,footer:u}){let d=Ve(e.mediaId===void 0?He(`track`,e.trackId):Ue(e.mediaId)),f=Math.round(e.importance*100),p=s===void 0?void 0:Math.round(s*100),m=lt(e.windowMs),_=()=>i(e),v=ot(c);return r(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${a?`border-primary ring-1 ring-primary`:`border-border`}`,children:[r(`div`,{className:`aspect-video relative overflow-hidden bg-surface-hover`,children:[d.src?l(`img`,{src:d.src,alt:`Event from ${t}`,onClick:_,className:`h-full w-full cursor-zoom-in object-cover`}):l(`button`,{type:`button`,onClick:_,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-surface-hover text-foreground-subtle`,title:d.failed?`Key-event media unavailable`:`No key-event media`,children:l(g,{className:`h-6 w-6 opacity-60`})}),o&&l(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),o(et(e.deviceId,e.trackId))},className:`absolute left-0 top-0 z-10 rounded-br-md bg-black/50 p-1.5 text-white hover:bg-black/70`,"aria-label":a?`Deselect`:`Select`,children:a?l(De,{className:`h-4 w-4 text-primary`}):l(h,{className:`h-4 w-4`})}),p!==void 0&&r(`span`,{className:`absolute left-1 top-1 z-10 rounded bg-primary/85 px-1.5 py-0.5 text-[10px] font-semibold text-white tabular-nums`,title:`CLIP semantic-match score`,children:[String(p),`%`]}),f>0&&l(`span`,{className:`absolute right-1 top-1 z-10 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-semibold text-white`,children:String(f)}),v!==null&&l(`span`,{className:`absolute bottom-1 right-1 z-10 rounded px-1.5 py-0.5 text-[10px] font-semibold text-white ${v.tone===`warning`?`bg-warning/90`:`bg-black/70`}`,title:v.title,children:v.label}),(e.markForTrain===!0||e.retrainStatus===`trained`||e.debug===!0||e.favourited===!0)&&r(`span`,{className:`absolute bottom-1 left-1 z-10 flex gap-1`,children:[e.markForTrain===!0&&l(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:`Marked for training`,"aria-label":`Marked for training`,children:l(I,{className:`h-3 w-3`})}),e.retrainStatus===`trained`&&e.markForTrain!==!0&&l(`span`,{className:`rounded bg-success/85 p-0.5 text-white`,title:`Training complete`,"aria-label":`Training complete`,"data-testid":`retrain-status-trained`,children:l(fe,{className:`h-3 w-3`})}),e.debug===!0&&l(`span`,{className:`rounded bg-black/70 p-0.5 text-white`,title:`Flagged for debug`,"aria-label":`Flagged for debug`,children:l(ie,{className:`h-3 w-3`})}),e.favourited===!0&&l(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:`Favourited`,"aria-label":`Favourited`,children:l(T,{className:`h-3 w-3`})})]})]}),r(`button`,{type:`button`,onClick:_,className:`min-w-0 px-2 py-1.5 text-left space-y-0.5`,children:[r(`p`,{className:`text-[11px] font-medium text-foreground truncate`,title:e.className,children:[e.className,Ye(e)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,Ye(e)]}):null]}),l(`p`,{className:`text-[10px] text-foreground-subtle truncate`,title:t,children:t}),r(`div`,{className:`flex items-center justify-between gap-2`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle truncate`,children:Te(e.timestamp,n)}),m&&l(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:m})]})]}),u!==void 0&&l(`div`,{className:`px-2 pb-1.5`,children:u})]})}var dt=1400,ft=`Admin-gated URL — opens only inside an authenticated session`;function pt({label:t,value:n,title:i}){let[a,o]=c(!1),s=M();return u(()=>{if(!a)return;let e=setTimeout(()=>o(!1),dt);return()=>clearTimeout(e)},[a]),r(`button`,{type:`button`,onClick:e(()=>{(async()=>{try{await navigator.clipboard.writeText(n),o(!0)}catch{await s({title:`Copy the media URL`,message:`Clipboard access was refused. Select the URL below and copy it manually.`,label:`${t} URL`,defaultValue:n,readOnly:!0,cancelLabel:`Close`})}})()},[n,t,s]),title:i,"aria-label":`Copy ${t} URL`,className:`flex min-w-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${a?`border-success/40 bg-success/10 text-success`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[l(a?fe:te,{className:`h-2.5 w-2.5 shrink-0`}),l(`span`,{className:`truncate`,children:a?`Copied`:t})]})}function mt({localUrl:e,publicUrl:t}){return r(`div`,{className:`flex flex-wrap gap-1`,children:[l(pt,{label:`Local`,value:e,title:`Copy LAN URL — ${ft}`}),t&&l(pt,{label:`Public`,value:t,title:`Copy public URL — ${ft}`})]})}var ht={firstFrame:`First frame (track start)`,lastFrame:`Last frame (track end)`,thumbnail:`Best detection`,thumbnailSmall:`Best detection (480)`,snapshot:`Snapshot`,keyFrame:`Key frame (native-res)`,keyFrameSmall:`Key frame (960)`,crop:`Object crop`,fullFrame:`Full frame`,fullFrameBoxed:`Full frame (boxed)`,faceCrop:`Face crop`,plateCrop:`Plate crop`,confirmationCrop:`Confirmation crop (what the gate saw)`,debugCrop:`Debug crop (why this decision)`,sceneFrame:`Scene frame (clean)`,lastSceneFrame:`Last frame (clean)`};function gt(e){return e in ht}function _t(e){return gt(e)?ht[e]:e}function vt(e,t){return`${e}${t}`}n();var yt=3e4;function bt(t){let[n,r]=c(null),i=e(e=>{r(t=>t??e)},[]);return u(()=>{t||r(null)},[t]),{publicOrigin:n,probes:t?l(xt,{onOrigin:i}):null}}function xt({onOrigin:e}){let{data:t}=w({capName:`network-access`});return l(o,{children:(t??[]).map(t=>l(St,{addonId:t.addonId,onOrigin:e},t.addonId))})}function St({addonId:e,onOrigin:t}){let{data:n}=ne({addonId:e},{refetchInterval:yt,retry:!1});return u(()=>{let e=n?Pe.safeParse(n):null,r=e?.success?e.data.endpoint?.url:void 0;if(r)try{t(new URL(r).origin)}catch{}},[n,t]),null}var W=typeof V==`function`,Ct=`Track flags arrive with the next server update`;function wt(){return{mutateAsync:async()=>{throw Error(`setTrackFlags unavailable`)},isPending:!1}}var Tt=W?V:wt;function Et(e){if(typeof e!=`object`||!e||!(`trackId`in e)||!(`markForTrain`in e)||!(`debug`in e)||!(`favourited`in e))return null;let{trackId:t,markForTrain:n,debug:r,favourited:i}=e;return typeof t!=`string`||typeof n!=`boolean`||typeof r!=`boolean`||typeof i!=`boolean`?null:{trackId:t,markForTrain:n,debug:r,favourited:i}}n();function Dt({label:e,hint:t,checked:n,disabled:i,title:a,icon:o,onToggle:s}){return r(`button`,{type:`button`,role:`switch`,"aria-checked":n,"aria-label":e,disabled:i,title:a,onClick:s,className:`flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left transition-colors disabled:opacity-50 ${n?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[l(`span`,{className:n?`text-primary`:`text-foreground-subtle`,children:o}),r(`span`,{className:`min-w-0 flex-1`,children:[l(`span`,{className:`block text-[11px] font-medium text-foreground`,children:e}),l(`span`,{className:`block text-[10px] text-foreground-subtle`,children:t})]}),l(`span`,{"aria-hidden":`true`,className:`h-4 w-7 shrink-0 rounded-full p-0.5 transition-colors ${n?`bg-primary`:`bg-border`}`,children:l(`span`,{className:`block h-3 w-3 rounded-full bg-white transition-transform ${n?`translate-x-3`:``}`})})]})}function Ot({deviceId:e,trackId:t,markForTrain:n,debug:i,favourited:a,onChange:o}){let s=Tt(),u=ee(),[d,f]=c(null),p=d?.markForTrain??n===!0,m=d?.debug??i===!0,h=d?.favourited??a===!0,g=!W||s.isPending,_=W?void 0:Ct,v=n=>{g||(async()=>{try{let r=Et(await s.mutateAsync({deviceId:e,trackId:t,flags:n}));if(!r)return;f(r),o?.(r)}catch(e){let t=e instanceof Error?e.message:``;await u({title:`Could not update this track`,message:t===``?`Could not update this track. Check the server logs.`:t,variant:`danger`})}})()};return r(`div`,{className:`grid gap-1.5 sm:grid-cols-2`,children:[l(Dt,{label:`Mark for training`,hint:`Keeps this track and its media past retention`,checked:p,disabled:g,..._===void 0?{}:{title:_},icon:l(I,{className:`h-4 w-4`}),onToggle:()=>v({markForTrain:!p})}),l(Dt,{label:`Debug`,hint:`Flag this track for diagnostic attention`,checked:m,disabled:g,..._===void 0?{}:{title:_},icon:l(ie,{className:`h-4 w-4`}),onToggle:()=>v({debug:!m})}),l(Dt,{label:`Favourited`,hint:`Keeps this track and its media past retention`,checked:h,disabled:g,..._===void 0?{}:{title:_},icon:l(T,{className:`h-4 w-4`}),onToggle:()=>v({favourited:!h})})]})}var G=100,kt=120,At={polyline:``,points:[],snapshots:[],start:null,end:null,peakBox:null},K=e=>e<0?0:e>1?1:e,q=e=>Math.round(e*100)/100;function jt(e,t){if(e.length<=t)return[...e];let n=(e.length-1)/(t-1),r=[];for(let i=0;i<t;i++)r.push(e[Math.round(i*n)]);return r[r.length-1]=e[e.length-1],r}function Mt(e,t,n){if(e.length===0||t===null)return At;let{width:r,height:i}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)return At;let a=jt(e,n?.maxPoints??kt).map(e=>({x:q(K(e.x/r)*G),y:q(K(e.y/i)*G)})),o=a[0]??null,s=a[a.length-1]??null,c=a.length>=2?a.map(e=>`${e.x},${e.y}`).join(` `):``,l=(n?.snapshots??[]).map(e=>({x:q(K(e.x/r)*G),y:q(K(e.y/i)*G),mediaId:e.mediaId})),u=null,d=-1;for(let t of e){let e=K(t.bbox.w/r)*K(t.bbox.h/i);e>d&&(d=e,u=t)}return{polyline:c,points:a,snapshots:l,start:o,end:s,peakBox:u?{x:q(K(u.bbox.x/r)*G),y:q(K(u.bbox.y/i)*G),w:q(K(u.bbox.w/r)*G),h:q(K(u.bbox.h/i)*G)}:null}}var Nt=typeof ge==`function`,Pt=`Track deletion arrives with the next server update`;function Ft(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var It=Nt?ge:Ft;n();var Lt=15e3,Rt=f();function zt({url:e,label:t}){let{src:n,failed:r}=Ve(e);return n===null?l(`div`,{className:`flex h-full w-full items-center justify-center bg-surface-hover`,children:r?l(g,{className:`h-4 w-4 text-foreground-subtle opacity-60`}):l(H,{className:`h-4 w-4 animate-spin text-foreground-subtle opacity-70`})}):l(`img`,{src:n,alt:t,className:`h-full w-full object-cover`})}var Bt=new Set([`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]),Vt=new Set([`keyFrame`,`fullFrame`,`fullFrameBoxed`,`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`,`sceneFrame`,`lastSceneFrame`]);function Ht(e){let[t,n]=c(null);return u(()=>{if(n(null),!e)return;let t=!1,r=new Image;return r.onload=()=>{t||n({width:r.naturalWidth,height:r.naturalHeight})},r.src=e,()=>{t=!0,r.onload=null}},[e]),t}function Ut({overlay:e,onPickSnapshot:t}){return!e.polyline&&!e.peakBox&&e.snapshots.length===0?null:r(`svg`,{viewBox:`0 0 100 100`,preserveAspectRatio:`none`,className:`pointer-events-none absolute inset-0 h-full w-full`,children:[e.peakBox&&l(`rect`,{x:e.peakBox.x,y:e.peakBox.y,width:e.peakBox.w,height:e.peakBox.h,fill:`none`,stroke:`var(--color-warning)`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),e.polyline&&l(`polyline`,{points:e.polyline,fill:`none`,stroke:`var(--color-info)`,strokeWidth:2,strokeLinejoin:`round`,strokeLinecap:`round`,strokeOpacity:.85,vectorEffect:`non-scaling-stroke`}),e.points.map((e,t)=>l(`circle`,{cx:e.x,cy:e.y,r:1,fill:`var(--color-info)`,fillOpacity:.6,vectorEffect:`non-scaling-stroke`},`${String(e.x)}-${String(e.y)}-${String(t)}`)),e.snapshots.map((e,n)=>l(`circle`,{cx:e.x,cy:e.y,r:1.9,fill:`var(--color-info)`,fillOpacity:.95,stroke:`var(--color-background)`,strokeWidth:.7,vectorEffect:`non-scaling-stroke`,className:t?`pointer-events-auto cursor-pointer`:void 0,onClick:t?n=>{n.stopPropagation(),t(e.mediaId)}:void 0,children:l(`title`,{children:`Snapshot checkpoint — click to view this frame`})},`snap-${String(e.mediaId)}-${String(n)}`)),e.start&&l(`circle`,{cx:e.start.x,cy:e.start.y,r:2.4,fill:`var(--color-success)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),e.end&&l(`circle`,{cx:e.end.x,cy:e.end.y,r:2.4,fill:`var(--color-danger)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function J({label:e,value:t,mono:n}){return r(`div`,{className:`flex items-baseline justify-between gap-3 border-b border-border/60 py-1.5 last:border-0`,children:[l(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:e}),l(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground ${n?`font-mono text-[11px]`:``}`,title:t,children:t})]})}function Wt({row:t,cameraName:n,deleteAvailable:a,onClose:s,onDeleted:d,onFlagsChanged:f}){let p=m(),h=ee(),_=he(),v=It(),b=t!==null,x=t?.deviceId??0,S=t?.trackId??``,w=t?.timestamp??0,T=t?.windowMs??0,{data:D}=ae({deviceId:x,trackId:S},{enabled:b}),{data:O}=de({trackId:S,deviceId:x},{enabled:b}),k=D?.bestEventId===void 0?void 0:Number(D.bestEventId),{data:M}=_e({ownerType:`object`,eventId:k??0,deviceId:x},{enabled:b&&k!==void 0&&Number.isFinite(k)}),{data:N}=A({deviceId:x},{enabled:b}),F=(N??[]).find(e=>e.addonId!==void 0)?.addonId,{data:I}=E({deviceId:x,since:w-Lt,until:w+T+Lt,provider:F??``},{enabled:b&&F!==void 0}),[L,te]=c(null),[ne,R]=c(!1),{publicOrigin:re,probes:ie}=bt(b);u(()=>{te(null)},[x,S]);let oe=i(()=>{let e=O??[],t=M??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[O,M]),z=L??oe,B=Ve(z?z.url:void 0),V=i(()=>{let e=new Set,t=[];for(let n of[...M??[],...O??[]])e.has(n.mediaId)||(e.add(n.mediaId),t.push(n));return t},[M,O]),se=i(()=>V.find(e=>Bt.has(e.kind))??null,[V]),ce=Ht(Ve(se?se.url:void 0).src),le=i(()=>Mt(D?.positions??[],ce,{snapshots:(D?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaId:e.mediaId}))}),[D?.positions,D?.snapshots,ce]),ue=e(e=>{let t=V.find(t=>t.mediaId===e);t&&te(t)},[V]);if(t===null)return null;let fe=B.src,pe=z?.kind,me=pe!==void 0&&Vt.has(pe)&&ce!==null&&(D?.positions.length??0)>=2,ge=I&&I.length>0?I[0]:null,U=()=>{ge&&(R(!0),(async()=>{try{let e=await p.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:ge.id});window.open(e.playbackUrl,`_blank`,`noopener`)}catch{h({title:`Clip unavailable`,message:`Could not resolve clip playback. Check the server logs.`,variant:`warning`})}finally{R(!1)}})())},ve=()=>{!a||v.isPending||(async()=>{if(await _({title:`Delete track`,message:`Delete this track and every image and clip captured for it? This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`}))try{await v.mutateAsync({deviceId:t.deviceId,trackIds:[t.trackId]}),d()}catch{await h({title:`Delete failed`,message:`Failed to delete this track. Check the server logs.`,variant:`danger`})}})()},ye=Math.round(t.importance*100),xe=D?.importanceReason?`${String(ye)}% · ${D.importanceReason}`:`${String(ye)}%`,Se=D?.zonesVisited&&D.zonesVisited.length>0?D.zonesVisited.join(`, `):`—`,Ce=D?.audioLabels&&D.audioLabels.length>0?D.audioLabels:t.audioLabels&&t.audioLabels.length>0?t.audioLabels:void 0,Te=Ce===void 0?`—`:Ce.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `),Ee=D?D.totalDistance.toFixed(2):`—`,De=ct(D?.previewMissReason),ke=Ae(D?D.firstSeen:w),je=D?Ae(D.lastSeen):`—`;return l(be,{open:!0,onOpenChange:e=>!e&&s(),children:r(C,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":`Event detail`,className:`flex h-[92dvh] flex-col gap-0 overflow-hidden p-0 bottom-0 left-0 right-0 top-auto w-full max-w-full translate-x-0 translate-y-0 rounded-b-none md:bottom-auto md:left-1/2 md:right-auto md:top-1/2 md:h-auto md:w-[calc(100vw-2rem)] md:max-w-xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:max-h-[calc(100dvh-2rem)]`,children:[l(`header`,{className:`flex shrink-0 items-start gap-2 border-b border-border py-3 pl-4 pr-10`,children:r(`div`,{className:`min-w-0`,children:[r(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:[t.className,Ye(t)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,Ye(t)]}):null]}),l(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:n})]})}),r(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[fe?l(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:l(Oe,{src:fe,alt:`Key frame from ${n}`,fit:`natural`,className:`w-full`,overlay:me?l(Ut,{overlay:le,onPickSnapshot:ue}):void 0})}):l(`div`,{className:`flex aspect-video w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-surface-hover text-foreground-subtle`,children:B.failed?r(o,{children:[l(g,{className:`h-8 w-8 opacity-60`}),l(`span`,{className:`text-[11px]`,children:`Key-frame media unavailable`})]}):l(H,{className:`h-6 w-6 animate-spin opacity-70`})}),V.length>0&&l(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:V.map(e=>{let t=_t(e.kind),n=vt(Rt,e.url),i=re?vt(re,e.url):null;return r(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[l(`button`,{type:`button`,onClick:()=>te(e),className:`relative h-16 w-full overflow-hidden rounded border border-border hover:border-primary`,title:`${t} · ${Ae(e.timestamp)}`,children:l(zt,{url:e.url,label:t})}),r(`figcaption`,{className:`min-w-0 px-0.5`,children:[l(`div`,{className:`truncate text-[10px] font-medium leading-tight text-foreground`,title:t,children:t}),l(`div`,{className:`text-[10px] leading-tight text-foreground-subtle`,title:Ae(e.timestamp),children:we(e.timestamp)})]}),l(mt,{localUrl:n,publicUrl:i})]},e.mediaId)})}),ie,ge&&r(j,{variant:`secondary`,onClick:U,disabled:ne,children:[ne?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(P,{className:`h-3.5 w-3.5`}),` `,`View clip`]}),l(Ot,{deviceId:t.deviceId,trackId:t.trackId,...(D?.markForTrain??t.markForTrain)===void 0?{}:{markForTrain:D?.markForTrain??t.markForTrain},...(D?.debug??t.debug)===void 0?{}:{debug:D?.debug??t.debug},...(D?.favourited??t.favourited)===void 0?{}:{favourited:D?.favourited??t.favourited},onChange:f}),De!==null&&r(`div`,{className:`rounded-lg border border-warning/40 bg-warning/8 px-3 py-2`,children:[l(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`Best shot`}),l(`p`,{className:`mt-0.5 text-xs text-foreground`,children:De.sentence}),l(`code`,{className:`mt-1 block break-all font-mono text-[10px] text-foreground-subtle`,children:De.raw})]}),r(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[l(J,{label:`Camera`,value:n}),l(J,{label:`Class`,value:t.className}),l(J,{label:`Label`,value:t.label??`—`}),l(J,{label:`Sub-label`,value:t.subLabel??`—`}),l(J,{label:`Importance`,value:xe}),l(J,{label:`Zones visited`,value:Se}),l(J,{label:`Audio heard`,value:Te}),l(J,{label:`Total distance`,value:Ee}),l(J,{label:`First seen`,value:ke}),l(J,{label:`Last seen`,value:je}),l(J,{label:`Track`,value:t.trackId,mono:!0})]})]}),l(`footer`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]`,children:l(`span`,{title:a?void 0:Pt,children:r(j,{variant:`secondary`,onClick:ve,disabled:!a||v.isPending,children:[v.isPending?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(y,{className:`h-3.5 w-3.5`}),` `,`Delete track`]})})})]})})}var Gt={status:`debug.tape.status`,promote:`debug.tape.promote`,list:`debug.tape.list`,tracks:`debug.tape.tracks`,review:`debug.tape.review`,release:`debug.tape.release`,remove:`debug.tape.delete`},Kt={setRelation:`debug.gt.setRelation`,setPurity:`debug.gt.setPurity`,list:`debug.gt.list`},qt=p(`/addon/pipeline-analytics/tape-export`),Jt=10*6e4;function Yt(e){return`${qt}?tapeId=${encodeURIComponent(e)}`}var Xt=`The server answered in a shape this build does not understand.`;function Zt(e){return e instanceof Error?e.message:`The action failed.`}function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Qt(e,t){if(!(t in e))return;let n=e[t];return n===null?null:typeof n==`number`&&Number.isFinite(n)?n:void 0}function Z(e,t){let n=e[t];return typeof n==`string`?n:null}function $t(e,t){let n=e[t];return typeof n==`boolean`?n:null}function en(e,t){if(!Array.isArray(e))return null;let n=[];for(let r of e){let e=t(r);if(e===null)return null;n.push(e)}return n}function tn(e){return e===`off`||e===`recording`||e===`refused`||e===`failing`||e===`unknown`}function nn(e){if(!Y(e))return null;let t=X(e,`deviceId`),n=e.state,r=X(e,`gapsSinceArmed`),i=Qt(e,`segmentsHeld`),a=Qt(e,`bytesLastHour`),o=Qt(e,`bytesHeld`);if(t===null||!tn(n)||r===null||i===void 0||a===void 0||o===void 0)return null;let s=Z(e,`reason`),c=X(e,`segmentOriginMs`),l=X(e,`framesPerMin`),u=X(e,`heldFromMs`),d=X(e,`heldToMs`),f=Z(e,`shelfError`);return{deviceId:t,state:n,gapsSinceArmed:r,segmentsHeld:i,bytesLastHour:a,bytesHeld:o,...s===null?{}:{reason:s},...c===null?{}:{segmentOriginMs:c},...l===null?{}:{framesPerMin:l},...u===null?{}:{heldFromMs:u},...d===null?{}:{heldToMs:d},...f===null?{}:{shelfError:f}}}function rn(e){return Y(e)?en(e.cameras,nn):null}function an(e){if(!Y(e))return null;let t=Z(e,`id`),n=X(e,`deviceId`),r=Z(e,`scenario`),i=e.lighting,a=X(e,`fromMs`),o=X(e,`toMs`),s=e.state,c=X(e,`frames`),l=X(e,`gaps`),u=X(e,`bytes`),d=$t(e,`reviewed`),f=$t(e,`released`),p=en(e.tracks,e=>typeof e==`string`?e:null),m=X(e,`tracksStillStored`);return t===null||n===null||r===null||i!==`day`&&i!==`ir`||a===null||o===null||s!==`complete`&&s!==`incomplete`||c===null||l===null||u===null||d===null||f===null||p===null||m===null?null:{id:t,deviceId:n,scenario:r,note:Z(e,`note`),lighting:i,fromMs:a,toMs:o,state:s,frames:c,gaps:l,bytes:u,reviewed:d,released:f,tracks:p,tracksStillStored:m}}function on(e){return Y(e)?en(e.tapes,an):null}function sn(e){if(!Y(e))return null;let t=Z(e,`trackId`),n=X(e,`firstT`),r=X(e,`lastT`),i=X(e,`boundFrames`),a=Z(e,`cls`),o=$t(e,`stillStored`);return t===null||n===null||r===null||i===null||a===null||o===null?null:{trackId:t,firstT:n,lastT:r,boundFrames:i,cls:a,stillStored:o}}function cn(e){if(!Y(e))return null;let t=Z(e,`tapeId`),n=X(e,`deviceId`),r=X(e,`fromMs`),i=X(e,`toMs`),a=$t(e,`reviewed`),o=en(e.lanes,sn);return t===null||n===null||r===null||i===null||a===null||o===null?null:{tapeId:t,deviceId:n,fromMs:r,toMs:i,reviewed:a,lanes:o}}function ln(e){if(!Y(e))return null;if(e.ok===!1){let t=Z(e,`reason`),n=Z(e,`detail`);return t===null||n===null?null:{ok:!1,reason:t,detail:n}}if(e.ok!==!0)return null;let t=Z(e,`tapeId`),n=e.state,r=X(e,`frames`),i=X(e,`gaps`),a=X(e,`pinnedTracks`),o=X(e,`bytes`);return t===null||n!==`complete`&&n!==`incomplete`||r===null||i===null||a===null||o===null?null:{ok:!0,tapeId:t,state:n,frames:r,gaps:i,pinnedTracks:a,bytes:o}}function un(e){if(!Y(e))return null;let t=e.status;if(t===`released`){let n=X(e,`unpinned`),r=$t(e,`pinsSettled`);return n===null||r===null?null:{status:t,unpinned:n,pinsSettled:r}}if(t===`already-released`||t===`not-found`)return{status:t};if(t===`unavailable`){let n=Z(e,`reason`);return n===null?null:{status:t,reason:n}}return null}function dn(e){if(!Y(e))return null;let t=e.status;if(t===`deleted`||t===`pins-owed`||t===`not-found`)return{status:t};if(t===`unavailable`){let n=Z(e,`reason`);return n===null?null:{status:t,reason:n}}return null}function fn(e){switch(e.status){case`released`:case`deleted`:return null;case`already-released`:return`This tape was already released.`;case`not-found`:return`That tape no longer exists — it may have been released or deleted elsewhere.`;case`pins-owed`:return`Refused: this tape still names pins not yet taken back. Try again shortly — the ledger settles them automatically.`;case`unavailable`:return`Unavailable on this node: ${e.reason}`}}function pn(e){if(!Y(e))return null;let t=Z(e,`leftTrackId`),n=Z(e,`rightTrackId`),r=e.relation,i=e.presence;return t===null||n===null||r!==`same-subject`&&r!==`different-subjects`?null:{leftTrackId:t,rightTrackId:n,relation:r,presence:i===`continuous`?`continuous`:null}}function mn(e){if(!Y(e))return null;let t=Z(e,`sourceTrackId`),n=e.purity;return t===null||n!==`mixed`&&n!==`not-a-subject`?null:{sourceTrackId:t,purity:n,switchAtMs:X(e,`switchAtMs`)}}function hn(e){if(!Y(e))return null;let t=en(e.relations,pn),n=en(e.purities,mn),r=$t(e,`truncated`);return t===null||n===null||r===null?null:{relations:t,purities:n,truncated:r}}function gn(e){if(!e.truncated)return null;let t=e.relations.length+e.purities.length;return`Showing the first ${String(t)} marks — more exist for this window.`}function _n(e){return e.filter(e=>e.segmentsHeld===null||e.segmentsHeld>0).map(e=>({deviceId:e.deviceId,segmentsUnknown:e.segmentsHeld===null}))}function vn(e){return e.slice(1).map((t,n)=>({trackId:e[n]??t,otherTrackId:t}))}function yn(e){return e.flatMap((t,n)=>e.slice(n+1).map(e=>({trackId:t,otherTrackId:e})))}function bn(e,t){let n=[];for(let r of t.relations){let t=r.leftTrackId===e?r.rightTrackId:r.rightTrackId===e?r.leftTrackId:null;if(t===null)continue;let i=r.relation===`same-subject`?`same as`:`different from`;n.push(`${i} ${t}${r.presence===`continuous`?` (continuous)`:``}`)}for(let r of t.purities)r.sourceTrackId===e&&n.push(r.purity===`not-a-subject`?`not a subject`:r.switchAtMs===null?`mixed`:`mixed at switch`);return n}function xn(e){switch(e.state){case`off`:return`Off`;case`recording`:return`Recording`;case`refused`:return`Refused: ${e.reason??`unknown reason`}`;case`failing`:return`Failing: ${e.reason??`unknown reason`}`;case`unknown`:return`Unknown: ${e.reason??`unknown reason`}`}}var Sn={"window-too-long":`A promoted window is at most 30 minutes.`,"window-in-future":`The window ends in the future.`,"window-not-recorded":`No segment covers that window — the camera was not recording then, or it is older than 24 h.`,"invalid-scenario":`The scenario must be a slug: lowercase letters, digits and dashes, 3–64 characters.`,"promotion-budget":`A promotion budget is full (60 tapes, 1 GiB, 3 000 pinned tracks). Release or delete a tape already committed as a case first.`,"empty-window":`No frame was recorded in that window.`,"shelf-unreadable":`The camera's recorded segments could not be listed, so the window cannot be proven whole.`,"not-post-processing-node":`This node does not post-process frames, so it records no tracking tapes.`,"artifacts-elsewhere":`The artifacts storage location is on another node; tapes are recorded only where it lives.`,"tapes-not-started":`The tape recorder has not started on this node (or failed to).`};function Cn(e,t){let n=Sn[e]??`Refused (${e}).`;return t.length>0?`${n} ${t}`:n}function wn(e){if(e.length===0)return null;let t=new Date(e).getTime();return Number.isFinite(t)?t:null}function Tn(e){return e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function En(e){return e===null?`unknown`:Tn(e)}function Dn(e){return e===null?`unknown`:String(e)}function On(e,t){let n=t.trim();return e===404?`This tape no longer exists on this node (unknown tape).`:e===503?n.length>0?n:`Tapes are unavailable on this node.`:e===500?n.length>0?n:`The export could not be read (the tape may have just been released or deleted).`:`Download failed (${String(e)}).`}n();function kn({cameras:e,call:t,onPromoted:n}){let[i,a]=c(``),[o,s]=c(``),[u,d]=c(``),[f,p]=c(``),[m,h]=c(``),[g,_]=c(`auto`),[v,y]=c(!1),[b,x]=c(null),S=async()=>{let r=Number.parseInt(i===``?e[0]?.value??``:i,10),a=wn(o),s=wn(u);if(!Number.isFinite(r)||a===null||s===null){x(`Pick a camera and both ends of the window.`);return}y(!0),x(null);try{let e=ln(await t(Gt.promote,{deviceId:r,fromMs:a,toMs:s,scenario:f,...m.trim().length>0?{note:m.trim()}:{},...g===`day`||g===`ir`?{lighting:g}:{}}));e===null?x(Xt):e.ok?(x(`Promoted ${e.tapeId}: ${String(e.frames)} frames, ${Tn(e.bytes)}, ${String(e.pinnedTracks)} tracks pinned`+(e.state===`incomplete`?` — incomplete (it has gaps) and cannot become a case.`:`.`)),n()):x(Cn(e.reason,e.detail))}catch(e){x(Zt(e))}finally{y(!1)}};return r(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border px-3 py-2`,children:[l(`div`,{className:`w-40`,children:l(D,{value:i,options:[...e],onChange:e=>a(e.target.value),"aria-label":`Camera`})}),l(O,{type:`datetime-local`,"aria-label":`From`,value:o,onChange:e=>s(e.target.value),className:`w-48`}),l(O,{type:`datetime-local`,"aria-label":`To`,value:u,onChange:e=>d(e.target.value),className:`w-48`}),l(O,{"aria-label":`Scenario`,placeholder:`615-door-groups`,value:f,onChange:e=>p(e.target.value),className:`w-44`}),l(O,{"aria-label":`Note`,placeholder:`optional note`,value:m,onChange:e=>h(e.target.value),className:`w-52`}),l(`div`,{className:`w-28`,children:l(D,{value:g,"aria-label":`Lighting`,options:[{value:`auto`,label:`Lighting: auto`},{value:`day`,label:`day`},{value:`ir`,label:`ir`}],onChange:e=>_(e.target.value)})}),r(j,{onClick:()=>void S(),disabled:v||e.length===0,children:[v?l(H,{className:`h-3.5 w-3.5 animate-spin`}):null,` Promote window`]}),l(`p`,{className:`w-full text-xs text-foreground-subtle`,children:`A promoted tape may be shared as a test case — keep the scenario slug and note free of names or other personal data.`}),b!==null&&l(`p`,{className:`w-full text-xs text-foreground`,children:b})]})}var An=`pipeline-analytics`,jn=`debug.listTracks`,Mn=`debug.analyze`,Nn=p(`/addon/pipeline-analytics/debug-export`);function Pn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`string`?n:null}function $(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Fn(e,t){let n=e[t];return typeof n==`boolean`?n:null}function In(e){return e===`error`||e===`warn`||e===`info`}function Ln(e){if(!Pn(e))return null;let t=Q(e,`code`),n=Q(e,`detail`),r=e.severity;return t===null||n===null||!In(r)?null:{code:t,severity:r,detail:n}}function Rn(e){if(!Pn(e))return null;let t=Q(e,`trackId`),n=$(e,`deviceId`),r=Q(e,`className`),i=$(e,`firstSeen`),a=$(e,`lastSeen`),o=$(e,`durationMs`),s=Fn(e,`active`);if(t===null||n===null||r===null||i===null||a===null||o===null||s===null)return null;let c=Q(e,`label`),l=Q(e,`subLabel`),u=Q(e,`previewMissReason`),d=Fn(e,`markForTrain`),f=Fn(e,`favourited`);return{trackId:t,deviceId:n,className:r,...c===null?{}:{label:c},...l===null?{}:{subLabel:l},firstSeen:i,lastSeen:a,durationMs:o,active:s,timestamp:i,windowMs:o,importance:$(e,`importance`)??0,bestEventId:Q(e,`bestEventId`)??``,...d===null?{}:{markForTrain:d},...f===null?{}:{favourited:f},debug:!0,...u===null||u.length===0?{}:{previewMissReason:u}}}function zn(e){let t=Rn(e);if(t===null||!Pn(e))return null;let n=$(e,`mediaCount`),r=$(e,`eventCount`),i=$(e,`positionCount`);if(n===null||r===null||i===null)return null;let a=e.mediaKinds,o=e.findings;if(!Array.isArray(a)||!Array.isArray(o))return null;let s=a.filter(e=>typeof e==`string`),c=[];for(let e of o){let t=Ln(e);t!==null&&c.push(t)}let l=e.thumbnailProvenance;return{...t,mediaCount:n,mediaKinds:s,eventCount:r,positionCount:i,findings:c,...it(l)?{thumbnailProvenance:l}:{}}}function Bn(e){if(!Pn(e))return null;let t=Fn(e,`truncated`),n=e.tracks;if(t===null||!Array.isArray(n))return null;let r=[];for(let e of n){let t=Rn(e);if(t===null)return null;r.push(t)}return{tracks:r,truncated:t}}function Vn(e){if(!Pn(e))return null;let t=e.reports,n=e.vanished;if(!Array.isArray(t)||!Array.isArray(n))return null;let r=[];for(let e of t){let t=zn(e);if(t===null)return null;r.push(t)}return{reports:r,vanished:n.filter(e=>typeof e==`string`)}}var Hn={MEDIA_EVICTED_OR_NEVER:`no media`,MISSING_KEYFRAME:`no keyframe`,MISSING_FIRSTFRAME:`no first frame`,MISSING_LASTFRAME:`no last frame`,MISSING_THUMBNAIL:`no thumbnail`,MISSING_BEST_CROP:`no crop`,SHORT_TRACK:`very short`,ZERO_EVENTS:`no events`,ZERO_POSITIONS:`no trajectory`,NO_PERIODIC_SNAPSHOTS:`no snapshots`,LASTFRAME_STALE:`stale last frame`,MEDIA_STOPPED_EARLY:`media stopped early`,NO_BEST_EVENT:`no best event`,LOW_BEST_SCORE:`low score`,UNSCORED_LABEL:`unscored label`,BEST_SHOT_STANDIN:`stand-in best shot`,BEST_SHOT_RASTER:`low-res best shot`};function Un(e){return Hn[e]??e}var Wn={error:0,warn:1,info:2};function Gn(e){return e.toSorted((e,t)=>Wn[e.severity]-Wn[t.severity]||e.code.localeCompare(t.code))}function Kn(e){return e.length===0?Nn:`${Nn}?deviceIds=${e.join(`,`)}`}function qn(e){if(e<1e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.round(e/1e3);if(t<60)return`${String(t)}s`;let n=Math.floor(t/60);return`${String(n)}m ${String(t%60).padStart(2,`0`)}s`}function Jn(e,t){return`${String(e)}:${t}`}function Yn(e,t){let n=[],r=new Set;for(let i of e){let e=Jn(i.deviceId,i.trackId);!t.has(e)||r.has(e)||(r.add(e),n.push({deviceId:i.deviceId,trackId:i.trackId}))}return n}n();function Xn({tapeId:e,call:t,onClose:n,onChanged:i}){let o=a({queryKey:[`events-debug`,`tapes`,`tracks`,e],queryFn:async()=>cn(await t(Gt.tracks,{tapeId:e}))}),s=o.data??null,u=a({queryKey:[`events-debug`,`tapes`,`marks`,e],enabled:s!==null,queryFn:async()=>s===null?null:hn(await t(Kt.list,{deviceId:s.deviceId,since:s.fromMs-Jt,until:s.toMs+Jt,limit:5e3}))}),[d,f]=c([]),[p,m]=c(``),[h,g]=c(null),_=e=>f(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),v=async e=>{g(null);try{for(let[n,r]of e)await t(n,r);f([]),await u.refetch(),i()}catch(e){g(Zt(e))}};if(s===null)return o.isLoading?l(`p`,{className:`text-xs`,children:`Loading the tape…`}):l(F,{message:Xt});let y=s.deviceId,b=(e,t)=>v(e.map(e=>[Kt.setRelation,{deviceId:y,...e,relation:t}])),x=e=>{let t=Number.parseFloat(p),n=e===`mixed`&&Number.isFinite(t)?s.fromMs+t*1e3:void 0;return v(d.map(t=>[Kt.setPurity,{deviceId:y,trackId:t,purity:e,...n===void 0?{}:{switchAtMs:Math.round(n)}}]))},S=u.data==null?null:gn(u.data);return r(`div`,{className:`space-y-2 rounded-md border border-primary/40 px-3 py-2`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[r(`span`,{className:`text-xs font-medium`,children:[s.tapeId,` — `,String(s.lanes.length),` tracks`]}),l(j,{disabled:d.length<2,onClick:()=>void b(vn(d),`same-subject`),children:`Same subject`}),l(j,{variant:`secondary`,disabled:d.length<2,onClick:()=>void b(yn(d),`different-subjects`),children:`Different subjects`}),l(O,{"aria-label":`Changed at (s from tape start)`,placeholder:`changed at s`,value:p,onChange:e=>m(e.target.value),className:`w-28`}),l(j,{variant:`secondary`,disabled:d.length!==1,onClick:()=>void x(`mixed`),children:`Mixed`}),l(j,{variant:`secondary`,disabled:d.length===0,onClick:()=>void x(`not-a-subject`),children:`Not a subject`}),l(j,{variant:s.reviewed?`secondary`:`primary`,onClick:()=>void v([[Gt.review,{tapeId:s.tapeId,reviewed:!s.reviewed}]]).then(()=>o.refetch()),children:s.reviewed?`Mark not reviewed`:`Mark reviewed`}),l(j,{variant:`ghost`,onClick:n,children:`Close`})]}),h!==null&&l(F,{message:h}),S!==null&&l(F,{variant:`warning`,message:S}),l(`ul`,{className:`space-y-1`,children:s.lanes.toSorted((e,t)=>e.firstT-t.firstT).map(e=>l(Zn,{lane:e,marks:u.data===null||u.data===void 0?[]:bn(e.trackId,u.data),selected:d.includes(e.trackId),onToggle:()=>_(e.trackId)},e.trackId))})]})}function Zn({lane:e,marks:t,selected:n,onToggle:i}){let{src:a}=Ve(e.stillStored?He(`track`,e.trackId):void 0);return r(`li`,{className:`flex items-center gap-2 text-xs`,children:[l(`input`,{type:`checkbox`,"aria-label":`select ${e.trackId}`,checked:n,onChange:i}),a===null?l(`div`,{className:`h-10 w-10 rounded bg-surface-hover`}):l(`img`,{src:a,alt:e.trackId,className:`h-10 w-10 rounded object-cover`}),l(`span`,{className:`font-mono`,children:e.trackId}),l(`span`,{children:e.cls}),r(`span`,{className:`text-foreground-subtle`,children:[qn(e.firstT),` → `,qn(e.lastT),` · `,String(e.boundFrames),` `,`frames`]}),!e.stillStored&&l(`span`,{className:`text-foreground-subtle`,children:`not stored — marked through the tape`}),t.map(e=>l(U,{variant:`info`,children:e},e))]})}n();var Qn=`camstack_admin_token`;function $n(){let e=m();return(t,n)=>e.trpcClient.addons.custom.mutate({addonId:An,action:t,input:n})}async function er(e,t){let n=localStorage.getItem(Qn),r={};n!==null&&(r.Authorization=`Bearer ${n}`);let i=await fetch(Yt(e),{headers:r});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(On(i.status,e))}let a=await i.blob(),o=i.headers.get(`content-disposition`),s=(o===null?null:/filename="?([^";]+)"?/i.exec(o))?.[1]?.trim()??t,c=URL.createObjectURL(a),l=document.createElement(`a`);l.href=c,l.download=s,l.click(),setTimeout(()=>URL.revokeObjectURL(c),6e4)}function tr(){let[e,t]=c(!1);return l(oe,{expanded:e,onExpandedChange:t,header:l(`span`,{className:`text-sm font-medium text-foreground`,children:`Tracking tapes`}),children:l(nr,{})})}function nr(){let e=$n(),t=ue({isCamera:!0,projection:`slim`}),n=i(()=>{let e=new Map;for(let n of t.data??[])e.set(n.id,n.name);return t=>e.get(t)??`Camera ${String(t)}`},[t.data]),o=a({queryKey:[`events-debug`,`tapes`,`status`],queryFn:async()=>rn(await e(Gt.status,{}))}),s=a({queryKey:[`events-debug`,`tapes`,`list`],queryFn:async()=>on(await e(Gt.list,{}))}),[u,d]=c(null),[f,p]=c(null),m=async e=>{p(null);try{await er(e.id,`${e.scenario}.tape-bundle.json.gz`)}catch(e){p(Zt(e))}},h=async t=>{let n=un(await e(Gt.release,{tapeId:t.id}));if(n===null)throw Error(Xt);let r=fn(n);if(r!==null)throw Error(r);await s.refetch()},g=async t=>{let n=dn(await e(Gt.remove,{tapeId:t.id}));if(n===null)throw Error(Xt);let r=fn(n);if(r!==null)throw Error(r);await s.refetch()};return r(`div`,{className:`space-y-3`,children:[r(`p`,{className:`text-xs text-foreground-subtle`,children:[`A camera records while its `,l(`strong`,{children:`Record the track history`}),` switch (camera settings → Tracking) is on; segments are kept 24 h. Promote a window worth keeping, label it in the review, mark it reviewed, download it and turn it into a test case with`,` `,l(`code`,{children:`npm run tracking-bench -- case`}),`.`]}),f!==null&&l(F,{message:f}),o.isLoading&&l(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading camera status…`}),o.data===null&&l(F,{message:`The server answered in a shape this build does not understand.`}),r(`table`,{className:`w-full text-xs`,children:[l(`thead`,{children:r(`tr`,{className:`text-left text-foreground-subtle`,children:[l(`th`,{children:`Camera`}),l(`th`,{children:`State`}),l(`th`,{children:`Frames/min`}),l(`th`,{children:`Last hour`}),l(`th`,{children:`Held`}),l(`th`,{children:`Gaps`})]})}),l(`tbody`,{children:(o.data??[]).map(e=>r(`tr`,{children:[l(`td`,{children:n(e.deviceId)}),l(`td`,{children:l(U,{variant:e.state===`recording`?`success`:e.state===`off`?`default`:e.state===`unknown`?`warning`:`danger`,children:xn(e)})}),l(`td`,{children:e.framesPerMin===void 0?`—`:String(Math.round(e.framesPerMin))}),l(`td`,{title:e.shelfError,children:En(e.bytesLastHour)}),r(`td`,{title:e.shelfError,children:[Dn(e.segmentsHeld),` seg · `,En(e.bytesHeld)]}),l(`td`,{children:String(e.gapsSinceArmed)})]},e.deviceId))})]}),l(kn,{cameras:_n(o.data??[]).map(e=>({value:String(e.deviceId),label:e.segmentsUnknown?`${n(e.deviceId)} (segments unknown)`:n(e.deviceId)})),call:e,onPromoted:()=>void s.refetch()}),s.isLoading&&l(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading promoted tapes…`}),s.data===null&&l(F,{message:`The server answered in a shape this build does not understand.`}),r(`table`,{className:`w-full text-xs`,children:[l(`thead`,{children:r(`tr`,{className:`text-left text-foreground-subtle`,children:[l(`th`,{children:`Scenario`}),l(`th`,{children:`Camera`}),l(`th`,{children:`Window`}),l(`th`,{children:`State`}),l(`th`,{children:`Tracks`}),l(`th`,{})]})}),l(`tbody`,{children:(s.data??[]).map(e=>r(`tr`,{children:[l(`td`,{children:e.scenario}),l(`td`,{children:n(e.deviceId)}),r(`td`,{children:[new Date(e.fromMs).toLocaleString(),` · `,qn(e.toMs-e.fromMs),` `,`· `,e.lighting]}),r(`td`,{children:[l(U,{variant:e.state===`complete`?`success`:`warning`,children:e.state}),` `,e.reviewed&&l(U,{variant:`info`,children:`reviewed`}),` `,e.released&&l(U,{children:`released`})]}),r(`td`,{children:[String(e.tracksStillStored),`/`,String(e.tracks.length),` stored`]}),r(`td`,{className:`space-x-1 text-right`,children:[l(j,{variant:`secondary`,"aria-label":`Review ${e.scenario}`,onClick:()=>d(e.id),children:`Review`}),l(j,{variant:`ghost`,"aria-label":`Download ${e.scenario}`,onClick:()=>void m(e),children:l(xe,{className:`h-3.5 w-3.5`})}),l(le,{label:`Release`,icon:se,title:`Release ${e.scenario}?`,description:`Releasing returns this tape's pinned tracks to ordinary retention — they can be pruned from then on. The promoted bundle itself is kept until deleted.`,confirmLabel:`Release`,triggerVariant:`ghost`,confirmVariant:`danger`,disabled:e.released,action:()=>h(e)}),l(le,{label:`Delete`,icon:y,title:`Delete ${e.scenario}?`,description:`Deleting removes the promoted bundle and its index row for good. Its tracks' pins are released first — this cannot be undone.`,confirmLabel:`Delete`,triggerVariant:`ghost`,confirmVariant:`danger`,action:()=>g(e)})]})]},e.id))})]}),u!==null&&l(Xn,{tapeId:u,call:e,onClose:()=>d(null),onChanged:()=>void s.refetch()})]})}n();var rr=`all`,ir=`The server answered in a shape this build does not understand.`,ar={error:`danger`,warn:`warning`,info:`info`};function or({findings:e}){return e.length===0?l(U,{variant:`success`,children:`no anomaly found`}):l(`div`,{className:`flex flex-wrap gap-1`,children:Gn(e).map(e=>l(U,{variant:ar[e.severity],title:e.detail,children:Un(e.code)},e.code))})}function sr({track:e,report:t,analyzing:n}){let i=ct(t?.previewMissReason??e.previewMissReason);return r(`div`,{className:`space-y-1 border-t border-border pt-1.5`,children:[t===void 0?l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n?`analysing…`:`not analysed`}):r(o,{children:[l(or,{findings:t.findings}),r(`p`,{className:`text-[10px] text-foreground-subtle`,title:t.mediaKinds.length>0?t.mediaKinds.join(`, `):`no media of any kind`,children:[String(t.mediaCount),` media · `,String(t.eventCount),` events ·`,` `,String(t.positionCount),` positions`]})]}),i!==null&&l(`p`,{className:`text-[10px] text-foreground-subtle`,title:i.raw,children:i.sentence})]})}function cr(){let e=m(),[t,n]=c(rr),[o,s]=c(!1),[u,d]=c(null),[f,p]=c(new Set),[h,g]=c(null),[_,v]=c(null),[y,b]=c(null),[x,C]=c([]),w=Tt(),E=ue({isCamera:!0,projection:`slim`}),O=i(()=>[{value:rr,label:`All cameras`},...(E.data??[]).map(e=>({value:String(e.id),label:e.name}))],[E.data]),k=i(()=>{let e=new Map;for(let t of E.data??[])e.set(t.id,t.name);return e},[E.data]),A=e=>k.get(e)??`Camera ${String(e)}`,M=i(()=>t===rr?[]:[Number.parseInt(t,10)],[t]),N=a({queryKey:[`events-debug`,`list`,M],queryFn:async()=>Bn(await e.trpcClient.addons.custom.mutate({addonId:An,action:jn,input:M.length===0?{}:{deviceIds:M}}))}),ee=i(()=>(N.data?.tracks??[]).map(e=>e.trackId),[N.data]),P=a({queryKey:[`events-debug`,`analyze`,ee],enabled:ee.length>0,queryFn:async()=>Vn(await e.trpcClient.addons.custom.mutate({addonId:An,action:Mn,input:{trackIds:ee}}))}),I=i(()=>{let e=new Map;for(let t of P.data?.reports??[])e.set(t.trackId,t);return e},[P.data]),L=N.data?.tracks??[],te=N.data===null||P.data===null,ne=()=>{N.refetch(),P.refetch()},ae=e=>{p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},oe=()=>{p(new Set(L.map(e=>Jn(e.deviceId,e.trackId))))},z=()=>p(new Set),B=async(e,t)=>{let n=e===`analyzed`?{debug:!1}:{favourited:!0},r=0,i=[];for(let e of t)try{await w.mutateAsync({deviceId:e.deviceId,trackId:e.trackId,flags:n}),r+=1}catch{i.push(e.trackId)}return{applied:r,refused:i}},V=e=>{if(!W||_!==null)return;let t=Yn(L,f);t.length!==0&&(v(e),b(null),(async()=>{let n=await B(e,t);v(null);let r=new Set(n.refused);p(new Set(t.filter(e=>r.has(e.trackId)).map(e=>Jn(e.deviceId,e.trackId)))),e===`analyzed`&&C(t.filter(e=>!r.has(e.trackId))),n.refused.length>0&&b(`${String(n.refused.length)} of ${String(t.length)} were refused by the server and are still selected. Check the hub log.`),N.refetch()})())},se=()=>{let e=x;e.length===0||_!==null||(v(`analyzed`),b(null),(async()=>{for(let t of e)try{await w.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,flags:{debug:!0}})}catch{b(`Some tracks could not be re-marked. Refresh and try again.`)}v(null),C([]),N.refetch()})())},le=async()=>{s(!0),d(null);try{await We(Kn(M),`camstack-debug.zip`)}catch(e){d(e instanceof Error?e.message:`Export failed.`)}finally{s(!1)}},de=_!==null;return l(Be,{children:r(`section`,{className:`space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[l(`div`,{className:`w-44`,children:l(D,{value:t,options:O,onChange:e=>n(e.target.value)})}),r(j,{variant:`secondary`,onClick:ne,disabled:N.isFetching,children:[N.isFetching?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(R,{className:`h-3.5 w-3.5`}),`Refresh`]}),r(j,{onClick:()=>void le(),disabled:o||L.length===0,children:[o?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(xe,{className:`h-3.5 w-3.5`}),`Export all (`,String(L.length),`)`]}),L.length>0&&f.size<L.length&&l(j,{variant:`ghost`,onClick:oe,children:`Select all`})]}),r(`p`,{className:`text-xs text-foreground-subtle`,children:[`A `,l(`code`,{children:`debug`}),` mark does not pin retention — this lists the marked tracks that still exist. A track whose media was evicted shows as missing media. Use `,l(`strong`,{children:`Keep`}),` `,`to hold a selection against pruning while you investigate, and `,l(`strong`,{children:`Analyzed`}),` `,`to un-mark the ones you are finished with.`]}),l(tr,{}),N.isError&&l(F,{message:`Could not load the marked tracks.`}),te&&!N.isError&&l(F,{message:ir}),u!==null&&l(F,{message:u}),y!==null&&l(F,{message:y}),N.data?.truncated===!0&&l(F,{message:`A camera filled the per-camera cap — some marked tracks are not listed. Un-mark a few, or filter to one camera.`}),(P.data?.vanished.length??0)>0&&r(`p`,{className:`text-xs text-foreground-subtle`,children:[String(P.data?.vanished.length),` marked track(s) were evicted between the list and the analysis.`]}),f.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[String(f.size),` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[l(`span`,{title:W?void 0:`Track flags arrive with the next server update`,children:r(j,{variant:`secondary`,onClick:()=>V(`keep`),disabled:!W||de,children:[_===`keep`?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(T,{className:`h-3.5 w-3.5`}),` `,`Keep`]})}),l(`span`,{title:W?void 0:`Track flags arrive with the next server update`,children:r(j,{onClick:()=>V(`analyzed`),disabled:!W||de,children:[_===`analyzed`?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(fe,{className:`h-3.5 w-3.5`}),` `,`Analyzed`]})}),l(j,{variant:`ghost`,onClick:z,disabled:de,children:l(ce,{className:`h-3.5 w-3.5`})})]})]}),x.length>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-border bg-surface px-3 py-2`,children:[r(`span`,{className:`text-xs text-foreground`,children:[String(x.length),` track(s) marked analyzed and removed from this list.`]}),r(j,{variant:`ghost`,onClick:se,disabled:de,children:[l(re,{className:`h-3.5 w-3.5`}),` Undo`]}),l(j,{variant:`ghost`,onClick:()=>C([]),disabled:de,children:l(ce,{className:`h-3.5 w-3.5`})})]}),N.isLoading?l(S,{children:l(`div`,{className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:`Loading…`})}):L.length===0?l(S,{children:r(`div`,{className:`flex flex-col items-center gap-2 px-3 py-8 text-center`,children:[l(ie,{className:`h-5 w-5 text-foreground-subtle`}),l(`p`,{className:`text-xs text-foreground-subtle`,children:`No track is marked for debug. Mark one from a track's actions to see it here.`})]})}):l(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:L.map(e=>{let t=I.get(e.trackId);return l(ut,{row:e,cameraName:A(e.deviceId),nowMs:e.lastSeen,selected:f.has(Jn(e.deviceId,e.trackId)),onToggleSelect:ae,onOpenDetail:g,...t?.thumbnailProvenance===void 0?{}:{provenance:t.thumbnailProvenance},footer:l(sr,{track:e,report:t,analyzing:P.isFetching})},Jn(e.deviceId,e.trackId))})}),h&&l(Wt,{row:h,cameraName:A(h.deviceId),deleteAvailable:Nt,onClose:()=>g(null),onDeleted:()=>{g(null),N.refetch()},onFlagsChanged:e=>{e.debug||(g(null),N.refetch())}})]})})}var lr=200,ur=3e4,dr=[];function fr(e){let t=m(),n=e.deviceIds.length>0,r=[...e.deviceIds].sort((e,t)=>e-t),{data:i,isLoading:o}=a({queryKey:[`events-feed`,r,e.since,e.until,e.minImportance??null,e.classFilter??null],enabled:n,staleTime:ur,refetchInterval:ur,queryFn:async()=>(await t.trpcClient.pipelineAnalytics.getKeyEventsBatch.query({deviceIds:r,since:e.since,until:e.until,limit:lr,...e.minImportance===void 0?{}:{minImportance:e.minImportance},...e.classFilter===void 0?{}:{classFilter:e.classFilter}})).map(e=>e.events.map(t=>({...t,deviceId:e.deviceId})))});return{rows:Qe(Ze(i??dr),`importance`),isLoading:n&&o}}n();var pr=[`events-feed`],mr=2e3;function hr(n){let r=s(),i=n?.paused===!0,a=t(r);a.current=r;let o=t(i);o.current=i;let[l,d]=c(!1),f=e(()=>{a.current.invalidateQueries({queryKey:pr})},[]),p=t(void 0);p.current||=Ne({delayMs:mr,invalidate:()=>{o.current?d(!0):f()}}),u(()=>()=>p.current?.cancel(),[]),u(()=>{i||!l||(d(!1),f())},[i,l,f]);let m=e(()=>{d(!1),f()},[f]);return ve(Fe.PipelineAnalyticsDetectionEvent,()=>{p.current?.trigger()}),ve(Fe.PipelineAnalyticsTrackEnded,()=>{p.current?.trigger()}),{pending:l,refreshNow:m}}n();function gr({groups:e,selected:t,onChange:n,loading:a=!1}){let{t:o}=Ie(),[s,u]=c(!1),[d,f]=c(``),[p,m]=c(new Set),h=d.trim().toLowerCase(),g=e=>h.length===0||x(e,o).toLowerCase().includes(h),y=i(()=>e.map(e=>({macro:e.macro,subs:e.subs.filter(t=>g(t)||g(e.macro))})).filter(e=>g(e.macro)||e.subs.length>0),[e,h]),b=e=>m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),S=e=>{let r=new Set(t),i=t.has(e.macro.kind)&&e.subs.every(e=>t.has(e.kind)),a=[e.macro.kind,...e.subs.map(e=>e.kind)];if(i)for(let e of a)r.delete(e);else for(let e of a)r.add(e);n(r)},C=e=>{let r=new Set(t);r.has(e)?r.delete(e):r.add(e),n(r)},w=()=>n(new Set),T=t.size;return r(`div`,{className:`relative`,children:[r(`button`,{type:`button`,onClick:()=>u(e=>!e),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${T>0?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[l(ye,{className:`h-3.5 w-3.5`}),T>0?`Kinds (${String(T)})`:`Kinds`,l(_,{className:`h-3 w-3`})]}),s&&r(`div`,{className:`absolute z-20 mt-1 max-h-80 w-64 overflow-auto rounded-md border border-border bg-surface p-2 shadow-lg`,children:[r(`div`,{className:`mb-2 flex items-center gap-1 rounded border border-border px-1.5`,children:[l(k,{className:`h-3.5 w-3.5 text-foreground-subtle`}),l(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),placeholder:`Search kinds…`,className:`w-full bg-transparent py-1 text-xs outline-none`}),T>0&&l(`button`,{type:`button`,onClick:w,className:`text-[10px] text-foreground-subtle hover:text-foreground`,children:`Clear`})]}),y.length===0&&l(`div`,{className:`px-1 py-2 text-[11px] text-foreground-subtle`,children:a?`Loading kinds…`:h.length>0?`No kind matches that search.`:`These cameras advertise no event kinds.`}),y.map(e=>{let n=B(e.macro.iconId),i=p.has(e.macro.kind)||h.length>0,a=t.has(e.macro.kind);return r(`div`,{className:`mb-0.5`,children:[r(`div`,{className:`flex items-center gap-1`,children:[e.subs.length>0?l(`button`,{type:`button`,onClick:()=>b(e.macro.kind),className:`text-foreground-subtle hover:text-foreground`,"aria-label":`Expand`,children:l(i?_:v,{className:`h-3 w-3`})}):l(`span`,{className:`w-3`}),r(`label`,{className:`flex flex-1 cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:a,onChange:()=>S(e),className:`accent-primary`}),l(n,{className:`h-3.5 w-3.5`,style:{color:e.macro.color}}),l(`span`,{className:`font-medium`,children:x(e.macro,o)})]})]}),i&&e.subs.map(e=>{let n=B(e.iconId);return r(`label`,{className:`ml-5 flex cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[l(`input`,{type:`checkbox`,checked:t.has(e.kind),onChange:()=>C(e.kind),className:`accent-primary`}),l(n,{className:`h-3.5 w-3.5`,style:{color:e.color}}),l(`span`,{children:x(e,o)})]},e.kind)})]},e.macro.kind)})]})]})}function _r(e,t){let n=new Map;for(let r of e)if(!(t.size>0&&!t.has(r.deviceId)))for(let e of r.kinds)n.has(e.kind)||n.set(e.kind,e);return n}function vr(e,t){return{...t,kind:e,labelKey:`eventKind.${e}`,label:e.charAt(0).toUpperCase()+e.slice(1),iconId:e,parentKind:null,level:`macro`}}var yr=new Set([`detection`,`package`]);function br(e,t){return[..._r(e,t).values()].filter(e=>e.parentKind===null&&yr.has(e.category)).sort((e,t)=>e.label.localeCompare(t.label))}function xr(e,t){let n=_r(e,t),r=new Map,i=new Map;for(let e of n.values()){if(e.parentKind===null){i.set(e.kind,e);continue}let t=r.get(e.parentKind);t===void 0?r.set(e.parentKind,[e]):t.push(e)}for(let[e,t]of r){if(i.has(e))continue;let n=t[0];n!==void 0&&i.set(e,vr(e,n))}return[...i.values()].map(e=>({macro:e,subs:[...r.get(e.kind)??[]].sort((e,t)=>e.label.localeCompare(t.label))})).sort((e,t)=>e.macro.label.localeCompare(t.macro.label))}n();function Sr(){let[n,r]=c(!1),i=t(null),[a,o]=c(0),s=e(e=>{i.current!==e&&(i.current=e,o(e=>e+1))},[]);return u(()=>{let e=i.current;if(!e||typeof IntersectionObserver>`u`){r(!1);return}let t=new IntersectionObserver(e=>{let t=e[e.length-1];t&&r(!t.isIntersecting)},{rootMargin:`64px 0px 0px 0px`,threshold:0});return t.observe(e),()=>t.disconnect()},[a]),{ref:s,scrolledPast:n}}n();var Cr=[`events-feed`],wr=60,Tr=[{value:`importance`,label:`Importance`,icon:qe},{value:`time`,label:`Recent`,icon:N}];function Er(){let e=s(),t=ee(),n=he(),[a,d]=c(Me),[f,p]=c(new Set),[m,h]=c(new Set),[g,_]=c(0),[v,b]=c(`time`),[x,S]=c(new Set),[C,w]=c(null),[T,E]=c(()=>Date.now());u(()=>{let e=setInterval(()=>E(Date.now()),6e4);return()=>clearInterval(e)},[]);let{since:D,until:O}=i(()=>nt({fromMs:a.fromMs,toMs:a.toMs},T),[a.fromMs,a.toMs,T]),k=Sr(),{pending:A,refreshNow:M}=hr({paused:C!==null||x.size>0||k.scrolledPast}),{data:N=[]}=ue({isCamera:!0,projection:`slim`}),P=i(()=>N.map(e=>e.id),[N]),{data:F,isLoading:I}=pe({deviceIds:P},{enabled:P.length>0,staleTime:5*6e4}),L=i(()=>xr(F??[],f),[F,f]),te=It(),ne=te.isPending,{rows:R,isLoading:re}=fr({deviceIds:P,since:D,until:O,minImportance:g>0?g:void 0,classFilter:m.size===1?[...m][0]:void 0}),ie=i(()=>{let e=new Map;for(let t of N??[])e.set(t.id,t.name);return e},[N]),ae=e=>ie.get(e)??`Camera #${String(e)}`,oe=i(()=>Ce(R).map(e=>({id:e,name:ae(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[R,ie]),z=i(()=>Qe($e(R,{cameras:f,classes:m,minImportance:g}),v),[R,f,m,g,v]),B=ke(z,wr,i(()=>JSON.stringify([[...f].sort((e,t)=>e-t),[...m].sort(),g,v,D,O]),[f,m,g,v,D,O])),V=()=>{e.invalidateQueries({queryKey:Cr})},se=()=>S(new Set);function le(e){S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function de(){if(x.size===0||!Nt)return;let e=tt(R,x),t=[...e.values()].reduce((e,t)=>e+t.length,0);t!==0&&(async()=>{await n({title:`Delete ${String(t)} track${t===1?``:`s`}`,message:`Delete ${String(t)} track${t===1?``:`s`} and every image and clip captured for ${t===1?`it`:`them`}? This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&fe(e)})()}function fe(e){let n=[...e];Promise.allSettled(n.map(([e,t])=>te.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{V();let r=[],i=new Set;e.forEach((e,t)=>{let a=n[t];if(!a)return;let[o,s]=a;if(e.status===`fulfilled`)for(let e of s)i.add(et(o,e));else r.push(o)}),S(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t}),r.length>0&&t({title:`Some tracks were not deleted`,message:`Failed to delete tracks on: ${r.map(e=>ae(e)).join(`, `)}. They remain selected — retry, or check the server logs.`,variant:`danger`})})}let me=z.length!==R.length;return r(`div`,{className:`relative space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[l(je,{onChange:d}),l(Ee,{cameras:oe,selected:f,onChange:p}),l(gr,{groups:L,selected:m,onChange:h,loading:I}),r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(`span`,{children:`Min score`}),l(`input`,{type:`range`,min:0,max:1,step:.05,value:g,onChange:e=>_(Number(e.target.value)),className:`h-1 w-24 cursor-pointer accent-primary`,"aria-label":`Minimum importance`}),l(`span`,{className:`w-6 tabular-nums text-foreground`,children:Math.round(g*100)})]}),l(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:Tr.map(e=>{let t=e.icon;return r(`button`,{type:`button`,onClick:()=>b(e.value),className:`flex items-center gap-1 rounded px-2 py-1 text-[11px] transition-colors ${v===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[l(t,{className:`h-3.5 w-3.5`}),` `,e.label]},e.value)})}),!re&&l(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:me?`${String(z.length)} of ${String(R.length)} events`:`${String(z.length)} event${z.length===1?``:`s`}`})]}),x.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[x.size,` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[l(`span`,{title:Nt?void 0:`Track deletion arrives with the next server update`,children:r(j,{variant:`secondary`,onClick:de,disabled:!Nt||ne,children:[ne?l(H,{className:`h-3.5 w-3.5 animate-spin`}):l(y,{className:`h-3.5 w-3.5`}),` `,`Delete`]})}),l(j,{variant:`ghost`,onClick:se,disabled:ne,children:l(ce,{className:`h-3.5 w-3.5`})})]})]}),re&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[l(H,{className:`h-4 w-4 animate-spin`}),` Loading events…`]}),!re&&z.length===0&&l(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:`No key events in this window.`}),A&&l(`div`,{className:`sticky top-2 z-20 flex justify-center`,children:l(`button`,{type:`button`,onClick:M,className:`rounded-full border border-primary/40 bg-surface px-3 py-1 text-[11px] font-medium text-primary shadow-sm hover:bg-primary/10`,children:`New events — refresh`})}),!re&&z.length>0&&r(o,{children:[l(`div`,{ref:k.ref,"aria-hidden":!0,className:`h-0`}),l(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:B.pageItems.map(e=>l(ut,{row:e,cameraName:ae(e.deviceId),nowMs:T,selected:x.has(et(e.deviceId,e.trackId)),onToggleSelect:le,onOpenDetail:w},et(e.deviceId,e.trackId)))}),l(Se,{currentPage:B.page,totalItems:B.totalItems,pageSize:B.pageSize,onPageChange:B.setPage,itemNoun:`events`})]}),C&&l(Wt,{row:C,cameraName:ae(C.deviceId),deleteAvailable:Nt,onClose:()=>w(null),onDeleted:()=>{V(),w(null)},onFlagsChanged:e=>{w(t=>t&&t.trackId===e.trackId?{...t,markForTrain:e.markForTrain,debug:e.debug,favourited:e.favourited}:t)}})]})}var Dr=`/addon/training`;function Or(){let e=ze();return r(S,{className:`flex flex-col gap-3 border-border bg-surface p-3 sm:flex-row sm:items-center sm:gap-4`,"data-testid":`events-feed-retrain-cta`,children:[r(`div`,{className:`flex min-w-0 flex-1 items-start gap-2.5`,children:[l(I,{className:`mt-0.5 h-4 w-4 shrink-0 text-primary`,"aria-hidden":!0}),r(`div`,{className:`min-w-0 space-y-0.5`,children:[l(`p`,{className:`text-xs font-medium text-foreground`,children:`Training from this feed`}),l(`p`,{className:`${d} leading-relaxed`,children:`Mark a track with the graduation-cap control on its card. On Training you correct frames, build collections, and start cloud fine-tunes.`})]})]}),l(j,{variant:`outline`,size:`sm`,className:`shrink-0 self-start sm:self-center`,onClick:()=>e(Dr),children:`Open Training`})]})}n();var kr=50,Ar=350,jr=[{value:`loose`,label:`Loose`,title:`The search model's own floor`},{value:`balanced`,label:`Balanced`,title:`1.25× the search model's floor`},{value:`strict`,label:`Strict`,title:`1.5× the search model's floor`}];function Mr(e){let t=String(e.id);return{id:t,trackId:e.trackId??t,deviceId:e.deviceId,timestamp:e.timestamp,className:e.className,label:e.label,subLabel:e.subLabel,importance:e.importance??0,bestEventId:t,mediaId:e.keyFrameMediaId??e.mediaId,windowMs:void 0}}function Nr({onActiveChange:e}){let[t,n]=c(``),[a,o]=c(`loose`),[s,d]=c(null),[f,p]=c(null),[m,h]=c(null),g=me(t,Ar).trim(),_=g.length>0;u(()=>{e(_)},[_,e]);let[v,y]=c(()=>Date.now());u(()=>{let e=setInterval(()=>y(Date.now()),6e4);return()=>clearInterval(e)},[]);let{data:b=[]}=ue({isCamera:!0,projection:`slim`}),S=i(()=>{let e=new Map;for(let t of b)e.set(t.id,t.name);return e},[b]),C=e=>S.get(e)??`Camera #${String(e)}`,w=i(()=>b.map(e=>e.id),[b]),{data:T}=pe({deviceIds:w},{enabled:w.length>0,staleTime:5*6e4}),E=i(()=>br(T??[],new Set(f===null?[]:[f])),[T,f]);u(()=>{s!==null&&(E.some(e=>e.kind===s)||d(null))},[E,s]);let{data:D,isFetching:O,isError:A,error:j}=z({text:g,strictness:a,limit:kr,classFilter:s??void 0,deviceId:f??void 0},{enabled:_}),M=i(()=>[...D??[]].sort((e,t)=>t.score-e.score).map(e=>({...Mr(e),score:e.score})),[D]);function N(e){d(t=>t===e?null:e)}return r(`div`,{className:`space-y-3`,children:[r(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(`div`,{className:`relative min-w-[16rem] flex-1`,children:[l(k,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle`}),l(`input`,{type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:`Semantic search — describe what you're looking for…`,className:`h-9 w-full rounded-md border border-border bg-background pl-8 pr-8 text-sm text-foreground placeholder:text-foreground-subtle focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary`,"aria-label":`Semantic event search`}),t&&l(`button`,{type:`button`,onClick:()=>n(``),className:`absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Clear search`,children:l(ce,{className:`h-3.5 w-3.5`})})]}),O&&_&&l(H,{className:`h-4 w-4 shrink-0 animate-spin text-foreground-subtle`})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[l(`div`,{className:`flex items-center gap-1`,children:E.map(e=>l(`button`,{type:`button`,onClick:()=>N(e.kind),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${s===e.kind?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:x(e)},e.kind))}),r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(`span`,{children:`Camera`}),r(`select`,{value:f===null?``:String(f),onChange:e=>p(e.target.value===``?null:Number(e.target.value)),className:`h-7 rounded-md border border-border bg-background px-1.5 text-xs text-foreground focus:border-primary focus:outline-none`,"aria-label":`Filter by camera`,children:[l(`option`,{value:``,children:`All`}),b.map(e=>l(`option`,{value:String(e.id),children:e.name},e.id))]})]}),r(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(`span`,{children:`Match`}),l(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:jr.map(e=>l(`button`,{type:`button`,onClick:()=>o(e.value),className:`rounded px-2 py-1 text-[11px] transition-colors ${a===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,title:e.title,children:e.label},e.value))})]}),_&&!O&&!A&&r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[M.length,` match`,M.length===1?``:`es`]})]})]}),_&&r(`div`,{className:`space-y-3`,children:[A&&r(`p`,{className:`py-4 text-xs text-danger`,children:[`Search failed: `,j instanceof Error?j.message:`unknown error`,`. Check that the CLIP embedding step is enabled.`]}),!A&&O&&M.length===0&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[l(H,{className:`h-4 w-4 animate-spin`}),` Searching…`]}),!A&&!O&&M.length===0&&r(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:[`No semantic matches for “`,g,`”. Try a looser match threshold or a different phrasing.`]}),!A&&M.length>0&&l(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:M.map(e=>l(ut,{row:e,cameraName:C(e.deviceId),nowMs:v,score:e.score,onOpenDetail:h},e.id))})]}),m&&l(Wt,{row:m,cameraName:C(m.deviceId),deleteAvailable:Nt,onClose:()=>h(null),onDeleted:()=>h(null)})]})}n();function Pr(e,t){let n=Math.max(0,Math.round((e-t)/6e4));if(n<1)return`just now`;if(n<60)return`${String(n)}m`;let r=Math.floor(n/60);return`${String(r)}h ${String(n%60)}m`}function Fr({row:e,cameraName:t,nowMs:n}){let i=Ve(e.keyFrameMediaId===void 0?void 0:Ue(e.keyFrameMediaId));return r(`div`,{className:`flex flex-col overflow-hidden rounded-md border border-border bg-surface`,children:[r(`div`,{className:`relative aspect-video overflow-hidden bg-surface-hover`,children:[i.src?l(`img`,{src:i.src,alt:`Parked ${e.className} on ${t}`,className:`h-full w-full object-cover`}):l(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:l(Je,{className:`h-6 w-6`})}),l(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium capitalize text-white`,children:e.label??e.className})]}),r(`div`,{className:`flex flex-col gap-0.5 p-1.5`,children:[l(`span`,{className:`truncate text-[11px] text-foreground`,children:t}),r(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`parked `,Pr(n,e.becameStationaryAt)]})]})]})}function Ir(){let[e,t]=c(!1),n=Date.now(),{data:a=[]}=ue({isCamera:!0,projection:`slim`}),o=i(()=>a.map(e=>e.id),[a]),s=i(()=>{let e=new Map;for(let t of a)e.set(t.id,t.name);return e},[a]),{rows:u,unreadableCount:d}=Ge(o);return u.length===0&&d===0?null:r(`div`,{className:`rounded-md border border-border bg-surface/40`,children:[r(`button`,{type:`button`,onClick:()=>t(e=>!e),className:`flex w-full items-center gap-2 px-3 py-2 text-left`,children:[l(e?_:v,{className:`h-4 w-4 text-foreground-subtle`}),l(Je,{className:`h-4 w-4 text-foreground-subtle`}),l(`span`,{className:`text-sm font-semibold text-foreground`,children:`Stationary`}),l(`span`,{className:`rounded-full bg-surface-hover px-2 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:u.length}),l(`span`,{className:`ml-2 text-[11px] text-foreground-subtle`,children:`Parked objects — kept out of the event feed`}),d>0?r(`span`,{className:`ml-2 text-[11px] text-warning`,children:[d,` camera`,d===1?``:`s`,` could not be read`]}):null]}),e&&l(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] gap-2 p-3 pt-0`,children:u.map(e=>l(Fr,{row:e,cameraName:s.get(e.deviceId)??`Camera #${String(e.deviceId)}`,nowMs:n},e.id))})]})}n();function Lr(){let[e,t]=c(!1);return l(Be,{children:r(`section`,{className:`space-y-3`,children:[l(Or,{}),l(Nr,{onActiveChange:t}),!e&&l(Ir,{}),!e&&l(Er,{})]})})}function Rr(){let[e]=Le();return e.get(`tab`)===`retrain`?l(Re,{to:`/addon/training`,replace:!0}):l(`div`,{className:`flex flex-col p-4`,children:l(Ke,{tabs:[{id:`feed`,label:`Feed`,icon:L,content:l(Lr,{})},{id:`debug`,label:`Debug`,icon:ie,content:l(cr,{})}]})})}export{Rr as EventsPage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Q as e,S as t,W as n,a as r,b as i,o as a,q as o,x as s}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as c,gt as l,ht as u,st as d,vt as f}from"./player-overlays-B7T46vDu.js";import{Al as p,Cl as m,Cn as h,Cr as g,Dl as _,Dn as v,El as y,En as b,Fd as x,Fn as S,Ft as C,Hl as w,In as T,Jn as E,Lu as D,Ml as ee,N as O,Nl as k,Ol as te,Ot as A,P as j,Pl as ne,Qd as M,Ru as N,Sd as P,Sl as re,Sn as F,Sr as ie,Tl as ae,Tn as I,U as oe,Uu as se,W as ce,bd as le,bl as ue,gd as L,id as de,iu as fe,jl as pe,ju as R,kl as me,la as he,mu as ge,nn as z,nu as B,qn as V,td as _e,tr as ve,vd as H,wl as ye,xd as be,xl as xe,xn as U,yl as Se,zu as Ce}from"./src-QOexoM_4.js";import{t as we}from"./history-Dcle7WpC.js";import{t as Te}from"./monitor-smartphone-CiL6wFjy.js";import{_ as W,a as Ee,b as De,c as Oe,d as ke,f as Ae,g as je,h as G,i as Me,l as Ne,m as Pe,n as Fe,o as Ie,p as Le,s as Re,t as ze,u as Be,v as K,y as q}from"./SessionsList-DW5tspI_.js";import{a as Ve,i as He,o as Ue,s as We}from"./client-BBcQuaON.js";import{$ as Ge,R as J,X as Ke,Y as qe,at as Je,c as Ye,it as Xe,p as Ze,rt as Qe,s as $e}from"./index-Wd9AuQ7z.js";import{t as et}from"./AdminPage-BSFohA3i.js";import{t as tt}from"./AdminTabs-C1o_WGDw.js";import{n as nt,r as rt,t as it}from"./AddonIntegrationBody-WZ-GmbiU.js";import{n as at,t as ot}from"./addon-display-names-BkwMrExv.js";var st=f(`book-open`,[[`path`,{d:`M12 7v14`,key:`1akyts`}],[`path`,{d:`M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z`,key:`ruj8y`}]]),ct=f(`key-square`,[[`path`,{d:`M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z`,key:`165ttr`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814`,key:`1ubxi2`}]]);e();function lt(){let e=V(),t=B.useUtils(),r=q(),{data:i,isLoading:a}=_(),c=n(()=>i??[],[i]),l=B.useQueries(e=>c.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),u=B.auth.listLoginMethods.useQuery(),[d,f]=o(null),p=k({onSuccess:()=>void t.userManagement.listExternalIdentities.invalidate(),onError:e=>f(`Remove failed: ${e.message}`)}),m=n(()=>new Map((u.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[u.data]),h=c.flatMap((e,t)=>l[t]?.data??[]),g=h.map(e=>({...ke(e,r),kind:m.get(e.provider)??e.provider})),v=async t=>{let n=h.find(e=>Be(e)===t.id);n!==void 0&&await e({title:`Remove sign-in link`,message:`"${t.ownerName}" will no longer be able to sign in with this ${t.kind} account.`,confirmLabel:`Remove`,variant:`danger`})&&(f(null),p.mutate({userId:n.userId,provider:n.provider,subject:n.subject}))};return s(W,{notice:K(d),onDismissNotice:()=>{f(null)},id:`external-identities`,title:`Sign-in links`,icon:Je,description:`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`,children:s(G,{rows:g,label:`sign-in links`,isLoading:a||l.some(e=>e.isLoading),loadError:l.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:`Remove`,icon:De,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:p.isPending}})})}e();function ut(){let e=V(),t=a(),r=q(),i=ye(),[c,l]=o(null),u=me({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listApiKeys`]]}),onError:e=>l(`Revoke failed: ${e.message}`)}),f=n(()=>(i.data??[]).map(e=>Ne(e,r)),[i.data,r]),p=async t=>{await e({title:`Revoke "${t.name}"?`,message:`Any client using this key loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(l(null),u.mutate({id:t.id}))};return s(W,{notice:K(c),onDismissNotice:()=>{l(null)},id:`legacy-api-keys`,title:`Legacy API keys`,icon:we,description:`Keys from before scoped tokens. Nothing creates them any more; revoke them and issue a scoped token instead.`,children:s(G,{rows:f,label:`legacy API keys`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No legacy API keys.`,action:{label:`Revoke`,icon:d,isAvailable:()=>!0,onRun:e=>void p(e),busyId:u.isPending?u.variables?.id??null:null,disabled:u.isPending}})})}e();function dt(e){if(e.type===`category`){let t=e.target??``;return t===`device`?`all devices`:`all ${t}`}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function ft(){let e=V(),t=a(),r=y(),[i,c]=o(null),l=p({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),onError:e=>c(`Revoke failed: ${e.message}`)}),u=n(()=>(r.data??[]).map(e=>Ae(e,e.scopes.map(dt).join(`, `))),[r.data]),f=async t=>{await e({title:`Revoke the "${t.name}" link?`,message:`${t.name} loses access for ${t.ownerName} on its next call. Linking it again needs the account-link flow from the start.`,confirmLabel:`Revoke`,variant:`danger`})&&(c(null),l.mutate({id:t.id}))},m=l.isPending?l.variables?.id??null:null;return s(W,{notice:K(i),onDismissNotice:()=>{c(null)},id:`linked-apps`,title:`Linked apps`,icon:H,description:`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call.`,children:s(G,{rows:u,label:`linked apps`,isLoading:r.isLoading,loadError:r.isError?r.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:`Revoke`,icon:d,isAvailable:e=>e.status===`active`,onRun:e=>void f(e),busyId:m,disabled:l.isPending}})})}e();var pt={one:`session`,many:`sessions`};function mt(){let e=V(),t=B.useUtils(),r=q(),i=B.auth.listSessions.useQuery(),[a,c]=o(null),l=()=>void t.auth.listSessions.invalidate(),u=B.auth.revokeSessions.useMutation({onSuccess:l,onError:e=>c(`Sign out failed: ${e.message}`)}),d=je(`login-session`,pt,l),f=n(()=>(i.data??[]).map(e=>Le(e,r,{client:e=>Ee(e).label,method:Ie})),[i.data,r]),p=async t=>{await e({title:`Sign out this session`,message:`${t.ownerName} on ${t.name} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(c(null),u.mutate({id:t.id}))};return s(W,{notice:K(a,d.outcome),onDismissNotice:()=>{c(null),d.dismiss()},id:`login-sessions`,title:`Login sessions`,icon:Te,description:`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`,children:s(G,{rows:f,label:`sessions`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:`Sign out`,icon:Qe,isAvailable:e=>e.status===`active`,onRun:e=>void p(e),busyId:u.isPending&&u.variables!==void 0&&`id`in u.variables?u.variables.id:null,disabled:u.isPending||d.busy},bulk:{revoke:d,noun:pt,isSelectable:e=>e.status===`active`}})})}e();function ht({users:e,onClose:n,onSubmit:r,submitting:i}){let{user:a}=J(),c=a?.isAdmin===!0?null:a?.scopes??[],[l,u]=o(e[0]?.id??``),[d,f]=o(``),[p,m]=o([{type:`capability`,target:``,access:[`view`,`create`]}]),[g,_]=o(``),y=j(p),x=l!==``&&d.trim().length>0&&p.length>0&&y===null&&!i;return s(U,{open:!0,onOpenChange:e=>!e&&n(),children:t(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(b,{children:s(v,{children:`Create scoped token`})}),t(F,{className:`space-y-3`,children:[t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`scoped-token-user`,children:`On behalf of user`}),s(S,{id:`scoped-token-user`,value:l,onChange:e=>u(e.target.value),options:e.map(e=>({value:e.id,label:e.username}))})]}),t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`scoped-token-name`,children:`Name`}),s(w,{id:`scoped-token-name`,value:d,onChange:e=>f(e.target.value),placeholder:`cloudflare-tunnel-route`})]}),t(`div`,{className:`space-y-1`,children:[s(z,{children:`Scopes`}),s(O,{value:p,onChange:m,clampToParent:c}),y&&s(`p`,{className:`text-[10px] text-danger`,children:y}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Each scope picks a (cap or addon) target + one or more access flavours. The token can access ONLY what's listed.`})]}),t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`scoped-token-days`,children:`Expires in (days)`}),s(w,{id:`scoped-token-days`,type:`number`,min:1,value:g,onChange:e=>_(e.target.value),placeholder:`30`}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave blank for non-expiring.`})]})]}),t(I,{children:[s(T,{type:`button`,variant:`outline`,size:`sm`,onClick:n,children:`Cancel`}),t(T,{type:`button`,variant:`primary`,size:`sm`,onClick:()=>{let e=parseInt(g,10),t=Number.isFinite(e)&&e>0?Date.now()+e*864e5:void 0;r({userId:l,name:d.trim(),scopes:p,expiresAt:t})},disabled:!x,children:[i?s(L,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}):s(D,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`Issue token`]})]})]})})}function gt({token:e,label:n,onClose:r}){return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`md`,scroll:`body`,children:[s(b,{children:s(v,{children:`Token: ${n}`})}),t(F,{className:`space-y-3`,children:[s(`div`,{className:`rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning`,children:`Copy this token now. Once you close this dialog the secret cannot be displayed again.`}),s(`div`,{className:`select-all break-all rounded-md border border-border bg-background p-2 font-mono text-[11px] text-foreground`,children:e})]}),t(I,{children:[s(A,{value:e,label:`Copy`,srLabel:`token`}),s(T,{type:`button`,variant:`primary`,size:`sm`,onClick:r,children:`Done`})]})]})})}e();function _t(e){return e.type===`device`?`device:[${ce(e.selector)}]`:`${e.type}:${e.target??``}`}function vt(){let e=V(),r=a(),i=q(),{data:c,isLoading:l}=_(),u=n(()=>c??[],[c]),f=B.useQueries(e=>u.map(t=>e.userManagement.listScopedTokens({userId:t.id}))),[p,m]=o(null),[h,g]=o(!1),[v,y]=o(null),b=()=>void r.invalidateQueries({queryKey:[[`userManagement`,`listScopedTokens`]]}),x=Se({onSuccess:({token:e,record:t})=>{b(),g(!1),y({token:e,label:t.name})},onError:e=>m(`Create failed: ${e.message}`)}),S=pe({onSuccess:b,onError:e=>m(`Revoke failed: ${e.message}`)}),C=Date.now(),w=u.flatMap((e,t)=>(f[t]?.data??[]).map(t=>Pe(t,e.id,i,t.scopes.map(_t).join(`, `),C))),E=f.find(e=>e.isError)?.error?.message??null,ee=async t=>{await e({title:`Revoke "${t.name}"?`,message:`${t.ownerName}'s scoped token stops working on its next use. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(m(null),S.mutate({id:t.id}))};return t(W,{notice:K(p),onDismissNotice:()=>{m(null)},id:`scoped-tokens`,title:`Scoped tokens`,icon:be,description:`Tokens issued on behalf of a user for one narrow surface — an addon, an integration, a capability or some devices. Every token must be scoped, so revoking one has a predictable blast radius.`,actions:t(T,{type:`button`,variant:`primary`,size:`sm`,onClick:()=>g(!0),disabled:u.length===0,title:u.length===0?`Create a user first`:`Issue a scoped token`,children:[s(D,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`New token`]}),children:[s(G,{rows:w,label:`scoped tokens`,isLoading:l||f.some(e=>e.isLoading),loadError:E,emptyText:`No scoped tokens.`,action:{label:`Revoke`,icon:d,isAvailable:()=>!0,onRun:e=>void ee(e),busyId:S.isPending?S.variables?.id??null:null,disabled:S.isPending}}),h&&s(ht,{users:u.map(e=>({id:e.id,username:e.username})),onClose:()=>g(!1),onSubmit:e=>x.mutate({userId:e.userId,name:e.name,scopes:e.scopes,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}}),submitting:x.isPending}),v!==null&&s(gt,{token:v.token,label:v.label,onClose:()=>y(null)})]})}e();var yt={one:`admin token`,many:`admin tokens`},bt=7,xt=90,St=80;function Ct(e){let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=xt?t:null}function wt(){let{user:e}=J();return e?.isAdmin?s(Tt,{}):null}function Tt(){let e=V(),r=B.useUtils(),i=B.auth.listAdminTokens.useQuery(),a=q(),{requestProof:c,dialog:l}=Me(`Creating an admin token`),[u,f]=o(``),[p,m]=o(String(bt)),[h,g]=o(null),[_,v]=o(!1),[y,b]=o(null),x=()=>{r.auth.listAdminTokens.invalidate(),r.auth.listAuthAudit.invalidate()},S=B.auth.createAdminToken.useMutation({onSuccess:({token:e,record:t})=>{x(),f(``),m(String(bt)),b({token:e,label:t.name})},onError:e=>g(`Create failed: ${e.message}`)}),C=B.auth.revokeAdminToken.useMutation({onSuccess:x,onError:e=>g(`Revoke failed: ${e.message}`)}),E=je(`admin-token`,yt,x),D=Date.now(),ee=n(()=>(i.data??[]).map(e=>Oe(e,a,D)),[i.data,a]),O=u.trim(),k=Ct(p),te=O.length>0&&O.length<=St&&k!==null&&!S.isPending&&!_,A=async()=>{if(!te||k===null)return;g(null),v(!0);let e=await c();v(!1),e!==null&&S.mutate({name:O,expiresInDays:k,reauthToken:e})},j=async t=>{await e({title:`Revoke admin token "${t.name}"?`,message:`Every script using it loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(g(null),C.mutate({id:t.id}))};return t(`div`,{"data-testid":`admin-tokens`,children:[l,t(W,{id:`admin-tokens`,title:`Admin tokens`,icon:N,tone:`danger`,notice:K(h,E.outcome),onDismissNotice:()=>{g(null),E.dismiss()},description:t(`div`,{className:`space-y-1`,children:[t(`p`,{children:[`An admin token acts as a `,s(`strong`,{children:`full administrator`}),` for scripts, e.g.`,` `,s(`code`,{className:`font-mono`,children:`node scripts/hub/hub.mjs --token-file <file> …`}),`. Anyone holding it can do anything an admin can.`]}),s(`p`,{children:`It expires in at most 90 days and every use is audited. Creating one asks you to confirm it is you.`})]}),children:[t(`form`,{className:`grid grid-cols-1 items-end gap-2 sm:grid-cols-[1fr_120px_auto]`,onSubmit:e=>{e.preventDefault(),A()},children:[t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`admin-token-name`,children:`Token name`}),s(w,{id:`admin-token-name`,value:u,maxLength:St,onChange:e=>f(e.target.value),placeholder:`nightly-backup`})]}),t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`admin-token-days`,children:`Expires in (days)`}),s(w,{id:`admin-token-days`,type:`number`,min:1,max:xt,value:p,onChange:e=>m(e.target.value),state:k===null?`error`:`default`})]}),t(T,{type:`submit`,variant:`danger`,size:`sm`,disabled:!te,children:[S.isPending||_?s(L,{className:`h-3.5 w-3.5 animate-spin`}):s(N,{className:`h-3.5 w-3.5`}),`Create admin token`]})]}),k===null&&t(`div`,{className:`text-[11px] text-danger`,children:[`Expiry must be a whole number of days, 1 to `,xt,`.`]}),s(G,{rows:ee,label:`admin tokens`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No admin tokens.`,action:{label:`Revoke`,icon:d,isAvailable:e=>e.status===`active`,onRun:e=>void j(e),busyId:C.isPending?C.variables?.id??null:null,disabled:C.isPending||E.busy},bulk:{revoke:E,noun:yt,isSelectable:e=>e.status===`active`}})]}),y&&s(gt,{token:y.token,label:y.label,onClose:()=>b(null)})]})}var Et={"share-link":`share links`,"admin-token":`admin tokens`,"login-session":`login sessions`};function Y(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Dt(e,t){let n=Y(e,`tokenId`);return Y(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function X(e){return e.filter(e=>e!==null)}function Ot(e){let t=Y(e,`prefix`);return t===null?null:`Prefix ${t}…`}function kt(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:`Admin token "${Dt(n,t)}" created`,details:X([Ot(n),typeof e==`number`?`Expires ${Re(e)}`:null])}}case`admin-token-used`:{let e=Y(n,`path`);return{title:`Admin token "${Dt(n,t)}" used`,details:X([Ot(n),e===null?null:`Call ${e}`])}}case`admin-token-revoked`:return{title:`Admin token "${Dt(n,t)}" revoked`,details:X([Ot(n)])};case`credentials-revoked`:{let e=Y(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=Et[e]??`${e}s`;return{title:`${typeof t==`number`?String(t):`?`} ${i} revoked in bulk`,details:X([typeof r==`number`&&r>0?`${String(r)} skipped`:null,Y(n,`ids`)===null?null:`Ids ${Y(n,`ids`)??``}`])}}case`second-factor-skipped`:{let e=Y(n,`method`),t=Y(n,`factors`);return{title:`Second factor skipped on a trusted network`,details:X([e===null?null:`Signed in with ${Ie(e)}`,t===null?null:`Skipped: ${t.split(`,`).join(`, `)}`])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}e();var At=100;function jt(){let{user:e}=J();return e?.isAdmin?s(Nt,{}):null}function Mt(){let{data:e}=_(),{data:t}=B.auth.listAdminTokens.useQuery();return n(()=>{let n=new Map;for(let t of e??[])n.set(t.id,t.username);let r=new Map;for(let e of t??[])r.set(e.id,e.name);return{userNameById:n,tokenNameById:r}},[e,t])}function Nt(){let e=B.auth.listAuthAudit.useQuery({limit:At}),{userNameById:n,tokenNameById:r}=Mt(),i=e.data??[];return t(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[t(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[s(se,{className:`h-3.5 w-3.5 text-foreground-subtle`}),s(`div`,{className:`text-xs font-semibold text-foreground`,children:`Authentication audit`}),t(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[`Latest `,At,`, newest first`]})]}),s(`div`,{className:`p-4`,children:e.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(L,{className:`h-3.5 w-3.5 animate-spin`}),`Loading audit trail…`]}):e.isError?t(`div`,{className:`text-[11px] text-danger`,children:[`Could not load the audit trail: `,e.error?.message??`Request failed`]}):i.length===0?s(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center`,children:`No authentication events recorded yet.`}):s(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:i.map(e=>s(Pt,{record:e,userName:e.userId===void 0?null:n.get(e.userId)??e.userId,tokenNameById:r},e.id))})})]})}function Pt({record:e,userName:n,tokenNameById:r}){let i=kt(e,r);return t(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[t(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[s(`span`,{className:`font-medium text-foreground`,children:i.title}),s(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Re(e.at)})]}),t(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[n!==null&&s(`span`,{className:`text-foreground`,children:n}),e.ip!==void 0&&s(`span`,{className:`font-mono`,children:e.ip}),i.details.map(e=>s(`span`,{className:`font-mono`,children:e},e))]})]})}var Z={loginSessions:`login-sessions`,linkedApps:`linked-apps`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,legacyApiKeys:`legacy-api-keys`,externalIdentities:`external-identities`,audit:`auth-audit`},Ft={state:`ok`,stateLabel:`available`,showState:!1};function Q(e,t,n,r){return{id:e,name:t,fallbackIcon:n,...Ft,render:r}}function It(){let e=ye(),t=(e.data??[]).length>0;return s(rt,{icon:ct,title:`Tokens & sessions`,subtitle:`Every credential this hub honours — who holds it, what it can reach, when it was last used and when it expires. Pick a kind; revoke one, or select several and revoke them after typing the count.`,groups:[{id:`sessions`,label:`Sessions`,entries:[Q(Z.loginSessions,`Login sessions`,Te,()=>s(mt,{})),Q(Z.linkedApps,`Linked apps`,H,()=>s(ft,{}))]},{id:`tokens`,label:`Tokens`,entries:[Q(Z.scopedTokens,`Scoped tokens`,be,()=>s(vt,{})),Q(Z.adminTokens,`Admin tokens`,N,()=>s(wt,{})),Q(Z.shareLinks,`Share links`,Ce,()=>s(Fe,{})),...t?[Q(Z.legacyApiKeys,`Legacy API keys`,we,()=>s(ut,{}))]:[]]},{id:`identity`,label:`Identity`,entries:[Q(Z.externalIdentities,`Sign-in links`,Je,()=>s(lt,{})),Q(Z.audit,`Audit`,se,()=>s(jt,{}))]}],isLoading:e.isLoading,emptyTitle:`No credential kinds`,emptyDescription:`This hub offers no credential kinds.`})}e();var Lt=3e4,Rt=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],$={title:`Authentication`,subtitle:`Login providers (local password, OIDC, SAML) and second-factor providers (passkeys / WebAuthn). They run in parallel — enable or disable each independently; disabling one only removes that method, local password login is unaffected.`,emptyTitle:`No authentication providers registered`,emptyDescription:`Local auth should always be available — if this list is empty the local-auth builtin failed to register. Check the Addons page for load errors.`,installLabel:`Add provider`};function zt(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:ct,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`Scoped tokens, admin tokens and sessions are managed from Identity → Tokens & sessions.`],setupSteps:[`A fresh hub has one account, admin / changeme — the first sign-in asks for a new password. Add users from Users → New user.`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:Xe,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`Explicit linking only: an IdP account signs in only the CamStack user who linked it from their profile (My access → Linked sign-in accounts). No auto-created users, no email matching.`,`The linked user’s role, scopes and two-factor authentication apply.`],setupSteps:[`Register a web app at your IdP and copy the client_id + client_secret.`,"Set the redirect URI to `https://<this-hub>/addon/<addon-id>/callback`.",`Paste issuer + credentials in the Settings panel below — saves on every change.`,`Each user then links their IdP account from My access → Linked sign-in accounts.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:Xe,bullets:[`Heavier handshake than OIDC — exchange metadata XML with your IdP.`,`Group → role mapping via SAML assertions.`]}:e.startsWith(`auth-webauthn`)||e.startsWith(`auth-passkey`)?{headline:`Passkeys / WebAuthn — passwordless second factor.`,icon:R,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)?{headline:`TOTP — second factor.`,icon:R,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:D,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Bt(){let e=g({capName:Rt[0].capName},{refetchInterval:Lt}),t=g({capName:Rt[1].capName},{refetchInterval:Lt}),r=ie(void 0,{refetchInterval:Lt}),i=n(()=>ot(r.data??[]),[r.data]),a=n(()=>{let n=[],r=[e.data??[],t.data??[]];for(let[e,t]of Rt.entries())for(let a of r[e]??[])n.push({addonId:a.addonId,displayName:i.get(a.addonId)??a.addonId,isActive:a.isActive,capName:t.capName,stageBadge:t.stageBadge});return n},[e.data,t.data,i]),o=[{id:`authentication`,label:`Authentication providers`,install:{capability:Rt[0].capName,label:$.installLabel},entries:a.map(e=>({id:e.addonId,name:e.displayName,fallbackIcon:D,...at(e.isActive),render:()=>s(it,{addonId:e.addonId,displayName:e.displayName,capName:e.capName,isActive:e.isActive,badges:e.stageBadge===null?null:s(ve,{variant:`info`,className:nt,children:e.stageBadge}),panels:[{id:`about`,title:`About`,icon:zt(e.addonId).icon,content:s(Vt,{addonId:e.addonId})}]})}))}];return s(rt,{icon:D,title:$.title,subtitle:$.subtitle,groups:o,isLoading:e.isLoading||t.isLoading,emptyTitle:$.emptyTitle,emptyDescription:$.emptyDescription})}function Vt({addonId:e}){let n=zt(e),r=n.icon;return t(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[t(`div`,{className:`flex items-start gap-2.5`,children:[s(r,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),s(`div`,{className:`text-xs text-foreground font-medium`,children:n.headline})]}),s(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:n.bullets.map((e,t)=>s(`li`,{children:e},t))}),n.setupSteps&&n.setupSteps.length>0&&t(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[t(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[s(st,{className:`h-3 w-3`}),`Setup steps`]}),s(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:n.setupSteps.map((e,t)=>s(`li`,{children:e},t))})]}),e===`local-auth`&&t(`div`,{className:`rounded-md border border-info/30 bg-info/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[s(P,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),t(`span`,{children:[`TOTP / 2FA is self-service: each user enrols from their own profile page —`,` `,s(qe,{to:`/system/my-access`,className:`underline text-primary`,children:`My access`}),` `,`→ “Two-factor authentication” → Enable 2FA. Admins can only remove a user’s active enrollment (lost device) from the`,` `,s(qe,{to:`/system/identity?tab=users`,className:`underline text-primary`,children:`Users`}),` `,`page via Actions → “Remove 2FA”.`]})]})]})}function Ht({userId:e,username:n,onClose:r}){let i=V(),a=B.useUtils(),o=ae({userId:e}),c=B.auth.listLoginMethods.useQuery(),l=k({onSuccess:()=>void a.userManagement.listExternalIdentities.invalidate()}),u=new Map((c.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),d=o.data??[],f=async(t,r)=>{await i({title:`Remove sign-in link`,message:`"${n}" will no longer be able to sign in with this ${r} account.`,confirmLabel:`Remove`,variant:`danger`})&&l.mutate({userId:e,provider:t.provider,subject:t.subject})};return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[s(b,{children:t(v,{className:`flex items-center gap-2`,children:[s(H,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Linked sign-in accounts`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),s(F,{className:`space-y-3`,children:o.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(L,{className:`h-3.5 w-3.5 animate-spin`}),`Loading…`]}):d.length===0?s(`p`,{className:`text-xs text-foreground-subtle`,children:`No linked accounts. Only the user can link one, from their own profile page.`}):s(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:d.map(e=>{let n=u.get(e.provider),r=n??e.provider;return t(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[t(`div`,{className:`flex-1 min-w-0`,children:[t(`div`,{className:`font-medium text-foreground truncate`,children:[r,n===void 0&&s(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:`provider unavailable`})]}),t(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[e.label??e.subject,` ·`,` `,new Date(e.linkedAt).toLocaleDateString()]})]}),t(`button`,{onClick:()=>void f(e,r),disabled:l.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[s(De,{className:`h-3 w-3`}),`Remove`]})]},`${e.provider}|${e.subject}`)})})}),s(I,{children:s(T,{onClick:r,variant:`secondary`,children:`Close`})})]})})}function Ut({userId:e,username:n,onClose:r}){let o=a(),c=V(),l=m({userId:e}),u=l.data,d=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),f=re({onSuccess:()=>{d(),r()}}),p=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(b,{children:t(v,{className:`flex items-center gap-2`,children:[s(R,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Two-factor authentication`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),t(F,{className:`space-y-4`,children:[p===`loading`&&t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(L,{className:`h-3.5 w-3.5 animate-spin`}),`Checking status…`]}),p===`not_enrolled`&&t(`div`,{className:`rounded-md border border-border bg-surface-hover/30 px-3 py-2.5 flex items-start gap-2.5 text-xs text-foreground-subtle`,children:[s(P,{className:`h-4 w-4 mt-0.5 shrink-0`}),t(`div`,{children:[s(`div`,{className:`font-medium text-foreground`,children:`2FA not enrolled`}),s(`p`,{className:`mt-0.5`,children:`Only the user themselves can enable 2FA, from their own profile page.`})]})]}),p===`enrolled`&&u&&t(i,{children:[t(`div`,{className:`rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5 flex items-start gap-2.5`,children:[s(M,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),t(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[s(`div`,{className:`font-medium`,children:`2FA is active`}),t(`div`,{className:`text-foreground-subtle`,children:[`Enrolled on`,` `,u.confirmedAt?new Date(u.confirmedAt).toLocaleString():`—`]})]})]}),s(`div`,{className:`text-[11px] text-foreground-subtle`,children:`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`}),t(`div`,{className:`flex justify-end gap-2`,children:[s(T,{onClick:r,variant:`secondary`,children:`Close`}),t(`button`,{onClick:async()=>{await c({title:`Remove 2FA`,message:`Remove two-factor authentication for "${n}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,confirmLabel:`Remove`,variant:`danger`})&&f.mutate({userId:e})},disabled:f.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[f.isPending?s(L,{className:`h-3 w-3 animate-spin`}):s(fe,{className:`h-3 w-3`}),`Remove 2FA`]})]})]})]})]})})}e();function Wt({userId:e,username:n,onClose:r}){let{user:i,logout:a}=J(),c=i?.id===e,l=V(),u=B.useUtils(),d=B.auth.listSessions.useQuery({userId:e}),[f,p]=o(null),m=B.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(c&&`userId`in t){a();return}u.auth.listSessions.invalidate()},onError:e=>p(`Sign out failed: ${e.message}`)}),g=async e=>{await l({title:`Sign out this session`,message:`"${n}" on ${Ee(e.client).label} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(p(null),m.mutate({id:e.id}))},_=async()=>{await l({title:`Sign out everywhere`,message:c?`Every session of your own account ends, this browser included: you will be signed out here too.`:`Every session of "${n}" ends at once; each device has to sign in again.`,confirmLabel:`Sign out everywhere`,variant:`danger`})&&(p(null),m.mutate({userId:e}))},y=m.isPending&&m.variables!==void 0&&`id`in m.variables?m.variables.id:null;return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[s(b,{children:t(v,{className:`flex items-center gap-2`,children:[s(Te,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Active sessions`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),t(F,{className:`space-y-3`,children:[f!==null&&s(`div`,{className:`text-[11px] text-danger`,children:f}),s(ze,{sessions:d.data??[],isLoading:d.isLoading,loadError:d.isError?d.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void g(e),revokingId:y})]}),t(I,{className:`justify-between`,children:[t(`button`,{onClick:()=>void _(),disabled:m.isPending||(d.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[m.isPending&&y===null?s(L,{className:`h-3 w-3 animate-spin`}):s(Qe,{className:`h-3 w-3`}),`Sign out everywhere`]}),s(T,{onClick:r,variant:`secondary`,children:`Close`})]})]})})}function Gt({icon:e,label:n,count:r,all:i,total:a}){return t(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[s(e,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(`span`,{className:`min-w-0 flex-1 text-foreground-subtle`,children:n}),s(`span`,{className:r===0?`text-foreground-subtle`:`font-medium text-foreground`,children:r===0?`none`:i?`all ${a}`:`${r} of ${a}`})]})}function Kt({scopes:e,isAdmin:n,invalidReason:a}){let o=c(),l=r({queryKey:[`auth`,`previewScope`,e,n],enabled:a===null,queryFn:()=>o.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:n})}),{data:u}=he({projection:`slim`}),f=u?.length??0;if(a!==null)return s(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:t(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,children:[s(N,{className:`h-3 w-3 shrink-0`}),a]})});if(l.isLoading)return t(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-surface p-3 text-[11px] text-foreground-subtle`,children:[s(L,{className:`h-3 w-3 animate-spin`}),`Resolving…`]});if(l.isError||!l.data)return s(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:s(`p`,{className:`text-[11px] text-danger`,children:`Could not resolve this grant set. Saving is still allowed — the server enforces the same rules either way.`})});let p=l.data;return s(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:p.isAdmin?t(`p`,{className:`text-[11px] text-foreground`,children:[s(`span`,{className:`font-medium`,children:`Administrator`}),` — unrestricted. Grants are ignored for an admin.`]}):t(i,{children:[s(Gt,{icon:x,label:`Devices they can see`,count:p.device.view.deviceCount,all:p.device.view.all,total:f}),s(Gt,{icon:de,label:`Devices they can operate`,count:p.device.create.deviceCount,all:p.device.create.all,total:f}),s(Gt,{icon:d,label:`Devices they can delete`,count:p.device.delete.deviceCount,all:p.device.delete.all,total:f}),t(`div`,{className:`border-t border-border pt-2 text-[10px] text-foreground-subtle`,children:[`System access: `,p.system.length===0?`none`:p.system.join(`, `),p.capabilities.length>0&&t(i,{children:[` · Extra capabilities: `,p.capabilities.map(e=>e.name).join(`, `)]}),p.addons.length>0&&t(i,{children:[` · Addons: `,p.addons.map(e=>e.name).join(`, `)]})]}),p.device.view.deviceCount===0&&s(`p`,{className:`text-[10px] text-warning`,children:`This user will not be able to see any device.`})]})})}e();function qt(e){let t=Ue(e);return t===null?{mode:e.length===0?`role`:`advanced`,roleId:null,selector:{kind:`all`},includeLinked:!0,advancedScopes:e}:{mode:`role`,roleId:t.roleId,selector:t.selector,includeLinked:t.includeLinked,advancedScopes:e}}function Jt(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:Ve({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function Yt({user:e,onClose:r,onSubmit:a,submitting:c,callerScopes:d}){let f=n(()=>qt(e.scopes??[]),[e.scopes]),[p,m]=o(f),[g,_]=o(f.mode===`advanced`),y=n(()=>Jt(p),[p]),x=!e.isAdmin&&p.mode===`role`&&p.roleId===null,S=n(()=>e.isAdmin?null:p.mode===`role`&&p.roleId===null?`Pick what this user can do to see the result.`:j(y),[e.isAdmin,p.mode,p.roleId,y]),C=e=>m({...p,...e});return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[t(b,{children:[t(v,{children:[`Access — `,e.username]}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.isAdmin?`This user is an administrator — they can do everything, and the settings below are ignored.`:`Choose what they can do, then which devices it applies to.`})]}),t(F,{className:`space-y-4`,children:[x&&t(`div`,{className:`flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 p-3`,children:[s(N,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),t(`p`,{className:`text-[11px] text-foreground`,children:[s(`span`,{className:`font-medium`,children:`No access.`}),` `,t(`span`,{className:`text-foreground-subtle`,children:[e.username,` cannot see or do anything yet. Configure it below.`]})]})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`1 · What can they do`}),s(`div`,{className:`space-y-1.5`,children:He.map(e=>{let n=p.mode===`role`&&p.roleId===e.id;return t(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 transition-colors ${n?`border-primary bg-primary/5`:`border-border hover:bg-foreground-subtle/5`}`,children:[s(`input`,{type:`radio`,name:`access-role`,checked:n,onChange:()=>C({mode:`role`,roleId:e.id}),className:`mt-0.5 border-border focus:ring-primary`}),t(`span`,{className:`min-w-0`,children:[s(`span`,{className:`block text-[12px] font-medium text-foreground`,children:e.label}),s(`span`,{className:`mt-0.5 block text-[10px] text-foreground-subtle`,children:e.description})]})]},e.id)})}),t(`button`,{type:`button`,onClick:()=>{if(!g){m({...p,mode:`advanced`,advancedScopes:y}),_(!0);return}_(!1),m(qt(p.advancedScopes))},className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] text-foreground-subtle transition-colors hover:bg-foreground-subtle/10 hover:text-foreground`,children:[s(g?l:u,{className:`h-3 w-3`}),`Advanced — edit raw grants`]}),g&&t(`div`,{className:`rounded-lg border border-border p-2`,children:[s(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`One row per grant. Anything expressible here overrides the three roles above; close this section to go back to them.`}),s(O,{value:p.advancedScopes,onChange:e=>C({mode:`advanced`,advancedScopes:e}),clampToParent:d,emptyHint:t(i,{children:[`No grants.`,` `,s(`span`,{className:`font-medium text-foreground`,children:e.username}),` cannot call any protected endpoint until one is added.`]})})]})]}),p.mode===`role`&&t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`2 · On which devices`}),s(oe,{value:p.selector,onChange:e=>C({selector:e}),includeLinked:p.includeLinked,onIncludeLinkedChange:e=>C({includeLinked:e}),clampToDeviceIds:null})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:p.mode===`role`?`3 · Result`:`2 · Result`}),s(Kt,{scopes:y,isAdmin:e.isAdmin,invalidReason:S})]})]}),t(I,{children:[s(T,{variant:`outline`,size:`sm`,onClick:r,children:`Cancel`}),s(T,{size:`sm`,onClick:()=>a([...y]),disabled:c||S!==null,children:c?s(L,{className:`h-3 w-3 animate-spin`}):`Save access`})]})]})})}e();var Xt=8;function Zt(){let e=a(),{user:n}=J(),[r,i]=o(!1),[c,l]=o(``),[u,f]=o(``),[p,m]=o(!1),[h,g]=o(null),{data:v,isLoading:y,isError:b}=_(),x=V(),S=E(),w=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),T=ue({onSuccess:()=>{w(),i(!1),l(``),f(``),m(!1),g(null)},onError:e=>{g(e instanceof Error?e.message:`Failed to create user`)}}),O=xe({onSuccess:w}),k=ne({onSuccess:w}),A=te({onSuccess:w}),j=ee({onSuccess:()=>{w(),N(null)}}),[M,N]=o(null),[P,re]=o(null),[F,ie]=o(null),[ae,I]=o(null),oe=v??[];async function se(e){await x({title:`Delete user`,message:`Permanently delete user "${e.username}"? This cannot be undone — any active sessions will be revoked on next request.`,confirmLabel:`Delete`,variant:`danger`})&&O.mutate({id:e.id})}async function ce(e){let t=await S({title:`Reset password`,message:`Set a new password for "${e.username}".`,label:`New password`,inputType:`password`,placeholder:`At least 8 characters`,confirmLabel:`Continue`,validate:e=>e.length<Xt?`Password must be at least ${String(Xt)} characters.`:null});t===null||t.length===0||await x({title:`Reset password`,message:`Reset the password for "${e.username}"? They will need to use the new password on their next login.`,confirmLabel:`Reset`})&&A.mutate({id:e.id,newPassword:t})}function de(e,t){t!==e.isAdmin&&k.mutate({id:e.id,isAdmin:t})}function pe(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}return t(et,{children:[s(`div`,{className:`flex items-center justify-end`,children:t(`button`,{onClick:()=>i(!0),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm hover:bg-primary/90`,children:[s(_e,{className:`h-3.5 w-3.5`}),`Create User`]})}),r&&t(`div`,{className:`rounded-lg border border-border bg-surface p-4 space-y-3`,children:[t(`div`,{className:`flex items-center justify-between`,children:[s(`span`,{className:`text-xs font-medium text-foreground`,children:`New User`}),s(`button`,{onClick:()=>i(!1),className:`text-foreground-subtle hover:text-foreground`,children:s(fe,{className:`h-4 w-4`})})]}),t(`div`,{className:`grid grid-cols-3 gap-3`,children:[t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Username`}),s(`input`,{type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`john`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Password`}),s(`input`,{type:`password`,value:u,onChange:e=>f(e.target.value),placeholder:`••••••••`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Admin`}),t(`label`,{className:`flex items-center gap-2 rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked),className:`rounded border-border focus:ring-primary`}),s(`span`,{className:`text-foreground-subtle`,children:`Unrestricted access`})]})]})]}),h&&s(`p`,{className:`text-[10px] text-danger`,children:h}),t(`div`,{className:`flex justify-end gap-2`,children:[s(`button`,{onClick:()=>i(!1),className:`rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground`,children:`Cancel`}),s(`button`,{onClick:()=>T.mutate({username:c,password:u,isAdmin:p}),disabled:T.isPending||!c||!u,className:`rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:T.isPending?`Creating...`:`Create`})]})]}),y&&s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Loading...`}),b&&s(`div`,{className:`text-xs text-danger`,children:`Failed to load`}),!y&&!b&&oe.length===0&&s(`div`,{className:`text-xs text-foreground-subtle`,children:`No data`}),(()=>{let e=e=>O.isPending&&O.variables?.id===e.id||k.isPending&&k.variables?.id===e.id||A.isPending&&A.variables?.id===e.id;return s(C,{columns:[{key:`username`,header:`Username`,render:e=>e.username},{key:`isAdmin`,header:`Admin`,render:n=>t(`label`,{className:`inline-flex items-center gap-1.5 text-xs cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:n.isAdmin,onChange:e=>de(n,e.target.checked),disabled:e(n),className:`rounded border-border focus:ring-primary disabled:opacity-50`}),s(`span`,{className:n.isAdmin?`text-primary font-medium`:`text-foreground-subtle`,children:n.isAdmin?`Admin`:`Regular`})]})},{key:`scopes`,header:`Access`,render:e=>e.isAdmin?s(`span`,{className:`text-[10px] italic text-foreground-subtle`,children:`everything (admin)`}):t(`button`,{onClick:()=>N(e),className:`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] hover:bg-foreground-subtle/10`,title:`Configure access`,children:[s(D,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(Qt,{scopes:e.scopes??[]})]})},{key:`createdAt`,header:`Created`,render:e=>s(`span`,{className:`text-foreground-subtle`,children:pe(e.createdAt)})},{key:`actions`,header:`Actions`,align:`right`,render:r=>{let i=e(r);return t(`div`,{className:`flex items-center justify-end gap-1`,children:[r.id!==n?.id&&r.totpEnabled&&t(`button`,{onClick:()=>re(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Remove two-factor authentication`,children:[s(R,{className:`h-3 w-3`}),`Remove 2FA`]}),t(`button`,{onClick:()=>ie(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Linked sign-in accounts`,children:[s(H,{className:`h-3 w-3`}),`Sign-in links`]}),t(`button`,{onClick:()=>I(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Active sessions`,children:[s(Te,{className:`h-3 w-3`}),`Sessions`]}),t(`button`,{onClick:()=>ce(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Reset password`,children:[s(le,{className:`h-3 w-3`}),`Reset password`]}),t(`button`,{onClick:()=>se(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Delete user`,children:[i?s(L,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Delete`]})]})}}],rows:oe,rowKey:e=>e.id,minWidthPx:560})})(),P&&s(Ut,{userId:P.id,username:P.username,onClose:()=>re(null)}),F&&s(Ht,{userId:F.id,username:F.username,onClose:()=>ie(null)}),ae&&s(Wt,{userId:ae.id,username:ae.username,onClose:()=>I(null)}),M&&s($t,{user:M,onClose:()=>N(null),onSubmit:e=>j.mutate({userId:M.id,scopes:e}),submitting:j.isPending})]})}function Qt({scopes:e}){if(e.length===0)return s(`span`,{className:`font-medium text-warning`,children:`No access`});let n=Ue(e);return n===null?t(`span`,{className:`text-foreground-subtle`,children:[`Custom · `,e.length,` grant`,e.length===1?``:`s`]}):t(`span`,{className:`text-foreground-subtle`,children:[s(`span`,{className:`font-medium text-foreground`,children:We(n.roleId).label}),` ·`,` `,ce(n.selector)]})}function $t(e){let{user:t}=J(),n=t?.isAdmin===!0;return s(Yt,{...e,callerScopes:n?null:t?.scopes??[]})}var en={"api-keys":Z.scopedTokens,"linked-sessions":Z.linkedApps};function tn(){let[e]=Ge(),t=en[e.get(`tab`)??``];return t===void 0?s(`div`,{className:`flex flex-col p-4`,children:s(tt,{tabs:[{id:`users`,label:`Users`,icon:ge,content:s(Zt,{})},{id:Ye.access.tab,label:`Tokens & sessions`,icon:be,content:s(It,{}),ownedParams:$e},{id:Ye.authentication.tab,label:`Authentication`,icon:D,content:s(Bt,{}),ownedParams:$e}]})}):s(Ke,{to:Ze(`access`,{integration:t}),replace:!0})}export{tn as IdentityPage};
|
|
1
|
+
import{Q as e,S as t,W as n,a as r,b as i,o as a,q as o,x as s}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as c,gt as l,ht as u,st as d,vt as f}from"./player-overlays-B7T46vDu.js";import{Al as p,Cl as m,Cn as h,Cr as g,Dl as _,Dn as v,El as y,En as b,Fd as x,Fn as S,Ft as C,Hl as w,In as T,Jn as E,Lu as D,Ml as ee,N as O,Nl as k,Ol as te,Ot as A,P as j,Pl as ne,Qd as M,Ru as N,Sd as P,Sl as re,Sn as F,Sr as ie,Tl as ae,Tn as I,U as oe,Uu as se,W as ce,bd as le,bl as ue,gd as L,id as de,iu as fe,jl as pe,ju as R,kl as me,la as he,mu as ge,nn as z,nu as B,qn as V,td as _e,tr as ve,vd as H,wl as ye,xd as be,xl as xe,xn as U,yl as Se,zu as Ce}from"./src-BTX2jfA7.js";import{t as we}from"./history-Dcle7WpC.js";import{t as Te}from"./monitor-smartphone-CiL6wFjy.js";import{_ as W,a as Ee,b as De,c as Oe,d as ke,f as Ae,g as je,h as G,i as Me,l as Ne,m as Pe,n as Fe,o as Ie,p as Le,s as Re,t as ze,u as Be,v as K,y as q}from"./SessionsList-B-6hhNIP.js";import{a as Ve,i as He,o as Ue,s as We}from"./client-BBcQuaON.js";import{$ as Ge,R as J,X as Ke,Y as qe,at as Je,c as Ye,it as Xe,p as Ze,rt as Qe,s as $e}from"./index-BWu66tVw.js";import{t as et}from"./AdminPage-BSFohA3i.js";import{t as tt}from"./AdminTabs-BcE-Q0tO.js";import{n as nt,r as rt,t as it}from"./AddonIntegrationBody-BhLL7FoP.js";import{n as at,t as ot}from"./addon-display-names-BkwMrExv.js";var st=f(`book-open`,[[`path`,{d:`M12 7v14`,key:`1akyts`}],[`path`,{d:`M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z`,key:`ruj8y`}]]),ct=f(`key-square`,[[`path`,{d:`M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z`,key:`165ttr`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814`,key:`1ubxi2`}]]);e();function lt(){let e=V(),t=B.useUtils(),r=q(),{data:i,isLoading:a}=_(),c=n(()=>i??[],[i]),l=B.useQueries(e=>c.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),u=B.auth.listLoginMethods.useQuery(),[d,f]=o(null),p=k({onSuccess:()=>void t.userManagement.listExternalIdentities.invalidate(),onError:e=>f(`Remove failed: ${e.message}`)}),m=n(()=>new Map((u.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[u.data]),h=c.flatMap((e,t)=>l[t]?.data??[]),g=h.map(e=>({...ke(e,r),kind:m.get(e.provider)??e.provider})),v=async t=>{let n=h.find(e=>Be(e)===t.id);n!==void 0&&await e({title:`Remove sign-in link`,message:`"${t.ownerName}" will no longer be able to sign in with this ${t.kind} account.`,confirmLabel:`Remove`,variant:`danger`})&&(f(null),p.mutate({userId:n.userId,provider:n.provider,subject:n.subject}))};return s(W,{notice:K(d),onDismissNotice:()=>{f(null)},id:`external-identities`,title:`Sign-in links`,icon:Je,description:`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`,children:s(G,{rows:g,label:`sign-in links`,isLoading:a||l.some(e=>e.isLoading),loadError:l.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:`Remove`,icon:De,isAvailable:()=>!0,onRun:e=>void v(e),busyId:null,disabled:p.isPending}})})}e();function ut(){let e=V(),t=a(),r=q(),i=ye(),[c,l]=o(null),u=me({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listApiKeys`]]}),onError:e=>l(`Revoke failed: ${e.message}`)}),f=n(()=>(i.data??[]).map(e=>Ne(e,r)),[i.data,r]),p=async t=>{await e({title:`Revoke "${t.name}"?`,message:`Any client using this key loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(l(null),u.mutate({id:t.id}))};return s(W,{notice:K(c),onDismissNotice:()=>{l(null)},id:`legacy-api-keys`,title:`Legacy API keys`,icon:we,description:`Keys from before scoped tokens. Nothing creates them any more; revoke them and issue a scoped token instead.`,children:s(G,{rows:f,label:`legacy API keys`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No legacy API keys.`,action:{label:`Revoke`,icon:d,isAvailable:()=>!0,onRun:e=>void p(e),busyId:u.isPending?u.variables?.id??null:null,disabled:u.isPending}})})}e();function dt(e){if(e.type===`category`){let t=e.target??``;return t===`device`?`all devices`:`all ${t}`}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function ft(){let e=V(),t=a(),r=y(),[i,c]=o(null),l=p({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),onError:e=>c(`Revoke failed: ${e.message}`)}),u=n(()=>(r.data??[]).map(e=>Ae(e,e.scopes.map(dt).join(`, `))),[r.data]),f=async t=>{await e({title:`Revoke the "${t.name}" link?`,message:`${t.name} loses access for ${t.ownerName} on its next call. Linking it again needs the account-link flow from the start.`,confirmLabel:`Revoke`,variant:`danger`})&&(c(null),l.mutate({id:t.id}))},m=l.isPending?l.variables?.id??null:null;return s(W,{notice:K(i),onDismissNotice:()=>{c(null)},id:`linked-apps`,title:`Linked apps`,icon:H,description:`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call.`,children:s(G,{rows:u,label:`linked apps`,isLoading:r.isLoading,loadError:r.isError?r.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:`Revoke`,icon:d,isAvailable:e=>e.status===`active`,onRun:e=>void f(e),busyId:m,disabled:l.isPending}})})}e();var pt={one:`session`,many:`sessions`};function mt(){let e=V(),t=B.useUtils(),r=q(),i=B.auth.listSessions.useQuery(),[a,c]=o(null),l=()=>void t.auth.listSessions.invalidate(),u=B.auth.revokeSessions.useMutation({onSuccess:l,onError:e=>c(`Sign out failed: ${e.message}`)}),d=je(`login-session`,pt,l),f=n(()=>(i.data??[]).map(e=>Le(e,r,{client:e=>Ee(e).label,method:Ie})),[i.data,r]),p=async t=>{await e({title:`Sign out this session`,message:`${t.ownerName} on ${t.name} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(c(null),u.mutate({id:t.id}))};return s(W,{notice:K(a,d.outcome),onDismissNotice:()=>{c(null),d.dismiss()},id:`login-sessions`,title:`Login sessions`,icon:Te,description:`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`,children:s(G,{rows:f,label:`sessions`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:`Sign out`,icon:Qe,isAvailable:e=>e.status===`active`,onRun:e=>void p(e),busyId:u.isPending&&u.variables!==void 0&&`id`in u.variables?u.variables.id:null,disabled:u.isPending||d.busy},bulk:{revoke:d,noun:pt,isSelectable:e=>e.status===`active`}})})}e();function ht({users:e,onClose:n,onSubmit:r,submitting:i}){let{user:a}=J(),c=a?.isAdmin===!0?null:a?.scopes??[],[l,u]=o(e[0]?.id??``),[d,f]=o(``),[p,m]=o([{type:`capability`,target:``,access:[`view`,`create`]}]),[g,_]=o(``),y=j(p),x=l!==``&&d.trim().length>0&&p.length>0&&y===null&&!i;return s(U,{open:!0,onOpenChange:e=>!e&&n(),children:t(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(b,{children:s(v,{children:`Create scoped token`})}),t(F,{className:`space-y-3`,children:[t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`scoped-token-user`,children:`On behalf of user`}),s(S,{id:`scoped-token-user`,value:l,onChange:e=>u(e.target.value),options:e.map(e=>({value:e.id,label:e.username}))})]}),t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`scoped-token-name`,children:`Name`}),s(w,{id:`scoped-token-name`,value:d,onChange:e=>f(e.target.value),placeholder:`cloudflare-tunnel-route`})]}),t(`div`,{className:`space-y-1`,children:[s(z,{children:`Scopes`}),s(O,{value:p,onChange:m,clampToParent:c}),y&&s(`p`,{className:`text-[10px] text-danger`,children:y}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Each scope picks a (cap or addon) target + one or more access flavours. The token can access ONLY what's listed.`})]}),t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`scoped-token-days`,children:`Expires in (days)`}),s(w,{id:`scoped-token-days`,type:`number`,min:1,value:g,onChange:e=>_(e.target.value),placeholder:`30`}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave blank for non-expiring.`})]})]}),t(I,{children:[s(T,{type:`button`,variant:`outline`,size:`sm`,onClick:n,children:`Cancel`}),t(T,{type:`button`,variant:`primary`,size:`sm`,onClick:()=>{let e=parseInt(g,10),t=Number.isFinite(e)&&e>0?Date.now()+e*864e5:void 0;r({userId:l,name:d.trim(),scopes:p,expiresAt:t})},disabled:!x,children:[i?s(L,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}):s(D,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`Issue token`]})]})]})})}function gt({token:e,label:n,onClose:r}){return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`md`,scroll:`body`,children:[s(b,{children:s(v,{children:`Token: ${n}`})}),t(F,{className:`space-y-3`,children:[s(`div`,{className:`rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning`,children:`Copy this token now. Once you close this dialog the secret cannot be displayed again.`}),s(`div`,{className:`select-all break-all rounded-md border border-border bg-background p-2 font-mono text-[11px] text-foreground`,children:e})]}),t(I,{children:[s(A,{value:e,label:`Copy`,srLabel:`token`}),s(T,{type:`button`,variant:`primary`,size:`sm`,onClick:r,children:`Done`})]})]})})}e();function _t(e){return e.type===`device`?`device:[${ce(e.selector)}]`:`${e.type}:${e.target??``}`}function vt(){let e=V(),r=a(),i=q(),{data:c,isLoading:l}=_(),u=n(()=>c??[],[c]),f=B.useQueries(e=>u.map(t=>e.userManagement.listScopedTokens({userId:t.id}))),[p,m]=o(null),[h,g]=o(!1),[v,y]=o(null),b=()=>void r.invalidateQueries({queryKey:[[`userManagement`,`listScopedTokens`]]}),x=Se({onSuccess:({token:e,record:t})=>{b(),g(!1),y({token:e,label:t.name})},onError:e=>m(`Create failed: ${e.message}`)}),S=pe({onSuccess:b,onError:e=>m(`Revoke failed: ${e.message}`)}),C=Date.now(),w=u.flatMap((e,t)=>(f[t]?.data??[]).map(t=>Pe(t,e.id,i,t.scopes.map(_t).join(`, `),C))),E=f.find(e=>e.isError)?.error?.message??null,ee=async t=>{await e({title:`Revoke "${t.name}"?`,message:`${t.ownerName}'s scoped token stops working on its next use. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(m(null),S.mutate({id:t.id}))};return t(W,{notice:K(p),onDismissNotice:()=>{m(null)},id:`scoped-tokens`,title:`Scoped tokens`,icon:be,description:`Tokens issued on behalf of a user for one narrow surface — an addon, an integration, a capability or some devices. Every token must be scoped, so revoking one has a predictable blast radius.`,actions:t(T,{type:`button`,variant:`primary`,size:`sm`,onClick:()=>g(!0),disabled:u.length===0,title:u.length===0?`Create a user first`:`Issue a scoped token`,children:[s(D,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`New token`]}),children:[s(G,{rows:w,label:`scoped tokens`,isLoading:l||f.some(e=>e.isLoading),loadError:E,emptyText:`No scoped tokens.`,action:{label:`Revoke`,icon:d,isAvailable:()=>!0,onRun:e=>void ee(e),busyId:S.isPending?S.variables?.id??null:null,disabled:S.isPending}}),h&&s(ht,{users:u.map(e=>({id:e.id,username:e.username})),onClose:()=>g(!1),onSubmit:e=>x.mutate({userId:e.userId,name:e.name,scopes:e.scopes,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}}),submitting:x.isPending}),v!==null&&s(gt,{token:v.token,label:v.label,onClose:()=>y(null)})]})}e();var yt={one:`admin token`,many:`admin tokens`},bt=7,xt=90,St=80;function Ct(e){let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=xt?t:null}function wt(){let{user:e}=J();return e?.isAdmin?s(Tt,{}):null}function Tt(){let e=V(),r=B.useUtils(),i=B.auth.listAdminTokens.useQuery(),a=q(),{requestProof:c,dialog:l}=Me(`Creating an admin token`),[u,f]=o(``),[p,m]=o(String(bt)),[h,g]=o(null),[_,v]=o(!1),[y,b]=o(null),x=()=>{r.auth.listAdminTokens.invalidate(),r.auth.listAuthAudit.invalidate()},S=B.auth.createAdminToken.useMutation({onSuccess:({token:e,record:t})=>{x(),f(``),m(String(bt)),b({token:e,label:t.name})},onError:e=>g(`Create failed: ${e.message}`)}),C=B.auth.revokeAdminToken.useMutation({onSuccess:x,onError:e=>g(`Revoke failed: ${e.message}`)}),E=je(`admin-token`,yt,x),D=Date.now(),ee=n(()=>(i.data??[]).map(e=>Oe(e,a,D)),[i.data,a]),O=u.trim(),k=Ct(p),te=O.length>0&&O.length<=St&&k!==null&&!S.isPending&&!_,A=async()=>{if(!te||k===null)return;g(null),v(!0);let e=await c();v(!1),e!==null&&S.mutate({name:O,expiresInDays:k,reauthToken:e})},j=async t=>{await e({title:`Revoke admin token "${t.name}"?`,message:`Every script using it loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(g(null),C.mutate({id:t.id}))};return t(`div`,{"data-testid":`admin-tokens`,children:[l,t(W,{id:`admin-tokens`,title:`Admin tokens`,icon:N,tone:`danger`,notice:K(h,E.outcome),onDismissNotice:()=>{g(null),E.dismiss()},description:t(`div`,{className:`space-y-1`,children:[t(`p`,{children:[`An admin token acts as a `,s(`strong`,{children:`full administrator`}),` for scripts, e.g.`,` `,s(`code`,{className:`font-mono`,children:`node scripts/hub/hub.mjs --token-file <file> …`}),`. Anyone holding it can do anything an admin can.`]}),s(`p`,{children:`It expires in at most 90 days and every use is audited. Creating one asks you to confirm it is you.`})]}),children:[t(`form`,{className:`grid grid-cols-1 items-end gap-2 sm:grid-cols-[1fr_120px_auto]`,onSubmit:e=>{e.preventDefault(),A()},children:[t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`admin-token-name`,children:`Token name`}),s(w,{id:`admin-token-name`,value:u,maxLength:St,onChange:e=>f(e.target.value),placeholder:`nightly-backup`})]}),t(`div`,{className:`space-y-1`,children:[s(z,{htmlFor:`admin-token-days`,children:`Expires in (days)`}),s(w,{id:`admin-token-days`,type:`number`,min:1,max:xt,value:p,onChange:e=>m(e.target.value),state:k===null?`error`:`default`})]}),t(T,{type:`submit`,variant:`danger`,size:`sm`,disabled:!te,children:[S.isPending||_?s(L,{className:`h-3.5 w-3.5 animate-spin`}):s(N,{className:`h-3.5 w-3.5`}),`Create admin token`]})]}),k===null&&t(`div`,{className:`text-[11px] text-danger`,children:[`Expiry must be a whole number of days, 1 to `,xt,`.`]}),s(G,{rows:ee,label:`admin tokens`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No admin tokens.`,action:{label:`Revoke`,icon:d,isAvailable:e=>e.status===`active`,onRun:e=>void j(e),busyId:C.isPending?C.variables?.id??null:null,disabled:C.isPending||E.busy},bulk:{revoke:E,noun:yt,isSelectable:e=>e.status===`active`}})]}),y&&s(gt,{token:y.token,label:y.label,onClose:()=>b(null)})]})}var Et={"share-link":`share links`,"admin-token":`admin tokens`,"login-session":`login sessions`};function Y(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Dt(e,t){let n=Y(e,`tokenId`);return Y(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function X(e){return e.filter(e=>e!==null)}function Ot(e){let t=Y(e,`prefix`);return t===null?null:`Prefix ${t}…`}function kt(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:`Admin token "${Dt(n,t)}" created`,details:X([Ot(n),typeof e==`number`?`Expires ${Re(e)}`:null])}}case`admin-token-used`:{let e=Y(n,`path`);return{title:`Admin token "${Dt(n,t)}" used`,details:X([Ot(n),e===null?null:`Call ${e}`])}}case`admin-token-revoked`:return{title:`Admin token "${Dt(n,t)}" revoked`,details:X([Ot(n)])};case`credentials-revoked`:{let e=Y(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=Et[e]??`${e}s`;return{title:`${typeof t==`number`?String(t):`?`} ${i} revoked in bulk`,details:X([typeof r==`number`&&r>0?`${String(r)} skipped`:null,Y(n,`ids`)===null?null:`Ids ${Y(n,`ids`)??``}`])}}case`second-factor-skipped`:{let e=Y(n,`method`),t=Y(n,`factors`);return{title:`Second factor skipped on a trusted network`,details:X([e===null?null:`Signed in with ${Ie(e)}`,t===null?null:`Skipped: ${t.split(`,`).join(`, `)}`])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}e();var At=100;function jt(){let{user:e}=J();return e?.isAdmin?s(Nt,{}):null}function Mt(){let{data:e}=_(),{data:t}=B.auth.listAdminTokens.useQuery();return n(()=>{let n=new Map;for(let t of e??[])n.set(t.id,t.username);let r=new Map;for(let e of t??[])r.set(e.id,e.name);return{userNameById:n,tokenNameById:r}},[e,t])}function Nt(){let e=B.auth.listAuthAudit.useQuery({limit:At}),{userNameById:n,tokenNameById:r}=Mt(),i=e.data??[];return t(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[t(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[s(se,{className:`h-3.5 w-3.5 text-foreground-subtle`}),s(`div`,{className:`text-xs font-semibold text-foreground`,children:`Authentication audit`}),t(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[`Latest `,At,`, newest first`]})]}),s(`div`,{className:`p-4`,children:e.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(L,{className:`h-3.5 w-3.5 animate-spin`}),`Loading audit trail…`]}):e.isError?t(`div`,{className:`text-[11px] text-danger`,children:[`Could not load the audit trail: `,e.error?.message??`Request failed`]}):i.length===0?s(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center`,children:`No authentication events recorded yet.`}):s(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:i.map(e=>s(Pt,{record:e,userName:e.userId===void 0?null:n.get(e.userId)??e.userId,tokenNameById:r},e.id))})})]})}function Pt({record:e,userName:n,tokenNameById:r}){let i=kt(e,r);return t(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[t(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[s(`span`,{className:`font-medium text-foreground`,children:i.title}),s(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Re(e.at)})]}),t(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[n!==null&&s(`span`,{className:`text-foreground`,children:n}),e.ip!==void 0&&s(`span`,{className:`font-mono`,children:e.ip}),i.details.map(e=>s(`span`,{className:`font-mono`,children:e},e))]})]})}var Z={loginSessions:`login-sessions`,linkedApps:`linked-apps`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,legacyApiKeys:`legacy-api-keys`,externalIdentities:`external-identities`,audit:`auth-audit`},Ft={state:`ok`,stateLabel:`available`,showState:!1};function Q(e,t,n,r){return{id:e,name:t,fallbackIcon:n,...Ft,render:r}}function It(){let e=ye(),t=(e.data??[]).length>0;return s(rt,{icon:ct,title:`Tokens & sessions`,subtitle:`Every credential this hub honours — who holds it, what it can reach, when it was last used and when it expires. Pick a kind; revoke one, or select several and revoke them after typing the count.`,groups:[{id:`sessions`,label:`Sessions`,entries:[Q(Z.loginSessions,`Login sessions`,Te,()=>s(mt,{})),Q(Z.linkedApps,`Linked apps`,H,()=>s(ft,{}))]},{id:`tokens`,label:`Tokens`,entries:[Q(Z.scopedTokens,`Scoped tokens`,be,()=>s(vt,{})),Q(Z.adminTokens,`Admin tokens`,N,()=>s(wt,{})),Q(Z.shareLinks,`Share links`,Ce,()=>s(Fe,{})),...t?[Q(Z.legacyApiKeys,`Legacy API keys`,we,()=>s(ut,{}))]:[]]},{id:`identity`,label:`Identity`,entries:[Q(Z.externalIdentities,`Sign-in links`,Je,()=>s(lt,{})),Q(Z.audit,`Audit`,se,()=>s(jt,{}))]}],isLoading:e.isLoading,emptyTitle:`No credential kinds`,emptyDescription:`This hub offers no credential kinds.`})}e();var Lt=3e4,Rt=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],$={title:`Authentication`,subtitle:`Login providers (local password, OIDC, SAML) and second-factor providers (passkeys / WebAuthn). They run in parallel — enable or disable each independently; disabling one only removes that method, local password login is unaffected.`,emptyTitle:`No authentication providers registered`,emptyDescription:`Local auth should always be available — if this list is empty the local-auth builtin failed to register. Check the Addons page for load errors.`,installLabel:`Add provider`};function zt(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:ct,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`Scoped tokens, admin tokens and sessions are managed from Identity → Tokens & sessions.`],setupSteps:[`A fresh hub has one account, admin / changeme — the first sign-in asks for a new password. Add users from Users → New user.`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:Xe,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`Explicit linking only: an IdP account signs in only the CamStack user who linked it from their profile (My access → Linked sign-in accounts). No auto-created users, no email matching.`,`The linked user’s role, scopes and two-factor authentication apply.`],setupSteps:[`Register a web app at your IdP and copy the client_id + client_secret.`,"Set the redirect URI to `https://<this-hub>/addon/<addon-id>/callback`.",`Paste issuer + credentials in the Settings panel below — saves on every change.`,`Each user then links their IdP account from My access → Linked sign-in accounts.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:Xe,bullets:[`Heavier handshake than OIDC — exchange metadata XML with your IdP.`,`Group → role mapping via SAML assertions.`]}:e.startsWith(`auth-webauthn`)||e.startsWith(`auth-passkey`)?{headline:`Passkeys / WebAuthn — passwordless second factor.`,icon:R,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)?{headline:`TOTP — second factor.`,icon:R,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:D,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Bt(){let e=g({capName:Rt[0].capName},{refetchInterval:Lt}),t=g({capName:Rt[1].capName},{refetchInterval:Lt}),r=ie(void 0,{refetchInterval:Lt}),i=n(()=>ot(r.data??[]),[r.data]),a=n(()=>{let n=[],r=[e.data??[],t.data??[]];for(let[e,t]of Rt.entries())for(let a of r[e]??[])n.push({addonId:a.addonId,displayName:i.get(a.addonId)??a.addonId,isActive:a.isActive,capName:t.capName,stageBadge:t.stageBadge});return n},[e.data,t.data,i]),o=[{id:`authentication`,label:`Authentication providers`,install:{capability:Rt[0].capName,label:$.installLabel},entries:a.map(e=>({id:e.addonId,name:e.displayName,fallbackIcon:D,...at(e.isActive),render:()=>s(it,{addonId:e.addonId,displayName:e.displayName,capName:e.capName,isActive:e.isActive,badges:e.stageBadge===null?null:s(ve,{variant:`info`,className:nt,children:e.stageBadge}),panels:[{id:`about`,title:`About`,icon:zt(e.addonId).icon,content:s(Vt,{addonId:e.addonId})}]})}))}];return s(rt,{icon:D,title:$.title,subtitle:$.subtitle,groups:o,isLoading:e.isLoading||t.isLoading,emptyTitle:$.emptyTitle,emptyDescription:$.emptyDescription})}function Vt({addonId:e}){let n=zt(e),r=n.icon;return t(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,children:[t(`div`,{className:`flex items-start gap-2.5`,children:[s(r,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),s(`div`,{className:`text-xs text-foreground font-medium`,children:n.headline})]}),s(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:n.bullets.map((e,t)=>s(`li`,{children:e},t))}),n.setupSteps&&n.setupSteps.length>0&&t(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[t(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[s(st,{className:`h-3 w-3`}),`Setup steps`]}),s(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:n.setupSteps.map((e,t)=>s(`li`,{children:e},t))})]}),e===`local-auth`&&t(`div`,{className:`rounded-md border border-info/30 bg-info/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[s(P,{className:`h-3.5 w-3.5 mt-0.5 text-info shrink-0`}),t(`span`,{children:[`TOTP / 2FA is self-service: each user enrols from their own profile page —`,` `,s(qe,{to:`/system/my-access`,className:`underline text-primary`,children:`My access`}),` `,`→ “Two-factor authentication” → Enable 2FA. Admins can only remove a user’s active enrollment (lost device) from the`,` `,s(qe,{to:`/system/identity?tab=users`,className:`underline text-primary`,children:`Users`}),` `,`page via Actions → “Remove 2FA”.`]})]})]})}function Ht({userId:e,username:n,onClose:r}){let i=V(),a=B.useUtils(),o=ae({userId:e}),c=B.auth.listLoginMethods.useQuery(),l=k({onSuccess:()=>void a.userManagement.listExternalIdentities.invalidate()}),u=new Map((c.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),d=o.data??[],f=async(t,r)=>{await i({title:`Remove sign-in link`,message:`"${n}" will no longer be able to sign in with this ${r} account.`,confirmLabel:`Remove`,variant:`danger`})&&l.mutate({userId:e,provider:t.provider,subject:t.subject})};return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[s(b,{children:t(v,{className:`flex items-center gap-2`,children:[s(H,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Linked sign-in accounts`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),s(F,{className:`space-y-3`,children:o.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(L,{className:`h-3.5 w-3.5 animate-spin`}),`Loading…`]}):d.length===0?s(`p`,{className:`text-xs text-foreground-subtle`,children:`No linked accounts. Only the user can link one, from their own profile page.`}):s(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:d.map(e=>{let n=u.get(e.provider),r=n??e.provider;return t(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[t(`div`,{className:`flex-1 min-w-0`,children:[t(`div`,{className:`font-medium text-foreground truncate`,children:[r,n===void 0&&s(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:`provider unavailable`})]}),t(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[e.label??e.subject,` ·`,` `,new Date(e.linkedAt).toLocaleDateString()]})]}),t(`button`,{onClick:()=>void f(e,r),disabled:l.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[s(De,{className:`h-3 w-3`}),`Remove`]})]},`${e.provider}|${e.subject}`)})})}),s(I,{children:s(T,{onClick:r,variant:`secondary`,children:`Close`})})]})})}function Ut({userId:e,username:n,onClose:r}){let o=a(),c=V(),l=m({userId:e}),u=l.data,d=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),f=re({onSuccess:()=>{d(),r()}}),p=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(b,{children:t(v,{className:`flex items-center gap-2`,children:[s(R,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Two-factor authentication`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),t(F,{className:`space-y-4`,children:[p===`loading`&&t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(L,{className:`h-3.5 w-3.5 animate-spin`}),`Checking status…`]}),p===`not_enrolled`&&t(`div`,{className:`rounded-md border border-border bg-surface-hover/30 px-3 py-2.5 flex items-start gap-2.5 text-xs text-foreground-subtle`,children:[s(P,{className:`h-4 w-4 mt-0.5 shrink-0`}),t(`div`,{children:[s(`div`,{className:`font-medium text-foreground`,children:`2FA not enrolled`}),s(`p`,{className:`mt-0.5`,children:`Only the user themselves can enable 2FA, from their own profile page.`})]})]}),p===`enrolled`&&u&&t(i,{children:[t(`div`,{className:`rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5 flex items-start gap-2.5`,children:[s(M,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),t(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[s(`div`,{className:`font-medium`,children:`2FA is active`}),t(`div`,{className:`text-foreground-subtle`,children:[`Enrolled on`,` `,u.confirmedAt?new Date(u.confirmedAt).toLocaleString():`—`]})]})]}),s(`div`,{className:`text-[11px] text-foreground-subtle`,children:`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`}),t(`div`,{className:`flex justify-end gap-2`,children:[s(T,{onClick:r,variant:`secondary`,children:`Close`}),t(`button`,{onClick:async()=>{await c({title:`Remove 2FA`,message:`Remove two-factor authentication for "${n}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,confirmLabel:`Remove`,variant:`danger`})&&f.mutate({userId:e})},disabled:f.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[f.isPending?s(L,{className:`h-3 w-3 animate-spin`}):s(fe,{className:`h-3 w-3`}),`Remove 2FA`]})]})]})]})]})})}e();function Wt({userId:e,username:n,onClose:r}){let{user:i,logout:a}=J(),c=i?.id===e,l=V(),u=B.useUtils(),d=B.auth.listSessions.useQuery({userId:e}),[f,p]=o(null),m=B.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(c&&`userId`in t){a();return}u.auth.listSessions.invalidate()},onError:e=>p(`Sign out failed: ${e.message}`)}),g=async e=>{await l({title:`Sign out this session`,message:`"${n}" on ${Ee(e.client).label} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(p(null),m.mutate({id:e.id}))},_=async()=>{await l({title:`Sign out everywhere`,message:c?`Every session of your own account ends, this browser included: you will be signed out here too.`:`Every session of "${n}" ends at once; each device has to sign in again.`,confirmLabel:`Sign out everywhere`,variant:`danger`})&&(p(null),m.mutate({userId:e}))},y=m.isPending&&m.variables!==void 0&&`id`in m.variables?m.variables.id:null;return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[s(b,{children:t(v,{className:`flex items-center gap-2`,children:[s(Te,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Active sessions`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),t(F,{className:`space-y-3`,children:[f!==null&&s(`div`,{className:`text-[11px] text-danger`,children:f}),s(ze,{sessions:d.data??[],isLoading:d.isLoading,loadError:d.isError?d.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void g(e),revokingId:y})]}),t(I,{className:`justify-between`,children:[t(`button`,{onClick:()=>void _(),disabled:m.isPending||(d.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[m.isPending&&y===null?s(L,{className:`h-3 w-3 animate-spin`}):s(Qe,{className:`h-3 w-3`}),`Sign out everywhere`]}),s(T,{onClick:r,variant:`secondary`,children:`Close`})]})]})})}function Gt({icon:e,label:n,count:r,all:i,total:a}){return t(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[s(e,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(`span`,{className:`min-w-0 flex-1 text-foreground-subtle`,children:n}),s(`span`,{className:r===0?`text-foreground-subtle`:`font-medium text-foreground`,children:r===0?`none`:i?`all ${a}`:`${r} of ${a}`})]})}function Kt({scopes:e,isAdmin:n,invalidReason:a}){let o=c(),l=r({queryKey:[`auth`,`previewScope`,e,n],enabled:a===null,queryFn:()=>o.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:n})}),{data:u}=he({projection:`slim`}),f=u?.length??0;if(a!==null)return s(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:t(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,children:[s(N,{className:`h-3 w-3 shrink-0`}),a]})});if(l.isLoading)return t(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-surface p-3 text-[11px] text-foreground-subtle`,children:[s(L,{className:`h-3 w-3 animate-spin`}),`Resolving…`]});if(l.isError||!l.data)return s(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:s(`p`,{className:`text-[11px] text-danger`,children:`Could not resolve this grant set. Saving is still allowed — the server enforces the same rules either way.`})});let p=l.data;return s(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:p.isAdmin?t(`p`,{className:`text-[11px] text-foreground`,children:[s(`span`,{className:`font-medium`,children:`Administrator`}),` — unrestricted. Grants are ignored for an admin.`]}):t(i,{children:[s(Gt,{icon:x,label:`Devices they can see`,count:p.device.view.deviceCount,all:p.device.view.all,total:f}),s(Gt,{icon:de,label:`Devices they can operate`,count:p.device.create.deviceCount,all:p.device.create.all,total:f}),s(Gt,{icon:d,label:`Devices they can delete`,count:p.device.delete.deviceCount,all:p.device.delete.all,total:f}),t(`div`,{className:`border-t border-border pt-2 text-[10px] text-foreground-subtle`,children:[`System access: `,p.system.length===0?`none`:p.system.join(`, `),p.capabilities.length>0&&t(i,{children:[` · Extra capabilities: `,p.capabilities.map(e=>e.name).join(`, `)]}),p.addons.length>0&&t(i,{children:[` · Addons: `,p.addons.map(e=>e.name).join(`, `)]})]}),p.device.view.deviceCount===0&&s(`p`,{className:`text-[10px] text-warning`,children:`This user will not be able to see any device.`})]})})}e();function qt(e){let t=Ue(e);return t===null?{mode:e.length===0?`role`:`advanced`,roleId:null,selector:{kind:`all`},includeLinked:!0,advancedScopes:e}:{mode:`role`,roleId:t.roleId,selector:t.selector,includeLinked:t.includeLinked,advancedScopes:e}}function Jt(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:Ve({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function Yt({user:e,onClose:r,onSubmit:a,submitting:c,callerScopes:d}){let f=n(()=>qt(e.scopes??[]),[e.scopes]),[p,m]=o(f),[g,_]=o(f.mode===`advanced`),y=n(()=>Jt(p),[p]),x=!e.isAdmin&&p.mode===`role`&&p.roleId===null,S=n(()=>e.isAdmin?null:p.mode===`role`&&p.roleId===null?`Pick what this user can do to see the result.`:j(y),[e.isAdmin,p.mode,p.roleId,y]),C=e=>m({...p,...e});return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(h,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[t(b,{children:[t(v,{children:[`Access — `,e.username]}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.isAdmin?`This user is an administrator — they can do everything, and the settings below are ignored.`:`Choose what they can do, then which devices it applies to.`})]}),t(F,{className:`space-y-4`,children:[x&&t(`div`,{className:`flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 p-3`,children:[s(N,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),t(`p`,{className:`text-[11px] text-foreground`,children:[s(`span`,{className:`font-medium`,children:`No access.`}),` `,t(`span`,{className:`text-foreground-subtle`,children:[e.username,` cannot see or do anything yet. Configure it below.`]})]})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`1 · What can they do`}),s(`div`,{className:`space-y-1.5`,children:He.map(e=>{let n=p.mode===`role`&&p.roleId===e.id;return t(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 transition-colors ${n?`border-primary bg-primary/5`:`border-border hover:bg-foreground-subtle/5`}`,children:[s(`input`,{type:`radio`,name:`access-role`,checked:n,onChange:()=>C({mode:`role`,roleId:e.id}),className:`mt-0.5 border-border focus:ring-primary`}),t(`span`,{className:`min-w-0`,children:[s(`span`,{className:`block text-[12px] font-medium text-foreground`,children:e.label}),s(`span`,{className:`mt-0.5 block text-[10px] text-foreground-subtle`,children:e.description})]})]},e.id)})}),t(`button`,{type:`button`,onClick:()=>{if(!g){m({...p,mode:`advanced`,advancedScopes:y}),_(!0);return}_(!1),m(qt(p.advancedScopes))},className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] text-foreground-subtle transition-colors hover:bg-foreground-subtle/10 hover:text-foreground`,children:[s(g?l:u,{className:`h-3 w-3`}),`Advanced — edit raw grants`]}),g&&t(`div`,{className:`rounded-lg border border-border p-2`,children:[s(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`One row per grant. Anything expressible here overrides the three roles above; close this section to go back to them.`}),s(O,{value:p.advancedScopes,onChange:e=>C({mode:`advanced`,advancedScopes:e}),clampToParent:d,emptyHint:t(i,{children:[`No grants.`,` `,s(`span`,{className:`font-medium text-foreground`,children:e.username}),` cannot call any protected endpoint until one is added.`]})})]})]}),p.mode===`role`&&t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`2 · On which devices`}),s(oe,{value:p.selector,onChange:e=>C({selector:e}),includeLinked:p.includeLinked,onIncludeLinkedChange:e=>C({includeLinked:e}),clampToDeviceIds:null})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:p.mode===`role`?`3 · Result`:`2 · Result`}),s(Kt,{scopes:y,isAdmin:e.isAdmin,invalidReason:S})]})]}),t(I,{children:[s(T,{variant:`outline`,size:`sm`,onClick:r,children:`Cancel`}),s(T,{size:`sm`,onClick:()=>a([...y]),disabled:c||S!==null,children:c?s(L,{className:`h-3 w-3 animate-spin`}):`Save access`})]})]})})}e();var Xt=8;function Zt(){let e=a(),{user:n}=J(),[r,i]=o(!1),[c,l]=o(``),[u,f]=o(``),[p,m]=o(!1),[h,g]=o(null),{data:v,isLoading:y,isError:b}=_(),x=V(),S=E(),w=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),T=ue({onSuccess:()=>{w(),i(!1),l(``),f(``),m(!1),g(null)},onError:e=>{g(e instanceof Error?e.message:`Failed to create user`)}}),O=xe({onSuccess:w}),k=ne({onSuccess:w}),A=te({onSuccess:w}),j=ee({onSuccess:()=>{w(),N(null)}}),[M,N]=o(null),[P,re]=o(null),[F,ie]=o(null),[ae,I]=o(null),oe=v??[];async function se(e){await x({title:`Delete user`,message:`Permanently delete user "${e.username}"? This cannot be undone — any active sessions will be revoked on next request.`,confirmLabel:`Delete`,variant:`danger`})&&O.mutate({id:e.id})}async function ce(e){let t=await S({title:`Reset password`,message:`Set a new password for "${e.username}".`,label:`New password`,inputType:`password`,placeholder:`At least 8 characters`,confirmLabel:`Continue`,validate:e=>e.length<Xt?`Password must be at least ${String(Xt)} characters.`:null});t===null||t.length===0||await x({title:`Reset password`,message:`Reset the password for "${e.username}"? They will need to use the new password on their next login.`,confirmLabel:`Reset`})&&A.mutate({id:e.id,newPassword:t})}function de(e,t){t!==e.isAdmin&&k.mutate({id:e.id,isAdmin:t})}function pe(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}return t(et,{children:[s(`div`,{className:`flex items-center justify-end`,children:t(`button`,{onClick:()=>i(!0),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm hover:bg-primary/90`,children:[s(_e,{className:`h-3.5 w-3.5`}),`Create User`]})}),r&&t(`div`,{className:`rounded-lg border border-border bg-surface p-4 space-y-3`,children:[t(`div`,{className:`flex items-center justify-between`,children:[s(`span`,{className:`text-xs font-medium text-foreground`,children:`New User`}),s(`button`,{onClick:()=>i(!1),className:`text-foreground-subtle hover:text-foreground`,children:s(fe,{className:`h-4 w-4`})})]}),t(`div`,{className:`grid grid-cols-3 gap-3`,children:[t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Username`}),s(`input`,{type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`john`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Password`}),s(`input`,{type:`password`,value:u,onChange:e=>f(e.target.value),placeholder:`••••••••`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Admin`}),t(`label`,{className:`flex items-center gap-2 rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked),className:`rounded border-border focus:ring-primary`}),s(`span`,{className:`text-foreground-subtle`,children:`Unrestricted access`})]})]})]}),h&&s(`p`,{className:`text-[10px] text-danger`,children:h}),t(`div`,{className:`flex justify-end gap-2`,children:[s(`button`,{onClick:()=>i(!1),className:`rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground`,children:`Cancel`}),s(`button`,{onClick:()=>T.mutate({username:c,password:u,isAdmin:p}),disabled:T.isPending||!c||!u,className:`rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:T.isPending?`Creating...`:`Create`})]})]}),y&&s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Loading...`}),b&&s(`div`,{className:`text-xs text-danger`,children:`Failed to load`}),!y&&!b&&oe.length===0&&s(`div`,{className:`text-xs text-foreground-subtle`,children:`No data`}),(()=>{let e=e=>O.isPending&&O.variables?.id===e.id||k.isPending&&k.variables?.id===e.id||A.isPending&&A.variables?.id===e.id;return s(C,{columns:[{key:`username`,header:`Username`,render:e=>e.username},{key:`isAdmin`,header:`Admin`,render:n=>t(`label`,{className:`inline-flex items-center gap-1.5 text-xs cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:n.isAdmin,onChange:e=>de(n,e.target.checked),disabled:e(n),className:`rounded border-border focus:ring-primary disabled:opacity-50`}),s(`span`,{className:n.isAdmin?`text-primary font-medium`:`text-foreground-subtle`,children:n.isAdmin?`Admin`:`Regular`})]})},{key:`scopes`,header:`Access`,render:e=>e.isAdmin?s(`span`,{className:`text-[10px] italic text-foreground-subtle`,children:`everything (admin)`}):t(`button`,{onClick:()=>N(e),className:`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] hover:bg-foreground-subtle/10`,title:`Configure access`,children:[s(D,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(Qt,{scopes:e.scopes??[]})]})},{key:`createdAt`,header:`Created`,render:e=>s(`span`,{className:`text-foreground-subtle`,children:pe(e.createdAt)})},{key:`actions`,header:`Actions`,align:`right`,render:r=>{let i=e(r);return t(`div`,{className:`flex items-center justify-end gap-1`,children:[r.id!==n?.id&&r.totpEnabled&&t(`button`,{onClick:()=>re(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Remove two-factor authentication`,children:[s(R,{className:`h-3 w-3`}),`Remove 2FA`]}),t(`button`,{onClick:()=>ie(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Linked sign-in accounts`,children:[s(H,{className:`h-3 w-3`}),`Sign-in links`]}),t(`button`,{onClick:()=>I(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Active sessions`,children:[s(Te,{className:`h-3 w-3`}),`Sessions`]}),t(`button`,{onClick:()=>ce(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Reset password`,children:[s(le,{className:`h-3 w-3`}),`Reset password`]}),t(`button`,{onClick:()=>se(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Delete user`,children:[i?s(L,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Delete`]})]})}}],rows:oe,rowKey:e=>e.id,minWidthPx:560})})(),P&&s(Ut,{userId:P.id,username:P.username,onClose:()=>re(null)}),F&&s(Ht,{userId:F.id,username:F.username,onClose:()=>ie(null)}),ae&&s(Wt,{userId:ae.id,username:ae.username,onClose:()=>I(null)}),M&&s($t,{user:M,onClose:()=>N(null),onSubmit:e=>j.mutate({userId:M.id,scopes:e}),submitting:j.isPending})]})}function Qt({scopes:e}){if(e.length===0)return s(`span`,{className:`font-medium text-warning`,children:`No access`});let n=Ue(e);return n===null?t(`span`,{className:`text-foreground-subtle`,children:[`Custom · `,e.length,` grant`,e.length===1?``:`s`]}):t(`span`,{className:`text-foreground-subtle`,children:[s(`span`,{className:`font-medium text-foreground`,children:We(n.roleId).label}),` ·`,` `,ce(n.selector)]})}function $t(e){let{user:t}=J(),n=t?.isAdmin===!0;return s(Yt,{...e,callerScopes:n?null:t?.scopes??[]})}var en={"api-keys":Z.scopedTokens,"linked-sessions":Z.linkedApps};function tn(){let[e]=Ge(),t=en[e.get(`tab`)??``];return t===void 0?s(`div`,{className:`flex flex-col p-4`,children:s(tt,{tabs:[{id:`users`,label:`Users`,icon:ge,content:s(Zt,{})},{id:Ye.access.tab,label:`Tokens & sessions`,icon:be,content:s(It,{}),ownedParams:$e},{id:Ye.authentication.tab,label:`Authentication`,icon:D,content:s(Bt,{}),ownedParams:$e}]})}):s(Ke,{to:Ze(`access`,{integration:t}),replace:!0})}export{tn as IdentityPage};
|