livedesk 0.1.587 → 0.1.588

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "livedesk",
3
- "version": "0.1.587",
3
+ "version": "0.1.588",
4
4
  "livedeskClientVersion": "0.1.249",
5
5
  "buildFlavor": "production",
6
6
  "description": "LiveDesk Hub and client launcher",
@@ -4,7 +4,7 @@
4
4
  "short_name": "LiveDesk",
5
5
  "description": "Monitor and control your LiveDesk computers from your phone.",
6
6
  "lang": "en",
7
- "start_url": "/app?pwa=0.1.587",
7
+ "start_url": "/app?pwa=0.1.588",
8
8
  "scope": "/",
9
9
  "display": "standalone",
10
10
  "orientation": "any",
@@ -1,4 +1,4 @@
1
- import{j as r,M as Ug,w as Vg,D as un,r as Ua,g as El,i as zl,h as Be,c as su,a as au,n as Gg,b as yy,d as xy,e as Fl,f as Kg,k as Qg,l as Sy,m as yh,p as Cs,P as No,F as cl}from"./index-DYTiW4gg.js";import{a as o,m as Oo,k as sn,n as Va,B as Cy,P as Dl,X as kn,o as Uo,l as As,F as xh,p as Ms,q as Yg,s as ky,t as Sh,u as Ch,v as My,D as Vo,b as _n,w as Ay,x as Xg,y as Ny,z as Ry,g as is,c as fn,H as ql,I as Bo,J as Ul,K as qs,O as Jg,Q as Zg,U as ev,V as kh,Y as Py,Z as Ty,_ as Ba,W as iu,$ as Iy,a0 as jy,a1 as Oi,a2 as Bi,a3 as Ey,a4 as Qd,S as Ks,a5 as tv,a6 as nv,a7 as Fy,a8 as Dy,a9 as Ly,aa as Ap,ab as _y,N as Np,ac as rv,ad as $y,ae as Jn,af as Mh,C as Rp,ag as ou,ah as Go,ai as Ho,aj as sv,ak as Oy,al as av,am as By,an as iv,ao as Hy,ap as Yd,aq as Wy,ar as Xd,as as ov,at as zy,au as qy,av as Uy,aw as Vy,ax as cv,ay as Gy,az as Ah,aA as Ky,aB as Qy,aC as Yy,aD as lv,f as Fo,T as Ll,A as Xy,E as Jy,aE as Nh,aF as md,aG as Zy,aH as hd,aI as Rh,aJ as Ph,aK as ex,aL as uv,aM as tx,G as nx}from"./icons-DwJmccVC.js";import{c as rx}from"./supabase-C7qjtLN3.js";import{r as sx}from"./react-DOZUPHF8.js";const ax="https://otbyfkjxrkngvjziawki.supabase.co",ix="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",ox={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},fd=typeof window<"u"&&!!window.liveDesk,ht=rx(ax,ix,{auth:{autoRefreshToken:!fd,persistSession:!fd,storage:fd?ox:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),cx=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),lx={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const e={browserLanguage:navigator.language||"",platform:navigator.platform||"",online:navigator.onLine,timezone:typeof Intl>"u"?"":Intl.DateTimeFormat().resolvedOptions().timeZone||"",viewport:typeof window>"u"?void 0:{width:window.innerWidth,height:window.innerHeight},screen:typeof window>"u"?void 0:{width:window.screen.width,height:window.screen.height}};return Object.fromEntries(Object.entries(e).filter(([t,n])=>cx.has(t)&&n!==void 0))}};function ux(e,t="Support request failed."){if(e&&typeof e=="object"&&"message"in e){const n=String(e.message||"").trim();if(n)return n.replace(/^.*Support request failed:\s*/i,"")}return e instanceof Error?e.message:t}function dx(e=lx){return e.collect()}async function px(e,t="livedesk"){const{data:n,error:s}=await ht.from("app_admins").select("role").eq("user_id",e).limit(1);if(s)throw s;const a=n?.[0]?.role||"user";if(a!=="owner"){const{error:w}=await ht.rpc("register_product_access",{p_product_key:t,p_access_type:"free"});if(w)throw w}const[i,c,u]=await Promise.all([ht.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),ht.from("product_admins").select("product_id, role").eq("user_id",e),ht.from("user_products").select("product_id").eq("user_id",e).eq("is_active",!0)]);if(i.error)throw i.error;if(c.error)throw c.error;if(u.error)throw u.error;const d=i.data||[],p=(c.data||[]).map(w=>String(w.product_id)),h=(u.data||[]).map(w=>String(w.product_id)),m=a==="owner",g=m?d.map(w=>w.id):[...new Set([...p,...h])];return{products:d,access:{userId:e,globalRole:a,accessibleProductIds:g,managedProductIds:m?d.map(w=>w.id):p,canViewAllProducts:m,canViewAllPrivatePosts:m,canManageAllProducts:m,canCreateAnnouncements:m||p.length>0}}}async function mx(e=""){const{data:t,error:n}=await ht.rpc("search_support_posts",{p_query:e.trim()||null,p_limit:250});if(n)throw n;return t||[]}async function hx(e){const{data:t,error:n}=await ht.from("support_attachments").select("*").eq("post_id",e).order("created_at");if(n)throw n;const s=t||[];return Promise.all(s.map(async a=>{const i=await ht.storage.from("support-attachments").createSignedUrl(a.storage_path,3600);return{...a,signed_url:i.data?.signedUrl||void 0}}))}async function fx(){const{data:e,error:t}=await ht.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(t)throw t;return e||[]}async function gx(e){const{error:t}=await ht.rpc("mark_support_notification_read",{p_notification_id:e});if(t)throw t}async function Th(e){const{data:t,error:n}=await ht.from("support_comments").select("*").eq("post_id",e).order("created_at");if(n)throw n;return t||[]}async function vx(e){const{data:t,error:n}=await ht.from("support_votes").select("post_id").eq("user_id",e);if(n)throw n;return new Set((t||[]).map(s=>String(s.post_id)))}async function bx(e){const{data:t,error:n}=await ht.rpc("create_support_post",{p_product_id:e.productId,p_post_type:e.postType,p_title:e.title,p_body:e.body,p_visibility:e.visibility,p_app_version:e.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:e.includeEnvironment?dx():{}});if(n)throw n;const s=Array.isArray(t)?t[0]?.post_id:t?.post_id;if(!s)throw new Error("Support post was not created.");return String(s)}const wx=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function yx(e,t){if(!wx.has(t.type))throw new Error("This file type is not allowed.");if(t.size<=0||t.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const n=t.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,a=`${e}/${s}-${n}`,i=await ht.storage.from("support-attachments").upload(a,t,{contentType:t.type,upsert:!1});if(i.error)throw i.error;const{data:c,error:u}=await ht.rpc("add_support_attachment",{p_post_id:e,p_storage_path:a,p_file_name:n,p_mime_type:t.type,p_size_bytes:t.size});if(u)throw await ht.storage.from("support-attachments").remove([a]),u;const d=Array.isArray(c)?c[0]?.attachment_id:c?.attachment_id;if(!d)throw new Error("Attachment metadata was not created.");return String(d)}async function xx(e,t,n,s){const{error:a}=await ht.rpc("update_support_post",{p_post_id:e,p_title:t,p_body:n,p_visibility:s});if(a)throw a}async function Sx(e,t){const{error:n}=await ht.rpc("add_support_comment",{p_post_id:e,p_body:t});if(n)throw n}async function Cx(e){const{data:t,error:n}=await ht.rpc("toggle_support_vote",{p_post_id:e});if(n)throw n;const s=Array.isArray(t)?t[0]:t;return{voted:!!s?.voted,totalVotes:Number(s?.total_votes||0)}}async function kx(e,t){const{error:n}=await ht.rpc("change_support_post_status",{p_post_id:e,p_target_status:t});if(n)throw n}async function Mx(e){const{error:t}=await ht.rpc("set_support_post_hidden",{p_post_id:e,p_hidden:!0});if(t)throw t}async function Ax(e,t){const{error:n}=await ht.rpc("set_support_post_locked",{p_post_id:e,p_locked:t});if(n)throw n}async function Nx(e,t){const{error:n}=await ht.rpc("set_support_post_pinned",{p_post_id:e,p_pinned:t});if(n)throw n}async function Rx(e,t){const{error:n}=await ht.rpc("mark_support_duplicate",{p_post_id:e,p_duplicate_of_post_id:t});if(n)throw n}async function Px(e,t){const{error:n}=await ht.rpc("accept_support_answer",{p_post_id:e,p_comment_id:t});if(n)throw n}async function Tx(e,t=!0){const{error:n}=await ht.rpc("hide_support_comment",{p_comment_id:e,p_hidden:t});if(n)throw n}const Jd=[{id:"question",label:"Questions",shortLabel:"Question"},{id:"issue",label:"Issues",shortLabel:"Issue"},{id:"feature",label:"Feature Requests",shortLabel:"Feature"},{id:"announcement",label:"Announcements",shortLabel:"Announcement"}],Ix=[{id:"all",label:"All statuses"},{id:"needs-response",label:"Needs response"},{id:"open",label:"Open"},{id:"needs-info",label:"Needs more information"},{id:"in-progress",label:"In progress"},{id:"planned",label:"Planned"},{id:"released",label:"Released"},{id:"closed",label:"Closed"}],jx={question:["open","answered","resolved","closed"],issue:["open","needs-info","confirmed","in-progress","fixed","closed"],feature:["under-review","planned","in-progress","released","declined","closed"],announcement:["published","archived"]},Ex={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function gd(){if(typeof window>"u")return Ex;const e=new URLSearchParams(window.location.search),t=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],n=e.get("type")||t||"",s=n==="questions"||n==="question"?"question":n==="issues"||n==="issue"?"issue":n==="features"||n==="feature"?"feature":n==="announcements"||n==="announcement"?"announcement":"all",a=e.get("visibility"),i=e.get("sort");return{type:s,product:e.get("product")||"",status:e.get("status")||"all",visibility:a==="public"||a==="private"?a:"all",sort:i==="votes"||i==="newest"?i:"recent",query:e.get("q")||""}}function Fx(e){return e==="all"?"":e==="question"?"questions":e==="issue"?"issues":e==="feature"?"features":"announcements"}function Dx(e,t){const n={...e,...t},s=new URLSearchParams;n.product&&s.set("product",n.product),n.status!=="all"&&s.set("status",n.status),n.visibility!=="all"&&s.set("visibility",n.visibility),n.sort!=="recent"&&s.set("sort",n.sort),n.query&&s.set("q",n.query);const a=Fx(n.type),i=s.toString();return`/support${a?`/${a}`:""}${i?`?${i}`:""}`}function ll(e){const t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):e}function vd(e){return e.replaceAll("-"," ").replace(/\b\w/g,t=>t.toUpperCase())}function Ih(e){return e==="question"?Ay:e==="issue"?Xg:e==="feature"?Ny:Ry}function jh(e){return Jd.find(t=>t.id===e)?.shortLabel||e}function bd(e,t){return e.find(n=>n.id===t)?.name||"Product"}function Yn(e){const t=ux(e);return/relation .* does not exist|function .* does not exist|schema cache/i.test(t)?"Support Board database is not installed yet. Apply the latest Supabase migration first.":/not-authenticated|jwt/i.test(t)?"Sign in again to use Support.":/product-access-denied|product-not-found/i.test(t)?"You do not have access to this product.":t}function dv({session:e,currentProductKey:t="livedesk",appVersion:n="",onSignIn:s}){const[a,i]=o.useState(()=>gd()),[c,u]=o.useState(null),[d,p]=o.useState([]),[h,m]=o.useState([]),[g,w]=o.useState(""),[b,y]=o.useState([]),[k,A]=o.useState([]),[C,N]=o.useState([]),[E,I]=o.useState(()=>new Set),[F,M]=o.useState(!0),[$,q]=o.useState(""),[T,D]=o.useState(""),[H,K]=o.useState(!1),[z,W]=o.useState(!1),[ce,j]=o.useState(""),[ne,ue]=o.useState(()=>gd().query),[U,ge]=o.useState(!1),[re,we]=o.useState(!1),[Me,Pe]=o.useState(""),[Te,Ce]=o.useState(""),[Y,Ne]=o.useState("free"),[De,je]=o.useState(""),[Je,ee]=o.useState(""),[te,pe]=o.useState("admin"),[le,J]=o.useState(""),[xe,de]=o.useState(""),[Le,st]=o.useState(""),[P,Se]=o.useState(""),[Ee,ct]=o.useState(""),[$e,qe]=o.useState([]),[ze,oe]=o.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),me=o.useCallback(L=>{const We={...a,...L};i(We),typeof window<"u"&&window.history.pushState({},"",Dx(a,L))},[a]);o.useEffect(()=>{const L=()=>i(gd());return window.addEventListener("popstate",L),()=>window.removeEventListener("popstate",L)},[]);const be=o.useCallback(async()=>{const L=await mx(a.query);return m(L),e?.user.id&&I(await vx(e.user.id)),L},[a.query,e?.user.id]),Z=o.useCallback(async()=>{if(!e?.user.id){u(null),p([]),m([]),w(""),N([]),M(!1);return}M(!0),D("");try{const L=await px(e.user.id,t);u(L.access),p(L.products),await be(),N(await fx())}catch(L){D(Yn(L))}finally{M(!1)}},[t,be,e?.user.id]);o.useEffect(()=>{Z()},[Z]);const V=o.useMemo(()=>c?c.canViewAllProducts?d:d.filter(L=>c.accessibleProductIds.includes(L.id)):[],[c,d]),se=o.useMemo(()=>{const L=V.find(We=>We.product_key===a.product);return c?.canViewAllProducts&&!a.product||a.product==="all"&&c?.canViewAllProducts?"all":L?L.product_key:V.some(We=>We.product_key===t)?t:V[0]?.product_key||""},[c?.canViewAllProducts,V,t,a.product]),R=se==="all"?"":V.find(L=>L.product_key===se)?.id||"",ae=o.useMemo(()=>{const L=new Map(d.map(mt=>[mt.id,mt.product_key]));return[...h.filter(mt=>a.type!=="all"&&mt.post_type!==a.type||se!=="all"&&R&&mt.product_id!==R||a.status==="needs-response"&&!["open","needs-info"].includes(mt.status)||a.status!=="all"&&a.status!=="needs-response"&&mt.status!==a.status||a.visibility!=="all"&&mt.visibility!==a.visibility?!1:L.has(mt.product_id))].sort((mt,Ft)=>a.sort==="votes"?Ft.vote_count-mt.vote_count||Ft.updated_at.localeCompare(mt.updated_at):a.sort==="newest"?Ft.created_at.localeCompare(mt.created_at):Number(Ft.is_pinned)-Number(mt.is_pinned)||Ft.updated_at.localeCompare(mt.updated_at))},[h,d,a.sort,a.status,a.type,a.visibility,R,se]),ie=ae.find(L=>L.id===g)||ae[0]||null,_e=!!(ie&&c&&(c.canViewAllProducts||c.managedProductIds.includes(ie.product_id))),Oe=!!(ie&&e?.user.id===ie.author_id)||_e;o.useEffect(()=>{if(!ie){w(""),y([]),W(!1);return}ie.id!==g&&w(ie.id)},[ie,g]),o.useEffect(()=>{let L=!0;return g?(Th(g).then(We=>{L&&y(We)}).catch(We=>{L&&D(Yn(We))}),hx(g).then(We=>{L&&A(We)}).catch(We=>{L&&D(Yn(We))}),()=>{L=!1}):(y([]),A([]),()=>{L=!1})},[g]),o.useEffect(()=>{!ze.productId&&V[0]&&oe(L=>({...L,productId:R||V[0].id}))},[V,ze.productId,R]),o.useEffect(()=>{ue(a.query)},[a.query]),o.useEffect(()=>{!Te&&V[0]&&Ce(V[0].id),!Je&&V[0]&&ee(V[0].id)},[V,Te,Je]);const ye=L=>{ie&&m(We=>We.map(mt=>mt.id===ie.id?{...mt,...L}:mt))},Ge=async L=>{if(L.preventDefault(),!(!e||!ze.productId)){q("create"),D("");try{const We=await bx({productId:ze.productId,postType:ze.postType,title:ze.title,body:ze.body,visibility:ze.postType==="announcement"?"public":ze.visibility,appVersion:n,includeEnvironment:ze.postType==="issue"&&ze.includeEnvironment});for(const Ft of $e)await yx(We,Ft);const mt=await be();K(!1),qe([]),oe(Ft=>({...Ft,title:"",body:"",files:[]})),w(We),mt.some(Ft=>Ft.id===We)||await Z()}catch(We){D(Yn(We))}finally{q("")}}},tt=async L=>{if(L.preventDefault(),!!ie){q("edit"),D("");try{await xx(ie.id,ie.title,ie.body,ie.visibility),W(!1),await be()}catch(We){D(Yn(We))}finally{q("")}}},Ye=async L=>{if(L.preventDefault(),!(!ie||!ce.trim())){q("comment"),D("");try{await Sx(ie.id,ce),j(""),y(await Th(ie.id)),await be()}catch(We){D(Yn(We))}finally{q("")}}},vt=async()=>{if(!(!ie||ie.post_type!=="feature")){q("vote"),D("");try{const L=await Cx(ie.id);I(We=>{const mt=new Set(We);return L.voted?mt.add(ie.id):mt.delete(ie.id),mt}),ye({vote_count:L.totalVotes})}catch(L){D(Yn(L))}finally{q("")}}},at=async L=>{if(ie){q("status"),D("");try{await kx(ie.id,L),ye({status:L}),await be()}catch(We){D(Yn(We))}finally{q("")}}},kt=async()=>{if(!(!ie||!window.confirm("Hide this Support post from the board?"))){q("hide"),D("");try{await Mx(ie.id),w(""),await be()}catch(L){D(Yn(L))}finally{q("")}}},jt=async()=>{if(ie){q("lock"),D("");try{await Ax(ie.id,!ie.is_locked),ye({is_locked:!ie.is_locked}),await be()}catch(L){D(Yn(L))}finally{q("")}}},dt=async()=>{if(ie){q("pin"),D("");try{await Nx(ie.id,!ie.is_pinned),ye({is_pinned:!ie.is_pinned}),await be()}catch(L){D(Yn(L))}finally{q("")}}},Wt=async L=>{if(ie){q(`accept-${L}`),D("");try{await Px(ie.id,L),ye({accepted_comment_id:L,status:ie.post_type==="question"?"answered":ie.status}),await be()}catch(We){D(Yn(We))}finally{q("")}}},Vt=async()=>{if(!(!ie||!P||P===ie.id)){q("duplicate"),D("");try{await Rx(ie.id,P),w(""),Se(""),await be()}catch(L){D(Yn(L))}finally{q("")}}},Mn=async L=>{if(!L.read_at)try{await gx(L.id),N(We=>We.map(mt=>mt.id===L.id?{...mt,read_at:new Date().toISOString()}:mt))}catch(We){D(Yn(We))}L.post_id&&w(L.post_id),ge(!1)};return e?F&&!c?r.jsxs("section",{className:"support-page support-loading",children:[r.jsx(Va,{className:"support-spin",size:23})," Loading Support Board..."]}):r.jsxs("section",{className:"support-page",children:[r.jsx("header",{className:"support-page-header support-page-actions-only",children:r.jsxs("div",{className:"support-header-actions",children:[r.jsxs("div",{className:"support-notification-wrap",children:[r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ge(L=>!L),title:"Notifications",children:[r.jsx(Cy,{size:16})," ",C.filter(L=>!L.read_at).length>0&&r.jsx("b",{children:C.filter(L=>!L.read_at).length})]}),U&&r.jsxs("div",{className:"support-notification-popover",children:[r.jsx("strong",{children:"Notifications"}),C.length===0?r.jsx("span",{className:"support-muted",children:"No notifications yet."}):C.map(L=>r.jsxs("button",{type:"button",className:L.read_at?"":"unread",onClick:()=>{Mn(L)},children:[r.jsx("b",{children:L.title}),r.jsx("span",{children:L.body}),r.jsx("small",{children:ll(L.created_at)})]},L.id))]})]}),c?.canViewAllProducts&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>we(L=>!L),children:[r.jsx(sn,{size:16})," Admin"]}),r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Z()},disabled:F,children:[r.jsx(Va,{size:16,className:F?"support-spin":""})," Refresh"]}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>K(!0),disabled:V.length===0,children:[r.jsx(Dl,{size:17})," New request"]})]})}),T&&r.jsxs("div",{className:"support-error",role:"alert",children:[r.jsx(kn,{size:17})," ",r.jsx("span",{children:T}),r.jsx("button",{type:"button",onClick:()=>D(""),"aria-label":"Dismiss error",children:r.jsx(kn,{size:15})})]}),H&&r.jsxs("form",{className:"support-composer",onSubmit:L=>{Ge(L)},children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"New Support request"}),r.jsx("strong",{children:"Describe one actionable problem or idea."})]}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>K(!1),"aria-label":"Close composer",children:r.jsx(kn,{size:18})})]}),r.jsxs("div",{className:"support-form-grid",children:[r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsx("select",{value:ze.productId,onChange:L=>oe(We=>({...We,productId:L.target.value})),children:V.map(L=>r.jsx("option",{value:L.id,children:L.name},L.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Type"}),r.jsx("select",{value:ze.postType,onChange:L=>oe(We=>({...We,postType:L.target.value})),children:Jd.filter(L=>L.id!=="announcement"||c?.canCreateAnnouncements).map(L=>r.jsx("option",{value:L.id,children:L.label},L.id))})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Title"}),r.jsx("input",{required:!0,minLength:3,maxLength:180,value:ze.title,onChange:L=>oe(We=>({...We,title:L.target.value})),placeholder:"A short, searchable summary"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:ze.postType==="issue"?"What happened?":ze.postType==="feature"?"Describe the desired behavior":ze.postType==="announcement"?"Announcement":"Question"}),r.jsx("textarea",{required:!0,value:ze.body,onChange:L=>oe(We=>({...We,body:L.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:ze.visibility,disabled:ze.postType==="announcement",onChange:L=>oe(We=>({...We,visibility:L.target.value})),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),ze.postType==="issue"&&r.jsxs("label",{className:"support-checkbox",children:[r.jsx("input",{type:"checkbox",checked:ze.includeEnvironment,onChange:L=>oe(We=>({...We,includeEnvironment:L.target.checked}))}),r.jsx("span",{children:"Attach safe browser/runtime details"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Attachments"}),r.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:L=>qe(Array.from(L.target.files||[]).slice(0,5))}),r.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),r.jsxs("div",{className:"support-composer-footer",children:[r.jsx("span",{children:$e.length>0?`${$e.length} attachment${$e.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:$==="create",children:[r.jsx(Uo,{size:16})," ",$==="create"?"Submitting...":"Submit request"]})]})]}),r.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[r.jsx("button",{className:a.type==="all"?"active":"",type:"button",onClick:()=>me({type:"all"}),children:"All"}),Jd.map(L=>{const We=Ih(L.id);return r.jsxs("button",{className:a.type===L.id?"active":"",type:"button",onClick:()=>me({type:L.id}),children:[r.jsx(We,{size:15})," ",L.label]},L.id)})]}),re&&c?.canViewAllProducts&&r.jsxs("section",{className:"support-admin-panel",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Owner controls"}),r.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),r.jsx(sn,{size:19})]}),r.jsxs("div",{className:"support-admin-grid",children:[r.jsxs("form",{onSubmit:L=>{},children:[r.jsx("strong",{children:"Grant product access"}),r.jsx("input",{type:"email",required:!0,placeholder:"User email",value:Me,onChange:L=>Pe(L.target.value)}),r.jsx("select",{value:Te,onChange:L=>Ce(L.target.value),children:V.map(L=>r.jsx("option",{value:L.id,children:L.name},L.id))}),r.jsxs("select",{value:Y,onChange:L=>Ne(L.target.value),children:[r.jsx("option",{value:"free",children:"Free"}),r.jsx("option",{value:"user",children:"User"}),r.jsx("option",{value:"paid",children:"Paid"}),r.jsx("option",{value:"beta",children:"Beta"}),r.jsx("option",{value:"staff",children:"Staff"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ee==="access",children:[r.jsx(As,{size:15})," Grant access"]})]}),r.jsxs("form",{onSubmit:L=>{},children:[r.jsx("strong",{children:"Assign product admin"}),r.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:De,onChange:L=>je(L.target.value)}),r.jsx("select",{value:Je,onChange:L=>ee(L.target.value),children:V.map(L=>r.jsx("option",{value:L.id,children:L.name},L.id))}),r.jsxs("select",{value:te,onChange:L=>pe(L.target.value),children:[r.jsx("option",{value:"admin",children:"Admin"}),r.jsx("option",{value:"support",children:"Support"}),r.jsx("option",{value:"moderator",children:"Moderator"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ee==="product-admin",children:[r.jsx(sn,{size:15})," Assign admin"]})]}),r.jsxs("form",{onSubmit:L=>{},children:[r.jsx("strong",{children:"Add a product"}),r.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:le,onChange:L=>J(L.target.value)}),r.jsx("input",{required:!0,placeholder:"Product name",value:xe,onChange:L=>de(L.target.value)}),r.jsx("input",{placeholder:"Description",value:Le,onChange:L=>st(L.target.value)}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ee==="product",children:[r.jsx(Dl,{size:15})," Add product"]})]})]})]}),r.jsxs("form",{className:"support-search-bar",onSubmit:L=>{L.preventDefault(),me({query:ne.trim()})},children:[r.jsxs("label",{children:[r.jsx("span",{children:"Search Support"}),r.jsx("input",{value:ne,onChange:L=>ue(L.target.value),placeholder:"Search titles and request details"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",children:[r.jsx(xh,{size:15})," Search"]}),a.query&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{ue(""),me({query:""})},"aria-label":"Clear search",children:r.jsx(kn,{size:16})})]}),r.jsxs("div",{className:"support-filter-bar",children:[r.jsxs("div",{className:"support-filter-title",children:[r.jsx(xh,{size:16}),r.jsx("span",{children:"Filter"})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsxs("select",{value:se,onChange:L=>me({product:L.target.value}),disabled:!c?.canViewAllProducts&&V.length<=1,children:[r.jsx("option",{value:"all",children:"All products"}),V.map(L=>r.jsx("option",{value:L.product_key,children:L.name},L.id))]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Status"}),r.jsx("select",{value:a.status,onChange:L=>me({status:L.target.value}),children:Ix.map(L=>r.jsx("option",{value:L.id,children:L.label},L.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:a.visibility,onChange:L=>me({visibility:L.target.value}),children:[r.jsx("option",{value:"all",children:"All visibility"}),r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{value:a.sort,onChange:L=>me({sort:L.target.value}),children:[r.jsx("option",{value:"recent",children:"Recently updated"}),r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),c?.canViewAllProducts&&r.jsxs("div",{className:"support-admin-shortcuts",children:[r.jsxs("span",{children:[r.jsx(sn,{size:15})," Owner view"]}),r.jsx("button",{type:"button",onClick:()=>me({status:"needs-response"}),children:"Needs response"}),r.jsx("button",{type:"button",onClick:()=>me({visibility:"private"}),children:"Private requests"}),r.jsx("button",{type:"button",onClick:()=>me({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),r.jsxs("div",{className:"support-board-layout",children:[r.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[r.jsxs("div",{className:"support-list-heading",children:[r.jsxs("span",{children:[ae.length," request",ae.length===1?"":"s"]}),r.jsx("small",{children:se==="all"?"All products":bd(V,R)})]}),ae.length===0?r.jsxs("div",{className:"support-list-empty",children:[r.jsx(Oo,{size:25}),r.jsx("strong",{children:"No posts match these filters."}),r.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),V.length>0&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>K(!0),children:[r.jsx(Dl,{size:16})," Create the first request"]})]}):ae.map(L=>{const We=Ih(L.post_type);return r.jsxs("button",{type:"button",className:`support-post-row ${L.id===ie?.id?"active":""}`,onClick:()=>{w(L.id),W(!1)},children:[r.jsx("span",{className:"support-post-row-icon",children:r.jsx(We,{size:17})}),r.jsxs("span",{className:"support-post-row-copy",children:[r.jsxs("span",{className:"support-post-row-meta",children:[r.jsx("b",{children:bd(d,L.product_id)}),r.jsx("em",{children:jh(L.post_type)}),L.visibility==="private"&&r.jsx(Ms,{size:13})]}),r.jsx("strong",{children:L.title}),r.jsxs("small",{children:[vd(L.status)," · ",ll(L.updated_at)," · ",L.comment_count," comments"]})]}),L.post_type==="feature"&&r.jsxs("span",{className:"support-vote-count",children:[r.jsx(Yg,{size:14})," ",L.vote_count]})]},L.id)})]}),r.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:ie?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"support-detail-head",children:[r.jsxs("div",{className:"support-detail-badges",children:[r.jsx("span",{className:"support-product-badge",children:bd(d,ie.product_id)}),r.jsx("span",{className:"support-type-badge",children:jh(ie.post_type)}),r.jsx("span",{className:`support-status-badge status-${ie.status}`,children:vd(ie.status)}),ie.visibility==="private"&&r.jsxs("span",{className:"support-private-badge",children:[r.jsx(Ms,{size:13})," Private"]})]}),r.jsxs("div",{className:"support-detail-actions",children:[Oe&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>W(L=>!L),title:"Edit post",children:r.jsx(ky,{size:16})}),_e&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{dt()},disabled:$==="pin",title:ie.is_pinned?"Unpin post":"Pin post",children:r.jsx(Sh,{size:16})}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{jt()},disabled:$==="lock",title:ie.is_locked?"Unlock post":"Lock post",children:r.jsx(Ms,{size:16})}),r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{kt()},disabled:$==="hide",title:"Hide post",children:r.jsx(Ch,{size:16})})]})]})]}),z?r.jsxs("form",{className:"support-edit-form",onSubmit:L=>{tt(L)},children:[r.jsx("input",{value:ie.title,onChange:L=>ye({title:L.target.value}),minLength:3,maxLength:180,required:!0}),r.jsx("textarea",{value:ie.body,onChange:L=>ye({body:L.target.value}),rows:9,required:!0}),r.jsxs("div",{className:"support-edit-actions",children:[r.jsxs("select",{value:ie.visibility,onChange:L=>ye({visibility:L.target.value}),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:$==="edit",children:[r.jsx(As,{size:16})," Save changes"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("h3",{children:ie.title}),r.jsx("div",{className:"support-detail-body",children:ie.body.split(`
1
+ import{j as r,M as Ug,w as Vg,D as un,r as Ua,g as El,i as zl,h as Be,c as su,a as au,n as Gg,b as yy,d as xy,e as Fl,f as Kg,k as Qg,l as Sy,m as yh,p as Cs,P as No,F as cl}from"./index-B50oR7D0.js";import{a as o,m as Oo,k as sn,n as Va,B as Cy,P as Dl,X as kn,o as Uo,l as As,F as xh,p as Ms,q as Yg,s as ky,t as Sh,u as Ch,v as My,D as Vo,b as _n,w as Ay,x as Xg,y as Ny,z as Ry,g as is,c as fn,H as ql,I as Bo,J as Ul,K as qs,O as Jg,Q as Zg,U as ev,V as kh,Y as Py,Z as Ty,_ as Ba,W as iu,$ as Iy,a0 as jy,a1 as Oi,a2 as Bi,a3 as Ey,a4 as Qd,S as Ks,a5 as tv,a6 as nv,a7 as Fy,a8 as Dy,a9 as Ly,aa as Ap,ab as _y,N as Np,ac as rv,ad as $y,ae as Jn,af as Mh,C as Rp,ag as ou,ah as Go,ai as Ho,aj as sv,ak as Oy,al as av,am as By,an as iv,ao as Hy,ap as Yd,aq as Wy,ar as Xd,as as ov,at as zy,au as qy,av as Uy,aw as Vy,ax as cv,ay as Gy,az as Ah,aA as Ky,aB as Qy,aC as Yy,aD as lv,f as Fo,T as Ll,A as Xy,E as Jy,aE as Nh,aF as md,aG as Zy,aH as hd,aI as Rh,aJ as Ph,aK as ex,aL as uv,aM as tx,G as nx}from"./icons-DwJmccVC.js";import{c as rx}from"./supabase-C7qjtLN3.js";import{r as sx}from"./react-DOZUPHF8.js";const ax="https://otbyfkjxrkngvjziawki.supabase.co",ix="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",ox={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},fd=typeof window<"u"&&!!window.liveDesk,ht=rx(ax,ix,{auth:{autoRefreshToken:!fd,persistSession:!fd,storage:fd?ox:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),cx=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),lx={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const e={browserLanguage:navigator.language||"",platform:navigator.platform||"",online:navigator.onLine,timezone:typeof Intl>"u"?"":Intl.DateTimeFormat().resolvedOptions().timeZone||"",viewport:typeof window>"u"?void 0:{width:window.innerWidth,height:window.innerHeight},screen:typeof window>"u"?void 0:{width:window.screen.width,height:window.screen.height}};return Object.fromEntries(Object.entries(e).filter(([t,n])=>cx.has(t)&&n!==void 0))}};function ux(e,t="Support request failed."){if(e&&typeof e=="object"&&"message"in e){const n=String(e.message||"").trim();if(n)return n.replace(/^.*Support request failed:\s*/i,"")}return e instanceof Error?e.message:t}function dx(e=lx){return e.collect()}async function px(e,t="livedesk"){const{data:n,error:s}=await ht.from("app_admins").select("role").eq("user_id",e).limit(1);if(s)throw s;const a=n?.[0]?.role||"user";if(a!=="owner"){const{error:w}=await ht.rpc("register_product_access",{p_product_key:t,p_access_type:"free"});if(w)throw w}const[i,c,u]=await Promise.all([ht.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),ht.from("product_admins").select("product_id, role").eq("user_id",e),ht.from("user_products").select("product_id").eq("user_id",e).eq("is_active",!0)]);if(i.error)throw i.error;if(c.error)throw c.error;if(u.error)throw u.error;const d=i.data||[],p=(c.data||[]).map(w=>String(w.product_id)),h=(u.data||[]).map(w=>String(w.product_id)),m=a==="owner",g=m?d.map(w=>w.id):[...new Set([...p,...h])];return{products:d,access:{userId:e,globalRole:a,accessibleProductIds:g,managedProductIds:m?d.map(w=>w.id):p,canViewAllProducts:m,canViewAllPrivatePosts:m,canManageAllProducts:m,canCreateAnnouncements:m||p.length>0}}}async function mx(e=""){const{data:t,error:n}=await ht.rpc("search_support_posts",{p_query:e.trim()||null,p_limit:250});if(n)throw n;return t||[]}async function hx(e){const{data:t,error:n}=await ht.from("support_attachments").select("*").eq("post_id",e).order("created_at");if(n)throw n;const s=t||[];return Promise.all(s.map(async a=>{const i=await ht.storage.from("support-attachments").createSignedUrl(a.storage_path,3600);return{...a,signed_url:i.data?.signedUrl||void 0}}))}async function fx(){const{data:e,error:t}=await ht.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(t)throw t;return e||[]}async function gx(e){const{error:t}=await ht.rpc("mark_support_notification_read",{p_notification_id:e});if(t)throw t}async function Th(e){const{data:t,error:n}=await ht.from("support_comments").select("*").eq("post_id",e).order("created_at");if(n)throw n;return t||[]}async function vx(e){const{data:t,error:n}=await ht.from("support_votes").select("post_id").eq("user_id",e);if(n)throw n;return new Set((t||[]).map(s=>String(s.post_id)))}async function bx(e){const{data:t,error:n}=await ht.rpc("create_support_post",{p_product_id:e.productId,p_post_type:e.postType,p_title:e.title,p_body:e.body,p_visibility:e.visibility,p_app_version:e.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:e.includeEnvironment?dx():{}});if(n)throw n;const s=Array.isArray(t)?t[0]?.post_id:t?.post_id;if(!s)throw new Error("Support post was not created.");return String(s)}const wx=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function yx(e,t){if(!wx.has(t.type))throw new Error("This file type is not allowed.");if(t.size<=0||t.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const n=t.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,a=`${e}/${s}-${n}`,i=await ht.storage.from("support-attachments").upload(a,t,{contentType:t.type,upsert:!1});if(i.error)throw i.error;const{data:c,error:u}=await ht.rpc("add_support_attachment",{p_post_id:e,p_storage_path:a,p_file_name:n,p_mime_type:t.type,p_size_bytes:t.size});if(u)throw await ht.storage.from("support-attachments").remove([a]),u;const d=Array.isArray(c)?c[0]?.attachment_id:c?.attachment_id;if(!d)throw new Error("Attachment metadata was not created.");return String(d)}async function xx(e,t,n,s){const{error:a}=await ht.rpc("update_support_post",{p_post_id:e,p_title:t,p_body:n,p_visibility:s});if(a)throw a}async function Sx(e,t){const{error:n}=await ht.rpc("add_support_comment",{p_post_id:e,p_body:t});if(n)throw n}async function Cx(e){const{data:t,error:n}=await ht.rpc("toggle_support_vote",{p_post_id:e});if(n)throw n;const s=Array.isArray(t)?t[0]:t;return{voted:!!s?.voted,totalVotes:Number(s?.total_votes||0)}}async function kx(e,t){const{error:n}=await ht.rpc("change_support_post_status",{p_post_id:e,p_target_status:t});if(n)throw n}async function Mx(e){const{error:t}=await ht.rpc("set_support_post_hidden",{p_post_id:e,p_hidden:!0});if(t)throw t}async function Ax(e,t){const{error:n}=await ht.rpc("set_support_post_locked",{p_post_id:e,p_locked:t});if(n)throw n}async function Nx(e,t){const{error:n}=await ht.rpc("set_support_post_pinned",{p_post_id:e,p_pinned:t});if(n)throw n}async function Rx(e,t){const{error:n}=await ht.rpc("mark_support_duplicate",{p_post_id:e,p_duplicate_of_post_id:t});if(n)throw n}async function Px(e,t){const{error:n}=await ht.rpc("accept_support_answer",{p_post_id:e,p_comment_id:t});if(n)throw n}async function Tx(e,t=!0){const{error:n}=await ht.rpc("hide_support_comment",{p_comment_id:e,p_hidden:t});if(n)throw n}const Jd=[{id:"question",label:"Questions",shortLabel:"Question"},{id:"issue",label:"Issues",shortLabel:"Issue"},{id:"feature",label:"Feature Requests",shortLabel:"Feature"},{id:"announcement",label:"Announcements",shortLabel:"Announcement"}],Ix=[{id:"all",label:"All statuses"},{id:"needs-response",label:"Needs response"},{id:"open",label:"Open"},{id:"needs-info",label:"Needs more information"},{id:"in-progress",label:"In progress"},{id:"planned",label:"Planned"},{id:"released",label:"Released"},{id:"closed",label:"Closed"}],jx={question:["open","answered","resolved","closed"],issue:["open","needs-info","confirmed","in-progress","fixed","closed"],feature:["under-review","planned","in-progress","released","declined","closed"],announcement:["published","archived"]},Ex={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function gd(){if(typeof window>"u")return Ex;const e=new URLSearchParams(window.location.search),t=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],n=e.get("type")||t||"",s=n==="questions"||n==="question"?"question":n==="issues"||n==="issue"?"issue":n==="features"||n==="feature"?"feature":n==="announcements"||n==="announcement"?"announcement":"all",a=e.get("visibility"),i=e.get("sort");return{type:s,product:e.get("product")||"",status:e.get("status")||"all",visibility:a==="public"||a==="private"?a:"all",sort:i==="votes"||i==="newest"?i:"recent",query:e.get("q")||""}}function Fx(e){return e==="all"?"":e==="question"?"questions":e==="issue"?"issues":e==="feature"?"features":"announcements"}function Dx(e,t){const n={...e,...t},s=new URLSearchParams;n.product&&s.set("product",n.product),n.status!=="all"&&s.set("status",n.status),n.visibility!=="all"&&s.set("visibility",n.visibility),n.sort!=="recent"&&s.set("sort",n.sort),n.query&&s.set("q",n.query);const a=Fx(n.type),i=s.toString();return`/support${a?`/${a}`:""}${i?`?${i}`:""}`}function ll(e){const t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):e}function vd(e){return e.replaceAll("-"," ").replace(/\b\w/g,t=>t.toUpperCase())}function Ih(e){return e==="question"?Ay:e==="issue"?Xg:e==="feature"?Ny:Ry}function jh(e){return Jd.find(t=>t.id===e)?.shortLabel||e}function bd(e,t){return e.find(n=>n.id===t)?.name||"Product"}function Yn(e){const t=ux(e);return/relation .* does not exist|function .* does not exist|schema cache/i.test(t)?"Support Board database is not installed yet. Apply the latest Supabase migration first.":/not-authenticated|jwt/i.test(t)?"Sign in again to use Support.":/product-access-denied|product-not-found/i.test(t)?"You do not have access to this product.":t}function dv({session:e,currentProductKey:t="livedesk",appVersion:n="",onSignIn:s}){const[a,i]=o.useState(()=>gd()),[c,u]=o.useState(null),[d,p]=o.useState([]),[h,m]=o.useState([]),[g,w]=o.useState(""),[b,y]=o.useState([]),[k,A]=o.useState([]),[C,N]=o.useState([]),[E,I]=o.useState(()=>new Set),[F,M]=o.useState(!0),[$,q]=o.useState(""),[T,D]=o.useState(""),[H,K]=o.useState(!1),[z,W]=o.useState(!1),[ce,j]=o.useState(""),[ne,ue]=o.useState(()=>gd().query),[U,ge]=o.useState(!1),[re,we]=o.useState(!1),[Me,Pe]=o.useState(""),[Te,Ce]=o.useState(""),[Y,Ne]=o.useState("free"),[De,je]=o.useState(""),[Je,ee]=o.useState(""),[te,pe]=o.useState("admin"),[le,J]=o.useState(""),[xe,de]=o.useState(""),[Le,st]=o.useState(""),[P,Se]=o.useState(""),[Ee,ct]=o.useState(""),[$e,qe]=o.useState([]),[ze,oe]=o.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),me=o.useCallback(L=>{const We={...a,...L};i(We),typeof window<"u"&&window.history.pushState({},"",Dx(a,L))},[a]);o.useEffect(()=>{const L=()=>i(gd());return window.addEventListener("popstate",L),()=>window.removeEventListener("popstate",L)},[]);const be=o.useCallback(async()=>{const L=await mx(a.query);return m(L),e?.user.id&&I(await vx(e.user.id)),L},[a.query,e?.user.id]),Z=o.useCallback(async()=>{if(!e?.user.id){u(null),p([]),m([]),w(""),N([]),M(!1);return}M(!0),D("");try{const L=await px(e.user.id,t);u(L.access),p(L.products),await be(),N(await fx())}catch(L){D(Yn(L))}finally{M(!1)}},[t,be,e?.user.id]);o.useEffect(()=>{Z()},[Z]);const V=o.useMemo(()=>c?c.canViewAllProducts?d:d.filter(L=>c.accessibleProductIds.includes(L.id)):[],[c,d]),se=o.useMemo(()=>{const L=V.find(We=>We.product_key===a.product);return c?.canViewAllProducts&&!a.product||a.product==="all"&&c?.canViewAllProducts?"all":L?L.product_key:V.some(We=>We.product_key===t)?t:V[0]?.product_key||""},[c?.canViewAllProducts,V,t,a.product]),R=se==="all"?"":V.find(L=>L.product_key===se)?.id||"",ae=o.useMemo(()=>{const L=new Map(d.map(mt=>[mt.id,mt.product_key]));return[...h.filter(mt=>a.type!=="all"&&mt.post_type!==a.type||se!=="all"&&R&&mt.product_id!==R||a.status==="needs-response"&&!["open","needs-info"].includes(mt.status)||a.status!=="all"&&a.status!=="needs-response"&&mt.status!==a.status||a.visibility!=="all"&&mt.visibility!==a.visibility?!1:L.has(mt.product_id))].sort((mt,Ft)=>a.sort==="votes"?Ft.vote_count-mt.vote_count||Ft.updated_at.localeCompare(mt.updated_at):a.sort==="newest"?Ft.created_at.localeCompare(mt.created_at):Number(Ft.is_pinned)-Number(mt.is_pinned)||Ft.updated_at.localeCompare(mt.updated_at))},[h,d,a.sort,a.status,a.type,a.visibility,R,se]),ie=ae.find(L=>L.id===g)||ae[0]||null,_e=!!(ie&&c&&(c.canViewAllProducts||c.managedProductIds.includes(ie.product_id))),Oe=!!(ie&&e?.user.id===ie.author_id)||_e;o.useEffect(()=>{if(!ie){w(""),y([]),W(!1);return}ie.id!==g&&w(ie.id)},[ie,g]),o.useEffect(()=>{let L=!0;return g?(Th(g).then(We=>{L&&y(We)}).catch(We=>{L&&D(Yn(We))}),hx(g).then(We=>{L&&A(We)}).catch(We=>{L&&D(Yn(We))}),()=>{L=!1}):(y([]),A([]),()=>{L=!1})},[g]),o.useEffect(()=>{!ze.productId&&V[0]&&oe(L=>({...L,productId:R||V[0].id}))},[V,ze.productId,R]),o.useEffect(()=>{ue(a.query)},[a.query]),o.useEffect(()=>{!Te&&V[0]&&Ce(V[0].id),!Je&&V[0]&&ee(V[0].id)},[V,Te,Je]);const ye=L=>{ie&&m(We=>We.map(mt=>mt.id===ie.id?{...mt,...L}:mt))},Ge=async L=>{if(L.preventDefault(),!(!e||!ze.productId)){q("create"),D("");try{const We=await bx({productId:ze.productId,postType:ze.postType,title:ze.title,body:ze.body,visibility:ze.postType==="announcement"?"public":ze.visibility,appVersion:n,includeEnvironment:ze.postType==="issue"&&ze.includeEnvironment});for(const Ft of $e)await yx(We,Ft);const mt=await be();K(!1),qe([]),oe(Ft=>({...Ft,title:"",body:"",files:[]})),w(We),mt.some(Ft=>Ft.id===We)||await Z()}catch(We){D(Yn(We))}finally{q("")}}},tt=async L=>{if(L.preventDefault(),!!ie){q("edit"),D("");try{await xx(ie.id,ie.title,ie.body,ie.visibility),W(!1),await be()}catch(We){D(Yn(We))}finally{q("")}}},Ye=async L=>{if(L.preventDefault(),!(!ie||!ce.trim())){q("comment"),D("");try{await Sx(ie.id,ce),j(""),y(await Th(ie.id)),await be()}catch(We){D(Yn(We))}finally{q("")}}},vt=async()=>{if(!(!ie||ie.post_type!=="feature")){q("vote"),D("");try{const L=await Cx(ie.id);I(We=>{const mt=new Set(We);return L.voted?mt.add(ie.id):mt.delete(ie.id),mt}),ye({vote_count:L.totalVotes})}catch(L){D(Yn(L))}finally{q("")}}},at=async L=>{if(ie){q("status"),D("");try{await kx(ie.id,L),ye({status:L}),await be()}catch(We){D(Yn(We))}finally{q("")}}},kt=async()=>{if(!(!ie||!window.confirm("Hide this Support post from the board?"))){q("hide"),D("");try{await Mx(ie.id),w(""),await be()}catch(L){D(Yn(L))}finally{q("")}}},jt=async()=>{if(ie){q("lock"),D("");try{await Ax(ie.id,!ie.is_locked),ye({is_locked:!ie.is_locked}),await be()}catch(L){D(Yn(L))}finally{q("")}}},dt=async()=>{if(ie){q("pin"),D("");try{await Nx(ie.id,!ie.is_pinned),ye({is_pinned:!ie.is_pinned}),await be()}catch(L){D(Yn(L))}finally{q("")}}},Wt=async L=>{if(ie){q(`accept-${L}`),D("");try{await Px(ie.id,L),ye({accepted_comment_id:L,status:ie.post_type==="question"?"answered":ie.status}),await be()}catch(We){D(Yn(We))}finally{q("")}}},Vt=async()=>{if(!(!ie||!P||P===ie.id)){q("duplicate"),D("");try{await Rx(ie.id,P),w(""),Se(""),await be()}catch(L){D(Yn(L))}finally{q("")}}},Mn=async L=>{if(!L.read_at)try{await gx(L.id),N(We=>We.map(mt=>mt.id===L.id?{...mt,read_at:new Date().toISOString()}:mt))}catch(We){D(Yn(We))}L.post_id&&w(L.post_id),ge(!1)};return e?F&&!c?r.jsxs("section",{className:"support-page support-loading",children:[r.jsx(Va,{className:"support-spin",size:23})," Loading Support Board..."]}):r.jsxs("section",{className:"support-page",children:[r.jsx("header",{className:"support-page-header support-page-actions-only",children:r.jsxs("div",{className:"support-header-actions",children:[r.jsxs("div",{className:"support-notification-wrap",children:[r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ge(L=>!L),title:"Notifications",children:[r.jsx(Cy,{size:16})," ",C.filter(L=>!L.read_at).length>0&&r.jsx("b",{children:C.filter(L=>!L.read_at).length})]}),U&&r.jsxs("div",{className:"support-notification-popover",children:[r.jsx("strong",{children:"Notifications"}),C.length===0?r.jsx("span",{className:"support-muted",children:"No notifications yet."}):C.map(L=>r.jsxs("button",{type:"button",className:L.read_at?"":"unread",onClick:()=>{Mn(L)},children:[r.jsx("b",{children:L.title}),r.jsx("span",{children:L.body}),r.jsx("small",{children:ll(L.created_at)})]},L.id))]})]}),c?.canViewAllProducts&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>we(L=>!L),children:[r.jsx(sn,{size:16})," Admin"]}),r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Z()},disabled:F,children:[r.jsx(Va,{size:16,className:F?"support-spin":""})," Refresh"]}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>K(!0),disabled:V.length===0,children:[r.jsx(Dl,{size:17})," New request"]})]})}),T&&r.jsxs("div",{className:"support-error",role:"alert",children:[r.jsx(kn,{size:17})," ",r.jsx("span",{children:T}),r.jsx("button",{type:"button",onClick:()=>D(""),"aria-label":"Dismiss error",children:r.jsx(kn,{size:15})})]}),H&&r.jsxs("form",{className:"support-composer",onSubmit:L=>{Ge(L)},children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"New Support request"}),r.jsx("strong",{children:"Describe one actionable problem or idea."})]}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>K(!1),"aria-label":"Close composer",children:r.jsx(kn,{size:18})})]}),r.jsxs("div",{className:"support-form-grid",children:[r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsx("select",{value:ze.productId,onChange:L=>oe(We=>({...We,productId:L.target.value})),children:V.map(L=>r.jsx("option",{value:L.id,children:L.name},L.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Type"}),r.jsx("select",{value:ze.postType,onChange:L=>oe(We=>({...We,postType:L.target.value})),children:Jd.filter(L=>L.id!=="announcement"||c?.canCreateAnnouncements).map(L=>r.jsx("option",{value:L.id,children:L.label},L.id))})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Title"}),r.jsx("input",{required:!0,minLength:3,maxLength:180,value:ze.title,onChange:L=>oe(We=>({...We,title:L.target.value})),placeholder:"A short, searchable summary"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:ze.postType==="issue"?"What happened?":ze.postType==="feature"?"Describe the desired behavior":ze.postType==="announcement"?"Announcement":"Question"}),r.jsx("textarea",{required:!0,value:ze.body,onChange:L=>oe(We=>({...We,body:L.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:ze.visibility,disabled:ze.postType==="announcement",onChange:L=>oe(We=>({...We,visibility:L.target.value})),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),ze.postType==="issue"&&r.jsxs("label",{className:"support-checkbox",children:[r.jsx("input",{type:"checkbox",checked:ze.includeEnvironment,onChange:L=>oe(We=>({...We,includeEnvironment:L.target.checked}))}),r.jsx("span",{children:"Attach safe browser/runtime details"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Attachments"}),r.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:L=>qe(Array.from(L.target.files||[]).slice(0,5))}),r.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),r.jsxs("div",{className:"support-composer-footer",children:[r.jsx("span",{children:$e.length>0?`${$e.length} attachment${$e.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:$==="create",children:[r.jsx(Uo,{size:16})," ",$==="create"?"Submitting...":"Submit request"]})]})]}),r.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[r.jsx("button",{className:a.type==="all"?"active":"",type:"button",onClick:()=>me({type:"all"}),children:"All"}),Jd.map(L=>{const We=Ih(L.id);return r.jsxs("button",{className:a.type===L.id?"active":"",type:"button",onClick:()=>me({type:L.id}),children:[r.jsx(We,{size:15})," ",L.label]},L.id)})]}),re&&c?.canViewAllProducts&&r.jsxs("section",{className:"support-admin-panel",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Owner controls"}),r.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),r.jsx(sn,{size:19})]}),r.jsxs("div",{className:"support-admin-grid",children:[r.jsxs("form",{onSubmit:L=>{},children:[r.jsx("strong",{children:"Grant product access"}),r.jsx("input",{type:"email",required:!0,placeholder:"User email",value:Me,onChange:L=>Pe(L.target.value)}),r.jsx("select",{value:Te,onChange:L=>Ce(L.target.value),children:V.map(L=>r.jsx("option",{value:L.id,children:L.name},L.id))}),r.jsxs("select",{value:Y,onChange:L=>Ne(L.target.value),children:[r.jsx("option",{value:"free",children:"Free"}),r.jsx("option",{value:"user",children:"User"}),r.jsx("option",{value:"paid",children:"Paid"}),r.jsx("option",{value:"beta",children:"Beta"}),r.jsx("option",{value:"staff",children:"Staff"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ee==="access",children:[r.jsx(As,{size:15})," Grant access"]})]}),r.jsxs("form",{onSubmit:L=>{},children:[r.jsx("strong",{children:"Assign product admin"}),r.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:De,onChange:L=>je(L.target.value)}),r.jsx("select",{value:Je,onChange:L=>ee(L.target.value),children:V.map(L=>r.jsx("option",{value:L.id,children:L.name},L.id))}),r.jsxs("select",{value:te,onChange:L=>pe(L.target.value),children:[r.jsx("option",{value:"admin",children:"Admin"}),r.jsx("option",{value:"support",children:"Support"}),r.jsx("option",{value:"moderator",children:"Moderator"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ee==="product-admin",children:[r.jsx(sn,{size:15})," Assign admin"]})]}),r.jsxs("form",{onSubmit:L=>{},children:[r.jsx("strong",{children:"Add a product"}),r.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:le,onChange:L=>J(L.target.value)}),r.jsx("input",{required:!0,placeholder:"Product name",value:xe,onChange:L=>de(L.target.value)}),r.jsx("input",{placeholder:"Description",value:Le,onChange:L=>st(L.target.value)}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:Ee==="product",children:[r.jsx(Dl,{size:15})," Add product"]})]})]})]}),r.jsxs("form",{className:"support-search-bar",onSubmit:L=>{L.preventDefault(),me({query:ne.trim()})},children:[r.jsxs("label",{children:[r.jsx("span",{children:"Search Support"}),r.jsx("input",{value:ne,onChange:L=>ue(L.target.value),placeholder:"Search titles and request details"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",children:[r.jsx(xh,{size:15})," Search"]}),a.query&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{ue(""),me({query:""})},"aria-label":"Clear search",children:r.jsx(kn,{size:16})})]}),r.jsxs("div",{className:"support-filter-bar",children:[r.jsxs("div",{className:"support-filter-title",children:[r.jsx(xh,{size:16}),r.jsx("span",{children:"Filter"})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Product"}),r.jsxs("select",{value:se,onChange:L=>me({product:L.target.value}),disabled:!c?.canViewAllProducts&&V.length<=1,children:[r.jsx("option",{value:"all",children:"All products"}),V.map(L=>r.jsx("option",{value:L.product_key,children:L.name},L.id))]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Status"}),r.jsx("select",{value:a.status,onChange:L=>me({status:L.target.value}),children:Ix.map(L=>r.jsx("option",{value:L.id,children:L.label},L.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:a.visibility,onChange:L=>me({visibility:L.target.value}),children:[r.jsx("option",{value:"all",children:"All visibility"}),r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{value:a.sort,onChange:L=>me({sort:L.target.value}),children:[r.jsx("option",{value:"recent",children:"Recently updated"}),r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),c?.canViewAllProducts&&r.jsxs("div",{className:"support-admin-shortcuts",children:[r.jsxs("span",{children:[r.jsx(sn,{size:15})," Owner view"]}),r.jsx("button",{type:"button",onClick:()=>me({status:"needs-response"}),children:"Needs response"}),r.jsx("button",{type:"button",onClick:()=>me({visibility:"private"}),children:"Private requests"}),r.jsx("button",{type:"button",onClick:()=>me({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),r.jsxs("div",{className:"support-board-layout",children:[r.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[r.jsxs("div",{className:"support-list-heading",children:[r.jsxs("span",{children:[ae.length," request",ae.length===1?"":"s"]}),r.jsx("small",{children:se==="all"?"All products":bd(V,R)})]}),ae.length===0?r.jsxs("div",{className:"support-list-empty",children:[r.jsx(Oo,{size:25}),r.jsx("strong",{children:"No posts match these filters."}),r.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),V.length>0&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>K(!0),children:[r.jsx(Dl,{size:16})," Create the first request"]})]}):ae.map(L=>{const We=Ih(L.post_type);return r.jsxs("button",{type:"button",className:`support-post-row ${L.id===ie?.id?"active":""}`,onClick:()=>{w(L.id),W(!1)},children:[r.jsx("span",{className:"support-post-row-icon",children:r.jsx(We,{size:17})}),r.jsxs("span",{className:"support-post-row-copy",children:[r.jsxs("span",{className:"support-post-row-meta",children:[r.jsx("b",{children:bd(d,L.product_id)}),r.jsx("em",{children:jh(L.post_type)}),L.visibility==="private"&&r.jsx(Ms,{size:13})]}),r.jsx("strong",{children:L.title}),r.jsxs("small",{children:[vd(L.status)," · ",ll(L.updated_at)," · ",L.comment_count," comments"]})]}),L.post_type==="feature"&&r.jsxs("span",{className:"support-vote-count",children:[r.jsx(Yg,{size:14})," ",L.vote_count]})]},L.id)})]}),r.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:ie?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"support-detail-head",children:[r.jsxs("div",{className:"support-detail-badges",children:[r.jsx("span",{className:"support-product-badge",children:bd(d,ie.product_id)}),r.jsx("span",{className:"support-type-badge",children:jh(ie.post_type)}),r.jsx("span",{className:`support-status-badge status-${ie.status}`,children:vd(ie.status)}),ie.visibility==="private"&&r.jsxs("span",{className:"support-private-badge",children:[r.jsx(Ms,{size:13})," Private"]})]}),r.jsxs("div",{className:"support-detail-actions",children:[Oe&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>W(L=>!L),title:"Edit post",children:r.jsx(ky,{size:16})}),_e&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{dt()},disabled:$==="pin",title:ie.is_pinned?"Unpin post":"Pin post",children:r.jsx(Sh,{size:16})}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{jt()},disabled:$==="lock",title:ie.is_locked?"Unlock post":"Lock post",children:r.jsx(Ms,{size:16})}),r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{kt()},disabled:$==="hide",title:"Hide post",children:r.jsx(Ch,{size:16})})]})]})]}),z?r.jsxs("form",{className:"support-edit-form",onSubmit:L=>{tt(L)},children:[r.jsx("input",{value:ie.title,onChange:L=>ye({title:L.target.value}),minLength:3,maxLength:180,required:!0}),r.jsx("textarea",{value:ie.body,onChange:L=>ye({body:L.target.value}),rows:9,required:!0}),r.jsxs("div",{className:"support-edit-actions",children:[r.jsxs("select",{value:ie.visibility,onChange:L=>ye({visibility:L.target.value}),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:$==="edit",children:[r.jsx(As,{size:16})," Save changes"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("h3",{children:ie.title}),r.jsx("div",{className:"support-detail-body",children:ie.body.split(`
2
2
  `).map((L,We)=>r.jsx("p",{children:L||" "},`${ie.id}-body-${We}`))})]}),r.jsxs("div",{className:"support-detail-meta",children:[r.jsxs("span",{children:["Opened ",ll(ie.created_at)]}),ie.app_version&&r.jsxs("span",{children:["Version ",ie.app_version]}),ie.platform&&r.jsx("span",{children:ie.platform}),ie.is_locked&&r.jsxs("span",{children:[r.jsx(Ms,{size:13})," Locked"]}),ie.is_pinned&&r.jsxs("span",{children:[r.jsx(Sh,{size:13})," Pinned"]})]}),r.jsxs("div",{className:"support-detail-controls",children:[ie.post_type==="feature"&&r.jsxs("button",{className:`support-vote-button ${E.has(ie.id)?"voted":""}`,type:"button",onClick:()=>{vt()},disabled:$==="vote",children:[r.jsx(My,{size:16})," ",E.has(ie.id)?"Voted":"Vote"," ",r.jsx("b",{children:ie.vote_count})]}),_e&&r.jsxs("label",{className:"support-status-control",children:[r.jsx("span",{children:"Change status"}),r.jsx("select",{value:ie.status,onChange:L=>{at(L.target.value)},disabled:$==="status",children:(jx[ie.post_type]||[]).map(L=>r.jsx("option",{value:L,children:vd(L)},L))})]}),_e&&r.jsxs(r.Fragment,{children:[r.jsxs("select",{className:"support-status-control",value:P,onChange:L=>Se(L.target.value),children:[r.jsx("option",{value:"",children:"Duplicate of..."}),ae.filter(L=>L.id!==ie.id&&L.product_id===ie.product_id).map(L=>r.jsx("option",{value:L.id,children:L.title.slice(0,55)},L.id))]}),r.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{Vt()},disabled:!P||$==="duplicate",children:"Merge duplicate"})]})]}),k.length>0&&r.jsxs("div",{className:"support-attachments",children:[r.jsx("div",{className:"support-section-heading",children:r.jsxs("div",{children:[r.jsx("span",{children:"Attachments"}),r.jsxs("strong",{children:[k.length," file",k.length===1?"":"s"]})]})}),k.map(L=>r.jsxs("a",{href:L.signed_url,target:"_blank",rel:"noreferrer",children:[r.jsx(Vo,{size:14})," ",L.file_name,r.jsxs("small",{children:[Math.ceil(L.size_bytes/1024)," KB"]})]},L.id))]}),r.jsxs("div",{className:"support-comments",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Discussion"}),r.jsxs("strong",{children:[b.length," comment",b.length===1?"":"s"]})]}),ie.is_locked&&r.jsxs("span",{className:"support-locked-label",children:[r.jsx(Ms,{size:14})," Locked"]})]}),b.length===0?r.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):r.jsx("div",{className:"support-comment-list",children:b.map(L=>r.jsxs("article",{className:`support-comment ${L.is_staff_answer?"staff":""} ${ie.accepted_comment_id===L.id?"accepted":""}`,children:[r.jsxs("div",{className:"support-comment-head",children:[r.jsx("strong",{children:L.is_staff_answer?"LiveDesk Support":L.author_id===e.user.id?"You":"Support user"}),L.is_staff_answer&&r.jsxs("span",{children:[r.jsx(sn,{size:13})," Staff answer"]}),ie.accepted_comment_id===L.id&&r.jsxs("span",{children:[r.jsx(_n,{size:13})," Accepted"]}),r.jsx("time",{children:ll(L.created_at)})]}),r.jsx("p",{children:L.body}),r.jsxs("div",{className:"support-comment-actions",children:[(e.user.id===ie.author_id||_e)&&ie.post_type==="question"&&ie.accepted_comment_id!==L.id&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Wt(L.id)},disabled:$===`accept-${L.id}`,children:[r.jsx(As,{size:14})," Accept answer"]}),_e&&r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Tx(L.id)},title:"Hide comment",children:r.jsx(Ch,{size:14})})]})]},L.id))}),!ie.is_locked&&r.jsxs("form",{className:"support-comment-form",onSubmit:L=>{Ye(L)},children:[r.jsx("textarea",{value:ce,onChange:L=>j(L.target.value),placeholder:"Add a focused reply...",rows:3}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:$==="comment"||!ce.trim(),children:[r.jsx(Uo,{size:15})," Reply"]})]})]})]}):r.jsxs("div",{className:"support-detail-empty",children:[r.jsx(Oo,{size:28}),r.jsx("strong",{children:"Select a Support request"}),r.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):r.jsx("section",{className:"support-page support-auth-page",children:r.jsxs("div",{className:"support-empty-hero",children:[r.jsx("span",{className:"support-hero-icon",children:r.jsx(Oo,{size:28})}),r.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),r.jsx("h2",{children:"Get help, report issues, and shape the product."}),r.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:s,children:[r.jsx(sn,{size:17})," Sign in with Google"]})]})})}function Lx(e){if(!e)return"Reading the installed version...";switch(e.state){case"checking":return"Checking for a newer LiveDesk version...";case"available":return`Version ${e.availableVersion||""} is available.`;case"downloading":return`Downloading version ${e.availableVersion||""} (${Math.round(e.progress||0)}%).`;case"downloaded":return`Version ${e.availableVersion||""} is ready. Restart to install it.`;case"installing":return"Closing LiveDesk safely and starting the update...";case"current":return"This computer has the latest LiveDesk version.";case"error":return"The update server could not be reached. This version will keep running.";case"development":return"Desktop updates are available in an installed LiveDesk build.";case"unavailable":return"Updates are not available for this desktop build.";default:return"LiveDesk checks once when the desktop app starts."}}function pv(){const e=window.liveDesk?.updates,[t,n]=o.useState(null),[s,a]=o.useState(!1);if(o.useEffect(()=>{if(!e)return;let d=!0;e.getStatus?.().then(h=>{d&&n(h)});const p=e.onStatus?.(h=>{d&&n(h)});return()=>{d=!1,p?.()}},[e]),!e)return null;const i=t?.state==="downloaded"||t?.downloaded===!0,c=s||t?.state==="checking"||t?.state==="downloading"||t?.state==="installing",u=async()=>{a(!0);try{const d=i?await e.install?.():await e.check?.();d&&n(d)}finally{a(!1)}};return r.jsxs("section",{className:"settings-section-card desktop-update-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Desktop app"}),r.jsx("h3",{children:"LiveDesk updates"})]}),r.jsx(Vo,{size:20})]}),r.jsx("p",{className:"settings-help","aria-live":"polite",children:Lx(t)}),r.jsxs("div",{className:"desktop-update-meta",children:[r.jsx("span",{children:"Installed"}),r.jsx("strong",{children:t?.currentVersion||"Unknown"}),t?.availableVersion&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"Available"}),r.jsx("strong",{children:t.availableVersion})]})]}),r.jsxs("button",{className:"settings-reset desktop-update-action",onClick:()=>{u()},disabled:c,type:"button",children:[r.jsx(Va,{size:15,className:c?"desktop-update-spin":""}),i?"Restart and update":c?"Updating...":"Check for updates"]})]})}function ul(e){return!!e&&typeof e=="object"}function mv(e){let t=e;return ul(t)&&"data"in t&&(t=t.data),ul(t)&&"session"in t&&(t=t.session),!ul(t)||typeof t.access_token!="string"||!t.access_token||!ul(t.user)||typeof t.user.id!="string"||!t.user.id?null:t}function Eh(e){return e?.access_token?e.refresh_token?"":"refresh-token-required":"access-token-required"}const hv={hub:"Use this computer as Hub. Hub connects to and manages Client computers.","switch-to-hub":"Switch this computer from Client to Hub. It will manage Client computers instead of sharing its own screen.",client:"Keep this computer in Client mode so its screens, files, audio, and remote controls remain available to the active Hub.",wall:"Show live thumbnails from every connected Client. Choose a display, change tile size, or move into Control without opening another connection.",control:"Open the selected Client at full resolution and send mouse and keyboard input through the existing Hub session.","share-files":"Browse files on the Hub, send files to selected Clients, and manage shared folders and transfer progress.",agents:"Run approved commands on connected Clients through the Hub-hosted Codex Agent and LiveDesk permission controls."},Zd={en:hv,ko:{hub:"이 컴퓨터를 Hub로 사용합니다. Hub는 Client 컴퓨터를 연결하고 관리합니다.","switch-to-hub":"이 컴퓨터를 Client에서 Hub로 바꿉니다. 자신의 화면 공유를 멈추고 Client 컴퓨터를 관리합니다.",client:"이 컴퓨터를 Client 모드로 유지합니다. 화면, 파일, 오디오와 원격 제어 기능이 활성 Hub에서 계속 사용 가능하도록 연결합니다.",wall:"연결된 모든 Client의 실시간 화면을 한곳에 표시합니다. 모니터와 타일 크기를 선택하고 새 연결 없이 Control로 이동할 수 있습니다.",control:"선택한 Client 화면을 전체 해상도로 열고 기존 Hub 세션을 통해 마우스와 키보드 입력을 전송합니다.","share-files":"Hub의 파일을 탐색하고 선택한 Client로 전송하며 공유 폴더와 전송 진행 상태를 관리합니다.",agents:"Hub의 Codex가 연결된 Client에서 LiveDesk 권한과 승인 범위 안의 명령을 실행합니다."},ja:{hub:"このコンピューターを LiveDesk Hub として運用します。Hub は Client 接続、Wall、Control、ファイル共有、Agents を一か所で管理する統合コントロールセンターで、ネットワーク変更後に押すと安全な接続情報も更新します。","switch-to-hub":"このコンピューターを Client から Hub に切り替えます。新しい役割を保存して同じデスクトップランタイムを再起動し、Wall を開きます。Client としての共有は停止します。",client:"このコンピューターを Client モードで維持し、画面、ファイル、音声、リモート操作をアクティブ Hub から利用できるようにします。",wall:"接続中のすべての Client のライブ画面を一覧表示します。ディスプレイやタイルサイズを選び、新しい接続なしで Control に移動できます。",control:"選択した Client をフル解像度で開き、既存の Hub セッションからマウスとキーボード入力を送信します。","share-files":"Hub のファイルを参照し、選択した Client への送信、共有フォルダー、転送状況を管理します。",agents:"Hub の Codex Agent が、LiveDesk の権限と承認の範囲内で接続中の Client にコマンドを実行します。"},zh:{hub:"将此电脑作为 LiveDesk Hub 运行。Hub 是统一控制中心,可集中管理 Client 连接、Wall、Control、文件共享和 Agents;网络变化后按下此按钮还会刷新安全连接信息。","switch-to-hub":"将此电脑从 Client 切换为 Hub。LiveDesk 保存新角色、重启同一桌面运行时并打开 Wall;此电脑将停止作为 Client 共享。",client:"让此电脑保持 Client 模式,使活动 Hub 可以继续使用它的屏幕、文件、音频和远程控制。",wall:"集中显示所有已连接 Client 的实时缩略图。可以选择显示器、调整磁贴大小,并在不新建连接的情况下进入 Control。",control:"以完整分辨率打开所选 Client,并通过现有 Hub 会话发送鼠标和键盘输入。","share-files":"浏览 Hub 文件、向所选 Client 发送文件,并管理共享文件夹和传输进度。",agents:"Hub 的 Codex Agent 会在 LiveDesk 权限与批准范围内,对已连接的 Client 执行命令。"},"zh-TW":{hub:"將此電腦作為 LiveDesk Hub 運作。Hub 是統一控制中心,可集中管理 Client 連線、Wall、Control、檔案分享與 Agents;網路變更後按下此按鈕也會更新安全連線資訊。","switch-to-hub":"將此電腦從 Client 切換為 Hub。LiveDesk 會儲存新角色、重新啟動同一桌面執行階段並開啟 Wall;此電腦將停止以 Client 身分共享。",client:"讓此電腦維持 Client 模式,使作用中 Hub 可繼續使用它的畫面、檔案、音訊與遠端控制。",wall:"集中顯示所有已連線 Client 的即時縮圖。可選擇顯示器、調整圖塊大小,並在不建立新連線的情況下進入 Control。",control:"以完整解析度開啟所選 Client,並透過現有 Hub 工作階段傳送滑鼠與鍵盤輸入。","share-files":"瀏覽 Hub 檔案、傳送檔案到所選 Client,並管理共享資料夾與傳輸進度。",agents:"Hub 的 Codex Agent 會在 LiveDesk 權限與核准範圍內,對已連線的 Client 執行命令。"},es:{hub:"Usa este equipo como LiveDesk Hub. Hub es el centro de control unificado para conexiones Client, Wall, Control, archivos y Agents; púlsalo tras cambios de red para actualizar el acceso seguro.","switch-to-hub":"Cambia este equipo de Client a Hub. LiveDesk guarda el nuevo rol, reinicia el mismo entorno de escritorio y abre Wall; el equipo deja de compartirse como Client.",client:"Mantiene este equipo en modo Client para que sus pantallas, archivos, audio y control remoto sigan disponibles desde el Hub activo.",wall:"Muestra miniaturas en vivo de todos los Clients conectados. Elige pantalla y tamaño, o entra en Control sin abrir otra conexión.",control:"Abre el Client seleccionado a resolución completa y envía ratón y teclado por la sesión Hub existente.","share-files":"Explora archivos del Hub, envíalos a los Clients seleccionados y administra carpetas compartidas y transferencias.",agents:"El Codex Agent del Hub ejecuta comandos en los Clients conectados dentro de los permisos y aprobaciones de LiveDesk."},fr:{hub:"Utilise cet ordinateur comme LiveDesk Hub. Hub est le centre de contrôle unifié des connexions Client, de Wall, Control, des fichiers et des Agents ; appuyez après un changement réseau pour actualiser l’accès sécurisé.","switch-to-hub":"Bascule cet ordinateur de Client vers Hub. LiveDesk enregistre le nouveau rôle, redémarre le même environnement de bureau et ouvre Wall ; le partage Client s’arrête.",client:"Maintient cet ordinateur en mode Client afin que ses écrans, fichiers, sons et commandes à distance restent disponibles depuis le Hub actif.",wall:"Affiche les miniatures en direct de tous les Clients connectés. Choisissez l’écran et la taille, ou passez à Control sans nouvelle connexion.",control:"Ouvre le Client sélectionné en pleine résolution et transmet souris et clavier via la session Hub existante.","share-files":"Parcourez les fichiers du Hub, envoyez-les aux Clients sélectionnés et gérez dossiers partagés et transferts.",agents:"Le Codex Agent du Hub exécute des commandes sur les Clients connectés selon les permissions et approbations de LiveDesk."},de:{hub:"Verwendet diesen Computer als LiveDesk Hub. Hub ist die gemeinsame Steuerzentrale für Client-Verbindungen, Wall, Control, Dateien und Agents; nach Netzwerkänderungen aktualisiert ein Klick den sicheren Zugriff.","switch-to-hub":"Wechselt diesen Computer von Client zu Hub. LiveDesk speichert die neue Rolle, startet dieselbe Desktop-Laufzeit neu und öffnet Wall; die Client-Freigabe endet.",client:"Hält diesen Computer im Client-Modus, damit Bildschirme, Dateien, Audio und Fernsteuerung am aktiven Hub verfügbar bleiben.",wall:"Zeigt Live-Vorschaubilder aller verbundenen Clients. Display und Kachelgröße wählen oder ohne neue Verbindung zu Control wechseln.",control:"Öffnet den gewählten Client in voller Auflösung und sendet Maus- und Tastatureingaben über die bestehende Hub-Sitzung.","share-files":"Dateien auf dem Hub durchsuchen, an gewählte Clients senden sowie Freigaben und Übertragungen verwalten.",agents:"Der Codex Agent des Hubs führt Befehle auf verbundenen Clients innerhalb der LiveDesk-Berechtigungen und Freigaben aus."},"pt-BR":{hub:"Usa este computador como LiveDesk Hub. Hub é o centro de controle unificado para conexões Client, Wall, Control, arquivos e Agents; após mudanças de rede, pressione para atualizar o acesso seguro.","switch-to-hub":"Muda este computador de Client para Hub. O LiveDesk salva a nova função, reinicia o mesmo runtime de desktop e abre o Wall; o compartilhamento como Client é encerrado.",client:"Mantém este computador no modo Client para que telas, arquivos, áudio e controle remoto continuem disponíveis no Hub ativo.",wall:"Mostra miniaturas ao vivo de todos os Clients conectados. Escolha a tela e o tamanho ou entre em Control sem criar outra conexão.",control:"Abre o Client selecionado em resolução total e envia mouse e teclado pela sessão Hub existente.","share-files":"Navegue pelos arquivos do Hub, envie para Clients selecionados e gerencie pastas compartilhadas e transferências.",agents:"O Codex Agent do Hub executa comandos nos Clients conectados dentro das permissões e aprovações do LiveDesk."},it:{hub:"Usa questo computer come LiveDesk Hub. Hub è il centro di controllo unificato per connessioni Client, Wall, Control, file e Agents; dopo modifiche di rete, premilo per aggiornare l’accesso sicuro.","switch-to-hub":"Passa questo computer da Client a Hub. LiveDesk salva il nuovo ruolo, riavvia lo stesso runtime desktop e apre Wall; la condivisione come Client termina.",client:"Mantiene questo computer in modalità Client, rendendo schermi, file, audio e controllo remoto disponibili all’Hub attivo.",wall:"Mostra le anteprime live di tutti i Client connessi. Scegli display e dimensione oppure passa a Control senza una nuova connessione.",control:"Apre il Client selezionato a piena risoluzione e invia mouse e tastiera tramite la sessione Hub esistente.","share-files":"Esplora i file dell’Hub, inviali ai Client selezionati e gestisci cartelle condivise e trasferimenti.",agents:"Il Codex Agent dell’Hub esegue comandi sui Client connessi entro i permessi e le approvazioni di LiveDesk."},id:{hub:"Gunakan komputer ini sebagai LiveDesk Hub. Hub adalah pusat kendali terpadu untuk koneksi Client, Wall, Control, file, dan Agents; tekan setelah perubahan jaringan untuk memperbarui akses aman.","switch-to-hub":"Alihkan komputer ini dari Client menjadi Hub. LiveDesk menyimpan peran baru, memulai ulang runtime desktop yang sama, lalu membuka Wall; berbagi sebagai Client berhenti.",client:"Pertahankan komputer ini dalam mode Client agar layar, file, audio, dan kendali jarak jauh tetap tersedia bagi Hub aktif.",wall:"Tampilkan thumbnail live semua Client yang terhubung. Pilih layar dan ukuran tile atau masuk ke Control tanpa koneksi baru.",control:"Buka Client terpilih pada resolusi penuh dan kirim input mouse serta keyboard melalui sesi Hub yang ada.","share-files":"Jelajahi file Hub, kirim ke Client terpilih, serta kelola folder bersama dan progres transfer.",agents:"Codex Agent di Hub menjalankan perintah pada Client terhubung sesuai izin dan persetujuan LiveDesk."},vi:{hub:"Dùng máy tính này làm LiveDesk Hub. Hub là trung tâm điều khiển hợp nhất cho kết nối Client, Wall, Control, tệp và Agents; nhấn sau khi đổi mạng để làm mới quyền truy cập an toàn.","switch-to-hub":"Chuyển máy tính này từ Client sang Hub. LiveDesk lưu vai trò mới, khởi động lại cùng môi trường desktop và mở Wall; việc chia sẻ dưới dạng Client sẽ dừng.",client:"Giữ máy tính này ở chế độ Client để màn hình, tệp, âm thanh và điều khiển từ xa luôn sẵn sàng cho Hub đang hoạt động.",wall:"Hiển thị ảnh thu nhỏ trực tiếp của mọi Client đã kết nối. Chọn màn hình, cỡ ô hoặc vào Control mà không tạo kết nối mới.",control:"Mở Client đã chọn ở độ phân giải đầy đủ và gửi chuột, bàn phím qua phiên Hub hiện có.","share-files":"Duyệt tệp trên Hub, gửi tới Client đã chọn và quản lý thư mục chia sẻ cùng tiến trình truyền.",agents:"Codex Agent trên Hub chạy lệnh trên các Client đã kết nối trong phạm vi quyền và phê duyệt của LiveDesk."},th:{hub:"ใช้คอมพิวเตอร์เครื่องนี้เป็น LiveDesk Hub โดย Hub คือศูนย์ควบคุมรวมสำหรับการเชื่อมต่อ Client, Wall, Control, ไฟล์ และ Agents และกดหลังเปลี่ยนเครือข่ายเพื่อรีเฟรชการเข้าถึงที่ปลอดภัย","switch-to-hub":"เปลี่ยนคอมพิวเตอร์นี้จาก Client เป็น Hub โดย LiveDesk จะบันทึกบทบาทใหม่ รีสตาร์ต desktop runtime เดิม และเปิด Wall พร้อมหยุดแชร์ในฐานะ Client",client:"ให้คอมพิวเตอร์นี้อยู่ในโหมด Client เพื่อให้ Hub ที่ใช้งานเข้าถึงหน้าจอ ไฟล์ เสียง และการควบคุมระยะไกลได้ต่อเนื่อง",wall:"แสดงภาพสดแบบย่อของ Client ที่เชื่อมต่อทั้งหมด เลือกจอและขนาด tile หรือเข้า Control ได้โดยไม่เปิดการเชื่อมต่อใหม่",control:"เปิด Client ที่เลือกแบบความละเอียดเต็ม และส่งเมาส์กับคีย์บอร์ดผ่าน session ของ Hub ที่มีอยู่","share-files":"เรียกดูไฟล์บน Hub ส่งไปยัง Client ที่เลือก และจัดการโฟลเดอร์แชร์กับความคืบหน้าการโอน",agents:"Codex Agent บน Hub เรียกใช้คำสั่งบน Client ที่เชื่อมต่อภายใต้สิทธิ์และการอนุมัติของ LiveDesk"},hi:{hub:"इस कंप्यूटर को LiveDesk Hub के रूप में उपयोग करें। Hub, Client कनेक्शन, Wall, Control, फ़ाइल और Agents का एकीकृत नियंत्रण केंद्र है; नेटवर्क बदलने के बाद सुरक्षित पहुँच ताज़ा करने के लिए इसे दबाएँ।","switch-to-hub":"इस कंप्यूटर को Client से Hub में बदलता है। LiveDesk नई भूमिका सहेजता है, उसी desktop runtime को restart करके Wall खोलता है और Client sharing रोक देता है।",client:"इस कंप्यूटर को Client मोड में रखता है ताकि इसकी स्क्रीन, फ़ाइलें, ऑडियो और remote control सक्रिय Hub पर उपलब्ध रहें।",wall:"सभी जुड़े Clients के live thumbnail दिखाता है। स्क्रीन और tile आकार चुनें या नया connection खोले बिना Control में जाएँ।",control:"चुने हुए Client को पूर्ण resolution में खोलता है और मौजूदा Hub session से mouse तथा keyboard input भेजता है।","share-files":"Hub की फ़ाइलें देखें, चुने हुए Clients को भेजें और shared folders तथा transfer progress प्रबंधित करें।",agents:"Hub का Codex Agent LiveDesk permissions और approvals के भीतर जुड़े Clients पर commands चलाता है।"},ar:{hub:"استخدم هذا الكمبيوتر بوصفه LiveDesk Hub. يمثّل Hub مركز التحكم الموحّد لاتصالات Client وWall وControl والملفات وAgents؛ اضغط عليه بعد تغييرات الشبكة لتحديث الوصول الآمن.","switch-to-hub":"يحوّل هذا الكمبيوتر من Client إلى Hub. يحفظ LiveDesk الدور الجديد ويعيد تشغيل بيئة سطح المكتب نفسها ويفتح Wall، ويتوقف الجهاز عن المشاركة كـ Client.",client:"يبقي هذا الكمبيوتر في وضع Client لتظل شاشاته وملفاته وصوته والتحكم عن بعد متاحة من Hub النشط.",wall:"يعرض صورا حية مصغرة لكل Clients المتصلين. اختر الشاشة وحجم البلاطات أو انتقل إلى Control من دون اتصال جديد.",control:"يفتح Client المحدد بالدقة الكاملة ويرسل إدخال الماوس ولوحة المفاتيح عبر جلسة Hub الحالية.","share-files":"استعرض ملفات Hub وأرسلها إلى Clients المحددين وأدر المجلدات المشتركة وتقدم النقل.",agents:"يشغّل Codex Agent على Hub الأوامر في Clients المتصلين ضمن صلاحيات وموافقات LiveDesk."},tr:{hub:"Bu bilgisayarı LiveDesk Hub olarak kullanır. Hub; Client bağlantıları, Wall, Control, dosyalar ve Agents için birleşik kontrol merkezidir; ağ değişikliklerinden sonra güvenli erişimi yenilemek için basın.","switch-to-hub":"Bu bilgisayarı Client rolünden Hub rolüne geçirir. LiveDesk yeni rolü kaydeder, aynı masaüstü runtime’ını yeniden başlatıp Wall’u açar; Client paylaşımı durur.",client:"Bu bilgisayarı Client modunda tutar; ekran, dosya, ses ve uzaktan kontrol özellikleri etkin Hub tarafından kullanılabilir kalır.",wall:"Bağlı tüm Client ekranlarının canlı küçük görüntülerini gösterir. Ekran ve kutu boyutunu seçin veya yeni bağlantı açmadan Control’e geçin.",control:"Seçili Client’ı tam çözünürlükte açar ve mevcut Hub oturumu üzerinden fare ile klavye girdisi gönderir.","share-files":"Hub dosyalarını gezin, seçili Client’lara gönderin ve paylaşılan klasörlerle aktarım ilerlemesini yönetin.",agents:"Hub Codex Agent, bağlı Client’larda LiveDesk izinleri ve onayları kapsamında komut çalıştırır."}};function cu(e){const t=e?[e]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const n of t){const s=String(n||"").trim(),a=s.toLowerCase();if(!a)continue;if(a.startsWith("zh-tw")||a.startsWith("zh-hk"))return"zh-TW";if(a.startsWith("zh"))return"zh";if(a.startsWith("pt"))return"pt-BR";const i=a.split("-")[0];if(Zd[s])return s;if(Zd[i])return i}return"en"}function Vl(e,t){const n=cu(t);return Zd[n]?.[e]||hv[e]}function ep(e,t,n){return`${e}
3
3
  ${Vl(t,n)}`}const fv={eyebrow:"Change computer role",title:"Switch this computer to Hub?",description:"LiveDesk will stop sharing this computer as a Client, save the Hub role, restart the local runtime, and open Wall in this same window.",restartNotice:"Remote streams from this computer will end while LiveDesk restarts.",cancel:"Cancel",confirm:"Switch to Hub",closeLabel:"Close Hub switch confirmation"},_x={en:fv,ko:{eyebrow:"컴퓨터 역할 변경",title:"이 컴퓨터를 Hub로 전환하시겠습니까?",description:"이 컴퓨터의 Client 공유를 중지하고 Hub 역할을 저장한 뒤 로컬 런타임을 재시작하여 같은 창에서 Wall을 엽니다.",restartNotice:"LiveDesk가 재시작되는 동안 이 컴퓨터의 원격 스트림이 종료됩니다.",cancel:"취소",confirm:"Hub로 전환",closeLabel:"Hub 전환 확인 닫기"},ja:{eyebrow:"コンピューターの役割を変更",title:"このコンピューターを Hub に切り替えますか?",description:"このコンピューターの Client 共有を停止し、Hub の役割を保存してローカルランタイムを再起動し、同じウィンドウで Wall を開きます。",restartNotice:"LiveDesk の再起動中、このコンピューターのリモートストリームは終了します。",cancel:"キャンセル",confirm:"Hub に切り替える",closeLabel:"Hub 切り替え確認を閉じる"},zh:{eyebrow:"更改电脑角色",title:"将此电脑切换为 Hub?",description:"LiveDesk 将停止此电脑的 Client 共享,保存 Hub 角色,重启本地运行时,并在同一窗口中打开 Wall。",restartNotice:"LiveDesk 重启期间,此电脑的远程流将会结束。",cancel:"取消",confirm:"切换为 Hub",closeLabel:"关闭 Hub 切换确认"},"zh-TW":{eyebrow:"變更電腦角色",title:"要將此電腦切換為 Hub 嗎?",description:"LiveDesk 將停止此電腦的 Client 分享、儲存 Hub 角色、重新啟動本機執行階段,並在同一視窗中開啟 Wall。",restartNotice:"LiveDesk 重新啟動期間,此電腦的遠端串流將會結束。",cancel:"取消",confirm:"切換為 Hub",closeLabel:"關閉 Hub 切換確認"},es:{eyebrow:"Cambiar función del equipo",title:"¿Cambiar este equipo a Hub?",description:"LiveDesk dejará de compartir este equipo como Client, guardará la función Hub, reiniciará el entorno local y abrirá Wall en esta misma ventana.",restartNotice:"Los streams remotos de este equipo terminarán mientras LiveDesk se reinicia.",cancel:"Cancelar",confirm:"Cambiar a Hub",closeLabel:"Cerrar confirmación de cambio a Hub"},fr:{eyebrow:"Changer le rôle de l’ordinateur",title:"Basculer cet ordinateur vers Hub ?",description:"LiveDesk arrêtera le partage Client de cet ordinateur, enregistrera le rôle Hub, redémarrera le runtime local et ouvrira Wall dans cette même fenêtre.",restartNotice:"Les flux distants de cet ordinateur prendront fin pendant le redémarrage de LiveDesk.",cancel:"Annuler",confirm:"Basculer vers Hub",closeLabel:"Fermer la confirmation de bascule vers Hub"},de:{eyebrow:"Computerrolle ändern",title:"Diesen Computer auf Hub umstellen?",description:"LiveDesk beendet die Client-Freigabe dieses Computers, speichert die Hub-Rolle, startet die lokale Laufzeit neu und öffnet Wall im selben Fenster.",restartNotice:"Die Remote-Streams dieses Computers enden während des LiveDesk-Neustarts.",cancel:"Abbrechen",confirm:"Auf Hub umstellen",closeLabel:"Bestätigung für Hub-Wechsel schließen"},"pt-BR":{eyebrow:"Alterar função do computador",title:"Mudar este computador para Hub?",description:"O LiveDesk interromperá o compartilhamento deste computador como Client, salvará a função Hub, reiniciará o runtime local e abrirá o Wall nesta mesma janela.",restartNotice:"Os streams remotos deste computador serão encerrados enquanto o LiveDesk reinicia.",cancel:"Cancelar",confirm:"Mudar para Hub",closeLabel:"Fechar confirmação de mudança para Hub"},it:{eyebrow:"Cambia ruolo del computer",title:"Passare questo computer a Hub?",description:"LiveDesk interromperà la condivisione Client di questo computer, salverà il ruolo Hub, riavvierà il runtime locale e aprirà Wall nella stessa finestra.",restartNotice:"Gli stream remoti di questo computer termineranno durante il riavvio di LiveDesk.",cancel:"Annulla",confirm:"Passa a Hub",closeLabel:"Chiudi la conferma del passaggio a Hub"},id:{eyebrow:"Ubah peran komputer",title:"Alihkan komputer ini menjadi Hub?",description:"LiveDesk akan menghentikan berbagi komputer ini sebagai Client, menyimpan peran Hub, memulai ulang runtime lokal, lalu membuka Wall di jendela yang sama.",restartNotice:"Stream jarak jauh dari komputer ini akan berakhir saat LiveDesk dimulai ulang.",cancel:"Batal",confirm:"Alihkan ke Hub",closeLabel:"Tutup konfirmasi peralihan Hub"},vi:{eyebrow:"Đổi vai trò máy tính",title:"Chuyển máy tính này thành Hub?",description:"LiveDesk sẽ dừng chia sẻ máy tính này dưới dạng Client, lưu vai trò Hub, khởi động lại runtime cục bộ và mở Wall trong cùng cửa sổ.",restartNotice:"Các luồng từ xa của máy tính này sẽ kết thúc trong khi LiveDesk khởi động lại.",cancel:"Hủy",confirm:"Chuyển sang Hub",closeLabel:"Đóng xác nhận chuyển sang Hub"},th:{eyebrow:"เปลี่ยนบทบาทคอมพิวเตอร์",title:"เปลี่ยนคอมพิวเตอร์เครื่องนี้เป็น Hub หรือไม่",description:"LiveDesk จะหยุดแชร์คอมพิวเตอร์เครื่องนี้ในฐานะ Client บันทึกบทบาท Hub รีสตาร์ทรันไทม์ภายในเครื่อง และเปิด Wall ในหน้าต่างเดิม",restartNotice:"สตรีมระยะไกลจากคอมพิวเตอร์เครื่องนี้จะสิ้นสุดลงระหว่างที่ LiveDesk รีสตาร์ท",cancel:"ยกเลิก",confirm:"เปลี่ยนเป็น Hub",closeLabel:"ปิดการยืนยันการเปลี่ยนเป็น Hub"},hi:{eyebrow:"कंप्यूटर की भूमिका बदलें",title:"इस कंप्यूटर को Hub में बदलें?",description:"LiveDesk इस कंप्यूटर की Client साझेदारी बंद करेगा, Hub भूमिका सहेजेगा, स्थानीय रनटाइम पुनः आरंभ करेगा और इसी विंडो में Wall खोलेगा।",restartNotice:"LiveDesk के पुनः आरंभ होने के दौरान इस कंप्यूटर की रिमोट स्ट्रीम समाप्त हो जाएँगी।",cancel:"रद्द करें",confirm:"Hub में बदलें",closeLabel:"Hub परिवर्तन की पुष्टि बंद करें"},ar:{eyebrow:"تغيير دور الكمبيوتر",title:"هل تريد تحويل هذا الكمبيوتر إلى Hub؟",description:"سيوقف LiveDesk مشاركة هذا الكمبيوتر كـ Client، ويحفظ دور Hub، ويعيد تشغيل وقت التشغيل المحلي، ثم يفتح Wall في النافذة نفسها.",restartNotice:"ستنتهي التدفقات البعيدة من هذا الكمبيوتر أثناء إعادة تشغيل LiveDesk.",cancel:"إلغاء",confirm:"التحويل إلى Hub",closeLabel:"إغلاق تأكيد التحويل إلى Hub"},tr:{eyebrow:"Bilgisayar rolünü değiştir",title:"Bu bilgisayar Hub rolüne geçirilsin mi?",description:"LiveDesk bu bilgisayarın Client paylaşımını durdurur, Hub rolünü kaydeder, yerel çalışma zamanını yeniden başlatır ve Wall’u aynı pencerede açar.",restartNotice:"LiveDesk yeniden başlatılırken bu bilgisayarın uzak akışları sona erer.",cancel:"İptal",confirm:"Hub’a geçir",closeLabel:"Hub geçişi onayını kapat"}},gv={eyebrow:"Computer role",title:"Use this computer as Hub?",description:"Hub connects to and manages Client computers.",restartNotice:"If another computer is Hub, this computer will become the new Hub.",cancel:"Cancel",confirm:"Use as Hub",closeLabel:"Close Hub confirmation"},$x={en:gv,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function Ox(e){const t=cu(e);return _x[t]||fv}function Bx(e){const t=cu(e);return $x[t]||gv}function Hx(e=[]){return[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean))]}function Wx(e=[],t=new Set){return e.find(n=>!t.has(n))||""}const zx=[{id:"docs",label:"Doc",icon:ql},{id:"support",label:"Support",icon:Oo},{id:"pricing",label:"Pricing",icon:Bo},{id:"settings",label:"Settings",icon:Ul}],Fh=[0,1e3,2e3,5e3,1e4,2e4,3e4],qx=15e3;function Ux(e=""){const t=e.trim().replace(/\/+$/,"");return t||(typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179")}async function Ea(e,t=!1){const n=t?"":sessionStorage.getItem("livedesk.client.csrf");if(n)return n;const s=await fetch(`${e}/api/runtime/status`,{cache:"no-store"}),a=await s.json().catch(()=>({}));if(!s.ok)throw new Error(a.error||`Client runtime returned HTTP ${s.status}.`);const i=String(a.csrfToken||"");return i&&sessionStorage.setItem("livedesk.client.csrf",i),i}function tp(e){return`${Math.max(0,Math.min(100,Number(e||0))).toFixed(0)}%`}function wd(e){return Number.isFinite(e)?`${Math.max(0,Math.min(100,Number(e))).toFixed(0)}%`:"—"}function vv(e){return Number.isFinite(e)?tp(Number(e)):"0%"}function Ha(e){const t=Number(e);return!Number.isFinite(t)||t<0?"—":t>=1024**4?`${(t/1024**4).toFixed(t>=10*1024**4?0:1)} TB`:t>=1024**3?`${(t/1024**3).toFixed(t>=10*1024**3?0:1)} GB`:`${(t/1024**2).toFixed(0)} MB`}function Dh(e){const t=Math.max(0,Number(e||0));return t>=1024**3?`${(t/1024**3).toFixed(1)} GB/s`:t>=1024**2?`${(t/1024**2).toFixed(1)} MB/s`:t>=1024?`${(t/1024).toFixed(1)} KB/s`:`${t.toFixed(0)} B/s`}function Vx(e,t){const n=Number(e||0)/1073741824,s=Number(t||0)/1024**3;return s>0?`${n.toFixed(1)} / ${s.toFixed(1)} GB`:"Checking..."}function Gx(e,t){return!Number.isFinite(t)||Number(t)<=0?"Dedicated memory unavailable":Number.isFinite(e)?`${Ha(e)} / ${Ha(t)}`:`${Ha(t)} available`}function Kx(e){const t=Math.max(0,Math.floor(Number(e||0)/60)),n=Math.floor(t/1440),s=Math.floor(t%1440/60),a=t%60;return n>0?`${n}d ${s}h`:s>0?`${s}h ${a}m`:`${a}m`}function dl({icon:e,label:t,value:n,detail:s,percent:a}){return r.jsxs("article",{className:"client-resource-metric",children:[r.jsxs("div",{className:"client-resource-metric-head",children:[r.jsx(e,{size:17}),r.jsx("span",{children:t}),r.jsx("strong",{children:n})]}),r.jsx("small",{title:s,children:s}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:vv(a)}})})]})}function Qx(e,t){const n=e?.user.user_metadata||{},s=n.full_name||n.name||n.preferred_username||e?.user.email||e?.user.id||t?.userName||t?.auth?.name||t?.userEmail||t?.userId||"Account";return String(s).trim()||"Account"}function Yx(e,t){const n=e?.user.user_metadata||{};return Hx([n.avatar_url,n.picture,t?.userAvatarUrl,t?.auth?.avatarUrl])}function Xx({page:e,status:t}){const s={docs:{label:"DOC",title:"Using this computer",body:"This computer connects to its assigned Hub automatically. Keep LiveDesk running and manage screens, files, and remote control from the Hub."},pricing:{label:"PRICING",title:"LiveDesk plans",body:"Plans are based on how many computers the Hub manages. This Client computer does not need a separate subscription or setup."},settings:{label:"SETTINGS",title:"Computer preferences",body:"LiveDesk keeps the verified sign-in on this computer and reconnects to the assigned Hub automatically."}}[e];return r.jsxs("section",{className:"client-service-page",children:[r.jsx("span",{className:"client-unified-section-label",children:s.label}),r.jsx("h2",{children:s.title}),r.jsx("p",{children:s.body}),r.jsxs("div",{className:"client-service-page-card",children:[e==="docs"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Automatic connection"}),r.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),e==="pricing"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"One plan, managed at the Hub"}),r.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),e==="settings"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Saved sign-in"}),r.jsx("span",{children:t?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]}),e==="settings"&&r.jsx(pv,{})]})}function Jx({session:e,status:t,pin:n,error:s,roleChangeMessage:a,videoAccelerationBusy:i,slotInput:c,slotBusy:u,onSignIn:d,onPinChange:p,onSubmitPin:h,onSlotInputChange:m,onSaveSlot:g,onEnableVideoAcceleration:w}){const b=t?.connectionState==="connected",y=t?.videoAcceleration,k=i||y?.busy||y?.state==="installing",A=y?.ready?`${y.encoder||"H.264"} · ${y.driver||"VAAPI"}`:k?"Setting up…":y?.message||"Setup available",C=t?.system?.memoryTotalBytes?Number(t.system.memoryUsedBytes||0)/t.system.memoryTotalBytes*100:0,N=t?.system?.gpus||[],E=N.find(K=>Number.isFinite(K.usagePercent)||Number.isFinite(K.memoryTotalBytes))||N[0],I=Number.isFinite(E?.usagePercent)?Number(E?.usagePercent):null,F=Number.isFinite(E?.memoryTotalBytes)&&Number(E?.memoryTotalBytes)>0&&Number.isFinite(E?.memoryUsedBytes)?Number(E?.memoryUsedBytes)/Number(E?.memoryTotalBytes)*100:null,M=t?.system?.disks||[],$=t?.system?.network,q=!!$?.sampledAt,T=$?.interfaces||[],D=[...new Set(T.map(K=>K.name).filter(Boolean))],H=T.map(K=>K.address).filter(Boolean);return r.jsxs("section",{className:"client-home-page",children:[r.jsxs("header",{className:"client-home-heading",children:[r.jsxs("div",{children:[r.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),r.jsx("h2",{children:t?.deviceName||"This Computer"})]}),r.jsxs("span",{className:`client-unified-role-chip ${b?"connected":""}`,children:[r.jsx(fn,{size:15})," ",b?"Online":"Connecting"]})]}),r.jsxs("div",{className:"client-home-layout",children:[r.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[r.jsxs("div",{className:"client-main-surface-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),r.jsx("strong",{children:"Hardware at a glance"})]}),r.jsxs("small",{children:[r.jsx(ev,{size:14})," Uptime ",Kx(t?.system?.uptimeSeconds)]})]}),r.jsxs("div",{className:"client-system-dashboard",children:[r.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),r.jsx("strong",{children:"Live resources"})]}),r.jsx("small",{children:"Live updates"})]}),r.jsxs("div",{className:"client-live-metrics",children:[r.jsx(dl,{icon:kh,label:"CPU",value:tp(t?.system?.cpuUsagePercent),detail:t?.system?.cpuLogicalCores?`${t.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:t?.system?.cpuUsagePercent}),r.jsx(dl,{icon:Py,label:"Memory",value:tp(C),detail:Vx(t?.system?.memoryUsedBytes,t?.system?.memoryTotalBytes),percent:C}),r.jsx(dl,{icon:Ty,label:"GPU",value:wd(I),detail:E?.name||(t?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:I}),r.jsx(dl,{icon:is,label:"VRAM",value:wd(F),detail:Gx(E?.memoryUsedBytes,E?.memoryTotalBytes),percent:F})]})]}),r.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),r.jsx("strong",{children:"Local drives"})]}),r.jsx("small",{children:M.length>0?`${M.length} ${M.length===1?"drive":"drives"}`:t?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),r.jsxs("div",{className:"client-disk-list",children:[M.map(K=>r.jsxs("article",{className:"client-disk-row",children:[r.jsxs("div",{className:"client-disk-row-head",children:[r.jsxs("span",{children:[r.jsx(Ba,{size:16}),r.jsx("strong",{children:K.mount||"Disk"}),r.jsx("small",{children:K.name||"Local disk"})]}),r.jsx("strong",{children:wd(K.usedPercent)})]}),r.jsxs("small",{children:[Ha(K.freeBytes)," free · ",Ha(K.totalBytes)," total"]}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:vv(K.usedPercent)}})})]},`${K.mount}-${K.name||""}`)),M.length===0&&r.jsxs("div",{className:"client-disk-empty",children:[r.jsx(Ba,{size:18}),r.jsx("span",{children:t?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),r.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),r.jsx("strong",{children:"Live traffic"})]}),r.jsx("small",{children:D.length>0?D.join(", "):"Detecting adapter"})]}),r.jsxs("div",{className:"client-network-live",children:[r.jsxs("div",{className:"client-network-adapter",children:[r.jsx(iu,{size:18}),r.jsxs("span",{children:[r.jsx("strong",{children:D.join(", ")||"Network"}),r.jsx("small",{children:H.join(" / ")||"Checking active connection"})]})]}),r.jsxs("div",{className:"client-network-rate download",children:[r.jsx(Iy,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Receive"}),r.jsx("strong",{children:Dh(q?$?.receiveBytesPerSecond:void 0)})]})]}),r.jsxs("div",{className:"client-network-rate upload",children:[r.jsx(jy,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Send"}),r.jsx("strong",{children:Dh(q?$?.sendBytesPerSecond:void 0)})]})]}),r.jsx("small",{className:"client-network-total",children:q?`Total ${Ha($?.receivedBytes)} received / ${Ha($?.sentBytes)} sent`:"Traffic has not been measured yet."})]})]})]})]}),r.jsxs("aside",{className:"client-connection-panel",children:[r.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),r.jsx("h3",{children:b?"Connected to the Hub":t?.authenticated?"Finding the Hub":"Connect this computer"}),b?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),r.jsxs("div",{className:"client-service-status-list",children:[r.jsxs("div",{children:[r.jsx(fn,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Screen sharing"}),r.jsx("small",{children:t?.permissions?.screenCapture?"Active":"Waiting"})]})]}),r.jsxs("div",{children:[r.jsx(sn,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Remote control"}),r.jsx("small",{children:t?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(Oi,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"File delivery"}),r.jsx("small",{children:t?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(Bi,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Computer audio"}),r.jsx("small",{children:t?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:t?.authenticated?"LiveDesk is checking the registered Hub endpoints. A temporary Hub PIN can be used as a fallback.":"Sign in once on this computer. LiveDesk saves the verified session, finds the Hub, and starts screen sharing automatically."}),!e&&!t?.authenticated?r.jsxs("button",{className:"client-unified-primary",type:"button",onClick:d,children:[r.jsx(qs,{size:16})," Sign in with Google"]}):r.jsxs("p",{className:"client-unified-success",children:[r.jsx(_n,{size:16})," Signed in as ",e?.user.email||e?.user.id||t?.userEmail||t?.userId||"saved account"]}),r.jsxs("div",{className:"client-unified-pin-row",children:[r.jsx(Ey,{size:16}),r.jsx("input",{value:n,onChange:K=>p(K.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),r.jsx("button",{className:"client-unified-secondary",type:"button",onClick:h,disabled:n.length!==6,children:"Connect"})]})]}),y?.supported&&r.jsxs("div",{className:`client-video-acceleration state-${y.ready?"ready":y.state||"setup-required"}`,children:[r.jsx(kh,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Hardware video"}),r.jsx("small",{children:A})]}),!y.ready&&y.canInstall&&r.jsx("button",{type:"button",onClick:w,disabled:k,title:"Install and verify Linux FFmpeg hardware video support",children:k?"Setting up":"Enable"})]}),(s||t?.lastError)&&r.jsxs("p",{className:"client-unified-error",role:"alert",children:[r.jsx(Zg,{size:15})," ",s||t?.lastError]}),a&&r.jsx("p",{className:"client-unified-success",children:a}),r.jsxs("div",{className:"client-slot-setting",children:[r.jsxs("label",{htmlFor:"client-slot-number",children:[r.jsx("span",{children:"Slot"}),r.jsx("input",{id:"client-slot-number",value:c,onChange:K=>m(K.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!b||u})]}),r.jsxs("button",{type:"button",onClick:g,disabled:!b||u||!c,"aria-label":"Save slot number",title:"Save slot number",children:[r.jsx(Ul,{size:17}),r.jsx("span",{children:u?"Saving":"Set"})]})]})]})]})]})}function Zx({runtimeBaseUrl:e=""}){const[t,n]=o.useState(null),[s,a]=o.useState(null),[i,c]=o.useState(!1),[u,d]=o.useState(""),[p,h]=o.useState(""),[m,g]=o.useState(""),[w,b]=o.useState(!1),[y,k]=o.useState(!1),[A,C]=o.useState(""),[N,E]=o.useState(!1),[I,F]=o.useState(null),[M,$]=o.useState(!1),[q,T]=o.useState("computer"),[D,H]=o.useState(!1),K=o.useRef(null),z=o.useRef(null),W=o.useRef(!1),ce=o.useRef(null),j=o.useRef(null),ne=o.useRef(!1),ue=o.useRef(!1),U=o.useRef(0),ge=o.useRef(!1),re=o.useMemo(()=>Ux(e),[e]),we=o.useMemo(()=>Qx(s,t),[s,t]),Me=o.useMemo(()=>Yx(s,t),[s,t]),Pe=JSON.stringify(Me),[Te,Ce]=o.useState(()=>new Set),Y=Wx(Me,Te),Ne=we.slice(0,1).toUpperCase()||"L";o.useEffect(()=>{Ce(new Set)},[Pe]);const De=o.useCallback(oe=>{Ce(me=>{if(!oe||me.has(oe))return me;const be=new Set(me);return be.add(oe),be})},[]),je=o.useCallback(async()=>{if(h(""),window.liveDesk?.auth?.signInWithGoogle){const oe=await window.liveDesk.auth.signInWithGoogle();return oe?.ok===!1?(h(oe.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${re}/auth/google`),!0},[re]),Je=o.useCallback(async()=>{ue.current||(ue.current=!0,h("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await ht.auth.signOut({scope:"local"}).catch(()=>{}),a(null),await je()||(ue.current=!1))},[je]),ee=o.useCallback(async oe=>{const me=Eh(oe);if(me)throw new Error(me);if(W.current)return!1;W.current=!0;try{const be=await window.liveDesk?.auth?.persistSession?.(oe);if(be?.ok===!1)throw new Error(be.error||"LiveDesk could not validate the desktop session.");for(let Z=0;Z<2;Z+=1){const V=await Ea(re,Z>0),se=await fetch(`${re}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":V},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:oe.access_token,refreshToken:oe.refresh_token,expiresAt:oe.expires_at,user:{id:oe.user.id,email:oe.user.email}})}),R=await se.json().catch(()=>({}));if(se.status===403&&Z===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!se.ok)throw new Error(R.error||`Client runtime returned HTTP ${se.status}.`);return h(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{W.current=!1}},[re]),te=o.useCallback(()=>{const oe=ce.current;if(oe)return oe;const me=(async()=>{try{const be=await fetch(`${re}/api/client/status`,{cache:"no-store",signal:AbortSignal.timeout(1500)}),Z=await be.json().catch(()=>({}));if(!be.ok)throw new Error(Z.error||`Client runtime returned HTTP ${be.status}.`);if(Z.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",Z.csrfToken),String(Z.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");n(Z)}catch(be){h(be instanceof Error?be.message:String(be))}})();return ce.current=me,me.finally(()=>{ce.current===me&&(ce.current=null)}),me},[re]),pe=o.useCallback(()=>{const oe=j.current;if(oe)return oe;const me=(async()=>{const be=await fetch(`${re}/api/client/diagnostics`,{cache:"no-store",signal:AbortSignal.timeout(8e3)}),Z=await be.json().catch(()=>({}));if(!be.ok)throw new Error(Z.error||`Client diagnostics returned HTTP ${be.status}.`);if(String(Z.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");n(Z)})();return j.current=me,me.finally(()=>{j.current===me&&(j.current=null)}),me},[re]);o.useEffect(()=>{let oe=!1,me=null;const be=async()=>{await te(),oe||(me=window.setTimeout(()=>{be()},2e3))};return be(),()=>{oe=!0,me!==null&&window.clearTimeout(me)}},[te]),o.useEffect(()=>{if(q!=="computer")return;let oe=!1,me=null;const be=()=>{oe||(me=window.setTimeout(()=>{Z()},qx))},Z=async()=>{document.visibilityState==="visible"&&await pe().catch(()=>{}),be()},V=()=>{document.visibilityState==="visible"&&(me!==null&&(window.clearTimeout(me),me=null),Z())};return document.addEventListener("visibilitychange",V),Z(),()=>{oe=!0,document.removeEventListener("visibilitychange",V),me!==null&&window.clearTimeout(me)}},[q,pe]),o.useEffect(()=>{if(ge.current)return;const oe=Number(t?.slotNumber||0);C(oe>0?String(oe):"")},[t?.slotNumber]),o.useEffect(()=>{if(!I)return;const oe=window.setTimeout(()=>F(null),5e3);return()=>window.clearTimeout(oe)},[I]);const le=o.useCallback(async()=>{const oe=Date.now();if(!(!t?.authenticated||t.connectionState==="connected"||!["waiting","reconnecting"].includes(String(t.agent?.state||""))||oe-U.current<4e3)){U.current=oe;try{const me=await fetch(`${re}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Ea(re)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!me.ok)throw new Error(`Client reconnect returned HTTP ${me.status}.`);await te()}catch(me){h(me instanceof Error?me.message:String(me))}}},[re,te,t]);o.useEffect(()=>{const oe=()=>{le()},me=()=>{le()},be=()=>{document.visibilityState==="visible"&&le()};return window.addEventListener("online",oe),window.addEventListener("focus",me),document.addEventListener("visibilitychange",be),()=>{window.removeEventListener("online",oe),window.removeEventListener("focus",me),document.removeEventListener("visibilitychange",be)}},[le]),o.useEffect(()=>{if(!i||!t||!s?.access_token||t.authenticated)return;if(Eh(s)==="refresh-token-required"){Je().catch(V=>{ue.current=!1,h(V instanceof Error?V.message:String(V))});return}let oe=!1,me,be=0;const Z=async()=>{if(oe)return;try{const se=await ee(s);if(await te(),se)return}catch(se){h(se instanceof Error?se.message:String(se))}if(oe)return;const V=Fh[Math.min(be,Fh.length-1)];be+=1,me=window.setTimeout(()=>{Z()},V)};return Z(),()=>{oe=!0,me!==void 0&&window.clearTimeout(me)}},[i,te,Je,s,t,ee]),o.useEffect(()=>{const oe=new URLSearchParams(window.location.search),me=oe.get("auth_error");if(!me)return;h(me),oe.delete("auth_error");const be=oe.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${be?`?${be}`:""}${window.location.hash}`)},[]),o.useEffect(()=>{let oe=!0;if(!window.liveDesk?.auth)return a(null),c(!0),te(),()=>{oe=!1};const me=window.liveDesk?.auth?.onComplete?.(Z=>{Z.ok&&Z.session?ht.auth.setSession(Z.session).catch(V=>h(V instanceof Error?V.message:String(V))):Z.ok&&Z.signedOut?(a(null),c(!0),ht.auth.signOut({scope:"local"})):Z.error&&h(Z.error)});(async()=>{try{const Z=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await ht.auth.getSession();if(!oe)return;const V=mv(Z);a(V),te()}catch(Z){oe&&h(Z instanceof Error?Z.message:String(Z))}finally{oe&&c(!0)}})();const{data:be}=ht.auth.onAuthStateChange((Z,V)=>{if(oe){if(!V&&window.liveDesk?.auth){c(!0);return}a(V),c(!0),te()}});return()=>{oe=!1,me?.(),be.subscription.unsubscribe()}},[te]),o.useEffect(()=>{if(!i||!t||ne.current||ue.current||s||t.authenticated)return;const oe=new URLSearchParams(window.location.search);if(!oe.has("livedesk_launch"))return;ne.current=!0,oe.delete("livedesk_launch");const me=oe.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${me?`?${me}`:""}${window.location.hash}`),je().catch(be=>h(be instanceof Error?be.message:String(be)))},[i,s,je,t]);const J=async()=>{H(!1),window.liveDesk?.auth?.signOut?(await ht.auth.signOut(),(await window.liveDesk.auth.signOut())?.runtimeCleared===!1&&h("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${re}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await Ea(re)}}).catch(()=>{}),a(null),await te()};o.useEffect(()=>{if(!D)return;const oe=be=>{be.target instanceof Element&&be.target.closest(".account-popover, .rail-account")||H(!1)},me=be=>{be.key==="Escape"&&H(!1)};return window.addEventListener("pointerdown",oe),window.addEventListener("keydown",me),()=>{window.removeEventListener("pointerdown",oe),window.removeEventListener("keydown",me)}},[D]);const xe=o.useCallback((oe=!0)=>{w||($(!1),oe&&window.requestAnimationFrame(()=>z.current?.focus()))},[w]),de=o.useCallback(()=>{w||!t?.authenticated||(z.current=document.activeElement instanceof HTMLElement?document.activeElement:null,g(""),$(!0))},[w,t?.authenticated]);o.useEffect(()=>{if(!M)return;const oe=window.requestAnimationFrame(()=>K.current?.focus()),me=Z=>{Z.target instanceof Element&&Z.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||xe(!1)},be=Z=>{Z.key==="Escape"&&xe()};return window.addEventListener("pointerdown",me),window.addEventListener("keydown",be),()=>{window.cancelAnimationFrame(oe),window.removeEventListener("pointerdown",me),window.removeEventListener("keydown",be)}},[xe,M]);const Le=async()=>{h("");try{const oe=await fetch(`${re}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Ea(re)},body:JSON.stringify({pin:u})}),me=await oe.json().catch(()=>({}));if(!oe.ok||me?.ok===!1)throw new Error(me?.error||"PIN could not be accepted.");d(""),await te()}catch(oe){h(oe instanceof Error?oe.message:String(oe))}},st=async()=>{$(!1),b(!0),g(""),h("");try{const oe=await fetch(`${re}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Ea(re)},body:JSON.stringify({role:"hub"})}),me=await oe.json().catch(()=>({}));if(!oe.ok||me?.ok===!1)throw new Error(me?.error||`Role change failed with HTTP ${oe.status}.`);g("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const be=Number(t?.runtimePid||0);await Vg({baseUrl:re,targetRole:"hub",previousRuntimePid:be,allowedStates:["running"]}),window.location.reload()}catch(oe){h(oe instanceof Error?oe.message:String(oe)),b(!1)}},P=async()=>{if(N)return;const oe=Number(A);if(!Number.isInteger(oe)||oe<1||oe>999){F({kind:"error",message:"Enter a slot number from 1 to 999."});return}E(!0),F(null);try{const me=await fetch(`${re}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Ea(re)},body:JSON.stringify({slotNumber:oe})}),be=await me.json().catch(()=>({}));if(!me.ok||be.ok===!1){if(be.error==="slot-taken"){const Z=be.conflict?.deviceName||be.conflict?.hostname||be.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(oe).padStart(3,"0")} is already used by ${Z}.`)}throw new Error(be.error||`Slot update failed with HTTP ${me.status}.`)}ge.current=!1,C(String(oe)),n(be),F({kind:"success",message:`Slot ${String(oe).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(me){F({kind:"error",message:me instanceof Error?me.message:String(me)})}finally{E(!1),await te()}},Se=async()=>{if(!y){k(!0),h("");try{const oe=await fetch(`${re}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Ea(re)},body:JSON.stringify({confirm:!0})}),me=await oe.json().catch(()=>({}));if(n(me),!oe.ok||me.videoAcceleration?.ready!==!0)throw new Error(me.videoAcceleration?.error||me.error||"Linux hardware video setup did not complete.")}catch(oe){h(oe instanceof Error?oe.message:String(oe))}finally{k(!1),await te()}}},Ee=!!(t?.authenticated||s),ct=o.useMemo(()=>cu(),[]),$e=Vl("switch-to-hub",ct),qe=Vl("client",ct),ze=Ox(ct);return r.jsxs("main",{className:"app-shell client-unified-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(Ug,{size:25})}),r.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:r.jsxs("div",{className:"client-main-tool-slot",children:[r.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:de,disabled:w||!t?.authenticated,"aria-busy":w,"aria-expanded":M,"aria-haspopup":"dialog","aria-controls":M?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${$e}`,"data-tooltip":M?void 0:ep("Hub","switch-to-hub",ct),children:[r.jsx(is,{size:19}),r.jsx("span",{children:w?"Switching…":"Hub"})]}),r.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${q==="computer"?"active":""}`,type:"button",onClick:()=>T("computer"),"aria-current":q==="computer"?"page":void 0,"aria-label":`Client. ${qe}`,"data-tooltip":ep("Client","client",ct),children:[r.jsx(fn,{size:19}),r.jsx("span",{children:"Client"})]})]})}),r.jsxs("div",{className:"rail-footer",children:[zx.map(oe=>{const me=oe.icon;return r.jsxs("button",{className:`rail-tool compact ${q===oe.id?"active":""}`,type:"button",onClick:()=>T(oe.id),title:oe.label,children:[r.jsx(me,{size:18}),r.jsx("span",{children:oe.label})]},oe.id)}),r.jsxs("button",{className:`rail-account ${Ee?"signed-in":""}`,type:"button",onClick:()=>H(oe=>!oe),"aria-expanded":D,"aria-haspopup":"dialog",title:Ee?"Account":"Sign in",children:[Ee&&Y?r.jsx("img",{src:Y,alt:we,referrerPolicy:"no-referrer",onError:()=>De(Y)},Y):Ee?r.jsx("span",{className:"avatar-fallback",children:Ne}):r.jsx(qs,{size:18}),r.jsx("span",{children:Ee?"Account":"Sign in"})]})]})]}),M&&r.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(is,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:ze.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>xe(),"aria-label":ze.closeLabel,children:r.jsx(kn,{size:17})})]}),r.jsx("h2",{id:"client-hub-switch-title",children:ze.title}),r.jsx("p",{id:"client-hub-switch-description",children:ze.description}),r.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[r.jsx(sn,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:ze.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>xe(),children:ze.cancel}),r.jsxs("button",{ref:K,className:"primary",type:"button",onClick:()=>{st()},disabled:w||!t?.authenticated,children:[r.jsx(is,{size:16}),ze.confirm]})]})]}),D&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:Ee&&Y?r.jsx("img",{src:Y,alt:we,referrerPolicy:"no-referrer",onError:()=>De(Y)},Y):Ee?r.jsx("span",{children:Ne}):r.jsx(qs,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:Ee?we:"Account"}),r.jsx("p",{children:s?.user.email||t?.userEmail||t?.userId||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:s?.user.email||t?.userEmail||t?.userId||"Not signed in"}),r.jsx("dt",{children:"Runtime"}),r.jsx("dd",{children:t?"Local app ready":"Checking local app"}),r.jsx("dt",{children:"Session"}),r.jsx("dd",{children:t?.auth?.persisted?"Saved on this computer":Ee?"Active for this run":"Not saved"}),r.jsx("dt",{children:"Role"}),r.jsx("dd",{children:"Client"})]}),Ee?r.jsxs("button",{className:"account-popover-action",onClick:()=>{J()},type:"button",children:[r.jsx(Jg,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:()=>{H(!1),je()},type:"button",children:[r.jsx(qs,{size:16}),"Sign in with Google"]})]}),r.jsx("section",{className:"desk-stage client-unified-stage",children:q==="support"?r.jsx("section",{className:"client-unified-page",children:r.jsx(dv,{session:s,currentProductKey:"livedesk",appVersion:t?.appVersion||"",onSignIn:()=>{je()}})}):q!=="computer"?r.jsx("section",{className:"client-unified-page",children:r.jsx(Xx,{page:q,status:t})}):r.jsx(Jx,{session:s,status:t,pin:u,error:p,roleChangeMessage:m,videoAccelerationBusy:y,slotInput:A,slotBusy:N,onSignIn:()=>{je()},onPinChange:oe=>d(oe.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{Le()},onSlotInputChange:oe=>{ge.current=!0,C(oe.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{P()},onEnableVideoAcceleration:()=>{Se()}})}),I&&r.jsxs("div",{className:`client-side-toast ${I.kind}`,role:I.kind==="error"?"alert":"status",children:[I.kind==="error"?r.jsx(Zg,{size:18}):r.jsx(_n,{size:18}),r.jsx("span",{children:I.message}),r.jsx("button",{type:"button",onClick:()=>F(null),"aria-label":"Dismiss notification",children:r.jsx(kn,{size:16})})]})]})}function zs(e,t,n){if(n<0||t<0||t+n>e.length)throw new Error("Invalid LZO1X block: input overrun.")}function yd(e,t,n){let s=0;for(;zs(e,t.inputIndex,1),e[t.inputIndex]===0;)s+=1,t.inputIndex+=1;const a=s*255+n+e[t.inputIndex];return t.inputIndex+=1,a}function pl(e,t,n,s){if(zs(e,t.inputIndex,s),t.outputIndex+s>n.length)throw new Error("Invalid LZO1X block: output overrun.");n.set(e.subarray(t.inputIndex,t.inputIndex+s),t.outputIndex),t.inputIndex+=s,t.outputIndex+=s}function eS(e,t,n,s){const a=t-n;if(a<=0||s<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let i=Math.min(a,s);for(e.set(e.subarray(n,n+i),t);i<s;){const c=Math.min(i,s-i);e.copyWithin(t+i,t,t+c),i+=c}return t+s}function bv(e,t){if(!(e instanceof Uint8Array)||e.length<3||t<0)throw new Error("Invalid LZO1X block.");const n=new Uint8Array(t),s={inputIndex:0,outputIndex:0};let a=0,i=0;if(e[s.inputIndex]>=22){const c=e[s.inputIndex]-17;s.inputIndex+=1,pl(e,s,n,c),a=4}else e[s.inputIndex]>=18&&(a=e[s.inputIndex]-17,s.inputIndex+=1,pl(e,s,n,a));for(;;){zs(e,s.inputIndex,1);const c=e[s.inputIndex];s.inputIndex+=1;let u,d;if((c&192)!==0)zs(e,s.inputIndex,1),d=s.outputIndex-((e[s.inputIndex]<<3)+(c>>2&7)+1),s.inputIndex+=1,i=(c>>5)+1,u=c&3;else if((c&32)!==0){i=(c&31)+2,i===2&&(i+=yd(e,s,31)),zs(e,s.inputIndex,2);const p=e[s.inputIndex]|e[s.inputIndex+1]<<8;s.inputIndex+=2,d=s.outputIndex-((p>>2)+1),u=p&3}else if((c&16)!==0){i=(c&7)+2,i===2&&(i+=yd(e,s,7)),zs(e,s.inputIndex,2);const p=e[s.inputIndex]|e[s.inputIndex+1]<<8;if(s.inputIndex+=2,d=s.outputIndex-(((c&8)<<11)+(p>>2)),u=p&3,d===s.outputIndex)break;d-=16384}else if(a===0){let p=c+3;p===3&&(p+=yd(e,s,15)),pl(e,s,n,p),a=4;continue}else a!==4?(zs(e,s.inputIndex,1),u=c&3,d=s.outputIndex-((c>>2)+(e[s.inputIndex]<<2)+1),s.inputIndex+=1,i=2):(zs(e,s.inputIndex,1),u=c&3,d=s.outputIndex-((c>>2)+(e[s.inputIndex]<<2)+2049),s.inputIndex+=1,i=3);if(d<0||s.outputIndex+i+u>n.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");s.outputIndex=eS(n,s.outputIndex,d,i),a=u,pl(e,s,n,u)}if(i!==3||s.inputIndex!==e.length||s.outputIndex!==n.length)throw new Error("Invalid LZO1X block: incomplete output.");return n}const Lh=16,_h=8,tS=24*1024*1024,wv=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,np=new Uint32Array(65536);for(let e=0;e<np.length;e+=1){const t=Math.round((e>>11&31)*255/31),n=Math.round((e>>5&63)*255/63),s=Math.round((e&31)*255/31);np[e]=wv?(t|n<<8|s<<16|4278190080)>>>0:(t<<24|n<<16|s<<8|255)>>>0}function Os(e,t){return e[t]|e[t+1]<<8}function nS(e,t){const n=Number(t);if(!Number.isSafeInteger(n)||n<Lh||n>tS)throw new Error(`Invalid Mode 5 packet length: ${t}.`);const s=e instanceof Uint8Array?e:new Uint8Array(e),a=bv(s,n);if(a[0]!==76||a[1]!==68||a[2]!==53||a[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(a[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${a[4]}.`);const i=(a[5]&1)!==0,c=Os(a,6),u=Os(a,8),d=Os(a,10),p=Os(a,12);if(c<=0||u<=0||c>3840||u>2160)throw new Error(`Invalid Mode 5 frame size: ${c}x${u}.`);if(d<=0||d>256||p>8192)throw new Error(`Invalid Mode 5 tile header: ${d}/${p}.`);const h=[];let m=Lh;for(let g=0;g<p;g+=1){if(m+_h>a.length)throw new Error("Mode 5 tile header is truncated.");const w=Os(a,m),b=Os(a,m+2),y=Os(a,m+4),k=Os(a,m+6);m+=_h;const A=y*k*2;if(y<=0||k<=0||y>d||k>d||w+y>c||b+k>u||m+A>a.length)throw new Error(`Invalid Mode 5 tile ${g}.`);h.push({x:w,y:b,width:y,height:k,pixels:a.subarray(m,m+A)}),m+=A}if(m!==a.length)throw new Error(`Mode 5 packet has ${a.length-m} trailing bytes.`);return{keyFrame:i,width:c,height:u,tileSize:d,tiles:h}}function rS(e,t,n,s){if(!(e instanceof Uint8ClampedArray)||e.length!==t*n*4||s.width!==t||s.height!==n)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let a=t,i=n,c=0,u=0;const d=new Uint32Array(e.buffer,e.byteOffset,e.byteLength>>>2);for(const p of s.tiles){const h=wv&&(p.pixels.byteOffset&1)===0?new Uint16Array(p.pixels.buffer,p.pixels.byteOffset,p.pixels.byteLength>>>1):null;let m=0;for(let g=0;g<p.height;g+=1){let w=(p.y+g)*t+p.x;for(let b=0;b<p.width;b+=1){const y=m<<1,k=h?h[m]:p.pixels[y]|p.pixels[y+1]<<8;d[w]=np[k],m+=1,w+=1}}a=Math.min(a,p.x),i=Math.min(i,p.y),c=Math.max(c,p.x+p.width),u=Math.max(u,p.y+p.height)}return s.tiles.length>0?{x:a,y:i,width:c-a,height:u-i}:null}function sS(e){if(!e)return!0;const t=Xt.get(e);return!t||t.hardwareAcceleration==="prefer-hardware"}const Xt=new WeakMap,$h=854,Oh=480,aS=3840,iS=2160,oS=500,Ko=new WeakMap,rp=new WeakMap,Ga=new Set,Wa=new Set,Ys=new WeakMap,za=new Set,qi=new WeakMap,sp=new WeakMap,ap=new WeakMap,Gl=new WeakMap,yv=4,cS=2,$i=4,lS=2,uS=2,dS=18,pS=0,mS=250,xv=80,hS=5,fS=150,gS=1200,vS=18,bS=.65,Sv=80,Cv=125,wS=4,yS=2*1024*1024,xS=8,SS=16,CS=180,kS=3,Pp=2e3,kv=64,Mv=32*1024*1024,MS=500,AS=25,NS=45,RS=20,Av=new Uint8Array(0),Tp=250,PS=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Nv=1,Rv=0,Pv=0,ip=0,Tv=0;const Do=[];let Jo=0,Iv=0,jv,Ev=0,Fv,Dv;function Zo(e,t){Do.push({sequence:++Tv,type:e,canvasId:qi.get(t)||0,observedAt:Date.now(),activeDecoderCount:Ga.size,hardwareLeaseCount:Wa.size,hardwareReleaseGeneration:Jo}),Do.length>256&&Do.splice(0,Do.length-256)}let Rs={h264DecodeAcceleration:"prefer-hardware"};function TS(e){e.h264DecodeAcceleration&&(Rs={...Rs,h264DecodeAcceleration:e.h264DecodeAcceleration})}function IS(e){return e.payload.byteLength===0?e:{...e,payload:Av}}function Lv(e,t){const n=String(e.streamPurpose||"").trim().toLowerCase();return n==="wall"?!0:n==="control"?!1:t>=45e3}function _v(e){try{return e.paintIsCancelled()}catch{return!0}}function lu(e,t){const n=e.pendingFrames.get(t);if(n)return e.pendingFrames.delete(t),e.pendingFrameBytes=Math.max(0,e.pendingFrameBytes-n.encodedByteLength),e.pendingFrames.size===0&&e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),n}function jS(e){const t=e.pendingFrames.entries().next().value;return t?lu(e,t[0]):void 0}function $v(e){e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),e.pendingFrames.clear(),e.pendingFrameBytes=0,e.pendingFrameEvictedThroughTimestamp=-1}function uu(e,t=performance.now()){for(;e.pendingFrames.size>0;){const n=e.pendingFrames.entries().next().value;if(!n)break;const s=t-n[1].queuedAt>Pp,a=e.pendingFrames.size>kv,i=e.pendingFrameBytes>Mv;if(!s&&!a&&!i)break;e.pendingFrameEvictedThroughTimestamp=Math.max(e.pendingFrameEvictedThroughTimestamp,n[0]),lu(e,n[0]),e.pendingFrameEvictionCount+=1}}function ES(e,t,n,s,a,i=performance.now()){lu(e,t);const c={frame:n,queuedAt:i,queueSize:s,encodedByteLength:Math.max(0,Math.floor(Number(n.payload.byteLength||0))),paintIsCancelled:a};e.pendingFrames.set(t,c),e.pendingFrameBytes+=c.encodedByteLength,uu(e,i),e.pendingFrameHighWaterMark=Math.max(e.pendingFrameHighWaterMark,e.pendingFrames.size),e.pendingFrameByteHighWaterMark=Math.max(e.pendingFrameByteHighWaterMark,e.pendingFrameBytes)}function Ov(e,t){if(t.pendingTrimTimer!==null||t.pendingFrames.size===0)return;const n=t.pendingFrames.values().next().value;if(!n)return;const s=Math.max(1,Pp-(performance.now()-n.queuedAt)+1);t.pendingTrimTimer=window.setTimeout(()=>{t.pendingTrimTimer=null,Xt.get(e)===t&&(uu(t),Ov(e,t))},s)}function Bv(e){return Wa.delete(e)?(Jo+=1,Zo("hardware-release",e),!0):!1}function FS(e,t,n){if(t!=="prefer-hardware"||!n)return!1;const s=Ys.get(e);return!s||s.requested!==t||s.actual!=="prefer-software"||Jo<=s.failedHardwareReleaseGeneration?!1:(Ys.delete(e),za.delete(e),Iv+=1,jv=Date.now(),!0)}function op(e,t=Rs.h264DecodeAcceleration){const n=Ys.get(e);return n?.requested===t?(n.actual!=="prefer-hardware"&&(Wa.delete(e),za.add(e)),n.actual):(n&&(Ys.delete(e),za.delete(e)),t!=="prefer-hardware"?(Bv(e),za.delete(e),t):(Wa.has(e)||Wa.add(e),"prefer-hardware"))}function du(e,t,n){if(t!=="prefer-hardware")return!1;const s=Ys.get(e),a=Xt.get(e),i=Date.now();return qi.has(e)||qi.set(e,Nv++),Ys.set(e,{requested:t,actual:"prefer-software",reason:n,failedAt:i,failureCount:(s?.requested===t?s.failureCount:0)+1,codec:a?.codec||s?.codec||"",latencyMode:a?.latencyMode||s?.latencyMode||"smooth",inputCount:a?.inputSerial??s?.inputCount??0,outputCount:a?.outputSerial??s?.outputCount??0,lastInputAt:a?.lastInputAt??s?.lastInputAt??0,lastOutputAt:a?.lastOutputAt??s?.lastOutputAt??0,lastPaintAt:a?.lastPaintAt??s?.lastPaintAt??0,decodeQueueHighWaterMark:Math.max(a?.decodeQueueHighWaterMark??0,s?.decodeQueueHighWaterMark??0),decodeQueueOverflowSamples:Math.max(a?.decodeQueueOverflowSamples??0,s?.decodeQueueOverflowSamples??0),decodeQueueOverflowAgeMs:a?.decodeQueueOverflowStartedAt?Math.max(0,performance.now()-a.decodeQueueOverflowStartedAt):s?.decodeQueueOverflowAgeMs,failedHardwareReleaseGeneration:Jo}),Wa.delete(e),za.add(e),Ev+=1,Fv=n,Dv=i,!0}function Xs(e){e.interactivePipelineFallbackTimer!==null&&(window.clearTimeout(e.interactivePipelineFallbackTimer),e.interactivePipelineFallbackTimer=null),e.interactivePipelineFallbackFrame!==null&&(window.cancelAnimationFrame(e.interactivePipelineFallbackFrame),e.interactivePipelineFallbackFrame=null),e.interactivePipelineRecoveryFrames=[],e.interactivePipelineRecoveryBytes=0,e.interactivePipelinePaintIsCancelled=void 0,e.interactivePipelineGuardTimestampUs=null}function Hv(e,t){const n=t.interactivePipelineRecoveryFrames,s=t.interactivePipelinePaintIsCancelled,a=t.onBeforePaint,i=t.onPaint;if(Xs(t),n.length===0||s?.()||Xt.get(e)!==t||t.hardwareAcceleration!=="prefer-hardware"||!du(e,t.requestedAcceleration,"interactive-pipeline-latency"))return!1;const c=t.requestedAcceleration,u=t.latencyMode;Zn(e);try{for(const d of n)jp(e,d,i,c,u,s,!1,a)}catch{Zn(e)}return!0}function DS(e,t,n){const s=Math.max(0,Number(t.payload.byteLength||0));return e.interactivePipelineRecoveryFrames.length>=wS||e.interactivePipelineRecoveryBytes+s>yS?(Xs(e),!1):(e.interactivePipelineRecoveryFrames.push({...t,payload:t.payload.slice()}),e.interactivePipelineRecoveryBytes+=s,e.interactivePipelinePaintIsCancelled=n,!0)}function LS(e,t,n,s,a=performance.now()){const i=()=>{if(!(Xt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==n)){if(!t.pendingFrames.has(n)){Xs(t);return}Hv(e,t)}},c=u=>{if(t.interactivePipelineFallbackFrame=null,!(Xt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==n)){if(!t.pendingFrames.has(n)){Xs(t);return}if(u-a>=s){i();return}t.interactivePipelineFallbackFrame=window.requestAnimationFrame(c)}};t.interactivePipelineFallbackTimer=window.setTimeout(i,s),t.interactivePipelineFallbackFrame=window.requestAnimationFrame(c)}function _S(e,t,n,s=64){try{let a=sp.get(e);a||(a={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},sp.set(e,a));const i=Math.max(8,Math.min(64,Math.round(s))),c=Math.max(1,Math.round(i*Math.max(1,n)/Math.max(1,t)));(a.canvas.width!==i||a.canvas.height!==c)&&(a.canvas.width=i,a.canvas.height=c);const u=a.canvas.getContext("2d",{willReadFrequently:!0});if(!u)return{visualHash:"",visualChanged:!0};u.drawImage(e,0,0,Math.max(1,t),Math.max(1,n),0,0,i,c);const d=u.getImageData(0,0,i,c).data;let p=2166136261;for(let g=0;g<d.length;g+=4)p^=d[g],p=Math.imul(p,16777619),p^=d[g+1],p=Math.imul(p,16777619),p^=d[g+2],p=Math.imul(p,16777619);const h=(p>>>0).toString(16).padStart(8,"0"),m=!a.initialized||h!==a.lastHash;return a.initialized=!0,a.lastHash=h,{visualHash:h,visualChanged:m}}catch{return{visualHash:"",visualChanged:!0}}}function cp(e,t,n,s=Tp,a=64,i){if(!PS&&i)return Wv(e,i);let c=ap.get(e);c||(c={lastHash:"",initialized:!1,lastCanvasSampleAt:0},ap.set(e,c));const u=performance.now();if(c.initialized&&s>0&&u-c.lastCanvasSampleAt<s)return{visualHash:c.lastHash,visualChanged:!1};const d=_S(e,t,n,a);return c.initialized=!0,c.lastHash=d.visualHash,c.lastCanvasSampleAt=u,d}function Wv(e,t){let n=Gl.get(e);n||(n={lastHash:"",initialized:!1},Gl.set(e,n));const s=String(t.contentHash||""),a=!n.initialized||!s||s!==n.lastHash;return n.initialized=!0,n.lastHash=s,{visualHash:s,visualChanged:a}}function zv(e,t,n=!1){const s=rp.get(e);if(s)return s;const a=e.getContext("2d",{alpha:!1,desynchronized:t==="interactive",willReadFrequently:n});if(a){const i=a.getContextAttributes?.(),c={context:a,presentation:i?.desynchronized?"desync":"sync"};return rp.set(e,c),c}return null}function $S(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),n=String(e.compression||"").toLowerCase(),s=String(e.mimeType||"").toLowerCase();return t==="mode2-lzo"||n==="lzo1x"||s==="application/vnd.livedesk.lzo-rgb565"||t==="mode2-lz4"||String(e.compression||"").toLowerCase()==="lz4"||s==="application/vnd.livedesk.lz4-raw"}function OS(e){return String(e.frameMode||e.mode||"").toLowerCase()==="mode3-h264-hw"||String(e.codec||"").toLowerCase()==="h264"||String(e.mimeType||"").toLowerCase()==="video/h264"}function BS(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),n=String(e.mimeType||"").toLowerCase();return t==="mode5-lzo-delta"||n==="application/vnd.livedesk.lzo-rgb565-delta"}function Bh(e,t,n){let s=n,a=t;if(s===15){let i=255;for(;i===255;){if(a>=e.length)throw new Error("Invalid LZ4 block: length overrun.");i=e[a],a+=1,s+=i}}return{length:s,cursor:a}}function HS(e,t){const n=new Uint8Array(t);let s=0,a=0;for(;s<e.length;){const i=e[s];s+=1;const c=Bh(e,s,i>>4);s=c.cursor;const u=c.length;if(s+u>e.length||a+u>n.length)throw new Error("Invalid LZ4 block: literal overrun.");if(n.set(e.subarray(s,s+u),a),s+=u,a+=u,s>=e.length)break;if(s+2>e.length)throw new Error("Invalid LZ4 block: missing offset.");const d=e[s]|e[s+1]<<8;if(s+=2,d<=0||d>a)throw new Error("Invalid LZ4 block: bad match offset.");const p=Bh(e,s,i&15);s=p.cursor;const h=p.length+4;if(a+h>n.length)throw new Error("Invalid LZ4 block: match overrun.");let m=a-d;for(let g=0;g<h;g+=1)n[a]=n[m],a+=1,m+=1}if(a!==n.length)throw new Error("Invalid LZ4 block: incomplete output.");return n}function WS(e){const t=Math.max(1,Math.floor(e.width||0)),n=Math.max(1,Math.floor(e.height||0)),s=String(e.compression||"").toLowerCase(),a=String(e.pixelFormat||e.codec||"").toLowerCase();if(s==="lzo1x"||String(e.frameMode||e.mode||"").toLowerCase()==="mode2-lzo"||String(e.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const h=Math.max(1,Math.floor(e.bytesPerPixel||2)),m=t*n*2,g=Math.floor(e.uncompressedByteLength||m);if(h!==2||g!==m)throw new Error(`Invalid mode2 RGB565 frame size: ${g} for ${t}x${n}.`);if(a&&a!=="rgb565le"&&a!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${a}`);const w=bv(e.payload,m),b=new Uint8ClampedArray(t*n*4);for(let y=0,k=0;y<w.length;y+=2,k+=4){const A=w[y]|w[y+1]<<8,C=A>>11&31,N=A>>5&63,E=A&31;b[k]=C<<3|C>>2,b[k+1]=N<<2|N>>4,b[k+2]=E<<3|E>>2,b[k+3]=255}return new ImageData(b,t,n)}const c=Math.max(1,Math.floor(e.bytesPerPixel||4)),u=Math.max(t*n*c,Math.floor(e.uncompressedByteLength||0)),d=HS(e.payload,u);if(c!==4)throw new Error(`Unsupported mode2 pixel size: ${c}`);const p=new Uint8ClampedArray(t*n*4);if(a==="rgba32"||a==="rgba")p.set(d.subarray(0,p.length));else for(let h=0,m=0;m<p.length;h+=4,m+=4)p[m]=d[h+2],p[m+1]=d[h+1],p[m+2]=d[h],p[m+3]=d[h+3];return new ImageData(p,t,n)}function Hh(e,t="smooth",n=Rs.h264DecodeAcceleration){const s=window.VideoDecoder;if(!s||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const a=Xt.get(e);if(a&&a.decoder.state!=="closed"&&a.latencyMode===t)return a;a&&Zn(e);let i;const c=new s({output:u=>{if(Xt.get(e)!==i){u.close();return}const d=Number(u.timestamp||0),p=performance.now();i.outputSerial+=1,uu(i,p);let h=lu(i,d);if(!h&&d>i.pendingFrameEvictedThroughTimestamp&&i.pendingFrames.size>0&&(h=jS(i),i.timestampFallbacks+=1),!h){i.pendingFrameUnmatchedOutputCount+=1,i.droppedForLatency+=1,i.lastOutputAt=p,u.close();return}const m=i.interactivePipelineGuardTimestampUs===d;if(_v(h)){m&&Xs(i),i.droppedForLatency+=1,i.lastOutputAt=p,u.close();return}const g=u.displayWidth||u.codedWidth||e.width||960,w=u.displayHeight||u.codedHeight||e.height||540,b=Number(h?.frame.durationUs||0),y=Number(u.duration||0),k=Math.max(16,Math.min(250,(b>0?b:y||83333)/1e3));i.targetPaintIntervalMs=k;const A=Math.max(0,p-h.queuedAt),N=Lv(h.frame,b>0?b:Math.round(k*1e3))?Cv:Sv;if(i.latencyMode==="interactive"&&i.hardwareAcceleration==="prefer-hardware"&&m&&i.interactivePipelineRecoveryFrames.length>0&&A>N){u.close(),i.droppedForLatency+=1,Hv(e,i);return}m&&Xs(i),Math.abs(i.interactiveBurstOutputCadenceMs-k)>1&&(i.interactiveBurstOutputTimeCursor=0,i.interactiveBurstOutputTimeCount=0,i.interactiveBurstOutputCadenceMs=k,i.interactiveBurstOutputWindowMs=0),i.interactiveBurstOutputTimes[i.interactiveBurstOutputTimeCursor]=p,i.interactiveBurstOutputTimeCursor=(i.interactiveBurstOutputTimeCursor+1)%$i,i.interactiveBurstOutputTimeCount=Math.min($i,i.interactiveBurstOutputTimeCount+1);const E=i.interactiveBurstOutputTimeCount>=$i?p-i.interactiveBurstOutputTimes[i.interactiveBurstOutputTimeCursor]:0;for(i.interactiveBurstOutputWindowMs=Math.max(0,E),i.decodedFrames.push({videoFrame:u,pending:h,decodedAt:p,width:g,height:w,durationMs:k}),i.latencyMode==="interactive"&&i.targetPaintIntervalMs>20&&i.interactiveBurstOutputTimeCount>=$i&&E<=Math.min(NS,Math.max(AS,i.targetPaintIntervalMs-5))&&(i.interactiveBurstTailHoldArmed=!0),i.lastOutputAt=p;i.decodedFrames.length>Ip(i);)Kl(i,i.decodedFrames.shift(),"capacity");i.renderQueueHighWaterMark=Math.max(i.renderQueueHighWaterMark,i.decodedFrames.length),Uv(i),i.renderTimer!==null&&i.renderScheduledAt>0&&performance.now()-i.renderScheduledAt>MS&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(i.renderTimer),i.renderTimer=null,i.renderScheduledAt=0),i.renderTimer!==null&&i.decodedFrames.length>=yv&&(window.cancelAnimationFrame(i.renderTimer),i.renderTimer=null,i.renderScheduledAt=0),Ql(e,i)},error:()=>{Xt.get(e)===i&&(du(e,i.requestedAcceleration,"decoder-error"),Zn(e))}});return Rv+=1,qi.has(e)||qi.set(e,Nv++),i={decoder:c,configured:!1,configKey:"",codec:"",requestedAcceleration:n,hardwareAcceleration:op(e,n),latencyMode:t,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,pendingFrameBytes:0,pendingFrameHighWaterMark:0,pendingFrameByteHighWaterMark:0,pendingFrameEvictionCount:0,pendingFrameUnmatchedOutputCount:0,pendingFrameEvictedThroughTimestamp:-1,pendingTrimTimer:null,decodedFrames:[],renderQueueHighWaterMark:0,renderQueueCapacityDropCount:0,renderQueueAgeDropCount:0,renderTimer:null,renderScheduledAt:0,flushTimer:null,flushInFlight:!1,flushCount:0,timestampFallbacks:0,inputSerial:0,outputSerial:0,lastFlushInputSerial:0,lastOutputAt:0,lastPaintAt:0,lastInputAt:0,interactiveBufferPrimed:!1,interactiveBufferStartedAt:0,interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,interactiveBurstTailHoldArmed:!1,interactiveBurstTailHoldCount:0,interactiveBurstOutputTimes:new Float64Array($i),interactiveBurstOutputTimeCursor:0,interactiveBurstOutputTimeCount:0,interactiveBurstOutputCadenceMs:0,interactiveBurstOutputWindowMs:0,interactivePipelineFallbackTimer:null,interactivePipelineFallbackFrame:null,interactivePipelineGuardTimestampUs:null,interactivePipelineRecoveryFrames:[],interactivePipelineRecoveryBytes:0,interactivePipelinePaintIsCancelled:void 0,interactiveBackingWidth:0,interactiveBackingHeight:0,interactiveBackingSourceWidth:0,interactiveBackingSourceHeight:0,interactiveBackingMeasuredAt:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0,decodeQueueHighWaterMark:0,decodeQueueOverflowStartedAt:0,decodeQueueOverflowSamples:0},Xt.set(e,i),Ga.add(e),ip=Math.max(ip,Ga.size),Zo("create",e),i}function qv(e){Xs(e),e.renderTimer!==null&&(window.cancelAnimationFrame(e.renderTimer),e.renderTimer=null),e.renderScheduledAt=0,e.flushTimer!==null&&(window.clearTimeout(e.flushTimer),e.flushTimer=null),e.flushInFlight=!1;const t=e.decodedFrames;e.decodedFrames=[];for(const n of t)try{n.videoFrame.close()}catch{}e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.interactiveBurstTailHoldArmed=!1,e.interactiveBurstOutputTimeCursor=0,e.interactiveBurstOutputTimeCount=0,e.interactiveBurstOutputCadenceMs=0,e.interactiveBurstOutputWindowMs=0}function Kl(e,t,n="other"){t&&(t.videoFrame.close(),e.droppedForLatency+=1,n==="capacity"?e.renderQueueCapacityDropCount+=1:n==="age"&&(e.renderQueueAgeDropCount+=1))}function Ip(e){return e.latencyMode==="interactive"?e.targetPaintIntervalMs<=20?lS:$i:String(e.decodedFrames[0]?.pending?.frame.frameMode||e.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?cS:yv}function Uv(e,t=performance.now()){const n=Ip(e);for(;e.decodedFrames.length>n;)Kl(e,e.decodedFrames.shift(),"capacity");const s=e.latencyMode==="interactive"?xv:mS;let a=e.decodedFrames[0];for(;e.decodedFrames.length>0&&a&&t-a.decodedAt>s;)Kl(e,e.decodedFrames.shift(),"age"),a=e.decodedFrames[0]}function Vv(e,t){if(t.hardwareAcceleration!=="prefer-hardware"||t.latencyMode==="interactive"||t.flushTimer!==null||t.flushInFlight)return;const n=fS;t.flushTimer=window.setTimeout(async()=>{t.flushTimer=null;const s=performance.now();if(uu(t,s),Xt.get(e)!==t||t.decoder.state!=="configured"||t.pendingFrames.size===0||t.inputSerial<=t.lastFlushInputSerial||t.lastOutputAt>0&&s-t.lastOutputAt<n)return;const a=t.inputSerial;t.flushInFlight=!0,t.flushCount+=1,t.keyFrameSeen=!1;try{await t.decoder.flush(),t.lastFlushInputSerial=Math.max(t.lastFlushInputSerial,a)}catch{Xt.get(e)===t&&_l(t)}finally{t.flushInFlight=!1,Xt.get(e)===t&&t.inputSerial>a&&t.pendingFrames.size>0&&performance.now()-t.lastOutputAt>=n&&Vv(e,t)}},n)}function zS(e,t,n,s){const a=performance.now();if(t.interactiveBackingWidth>0&&t.interactiveBackingHeight>0&&a-t.interactiveBackingMeasuredAt<oS)return{width:Math.min(n,t.interactiveBackingWidth),height:Math.min(s,t.interactiveBackingHeight)};const i=typeof e.getBoundingClientRect=="function"?e.getBoundingClientRect():{width:Number(e.clientWidth||e.width||0),height:Number(e.clientHeight||e.height||0)},c=Math.max(1,Math.min(2,Number(globalThis.devicePixelRatio)||1)),u=Math.max(0,Number(e.width||0)),d=Math.max(0,Number(e.height||0)),p=i.width>0?Math.round(i.width*c):u||$h,h=i.height>0?Math.round(i.height*c):d||Oh,m=Math.min(1,p/n,h/s),g=Math.min(1,Math.max($h/n,Oh/s)),w=Math.min(1,aS/n,iS/s),b=Math.max(.01,Math.min(w,Math.max(g,m)));return t.interactiveBackingWidth=Math.max(1,Math.round(n*b)),t.interactiveBackingHeight=Math.max(1,Math.round(s*b)),t.interactiveBackingMeasuredAt=a,{width:t.interactiveBackingWidth,height:t.interactiveBackingHeight}}function Wh(e,t,n){const s=performance.now();try{if(!n.pending||_v(n.pending)){t.droppedForLatency+=1;return}let a=1;try{const h=t.onBeforePaint?.(n.pending.frame);typeof h=="number"&&Number.isFinite(h)&&(a=Math.max(.05,Math.min(1,h)))}catch{}const i=t.latencyMode==="interactive"?zS(e,t,n.width,n.height):{width:n.width,height:n.height},c=i.width,u=i.height,d=e.width!==c||e.height!==u;d&&(e.width=c,e.height=u);const p=zv(e,t.latencyMode,t.hardwareAcceleration==="prefer-software");if(p){const h=p.context.globalAlpha;p.context.globalAlpha=d||t.lastPaintAt<=0||t.hardwareAcceleration!=="prefer-hardware"?1:a;try{p.context.drawImage(n.videoFrame,0,0,n.width,n.height,0,0,c,u)}finally{p.context.globalAlpha=h}}if(n.pending){const h=performance.now(),g=t.latencyMode==="interactive"?Wv(e,n.pending.frame):cp(e,n.width,n.height,Tp,64,n.pending.frame),w=IS(n.pending.frame);try{t.onPaint?.(w,{deviceId:w.deviceId,frameSeq:w.frameSeq,mode:w.frameMode||w.mode||w.codec||w.mimeType,width:n.width,height:n.height,byteLength:w.byteLength,queuedForMs:Math.max(0,s-n.pending.queuedAt),decodedForMs:Math.max(0,n.decodedAt-n.pending.queuedAt),scheduledForMs:Math.max(0,s-n.decodedAt),drawMs:Math.max(0,h-s),queueSize:n.pending.queueSize,renderQueueSize:t.decodedFrames.length,droppedForLatency:t.droppedForLatency,h264DecodeAcceleration:t.hardwareAcceleration,decoderLabel:t.hardwareAcceleration,decoderFlushCount:t.flushCount,decoderTimestampFallbacks:t.timestampFallbacks,decoderInputCount:t.inputSerial,decoderOutputCount:t.outputSerial,targetPaintIntervalMs:t.targetPaintIntervalMs,canvasPresentation:p?.presentation||"sync",interactiveBufferWaitCount:t.interactiveBufferWaitCount,interactiveBufferWaitMs:t.interactiveBufferWaitMs,interactiveQueueDrainCount:t.interactiveQueueDrainCount,interactiveBurstOutputWindowMs:t.interactiveBurstOutputWindowMs,interactiveBurstTailHoldCount:t.interactiveBurstTailHoldCount,visualHash:g.visualHash,visualChanged:g.visualChanged,paintedAt:h})}catch{}}t.lastPaintAt=performance.now()}finally{n.videoFrame.close()}}function Ql(e,t){if(t.renderTimer!==null||t.decodedFrames.length===0)return;const n=Math.max(16,Math.min(250,t.targetPaintIntervalMs||1e3/12)),s=()=>{if(t.renderTimer=null,t.renderScheduledAt=0,t.decodedFrames.length===0)return;const a=performance.now();if(Uv(t,a),t.decodedFrames.length===0){t.interactiveBurstTailHoldArmed=!1;return}if(t.latencyMode==="interactive"){const d=t.targetPaintIntervalMs<=20;if(d&&!t.interactiveBufferPrimed){t.interactiveBufferStartedAt<=0&&(t.interactiveBufferStartedAt=a,t.interactiveBufferWaitCount+=1);const h=t.decodedFrames.length>=uS,m=a-t.interactiveBufferStartedAt>=dS;if(!h&&!m){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}t.interactiveBufferWaitMs+=Math.max(0,a-t.interactiveBufferStartedAt),t.interactiveBufferPrimed=!0}else d||(t.interactiveBufferPrimed=!0);if(!d&&t.interactiveBurstTailHoldArmed&&t.decodedFrames.length===1&&a-t.decodedFrames[0].decodedAt<=xv-RS){t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstTailHoldCount+=1,t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}const p=t.decodedFrames.shift();if(p)try{Wh(e,t,p)}catch{}t.decodedFrames.length===0&&(t.interactiveQueueDrainCount+=1,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1),Ql(e,t);return}const i=t.lastPaintAt>0?t.lastPaintAt+n:a+pS;if(!(a+hS>=i||t.decodedFrames.length>=Math.max(1,Ip(t)-1))){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}const u=t.decodedFrames.shift();if(u)try{Wh(e,t,u)}catch{}Ql(e,t)};t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s)}function Gv(e,t){if(Xt.get(e)!==t||t.decoder.state==="closed")return!1;for(t.renderTimer!==null&&(window.cancelAnimationFrame(t.renderTimer),t.renderTimer=null),t.renderScheduledAt=0;t.decodedFrames.length>1;)Kl(t,t.decodedFrames.shift());return t.lastPaintAt=0,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstOutputTimeCursor=0,t.interactiveBurstOutputTimeCount=0,t.interactiveBurstOutputCadenceMs=0,t.interactiveBurstOutputWindowMs=0,Ql(e,t),!0}function xd(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const e of Ga){const t=Xt.get(e);if(!t||t.decoder.state==="closed"){Ga.delete(e);continue}Gv(e,t)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",xd),window.addEventListener("focus",xd),window.addEventListener("pageshow",xd));function Zn(e){Bv(e),Ga.delete(e),Gl.delete(e);const t=Xt.get(e);if(t){Xt.delete(e),Pv+=1,$v(t),t.onBeforePaint=void 0,t.onPaint=void 0,qv(t);try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}try{t.decoder.state!=="closed"&&t.decoder.close()}catch{}Zo("close",e)}}function Ii(e){e&&(Ys.delete(e),za.delete(e),rp.delete(e),ap.delete(e),sp.delete(e),Gl.delete(e),Ko.delete(e),Zn(e))}function qS(e,t){const n=Xt.get(e),s=Ys.get(e);if(!n&&!s)return null;const a=c=>c>0?Math.max(0,t-c):void 0,i=n?.pendingFrames.values().next().value;return{canvasId:qi.get(e)||0,canvasWidth:Math.max(0,Number(e.width||0)),canvasHeight:Math.max(0,Number(e.height||0)),decoderState:n?.decoder.state||"fallback-pending",configured:n?.configured||!1,keyFrameSeen:n?.keyFrameSeen||!1,codec:n?.codec||s?.codec||"",requestedAcceleration:n?.requestedAcceleration||s?.requested||Rs.h264DecodeAcceleration,configuredAcceleration:n?.hardwareAcceleration||s?.actual||Rs.h264DecodeAcceleration,latencyMode:n?.latencyMode||s?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(n?.decoder.decodeQueueSize||0)),decodeQueueHighWaterMark:Math.max(0,Number(n?.decodeQueueHighWaterMark??0),Number(s?.decodeQueueHighWaterMark??0)),decodeQueueOverflowSamples:Math.max(0,Number(n?.decodeQueueOverflowSamples??0),Number(s?.decodeQueueOverflowSamples??0)),decodeQueueOverflowAgeMs:n?.decodeQueueOverflowStartedAt?Math.max(0,t-n.decodeQueueOverflowStartedAt):s?.decodeQueueOverflowAgeMs,pendingFrameCount:n?.pendingFrames.size||0,pendingFrameBytes:n?.pendingFrameBytes||0,pendingFrameHighWaterMark:n?.pendingFrameHighWaterMark||0,pendingFrameByteHighWaterMark:n?.pendingFrameByteHighWaterMark||0,pendingFrameEvictionCount:n?.pendingFrameEvictionCount||0,pendingFrameUnmatchedOutputCount:n?.pendingFrameUnmatchedOutputCount||0,pendingFrameOldestAgeMs:i?Math.max(0,t-i.queuedAt):void 0,pendingFrameMaxCount:kv,pendingFrameMaxBytes:Mv,pendingFrameMaxAgeMs:Pp,renderQueueSize:n?.decodedFrames.length||0,renderQueueHighWaterMark:n?.renderQueueHighWaterMark||0,renderQueueCapacityDropCount:n?.renderQueueCapacityDropCount||0,renderQueueAgeDropCount:n?.renderQueueAgeDropCount||0,interactiveBurstTailHoldCount:n?.interactiveBurstTailHoldCount||0,interactiveBurstOutputWindowMs:Math.max(0,Number(n?.interactiveBurstOutputWindowMs||0)),interactivePipelineRecoveryBytes:Math.max(0,Number(n?.interactivePipelineRecoveryBytes||0)),targetPaintIntervalMs:Math.max(0,Number(n?.targetPaintIntervalMs||0)),droppedForLatency:Math.max(0,Number(n?.droppedForLatency||0)),inputCount:n?.inputSerial??s?.inputCount??0,outputCount:n?.outputSerial??s?.outputCount??0,lastInputAgeMs:a(n?.lastInputAt??s?.lastInputAt??0),lastOutputAgeMs:a(n?.lastOutputAt??s?.lastOutputAt??0),lastPaintAgeMs:a(n?.lastPaintAt??s?.lastPaintAt??0),softwareFallbackReason:s?.reason,softwareFallbackAt:s?.failedAt,softwareFallbackCount:s?.failureCount||0}}function ml(e,t={}){const n=performance.now(),a=(e?[e]:[...new Set([...Ga,...za])]).map(u=>qS(u,n)).filter(u=>u!==null),i=a.reduce((u,d)=>u+d.pendingFrameCount,0),c=a.reduce((u,d)=>u+d.pendingFrameBytes,0);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:a.filter(u=>u.decoderState!=="fallback-pending").length,hardwareLeaseCount:Wa.size,hardwareReleaseGeneration:Jo,hardwareRecoveryProbeCount:Iv,lastHardwareRecoveryProbeAt:jv,activeSoftwareFallbackCount:a.filter(u=>u.configuredAcceleration==="prefer-software"&&u.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:Rv,decoderCloseCount:Pv,activeDecoderHighWaterMark:ip,decoderLifecycleSequence:Tv,decoderLifecycleEvents:t.includeLifecycleEvents===!1?[]:Do.map(u=>({...u})),softwareFallbackEventCount:Ev,lastSoftwareFallbackReason:Fv,lastSoftwareFallbackAt:Dv,pendingFrameCount:i,pendingFrameBytes:c,canvases:a}}function _l(e,t=1){try{e.decoder.state!=="closed"&&e.decoder.reset()}catch{}e.configured=!1,e.configKey="",e.keyFrameSeen=!1,$v(e),qv(e),e.lastPaintAt=0,e.lastOutputAt=0,e.lastInputAt=0,e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.lastInputFrameSeq=void 0,e.nextChunkTimestampUs=0,e.healthSampleStartedAt=performance.now(),e.healthInputSerial=e.inputSerial,e.healthOutputSerial=e.outputSerial,e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,e.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t)))}function US(e,t,n=performance.now()){const s=Math.max(0,Number.isFinite(t)?t:0);if(e.decodeQueueHighWaterMark=Math.max(e.decodeQueueHighWaterMark,s),s<=xS)return e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,!1;e.decodeQueueOverflowStartedAt<=0?(e.decodeQueueOverflowStartedAt=n,e.decodeQueueOverflowSamples=1):e.decodeQueueOverflowSamples+=1;const a=Math.max(0,n-e.decodeQueueOverflowStartedAt);return s>=SS||e.decodeQueueOverflowSamples>=kS&&a>=CS}function VS(e,t,n,s,a,i){t.decoder.configure(n),t.configured=!0,t.configKey=s,t.codec=n.codec,t.requestedAcceleration=i,t.hardwareAcceleration=a,t.keyFrameSeen=!1,t.nextChunkTimestampUs=0,t.lastInputFrameSeq=void 0,Zo("configure",e)}function GS(e,t){if(t.latencyMode!=="interactive"||t.hardwareAcceleration!=="prefer-hardware")return!1;const n=performance.now();if(n-t.healthSampleStartedAt<gS)return!1;const s=t.inputSerial-t.healthInputSerial,a=t.outputSerial-t.healthOutputSerial;return t.healthSampleStartedAt=n,t.healthInputSerial=t.inputSerial,t.healthOutputSerial=t.outputSerial,s<vS||a/Math.max(1,s)>=bS?!1:(du(e,t.requestedAcceleration,"interactive-health"),Zn(e),!0)}function ji(e,t=1){if(!e)return!1;const n=Xt.get(e);return n?(n.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t))),Zn(e),!0):!1}function KS(e){if(!e)return!1;const t=Xt.get(e);return t?Gv(e,t):!1}function QS(e,t,n,s="interactive",a){Zn(e);const i=performance.now(),c=nS(t.payload,t.uncompressedByteLength||0),u=String(t.streamId||"mode5");let d=Ko.get(e);if(!d||d.streamId!==u||d.width!==c.width||d.height!==c.height){const k=new Uint8ClampedArray(c.width*c.height*4);for(let A=3;A<k.length;A+=4)k[A]=255;d={streamId:u,width:c.width,height:c.height,rgba:k,imageData:new ImageData(k,c.width,c.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Ko.set(e,d)}if(!d)throw new Error("Mode 5 canvas state could not be initialized.");d.inputSerial+=1;const h=Number(t.streamFrameSeq||0);if(h>0&&(d.lastStreamFrameSeq=h),!c.keyFrame&&!d.keyFrameSeen)return;c.keyFrame&&(d.keyFrameSeen=!0);const m=rS(d.rgba,d.width,d.height,c),g=performance.now();try{a?.(t)}catch{}(e.width!==d.width||e.height!==d.height)&&(e.width=d.width,e.height=d.height);const w=zv(e,s),b=performance.now();m&&w?.context.putImageData(d.imageData,0,0,m.x,m.y,m.width,m.height);const y=performance.now();d.outputSerial+=1,n?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.mimeType,width:d.width,height:d.height,byteLength:t.byteLength,queuedForMs:Math.max(0,y-i),decodedForMs:Math.max(0,g-i),scheduledForMs:0,drawMs:Math.max(0,y-b),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:d.inputSerial,decoderOutputCount:d.outputSerial,targetPaintIntervalMs:Math.max(1,Number(t.durationUs||0)/1e3||1e3/30),canvasPresentation:w?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(t.contentHash||""),visualChanged:Number(t.deltaVisualTileCount||0)>0,paintedAt:y})}const Sd=[{code:30,maxFrameSize:1620,maxMacroblocksPerSecond:40500},{code:31,maxFrameSize:3600,maxMacroblocksPerSecond:108e3},{code:32,maxFrameSize:5120,maxMacroblocksPerSecond:216e3},{code:40,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:41,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:42,maxFrameSize:8704,maxMacroblocksPerSecond:522240},{code:50,maxFrameSize:22080,maxMacroblocksPerSecond:589824},{code:51,maxFrameSize:36864,maxMacroblocksPerSecond:983040},{code:52,maxFrameSize:36864,maxMacroblocksPerSecond:2073600}];function zh(e,t){for(let n=Math.max(0,t);n+3<e.length;n+=1)if(!(e[n]!==0||e[n+1]!==0)){if(e[n+2]===1)return{index:n,length:3};if(e[n+2]===0&&e[n+3]===1)return{index:n,length:4}}return null}function YS(e){let t=0;for(;t<e.length;){const n=zh(e,t);if(!n)break;const s=n.index+n.length,a=zh(e,s),i=a?.index??e.length;if(s<i&&(e[s]&31)===7){const c=[];let u=0;for(let d=s+1;d<i;d+=1){const p=e[d];if(u>=2&&p===3){u=0;continue}c.push(p),u=p===0?u+1:0}if(c.length>=3)return`avc1.${c.slice(0,3).map(d=>d.toString(16).toUpperCase().padStart(2,"0")).join("")}`}t=a?a.index:e.length}return""}function XS(e,t,n,s,a=""){const i=Math.ceil(e/16)*Math.ceil(t/16),c=n>0?1e6/n:30,u=i*c,d=Sd.find(p=>i<=p.maxFrameSize&&u<=p.maxMacroblocksPerSecond)||Sd[Sd.length-1];return YS(s)||a||`avc1.42E0${d.code.toString(16).toUpperCase().padStart(2,"0")}`}function jp(e,t,n,s,a="smooth",i=()=>!1,c=!0,u){Ko.delete(e);const d=String(t.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",p=Math.max(1,Math.floor(t.width||960)),h=Math.max(1,Math.floor(t.height||540)),m=Math.max(1,Math.floor(t.durationUs||1e6/12)),g=s||Rs.h264DecodeAcceleration,w=t.isKeyFrame===!0||String(t.chunkType||"").toLowerCase()==="key";FS(e,g,w);let b=Hh(e,a,g);const y=XS(p,h,m,t.payload,b.codec);let k=op(e,g),A="";const C=()=>{A=[t.streamId||"",t.commandId||"",p,h,y,d,g,k,a].join("|")};C(),b.onBeforePaint=u,b.onPaint=n,b.configured&&b.decoder.state!=="configured"&&(b.configured=!1,b.configKey=""),b.configured&&b.configKey!==A&&(Zn(e),b=Hh(e,a,g),b.onBeforePaint=u,b.onPaint=n,k=op(e,g),C());const N=()=>({codec:y,codedWidth:p,codedHeight:h,hardwareAcceleration:k,optimizeForLatency:!0,avc:{format:d}}),E=ne=>b.hardwareAcceleration!=="prefer-hardware"||!du(e,b.requestedAcceleration,ne)?!1:(Zn(e),c&&w&&jp(e,t,n,g,a,i,!1,u),!0),I=()=>{try{return VS(e,b,N(),A,k,g),!0}catch(ne){if(E("configure-error"))return!1;throw Zn(e),ne}};if(!b.configured&&!I())return;const F=Number(t.streamFrameSeq||0);if(F>0&&b.lastInputFrameSeq!==void 0&&(F<=b.lastInputFrameSeq&&(!w||F===b.lastInputFrameSeq||(_l(b,b.lastInputFrameSeq-F+1),!I()))||F>b.lastInputFrameSeq+1&&(_l(b,F-b.lastInputFrameSeq-1),!w||!I()))||(F>0&&(b.lastInputFrameSeq=F),!w&&!b.keyFrameSeen))return;w&&(b.keyFrameSeen=!0);const M=Number(b.decoder.decodeQueueSize||0);if(US(b,M)){if(b.latencyMode==="interactive"&&b.hardwareAcceleration==="prefer-hardware"){E("decode-queue-overflow");return}if(_l(b),!w||!I())return;b.keyFrameSeen=!0}const $=b.nextChunkTimestampUs;b.nextChunkTimestampUs+=m,ES(b,$,t,M,i),Ov(e,b),b.inputSerial+=1,b.lastInputAt=performance.now(),b.inputSerial===1&&Zo("first-input",e);const q=t.payload.buffer,T=q instanceof ArrayBuffer?[q]:[],D=Lv(t,m),H=!D&&b.outputSerial>0,K=w&&b.latencyMode==="interactive"&&b.hardwareAcceleration==="prefer-hardware"&&(D||H),z=D?Cv:Sv;K&&(Xs(b),b.interactivePipelineGuardTimestampUs=$);const W=b.interactivePipelineGuardTimestampUs!==null&&b.interactivePipelineRecoveryFrames.length>0,ce=K||W?DS(b,t,i):!1,j=new EncodedVideoChunk({type:w?"key":"delta",timestamp:$,duration:m,data:t.payload,transfer:T});t.payload=Av;try{b.decoder.decode(j)}catch(ne){if(E("decode-error"))return;throw Zn(e),ne}ce&&Xt.get(e)===b&&b.interactivePipelineGuardTimestampUs===$&&K&&LS(e,b,$,z),Vv(e,b),GS(e,b)}async function Cd(e,t,n,s,a,i="smooth",c=n,u){if(BS(t)){n()||QS(e,t,s,i,u);return}if(OS(t)){n()||jp(e,t,s,a,i,c,!0,u);return}if(Ko.delete(e),$S(t)){Zn(e);const w=WS(t);if(n())return;try{u?.(t)}catch{}(e.width!==w.width||e.height!==w.height)&&(e.width=w.width,e.height=w.height);const b=e.getContext("2d"),y=performance.now();b?.putImageData(w,0,0);const k=performance.now(),A=cp(e,w.width,w.height,Tp,64,t);s?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:w.width,height:w.height,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,k-y),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Rs.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:A.visualHash,visualChanged:A.visualChanged,paintedAt:k});return}Zn(e);const d=new Blob([t.payload],{type:t.mimeType}),p=await createImageBitmap(d);if(n()){p.close();return}const h=t.width||p.width||960,m=t.height||p.height||540;try{u?.(t)}catch{}(e.width!==h||e.height!==m)&&(e.width=h,e.height=m);const g=e.getContext("2d");if(g){const w=performance.now();g.clearRect(0,0,h,m),g.drawImage(p,0,0,h,m);const b=performance.now(),y=cp(e,h,m);s?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:h,height:m,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,b-w),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Rs.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:y.visualHash,visualChanged:y.visualChanged,paintedAt:b})}p.close()}function JS(e){queueMicrotask(e)}function ZS(e){return e?(e.width=0,e.height=0,!0):!1}function pu(e,t){if(!e)return!1;try{t?.(e)}finally{ZS(e)}return!0}function Ep(e,t){if(!e||!t)return 0;const n=Math.max(0,Number(e.get(t)||0))+1;return e.set(t,n),n}function eC(e,t){if(!e||!t)return 0;const n=Number(e.get(t)||0);return Number.isSafeInteger(n)&&n>0?n:Ep(e,t)}function qh(e,t){return Ep(e,t)}function Uh(e,t,n){return!!e&&!!t&&Number(n)>0&&Number(e.get(t)||0)===Number(n)}function tC(e,t,n){if(!e||!e.has(t))return!1;const s=e.get(t);return e.delete(t),pu(s,n)}function nC(e,t,n){const s=new Set;for(const a of e||[])if(a){for(const i of a.values())i&&s.add(i);a.clear()}for(const a of t||[])a&&s.add(a);for(const a of s)pu(a,n);return s.size}function rC(e,{isCurrent:t,dispose:n,schedule:s=JS}){return!e||typeof t!="function"?!1:(s(()=>{t(e)||pu(e,n)}),!0)}const sC=new Uint8Array(0);function Oa(e){if(!e||typeof e!="object")return e;const t=e.payload;return t instanceof Uint8Array&&t.byteLength===0?e:{...e,payload:sC}}function aC(e,t){const n=Oa(t);return e.set(t.deviceId,n),n}function iC(e,t){for(const[n,s]of t.entries())e.set(n,Oa(s));return t.clear(),new Map(e)}const oC=1500;function cC(e={}){const t=Math.max(10,Math.min(1e4,Number(e.closeDeadlineMs)||oC)),n=typeof e.setTimeout=="function"?e.setTimeout:setTimeout,s=typeof e.clearTimeout=="function"?e.clearTimeout:clearTimeout,a=new Set,i=new WeakMap;let c=0,u=0;const d=(p,h)=>{if(!p||p.settled)return!1;p.settled=!0,p.timer!==null&&(s(p.timer),p.timer=null);try{p.socket.removeEventListener?.("close",p.handleClose)}catch{}return a.delete(p),i.delete(p.entry),h&&(c+=1),!0};return Object.freeze({beginClosing(p,h="livedesk-frame-socket-release"){if(!p?.socket||i.has(p))return!1;const m=p.socket;if(Number(m.readyState)===3)return!1;const g={entry:p,socket:m,timer:null,settled:!1,handleClose:null};g.handleClose=()=>d(g,!1),i.set(p,g),a.add(g),u=Math.max(u,a.size);try{m.addEventListener?.("close",g.handleClose)}catch{}g.timer=n(()=>{if(!g.settled){try{m.close()}catch{}d(g,Number(m.readyState)!==3)}},t);try{Number(m.readyState)===0||Number(m.readyState)===1?m.close(1e3,h):m.close()}catch{try{m.close()}catch{}}return Number(m.readyState)===3&&d(g,!1),!0},snapshot(){return{closingSocketCount:a.size,closingSocketTimerCount:[...a].filter(p=>p.timer!==null).length,closingSocketTimeoutCount:c,maximumClosingSocketCount:u}}})}function lC(e,t="livedesk-frame-socket-release",n=null){if(!e)return 0;const s=[e],a=new Set;let i=0;for(;s.length>0;){const c=s.pop();if(!c||a.has(c))continue;a.add(c);const u=c.handoffFrom;c.handoffFrom=void 0,u&&!a.has(u)&&s.push(u);const d=c.disposed===!0;c.disposed=!0,c.handoffCompleted=!0;const p=c.detachListeners;c.detachListeners=void 0;try{p?.()}catch{}const h=c.releaseOwnedState;c.releaseOwnedState=void 0;try{h?.()}catch{}if(!d){if(n?.beginClosing)n.beginClosing(c,t);else try{c.socket.readyState===0||c.socket.readyState===1?c.socket.close(1e3,t):c.socket.close()}catch{try{c.socket.close()}catch{}}i+=1}}return i}const Vh=Object.freeze(["nativeCaptureTelemetryAvailable","nativeCaptureTelemetryVersion","nativeEncoderHardwareAccelerationKnown","nativeEncoderHardwareAccelerated","nativeEncoderHardwareQueryStatus","nativeCaptureDisplayId","nativeCaptureFps","nativeCompressionFps","nativeEncodedFps","nativeCaptureSampleCount","nativeEncodableFrameCount","nativeSkippedFrameCount","nativeCompressionOutputCount","nativeEncodedFrameCount","nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs","nativeCaptureResourceTelemetryAvailable","nativeCaptureTelemetryAt"]),uC=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function dC(e){return[String(e?.deviceId||""),String(e?.sessionId||""),String(e?.streamId||""),String(e?.commandId||""),String(Number(e?.captureGeneration||0)||0),String(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1),String(e?.streamPurpose||"")].join("\0")}function pC(e,t){return!!t&&String(e?.deviceId||"")===String(t.deviceId||"")&&String(e?.sessionId||"")===String(t.sessionId||"")&&String(e?.streamId||"")===String(t.streamId||"")&&String(e?.commandId||"")===String(t.commandId||"")&&(Number(e?.captureGeneration||0)||0)===(Number(t.captureGeneration||0)||0)&&(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1)===(Number.isFinite(Number(t.monitorIndex))?Number(t.monitorIndex):-1)&&String(e?.streamPurpose||"")===String(t.streamPurpose||"")}function mC(){return{ownerKey:"",values:Object.create(null)}}function Gh(e){e&&(e.ownerKey="",e.values=Object.create(null))}function hC(e,t,n){if(!e||!t||!pC(e,n))return!1;const s=dC(n);if(t.ownerKey!==s&&(t.ownerKey=s,t.values=Object.create(null)),e.nativeCaptureTelemetryAvailable===!1){for(const a of Vh)a!=="nativeCaptureTelemetryAvailable"&&(delete t.values[a],delete e[a]);return t.values.nativeCaptureTelemetryAvailable=!1,!0}if(e.nativeCaptureResourceTelemetryAvailable===!1)for(const a of uC)delete t.values[a],delete e[a];for(const a of Vh)Object.prototype.hasOwnProperty.call(e,a)?t.values[a]=e[a]:Object.prototype.hasOwnProperty.call(t.values,a)&&(e[a]=t.values[a]);return!0}const Kv=new ArrayBuffer(0);function fC(e){return`${String(e?.streamId||"")}:${Number(e?.frameSeq||0)}`}function gC(e){return!e||typeof e!="object"||e.payload instanceof ArrayBuffer&&e.payload.byteLength===0?e:{...e,payload:Kv}}function vC(){let e=null,t="";return{accept(n){e=gC(n)},publish(){const n=e;if(e=null,!n)return null;const s=fC(n);return s===t?null:(t=s,n)},clear(){e=null,t=""},inspect(){return{pending:e?1:0,pendingPayloadBytes:Number(e?.payload?.byteLength||0),publishedKey:t}}}}const bC=0,wC=1,Kh=3;function En(e){return Math.max(0,Math.floor(Number(e)||0))}function Ir(e,t){return!t||t.active||t.socket!==null||t.audioContext!==null||t.statsTimer!==null||t.scheduledSourceCount!==0||t.pendingDecodeCount!==0||t.workletNodeCount!==0||t.workletPortCount!==0||t.pcmRingCapacityBytes!==0||t.pcmRingBufferedBytes!==0||t.pendingWorkletPacketCount!==0||t.pendingWorkletPacketBytes!==0||t.retainedFrameCount!==0||t.retainedPayloadBytes!==0?!1:e.delete(t)}function yC(){const e=new Set;let t=null;const n={ownerCount:0,socketCount:0,audioContextCount:0,workletNodeCount:0,workletPortCount:0},s=()=>{let a=0,i=0,c=0,u=0;for(const d of e){const p=Number(d.socket?.readyState);a+=d.socket&&p!==Kh?1:0,i+=d.audioContext===null?0:1,c+=En(d.workletNodeCount),u+=En(d.workletPortCount)}n.ownerCount=Math.max(n.ownerCount,e.size),n.socketCount=Math.max(n.socketCount,a),n.audioContextCount=Math.max(n.audioContextCount,i),n.workletNodeCount=Math.max(n.workletNodeCount,c),n.workletPortCount=Math.max(n.workletPortCount,u)};return{createOwner({deviceId:a,socket:i,audioContext:c,statsTimer:u=null}){t=null;const d={deviceId:String(a||""),active:!0,socket:i||null,audioContext:c||null,statsTimer:u,scheduledSourceCount:0,pendingDecodeCount:0,workletNodeCount:0,workletPortCount:0,workletNodeCreateCount:0,pcmRingCapacityBytes:0,pcmRingBufferedBytes:0,pendingWorkletPacketCount:0,pendingWorkletPacketBytes:0,pendingWorkletPacketHighWater:0,pendingWorkletByteHighWater:0,retainedFrameCount:0,retainedPayloadBytes:0};return e.add(d),s(),d},recordTerminalFailure(a,i,c="playback"){return e.has(a)?(t={deviceId:a.deviceId,phase:String(c||"playback").slice(0,64),message:String(i||"Remote audio playback failed.").slice(0,512)},!0):!1},deactivate(a){return e.has(a)?(a.active=!1,Ir(e,a)):!1},setSocket(a,i){return e.has(a)?(a.socket=i||null,s(),Ir(e,a)):!1},setAudioContext(a,i){return e.has(a)?(a.audioContext=i||null,s(),Ir(e,a)):!1},setStatsTimer(a,i){return e.has(a)?(a.statsTimer=i??null,Ir(e,a)):!1},setScheduledSourceCount(a,i){return e.has(a)?(a.scheduledSourceCount=En(i),Ir(e,a)):!1},setPendingDecodeCount(a,i){return e.has(a)?(a.pendingDecodeCount=En(i),Ir(e,a)):!1},setWorkletNode(a,i,c,u=a?.workletNodeCreateCount){return e.has(a)?(a.workletNodeCount=En(i),a.workletPortCount=En(c),a.workletNodeCreateCount=En(u),s(),Ir(e,a)):!1},setPcmRing(a,i,c){return e.has(a)?(a.pcmRingCapacityBytes=En(i),a.pcmRingBufferedBytes=Math.min(a.pcmRingCapacityBytes,En(c)),Ir(e,a)):!1},setPendingWorkletPackets(a,i,c,u=a?.pendingWorkletPacketHighWater,d=a?.pendingWorkletByteHighWater){return e.has(a)?(a.pendingWorkletPacketCount=En(i),a.pendingWorkletPacketBytes=En(c),a.pendingWorkletPacketHighWater=Math.max(a.pendingWorkletPacketHighWater,En(u)),a.pendingWorkletByteHighWater=Math.max(a.pendingWorkletByteHighWater,En(d)),Ir(e,a)):!1},setRetainedFrame(a,i,c=0){return e.has(a)?(a.retainedFrameCount=En(i),a.retainedPayloadBytes=En(c),Ir(e,a)):!1},releaseIfDrained(a){return Ir(e,a)},hasOwner(a){return e.has(a)},snapshot(){const a=[...e].map(c=>{const u=Number(c.socket?.readyState),d=c.socket&&u!==Kh?1:0;return{deviceId:c.deviceId,active:c.active,socketCount:d,openSocketCount:u===wC?1:0,connectingSocketCount:u===bC?1:0,audioContextCount:c.audioContext===null?0:1,statsTimerCount:c.statsTimer===null?0:1,scheduledSourceCount:c.scheduledSourceCount,pendingDecodeCount:c.pendingDecodeCount,workletNodeCount:c.workletNodeCount,workletPortCount:c.workletPortCount,workletNodeCreateCount:c.workletNodeCreateCount,pcmRingCapacityBytes:c.pcmRingCapacityBytes,pcmRingBufferedBytes:c.pcmRingBufferedBytes,pendingWorkletPacketCount:c.pendingWorkletPacketCount,pendingWorkletPacketBytes:c.pendingWorkletPacketBytes,pendingWorkletPacketHighWater:c.pendingWorkletPacketHighWater,pendingWorkletByteHighWater:c.pendingWorkletByteHighWater,retainedFrameCount:c.retainedFrameCount,retainedPayloadBytes:c.retainedPayloadBytes}}),i=c=>a.reduce((u,d)=>u+En(d[c]),0);return{ownerCount:a.length,activeOwnerCount:a.filter(c=>c.active).length,socketCount:i("socketCount"),openSocketCount:i("openSocketCount"),connectingSocketCount:i("connectingSocketCount"),audioContextCount:i("audioContextCount"),statsTimerCount:i("statsTimerCount"),scheduledSourceCount:i("scheduledSourceCount"),pendingDecodeCount:i("pendingDecodeCount"),workletNodeCount:i("workletNodeCount"),workletPortCount:i("workletPortCount"),workletNodeCreateCount:i("workletNodeCreateCount"),pcmRingCapacityBytes:i("pcmRingCapacityBytes"),pcmRingBufferedBytes:i("pcmRingBufferedBytes"),pendingWorkletPacketCount:i("pendingWorkletPacketCount"),pendingWorkletPacketBytes:i("pendingWorkletPacketBytes"),pendingWorkletPacketHighWater:i("pendingWorkletPacketHighWater"),pendingWorkletByteHighWater:i("pendingWorkletByteHighWater"),retainedFrameCount:i("retainedFrameCount"),retainedPayloadBytes:i("retainedPayloadBytes"),ownerHighWater:n.ownerCount,socketHighWater:n.socketCount,audioContextHighWater:n.audioContextCount,workletNodeHighWater:n.workletNodeCount,workletPortHighWater:n.workletPortCount,lastTerminalFailure:t,owners:a}}}}const nn=yC();function xC(){let e=Promise.resolve(),t=0,n=0,s=0;return{acquire(a){const i=++s;let c=!1,u=!1,d=!1,p;const h=new Promise(b=>{p=b}),m=Promise.resolve(e).catch(()=>{});e=m.then(()=>h);const g=()=>d?!1:(d=!0,c&&(t=Math.max(0,t-1)),p(),!0),w=m.then(async()=>{if(u||d)return g(),null;c=!0,t+=1,n=Math.max(n,t);try{return await a({ownerId:i,release:g})}catch(b){throw g(),b}});return{ownerId:i,ready:w,release:g,cancel(){u=!0,c||g()}}},snapshot(){return{activeOwnerCount:t,ownerHighWater:n,nextOwnerId:s}}}}const SC=xC(),Qh=1e3;function CC({enabled:e,now:t,lastPublishedAt:n,intervalMs:s=Qh}){if(!e)return!1;const a=Math.max(0,Number(t)||0),i=Math.max(0,Number(n)||0),c=Math.max(1,Number(s)||Qh);return i<=0||a-i>=c}const Qv="livedesk-remote-audio-v1",kC=250,MC=160,lp=4;function AC(e){const t=String(e||"").toLowerCase();return t.includes("audio/pcm")||t.includes("f32le")||t.includes("s16le")}function up(e={},t={}){const n=String(t.deviceId||""),s=String(t.streamId||"");return!!n&&!!s&&String(e.deviceId||"")===n&&String(e.streamId||"")===s}function NC(e={},t={}){if(!up(e,t))return{accepted:!1,reason:"owner-mismatch",nextFrameSeq:Math.max(0,Math.floor(Number(t.lastFrameSeq)||0))};const n=Math.max(0,Math.floor(Number(e.frameSeq)||0)),s=Math.max(0,Math.floor(Number(t.lastFrameSeq)||0));return n>0&&n<=s?{accepted:!1,reason:"sequence-not-newer",nextFrameSeq:s}:{accepted:!0,reason:"",nextFrameSeq:n}}function RC(e={}){const t=String(e.capturePhase||"").toLowerCase(),n=String(e.backendKind||"").toLowerCase(),s=e.captureAlive===!0?!0:e.captureAlive===!1?!1:null,a=e.helperAlive===!0?!0:e.helperAlive===!1?!1:null,i=Math.max(0,Math.floor(Number(e.helperPid)||0)),c=n==="windows-wasapi-in-process",u=n==="macos-screencapturekit-helper"||n==="linux-system-audio-helper",d=c||u,p=e.helperRequired===!0?!0:e.helperRequired===!1?!1:u?!0:c?!1:null,h=p===!1?!0:p===!0?a===!0&&i>0:!1,m=t==="starting"||t==="capture-active-awaiting-current-pcm",g=t==="active"&&s===!0&&d&&h,w=t==="failed"||t==="stopped"||s===!1||t==="active"&&(!d||!h);let b="";return m?b="awaiting-current-pcm":!c&&!u?b="backend-unknown":t!=="active"?b=t?`phase-${t}`:"phase-unknown":s!==!0?b="capture-not-alive":p===!0&&a!==!0?b="external-helper-not-alive":p===!0&&i<=0&&(b="external-helper-pid-missing"),{capturePhase:t,backendKind:n,captureAlive:s,helperAlive:a,helperPid:i,helperRequired:p,inProcessBackend:c,externalHelperBackend:u,backendKnown:d,helperReady:h,awaitingCurrentPcm:m,healthy:g,failed:w,reason:b}}function Js(e,t){const n=Math.floor(Number(e));return Number.isFinite(n)&&n>0?n:t}function Fp(e={}){const t=Math.max(8e3,Math.min(192e3,Js(e.sampleRate,48e3))),n=Math.max(1,Math.min(8,Js(e.channels,2))),s=String(e.mimeType||"").toLowerCase(),i=String(e.sampleFormat||"").toLowerCase()==="s16le"||s.includes("s16le")||s.includes("audio/l16")?"s16le":"f32le";return{sampleRate:t,channels:n,sampleFormat:i}}function Dp(e={}){const t=Fp(e),n=Math.max(1,Math.min(250,Js(e.maxDurationMs,250))),s=Math.max(1,Math.ceil(t.sampleRate*n/1e3));return{...t,maxDurationMs:n,capacityFrames:s,capacityBytes:s*t.channels*Float32Array.BYTES_PER_ELEMENT}}function PC(e={}){const t=Dp(e),n=Math.max(0,Math.min(t.maxDurationMs,Js(e.targetLeadMs,160))),s=Math.min(t.capacityFrames,Math.max(1,Math.ceil(t.sampleRate*n/1e3)));let a=new Float32Array(t.capacityFrames*t.channels),i=0,c=0,u=0,d=0,p=!1,h=!1,m=0,g=0,w=0;const b={acceptedFrames:0,droppedFrames:0},y=()=>(w+=1,{sampleRate:t.sampleRate,channels:t.channels,sampleFormat:t.sampleFormat,maxDurationMs:t.maxDurationMs,targetLeadMs:n,capacityFrames:h?0:t.capacityFrames,capacityBytes:h?0:t.capacityBytes,bufferedFrames:h?0:u,bufferedBytes:h?0:u*t.channels*Float32Array.BYTES_PER_ELEMENT,bufferedMs:h?0:u*1e3/t.sampleRate,droppedFrames:m,underflowCount:g,started:!h&&p,disposed:h}),k=()=>{i=0,c=0,u=0,d=0,p=!1},A=()=>{h||(k(),a=new Float32Array(0),h=!0)},C=(I,F=0,M,$=t.sampleFormat)=>{if(b.acceptedFrames=0,b.droppedFrames=0,h||!(I instanceof ArrayBuffer))return b;const q=Math.max(0,Math.floor(Number(F)||0)),T=Math.max(0,I.byteLength-q),D=Math.min(T,Math.max(0,Math.floor(Number(M??T)||0))),H=$==="s16le",K=H?2:4,z=K*t.channels,W=Math.floor(D/z);if(W<=0)return b;const ce=Math.min(W,t.capacityFrames),j=W-ce,ne=Math.max(0,u+ce-t.capacityFrames);ne>0&&(i=(i+ne)%t.capacityFrames,u-=ne);const ue=j+ne;m+=ue;const U=new DataView(I,q,D);for(let ge=j;ge<W;ge+=1){const re=c*t.channels,we=ge*t.channels;for(let Me=0;Me<t.channels;Me+=1){const Te=(we+Me)*K,Ce=H?U.getInt16(Te,!0)/32768:U.getFloat32(Te,!0);a[re+Me]=Number.isFinite(Ce)?Math.max(-1,Math.min(1,Ce)):0}c=(c+1)%t.capacityFrames}return u+=ce,!p&&u>=s&&(p=!0),b.acceptedFrames=ce,b.droppedFrames=ue,b};return{writePcm:(I={})=>C(I.buffer,I.byteOffset,I.byteLength,I.sampleFormat),writePcmBuffer:C,readToChannels:(I,F=t.sampleRate)=>{if(!Array.isArray(I)||I.length===0)return;let M=Number.POSITIVE_INFINITY;for(let T=0;T<I.length;T+=1){const D=I[T];M=Math.min(M,D?.length||0)}if(h||!Number.isFinite(M)||M<=0||!p){for(let T=0;T<I.length;T+=1)I[T]?.fill?.(0);return}const $=Math.max(8e3,Math.min(192e3,Js(F,t.sampleRate))),q=t.sampleRate/$;for(let T=0;T<M;T+=1){if(u<=0){p=!1,g+=1,d=0;for(let K=0;K<I.length;K+=1)I[K].fill(0,T);break}const D=i*t.channels;for(let K=0;K<I.length;K+=1){const z=Math.min(K,t.channels-1);I[K][T]=a[D+z]}d+=q;const H=Math.min(u,Math.floor(d));H>0&&(i=(i+H)%t.capacityFrames,u-=H,d-=H)}},flush:k,dispose:A,snapshot:y,getSnapshotCount:()=>w}}function TC(e={}){const t=Math.max(1,Math.min(lp,Js(e.maxPendingPackets,lp))),n=Math.max(1,Js(e.maxPendingBytes,1)),s=new Map;let a=0,i=0,c=0,u=0,d=0,p=!1;const h=()=>({terminal:p,maxPendingPackets:t,maxPendingBytes:n,pendingPacketCount:s.size,pendingPacketBytes:a,pendingPacketHighWater:i,pendingByteHighWater:c,acceptedCount:u,droppedCount:d});return{claim(m,g){const w=typeof m=="number"&&Number.isFinite(m)?m:String(m||""),b=Math.max(0,Math.floor(Number(g)||0));return p||!w||b<=0||s.has(w)||s.size>=t||a+b>n?(d+=1,!1):(s.set(w,b),a+=b,i=Math.max(i,s.size),c=Math.max(c,a),u+=1,!0)},acknowledge(m){const g=typeof m=="number"&&Number.isFinite(m)?m:String(m||""),w=s.get(g);return w===void 0?!1:(s.delete(g),a=Math.max(0,a-w),!0)},terminate(){return s.clear(),a=0,p=!0,h()},getPendingPacketCount:()=>s.size,getPendingPacketBytes:()=>a,getPendingPacketHighWater:()=>i,getPendingByteHighWater:()=>c,snapshot:h}}function mu(e,t){const n=String(e?.name||"");if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))throw new Error("Remote Audio worklet function binding name is invalid.");const s=`const ${n} = ${Function.prototype.toString.call(e)};`;return n===t?s:`${s}
4
4
  const ${t} = ${n};`}const IC=mu(Js,"positiveInteger"),jC=mu(Fp,"normalizeRemoteAudioPcmFormat"),EC=mu(Dp,"remoteAudioPcmRingCapacity"),FC=mu(PC,"createRemoteAudioPcmRing"),DC=`